diff --git a/.forgejo/workflows/build.yaml b/.forgejo/workflows/build.yaml index 36c26b6..033ebe2 100644 --- a/.forgejo/workflows/build.yaml +++ b/.forgejo/workflows/build.yaml @@ -54,15 +54,15 @@ jobs: if: steps.get_release.outputs.prerelease == 'true' run: | ./gradlew assembleNightly --stacktrace \ - -PversionName=${{ steps.get_release.outputs.tag_name }} \ -PversionCode=$(date +%s) + # -PversionName=${{ steps.get_release.outputs.tag_name }} - name: Build unsigned release APK - if: steps.get_release.outputs.prerelease == 'false' + if: steps.get_release.outputs.prerelease != 'true' run: | ./gradlew assembleRelease --stacktrace \ -PversionName=${{ steps.get_release.outputs.tag_name }} \ - -PversionCode=${{ gitea.event.release.id }} + -PversionCode=${{ steps.get_release.outputs.release_id }} - name: Sign nightly apk if: steps.get_release.outputs.prerelease == 'true' @@ -76,7 +76,7 @@ jobs: keyPassword: ${{ secrets.KEY_PASSWORD }} - name: Sign release apk - if: steps.get_release.outputs.prerelease == 'false' + if: steps.get_release.outputs.prerelease != 'true' uses: https://github.com/ilharp/sign-android-release@v2 id: sign_app with: @@ -94,7 +94,7 @@ jobs: path: app/build/outputs/apk/nightly/*-signed.apk - name: Upload release apk - if: steps.get_release.outputs.prerelease == 'false' + if: steps.get_release.outputs.prerelease != 'true' && steps.get_release.outputs.release_id != 'null' uses: actions/upload-artifact@v3 with: name: app-release @@ -109,9 +109,9 @@ jobs: "${{ env.GITHUB_API_URL }}/repos/${{ env.GITHUB_REPOSITORY }}/releases/${{ steps.get_release.outputs.release_id }}/assets?name=app-nightly.apk" - name: Upload release Asset - if: steps.get_release.outputs.prerelease == 'false' && steps.get_release.outputs.release_id != 'null' + if: steps.get_release.outputs.prerelease != 'true' && steps.get_release.outputs.release_id != 'null' run: | curl -X POST -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \ -H "Content-Type: multipart/form-data" \ - -F "attachment=@app/build/outputs/apk/release/app-release-signed.apk" \ + -F "attachment=@app/build/outputs/apk/release/app-release-unsigned-signed.apk" \ "${{ env.GITHUB_API_URL }}/repos/${{ env.GITHUB_REPOSITORY }}/releases/${{ steps.get_release.outputs.release_id }}/assets?name=app-release.apk" diff --git a/BUILDING.md b/BUILDING.md new file mode 100644 index 0000000..580046c --- /dev/null +++ b/BUILDING.md @@ -0,0 +1,37 @@ +## Building the app + +### Getting started +Requirements/Dependencies: +- tools: [listed here](https://codeberg.org/mi6e4ka/android-build-ct/src/branch/main/Dockerfile#L9-L26) +- SDK: `OpenJDK 17` +- [Android Studio](https://developer.android.com/studio) for app debugging + +### Building debug release +Open Android Studio, open project and Sync Gradle. After, in toolbar go to Run and run the app. +Alternatively, run in terminal from project directory: +``` +export ANDROID_HOME=/usr/lib/jvm/java-17-openjdk; # here the path to openjdk 17 \ +export ANDROID_SDK_ROOT=$ANDROID_HOME; \ +export JAVA_HOME=$ANDROID_HOME; \ +./gradlew assembleDebug +``` + +### Building signed release +Create file named `keystore.properties` in project directory with next values: +``` +storeFile= +keyAlias= +storePassword= +keyPassword= +``` + +After that, run in terminal from project directory: +``` +export ANDROID_HOME=/usr/lib/jvm/java-17-openjdk; # here the path to openjdk 17 \ +export ANDROID_SDK_ROOT=$ANDROID_HOME; \ +export JAVA_HOME=$ANDROID_HOME; \ +./gradlew assembleRelease +``` + +Release artifacts will be located in `app/build/outputs/apk/release/` directory. +If you have no your keystore.jks, you can create it using `keytool` or just follow [this guide](https://developer.android.com/studio/publish/app-signing#generate-key) from Google for Android Studio. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..496acdb --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,675 @@ +# GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/Maestro/.gitignore b/Maestro/.gitignore new file mode 100644 index 0000000..ca7dc48 --- /dev/null +++ b/Maestro/.gitignore @@ -0,0 +1 @@ +.maestro \ No newline at end of file diff --git a/Maestro/flow.yaml b/Maestro/flow.yaml new file mode 100644 index 0000000..a96d651 --- /dev/null +++ b/Maestro/flow.yaml @@ -0,0 +1,37 @@ +appId: dev.mi6e4ka.openstore +--- +- launchApp: + clearState: true + +- assertVisible: "OpenStore" +- takeScreenshot: "01_main_screen" + +- tapOn: "Search" +- inputText: "Mir Pay" +- pressKey: Enter +- assertVisible: "Mir Pay" +- takeScreenshot: "02_search_screen" + +- tapOn: "Mir Pay" +- assertVisible: "Mir Pay" +- takeScreenshot: "03_details_screen" + +- scrollUntilVisible: + element: "Rating and reviews" + direction: DOWN +- tapOn: "Rating and reviews" +- assertVisible: "Reviews" +- takeScreenshot: "04_review_screen" + +- back +- back +- back +- assertVisible: "OpenStore" +- tapOn: "updates|обновления" +- assertVisible: "Updates" +- takeScreenshot: "05_updates_screen" + +- back +- tapOn: "settings|настройки" +- assertVisible: "Settings|Настройки" +- takeScreenshot: "06_settings_screen" \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..04104d7 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# OpenStore + +[![API](https://img.shields.io/badge/API-21%2B-flat.svg?style=flat)](https://apilevels.com) +[![IzzyOnDroid](https://img.shields.io/endpoint?url=https://apt.izzysoft.de/fdroid/api/v1/shield/dev.mi6e4ka.openstore&label=IzzyOnDroid&cacheSeconds=86400)](https://apt.izzysoft.de/fdroid/index/apk/dev.mi6e4ka.openstore) +![Latest Release](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fcodeberg.org%2Fapi%2Fv1%2Frepos%2Fmi6e4ka%2Fopenstore%2Ftags&query=%24.%5B0%5D.name&label=latest%20release) + +--- + +logo + +Open client for popular russian app store (unofficial) + +## Installation + + + Get it on IzzyOnDroid + + + Get it on Codeberg + + +Verification info: +- Package ID: `dev.mi6e4ka.openstore` +- SHA-256 hash of signing certificate: `57:F7:EA:8B:41:B7:2E:6E:CF:C5:08:46:AF:ED:12:01:47:1A:8D:37:8E:18:D7:6A:AD:AC:BD:9F:B2:19:DF:98` + +## Features +- [x] Search apps +- [x] View apps descriptions, rating and reviews +- [x] Native app installing +- [x] Android 5.0+ support! +- [x] Search and view TV apps +- [x] Check all apps for updates + +## Roadmap +- [ ] Better TV navigation support +- [ ] ...maybe more? + +## Screenshots + + + + + + + +## Building the app +See [here](https://codeberg.org/mi6e4ka/openstore/src/branch/main/BUILDING.md) diff --git a/SAFETY.md b/SAFETY.md new file mode 100644 index 0000000..31c4494 --- /dev/null +++ b/SAFETY.md @@ -0,0 +1,5 @@ +# SAFETY + +> Все приложения опубликованные в RuStore проходят обязательную проверку на вирусы и опасные разрешения, в том числе предоставленные из сторонних источников. Однако, вся ответственность за установленные приложения лежит на конечном пользователе. + +[Как RuStore проверяет приложения](https://www.rustore.ru/help/users/authorization/trust-rustore) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 7d5764f..809481a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,9 +1,31 @@ +import java.io.ByteArrayOutputStream +import java.util.Properties +import java.io.FileInputStream plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) } +val keystoreProperties = Properties() +val keystoreFileExists = rootProject.file("keystore.properties").exists(); +if (keystoreFileExists) { + keystoreProperties.load(rootProject.file("keystore.properties").inputStream()) +} + +val gitCommitShort: String = run { + try { + val process = ProcessBuilder("git", "rev-parse", "--short", "HEAD") + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().use { it.readText() }.trim() + val exitCode = process.waitFor() + if (exitCode == 0 && output.isNotEmpty()) output else "unknown" + } catch (e: Exception) { + "unknown" + } +} + android { namespace = "dev.mi6e4ka.openstore" compileSdk = 36 @@ -17,14 +39,26 @@ android { minSdk = 21 targetSdk = 36 versionCode = (project.findProperty("versionCode") as String?)?.toInt() ?: 1 - versionName = project.findProperty("versionName") as String? ?: "dev" + versionName = project.findProperty("versionName") as String? ?: ("git-" + gitCommitShort) //testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } + signingConfigs { + if (keystoreFileExists) { + create("release") { + storeFile = keystoreProperties["storeFile"]?.let { file(it as String) } + storePassword = keystoreProperties["storePassword"] as String + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + } + } + } + buildTypes { release { isMinifyEnabled = true isShrinkResources = true + signingConfig = signingConfigs.findByName("release")?.takeIf { it.storeFile != null } proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" @@ -46,6 +80,7 @@ android { compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 + isCoreLibraryDesugaringEnabled = true } kotlinOptions { jvmTarget = "11" @@ -57,33 +92,19 @@ android { } dependencies { - implementation(libs.androidx.core.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.activity.compose) implementation(platform(libs.androidx.compose.bom)) - implementation(libs.androidx.ui) - implementation(libs.androidx.ui.graphics) - implementation(libs.androidx.material.icons.extended.android) - implementation(libs.accompanist.pager) - implementation(libs.accompanist.pager.indicators) - implementation(libs.androidx.runtime.livedata) implementation(libs.material3) - implementation(libs.androidx.animation) implementation(libs.androidx.paging.compose) - debugImplementation(libs.androidx.ui.tooling.preview) - debugImplementation(libs.okhttp3.logging.interceptor) - testImplementation(libs.junit) - androidTestImplementation(libs.androidx.junit) - androidTestImplementation(libs.androidx.espresso.core) - androidTestImplementation(platform(libs.androidx.compose.bom)) - androidTestImplementation(libs.androidx.ui.test.junit4) - debugImplementation(libs.androidx.ui.tooling) - debugImplementation(libs.androidx.ui.test.manifest) + implementation(libs.kotlinx.datetime) implementation(libs.navigation.compose) implementation(libs.retrofit) implementation(libs.converter.gson) implementation(libs.kotlinx.coroutines.android) implementation(libs.androidx.lifecycle.viewmodel.ktx) implementation(libs.coil.compose) + implementation(libs.lz4.java) + coreLibraryDesugaring(libs.desugar.jdk.libs) } \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index f1b4245..9568d0d 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -19,3 +19,6 @@ # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile + +# Keep xxhash classes used by LZ4 library +-keep class net.jpountz.xxhash.** { *; } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5dd955c..7deb6c6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,12 +3,13 @@ xmlns:tools="http://schemas.android.com/tools"> - + + tools:ignore="PackageVisibilityPolicy,QueryAllPackagesPermission" /> @@ -20,28 +21,47 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" - android:theme="@style/Theme.OpenStore" + android:theme="@style/AppTheme" android:localeConfig="@xml/locale_config" - tools:targetApi="36"> + tools:targetApi="36" + android:memtagMode="async"> + android:theme="@style/AppTheme"> - - - - - + + + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/app/src/main/java/dev/mi6e4ka/openstore/EditPreferencesActivity.kt b/app/src/main/java/dev/mi6e4ka/openstore/EditPreferencesActivity.kt new file mode 100644 index 0000000..91e06d3 --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/EditPreferencesActivity.kt @@ -0,0 +1,17 @@ +package dev.mi6e4ka.openstore + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.core.net.toUri + +class EditPreferencesActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val intent = Intent(this, MainActivity::class.java).apply { + data = "openstore://settings".toUri() + } + startActivity(intent) + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/MainActivity.kt b/app/src/main/java/dev/mi6e4ka/openstore/MainActivity.kt index 15e7efe..5df0999 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/MainActivity.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/MainActivity.kt @@ -3,16 +3,19 @@ package dev.mi6e4ka.openstore import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut +import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface +import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable @@ -27,21 +30,21 @@ import dev.mi6e4ka.openstore.ui.screen.details.DetailsScreen import dev.mi6e4ka.openstore.ui.screen.results.ResultsScreen import dev.mi6e4ka.openstore.ui.screen.reviews.ReviewsScreen import dev.mi6e4ka.openstore.ui.screen.search.SearchScreen +import dev.mi6e4ka.openstore.ui.screen.settings.SettingsScreen +import dev.mi6e4ka.openstore.ui.screen.updates.UpdatesScreen import dev.mi6e4ka.openstore.ui.theme.AppTheme class MainActivity : ComponentActivity() { - override fun onStart() { - super.onStart() - } override fun onCreate(savedInstanceState: Bundle?) { - val cacheDir = externalCacheDir ?: return + enableEdgeToEdge() + super.onCreate(savedInstanceState) + val cacheDir = externalCacheDir ?: cacheDir cacheDir.listFiles()?.forEach { file -> if (file.isFile && file.name.endsWith(".apk", ignoreCase = true)) { file.delete() println("CacheCleaner" + "Удален: ${file.name}") } } - super.onCreate(savedInstanceState) val imageLoader = ImageLoader.Builder(this) .diskCache { DiskCache.Builder() @@ -59,7 +62,6 @@ class MainActivity : ComponentActivity() { .memoryCachePolicy(CachePolicy.ENABLED) .build() Coil.setImageLoader(imageLoader) - setContent { AppTheme { Surface( @@ -67,20 +69,34 @@ class MainActivity : ComponentActivity() { color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() + val duration = 300 + val easing = FastOutSlowInEasing NavHost( navController = navController, startDestination = "search", enterTransition = { - slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left, animationSpec = tween(300)) + slideInHorizontally( + initialOffsetX = { (it * 0.1f).toInt() }, + animationSpec = tween(duration, easing = easing) + ) + fadeIn(animationSpec = tween(duration)) }, exitTransition = { - slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Left, animationSpec = tween(300)) + slideOutHorizontally( + targetOffsetX = { -(it * 0.1f).toInt() }, + animationSpec = tween(duration, easing = easing) + ) + fadeOut(animationSpec = tween(duration)) }, popEnterTransition = { - slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Right, animationSpec = tween(300)) + slideInHorizontally( + initialOffsetX = { -(it * 0.1f).toInt() }, + animationSpec = tween(duration, easing = easing) + ) + fadeIn(animationSpec = tween(duration)) }, popExitTransition = { - slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right, animationSpec = tween(300)) + slideOutHorizontally( + targetOffsetX = { (it * 0.1f).toInt() }, + animationSpec = tween(duration, easing = easing) + ) + fadeOut(animationSpec = tween(duration)) } ) { composable("search") { @@ -90,24 +106,33 @@ class MainActivity : ComponentActivity() { val query = it.arguments?.getString("query") ?: "" ResultsScreen(query = query, navController = navController) } - composable("app/{appId}", deepLinks = listOf( + composable("app/{appId}?platform={platform}", deepLinks = listOf( navDeepLink { uriPattern = "https://www.rustore.ru/catalog/app/{appId}" }, navDeepLink { uriPattern = "https://apps.rustore.ru/app/{appId}" }, navDeepLink { uriPattern = "https://www.rustore.ru/instruction?appName={appName}&utm_campaign={appId}" } )) { backStackEntry -> val itemId = backStackEntry.arguments?.getString("appId") ?: "" + val platform = backStackEntry.arguments?.getString("platform") ?: "mobile" AnimatedVisibility( visible = true, enter = slideInHorizontally(initialOffsetX = { 1000 }) + fadeIn(), exit = slideOutHorizontally(targetOffsetX = { -1000 }) + fadeOut() ) { - DetailsScreen(itemId = itemId, navController = navController) + DetailsScreen(itemId = itemId, appPlatform=platform, navController = navController) } } composable("app/{packageName}/reviews") { val packageName = it.arguments?.getString("packageName") ?: "" ReviewsScreen(packageName = packageName, navController = navController) } + composable("updates") { + UpdatesScreen(navController = navController) + } + composable("settings", deepLinks = listOf( + navDeepLink { uriPattern = "openstore://settings" } + )) { + SettingsScreen(navController = navController) + } } } } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/api/ApiService.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/api/ApiService.kt index ee99106..e361fef 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/data/api/ApiService.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/api/ApiService.kt @@ -2,25 +2,42 @@ package dev.mi6e4ka.openstore.data.api import dev.mi6e4ka.openstore.data.model.AppCommentsResponse import dev.mi6e4ka.openstore.data.model.AppRatingResponse +import dev.mi6e4ka.openstore.data.model.AppUpdateRequest +import dev.mi6e4ka.openstore.data.model.AppUpdateResponse +import dev.mi6e4ka.openstore.data.model.BatchItemDetailsRequest import dev.mi6e4ka.openstore.data.model.DownloadLinkRequest import dev.mi6e4ka.openstore.data.model.DownloadLinkResponse import dev.mi6e4ka.openstore.data.model.ItemDetailsResponse import dev.mi6e4ka.openstore.data.model.SearchResponse +import dev.mi6e4ka.openstore.data.model.ShortItemDetails import retrofit2.http.Body import retrofit2.http.GET +import retrofit2.http.Header import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query interface ApiService { @GET("applicationData/apps") - suspend fun search(@Query("pageSize") pageSize: Int, @Query("pageNumber") pageNumber: Int, @Query("query") query: String): SearchResponse + suspend fun search( + @Query("pageSize") pageSize: Int, + @Query("pageNumber") pageNumber: Int, + @Query("query") query: String, + @Query("buyeruid") buyeruid : String, + @Header("deviceType") deviceType : String + ): SearchResponse @GET("applicationData/overallInfo/{packageName}") - suspend fun getItemDetails(@Path("packageName") packageName: String): ItemDetailsResponse + suspend fun getItemDetails( + @Header("deviceType") deviceType : String, + @Path("packageName") packageName: String + ): ItemDetailsResponse @POST("applicationData/v2/download-link") - suspend fun getAppDownloadLink(@Body request: DownloadLinkRequest) : DownloadLinkResponse + suspend fun getAppDownloadLink( + @Header("deviceType") deviceType : String, + @Body request: DownloadLinkRequest + ) : DownloadLinkResponse @GET("comment/findRating") suspend fun getAppRating(@Query("packageName") packageName: String) : AppRatingResponse @@ -32,4 +49,14 @@ interface ApiService { @Query("pageSize") pageSize: Int, @Query("sortBy") sortBy: String, ) : AppCommentsResponse + + @POST("applicationData/newApps") + suspend fun getBatchUpdates( + @Body request: AppUpdateRequest + ) : AppUpdateResponse + + @POST("v2/showcase/store-app") + suspend fun getBatchItemDetails( + @Body request: BatchItemDetailsRequest + ) : List } \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/model/AppUpdates.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/model/AppUpdates.kt new file mode 100644 index 0000000..299fc2d --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/model/AppUpdates.kt @@ -0,0 +1,31 @@ +package dev.mi6e4ka.openstore.data.model + +import com.google.gson.annotations.SerializedName + +data class AppUpdateRequestEntry( + @SerializedName("packageName") val packageName: String, + @Transient val appName: String, + @SerializedName("versionCode") val versionCode: Long, + @Transient val versionName: String, + @Transient val installSource: String +) + +data class AppUpdateRequest( + @SerializedName("content") val content: List +) + +data class AppUpdateResponse( + @SerializedName("body") val body: AppUpdateResponseBody +) + +data class AppUpdateResponseBody( + @SerializedName("content") val content: List +) + +data class AppUpdateResponseEntry( + @SerializedName("appId") val appId: Int, + @SerializedName("packageName") val packageName: String, + @SerializedName("appName") val appName: String, + @SerializedName("updatedAt") val updatedAt: String, + @SerializedName("versionCode") val versionCode: Long +) \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/model/DownloadLink.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/model/DownloadLink.kt index c37b2b1..722a81e 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/data/model/DownloadLink.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/model/DownloadLink.kt @@ -8,6 +8,7 @@ data class DownloadLinkRequest( @SerializedName("screenDensity") val screenDensity: Int, @SerializedName("sdkVersion") val sdkVersion: Int, @SerializedName("withoutSplits") val withoutSplits: Boolean, + @SerializedName("supportedAbis") val supportedAbis: List, ) data class DownloadLinkResponse( @@ -20,4 +21,6 @@ data class DownloadLinkResponseBody( data class DownloadLinkResponseItem( @SerializedName("url") val url: String, + @SerializedName("size") val size: Long, + @SerializedName("hash") val hash: String, ) \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/model/ItemDetails.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/model/ItemDetails.kt index 5a73059..9edd7b2 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/data/model/ItemDetails.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/model/ItemDetails.kt @@ -20,6 +20,19 @@ data class ItemDetails( @SerializedName("roundedDownloadsText") val roundedDownloadsText: String, @SerializedName("ageLegal") val ageLegal: String, @SerializedName("whatsNew") val whatsNew: String, + @SerializedName("appVerUpdatedAt") val appVerUpdatedAt: String, +) + +data class ShortItemDetails( + @SerializedName("appId") val appId: Int, + @SerializedName("appName") val appName: String, + @SerializedName("packageName") val packageName: String, + @SerializedName("iconUrl") val iconUrl: String, + @SerializedName("versionCode") val versionCode: Long, +) + +data class BatchItemDetailsRequest( + @SerializedName("packageNames") val packageNames: List, ) data class Files( diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/paging/SearchPagingSource.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/paging/SearchPagingSource.kt index 23bc638..0f74c41 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/data/paging/SearchPagingSource.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/paging/SearchPagingSource.kt @@ -7,7 +7,8 @@ import dev.mi6e4ka.openstore.data.model.SearchResult class SearchPagingSource( private val api: ApiService, - private val query: String + private val query: String, + private val deviceType : String ) : PagingSource() { override suspend fun load(params: LoadParams): LoadResult { @@ -16,7 +17,9 @@ class SearchPagingSource( val response = api.search( pageSize = params.loadSize, query = query, - pageNumber = page + pageNumber = page, + buyeruid = " ", // TODO: empty string for now. It should be zlib compressed string with many info about client. For now required at least the very presence + deviceType = deviceType ) LoadResult.Page( data = response.body.content, diff --git a/app/src/main/java/dev/mi6e4ka/openstore/data/repository/SearchRepository.kt b/app/src/main/java/dev/mi6e4ka/openstore/data/repository/SearchRepository.kt index ada28b3..34a863f 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/data/repository/SearchRepository.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/data/repository/SearchRepository.kt @@ -5,32 +5,46 @@ import androidx.paging.PagingConfig import dev.mi6e4ka.openstore.data.api.ApiClient import dev.mi6e4ka.openstore.data.model.AppCommentsComments import dev.mi6e4ka.openstore.data.model.AppRatingResponseBody +import dev.mi6e4ka.openstore.data.model.AppUpdateRequest +import dev.mi6e4ka.openstore.data.model.AppUpdateRequestEntry +import dev.mi6e4ka.openstore.data.model.AppUpdateResponse +import dev.mi6e4ka.openstore.data.model.AppUpdateResponseEntry +import dev.mi6e4ka.openstore.data.model.BatchItemDetailsRequest import dev.mi6e4ka.openstore.data.model.DownloadLinkRequest +import dev.mi6e4ka.openstore.data.model.DownloadLinkResponseItem import dev.mi6e4ka.openstore.data.model.ItemDetails import dev.mi6e4ka.openstore.data.model.SearchResult +import dev.mi6e4ka.openstore.data.model.ShortItemDetails import dev.mi6e4ka.openstore.data.paging.SearchPagingSource class SearchRepository { private val apiService = ApiClient.service - fun search(query: String): Pager { + fun search(query: String, deviceType : String): Pager { return Pager( config = PagingConfig( pageSize = 20, initialLoadSize = 20, enablePlaceholders = false ), - pagingSourceFactory = { SearchPagingSource(apiService, query) } + pagingSourceFactory = { SearchPagingSource(apiService, query, deviceType) } ) } - suspend fun getItemDetails(id: String): ItemDetails { - return apiService.getItemDetails(id).body + suspend fun getItemDetails(packageName: String, deviceType: String): ItemDetails { + return apiService.getItemDetails(deviceType, packageName).body } - suspend fun getAppDownloadLink(id: Int): String { - val req = DownloadLinkRequest(appId = id, firstInstall = true, screenDensity = 420, sdkVersion = 36, withoutSplits = true) - return apiService.getAppDownloadLink(req).body.downloadUrls[0].url + suspend fun getAppFiles(id: Int, firstInstall: Boolean, supportedAbis: List, withoutSplits: Boolean, deviceType: String): List { + val req = DownloadLinkRequest( + appId = id, + firstInstall = firstInstall, + screenDensity = 420, + sdkVersion = 36, + withoutSplits = withoutSplits, + supportedAbis = supportedAbis + ) + return apiService.getAppDownloadLink(deviceType, req).body.downloadUrls } suspend fun getAppRating(packageName: String): AppRatingResponseBody { @@ -40,4 +54,12 @@ class SearchRepository { suspend fun getAppComments(packageName: String, pageSize: Int, sortBy: String): List { return apiService.getAppComments(packageName, pageSize = pageSize, sortBy = sortBy).body.content } + + suspend fun getBatchUpdates(apps: List): List { + return apiService.getBatchUpdates(AppUpdateRequest(content = apps)).body.content + } + + suspend fun getBatchItemDetails(packageNames: List) : List { + return apiService.getBatchItemDetails(request = BatchItemDetailsRequest(packageNames = packageNames)) + } } \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/ApkInstaller.kt b/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/ApkInstaller.kt index 9160bce..bedb935 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/ApkInstaller.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/ApkInstaller.kt @@ -4,189 +4,378 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageInstaller +import android.net.Uri import android.os.Build import android.os.Handler import android.os.Looper +import android.util.Base64 import android.util.Log -import androidx.annotation.RequiresApi +import android.widget.Toast +import androidx.core.content.FileProvider +import dev.mi6e4ka.openstore.R +import dev.mi6e4ka.openstore.data.model.DownloadLinkResponseItem import kotlinx.coroutines.CoroutineScope import java.io.File +import java.io.FileInputStream import java.io.FileOutputStream import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request -import okhttp3.ResponseBody +import java.io.BufferedOutputStream import java.io.IOException +import net.jpountz.xxhash.XXHashFactory +import java.util.Collections import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.concurrent.atomics.AtomicLong +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.coroutines.cancellation.CancellationException +import kotlin.coroutines.coroutineContext class ApkInstaller(private val context: Context) { companion object { - private val okHttpClient = OkHttpClient() - } - - fun downloadApkWithProgress( - url: String, - onProgress: (percent: Int, downloaded: Long, total: Long) -> Unit, - onSuccess: (File) -> Unit, - onError: (Throwable) -> Unit, - onCancel: () -> Unit, - ): () -> Unit { - - val fileName = url.split("/").last() - val apkFile = getApkFile(fileName) - - // Проверяем, не скачан ли уже файл - if (isApkAlreadyDownloaded(fileName)) { - onSuccess(apkFile) - return {} // Пустая функция отмены - } - - val request = Request.Builder() - .url(url) - .build() - - val okHttpClient = OkHttpClient.Builder() + private val okHttpClient = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .writeTimeout(120, TimeUnit.SECONDS) .build() + } - val call = okHttpClient.newCall(request) + @OptIn(ExperimentalAtomicApi::class) + fun downloadFilesWithProgress( + files: List, + onProgress: (percent: Int, downloaded: Long, total: Long) -> Unit, + onSuccess: (List) -> Unit, + onError: (Throwable) -> Unit, + onCancel: () -> Unit, + onInvalidHash: (List, String?, String?) -> Unit = { _, _, _ -> } + ): () -> Unit { + val downloadRunner = CoroutineScope(Dispatchers.IO).launch { + val totalBytesToDownload = files.sumOf { it.size } + val totalBytesDownloaded = AtomicLong(0) + val downloadedFiles = Collections.synchronizedList(mutableListOf()) + var lastUpdateMillis = 0L - CoroutineScope(Dispatchers.IO).launch { try { - call.execute().use { response -> - if (!response.isSuccessful) { - throw IOException("Ошибка загрузки: ${response.code}") - } + val resultingFiles = coroutineScope { + files.map { file -> + async { + val fileName = file.url.split("/").last() + val apkFile = getApkFile(fileName) + if (!downloadedFiles.contains(apkFile)) { + downloadedFiles.add(apkFile) + } - val responseBody = response.body - if (responseBody == null) { - throw IOException("Пустой ответ от сервера") - } + if (apkFile.exists() && apkFile.length() == file.size) { + if (verifyFileHash(apkFile, file.hash)) { + totalBytesDownloaded.addAndFetch(file.size) + return@async apkFile + } + apkFile.delete() + } - val contentLength = responseBody.contentLength() - val inputStream = responseBody.byteStream() - val outputStream = FileOutputStream(apkFile) + val request = Request.Builder().url(file.url).build() + val call = okHttpClient.newCall(request) + + // Связываем отмену корутины с OkHttp + val job = coroutineContext[Job]!! + val cancelHandler = job.invokeOnCompletion { call.cancel() } - val buffer = ByteArray(8192) - var downloaded: Long = 0 - var bytesRead: Int + try { + call.execute().use { response -> + if (!response.isSuccessful) throw IOException("Ошибка загрузки: ${response.code}") - while (inputStream.read(buffer).also { bytesRead = it } != -1) { - if (call.isCanceled()) { - throw IOException("Canceled") + val responseBody = response.body ?: throw IOException("Пустой ответ") + + responseBody.byteStream().use { inputStream -> + FileOutputStream(apkFile).use { outputStream -> + val buffer = ByteArray(16384) // Увеличил буфер для скорости + var bytesRead: Int + + while (inputStream.read(buffer).also { bytesRead = it } != -1) { + job.ensureActive() + outputStream.write(buffer, 0, bytesRead) + + val currentTotal = totalBytesDownloaded.addAndFetch(bytesRead.toLong()) + + // Троттлинг обновлений UI (не чаще 10 раз в секунду) + val now = System.currentTimeMillis() + if (now - lastUpdateMillis > 100) { + lastUpdateMillis = now + val percent = if (totalBytesToDownload > 0) { + (currentTotal * 100 / totalBytesToDownload).toInt() + } else 0 + + withContext(Dispatchers.Main) { + onProgress(percent, currentTotal, totalBytesToDownload) + } + } + } + outputStream.flush() + } + } + + if (!verifyFileHash(apkFile, file.hash)) { + throw HashMismatchException(apkFile, file.hash) + } + apkFile + } + } finally { + cancelHandler.dispose() + } } - - outputStream.write(buffer, 0, bytesRead) - downloaded += bytesRead.toLong() - - val percent = if (contentLength > 0) { - (downloaded * 100 / contentLength).toInt() - } else { - 0 - } - - withContext(Dispatchers.Main) { - onProgress(percent, downloaded, contentLength) - } - } - - outputStream.flush() - inputStream.close() - outputStream.close() - - withContext(Dispatchers.Main) { - onSuccess(apkFile) - } + }.awaitAll() } - } catch (e: IOException) { - if (apkFile.exists()) { - apkFile.delete() - } - if (e.message == "Canceled") { - onCancel() - } else { - withContext(Dispatchers.Main) { - onError(e) - } + + withContext(Dispatchers.Main) { + onSuccess(resultingFiles) } } catch (e: Exception) { - if (apkFile.exists()) { - apkFile.delete() - } - withContext(Dispatchers.Main) { - onError(e) + withContext(NonCancellable) { + if (e is HashMismatchException) { + val expectedHash = formatHashForDisplay(e.expectedHash) + val actualHash = computeExistingHash(e.file) + val filesCopy = downloadedFiles.toList() + withContext(Dispatchers.Main) { + onInvalidHash(filesCopy, expectedHash, actualHash) + } + } else { + // Удаляем недокачанные файлы при любой другой ошибке или отмене + downloadedFiles.forEach { if (it.exists()) it.delete() } + + withContext(Dispatchers.Main) { + if (e is CancellationException || (e is IOException && callIsCanceled(e))) { + onCancel() + } else { + onError(e) + } + } + } } } } - return { - call.cancel() - } + return { downloadRunner.cancel() } } - fun isApkAlreadyDownloaded(fileName: String): Boolean { - val apkFile = getApkFile(fileName) - return apkFile.exists() && apkFile.length() > 0 + private fun callIsCanceled(e: IOException): Boolean { + return e.message?.contains("Canceled", ignoreCase = true) == true || + e.message?.contains("Socket closed", ignoreCase = true) == true } + private class HashMismatchException(val file: File, val expectedHash: String) : IOException("Hash mismatch") + fun getApkFile(fileName: String): File { - return File(context.externalCacheDir, fileName) + return File(context.externalCacheDir ?: context.cacheDir, fileName) } - fun deleteApkFile(fileName: String) { - val apkFile = getApkFile(fileName) - if (apkFile.exists()) { - apkFile.delete() + fun cleanApkFiles(files: List) { + files.forEach { + val apkFile = getApkFile(it) + if (apkFile.exists()) { + apkFile.delete() + } } } - - fun getApkFileSize(fileName: String): Long { - return getApkFile(fileName).length() - } - private val installer = context.packageManager.packageInstaller private val flags = PendingIntent.FLAG_MUTABLE private val intent = Intent(context, PackageInstallerStatusReceiver::class.java) - private val sessionParams = - PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + + private fun verifyFileHash(file: File, expectedHash: String): Boolean { + val normalizedHash = expectedHash.trim().ifEmpty { return true } + val expectedBytes = decodeHashValue(normalizedHash) ?: return true + if (expectedBytes.size != 8) return true + + val actualBytes = digestFileXXH64(file) ?: return false + return actualBytes.contentEquals(expectedBytes) + } + + private fun decodeHashValue(hash: String): ByteArray? { + return try { + if (hash.matches(Regex("^[0-9A-Fa-f]+$"))) { + hash.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + } else { + Base64.decode(hash, Base64.DEFAULT) } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - setRequestUpdateOwnership(true) + } catch (e: Exception) { + null + } + } + + private fun formatHashForDisplay(hash: String): String { + return if (hash.matches(Regex("^[0-9A-Fa-f]+$"))) { + hash.lowercase() + } else { + hash + } + } + + private fun computeExistingHash(file: File): String { + val actualBytes = digestFileXXH64(file) ?: return "" + return actualBytes.toHexString() + } + + private fun digestFileXXH64(file: File): ByteArray? { + return try { + val factory = XXHashFactory.fastestInstance() + val hash64 = factory.newStreamingHash64(0L) + FileInputStream(file).use { fis -> + val buffer = ByteArray(8192) + var bytesRead: Int + while (fis.read(buffer).also { bytesRead = it } != -1) { + hash64.update(buffer, 0, bytesRead) + } + } + val hashValue = hash64.getValue() + byteArrayOf( + (hashValue shr 56).toByte(), + (hashValue shr 48).toByte(), + (hashValue shr 40).toByte(), + (hashValue shr 32).toByte(), + (hashValue shr 24).toByte(), + (hashValue shr 16).toByte(), + (hashValue shr 8).toByte(), + hashValue.toByte() + ) + } catch (e: Exception) { + null + } + } + + private fun ByteArray.toHexString(): String { + val sb = StringBuilder(size * 2) + for (b in this) { + sb.append(String.format("%02x", b)) + } + return sb.toString() + } + + fun installApp( + packageName: String, + apkFiles: List, + onSessionFinished: (Boolean) -> Unit = {}, + onError: (Exception) -> Unit = {} + ) { + val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE) + val installerType = prefs.getString("installer_type", "session") + + when (installerType) { + "session" -> { + installViaSession(apkFiles, onSessionFinished, onError) + } + "intent" -> { + installViaIntent(packageName, apkFiles, onError) } } + } - fun installApk(context: Context, apkFile: File, installerCallback: PackageInstaller.SessionCallback, onError: (e: Exception) -> Unit) { + private fun installViaSession( + apkFiles: List, + onSessionFinished: (Boolean) -> Unit, + onError: (Exception) -> Unit + ) { try { - val id = installer.createSession(sessionParams) - installer.registerSessionCallback( - installerCallback, - Handler(Looper.getMainLooper()) - ) - - val session = installer.openSession(id) - - session.use { activeSession -> - val sizeBytes = apkFile.length() - apkFile.inputStream().use { fileStream -> - activeSession.openWrite(apkFile.name, 0, sizeBytes).use { outputStream -> - fileStream.copyTo(outputStream) - activeSession.fsync(outputStream) + val sessionParams = + PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + setRequestUpdateOwnership(true) } } - val pendingIntent = PendingIntent.getBroadcast(context, id, intent, flags) + val sessionId = installer.createSession(sessionParams) + installer.registerSessionCallback(object : PackageInstaller.SessionCallback() { + override fun onCreated(sessionId: Int) {} + override fun onBadgingChanged(sessionId: Int) {} + override fun onActiveChanged(sessionId: Int, active: Boolean) {} + override fun onProgressChanged(sessionId: Int, progress: Float) {} + override fun onFinished(id: Int, success: Boolean) { + if (id == sessionId) { + onSessionFinished(success) + installer.unregisterSessionCallback(this) + } + } + }, Handler(Looper.getMainLooper())) + + val session = installer.openSession(sessionId) + session.use { activeSession -> + apkFiles.forEach { file -> + val sizeBytes = file.length() + file.inputStream().use { fileStream -> + activeSession.openWrite(file.name, 0, sizeBytes).use { outputStream -> + fileStream.copyTo(outputStream) + activeSession.fsync(outputStream) + } + } + } + val pendingIntent = PendingIntent.getBroadcast(context, sessionId, intent, flags) activeSession.commit(pendingIntent.intentSender) } } catch (e: Exception) { + Log.e("ApkInstaller", "Error during session install", e) onError(e) } - } -} \ No newline at end of file + private fun installViaIntent( + packageName: String, + apkFiles: List, + onError: (Exception) -> Unit + ) { + try { + val apkUri: Uri + if (apkFiles.size == 1) { + apkUri = FileProvider.getUriForFile( + context, + "${context.packageName}.provider", + apkFiles[0] + ) + } else { + Toast.makeText(context, R.string.intent_installer_split_apk_build, Toast.LENGTH_SHORT) + .show() + val apksFile = File(context.externalCacheDir ?: context.cacheDir, "$packageName.apks") + buildSplitApk(apkFiles, apksFile) + apkUri = FileProvider.getUriForFile( + context, + "${context.packageName}.provider", + apksFile + ) + } + Toast.makeText(context, R.string.intent_installer_warning, Toast.LENGTH_SHORT) + .show() + + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(apkUri, "application/vnd.android.package-archive") + flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK + } + context.startActivity(intent) + } catch (e: Exception) { + Log.e("ApkInstaller", "Error during intent install", e) + onError(e) + } + } + + private fun buildSplitApk(apkFiles: List, outputZip: File) { + ZipOutputStream(BufferedOutputStream(FileOutputStream(outputZip))).use { zos -> + apkFiles.forEach { file -> + FileInputStream(file).use { fis -> + val entry = ZipEntry(file.name) + zos.putNextEntry(entry) + fis.copyTo(zos) + zos.closeEntry() + } + } + } + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/InstallResultReceiver.kt b/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/InstallResultReceiver.kt index e7c74e3..8be4958 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/InstallResultReceiver.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/internal/installer/InstallResultReceiver.kt @@ -4,6 +4,7 @@ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageInstaller +import android.util.Log import android.widget.Toast import androidx.core.os.BundleCompat import dev.mi6e4ka.openstore.R @@ -33,7 +34,15 @@ class PackageInstallerStatusReceiver : BroadcastReceiver() { } } else -> { - Toast.makeText(context, if (isUninstall) R.string.failed_uninstall else R.string.failed_install, Toast.LENGTH_SHORT).show() + val errorMessage = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + + if (errorMessage?.contains("INSUFFICIENT_STORAGE", ignoreCase = true) == true) { + Toast.makeText(context, R.string.insufficient_memory, Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(context, if (isUninstall) R.string.failed_uninstall else R.string.failed_install, Toast.LENGTH_SHORT).show() + } + + Log.e("app manager", errorMessage ?: "no error message") } } } @@ -41,4 +50,4 @@ class PackageInstallerStatusReceiver : BroadcastReceiver() { companion object { const val ACTION_UNINSTALL = "action_uninstall" } -} \ No newline at end of file +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/components/AppIcon.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/components/AppIcon.kt index 10b599e..3144c68 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/components/AppIcon.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/components/AppIcon.kt @@ -1,14 +1,14 @@ package dev.mi6e4ka.openstore.ui.components import androidx.compose.foundation.layout.size -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Error import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import coil.compose.SubcomposeAsyncImage +import dev.mi6e4ka.openstore.R @Composable fun AppIcon( @@ -27,7 +27,7 @@ fun AppIcon( error = { Icon( modifier = Modifier.size(24.dp), - imageVector = Icons.Filled.Error, + painter = painterResource(R.drawable.ic_broken_image_24px), contentDescription = "Error" ) } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/components/Gallery.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/components/Gallery.kt index 0865a21..4fc242d 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/components/Gallery.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/components/Gallery.kt @@ -33,6 +33,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.hideFromAccessibility +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties @@ -62,7 +65,8 @@ fun GalleryWithPager(images: List) { modifier = Modifier.height(250.dp) ) { LazyRow( - horizontalArrangement = Arrangement.spacedBy(8.dp) + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.clearAndSetSemantics{} ) { itemsIndexed(images) { i, file -> var isLoading by remember { mutableStateOf(true) } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsScreen.kt index 8e3cb7a..1601359 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsScreen.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsScreen.kt @@ -1,12 +1,8 @@ package dev.mi6e4ka.openstore.ui.screen.details -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.os.Build -import android.util.Log -import android.widget.Toast import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.LinearOutSlowInEasing @@ -14,12 +10,14 @@ import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding @@ -28,18 +26,6 @@ import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material.ExperimentalMaterialApi -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.automirrored.rounded.ArrowForward -import androidx.compose.material.icons.filled.ArrowCircleUp -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.OpenInBrowser -import androidx.compose.material.icons.filled.SupervisedUserCircle -import androidx.compose.material.icons.rounded.Android -import androidx.compose.material.icons.rounded.Download -import androidx.compose.material.icons.rounded.Security -import androidx.compose.material.icons.rounded.Warning import androidx.compose.material3.AssistChip import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -52,10 +38,13 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.AlertDialog import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Scaffold import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar +import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState @@ -64,6 +53,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha @@ -76,6 +66,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController @@ -86,11 +77,28 @@ import dev.mi6e4ka.openstore.internal.installer.ApkInstaller import dev.mi6e4ka.openstore.ui.components.AppIcon import dev.mi6e4ka.openstore.ui.components.GalleryWithPager import kotlinx.coroutines.launch +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.TimeZone +import kotlinx.datetime.format +import kotlinx.datetime.format.FormatStringsInDatetimeFormats +import kotlinx.datetime.format.byUnicodePattern +import kotlinx.datetime.toLocalDateTime +import android.Manifest +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import kotlin.time.ExperimentalTime +import kotlin.time.Instant -@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class) +@OptIn(ExperimentalMaterial3Api::class, + FormatStringsInDatetimeFormats::class, ExperimentalTime::class +) @Composable fun DetailsScreen( itemId: String, + appPlatform: String, navController: NavController = rememberNavController() ) { val context = LocalContext.current @@ -98,17 +106,27 @@ fun DetailsScreen( //val viewModel = remember (itemId) { DetailsViewModel(itemId, apkInstaller) } val viewModel : DetailsViewModel = viewModel( - factory = DetailsViewModelFactory(itemId, apkInstaller) + factory = DetailsViewModelFactory(appPlatform, apkInstaller) ) val state by viewModel.state.collectAsState() val scope = rememberCoroutineScope() var showAppDescriptionSheet by remember { mutableStateOf(false) } + var showHashDetails by remember { mutableStateOf(false) } // val appDescriptionSheetState = rememberModalBottomSheetState( // skipPartiallyExpanded = true // ) + val permissionLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission(), + onResult = { isGranted -> + if (isGranted) { + viewModel.downloadFileToFolder(context) + } + } + ) + LaunchedEffect(itemId) { viewModel.loadDetails(context, itemId) } @@ -125,23 +143,48 @@ fun DetailsScreen( navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = "Back" + painter = painterResource(R.drawable.ic_arrow_back_24px), + contentDescription = stringResource(R.string.back_button_desc) ) } }, actions = { - IconButton(onClick = { - scope.launch { - val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - val clip = ClipData.newPlainText("", state.downloadLink) - clipboard.setPrimaryClip(clip) - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { - Toast.makeText(context, R.string.copied_to_buffer, Toast.LENGTH_SHORT).show() + IconButton( + { + scope.launch { + viewModel.copyTextToCB(context, state.plainApkUrl ?: "") } } - }, enabled = state.downloadLink != null) { - Icon(painterResource(R.drawable.apk_install_24px), null) + ){ + Icon( + painterResource(R.drawable.ic_link_24px), + stringResource(R.string.copy_link_desc) + ) + } + IconButton( + { + scope.launch { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + viewModel.downloadFileToFolder(context) + } else { + val permissionStatus = ContextCompat.checkSelfPermission( + context, + Manifest.permission.WRITE_EXTERNAL_STORAGE + ) + + if (permissionStatus == PackageManager.PERMISSION_GRANTED) { + viewModel.downloadFileToFolder(context) + } else { + permissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) + } + } + } + } + ){ + Icon( + painterResource(R.drawable.apk_install_24px), + stringResource(R.string.download_apk_desc) + ) } IconButton(onClick = { val intent = Intent(Intent.ACTION_VIEW, "https://www.rustore.ru/catalog/app/${state.item?.packageName ?: ""}".toUri()).apply { @@ -149,8 +192,11 @@ fun DetailsScreen( setSelector(Intent(Intent.ACTION_VIEW, "http://".toUri())) } context.startActivity(intent) - }) { - Icon(Icons.Default.OpenInBrowser, null) + }, enabled = state.item != null) { + Icon( + painterResource(R.drawable.ic_captive_portal_24px), + stringResource(R.string.open_in_browser_desc) + ) } } ) } @@ -175,6 +221,36 @@ fun DetailsScreen( } } } + if (state.invalidDownloadedApkFiles != null) { + AlertDialog( + onDismissRequest = { viewModel.clearInvalidDownloadState() }, + title = { Text(stringResource(R.string.invalid_download_hash_title)) }, + text = { + Column { + Text(stringResource(R.string.invalid_download_hash_message)) + Spacer(modifier = Modifier.size(12.dp)) + TextButton(onClick = { showHashDetails = !showHashDetails }) { + Text(stringResource(R.string.show_hashes)) + } + if (showHashDetails) { + Spacer(modifier = Modifier.size(8.dp)) + Text(stringResource(R.string.expected_hash, state.invalidExpectedHash ?: "")) + Text(stringResource(R.string.actual_hash, state.invalidActualHash ?: "")) + } + } + }, + confirmButton = { + TextButton(onClick = { viewModel.retryDownloadAfterInvalid(context) }) { + Text(stringResource(R.string.download_again)) + } + }, + dismissButton = { + TextButton(onClick = { viewModel.installAsIsAfterInvalid(context) }) { + Text(stringResource(R.string.install_as_is)) + } + } + ) + } if (state.isLoading) { LinearProgressIndicator(modifier = Modifier .padding(horizontal = 4.dp) @@ -213,14 +289,14 @@ fun DetailsScreen( verticalAlignment = Alignment.CenterVertically ) { Icon( - imageVector = Icons.Rounded.Security, + painter = painterResource(R.drawable.ic_security_24px), contentDescription = null, modifier = Modifier.size(28.dp) ) if (item.aggregatorInfo != null) { - Text(stringResource(R.string.provided_by, item.aggregatorInfo.source)) + Text(stringResource(R.string.provided_by_third_party, item.aggregatorInfo.source)) } else { - Text(stringResource(R.string.provided_by, "RuStore")) + Text(stringResource(R.string.provided_by_developer)) } } } @@ -268,7 +344,7 @@ fun DetailsScreen( verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text(item.appName, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis) - Text(item.aggregatorInfo?.companyName ?: item.companyName, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(item.aggregatorInfo?.companyName ?: item.companyName, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.clearAndSetSemantics(){contentDescription = "Разработчик: ${item.aggregatorInfo?.companyName ?: item.companyName}"}) } } if (!state.isSupported) { @@ -276,18 +352,40 @@ fun DetailsScreen( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { - Icon(Icons.Rounded.Warning, null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(22.dp)) + Icon(painterResource(R.drawable.ic_warning_24px), null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(22.dp)) Text(stringResource(R.string.device_unsupported), color = MaterialTheme.colorScheme.error) } } + if (state.isInstalled && state.isNeedUpgrade && + state.installerPackageName != context.packageName && + state.installerPackageName != "ru.vk.store") { + Card( + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer), + modifier = Modifier.fillMaxWidth() + ) { + Row( + Modifier.padding(12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(painterResource(R.drawable.ic_warning_24px), null, tint = MaterialTheme.colorScheme.onPrimaryContainer) + Text( + stringResource(R.string.signature_mismatch_warning), + fontSize = 16.sp + //color = MaterialTheme.colorScheme.onPrimaryContainer + ) + } + } + } Column { Row( - horizontalArrangement = Arrangement.spacedBy(8.dp) + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically ) { if (!state.isInstalled || state.isDownloading) { - //FilledTonalButton(onClick = {}, modifier = Modifier.weight(1f)) { Text("Copy apk link") } Button(onClick = { - viewModel.downloadAndInstallApk(context) + viewModel.downloadAndInstallApp(context) }, modifier = Modifier.weight(1f), enabled = !state.isDownloading && state.isSupported) { if (state.installStatus is InstallStatus.Pending) { Text(stringResource(R.string.installing)) @@ -305,10 +403,19 @@ fun DetailsScreen( FilledTonalButton(onClick = { viewModel.deleteApplication(context, itemId) }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.uninstall)) } + if (state.isNeedUpgrade) { Button(onClick = { - viewModel.downloadAndInstallApk(context) + viewModel.downloadAndInstallApp(context) }, modifier = Modifier.weight(1f), enabled = state.isSupported) { Text(stringResource(R.string.update)) } + + CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) { + FilledTonalIconButton(onClick = { + viewModel.runApplication(context, itemId) + }, modifier = Modifier.size(40.dp)) { + Icon(painterResource(R.drawable.ic_open_in_browser_24px), contentDescription = stringResource(R.string.open)) + } + } } else { Button(onClick = { viewModel.runApplication(context, itemId) @@ -316,10 +423,12 @@ fun DetailsScreen( } } if (state.isDownloading) { - FilledTonalIconButton(onClick = { - viewModel.cancelDownload() - }, enabled = state.installStatus != InstallStatus.Pending) { - Icon(imageVector = Icons.Default.Close, null) + CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) { + FilledTonalIconButton(onClick = { + viewModel.cancelDownload() + }, enabled = state.installStatus != InstallStatus.Pending, modifier = Modifier.size(40.dp)) { + Icon(painterResource(R.drawable.ic_close_24px), null) + } } } } @@ -330,20 +439,40 @@ fun DetailsScreen( .padding(bottom = 4.dp, top = 2.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - //InfoBadge("%.1f MB".format(item.fileSize/1024/1024), "Вес") -// InfoBadge(, "загрузок") -// InfoBadge("${getAndroidVersion(item.minSdkVersion)}+", "Android", -// Modifier -// .clip(RoundedCornerShape(12.dp)) -// .clickable(onClick = { -// -// })) -// InfoBadge(item.ageLegal, "возраст") -// InfoBadge(item.versionName, "версия") + AssistChip( + label = { + Text("%.1f MB".format( + (state.appFiles?.sumOf { it.size } ?: 0L) / 1024.0 / 1024.0) + ) + }, + leadingIcon = { + Icon( + painterResource(R.drawable.ic_upload_file_24px), + stringResource(R.string.app_size_desc) + )}, + onClick = {}, + ) + AssistChip( + onClick = {}, + label = {Text(item.versionName)}, + leadingIcon = { + Icon( + painterResource(R.drawable.ic_arrow_circle_up_24px), + stringResource(R.string.latest_version_desc) + )} + ) + AssistChip( + onClick = {}, + label = {FormattedDateText(item.appVerUpdatedAt)}, + leadingIcon = { + Icon( + painterResource(R.drawable.ic_update_24px), + stringResource(R.string.last_update_desc) + )} + ) var detailedApiVersion by remember { mutableStateOf(false) } AssistChip( onClick = { - //Toast.makeText(context, "MinSdkVersion ${item.minSdkVersion}\nTargetSdkVersion ${item.targetSdkVersion}", Toast.LENGTH_SHORT).show() detailedApiVersion = !detailedApiVersion }, label = { @@ -353,30 +482,53 @@ fun DetailsScreen( Text("API ${item.minSdkVersion} +") } }, - leadingIcon = {Icon(imageVector = Icons.Rounded.Android, contentDescription = null)} + leadingIcon = { + Icon( + painterResource(R.drawable.ic_android_24px), + stringResource(R.string.min_api_desc) + )} + ) + AssistChip( + onClick = {}, + label = {Text(if ((state.appFiles?.size ?: 1) > 1) "${state.appFiles?.size} Split APKs" else "APK")}, + leadingIcon = { + Icon( + painterResource(R.drawable.ic_adb_24px), + stringResource(R.string.installer_type_desc) + )} ) AssistChip( onClick = {}, label = {Text(item.roundedDownloadsText)}, - leadingIcon = {Icon(imageVector = Icons.Rounded.Download, contentDescription = null)} - ) - AssistChip( - onClick = {}, - label = {Text(item.versionName)}, - leadingIcon = {Icon(imageVector = Icons.Default.ArrowCircleUp, contentDescription = null)} + leadingIcon = { + Icon( + painterResource(R.drawable.ic_download_24px), + stringResource(R.string.downloads_desc) + )} ) AssistChip( onClick = {}, label = {Text(item.ageLegal)}, - leadingIcon = {Icon(imageVector = Icons.Default.SupervisedUserCircle, contentDescription = null)} + leadingIcon = { + Icon( + painterResource(R.drawable.ic_supervised_user_circle_24px), + stringResource(R.string.age_legal_desc) + )} ) } GalleryWithPager(item.fileUrls) } var isWhatsNewExpanded by remember { mutableStateOf(false) } Card( - modifier = Modifier.fillMaxWidth(), - onClick = {isWhatsNewExpanded = !isWhatsNewExpanded} + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .combinedClickable( + onClick = {isWhatsNewExpanded = !isWhatsNewExpanded}, + onLongClick = { + viewModel.copyTextToCB(context, item.whatsNew) + } + ), ) { Column( Modifier @@ -413,7 +565,7 @@ fun DetailsScreen( ) { Text(stringResource(R.string.about_app), fontWeight = FontWeight.Bold, fontSize = 18.sp) IconButton(onClick = {showAppDescriptionSheet = true}) { - Icon(imageVector = Icons.AutoMirrored.Rounded.ArrowForward, contentDescription = null) + Icon(painterResource(R.drawable.ic_arrow_forward_24px), contentDescription = null) } } Text(text = item.shortDescription) @@ -427,6 +579,13 @@ fun DetailsScreen( restoreState = true } }) + .clearAndSetSemantics { + contentDescription = context.getString( + R.string.reviews_desc, + state.rating?.averageUserRating ?: 0, + state.rating?.totalRatings ?: 0 + ) + } ) { Row( Modifier @@ -498,6 +657,22 @@ fun DetailsScreen( } } +@OptIn(ExperimentalTime::class, FormatStringsInDatetimeFormats::class) +@Composable +fun FormattedDateText(dateString: String) { + val formattedDate = remember(dateString) { + try { + Instant.parse(dateString) + .toLocalDateTime(TimeZone.currentSystemDefault()) + .format(LocalDateTime.Format { byUnicodePattern("dd.MM.yyyy") }) + } catch (e: Exception) { + "..." + } + } + + Text(text = formattedDate) +} + fun getAndroidVersion(apiLevel: Int): String { val versions = mapOf( 1 to "1.0", diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsViewModel.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsViewModel.kt index f4750a5..3c9f24e 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsViewModel.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/details/DetailsViewModel.kt @@ -1,20 +1,23 @@ package dev.mi6e4ka.openstore.ui.screen.details +import android.app.DownloadManager import android.app.PendingIntent +import android.content.ClipData +import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build +import android.os.Environment import android.util.Log import android.widget.Toast -import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import dev.mi6e4ka.openstore.R -import dev.mi6e4ka.openstore.data.model.AppCommentsResponseBody import dev.mi6e4ka.openstore.data.model.AppRatingResponseBody +import dev.mi6e4ka.openstore.data.model.DownloadLinkResponseItem import dev.mi6e4ka.openstore.data.model.ItemDetails import dev.mi6e4ka.openstore.di.AppModule import dev.mi6e4ka.openstore.internal.installer.ApkInstaller @@ -25,13 +28,16 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.io.File +import androidx.core.net.toUri data class DetailsState( val isLoading: Boolean = true, val item: ItemDetails? = null, val rating: AppRatingResponseBody? = null, val error: String? = null, - val downloadLink: String? = null, + val appFiles: List? = null, + val plainApkUrl: String? = null, + val splitOnly: Boolean? = null, val installStatus: InstallStatus = InstallStatus.Idle, val isDownloading: Boolean = false, val downloadProgress: Int = 0, @@ -40,6 +46,11 @@ data class DetailsState( val isInstalled: Boolean = false, val isNeedUpgrade: Boolean = false, val isSupported: Boolean = true, + val installerPackageName: String? = null, + val invalidDownloadedApkFiles: List? = null, + val invalidDownloadMessage: String? = null, + val invalidExpectedHash: String? = null, + val invalidActualHash: String? = null ) sealed class InstallStatus { @@ -48,7 +59,7 @@ sealed class InstallStatus { object Success : InstallStatus() } -class DetailsViewModel(private val itemId: String, private val apkInstaller: ApkInstaller) : ViewModel() { +class DetailsViewModel(private val appPlatform: String, private val apkInstaller: ApkInstaller) : ViewModel() { private val _state = MutableStateFlow(DetailsState()) val state: StateFlow = _state.asStateFlow() private var cancelDownload: (() -> Unit)? = null @@ -59,74 +70,109 @@ class DetailsViewModel(private val itemId: String, private val apkInstaller: Apk } Log.d(null, "Initial loading") viewModelScope.launch { + var item: ItemDetails? = null + // основная информация о приложении try { - val item = AppModule.searchRepository.getItemDetails(itemId) + item = AppModule.searchRepository.getItemDetails(itemId, appPlatform) // val packageInfo = getPackageInfo(context, itemId) - _state.value = DetailsState(isLoading = true, isInstalled = packageInfo != null) + val installer = if (packageInfo != null) getInstallSource(context.packageManager, itemId) else null + + _state.value = DetailsState( + isLoading = true, + isInstalled = packageInfo != null, + installerPackageName = installer + ) + if (packageInfo != null) { val installedVersionCode = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { packageInfo.longVersionCode } else { - packageInfo.versionCode - }) as Long + @Suppress("DEPRECATION") + packageInfo.versionCode.toLong() + }) if (installedVersionCode < item.versionCode) { _state.update { it.copy(isNeedUpgrade = true) } } } // _state.update { it.copy(isSupported = Build.VERSION.SDK_INT >= item.minSdkVersion) } - - val downloadLink = AppModule.searchRepository.getAppDownloadLink(item.appId) - val rating = AppModule.searchRepository.getAppRating(itemId) - _state.update{ it.copy(item = item, rating = rating, downloadLink = downloadLink, isLoading = false) } + _state.update{ it.copy(item = item) } } catch (e: Exception) { _state.update { it.copy(error = e.message, isLoading = false) } } + // пробуем получить все файлы приложения (включая split) + try { + if (item == null) return@launch + val appFiles = AppModule.searchRepository.getAppFiles(item.appId, firstInstall = true, supportedAbis = Build.SUPPORTED_ABIS.toList(), withoutSplits = false, deviceType = appPlatform) + _state.update{ it.copy(appFiles = appFiles) } + } catch (e: Exception) {} + // пробуем получить файлы приложения указав что нам не нужны split apk + try { + if (item == null) return@launch + val singleApkUrl = AppModule.searchRepository.getAppFiles(item.appId, firstInstall = true, supportedAbis = Build.SUPPORTED_ABIS.toList(), withoutSplits = true, deviceType = appPlatform).firstOrNull()?.url + _state.update{ it.copy(plainApkUrl = singleApkUrl, splitOnly = singleApkUrl == null) } + } catch (e: Exception) {} + // рейтинг + try { + val rating = AppModule.searchRepository.getAppRating(itemId) + _state.update{ it.copy(rating = rating) } + } catch (e: Exception) {} + + _state.update { it.copy(isLoading = false) } } } - fun downloadAndInstallApk(context: Context) { + private fun getInstallSource(pm: PackageManager, packageName: String): String? { + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + pm.getInstallSourceInfo(packageName).installingPackageName + } else { + @Suppress("DEPRECATION") + pm.getInstallerPackageName(packageName) + } + } catch (e: Exception) { + null + } + } + + fun downloadAndInstallApp(context: Context) { viewModelScope.launch { _state.update { it.copy(isDownloading = true, downloadProgress = 0, downloadTotalBytes = 0, downloadCurrentBytes = 0) } - Log.d(null, "download apk " + state.value.downloadLink) - cancelDownload = apkInstaller.downloadApkWithProgress( - state.value.downloadLink ?: "", + Log.d(null, "download apk " + state.value.appFiles) + cancelDownload = apkInstaller.downloadFilesWithProgress( + state.value.appFiles!!, onProgress = { percent, downloaded, total -> _state.update { it.copy(downloadProgress = percent, downloadCurrentBytes = downloaded, downloadTotalBytes = total) } }, - onSuccess = { apkFile -> - installApk(context, apkFile) + onSuccess = { apkFiles -> + installApp(context, apkFiles) }, onError = { error -> - if (error.message?.contains("Canceled") == true || error.message?.contains("Socket is closed") == true || error.message?.contains("CANCEL") == true) { - return@downloadApkWithProgress - } else if (error.message?.contains("timeout") == true) { + if (error.message?.contains("timeout") == true) { Toast.makeText(context, R.string.timeout, Toast.LENGTH_SHORT).show() } else if (error.message?.contains("Failed to allocate") == true) { Toast.makeText(context, R.string.insufficient_memory, Toast.LENGTH_SHORT).show() } else { - println("ERROR: ${error.message}") Toast.makeText(context, R.string.loading_error, Toast.LENGTH_SHORT).show() } _state.update { it.copy(isDownloading = false) } }, onCancel = { _state.update { it.copy(isDownloading = false) } + }, + onInvalidHash = { apkFiles, expectedHash, actualHash -> + _state.update { + it.copy( + isDownloading = false, + invalidDownloadedApkFiles = apkFiles, + invalidDownloadMessage = "Файл скачан некорректно.", + invalidExpectedHash = expectedHash, + invalidActualHash = actualHash + ) + } } ) -// val uri = FileProvider.getUriForFile( -// context, -// "${context.packageName}.provider", -// apkFile -// ) -// -// val intent = Intent(Intent.ACTION_VIEW).apply { -// setDataAndType(uri, "application/vnd.android.package-archive") -// addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) -// addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) -// } -// launcher.launch(intent) } } @@ -135,30 +181,75 @@ class DetailsViewModel(private val itemId: String, private val apkInstaller: Apk cancelDownload = null } - private fun installApk(context: Context, apkFile: File) { - viewModelScope.launch { - _state.update { it.copy(installStatus = InstallStatus.Pending) } - val installerCallback = object : android.content.pm.PackageInstaller.SessionCallback() { - override fun onCreated(sessionId: Int) {} - override fun onBadgingChanged(sessionId: Int) {} - override fun onActiveChanged(sessionId: Int, active: Boolean) {} - override fun onProgressChanged(sessionId: Int, progress: Float) {} - override fun onFinished(sessionId: Int, success: Boolean) { - _state.update { it.copy(installStatus = InstallStatus.Success, isDownloading = false)} - if (success) { - _state.update { it.copy(isInstalled = true, isNeedUpgrade = false) } - apkInstaller.deleteApkFile(apkFile.name) - } + private fun installApp(context: Context, apkFiles: List) { + val packageName = state.value.item?.packageName ?: "tmp" + _state.update { it.copy(installStatus = InstallStatus.Pending) } + + apkInstaller.installApp( + packageName = packageName, + apkFiles = apkFiles, + onSessionFinished = { success -> + _state.update { it.copy(installStatus = InstallStatus.Success, isDownloading = false)} + if (success) { + _state.update { it.copy(isInstalled = true, isNeedUpgrade = false, installerPackageName = context.packageName) } + apkInstaller.cleanApkFiles(apkFiles.map {it.name}) + } + }, + onError = { error -> + if (error.message?.contains("Failed to allocate") == true) { + Toast.makeText( + context, + R.string.insufficient_memory, + Toast.LENGTH_SHORT + ).show() + } else { + println("apk installer $error") + Toast.makeText(context, R.string.installing_error, Toast.LENGTH_SHORT) + .show() + } + _state.update { + it.copy( + installStatus = InstallStatus.Idle, + isDownloading = false + ) } } - apkInstaller.installApk(context, apkFile, installerCallback, onError = { error -> - if (error.message?.contains("Failed to allocate") == true) { - Toast.makeText(context, R.string.insufficient_memory, Toast.LENGTH_SHORT).show() - } else { - Toast.makeText(context, R.string.installing_error, Toast.LENGTH_SHORT).show() - } - _state.update { it.copy(installStatus = InstallStatus.Idle, isDownloading = false) } - }) + ) + } + + fun retryDownloadAfterInvalid(context: Context) { + _state.update { + it.copy( + invalidDownloadedApkFiles = null, + invalidDownloadMessage = null, + invalidExpectedHash = null, + invalidActualHash = null + ) + } + downloadAndInstallApp(context) + } + + fun installAsIsAfterInvalid(context: Context) { + val apkFiles = state.value.invalidDownloadedApkFiles ?: return + _state.update { + it.copy( + invalidDownloadedApkFiles = null, + invalidDownloadMessage = null, + invalidExpectedHash = null, + invalidActualHash = null + ) + } + installApp(context, apkFiles) + } + + fun clearInvalidDownloadState() { + _state.update { + it.copy( + invalidDownloadedApkFiles = null, + invalidDownloadMessage = null, + invalidExpectedHash = null, + invalidActualHash = null + ) } } @@ -197,7 +288,34 @@ class DetailsViewModel(private val itemId: String, private val apkInstaller: Apk } fun updateInstallStatus(isInstalled: Boolean) { - _state.update { it.copy(isInstalled = isInstalled) } + _state.update { it.copy(isInstalled = isInstalled, installerPackageName = if (isInstalled) it.installerPackageName else null) } + } + + fun downloadFileToFolder(context: Context) { + val fileName = "${state.value.item?.packageName}-${state.value.item?.versionName}.apk" + val request = DownloadManager.Request(state.value.plainApkUrl?.toUri()) + .setTitle(fileName) + .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) + .setMimeType("application/vnd.android.package-archive") + .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) + + val downloadManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + context.getSystemService(DownloadManager::class.java) + } else { + @Suppress("DEPRECATION") + context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager + } + downloadManager.enqueue(request) + Toast.makeText(context, R.string.download_has_started, Toast.LENGTH_SHORT).show() + } + + fun copyTextToCB(context: Context, text: String) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText("", text) + clipboard.setPrimaryClip(clip) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { + Toast.makeText(context, R.string.copied_to_buffer, Toast.LENGTH_SHORT).show() + } } } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsScreen.kt index 193c852..811dd57 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsScreen.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsScreen.kt @@ -5,15 +5,16 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Card +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -21,13 +22,21 @@ import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.hideFromAccessibility +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -50,19 +59,50 @@ fun ResultsScreen( val viewModel : ResultsViewModel = viewModel( factory = ResultsViewModelFactory(query) ) - val resultsLazyPaging = viewModel.searchFlow.collectAsLazyPagingItems() + val resultsLazyPaging = viewModel.searchFlow.collectAsLazyPagingItems() + var platformSelectorExpanded by remember { mutableStateOf(false) } + val state by viewModel.state.collectAsState() Scaffold( topBar = { TopAppBar( title = {Text(stringResource(R.string.search_title))}, navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = "Back" + painterResource(R.drawable.ic_arrow_back_24px), + contentDescription = stringResource(R.string.back_button_desc) ) } }, + actions = { + val platforms = remember { + listOf( + Platform(R.string.mobile_label, "mobile", R.drawable.ic_mobile_24px), + Platform(R.string.tv_label, "tv", R.drawable.ic_tv_gen_24px) + ) + } + + TextButton({platformSelectorExpanded = true}) { + Icon( + painterResource(state.selectedPlatform.icon), + contentDescription = stringResource(R.string.tts_current_platform) + ) + Spacer(Modifier.size(8.dp)) + Text(stringResource(state.selectedPlatform.label)) + } + DropdownMenu( + expanded = platformSelectorExpanded, + onDismissRequest = {platformSelectorExpanded = false} + ) { + platforms.forEach { + DropdownMenuItem( + leadingIcon = {Icon(painterResource(it.icon), null)}, + text = { Text(stringResource(it.label)) }, + onClick = { viewModel.selectPlatform(it); platformSelectorExpanded=false } + ) + } + } + } ) } ) { innerPadding -> LazyColumn( @@ -78,7 +118,7 @@ fun ResultsScreen( Card( modifier = Modifier .clip(RoundedCornerShape(12.dp)) - .clickable(onClick = { navController.navigate("app/${app.packageName}") }) + .clickable(onClick = { navController.navigate("app/${app.packageName}?platform=${state.selectedPlatform.value}") }) ) { Row( modifier = Modifier.fillMaxSize().padding(16.dp), @@ -90,7 +130,16 @@ fun ResultsScreen( modifier = Modifier.weight(1f).padding(start = 16.dp,end = 4.dp) ) { Text(text = app.appName, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text(text = app.packageName, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, color = MaterialTheme.colorScheme.secondary) + Text( + text = app.packageName, + fontSize = 14.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.secondary, + modifier = Modifier.semantics{ + hideFromAccessibility() + } + ) } } } @@ -139,5 +188,21 @@ fun ResultsScreen( } } } + if (resultsLazyPaging.itemCount == 0 && resultsLazyPaging.loadState.isIdle) { + Column( + modifier = Modifier + .padding(horizontal = 16.dp) + .padding(bottom = 56.dp) + .fillMaxSize() + .padding(innerPadding) + .fillMaxSize(), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon(painterResource(R.drawable.ic_search_24px), "", modifier = Modifier.size(64.dp)) + Spacer(Modifier.size(4.dp)) + Text(stringResource(R.string.not_found_error)) + } + } } } \ No newline at end of file diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsViewModel.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsViewModel.kt index 4dfe6f2..5bfbf0b 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsViewModel.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/results/ResultsViewModel.kt @@ -5,14 +5,37 @@ import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.paging.PagingData import androidx.paging.cachedIn +import dev.mi6e4ka.openstore.R import dev.mi6e4ka.openstore.data.model.SearchResult import dev.mi6e4ka.openstore.di.AppModule +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.update + +data class Platform( + val label: Int, + val value: String, + val icon: Int +) +data class ResultsState( + val selectedPlatform: Platform = Platform(R.string.mobile_label, "mobile", R.drawable.ic_mobile_24px), +) class ResultsViewModel(private val query: String) : ViewModel() { + private val _state = MutableStateFlow(ResultsState()) + val state: StateFlow = _state.asStateFlow() + @OptIn(ExperimentalCoroutinesApi::class) + val searchFlow: Flow> = state.flatMapLatest { + AppModule.searchRepository.search(query, it.selectedPlatform.value).flow + }.cachedIn(viewModelScope) - val searchFlow: Flow> = - AppModule.searchRepository.search(query).flow.cachedIn(viewModelScope) + fun selectPlatform(newPlatform: Platform) { + _state.update { it.copy(selectedPlatform = newPlatform) } + } } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/reviews/ReviewsScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/reviews/ReviewsScreen.kt index c8e4970..56eea6e 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/reviews/ReviewsScreen.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/reviews/ReviewsScreen.kt @@ -15,13 +15,6 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.filled.Check -import androidx.compose.material.icons.filled.Star -import androidx.compose.material.icons.filled.ThumbDownOffAlt -import androidx.compose.material.icons.filled.ThumbUpOffAlt -import androidx.compose.material.icons.outlined.StarBorder import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip @@ -42,7 +35,12 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.navigation.NavController @@ -100,8 +98,8 @@ fun ReviewsScreen(packageName: String, navController: NavController = rememberNa navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = "Back" + painterResource(R.drawable.ic_arrow_back_24px), + contentDescription = stringResource(R.string.back_button_desc) ) } }, @@ -124,7 +122,7 @@ fun ReviewsScreen(packageName: String, navController: NavController = rememberNa onClick = { selectedFilter = filter }, label = {Text(stringResource(filter.displayStringResource))}, leadingIcon = if (selectedFilter == filter) { - { Icon(Icons.Default.Check, contentDescription = null) } + { Icon(painterResource(R.drawable.ic_check_24px), contentDescription = null) } } else null ) } @@ -141,11 +139,12 @@ fun ReviewsScreen(packageName: String, navController: NavController = rememberNa } items(reviews ?: listOf()) { review -> Card( - Modifier.fillMaxWidth() + Modifier.fillMaxWidth().semantics(mergeDescendants = true){} ) { Column( Modifier.padding(16.dp) ) { + val context = LocalContext.current Row( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, @@ -161,13 +160,16 @@ fun ReviewsScreen(packageName: String, navController: NavController = rememberNa } Spacer(Modifier.height(8.dp)) Row( - verticalAlignment = Alignment.CenterVertically + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.clearAndSetSemantics{ + contentDescription = context.getString(R.string.review_rating_desc, review.appRating) + } ) { repeat(review.appRating) { - Icon(Icons.Filled.Star, null, Modifier.size(16.dp), tint = MaterialTheme.colorScheme.primary) + Icon(painterResource(R.drawable.ic_star_filled_24px), null, Modifier.size(16.dp), tint = MaterialTheme.colorScheme.primary) } repeat(5 - review.appRating) { - Icon(Icons.Outlined.StarBorder, null, Modifier.size(16.dp), tint = MaterialTheme.colorScheme.secondary) + Icon(painterResource(R.drawable.ic_star_24px), null, Modifier.size(16.dp), tint = MaterialTheme.colorScheme.secondary) } } Spacer(Modifier.height(8.dp)) @@ -177,12 +179,12 @@ fun ReviewsScreen(packageName: String, navController: NavController = rememberNa horizontalArrangement = Arrangement.spacedBy(16.dp) ) { Row(verticalAlignment = Alignment.CenterVertically) { - Icon(imageVector = Icons.Default.ThumbUpOffAlt, contentDescription = null, Modifier.size(20.dp), tint = MaterialTheme.colorScheme.secondary) + Icon(painterResource(R.drawable.ic_thumb_up_24px), contentDescription = stringResource(R.string.likes_desc), Modifier.size(20.dp), tint = MaterialTheme.colorScheme.secondary) Spacer(Modifier.width(4.dp)) Text("${review.likeCounter}") } Row(verticalAlignment = Alignment.CenterVertically) { - Icon(imageVector = Icons.Default.ThumbDownOffAlt, contentDescription = null, Modifier.size(20.dp), tint = MaterialTheme.colorScheme.secondary) + Icon(painterResource(R.drawable.ic_thumb_down_24px), contentDescription = stringResource(R.string.dislikes_desc), Modifier.size(20.dp), tint = MaterialTheme.colorScheme.secondary) Spacer(Modifier.width(6.dp)) Text("${review.dislikeCounter}") } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/search/SearchScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/search/SearchScreen.kt index 6e08939..e5c319b 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/search/SearchScreen.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/search/SearchScreen.kt @@ -2,16 +2,15 @@ package dev.mi6e4ka.openstore.ui.screen.search import android.content.Intent import android.content.pm.verify.domain.DomainVerificationManager -import android.content.pm.verify.domain.DomainVerificationUserState import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log -import androidx.annotation.RequiresApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -19,19 +18,16 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.DomainVerification -import androidx.compose.material.icons.filled.Search -import androidx.compose.material.icons.filled.Verified -import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -39,7 +35,6 @@ import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -50,7 +45,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp @@ -63,6 +62,7 @@ import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import dev.mi6e4ka.openstore.BuildConfig import dev.mi6e4ka.openstore.R +import dev.mi6e4ka.openstore.ui.screen.results.Platform import java.net.URLEncoder @OptIn(ExperimentalMaterial3Api::class) @@ -88,29 +88,24 @@ fun SearchScreen(navController: NavController = rememberNavController()) { Scaffold( modifier = Modifier.fillMaxSize(), - topBar = { TopAppBar(title = {Text(stringResource(R.string.app_name))}) }, + topBar = { TopAppBar( + title = {Text(stringResource(R.string.app_name))}, + actions = { + IconButton(onClick = { navController.navigate("updates") }) { + Icon( + painter = painterResource(R.drawable.ic_update_24px), + contentDescription = stringResource(R.string.updates_title) + ) + } + IconButton({navController.navigate("settings")}) { + Icon( + painterResource(R.drawable.ic_settings_24px), + contentDescription = stringResource(R.string.settings_title) + ) + } + } + ) }, ) { innerPadding -> -// if (showDialog) { -// AlertDialog( -// onDismissRequest = {showDialog=false}, -// title = { Text("Добавьте ссылки RuStore") }, -// text = { Text("Чтобы ") }, -// confirmButton = { -// TextButton(onClick = { -// val intent = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS) -// .apply { data = Uri.fromParts("package", context.packageName, null) } -// context.startActivity(intent) -// }) { -// Text("Подтвердить") -// } -// }, -// dismissButton = { -// TextButton(onClick = {showDialog=false}) { -// Text("Позже") -// } -// } -// ) -// } Column( modifier = Modifier .padding(innerPadding) @@ -129,11 +124,13 @@ fun SearchScreen(navController: NavController = rememberNavController()) { .height(50.dp) .clip(RoundedCornerShape(12.dp)) .clickable(onClick = { - val intent = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS) - .apply { data = Uri.fromParts("package", context.packageName, null) } - context.startActivity(intent) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val intent = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS) + .apply { data = Uri.fromParts("package", context.packageName, null) } + context.startActivity(intent) + } }), - colors = CardDefaults.cardColors(containerColor = Color(255, 30, 30, 40)) + colors = CardDefaults.cardColors(containerColor = Color(109, 255, 30, 40)) ) { Row( horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -143,7 +140,7 @@ fun SearchScreen(navController: NavController = rememberNavController()) { .padding(horizontal = 10.dp) ) { Icon( - imageVector = Icons.Default.DomainVerification, + painterResource(R.drawable.ic_add_link_24px), contentDescription = null, modifier = Modifier.size(32.dp), ) @@ -155,8 +152,10 @@ fun SearchScreen(navController: NavController = rememberNavController()) { OutlinedTextField( value = search, onValueChange = {s -> search=s}, - leadingIcon = { Icon(imageVector = Icons.Default.Search, contentDescription = null) }, - modifier = Modifier.fillMaxWidth(), + leadingIcon = { Icon(painterResource(R.drawable.ic_search_24px), contentDescription = null) }, + modifier = Modifier.fillMaxWidth().semantics{ + contentDescription = context.getString(R.string.search_title) + }, singleLine = true, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search @@ -176,7 +175,7 @@ fun SearchScreen(navController: NavController = rememberNavController()) { val intent = Intent(Intent.ACTION_VIEW, "https://codeberg.org/mi6e4ka/openstore".toUri()) context.startActivity(intent) })) - Text("v${BuildConfig.VERSION_NAME}") + Text(BuildConfig.VERSION_NAME) } } } diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsScreen.kt new file mode 100644 index 0000000..a5cbd2f --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsScreen.kt @@ -0,0 +1,407 @@ +package dev.mi6e4ka.openstore.ui.screen.settings + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Context +import android.os.Build +import android.util.Log +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.navigation.NavController +import dev.mi6e4ka.openstore.R +import androidx.core.content.edit + +data class SettingsSection( + val id: String, + val title: Int, + val description: Int?, + val icon: Int, + val type: ParamType, + val defaultVal: String, + val select: List? = null +) + +@SuppressLint("ModifierParameter") +data class SettingsSectionSelect( + val title: String, + val value: String, + val isGroup: Boolean = false, + val groupPackages: List = emptyList() +) + +enum class ParamType { + SWITCH, + SELECT, + MULTI_SELECT +} + +@SuppressLint("ContextCastToActivity") +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen( + navController: NavController +) { + val context = LocalContext.current + + val dynamicSources = remember { + getDynamicInstallerSources(context) + } + + val sections = listOf( + SettingsSection( + id = "installer_type", + title = R.string.settings_installer_title, + description = R.string.settings_installer_description, + icon = R.drawable.apk_install_24px, + type = ParamType.SELECT, + defaultVal = "session", + select = listOf( + SettingsSectionSelect( + title = "Session", + value = "session" + ), + SettingsSectionSelect( + title = "Intent", + value = "intent" + ) + ) + ), + SettingsSection( + id = "updates_sources", + title = R.string.settings_updates_sources_title, + description = R.string.settings_updates_sources_description, + icon = R.drawable.ic_checklist_24px, + type = ParamType.MULTI_SELECT, + defaultVal = "dev.mi6e4ka.openstore;dev.mi6e4ka.openstore.nightly;dev.mi6e4ka.openstore.debug;ru.vk.store", + select = dynamicSources + ), + SettingsSection( + id = "updates_check_all", + title = R.string.settings_updates_check_all_title, + description = R.string.settings_updates_check_all_description, + icon = R.drawable.ic_arrow_shape_up_stack_2_24px, + type = ParamType.SWITCH, + defaultVal = "" + ), + SettingsSection( + id = "app_theme", + title = R.string.settings_app_theme_title, + description = null, + icon = R.drawable.ic_brightness_6_24px, + type = ParamType.SELECT, + defaultVal = "auto", + select = listOf( + SettingsSectionSelect( + title = context.getString(R.string.theme_auto_label), + value = "auto" + ), + SettingsSectionSelect( + title = context.getString(R.string.theme_dark_label), + value = "dark" + ), + SettingsSectionSelect( + title = context.getString(R.string.theme_light_label), + value = "light" + ), + ) + ) + ) + + val activity = context as? Activity + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.settings_title)) }, + navigationIcon = { + IconButton( + { + val popped = navController.popBackStack() + if (!popped) { + activity?.finish() + } + } + ) { + Icon( + painterResource(R.drawable.ic_arrow_back_24px), + stringResource(R.string.back_button_desc) + ) + } + } + ) + } + ) { + innerPadding -> + LazyColumn( + modifier = Modifier.fillMaxSize().padding(innerPadding) + ) { + items(sections) { item -> + SettingsCard( + item = item + ) + } + } + } +} + +private fun getDynamicInstallerSources(context: Context): List { + val pm = context.packageManager + val installedPackages = pm.getInstalledPackages(0) + + val foundInstallers = installedPackages.map { pkg -> + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + pm.getInstallSourceInfo(pkg.packageName).installingPackageName + } catch (e: Exception) { null } + } else { + @Suppress("DEPRECATION") + pm.getInstallerPackageName(pkg.packageName) + } + }.toSet() + + val result = mutableListOf() + + result.add(SettingsSectionSelect( + title = "RuStore/OpenStore", + value = "group_openstore", + isGroup = true, + groupPackages = listOf( + "dev.mi6e4ka.openstore", + "dev.mi6e4ka.openstore.nightly", + "dev.mi6e4ka.openstore.debug", + "ru.vk.store" + ) + )) + + result.add(SettingsSectionSelect( + title = context.getString(R.string.settings_source_manual), + value = "group_installers", + isGroup = true, + groupPackages = listOf( + "com.google.android.packageinstaller", + "com.android.packageinstaller" + ) + )) + + result.add(SettingsSectionSelect( + title = context.getString(R.string.settings_source_unknown), + value = "null" + )) + + val handledPackages = mutableSetOf() + handledPackages.add(null) + handledPackages.add("null") + handledPackages.add("com.google.android.packageinstaller") + handledPackages.add("com.android.packageinstaller") + handledPackages.add("ru.vk.store") + handledPackages.add(context.packageName) + handledPackages.addAll(listOf("dev.mi6e4ka.openstore", "dev.mi6e4ka.openstore.nightly", "dev.mi6e4ka.openstore.debug")) + + foundInstallers.filter { it !in handledPackages && it != null }.forEach { pkg -> + val label = try { + val info = pm.getApplicationInfo(pkg!!, 0) + pm.getApplicationLabel(info).toString() + } catch (e: Exception) { + pkg + } + result.add(SettingsSectionSelect(title = label ?: pkg!!, value = pkg!!)) + } + Log.i("OS", "Found installers: $result") + return result +} + +@Composable +fun SettingsCard( + item: SettingsSection +) { + + val context = LocalContext.current + val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE) + var showDialog by remember { mutableStateOf(false) } + + var currentValue by remember { + mutableStateOf( + if (item.type == ParamType.SWITCH) prefs.getBoolean(item.id, false) + else prefs.getString(item.id, item.defaultVal) ?: item.defaultVal + ) + } + + val description = if (item.description != null && item.description != 0) { + stringResource(item.description) + } else if (item.type != ParamType.SWITCH) { + val strVal = currentValue as? String ?: "" + val selectedValues = strVal.split(";").filter { it.isNotEmpty() }.toSet() + item.select?.filter { entry -> + if (entry.isGroup) { + entry.groupPackages.any { it in selectedValues } + } else { + entry.value in selectedValues + } + }?.joinToString(", ") { it.title } ?: "" + } else "" + + Card ( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 4.dp), + ) { + Row( + Modifier + .clickable{ + if (item.type == ParamType.SWITCH) { + val newValue = !(currentValue as Boolean) + prefs.edit { putBoolean(item.id, newValue) } + currentValue = newValue + } else { + showDialog = true + } + } + .padding(15.dp) + .fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(15.dp) + ) { + Icon( + painterResource(item.icon), + "icon", + modifier = Modifier.size(32.dp) + ) + Column( + modifier = Modifier.weight(1f) + ) { + Text(stringResource(item.title), fontWeight = FontWeight.Medium) + if (description.isNotEmpty()) { + Text(description, color = Color.Gray, fontWeight = FontWeight.Normal) + } + } + if (item.type == ParamType.SWITCH) { + Switch( + currentValue as Boolean, + { v -> + prefs.edit { putBoolean(item.id, v) } + currentValue = v + } + ) + } + } + if (showDialog) { + val selectedPackages = remember { + mutableStateListOf().apply { + val currentStr = currentValue as? String ?: "" + addAll(currentStr.split(";").filter { it.isNotEmpty() }) + } + } + + var selectedVal by remember { mutableStateOf(currentValue as? String) } + + AlertDialog( + onDismissRequest = { showDialog = false }, + title = { Text(stringResource(item.title)) }, + text = { + LazyColumn(modifier = Modifier.heightIn(max = 380.dp)) { + items(item.select ?: listOf()) { entry -> + val isChecked = if (entry.isGroup) { + entry.groupPackages.all { it in selectedPackages } + } else { + entry.value in selectedPackages + } + + Row( + Modifier + .fillMaxWidth() + .clickable { + if (item.type == ParamType.MULTI_SELECT) { + if (entry.isGroup) { + if (isChecked) { + selectedPackages.removeAll(entry.groupPackages) + } else { + entry.groupPackages.forEach { + if (it !in selectedPackages) selectedPackages.add(it) + } + } + } else { + if (isChecked) { + selectedPackages.remove(entry.value) + } else { + selectedPackages.add(entry.value) + } + } + } else { + selectedVal = entry.value + } + } + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (item.type == ParamType.SELECT) { + RadioButton( + selected = selectedVal == entry.value, + onClick = { selectedVal = entry.value } + ) + } else { + Checkbox( + checked = isChecked, + onCheckedChange = null // Click handled by Row + ) + } + + Text( + entry.title, + modifier = Modifier.padding(start = 8.dp) + ) + } + } + } + }, + confirmButton = { + TextButton(onClick = { + val newValue = if (item.type == ParamType.MULTI_SELECT) { + selectedPackages.joinToString(";") + } else { + selectedVal ?: item.defaultVal + } + prefs.edit { putString(item.id, newValue) } + currentValue = newValue + showDialog = false + }) { + Text(stringResource(R.string.settings_save_button)) + } + } + ) + } + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsViewModel.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsViewModel.kt new file mode 100644 index 0000000..31109b9 --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/settings/SettingsViewModel.kt @@ -0,0 +1,19 @@ +package dev.mi6e4ka.openstore.ui.screen.settings + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider + +class DetailsViewModel() : ViewModel() { + +} + +class SettingsViewModelFactory() : ViewModelProvider.Factory { + + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(DetailsViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return DetailsViewModel() as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesScreen.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesScreen.kt new file mode 100644 index 0000000..ac422c0 --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesScreen.kt @@ -0,0 +1,346 @@ +package dev.mi6e4ka.openstore.ui.screen.updates + +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +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.fillMaxHeight +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.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.FilledTonalIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation.NavController +import dev.mi6e4ka.openstore.R +import dev.mi6e4ka.openstore.internal.installer.ApkInstaller +import dev.mi6e4ka.openstore.ui.components.AppIcon + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun UpdatesScreen(navController: NavController) { + val context = LocalContext.current + val apkInstaller = remember { ApkInstaller(context) } + val viewModel: UpdatesViewModel = viewModel( + factory = UpdatesViewModelFactory(apkInstaller) + ) + val state by viewModel.state.collectAsState() + var showHashDetails by remember { mutableStateOf(false) } + + if (state.invalidDownloadedApkFiles != null && state.invalidDownloadedAppPackage != null) { + AlertDialog( + onDismissRequest = { viewModel.clearInvalidDownloadState() }, + title = { Text(stringResource(R.string.invalid_download_hash_title)) }, + text = { + Column { + Text(stringResource(R.string.invalid_download_hash_message)) + Spacer(modifier = Modifier.size(12.dp)) + TextButton(onClick = { showHashDetails = !showHashDetails }) { + Text(stringResource(R.string.show_hashes)) + } + if (showHashDetails) { + Spacer(modifier = Modifier.size(8.dp)) + Text(stringResource(R.string.expected_hash, state.invalidExpectedHash ?: "")) + Text(stringResource(R.string.actual_hash, state.invalidActualHash ?: "")) + } + } + }, + confirmButton = { + TextButton(onClick = { viewModel.retryDownloadAfterInvalid(context) }) { + Text(stringResource(R.string.download_again)) + } + }, + dismissButton = { + TextButton(onClick = { viewModel.installAsIsAfterInvalid(context) }) { + Text(stringResource(R.string.install_as_is)) + } + } + ) + } + + LaunchedEffect(Unit) { + viewModel.loadAndCheckUpdates(context) + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.updates_title)) }, + navigationIcon = { + IconButton(onClick = { navController.popBackStack() }) { + Icon( + painter = painterResource(R.drawable.ic_arrow_back_24px), + contentDescription = stringResource(R.string.back_button_desc) + ) + } + }, + actions = { + IconButton( + onClick = { viewModel.checkForUpdates(context) }, + enabled = !state.isCheckingUpdates && !state.isLoading + ) { + Icon( + painter = painterResource(R.drawable.ic_refresh_24px), + contentDescription = stringResource(R.string.check_updates) + ) + } + } + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + if (state.isLoading) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator() + } + } else if (state.isCheckingUpdates) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + CircularProgressIndicator() + Spacer(modifier = Modifier.size(16.dp)) + Text(stringResource(R.string.checking_updates)) + } + } else if (state.appsWithUpdates.isEmpty()) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + UpdatesBanner(navController, state.installedApps.size) + Spacer(modifier = Modifier.weight(1f)) + + Icon( + painter = painterResource(R.drawable.ic_check_circle_24px), + contentDescription = null, + modifier = Modifier.size(80.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.size(16.dp)) + Text( + stringResource(R.string.all_apps_updated), + fontWeight = FontWeight.Bold, + fontSize = 18.sp + ) + + Spacer(modifier = Modifier.weight(1f)) + } + } else { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + item { + UpdatesBanner(navController, state.installedApps.size) + } + + item { + Text( + stringResource(R.string.available_updates, state.appsWithUpdates.size), + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(vertical = 8.dp) + ) + } + + items(state.appsWithUpdates, key = { it.packageName }) { app -> + UpdateAppCard( + app = app, + isDownloading = state.downloadingPackages.contains(app.packageName), + downloadProgress = state.downloadProgress[app.packageName] ?: 0, + onUpdateClick = { viewModel.downloadAndUpdateApp(context, app) }, + onCancelClick = { viewModel.cancelDownload(app.packageName) }, + onCardClick = { navController.navigate("app/${app.packageName}?platform=mobile") } + ) + } + } + } + } + } +} + +@Composable +fun UpdatesBanner(navController: NavController, checkAppsCount: Int) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(0.dp) + .height(80.dp) + .clip(RoundedCornerShape(12.dp)) + .clickable(onClick = { + navController.navigate("settings") + }), + //colors = CardDefaults.cardColors(containerColor = Color(109, 255, 30, 40)) + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxHeight() + .fillMaxWidth() + .padding(horizontal = 24.dp) + ) { + Icon( + painterResource(R.drawable.ic_settings_24px), + contentDescription = null, + modifier = Modifier.size(32.dp), + ) + Column { + Text(stringResource(R.string.updates_app_count, checkAppsCount)) + Text(stringResource(R.string.updates_change_settings)) + } + } + } +} + +@Composable +fun UpdateAppCard( + app: AppWithUpdates, + isDownloading: Boolean, + downloadProgress: Int, + onUpdateClick: () -> Unit, + onCancelClick: () -> Unit, + onCardClick: () -> Unit +) { + Card( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable(onClick = onCardClick) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + if (app.iconUrl != null) { + AppIcon( + app.iconUrl, + modifier = Modifier + .size(56.dp) + .clip(RoundedCornerShape(12.dp)) + ) + } else { + Box( + modifier = Modifier + .size(56.dp) + .clip(RoundedCornerShape(12.dp)), + contentAlignment = Alignment.Center + ) { + Icon( + painter = painterResource(R.drawable.ic_android_24px), + contentDescription = null, + modifier = Modifier.size(32.dp) + ) + } + } + + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 12.dp) + ) { + Text( + text = app.appName, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = "${app.installedVersionCode} → ${app.latestVersionCode}", + fontSize = 12.sp, + color = MaterialTheme.colorScheme.secondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) +// Text( +// text = "from ${app.installSource}", +// fontSize = 12.sp, +// color = MaterialTheme.colorScheme.secondary, +// maxLines = 1, +// overflow = TextOverflow.Ellipsis +// ) + if (isDownloading) { + Spacer(modifier = Modifier.size(4.dp)) + LinearProgressIndicator( + progress = { downloadProgress / 100f }, + modifier = Modifier.fillMaxWidth() + ) + } + } + + if (isDownloading) { + FilledTonalIconButton(onClick = onCancelClick) { + Icon( + painter = painterResource(R.drawable.ic_close_24px), + contentDescription = null + ) + } + } else { + FilledTonalButton(onClick = onUpdateClick) { + Text(stringResource(R.string.update)) + } + } + } + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModel.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModel.kt new file mode 100644 index 0000000..a357330 --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModel.kt @@ -0,0 +1,322 @@ +package dev.mi6e4ka.openstore.ui.screen.updates + +import android.content.Context +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import android.os.Build +import android.widget.Toast +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dev.mi6e4ka.openstore.R +import dev.mi6e4ka.openstore.data.model.AppUpdateRequestEntry +import dev.mi6e4ka.openstore.di.AppModule +import dev.mi6e4ka.openstore.internal.installer.ApkInstaller +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File + +data class AppWithUpdates ( + val packageName: String, + val appName: String, + val installedVersionCode: Long, + val installedVersionName: String, + val iconUrl: String? = null, + val latestVersionCode: Long? = null, + val latestVersionName: String? = null, + val appId: Int? = null, + val installSource: String +) + +data class UpdatesState( + val isLoading: Boolean = false, + val isCheckingUpdates: Boolean = false, + val installedApps: List = emptyList(), + val appsWithUpdates: List = emptyList(), + val error: String? = null, + val downloadingPackages: Set = emptySet(), + val downloadProgress: Map = emptyMap(), + val invalidDownloadedApkFiles: List? = null, + val invalidDownloadedAppPackage: String? = null, + val invalidExpectedHash: String? = null, + val invalidActualHash: String? = null +) + +class UpdatesViewModel(private val apkInstaller: ApkInstaller) : ViewModel() { + private val _state = MutableStateFlow(UpdatesState()) + val state: StateFlow = _state.asStateFlow() + + private val cancelDownloads = mutableMapOf Unit>() + + companion object { + private const val DEFAULT_SOURCES = "dev.mi6e4ka.openstore;dev.mi6e4ka.openstore.nightly;dev.mi6e4ka.openstore.debug;ru.vk.store" + } + + fun loadAndCheckUpdates(context: Context) { + viewModelScope.launch { + // Загружаем список приложений + _state.update { it.copy(isLoading = true, error = null) } + val installedApps = try { + withContext(Dispatchers.IO) { + getInstalledApps(context) + } + } catch (e: Exception) { + _state.update { it.copy(error = e.message, isLoading = false) } + return@launch + } + _state.update { it.copy(installedApps = installedApps, isLoading = false) } + + // Сразу запускаем проверку + checkForUpdatesInternal(installedApps) + } + } + + fun checkForUpdates(context: Context) { + loadAndCheckUpdates(context) + } + + private suspend fun checkForUpdatesInternal(installedApps: List) { + _state.update { it.copy(isCheckingUpdates = true, appsWithUpdates = emptyList()) } + + val rawUpdates = AppModule.searchRepository.getBatchUpdates(installedApps) + + if (rawUpdates.isEmpty()) { + _state.update { + it.copy( + isCheckingUpdates = false, + appsWithUpdates = emptyList() + ) + } + return + } + + val detailsUpdates = AppModule.searchRepository.getBatchItemDetails(rawUpdates.map {it.packageName} ) + + val detailsByPackageName = detailsUpdates.associateBy {it.packageName} + val installedAppsByPackageName = installedApps.associateBy {it.packageName} + + val appsWithUpdates = rawUpdates.mapNotNull { + val details = detailsByPackageName[it.packageName] ?: return@mapNotNull null + val installedApp = installedAppsByPackageName[it.packageName] ?: return@mapNotNull null + AppWithUpdates( + packageName = it.packageName, + appName = it.appName, + installedVersionCode = installedApp.versionCode, + installedVersionName = installedApp.versionName, + iconUrl = details.iconUrl, + latestVersionCode = details.versionCode, + latestVersionName = "?", + appId = it.appId, + installSource = installedApp.installSource + ) + } + + _state.update { + it.copy( + isCheckingUpdates = false, + appsWithUpdates = appsWithUpdates + ) + } + } + + fun downloadAndUpdateApp(context: Context, app: AppWithUpdates) { + if (app.appId == null) return + + viewModelScope.launch { + _state.update { + it.copy( + downloadingPackages = it.downloadingPackages + app.packageName, + downloadProgress = it.downloadProgress + (app.packageName to 0) + ) + } + + try { + val appFiles = withContext(Dispatchers.IO) { + AppModule.searchRepository.getAppFiles( + app.appId, + firstInstall = false, + supportedAbis = Build.SUPPORTED_ABIS.toList(), + withoutSplits = false, + deviceType = "mobile" + ) + } + + cancelDownloads[app.packageName] = apkInstaller.downloadFilesWithProgress( + appFiles, + onProgress = { percent, _, _ -> + _state.update { + it.copy(downloadProgress = it.downloadProgress + (app.packageName to percent)) + } + }, + onSuccess = { apkFiles -> + installApp(context, app.packageName, apkFiles) + }, + onError = { error -> + handleError(context, app.packageName, error) + }, + onCancel = { + _state.update { + it.copy( + downloadingPackages = it.downloadingPackages - app.packageName, + downloadProgress = it.downloadProgress - app.packageName + ) + } + }, + onInvalidHash = { apkFiles, expectedHash, actualHash -> + _state.update { + it.copy( + downloadingPackages = it.downloadingPackages - app.packageName, + downloadProgress = it.downloadProgress - app.packageName, + invalidDownloadedApkFiles = apkFiles, + invalidDownloadedAppPackage = app.packageName, + invalidExpectedHash = expectedHash, + invalidActualHash = actualHash + ) + } + } + ) + } catch (e: Exception) { + handleError(context, app.packageName, e) + } + } + } + + private fun installApp(context: Context, packageName: String, apkFiles: List) { + apkInstaller.installApp( + packageName = packageName, + apkFiles = apkFiles, + onSessionFinished = { success -> + _state.update { + it.copy( + downloadingPackages = it.downloadingPackages - packageName, + downloadProgress = it.downloadProgress - packageName, + appsWithUpdates = if (success) { + it.appsWithUpdates.filter { app -> app.packageName != packageName } + } else it.appsWithUpdates + ) + } + if (success) { + apkInstaller.cleanApkFiles(apkFiles.map { it.name }) + } + }, + onError = { error -> + handleError(context, packageName, error) + } + ) + } + + private fun handleError(context: Context, packageName: String, error: Throwable) { + if (error.message?.contains("Failed to allocate") == true) { + Toast.makeText(context, R.string.insufficient_memory, Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(context, R.string.loading_error, Toast.LENGTH_SHORT).show() + } + _state.update { + it.copy( + downloadingPackages = it.downloadingPackages - packageName, + downloadProgress = it.downloadProgress - packageName + ) + } + } + + fun cancelDownload(packageName: String) { + cancelDownloads[packageName]?.invoke() + cancelDownloads.remove(packageName) + } + + fun retryDownloadAfterInvalid(context: Context) { + val packageName = state.value.invalidDownloadedAppPackage ?: return + _state.update { + it.copy( + invalidDownloadedAppPackage = null, + invalidDownloadedApkFiles = null, + invalidExpectedHash = null, + invalidActualHash = null + ) + } + val app = state.value.appsWithUpdates.find { it.packageName == packageName } ?: return + downloadAndUpdateApp(context, app) + } + + fun installAsIsAfterInvalid(context: Context) { + val packageName = state.value.invalidDownloadedAppPackage ?: return + val apkFiles = state.value.invalidDownloadedApkFiles ?: return + _state.update { + it.copy( + invalidDownloadedAppPackage = null, + invalidDownloadedApkFiles = null, + invalidExpectedHash = null, + invalidActualHash = null + ) + } + installApp(context, packageName, apkFiles) + } + + fun clearInvalidDownloadState() { + _state.update { + it.copy( + invalidDownloadedAppPackage = null, + invalidDownloadedApkFiles = null, + invalidExpectedHash = null, + invalidActualHash = null + ) + } + } + + private fun getInstalledApps(context: Context): List { + val pm = context.packageManager + val packages = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + pm.getInstalledPackages(PackageManager.PackageInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + pm.getInstalledPackages(0) + } + + val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE) + + val allowedSources = prefs.getString("updates_sources", DEFAULT_SOURCES)?.split(";") ?: listOf() + val allowAllSources = prefs.getBoolean("updates_check_all", false) + + return packages + .filter { !isSystemApp(it) && (allowAllSources || allowedSources.contains(getInstallSource(pm, it.packageName))) } + .map { packageInfo -> + val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + packageInfo.longVersionCode + } else { + @Suppress("DEPRECATION") + packageInfo.versionCode.toLong() + } + println("package "+packageInfo.packageName+" from "+getInstallSource(pm, packageInfo.packageName)) + AppUpdateRequestEntry( + packageName = packageInfo.packageName, + appName = pm.getApplicationLabel(packageInfo.applicationInfo!!).toString(), + versionCode = versionCode, + versionName = packageInfo.versionName ?: "Unknown", + installSource = getInstallSource(pm, packageInfo.packageName) + ) + } + } + + private fun isSystemApp(packageInfo: PackageInfo): Boolean { + return (packageInfo.applicationInfo?.flags?.and(ApplicationInfo.FLAG_SYSTEM) ?: 0) != 0 + } + + private fun getInstallSource(pm: PackageManager, packageName: String): String { + val installer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + pm.getInstallSourceInfo(packageName).installingPackageName + } catch (e: Exception) { + null + } + } else { + @Suppress("DEPRECATION") + pm.getInstallerPackageName(packageName) + } + return installer ?: "null" + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModelFactory.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModelFactory.kt new file mode 100644 index 0000000..e716802 --- /dev/null +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/screen/updates/UpdatesViewModelFactory.kt @@ -0,0 +1,18 @@ +package dev.mi6e4ka.openstore.ui.screen.updates + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import dev.mi6e4ka.openstore.internal.installer.ApkInstaller + +class UpdatesViewModelFactory( + private val apkInstaller: ApkInstaller +) : ViewModelProvider.Factory { + + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(UpdatesViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return UpdatesViewModel(apkInstaller) as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } +} diff --git a/app/src/main/java/dev/mi6e4ka/openstore/ui/theme/Theme.kt b/app/src/main/java/dev/mi6e4ka/openstore/ui/theme/Theme.kt index 807a5c3..ecf25de 100644 --- a/app/src/main/java/dev/mi6e4ka/openstore/ui/theme/Theme.kt +++ b/app/src/main/java/dev/mi6e4ka/openstore/ui/theme/Theme.kt @@ -1,4 +1,6 @@ package dev.mi6e4ka.openstore.ui.theme +import android.app.Activity +import android.content.Context import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme @@ -8,8 +10,13 @@ import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat private val lightScheme = lightColorScheme( primary = primaryLight, @@ -253,21 +260,36 @@ val unspecified_scheme = ColorFamily( @Composable fun AppTheme( - darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable() () -> Unit ) { + val context = LocalContext.current + val prefs = remember { context.getSharedPreferences("settings", Context.MODE_PRIVATE) } + val appTheme = prefs.getString("app_theme", "auto") + + val darkTheme = (isSystemInDarkTheme() && appTheme == "auto") || (appTheme == "dark") + val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { - val context = LocalContext.current - if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + if (darkTheme) + dynamicDarkColorScheme(context) + else dynamicLightColorScheme(context) } darkTheme -> darkScheme else -> lightScheme } + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme + WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = !darkTheme + } + } + MaterialTheme( colorScheme = colorScheme, //typography = AppTypography, diff --git a/app/src/main/res/drawable-v24/ic_launcher_background.xml b/app/src/main/res/drawable-v24/ic_launcher_background.xml index e5e9a2e..721ed9f 100644 --- a/app/src/main/res/drawable-v24/ic_launcher_background.xml +++ b/app/src/main/res/drawable-v24/ic_launcher_background.xml @@ -2,19 +2,19 @@ xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" - android:viewportWidth="199" - android:viewportHeight="199"> + android:viewportWidth="130" + android:viewportHeight="130"> + android:pathData="M0,0h130v130h-130z"> - - - + + diff --git a/app/src/main/res/drawable/ic_adb_24px.xml b/app/src/main/res/drawable/ic_adb_24px.xml new file mode 100644 index 0000000..c62bc18 --- /dev/null +++ b/app/src/main/res/drawable/ic_adb_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_add_link_24px.xml b/app/src/main/res/drawable/ic_add_link_24px.xml new file mode 100644 index 0000000..42fb1f7 --- /dev/null +++ b/app/src/main/res/drawable/ic_add_link_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_android_24px.xml b/app/src/main/res/drawable/ic_android_24px.xml new file mode 100644 index 0000000..4791c04 --- /dev/null +++ b/app/src/main/res/drawable/ic_android_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_arrow_back_24px.xml b/app/src/main/res/drawable/ic_arrow_back_24px.xml new file mode 100644 index 0000000..0e2e863 --- /dev/null +++ b/app/src/main/res/drawable/ic_arrow_back_24px.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_arrow_circle_up_24px.xml b/app/src/main/res/drawable/ic_arrow_circle_up_24px.xml new file mode 100644 index 0000000..490a1ef --- /dev/null +++ b/app/src/main/res/drawable/ic_arrow_circle_up_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_arrow_forward_24px.xml b/app/src/main/res/drawable/ic_arrow_forward_24px.xml new file mode 100644 index 0000000..81139b1 --- /dev/null +++ b/app/src/main/res/drawable/ic_arrow_forward_24px.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_arrow_shape_up_stack_2_24px.xml b/app/src/main/res/drawable/ic_arrow_shape_up_stack_2_24px.xml new file mode 100644 index 0000000..d973457 --- /dev/null +++ b/app/src/main/res/drawable/ic_arrow_shape_up_stack_2_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_brightness_6_24px.xml b/app/src/main/res/drawable/ic_brightness_6_24px.xml new file mode 100644 index 0000000..b45159e --- /dev/null +++ b/app/src/main/res/drawable/ic_brightness_6_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_broken_image_24px.xml b/app/src/main/res/drawable/ic_broken_image_24px.xml new file mode 100644 index 0000000..42d644f --- /dev/null +++ b/app/src/main/res/drawable/ic_broken_image_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_captive_portal_24px.xml b/app/src/main/res/drawable/ic_captive_portal_24px.xml new file mode 100644 index 0000000..db496ab --- /dev/null +++ b/app/src/main/res/drawable/ic_captive_portal_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_check_24px.xml b/app/src/main/res/drawable/ic_check_24px.xml new file mode 100644 index 0000000..280f0bd --- /dev/null +++ b/app/src/main/res/drawable/ic_check_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_check_circle_24px.xml b/app/src/main/res/drawable/ic_check_circle_24px.xml new file mode 100644 index 0000000..728be3b --- /dev/null +++ b/app/src/main/res/drawable/ic_check_circle_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_checklist_24px.xml b/app/src/main/res/drawable/ic_checklist_24px.xml new file mode 100644 index 0000000..28c2be7 --- /dev/null +++ b/app/src/main/res/drawable/ic_checklist_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_close_24px.xml b/app/src/main/res/drawable/ic_close_24px.xml new file mode 100644 index 0000000..7a0ff35 --- /dev/null +++ b/app/src/main/res/drawable/ic_close_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_download_24px.xml b/app/src/main/res/drawable/ic_download_24px.xml new file mode 100644 index 0000000..dba4601 --- /dev/null +++ b/app/src/main/res/drawable/ic_download_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml index 068a3c6..239cfed 100644 --- a/app/src/main/res/drawable/ic_launcher_foreground.xml +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -1,14 +1,14 @@ - + android:viewportWidth="137" + android:viewportHeight="130"> + diff --git a/app/src/main/res/drawable/ic_launcher_monochrome.xml b/app/src/main/res/drawable/ic_launcher_monochrome.xml new file mode 100644 index 0000000..15794c1 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_link_24px.xml b/app/src/main/res/drawable/ic_link_24px.xml new file mode 100644 index 0000000..e8af9e1 --- /dev/null +++ b/app/src/main/res/drawable/ic_link_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_mobile_24px.xml b/app/src/main/res/drawable/ic_mobile_24px.xml new file mode 100644 index 0000000..0f49a21 --- /dev/null +++ b/app/src/main/res/drawable/ic_mobile_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_open_in_browser_24px.xml b/app/src/main/res/drawable/ic_open_in_browser_24px.xml new file mode 100644 index 0000000..40fcc74 --- /dev/null +++ b/app/src/main/res/drawable/ic_open_in_browser_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_refresh_24px.xml b/app/src/main/res/drawable/ic_refresh_24px.xml new file mode 100644 index 0000000..f4302a5 --- /dev/null +++ b/app/src/main/res/drawable/ic_refresh_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_search_24px.xml b/app/src/main/res/drawable/ic_search_24px.xml new file mode 100644 index 0000000..390774b --- /dev/null +++ b/app/src/main/res/drawable/ic_search_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_security_24px.xml b/app/src/main/res/drawable/ic_security_24px.xml new file mode 100644 index 0000000..b21a4aa --- /dev/null +++ b/app/src/main/res/drawable/ic_security_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings_24px.xml b/app/src/main/res/drawable/ic_settings_24px.xml new file mode 100644 index 0000000..4bcd4aa --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_star_24px.xml b/app/src/main/res/drawable/ic_star_24px.xml new file mode 100644 index 0000000..0a592a4 --- /dev/null +++ b/app/src/main/res/drawable/ic_star_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_star_filled_24px.xml b/app/src/main/res/drawable/ic_star_filled_24px.xml new file mode 100644 index 0000000..99b100a --- /dev/null +++ b/app/src/main/res/drawable/ic_star_filled_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_supervised_user_circle_24px.xml b/app/src/main/res/drawable/ic_supervised_user_circle_24px.xml new file mode 100644 index 0000000..f1fede5 --- /dev/null +++ b/app/src/main/res/drawable/ic_supervised_user_circle_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_thumb_down_24px.xml b/app/src/main/res/drawable/ic_thumb_down_24px.xml new file mode 100644 index 0000000..f31531e --- /dev/null +++ b/app/src/main/res/drawable/ic_thumb_down_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_thumb_up_24px.xml b/app/src/main/res/drawable/ic_thumb_up_24px.xml new file mode 100644 index 0000000..2d66139 --- /dev/null +++ b/app/src/main/res/drawable/ic_thumb_up_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_tv_24px.xml b/app/src/main/res/drawable/ic_tv_24px.xml new file mode 100644 index 0000000..15fc7be --- /dev/null +++ b/app/src/main/res/drawable/ic_tv_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_tv_gen_24px.xml b/app/src/main/res/drawable/ic_tv_gen_24px.xml new file mode 100644 index 0000000..0ba1061 --- /dev/null +++ b/app/src/main/res/drawable/ic_tv_gen_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_update_24px.xml b/app/src/main/res/drawable/ic_update_24px.xml new file mode 100644 index 0000000..ebbdc22 --- /dev/null +++ b/app/src/main/res/drawable/ic_update_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_upload_file_24px.xml b/app/src/main/res/drawable/ic_upload_file_24px.xml new file mode 100644 index 0000000..7f7df0f --- /dev/null +++ b/app/src/main/res/drawable/ic_upload_file_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_warning_24px.xml b/app/src/main/res/drawable/ic_warning_24px.xml new file mode 100644 index 0000000..3e981e7 --- /dev/null +++ b/app/src/main/res/drawable/ic_warning_24px.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml index 50ec886..04091bd 100644 --- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -2,5 +2,5 @@ - + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml index 50ec886..04091bd 100644 --- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -2,5 +2,5 @@ - + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp index 2af4a43..1424eb6 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp index e883ea3..73244a6 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp index 706e6a4..9e24140 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp index a053d4c..7bbd886 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp index b8f9066..495ec0c 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp index c4d13f3..46033b0 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp index fa14656..f300bf0 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp index 8a53082..1e5938b 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp index 929a3a1..fc81277 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp index 54aa9de..9af7294 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index a4262c4..43e6f88 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -1,7 +1,8 @@ + OpenStore About app safety Error: %1$s - Provided by %1$s + App from %1$s Not compatible with your device Installing… Downloading…%1$s @@ -17,7 +18,7 @@ Search No reviews yet Reviews - Domains not verified + Open links in the app App deleted App installed Unable to uninstall @@ -31,4 +32,47 @@ Useful Positive Negative + Download has started + File downloaded incorrectly + Checksum does not match. Retry download or install file as is. + Show hashes + Expected hash: %1$s + Actual hash: %1$s + Download again + Install as is + Nothing found + Settings + Installer + If there are problems installing applications + Tracked sources + Updates will be checked for applications from selected sources + Check all applications + Do not limit the update check to selected sources. RuStore will get access to the entire list of applications on device + Save + Updates + Check for updates + Checking for updates… + All apps are up to date + Available updates: %1$d + Tap to check for updates + Exclude Google Play + Open settings + Applications checked: %1$d + Installation via intent, go back to the page after installation + The assembly is in progress .apks file, installation is possible only with a custom installer… + Color scheme (restart required) + Aurora Store + File Managers + Browsers + Installed from another source + Manual Installed + Unknown (ADB/Other) + Provided by developer + Mobile + TV + Auto + Dark + Light + Back + Apps for platfom \ No newline at end of file diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..45af79c --- /dev/null +++ b/app/src/main/res/values-night/themes.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/values/attrs.xml b/app/src/main/res/values/attrs.xml new file mode 100644 index 0000000..6674408 --- /dev/null +++ b/app/src/main/res/values/attrs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml deleted file mode 100644 index f8c6127..0000000 --- a/app/src/main/res/values/colors.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - #FFBB86FC - #FF6200EE - #FF3700B3 - #FF03DAC5 - #FF018786 - #FF000000 - #FFFFFFFF - \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a214303..cc0eee6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2,7 +2,8 @@ OpenStore О безопасности приложений Ошибка: %1$s - Предоставлено %1$s + Предоставлено разработчиком + Приложение из %1$s Не поддерживается на этом устройстве Установка… Загрузка…%1$s @@ -18,7 +19,7 @@ Поиск Отзывов пока нет Отзывы - Домены не подтверждены + Открывать ссылки в приложении Удалено Установлено Не удалось удалить @@ -32,4 +33,60 @@ Полезные Позитивные Негативные + Загрузка началась + Файл скачан некорректно + Контрольная сумма не совпадает. Повторите загрузку или установите файл как есть. + Показать хеши + Ожидаемый хеш: %1$s + Фактический хеш: %1$s + Скачать по новой + Установить как есть + Ничего не найдено + Настройки + Установщик + Если есть проблемы при установке приложений + Отслеживаемые источники + Проверять все приложения + Не ограничивать проверку обновлений выбранными источниками. RuStore получит доступ ко всему списку приложений на устройстве + Сохранить + Обновления + Проверить обновления + Проверка обновлений… + Все приложения обновлены + Доступно обновлений: %1$d + Нажмите для проверки обновлений + Исключить Google Play + Открыть настройки + Проверяется приложений: %1$d + Установка через intent, перезайдите на страницу после установки + Выполняется сборка .apks файла, установка возможно только кастомным установщиком… + Тема (необходим перезапуск) + Aurora Store + Файловые менеджеры + Браузеры + Установлено вручную + Неизвестно (ADB/Другое) + Установлено из другого источника + Телефон + ТВ + Системная + Тёмная + Светлая + Обновления будут проверяться для приложений из выбранных источников + Назад + Приложения для платформы + Скопировать ссылку на apk + Скачать apk без установки + Открыть страницу приложения в браузере + Вес приложения + Текущая версия + Последнее обновление + Минимальная версия android + Тип установочного файла + Количество установок + Возрастная категория + Рейтинг и отзывы\nСредняя оценка: %1$.2f\nВсего оценок: %2$d + оценка: %1$d + Лайки + Дизлайки \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index 23c8862..6872e24 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,5 +1,3 @@ - - -