diff --git a/.github/workflows/build-addons.yml b/.github/workflows/build-addons.yml index eb43a12d0..8642eb9c6 100644 --- a/.github/workflows/build-addons.yml +++ b/.github/workflows/build-addons.yml @@ -29,6 +29,29 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 45 steps: + # Every prerequisite is checked here, first, and all failures are reported + # together, so a missing secret fails the run in seconds, not after the build. + - name: Pre-flight checks + env: + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} + run: | + failed=0 + # Share Your Apps Server's release key (scripts/server-signing-key.sh). + for v in SERVER_SIGNING_KEYSTORE_BASE64 SERVER_SIGNING_STORE_PASSWORD SERVER_SIGNING_KEY_ALIAS SERVER_SIGNING_KEY_PASSWORD; do + if [ -z "${!v}" ]; then + echo "::error::Repository secret $v is missing or empty. See The release signing key in plugins/Share-Your-Apps/docs/share-your-apps-design.md." + failed=1 + fi + done + if [ "$failed" != 0 ]; then + echo "Pre-flight checks failed; see the errors above." >&2 + exit 1 + fi + echo "Pre-flight checks passed." + - name: Checkout plugin-examples uses: actions/checkout@v4 @@ -47,6 +70,14 @@ jobs: cache-disabled: true add-job-summary: 'never' + - name: Put Share Your Apps Server's release key in place + env: + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} + run: ./scripts/server-signing-key.sh + - name: Refresh libs and build plugins env: CODEONTHEGO_REF: ${{ inputs.codeonthego_ref }} diff --git a/.github/workflows/publish-addons.yml b/.github/workflows/publish-addons.yml index 184fd6c0c..844e8a603 100644 --- a/.github/workflows/publish-addons.yml +++ b/.github/workflows/publish-addons.yml @@ -20,33 +20,51 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '17' - - - uses: gradle/actions/setup-gradle@v4 - - - uses: astral-sh/setup-uv@v5 - - - name: Verify the R2 configuration - # The build below takes a long time. Without this, a renamed variable - # is only discovered after all of it, inside boto3. + # Every prerequisite is checked here, first, and all failures are reported + # together, so a missing secret fails the run in seconds, not after the build. + - name: Pre-flight checks env: R2_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_ACCESS_KEY_ID }} R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_SECRET_ACCESS_KEY }} R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET_NAME }} + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} run: | + failed=0 + # Share Your Apps Server's release key (scripts/server-signing-key.sh). + for v in SERVER_SIGNING_KEYSTORE_BASE64 SERVER_SIGNING_STORE_PASSWORD SERVER_SIGNING_KEY_ALIAS SERVER_SIGNING_KEY_PASSWORD; do + if [ -z "${!v}" ]; then + echo "::error::Repository secret $v is missing or empty. See The release signing key in plugins/Share-Your-Apps/docs/share-your-apps-design.md." + failed=1 + fi + done + # Cloudflare R2, for the publish at the end. Without this, a renamed + # variable is only discovered after the whole build, inside boto3. for v in R2_ACCOUNT_ID R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY R2_BUCKET; do if [ -z "${!v}" ]; then - echo "$v is empty. Check the repository secrets and variables." >&2 - exit 1 + echo "::error::$v is empty. Check the repository secrets and variables." + failed=1 fi done - echo "Publishing to bucket '$R2_BUCKET'." + if [ "$failed" != 0 ]; then + echo "Pre-flight checks failed; see the errors above." >&2 + exit 1 + fi + echo "Pre-flight checks passed. Publishing to bucket '$R2_BUCKET'." + + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@v4 + + - uses: astral-sh/setup-uv@v5 - name: Check names and metadata run: uv run --directory tools/addons addons --root "$GITHUB_WORKSPACE" check @@ -79,6 +97,14 @@ jobs: echo "revision=$revision" >> "$GITHUB_OUTPUT" echo "Building against $COGO_REPO@$revision ($COGO_RELEASE)." >> "$GITHUB_STEP_SUMMARY" + - name: Put Share Your Apps Server's release key in place + env: + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} + run: ./scripts/server-signing-key.sh + - name: Build, package, and stage id: stage env: diff --git a/.github/workflows/update-libs.yml b/.github/workflows/update-libs.yml index f86a9eaf9..53a7c2cb3 100644 --- a/.github/workflows/update-libs.yml +++ b/.github/workflows/update-libs.yml @@ -11,44 +11,57 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 45 steps: - - name: Checkout plugin-examples - uses: actions/checkout@v4 - with: - # PAT from a repo admin so the libs/ push bypasses the main ruleset. - # A fine-grained PAT must use the organization as its resource owner, - # not a personal account, or every push returns 403. The next step - # checks this. GITHUB_TOKEN is only a fallback to keep checkout - # working; it cannot bypass the ruleset, so the check rejects it. - token: ${{ secrets.ADMIN_PERSONAL_ACCESS_TOKEN || github.token }} - - # The build below takes ~30 minutes. Without this guard, a token that - # cannot write to this repo throws all of that away at "Commit updated - # jars". Check the token first so the run fails in seconds instead. - - name: Verify the push token + # Every prerequisite is checked here, first, and all failures are reported + # together, so a missing secret fails the run in seconds, not after the build. + - name: Pre-flight checks env: - ADMIN_PAT: ${{ secrets.ADMIN_PERSONAL_ACCESS_TOKEN }} - GH_TOKEN: ${{ secrets.ADMIN_PERSONAL_ACCESS_TOKEN || github.token }} + GH_TOKEN: ${{ secrets.ADMIN_PERSONAL_ACCESS_TOKEN }} + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} run: | + failed=0 + # Share Your Apps Server's release key (scripts/server-signing-key.sh). + for v in SERVER_SIGNING_KEYSTORE_BASE64 SERVER_SIGNING_STORE_PASSWORD SERVER_SIGNING_KEY_ALIAS SERVER_SIGNING_KEY_PASSWORD; do + if [ -z "${!v}" ]; then + echo "::error::Repository secret $v is missing or empty. See The release signing key in plugins/Share-Your-Apps/docs/share-your-apps-design.md." + failed=1 + fi + done + # The push token. The build takes ~30 minutes; without this, a token that + # cannot write to this repo throws all of that away at "Commit updated jars". org="${GITHUB_REPOSITORY%%/*}" - - if [ -z "$ADMIN_PAT" ]; then + if [ -z "$GH_TOKEN" ]; then echo "::error::ADMIN_PERSONAL_ACCESS_TOKEN is not set. GITHUB_TOKEN cannot bypass the ${org} main ruleset, so the push would fail." - exit 1 - fi - - if ! repo=$(gh api "repos/${GITHUB_REPOSITORY}" 2>/dev/null); then + failed=1 + elif ! repo=$(gh api "repos/${GITHUB_REPOSITORY}" 2>/dev/null); then echo "::error::The token cannot see ${GITHUB_REPOSITORY}. A fine-grained PAT must use resource owner '${org}' (the organization). A token owned by a personal account cannot reach ${org} repositories." - exit 1 + failed=1 + else + who=$(gh api user --jq .login 2>/dev/null || echo '(unknown)') + push=$(printf '%s' "$repo" | jq -r '.permissions.push // false') + echo "Token identity: ${who}. Push permission: ${push}." + if [ "$push" != "true" ]; then + echo "::error::The token authenticates as '${who}' but cannot write to ${GITHUB_REPOSITORY}. Grant it 'Contents: Read and write' with resource owner '${org}'." + failed=1 + fi fi - - who=$(gh api user --jq .login 2>/dev/null || echo '(unknown)') - push=$(printf '%s' "$repo" | jq -r '.permissions.push // false') - echo "Token identity: ${who}. Push permission: ${push}." - - if [ "$push" != "true" ]; then - echo "::error::The token authenticates as '${who}' but cannot write to ${GITHUB_REPOSITORY}. Grant it 'Contents: Read and write' with resource owner '${org}'." + if [ "$failed" != 0 ]; then + echo "Pre-flight checks failed; see the errors above." >&2 exit 1 fi + echo "Pre-flight checks passed." + + - name: Checkout plugin-examples + uses: actions/checkout@v4 + with: + # PAT from a repo admin so the libs/ push bypasses the main ruleset. + # A fine-grained PAT must use the organization as its resource owner, + # not a personal account, or every push returns 403. Pre-flight + # checks this. GITHUB_TOKEN is only a fallback to keep checkout + # working; it cannot bypass the ruleset, so the check rejects it. + token: ${{ secrets.ADMIN_PERSONAL_ACCESS_TOKEN || github.token }} - name: Set up JDK 17 uses: actions/setup-java@v4 @@ -71,6 +84,14 @@ jobs: RUN_NUMBER: ${{ github.run_number }} run: echo "name=build-$(date -u +%Y-%m-%d)-${RUN_NUMBER}" >> "$GITHUB_OUTPUT" + - name: Put Share Your Apps Server's release key in place + env: + SERVER_SIGNING_KEYSTORE_BASE64: ${{ secrets.SERVER_SIGNING_KEYSTORE_BASE64 }} + SERVER_SIGNING_STORE_PASSWORD: ${{ secrets.SERVER_SIGNING_STORE_PASSWORD }} + SERVER_SIGNING_KEY_ALIAS: ${{ secrets.SERVER_SIGNING_KEY_ALIAS }} + SERVER_SIGNING_KEY_PASSWORD: ${{ secrets.SERVER_SIGNING_KEY_PASSWORD }} + run: ./scripts/server-signing-key.sh + # Refreshes libs/ from CodeOnTheGo@stage, then proves every plugin still # compiles against the new jars. Templates use no jars, so none are built. - name: Refresh libs and build plugins diff --git a/plugins/Share-Your-Apps/.gitignore b/plugins/Share-Your-Apps/.gitignore new file mode 100644 index 000000000..ecfb7b0c7 --- /dev/null +++ b/plugins/Share-Your-Apps/.gitignore @@ -0,0 +1,35 @@ +# Build output and caches +build/ +.gradle/ +.kotlin/ +.cxx/ +.externalNativeBuild/ +captures/ +*.hprof + +# IDE and editor state (.cg is CodeOnTheGo's) +.cg/ +.idea/ +*.iml +.DS_Store +Thumbs.db + +# Machine-specific settings +local.properties + +# Signing: the keystore and its passwords must never be committed +release.keystore +release.properties +keystore.properties +*.jks +*.keystore +*.p12 +*.pfx + +# The bundled server APK is a build output, copied in before each release (see README) +src/main/assets/share-your-apps-server.apk + +# Media (demo video, narration recordings) is kept out of git +*.webm +*.mp3 +*.mp4 diff --git a/plugins/Share-Your-Apps/LICENSE b/plugins/Share-Your-Apps/LICENSE new file mode 100644 index 000000000..0c97efd25 --- /dev/null +++ b/plugins/Share-Your-Apps/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/plugins/Share-Your-Apps/README.md b/plugins/Share-Your-Apps/README.md new file mode 100644 index 000000000..315c98d83 --- /dev/null +++ b/plugins/Share-Your-Apps/README.md @@ -0,0 +1,89 @@ +# Share Your Apps (Code On The Go plugin) + +A plugin for [Code On The Go](https://github.com/appdevforall/CodeOnTheGo) that publishes +the owner's apps (APK, source, or both) to a small web store that people on the same Wi-Fi +network or hotspot can open in their phone's browser. The store is served by the companion +**Share Your Apps Server** app, which this plugin installs and starts. + +## What it does + +- **Manage Catalog** (the Share Your Apps tab): the store's name, description, header image and + optional PIN; products with their project, APK, pictures and description; an optional + Pebble template override and extra JSON. Everything is saved as it's edited. +- **Publish** builds a complete new Store directory beside the current one: it copies the + APKs and media (inlining media of 10,240 bytes or less), zips the source without build + output, caches, IDE settings or signing files, and renders the page. It then installs the + server if needed, starts it on the new directory, checks every file is served correctly, + and deletes the old directory. If anything fails, the store keeps serving the previous + version. +- Tooltips on every heading and button (long-press). + +The full design is in the Share Your Apps design document (ADFA-6207). + +## Building + +Open the project in Code On The Go and build the plugin. `plugin.id` is +`org.appdevforall.shareyourapps`. + +The catalog page is rendered with Pebble, declared `compileOnly`: at runtime the plugin uses +Code On The Go's own copy (4.1.1), so building needs internet access once to fetch it for +compiling. + +## Bundling the server + +The plugin carries the server as `src/main/assets/share-your-apps-server.apk`. That file is a +build output, so it isn't committed. `./gradlew downloadAssets`, run as its own command before +`assemblePlugin`, builds the server's release from `server/` and copies it there. CI runs it for every +build and signs the server with its release key, from repository secrets (see *The release signing key* +in the design document). + +## Running the tests + +The tests are in `src/test/kotlin`: an end-to-end test that publishes real catalogs, serves them +with the server's own code and verifies every file, and a test of the HTML checker. Each runs a +list of named checks and, if any fail, names them. They run on a computer's Java, not on Android: + + ./gradlew testDebugUnitTest + +**On the phone,** two things differ from a computer: + +- **Start Gradle with `sh`.** Shared storage doesn't keep the executable bit, so `./gradlew` won't + run there. Use `sh ./gradlew testDebugUnitTest` instead. +- **Use CodeOnTheGo's `aapt2`.** Run from a terminal, Gradle downloads the standard `aapt2`, which + is built for Linux computers and can't run on a phone. The build then fails at + `processDebugResources` with `Syntax error: word unexpected (expecting ")")`. CodeOnTheGo + supplies its own `aapt2` to builds it starts, but not to a terminal, so pass it to Gradle: + + sh ./gradlew testDebugUnitTest -Pandroid.aapt2FromMavenOverride=/data/data/com.itsaky.androidide/files/home/android-sdk/build-tools/36.0.0/aapt2 + + That's where CodeOnTheGo keeps it, with build tools 36.0.0. If a different version of + CodeOnTheGo keeps it elsewhere, find it with + + find /data/data/com.itsaky.androidide/files -name aapt2 -type f 2>/dev/null | grep -v transforms + + and check a copy with ` version`, which should print `Android Asset Packaging Tool (aapt) 2.…`. + + Give it on the command line like this, not in `gradle.properties`: that file goes with the + project, and the setting would break the build on every computer. + +The end-to-end test needs the server's core, so `src/test/kotlin/org/appdevforall/shareyourapps/server/` +holds a **copy** of five of Share Your Apps Server's files. They're used only by the tests and never +ship in the plugin. When the server's copies of those files change, copy them here again. + +**Writing tests:** unit tests compile against Android's version of Java's library (from +`android.jar`), but run on the computer's or phone's full Java. So they may only use Java +features Android also has. Reach anything newer through reflection, as `PublishTest.kt` does for +Unix-domain sockets, or the tests won't compile under Gradle. + +## Documentation + +- [`docs/share-your-apps-design.md`](docs/share-your-apps-design.md) — the design of Share Your Apps, both the plugin and Share Your Apps Server: how everything works, its limitations and open items, developer notes for building, releasing and testing, and the store page templates. +- [`docs/qa-steps.md`](docs/qa-steps.md) — step-by-step checks for testers. +- [`docs/tester-guide/`](docs/tester-guide/) — builds the one-page tester guide PDF. +- [`docs/review-prompt.md`](docs/review-prompt.md) — a prompt for an independent review of the design. +- [`templates/`](templates/) — alternative store page templates, and an annotated copy of the default. +- [`demo/`](demo/) — a demo store of twelve apps with placeholder downloads, for testing and demonstrations. + +## License + +GNU Affero General Public License v3.0 or later. See `LICENSE`. diff --git a/plugins/Share-Your-Apps/addon.json b/plugins/Share-Your-Apps/addon.json new file mode 100644 index 000000000..29314e31e --- /dev/null +++ b/plugins/Share-Your-Apps/addon.json @@ -0,0 +1,16 @@ +{ + "summary": "Publish your apps and their source to a store on your local network.", + "description": "Turns the apps you build into a small web store that people on the same Wi-Fi network or hotspot open in their phone's browser, with no internet and no accounts. The companion Share Your Apps Server serves the store, and a store can be copied to another phone by QR code, typed code or sound.", + "tags": [ + "publishing", + "store", + "network", + "offline" + ], + "origin": "appdevforall", + "license": "AGPL-3.0-or-later", + "author": { + "name": "App Dev For All", + "url": "https://www.appdevforall.org" + } +} diff --git a/plugins/Share-Your-Apps/build.gradle.kts b/plugins/Share-Your-Apps/build.gradle.kts new file mode 100644 index 000000000..c216e1f11 --- /dev/null +++ b/plugins/Share-Your-Apps/build.gradle.kts @@ -0,0 +1,177 @@ +// Imported, since in a Gradle build file, "java" alone means Gradle's java extension, not the package. +import java.io.File +import java.util.Properties + +plugins { + id("com.android.application") + id("com.itsaky.androidide.plugins.build") +} + +pluginBuilder { + pluginName = "share-your-apps" +} + +// Release signing: the same key and details as Share Your Apps Server's, from release.properties in Code On The Go's +// private folder, which is never in the project. Without it, a release build still works, but isn't signed. +val keystorePropsFile = File("/data/data/com.itsaky.androidide/files/home/keys/release.properties") +val keystoreProps = Properties().apply { + if (keystorePropsFile.exists()) keystorePropsFile.inputStream().use { load(it) } +} +val hasValidSigningProps = listOf("storeFile", "storePassword", "keyAlias", "keyPassword").all { keystoreProps[it] != null } + +android { + namespace = "org.appdevforall.shareyourapps" + compileSdk = 36 + + defaultConfig { + applicationId = "org.appdevforall.shareyourapps" + minSdk = 28 + targetSdk = 36 + versionCode = 4 + versionName = "1.0.3" + // When this build was made, for the Share Your Apps tab's footer. Release builds use + // --no-configuration-cache, so theirs is exact; a cached debug build may show an older time. + buildConfigField("long", "BUILD_TIME", "${System.currentTimeMillis()}L") + } + + signingConfigs { + if (hasValidSigningProps) { + create("release") { + storeFile = rootProject.file(keystoreProps["storeFile"] as String) + storePassword = keystoreProps["storePassword"] as String + keyAlias = keystoreProps["keyAlias"] as String + keyPassword = keystoreProps["keyPassword"] as String + } + } + } + + buildTypes { + release { + if (hasValidSigningProps) signingConfig = signingConfigs.getByName("release") + // No R8. With AndroidX compileOnly (below), all that's left to shrink is ZXing, and R8 kept breaking + // what Code On The Go calls in ways it can't see: a NoSuchMethodError, a NullPointerException and an + // AbstractMethodError. proguard-rules.pro stays, with what those taught, in case R8 is ever turned back on. + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + // BuildConfig.VERSION_NAME gives store pages a "Made with Share Your Apps 1.0.0" line. + buildFeatures { + buildConfig = true + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + packaging { + // Compress the compiled code in the .cgp. Android's default stores it uncompressed, so apps can run it in + // place, but that made it 4.3 MB of the plugin's 4.5 MB. Code On The Go's class loader handles either. + dex { useLegacyPackaging = true } + resources { + excludes += setOf( + "META-INF/versions/9/OSGI-INF/MANIFEST.MF", + "META-INF/DEPENDENCIES", + "META-INF/LICENSE", + "META-INF/LICENSE.txt", + "META-INF/NOTICE", + "META-INF/NOTICE.txt" + ) + } + } +} + +// Every plugin file (.cgp) must carry the server: it's left out of git, so a fresh clone doesn't +// have it, and without it the plugin can't install or update the server. This guards the tasks +// that make the .cgp — assemblePluginDebug, and assemblePlugin for a release — so neither kind can be made +// without it. Compiling and running the tests don't need it. +tasks.matching { it.name.startsWith("assemblePlugin") }.configureEach { + val server = layout.projectDirectory.file("src/main/assets/share-your-apps-server.apk").asFile + doFirst { + check(server.isFile) { + "src/main/assets/share-your-apps-server.apk is missing. Run ./gradlew downloadAssets, or build Share Your " + + "Apps Server's release, copy its app/build/outputs/apk/release/app-release.apk there, and build again. " + + "See the README's Bundling the server." + } + } +} + +// Builds Share Your Apps Server's release from server/ and bundles it. scripts/build-plugins.sh runs any task named +// downloadAssets before assemblePlugin, as its own invocation, so CI makes the APK this way. In CI the server must be +// signed with its release key, from the SERVER_SIGNING_* variables: an unsigned or differently signed server can't +// update the one already on owners' phones, so the build stops instead. +tasks.register("downloadAssets") { + val serverDir = layout.projectDirectory.dir("server").asFile + val built = layout.projectDirectory.file("server/app/build/outputs/apk/release/app-release.apk").asFile + val bundled = layout.projectDirectory.file("src/main/assets/share-your-apps-server.apk").asFile + val ci = System.getenv("CI") == "true" + val signed = System.getenv("SERVER_SIGNING_STORE_FILE") != null + workingDir = serverDir + commandLine("sh", "gradlew", "--console=plain", ":app:assembleRelease") + doFirst { + check(!ci || signed) { + "SERVER_SIGNING_STORE_FILE isn't set. In CI the server is signed with its release key, from the " + + "SERVER_SIGNING_* repository secrets. See the design document's The release signing key." + } + } + doLast { built.copyTo(bundled, overwrite = true) } +} + +// The Kotlin library comes from Code On The Go at run time. AndroidX brings its own copies (Fragment depends on +// Kotlin 1.8, and older parts come with it), so they're excluded from what the plugin bundles — except for the +// unit tests, which run on a desktop and need their own. +configurations.configureEach { + if (name.endsWith("RuntimeClasspath") && !name.contains("UnitTest") && !name.contains("AndroidTest")) { + listOf("kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-stdlib-common").forEach { + exclude(group = "org.jetbrains.kotlin", module = it) + } + } +} + +dependencies { + compileOnly(files("../../libs/plugin-api.jar")) + // Pebble renders the catalog page. compileOnly: at runtime the plugin uses CodeOnTheGo's own + // copy (4.1.1, kept intact by its build), found through the plugin's parent class loader. + compileOnly("io.pebbletemplates:pebble:4.1.1") + + // QR codes for templates' qr() function (design, Appendix D.2); the same version as the server's. + implementation("com.google.zxing:core:3.5.3") + // No AppCompat or Material: the plugin uses neither — it draws its own views, in Code On The Go's screen — + // and together they made up most of the .cgp's 13.9 MB. + // Just Fragment, not fragment-ktx: the plugin uses only Fragment and Activity's result contracts. + // compileOnly: Code On The Go loads classes parent-first, so its own AndroidX (fragment 1.8.9, activity 1.10.1) + // is what runs, never a bundled copy. It has every class and method the plugin uses: Fragment, ActivityResult, + // ActivityResultCallback, ActivityResultLauncher, ActivityResultContract and StartActivityForResult. Check + // any new AndroidX use against Code On The Go's APK first: a missing one fails at run time, not in the build. + compileOnly("androidx.fragment:fragment:1.8.8") + // The Kotlin library comes from Code On The Go, as Pebble and the plugin API do, rather than being bundled. + // gradle.properties sets kotlin.stdlib.default.dependency=false, so the Kotlin build doesn't add it itself. + compileOnly("org.jetbrains.kotlin:kotlin-stdlib:2.3.21") + testImplementation("org.jetbrains.kotlin:kotlin-stdlib:2.3.21") + + // Tests (./gradlew testDebugUnitTest) run on a computer's Java, not on Android. There, Android's + // org.json is only an empty stub, and Pebble isn't provided by CodeOnTheGo, so tests bring their own. + testImplementation("junit:junit:4.13.2") + testImplementation("org.json:json:20240303") + testImplementation("io.pebbletemplates:pebble:4.1.1") +} + +tasks.wrapper { + gradleVersion = "9.6.1" + distributionType = Wrapper.DistributionType.BIN +} + +tasks.matching { + it.name.contains("checkDebugAarMetadata") || + it.name.contains("checkReleaseAarMetadata") +}.configureEach { + enabled = false +} + +kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) + } +} diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/aurora-store.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/aurora-store.apk new file mode 100644 index 000000000..50838f775 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/aurora-store.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-32-bit.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-32-bit.apk new file mode 100644 index 000000000..3a532ea3b Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-32-bit.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-64-bit.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-64-bit.apk new file mode 100644 index 000000000..1fac4439f Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/code-on-the-go-64-bit.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/davx5.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/davx5.apk new file mode 100644 index 000000000..ed1b53659 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/davx5.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/f-droid.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/f-droid.apk new file mode 100644 index 000000000..6356ead5e Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/f-droid.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/fennec.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/fennec.apk new file mode 100644 index 000000000..147a31c54 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/fennec.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-32-bit.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-32-bit.apk new file mode 100644 index 000000000..467583734 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-32-bit.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-64-bit.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-64-bit.apk new file mode 100644 index 000000000..da3b8589a Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-64-bit.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-universal.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-universal.apk new file mode 100644 index 000000000..c488baf7b Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/knowledge-to-go-universal.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/librera.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/librera.apk new file mode 100644 index 000000000..21dba9663 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/librera.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/organic-maps.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/organic-maps.apk new file mode 100644 index 000000000..e92f666a5 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/organic-maps.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/pipepipe.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/pipepipe.apk new file mode 100644 index 000000000..294f8315d Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/pipepipe.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/proton-vpn.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/proton-vpn.apk new file mode 100644 index 000000000..5c5823887 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/proton-vpn.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/termux.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/termux.apk new file mode 100644 index 000000000..0b4dbdacf Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/termux.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/thunderbird.apk b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/thunderbird.apk new file mode 100644 index 000000000..caf0ac094 Binary files /dev/null and b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/apks/thunderbird.apk differ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/aurora-store/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/aurora-store/README.md new file mode 100644 index 000000000..a235156c7 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/aurora-store/README.md @@ -0,0 +1,5 @@ +# Aurora Store — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Aurora Store's source code. + +The real app and its source: https://f-droid.org/packages/com.aurora.store/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/code-on-the-go/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/code-on-the-go/README.md new file mode 100644 index 000000000..baf9a8f3e --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/code-on-the-go/README.md @@ -0,0 +1,5 @@ +# Code on the Go — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Code on the Go's source code. + +The real app and its source: https://appdevforall.org/code-on-the-go/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/davx5/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/davx5/README.md new file mode 100644 index 000000000..6953c2b89 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/davx5/README.md @@ -0,0 +1,5 @@ +# DAVx⁵ — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't DAVx⁵'s source code. + +The real app and its source: https://f-droid.org/packages/at.bitfire.davdroid/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/f-droid/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/f-droid/README.md new file mode 100644 index 000000000..eea3f00d9 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/f-droid/README.md @@ -0,0 +1,5 @@ +# F-Droid — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't F-Droid's source code. + +The real app and its source: https://f-droid.org/packages/org.fdroid.fdroid/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/fennec/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/fennec/README.md new file mode 100644 index 000000000..32e8b36a2 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/fennec/README.md @@ -0,0 +1,5 @@ +# Fennec F-Droid — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Fennec F-Droid's source code. + +The real app and its source: https://f-droid.org/packages/org.mozilla.fennec_fdroid/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/knowledge-to-go/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/knowledge-to-go/README.md new file mode 100644 index 000000000..be51bf1a3 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/knowledge-to-go/README.md @@ -0,0 +1,5 @@ +# Knowledge to Go — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Knowledge to Go's source code. + +The real app and its source: https://appdevforall.org/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/librera/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/librera/README.md new file mode 100644 index 000000000..1a5f15fe2 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/librera/README.md @@ -0,0 +1,5 @@ +# Librera Reader — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Librera Reader's source code. + +The real app and its source: https://f-droid.org/packages/com.foobnix.pro.pdf.reader/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/organic-maps/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/organic-maps/README.md new file mode 100644 index 000000000..c6f406003 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/organic-maps/README.md @@ -0,0 +1,5 @@ +# Organic Maps — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Organic Maps's source code. + +The real app and its source: https://f-droid.org/packages/app.organicmaps/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/pipepipe/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/pipepipe/README.md new file mode 100644 index 000000000..494ae9993 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/pipepipe/README.md @@ -0,0 +1,5 @@ +# PipePipe — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't PipePipe's source code. + +The real app and its source: https://f-droid.org/packages/InfinityLoop1309.NewPipeEnhanced/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/proton-vpn/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/proton-vpn/README.md new file mode 100644 index 000000000..cf9baa05f --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/proton-vpn/README.md @@ -0,0 +1,5 @@ +# Proton VPN — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Proton VPN's source code. + +The real app and its source: https://f-droid.org/packages/ch.protonvpn.android/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/termux/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/termux/README.md new file mode 100644 index 000000000..a04309872 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/termux/README.md @@ -0,0 +1,5 @@ +# Termux — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Termux's source code. + +The real app and its source: https://f-droid.org/packages/com.termux/ diff --git a/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/thunderbird/README.md b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/thunderbird/README.md new file mode 100644 index 000000000..cc73c3a12 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/Documents/ShareYourAppsDemo/source/thunderbird/README.md @@ -0,0 +1,5 @@ +# Thunderbird — placeholder source + +This folder is a placeholder made for a Share Your Apps demo. It isn't Thunderbird's source code. + +The real app and its source: https://f-droid.org/packages/net.thunderbird.android/ diff --git a/plugins/Share-Your-Apps/demo/README.md b/plugins/Share-Your-Apps/demo/README.md new file mode 100644 index 000000000..b214d092a --- /dev/null +++ b/plugins/Share-Your-Apps/demo/README.md @@ -0,0 +1,31 @@ +# Demo store + +A catalog of the ten most downloaded apps on F-Droid, with App Dev for All's Code on the Go and Knowledge to Go, for testing and demonstrating Share Your Apps. Code on the Go is listed twice, as its 32-bit and 64-bit versions, and Knowledge to Go three times, as its 32-bit, 64-bit and universal versions, each saying which phones it's for. **Every download is a placeholder**, a tiny file that says so, and the store's description says so too. + +- `catalog.json` — the catalog: fifteen products, with pictures, descriptions and links. +- `Documents/ShareYourAppsDemo/` — the placeholder APKs and source folders the catalog points to. +- `Pictures/ShareYourAppsDemo/code-on-the-go/` — two videos for Code on the Go: a 15-second title clip with sound, made for this demo, and a Sketch to UI tutorial. +- `get-demo-pictures.sh` — fetches the other pictures onto the phone: each F-Droid app's icon and two screenshots, read fresh from its F-Droid page, and our apps' icons from their repositories. It never downloads an APK or source code. + +## Setting it up + +In Code On The Go's terminal, from this `demo` folder: + +1. Copy the placeholders and videos to the top of shared storage: + ``` + cp -r Documents Pictures /storage/emulated/0/ + ``` +2. Fetch the pictures. It should end with `All pictures fetched.`: + ``` + sh get-demo-pictures.sh + ``` +3. Install the catalog. The plugin reads its catalog when the Share Your Apps tab first opens, and writes it back when you leave the tab after a change, so do this **after a fresh start of Code On The Go, before opening the tab**: + ``` + D=~/.cg/plugins/org.appdevforall.shareyourapps/data + cp "$D/catalog.json" /storage/emulated/0/Download/catalog-backup.json + cp catalog.json "$D/catalog.json" + ``` + On older installations, `.cg` may be called `.androidide`. +4. Open the Share Your Apps tab. It should show **Top Android apps**, with fifteen products. Publish. + +To go back to your own store, restore `Download/catalog-backup.json` the same way, after a fresh start. diff --git a/plugins/Share-Your-Apps/demo/catalog.json b/plugins/Share-Your-Apps/demo/catalog.json new file mode 100644 index 000000000..7a37de9d5 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/catalog.json @@ -0,0 +1,238 @@ +{ + "storeDir": null, + "pendingDir": null, + "storeName": "Top Android apps", + "storeDescriptionHtml": "

The ten most downloaded apps on F-Droid, with App Dev for All's Code on the Go and Knowledge to Go.

This is a demo store: every download is a small placeholder, not the real app or its source. Follow each app's link to get the real one.

", + "headerImage": null, + "pin": null, + "templateOverride": null, + "extra": {}, + "products": [ + { + "name": "F-Droid", + "project": "Documents/ShareYourAppsDemo/source/f-droid", + "apk": "Documents/ShareYourAppsDemo/apks/f-droid.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/f-droid/icon.png", + "Pictures/ShareYourAppsDemo/f-droid/screenshot-1.png", + "Pictures/ShareYourAppsDemo/f-droid/screenshot-2.png" + ], + "descriptionHtml": "

The app store for free and open-source Android apps. It installs apps from F-Droid's catalogue and keeps them up to date.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 1 + }, + { + "name": "Termux", + "project": "Documents/ShareYourAppsDemo/source/termux", + "apk": "Documents/ShareYourAppsDemo/apks/termux.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/termux/icon.png", + "Pictures/ShareYourAppsDemo/termux/screenshot-1.png", + "Pictures/ShareYourAppsDemo/termux/screenshot-2.png" + ], + "descriptionHtml": "

A terminal emulator with a full Linux package collection. Run shells, editors, compilers and command-line tools on your phone.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 2 + }, + { + "name": "Aurora Store", + "project": "Documents/ShareYourAppsDemo/source/aurora-store", + "apk": "Documents/ShareYourAppsDemo/apks/aurora-store.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/aurora-store/icon.png", + "Pictures/ShareYourAppsDemo/aurora-store/screenshot-1.png", + "Pictures/ShareYourAppsDemo/aurora-store/screenshot-2.png" + ], + "descriptionHtml": "

An unofficial, open-source client for Google Play. Search for, download and update Play Store apps, with or without Google services.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 3 + }, + { + "name": "Fennec F-Droid", + "project": "Documents/ShareYourAppsDemo/source/fennec", + "apk": "Documents/ShareYourAppsDemo/apks/fennec.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/fennec/icon.png", + "Pictures/ShareYourAppsDemo/fennec/screenshot-1.png", + "Pictures/ShareYourAppsDemo/fennec/screenshot-2.png" + ], + "descriptionHtml": "

A web browser built from Firefox's source, packaged for F-Droid. Private browsing, add-ons and tracking protection.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 4 + }, + { + "name": "DAVx⁵", + "project": "Documents/ShareYourAppsDemo/source/davx5", + "apk": "Documents/ShareYourAppsDemo/apks/davx5.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/davx5/icon.png", + "Pictures/ShareYourAppsDemo/davx5/screenshot-1.png", + "Pictures/ShareYourAppsDemo/davx5/screenshot-2.png" + ], + "descriptionHtml": "

Syncs calendars, contacts and tasks with your own server over CalDAV and CardDAV, so they work in your phone's usual apps.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 5 + }, + { + "name": "Thunderbird", + "project": "Documents/ShareYourAppsDemo/source/thunderbird", + "apk": "Documents/ShareYourAppsDemo/apks/thunderbird.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/thunderbird/icon.png", + "Pictures/ShareYourAppsDemo/thunderbird/screenshot-1.png", + "Pictures/ShareYourAppsDemo/thunderbird/screenshot-2.png" + ], + "descriptionHtml": "

The open-source email app from the makers of Thunderbird for desktop. Several accounts, one inbox, and no tracking.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 6 + }, + { + "name": "Proton VPN", + "project": "Documents/ShareYourAppsDemo/source/proton-vpn", + "apk": "Documents/ShareYourAppsDemo/apks/proton-vpn.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/proton-vpn/icon.png", + "Pictures/ShareYourAppsDemo/proton-vpn/screenshot-1.png", + "Pictures/ShareYourAppsDemo/proton-vpn/screenshot-2.png" + ], + "descriptionHtml": "

A VPN from the makers of Proton Mail, with a free plan and a no-logs policy. Encrypts your connection on public Wi-Fi.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 7 + }, + { + "name": "PipePipe", + "project": "Documents/ShareYourAppsDemo/source/pipepipe", + "apk": "Documents/ShareYourAppsDemo/apks/pipepipe.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/pipepipe/icon.png", + "Pictures/ShareYourAppsDemo/pipepipe/screenshot-1.png", + "Pictures/ShareYourAppsDemo/pipepipe/screenshot-2.png" + ], + "descriptionHtml": "

A lightweight, privacy-friendly player for YouTube and other video sites, without ads or an account. It began as a fork of NewPipe.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 8 + }, + { + "name": "Organic Maps", + "project": "Documents/ShareYourAppsDemo/source/organic-maps", + "apk": "Documents/ShareYourAppsDemo/apks/organic-maps.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/organic-maps/icon.png", + "Pictures/ShareYourAppsDemo/organic-maps/screenshot-1.png", + "Pictures/ShareYourAppsDemo/organic-maps/screenshot-2.png" + ], + "descriptionHtml": "

Offline maps and navigation from OpenStreetMap data, for walking, cycling and driving, with no tracking or ads.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 9 + }, + { + "name": "Librera Reader", + "project": "Documents/ShareYourAppsDemo/source/librera", + "apk": "Documents/ShareYourAppsDemo/apks/librera.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/librera/icon.png", + "Pictures/ShareYourAppsDemo/librera/screenshot-1.png", + "Pictures/ShareYourAppsDemo/librera/screenshot-2.png" + ], + "descriptionHtml": "

A reader for ebooks and documents — PDF, EPUB, MOBI and more — with bookmarks, notes and text-to-speech.

Get it from F-Droid.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 10 + }, + { + "name": "Code on the Go (32-bit)", + "project": "Documents/ShareYourAppsDemo/source/code-on-the-go", + "apk": "Documents/ShareYourAppsDemo/apks/code-on-the-go-32-bit.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/code-on-the-go/logo.png", + "Pictures/ShareYourAppsDemo/code-on-the-go/demo.mp4", + "Pictures/ShareYourAppsDemo/code-on-the-go/sketch-to-ui-button.webm", + "Pictures/ShareYourAppsDemo/code-on-the-go/sketch-to-ui.png", + "Pictures/ShareYourAppsDemo/code-on-the-go/plugin-manager.png" + ], + "descriptionHtml": "

A complete Android development environment that runs on your phone. Write, debug and build Kotlin and Java apps with no computer and no internet.

32-bit version: for phones that run only 32-bit apps, such as many low-cost and Android Go phones. If the 64-bit version won't install, use this one.

Get it from App Dev for All.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 11 + }, + { + "name": "Code on the Go (64-bit)", + "project": "Documents/ShareYourAppsDemo/source/code-on-the-go", + "apk": "Documents/ShareYourAppsDemo/apks/code-on-the-go-64-bit.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/code-on-the-go/logo.png", + "Pictures/ShareYourAppsDemo/code-on-the-go/demo.mp4", + "Pictures/ShareYourAppsDemo/code-on-the-go/sketch-to-ui-button.webm", + "Pictures/ShareYourAppsDemo/code-on-the-go/sketch-to-ui.png", + "Pictures/ShareYourAppsDemo/code-on-the-go/plugin-manager.png" + ], + "descriptionHtml": "

A complete Android development environment that runs on your phone. Write, debug and build Kotlin and Java apps with no computer and no internet.

64-bit version: for most phones from recent years. If Android says it isn't compatible with your phone, use the 32-bit version.

Get it from App Dev for All.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 12 + }, + { + "name": "Knowledge to Go (32-bit)", + "project": "Documents/ShareYourAppsDemo/source/knowledge-to-go", + "apk": "Documents/ShareYourAppsDemo/apks/knowledge-to-go-32-bit.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/knowledge-to-go/logo.png", + "Pictures/ShareYourAppsDemo/knowledge-to-go/announcement.png" + ], + "descriptionHtml": "

Turns an Android phone into an offline library for everyone nearby: Wikipedia, books, maps, lessons and more, shared over local Wi-Fi. Built on Internet-in-a-Box.

32-bit version: for phones that run only 32-bit apps, such as many low-cost and Android Go phones. If the 64-bit version won't install, use this one.

Get it from App Dev for All.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 13 + }, + { + "name": "Knowledge to Go (64-bit)", + "project": "Documents/ShareYourAppsDemo/source/knowledge-to-go", + "apk": "Documents/ShareYourAppsDemo/apks/knowledge-to-go-64-bit.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/knowledge-to-go/logo.png", + "Pictures/ShareYourAppsDemo/knowledge-to-go/announcement.png" + ], + "descriptionHtml": "

Turns an Android phone into an offline library for everyone nearby: Wikipedia, books, maps, lessons and more, shared over local Wi-Fi. Built on Internet-in-a-Box.

64-bit version: for most phones from recent years. If Android says it isn't compatible with your phone, use the 32-bit version.

Get it from App Dev for All.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 14 + }, + { + "name": "Knowledge to Go (universal)", + "project": "Documents/ShareYourAppsDemo/source/knowledge-to-go", + "apk": "Documents/ShareYourAppsDemo/apks/knowledge-to-go-universal.apk", + "apkPublished": true, + "sourceZipPublished": true, + "carousel": [ + "Pictures/ShareYourAppsDemo/knowledge-to-go/logo.png", + "Pictures/ShareYourAppsDemo/knowledge-to-go/announcement.png" + ], + "descriptionHtml": "

Turns an Android phone into an offline library for everyone nearby: Wikipedia, books, maps, lessons and more, shared over local Wi-Fi. Built on Internet-in-a-Box.

Universal version: works on any phone, 32-bit or 64-bit, but it's a larger download.

Get it from App Dev for All.

", + "dateAdded": "2026-09-24T12:00:00Z", + "ordinal": 15 + } + ] +} diff --git a/plugins/Share-Your-Apps/demo/get-demo-pictures.sh b/plugins/Share-Your-Apps/demo/get-demo-pictures.sh new file mode 100644 index 000000000..763cbd3a2 --- /dev/null +++ b/plugins/Share-Your-Apps/demo/get-demo-pictures.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Fetches the demo catalog's pictures into Pictures/ShareYourAppsDemo: icons and screenshots +# only, from F-Droid, GitHub and appdevforall.org. It never downloads an APK or source code. +D=/storage/emulated/0/Pictures/ShareYourAppsDemo +missing=0 + +get() { # url, file + if curl -fsSL -o "$2" "$1"; then echo " ok $2"; else echo " FAIL $1"; missing=$((missing+1)); fi +} + +fdroid() { # package, folder + mkdir -p "$D/$2"; echo "$2" + page=$(curl -fsSL "https://f-droid.org/packages/$1/") || { echo " FAIL couldn't read the F-Droid page for $1"; missing=$((missing+3)); return; } + icon=$(printf '%s' "$page" | grep -o "repo/$1/en-US/icon_[^\"]*\.png" | head -1) + shots=$(printf '%s' "$page" | grep -o "repo/$1/en-US/phoneScreenshots/[^\"]*" | awk '!seen[$0]++' | head -2) + if [ -n "$icon" ]; then get "https://f-droid.org/$icon" "$D/$2/icon.png"; else echo " FAIL no icon on the page"; missing=$((missing+1)); fi + n=0; for s in $shots; do n=$((n+1)); get "https://f-droid.org/$s" "$D/$2/screenshot-$n.png"; done + while [ $n -lt 2 ]; do n=$((n+1)); echo " FAIL no screenshot $n on the page"; missing=$((missing+1)); done +} + +fdroid org.fdroid.fdroid f-droid +fdroid com.termux termux +fdroid com.aurora.store aurora-store +fdroid org.mozilla.fennec_fdroid fennec +fdroid at.bitfire.davdroid davx5 +fdroid net.thunderbird.android thunderbird +fdroid ch.protonvpn.android proton-vpn +fdroid InfinityLoop1309.NewPipeEnhanced pipepipe +fdroid app.organicmaps organic-maps +fdroid com.foobnix.pro.pdf.reader librera + +mkdir -p "$D/code-on-the-go" "$D/knowledge-to-go" +echo code-on-the-go +# The app icons come from each app's own GitHub repository, on its default branch. +get https://raw.githubusercontent.com/appdevforall/CodeOnTheGo/HEAD/app/src/main/ic_launcher-playstore.png "$D/code-on-the-go/logo.png" +get https://appdevforall.org/wp-content/uploads/2026/08/SketchToUI.png "$D/code-on-the-go/sketch-to-ui.png" +get https://appdevforall.org/wp-content/uploads/2026/08/plugin-mgr-light.png "$D/code-on-the-go/plugin-manager.png" +echo knowledge-to-go +get https://raw.githubusercontent.com/appdevforall/KnowledgeToGo/HEAD/docs/images/k2go-logo.png "$D/knowledge-to-go/logo.png" +get https://appdevforall.org/wp-content/uploads/2026/09/KnowledgeToGoPressRelease.png "$D/knowledge-to-go/announcement.png" + +if [ $missing -eq 0 ]; then echo "All pictures fetched."; else echo "$missing picture(s) missing: remove them from those products in Manage Catalog, or publishing will stop."; fi diff --git a/plugins/Share-Your-Apps/docs/qa-steps.md b/plugins/Share-Your-Apps/docs/qa-steps.md new file mode 100644 index 000000000..9008ccf1a --- /dev/null +++ b/plugins/Share-Your-Apps/docs/qa-steps.md @@ -0,0 +1,334 @@ +# Share Your Apps — QA steps + +**You'll need two phones:** + +- **Phone A, the owner's:** Android 9 or later, with Code On The Go, and one or two apps you've built, so each has an APK. +- **Phone B, a buyer's:** any Android phone with a browser and a camera. In section J, it's also a second seller: it gets Share Your Apps Server from Phone A, and needs no Code On The Go. + +Install the plugin with the tester guide attached to this ticket. For each step that fails, add a comment with the step number, what happened, a screenshot, and the logs: in Share Your Apps Server, tap **Export logs**. + +Some public and guest Wi-Fi networks stop phones reaching each other. If Phone B can't open the store on Wi-Fi, try a home network, or the hotspot tests in section F. + +## A. Install + +1. **Install the plugin.** In Code On The Go, open the **Addons Manager**. If an earlier Share Your Apps plugin is installed, uninstall it first: this one is a release build, signed with a different key, so it may be refused otherwise. Then install the `.cgp` from this ticket, and activate it. + **Expected:** a **Share Your Apps** tab appears. +2. **Open the tab.** + **Expected:** **Manage Catalog**, grouped into **Store**, **Products** and **Advanced**, with a **Publish** bar at the bottom. It's light or dark to match your phone's setting. + +## B. The catalog + +1. **Fill it in.** Enter a store name. Tap **+ Add product**, then **Choose** a project and its APK. + **Expected:** the product's card shows `Source –` and `APK ✓` with the APK's size, in green. +2. **It's kept.** Leave Code On The Go, then return to the tab. Then close Code On The Go completely and reopen it. + **Expected:** the catalog is exactly as you left it both times. +3. **Rotation and font size.** While typing in a field, rotate the phone. Then change the phone's font size and come back. + **Expected:** nothing you typed is lost. +4. **HTML warnings.** Type `bold` into the store description. + **Expected:** a red warning under the field says ` is opened but never closed`. Add `` at the end, and the warning disappears. +5. **Warnings on closed cards.** Type `oops` into a product's description, then tap the product's name to close its card. + **Expected:** the closed card shows a one-line warning about the description's HTML. +6. **Help.** Long-press a heading, such as **PIN (optional)**, then tap **+ See more**, then the button under the detail. + **Expected:** a short tooltip appears — not *n/a* — then more detail, with a button, *The store's PIN*. It opens the plugin's help page at *PIN*, with no internet needed. Long-pressing the PIN field itself still selects its text, as usual. + +7. **A product's Extra JSON.** In a product, type `{"whatsNew": "Faster", "license": "MIT", "author": "You", "website": "https://example.org"}` into **Extra JSON**. Then type something invalid, such as `{oops`. + **Expected:** while it's invalid, the note under the field says *Not valid yet*, and the last valid value is kept. Long-pressing the heading lists the four keys. + +8. **Describing a picture, and captions for a video.** On a product with a picture, tap **Describe** beside it, write what it shows, and **Save**. On one with a video, tap **Describe**, then **Choose captions file**, and pick a `.vtt` file. Publish. + **Expected:** the list shows *described* and *captions* beside them. On the store page, a screen reader — or, on a computer, the browser's inspector — gives the picture your description, not *…, picture 1 of 2*. The video offers captions, in its menu or its **CC** button. + +## C. Publishing + +1. **First publish.** Tap **Publish**. A dialog asks you to confirm, saying how many products the store will have; tap **Cancel**. Then tap **Publish** again, and **Publish** in the dialog. Allow each thing Android asks for: installing apps, **All files access**, and **Nearby devices** if you're not on Wi-Fi. + **Expected:** **Cancel** changes nothing, and nothing starts. After confirming, it ends with `Published Store_… — … files verified.` +2. **A product with nothing to download.** Add a product without choosing an APK, and publish. + **Expected:** the message ends with `Left out: has no APK chosen, and Publish the source isn't ticked.` +3. **Removing a product.** Remove a product, publish, then open the store on Phone B. + **Expected:** the product is gone from the store. +4. **Only one store folder.** In a file manager, open `CodeOnTheGoProjects`. + **Expected:** exactly one folder named `Store_` and 8 digits. + +5. **The timestamp.** Publish, and read the message under the button. Then turn on **Use 24-hour format** in Android's date and time settings, and publish again. + **Expected:** the message starts with the date and time, then a dot, then *Published*, on one line. After the switch, the time is in 24-hour form, such as `16:32:10`. + +6. **The accessible version.** Open the store. Tap **Accessible version**, at the top left. + **Expected:** a plain, large-text page with every product, and *Standard version* at its top left, leading back. + +7. **A publish that updates the server.** Install a newer plugin, as testers do with each build, and publish. + **Expected:** Android asks to update Share Your Apps Server, and the store serves again once it's done. The version line at the foot of **Manage server** shows the new version. + +8. **An unsigned APK.** Build an app with **assembleRelease** but no signing set up, so it makes `app-release-unsigned.apk`. Choose it for a product. + **Expected:** the APK picker marks it *Unsigned: buyers can't install it*. Publishing goes ahead, and its message ends with a note that the APK isn't signed, so buyers can't install it. Choose a signed build again afterwards. + +9. **Progress and timing.** Publish a store with at least one product whose source is ticked, and watch the message under the button. + **Expected:** while the store is built, it changes every half second, naming what it's doing — such as *zipping Todo App's source* — with files and bytes handled, of their totals. When it's done, the message says *Published … files verified*, as before. + +## D. A buyer on the same Wi-Fi + +Put both phones on the same Wi-Fi network. + +1. **The QR codes.** On Phone A, open **Share Your Apps Server** and tap **Show QR codes for buyers**. Enter the Wi-Fi password, then tap the keyboard's **Done** key. + **Expected:** the keyboard closes, the fields shrink to `Joining "…" · Change`, and two codes appear: one to join the network, one to open the store. +2. **Open the store.** On Phone B, scan the second code. + **Expected:** the store opens, with a red-and-cream awning across the top, a teal header, and a card for each product. With no header image set, the octopus in the header moves. +3. **Download the APK.** Tap **Download APK**, then open the download. + **Expected:** it downloads named after the product, such as `great-scott.apk`, not `app-release.apk`. The phone asks to allow the browser to install apps; allow it, and the app installs. Afterwards, turn that setting off again, in **Settings → Apps → Special app access → Install unknown apps**. On some Samsung phones, **Auto Blocker** blocks the install: turn it off, in **Settings → Security and privacy → Auto Blocker**, install, and it turns itself back on. Note in your report if your phone needed this, and its model, since these obstacles vary between phones. +4. **Download the source.** Tap **Download source**, then open the zip. + **Expected:** it opens and holds the project's files, but no `.git` folder, no `build` folders, and no keystore or `release.properties` files. +5. **Changes show straight away.** On Phone A, rename a product and publish. On Phone B, reload the store. + **Expected:** the new name appears on the first reload. +6. **Lists in descriptions.** Give a product the description `
  1. one
  2. two
`, publish, and look on Phone B. + **Expected:** the numbers sit inside the card, not past its edge. +7. **A stalled download.** Give a product a large source zip, over 50 MB. On Phone B, start **Download source**, then switch Phone B's Wi-Fi off. Straight away, open the store on a third device, or on Phone A's browser. + **Expected:** the store opens straight away. About two minutes later, Share Your Apps Server's log shows `closed a connection … that received nothing for 120 s`. +8. **A paused video.** On Phone B, play one of Code on the Go's videos, and pause it partway. Straight away, open the store on a third device, or on Phone A's browser, and download an APK. + **Expected:** the store opens and the download starts straight away, with the video still paused on Phone B. + +9. **Skipping in a video.** On Phone B, play one of Code on the Go's videos, and drag its position bar to near the end. Then pause a video for over two minutes, and play it again. + **Expected:** the video jumps to the new position, and plays from there. The paused video carries on from where it stopped, not from the beginning. + +10. **Leaving Wi-Fi.** While Phone A serves on Wi-Fi, switch its Wi-Fi off. + **Expected:** within a few seconds, Share Your Apps Server shows it stopped, because the Wi-Fi network was lost, and says to reconnect or tap Start to use a hotspot. +11. **A missing page.** On Phone B, add `f/nothing` to the end of the store's address. + **Expected:** a page saying **Not found**, with the awning and the octopus. + +12. **What buyers learn about each download.** Look under a product's buttons. + **Expected:** both buttons show a size. Under them, a line such as *Version 2.1 · Android 9 or later · For 64-bit phones*; an app with no native code says *For all phones*. A product given the Extra JSON from B shows *What's new* under its description, and *By You · License: MIT · Website* under the buttons. + +13. **The store's Extra JSON.** On Phone A, set the store's **Extra JSON** to `{"announcement": "New this week", "contact": {"name": "Your name", "email": "you@example.org"}, "accent": "#1E88E5"}`, and publish. Reload the store on Phone B. Then change the accent to `"red"`, and publish again. + **Expected:** the announcement appears above the products, the contact details at the foot of the page, with the email as a link, and the APK buttons in blue, with black or white text. `"red"` isn't a hex colour, so it's ignored, and the buttons go back to their usual colour. The accessible version shows the announcement and contact, but keeps its own colours. + +## E. PIN + +1. **Set a PIN.** On Phone A, enter a PIN such as `1234`, and publish. On Phone B, open the store in a new private tab. + **Expected:** a PIN page with the awning, the octopus and the store's name. A wrong PIN shows a red error; the right one opens the store. +2. **It remembers.** On Phone B, open the store in an ordinary tab — not a private one, which forgets everything when it closes — and enter the PIN. Close the browser, reopen it, and open the store again. + **Expected:** no PIN is asked for, for up to 24 hours. +3. **Changing the PIN.** Change the PIN on Phone A and publish. Reload the store on Phone B. + **Expected:** Phone B still gets straight in, without the new PIN. + +4. **The PIN field.** Look at the PIN field in Manage Catalog. + **Expected:** it's on one line with its label, just wide enough for six digits, with *Up to 6 digits* in the note below. + +## F. The hotspot — Phone A not on Wi-Fi + +1. **Wi-Fi Direct.** On Phone A, switch Wi-Fi **on**, but disconnect from every network. In Share Your Apps Server, tap **Start**, and allow **Nearby devices** if asked. + **Expected:** the status panel shows a network named `DIRECT-LS-…` and its password. The log shows `Wi-Fi Direct group up`. +2. **Join and shop.** Open **Show QR codes for buyers**. On Phone B, scan the first code, then the second. + **Expected:** Phone B joins the network, then the store opens. +3. **The same network every time.** Tap **Stop**, then **Start**. + **Expected:** the same name and password as before, and Phone B reconnects by itself. +4. **Buyers stay connected during a publish.** With Phone B connected, publish from Phone A. + **Expected:** Phone B stays connected, and a reload shows the new store. +5. **Tap to copy.** On the QR code screen, tap the network name, the password, then the address; then tap the copy icon to the right of the name and password. + **Expected:** each one flashes a green **Copied!**. The icon copies the name and password together, on two lines. +6. **The fallback hotspot.** Tap **Stop**, switch Wi-Fi **off**, and tap **Start**. + **Expected:** it starts anyway. The log shows `Wi-Fi Direct group failed`, then `local-only hotspot up`. The name and password differ from the Wi-Fi Direct ones. +7. **Losing the hotspot.** Tap **Stop**. Switch Wi-Fi **on** without connecting, tap **Start**, then switch Wi-Fi **off**. + **Expected:** within a second or two the server stops, saying Wi-Fi was switched off, which stopped the Wi-Fi Direct group. +8. **Changing the name and password.** In the **Wi-Fi Direct hotspot** panel, type a name after `DIRECT-LS-`, tap **Suggest a password**, then **Save name & password**. Tap **Stop**, then **Start**. + **Expected:** the limits update as you type, a name that's too long turns red, and saving explains that buyers must join again. After restarting, the new name and password are in use, and Phone B has to join again. + +9. **The phone's own Mobile hotspot.** Tap **Stop**. Switch Phone A's Wi-Fi off, turn on its **Mobile hotspot** in Settings, and join Phone B to it. Tap **Start**. + **Expected:** the status panel says *On this phone's Mobile hotspot*. On the QR code screen, enter the Mobile hotspot's name and password; the join code appears, and Phone B opens the store from the address code. Then turn the Mobile hotspot off: within about 10 seconds, the server stops, saying the phone's Mobile hotspot was turned off. + +10. **Buyers on mobile data.** With the server on a hotspot, open **Show QR codes for buyers**. + **Expected:** under the store's code, a tip says the network has no internet, and, if a buyer's phone can't open the store, to have them turn on airplane mode, then Wi-Fi, and turn airplane mode off afterwards. + +11. **Location off, on Android 9 to 12,** if you have such a phone. Turn Location off, turn Wi-Fi off, and tap **Start**. + **Expected:** the server doesn't start, and Manage Server says to turn Location on, then tap **Start**. With Location on, it starts. + +## G. Share Your Apps Server + +1. **The layout.** Open the app. + **Expected:** five raised panels: **Status**, **Server**, **When to run**, **Wi-Fi Direct hotspot** and **Logs**. +2. **Pausing with the screen.** Choose **Pause when the screen turns off**. Turn the screen off, wait a few seconds, then turn it on without unlocking. + **Expected:** the notification says the server is paused. Now unlock the phone: within a few seconds it's serving again, and the log shows `[server] resuming: the phone was unlocked`. +3. **The full log.** Tap **View logs**. Try an older file's chip, search for `gzip`, switch between **Requests** and **Status**, and pinch to zoom. + **Expected:** each works; the newest lines are at the top. +4. **Exporting logs.** Tap **Export logs**, and choose Gmail or Drive. + **Expected:** the attachments are named `share-your-apps-server-log….txt`. +5. **The log pane.** Swipe the small log pane sideways, and wait a few seconds. + **Expected:** it stays where you left it. +6. **Help.** Long-press a panel's heading, such as **Server**, or a button. Tap the underlined **+ See more**, then the button under the detail. Then long-press it again, and tap the faint **ⓘ** in the tooltip's corner. + **Expected:** a tooltip on a pale beige, with a faint ⓘ; then its detail, and a button that opens a help page at the right section; the pages, on the same beige, link to each other. **ⓘ** opens *Help data*, listing the database rows behind the tooltip. Long-pressing a text field, such as the port, still selects its text, as usual. **Help**, beside **Start** and **Stop**, opens the table of contents. + +7. **Back in help, on Android 13, 14 or 15,** if you have such a phone: open help, follow a link, then press Back. + **Expected:** Back goes back a page, rather than closing help. + +8. **Dark mode.** Switch the phone to dark mode, and open **Manage server**, **Share this store…**, **Import a store…**, **View logs**, and a tooltip and a help page. Then **Show QR codes for buyers**. + **Expected:** every screen dark, with readable text and buttons, and help on a warm dark brown — except the QR codes screen, which stays black on white, for cameras. Switch back to light mode: each screen follows. + +9. **The address, and what Start will serve.** While serving, look at the **Status** panel. + **Expected:** the address, with a copy icon on its right, which copies it — paste it somewhere to check. Long-pressing the address shows its help. The line under **Show QR codes for buyers** reads *Start will serve…*, with *Start* in a thin box. + +10. **The log size limit.** In **Logs**, enter **500**, then **0**, then **100**. + **Expected:** 500 gets a red marker and a red note naming the valid range, 0 to 100; 0 and 100 are accepted. + +11. **Tooltips near the bottom.** Long-press **Done** on **Show QR codes for buyers**, and **Cancel** on **Share this store…**; in each, tap **+ See more**. + **Expected:** each tooltip stays fully on screen — above its button if there's no room below — also after it grows. + +12. **Smaller stores.** Publish a store with at least one product whose source is ticked. Wait a minute, then, in a file manager, open `CodeOnTheGoProjects`, the `Store_…` folder, then `products` and that product's folder. Then, on Phone B, open the store, and tap **Download source** for that product. + **Expected:** the source zip is there only as `…-source.zip.gz`, with no plain `.zip` beside it. The source downloaded on Phone B is a `.zip` that opens normally, with the project's files inside. +13. **Start and Stop follow the server.** Open **Share Your Apps Server** with the server stopped. Tap **Start**, wait for the address to appear in the **Status** panel, then tap **Stop**. Then tap **Start** again, leave the app, and open it again. + **Expected:** while the server is stopped, **Status** says *Stopped*, **Start** is enabled, green, with white text, and **Stop** is disabled, with the default grey background. While it's serving, **Start** is disabled, with the default grey background, and **Stop** is enabled, red, with white text. After **Stop**, it's back to the stopped look. Reopening the app while it's serving shows **Start** disabled and **Stop** enabled. A known limit: between tapping **Start** and the address appearing, **Start** stays enabled. +14. **The button colours in both modes, and at a large font.** Look at the **Server** panel in the phone's light mode, then dark mode, with the server stopped and again while it's serving. Then set the phone's font size to its largest, and look again. + **Expected:** in both modes, the enabled and disabled buttons are easy to tell apart, and each button's text is readable. At the largest font, **Start**, **Stop** and **Help** aren't cut off, and you can reach all three. + +## H. Icons and motion + +1. **The launcher icon.** Look at Share Your Apps Server on the home screen. + **Expected:** a violet octopus at a market stall, under a red-and-cream awning. +2. **Themed icons.** Turn on themed icons. On a Samsung: **Settings → Wallpaper and style → Color palette**, then **Apply palette to app icons**. + **Expected:** the icon becomes a one-colour silhouette of the octopus, holding up two tiles. +3. **Reduced motion.** Turn on **Remove animations** in Android's accessibility settings, then reload the store on Phone B. + **Expected:** the octopus in the header stands still. + +## I. Templates + +The four alternative templates are attached to ADFA-6207 as `.peb` files. Save them to Phone A's Download folder. + +1. **Choosing a template.** In Manage Catalog, under **Advanced**, tap **Choose a template file**. + **Expected:** a browser opens in Download, showing folders and `.peb` files only. +2. **Each look.** Choose `theme-neon-arcade.peb`, publish, and open the store on Phone B. Do the same with `theme-morning-edition.peb` and `theme-aurora-deck.peb`. + **Expected:** three very different looks, each with every product, its pictures, downloads and facts, and an *Accessible version* link at the top left. +3. **Clear Access.** Choose `theme-clear-access.peb`, and publish. + **Expected:** the store itself is the large-text accessible page, with no *Accessible version* link, since it doesn't need one. +4. **With a screen reader.** On Phone B, turn on **TalkBack** in Android's accessibility settings, and open the accessible version of any store. Swipe through the page, then use TalkBack's heading navigation. + **Expected:** TalkBack reads a *Skip to the apps* link first, then each app's name as a heading. Download links say whose they are and how big, such as *Download Termux APK, 265 B*, and pictures are read as *Termux, picture 1 of 3*. +5. **Reduced motion.** With **Remove animations** on, open Neon Arcade and Aurora Deck. + **Expected:** nothing moves. +6. **Back to the default.** Tap **Load the default template**, and publish. + **Expected:** the store's usual look. + +7. **Extending the default.** Make a file `mine.peb` in Download containing just these two lines, choose it with **Choose a template file**, and publish: + ``` + {% extends "default" %} + {% block announcement %}

Welcome to the new look

{% endblock %} + ``` + **Expected:** the store looks exactly as it does with the default template, apart from the announcement line, which reads *Welcome to the new look*. +8. **A macro and an include, from the template library.** Make the folder `CodeOnTheGoProjects/ShareYourAppsTemplates`, with a file `macros.peb` containing `{% macro badge(text) %}[{{ text }}]{% endmacro %}`, and a file `note.peb` containing `

Shared nearby

`. Add these lines to `mine.peb`, choose it again, and publish: + ``` + {% import "macros" %} + {% block footer %}{{ badge('Hi') }}{% include "note" %}{{ parent() }}{% endblock %} + ``` + **Expected:** the footer starts with **[Hi]** and *Shared nearby*, followed by the usual footer. +9. **A missing template.** In `mine.peb`, change `"note"` to `"nowhere"`, choose it again, and publish. + **Expected:** the publish stops, saying *There's no template "nowhere" in CodeOnTheGoProjects/ShareYourAppsTemplates*, and the store keeps serving its previous version. Afterwards, tap **Load the default template**, and publish. + +10. **Built-in functions.** Make `mine.peb` contain just these lines, choose it, and publish: + ``` + {% extends "default" %} + {% block announcement %}
{{ plural(products|length, '# app', '# apps') }} · {{ '**Bold** and [a link](https://example.org)'|markdown }}
{% endblock %} + {% block footer %}{{ qr('https://example.org', 'Example') }}{{ parent() }}{% endblock %} + ``` + **Expected:** the announcement shows how many apps the store has, such as *3 apps*, then **Bold** and a working link. The footer starts with a QR code that a phone's camera reads as `https://example.org`. Afterwards, tap **Load the default template**, and publish. + +## J. Sharing a store with another seller + +Phone A serves its own store; Phone B becomes a second seller, serving a copy. Phone B's own browser, or a third device, is the buyer of the copy. + +1. **The share screen.** Right after publishing, on Phone A: **Share Your Apps Server** → **Manage server** → *Copies of this store* → **Share this store…** + **Expected:** it may say *Getting the store ready to share…* for a moment, then shows a QR code, a code such as `LS-FM50-ZV7G` with a copy button beside it, *This code works for one phone, for 10 more minutes*, and a smaller QR code, *No Share Your Apps Server on the other phone?* Rotating Phone A keeps the same code. The screen stays on. +2. **Copying the code.** Tap the copy button, and paste into any text field. + **Expected:** the code pastes exactly as shown. +3. **The app for Phone B.** If Phone B doesn't have Share Your Apps Server, scan the **small** QR code with its camera app, open the link, and install the download. Allow the browser to install apps if asked, and turn that off again afterwards; on some Samsung phones, turn **Auto Blocker** off first. + **Expected:** Share Your Apps Server installs. Its version line, at the foot of **Manage server**, matches Phone A's. +4. **Importing by QR code, then denying.** On Phone B, scan the **large** QR code with the camera, and open the link. + **Expected:** Share Your Apps Server's import screen opens with the code filled in, and the phone's own name. Tap **Continue**: Phone B shows four digits, and Phone A shows *Allow a copy?*, with Phone B's name and the **same** four digits. Tap **Deny** on Phone A: Phone B says the owner denied it, and nothing was imported. +5. **Importing by typed code, and allowing.** On Phone A, tap **Share again**. On Phone B: **Manage server** → **Import a store…**, type the code in lower case, and **Continue**. On Phone A, choose **In a month**, and **Allow**. + **Expected:** Phone B shows its progress, receiving the store, then *Imported …*, with its expiry date. +6. **Leaving mid-transfer.** Share again, with a store large enough to take a while. As Phone B starts receiving, press Home. + **Expected:** a notification shows the import's progress, and the import finishes. Opening it again shows *Imported …*. +7. **Cancel mid-transfer.** Share again. As Phone B starts receiving, tap **Cancel**. + **Expected:** nothing is imported, and Phone B's earlier copy, if any, is untouched. +8. **A transfer that fails, then Try again.** Share again. As Phone B starts receiving, turn its Wi-Fi off for a few seconds, then on. + **Expected:** Phone B says the import failed, with **Try again**; Phone A says the copy didn't arrive. **Try again** on Phone B finishes it. +9. **Code rules.** On a fresh share: type a wrong code on Phone B five times, then the right one. + **Expected:** the right one is refused too, and Phone A's screen says the share has ended. Share again, and wait 10 minutes without importing: the code is then refused as expired. And with Phone B importing, a third phone using the same code is refused. +10. **Over Phone A's hotspot, with mobile data on.** Turn Phone A's Wi-Fi off, so it serves on a hotspot, and share. Join the hotspot on Phone B, with its mobile data **on**, and import. + **Expected:** the import works. Its last screen warns that Phone B is on the owner's network. +11. **Serving the copy.** On Phone B, back on your ordinary Wi-Fi: tap **Serve it now**, or **Manage server** → the store's panel → **Serve this store**, after setting a PIN. Open the store as a buyer, from Phone B's **Show QR codes for buyers**. + **Expected:** the store asks for Phone B's PIN — not Phone A's — then shows the same store as Phone A's. Downloads work. +12. **The panels' captions.** Look at **Manage server**'s sharing panels on each phone. + **Expected:** on Phone A, serving: **Share this store…** enabled, and *Import a store* disabled, saying the phone is serving a store. On Phone A, after **Stop**: **Share this store…** disabled, *Start serving your store to share it*. On Phone B, serving its copy: both disabled, with *Copies can't be passed on*, and *This phone is serving a store*. Each changes as soon as the server starts or stops. +13. **Start on Phone B.** Tap **Stop**, then **Start**. + **Expected:** it serves the copy again. The Status panel says *Start will serve the imported copy of …*, with *Start* in a thin box. +14. **A QR link while serving.** With Phone B serving its copy, scan another share's QR code with its camera. + **Expected:** the import screen says *Can't import a store here*, and why. +15. **A newer copy.** On Phone B, **Stop**. On Phone A, change something in the catalog, publish, and share again. Import it on Phone B. + **Expected:** it replaces the old copy without asking, with the change, and its new expiry. +16. **Removing a copy.** On Phone B, **Remove this store**. + **Expected:** it asks first; **Keep it** changes nothing. **Remove** stops the server if it's serving the copy, and the panel disappears. +17. **Expiry by date.** Import a fresh copy, choosing **In a week**, and serve it. Turn off **Automatic date and time**, and set the date 8 days ahead. + **Expected:** within a minute, the server stops, and **Manage server** shows *A store has expired*, with no date. A download under way at that moment finishes first. Turn **Automatic date and time** back on, and tap **OK**. +18. **The clock.** Import a fresh copy with **In a week**, and another time with **Never**. Each time, turn off **Automatic date and time**, set the time 10 minutes back, then open Share Your Apps Server. The copy is checked when the app opens or while the server is serving it, not while the server is stopped and the app is closed. + **Expected:** the **In a week** copy is deleted, with exactly the same *A store has expired* notice as step 17, and nothing mentioning the clock, on screen or in **View logs**. The **Never** copy is kept. Turn **Automatic date and time** back on afterwards. +19. **Optional, with a third phone that has Code On The Go:** publishing on a phone holding a copy. On Phone A, stop serving, and import a copy from the third phone. Then publish from Code On The Go on Phone A. + **Expected:** Phone A serves its own store, not the copy, without asking. The copy's panel stays, offering **Serve this store**. + +20. **The share screen, for Phone B.** On Phone A's share screen, read each line, then look under the small QR code. + **Expected:** each line makes clear whether it means *this phone* or *the other phone*. Under the small code, *Or open this link in the other phone's browser:*, the whole link — on two lines if it doesn't fit on one — and a copy button that copies it. + +## K. Optional: checks that need a terminal + +Run these on Phone A, in Code On The Go's terminal, using the address shown in Share Your Apps Server in place of `ADDRESS`. + +1. **Compression.** A few seconds after publishing, once the server has compressed the page in the background: `curl -sI -H 'Accept-Encoding: gzip' http://ADDRESS/` + **Expected:** the headers include `Content-Encoding: gzip` and `Cache-Control: no-cache`. +2. **Without compression.** `curl -sI http://ADDRESS/` + **Expected:** no `Content-Encoding` header. +3. **The hotspot address.** While the server runs on a hotspot, `curl -s http://ADDRESS/ | head -c 200` + **Expected:** the start of the store's page. + +4. **A catalog replaced by hand.** With the Share Your Apps tab open, go to the terminal and copy another catalog over the plugin's — for example, the demo's: `cp demo/catalog.json ~/.cg/plugins/org.appdevforall.shareyourapps/data/catalog.json` from the plugin project. Return to the tab. + **Expected:** the tab now shows that catalog, without restarting. If you had unsaved changes in the tab, they're kept instead, with a message saying so. Put your own catalog back the same way afterwards. + + +## L. MCP control + +New in Share Your Apps Server 1.0.48. **MCP control** lets apps on the same phone, such as an AI assistant, start and stop the server, share the store and import a store. It's off until you turn it on, only apps on that phone can reach it, and they can't change the store or approve a copy. Steps 1 to 8 need only Phone A. Steps 9 and 10 are optional and need a terminal. + +1. **Off by default.** On Phone A, open **Share Your Apps Server**, and look at the **Server** panel, below **Start**, **Stop** and **Help**. + **Expected:** a switch, **MCP control**, is off. The line under it says *Off. Turn on to let apps on this phone control the server.* **Copy token** and **New token** aren't shown, and there's no MCP notification. +2. **Turning it on asks first.** Turn the switch on. + **Expected:** a dialog, *Turn on MCP control?*, says that apps will be able to start and stop the server, share this store and import a store; that they can't change the store or approve a copy; that it also lets the app use the microphone, while receiving a handshake; and that each app needs the token. **Cancel** leaves the switch off. Turn it on again, and tap **Turn on**: the switch is on, and the line under it reads *On, at http://127.0.0.1:6176/mcp*. **Copy token** and **New token** appear, and a notification shows, with a **Turn off** button. The first time, Android then asks to allow the microphone. +3. **The microphone line.** Allow the microphone. + **Expected:** the line under the switch shows only the address. Now turn MCP control off, take the microphone permission away in Android's **Settings → Apps → Share Your Apps Server → Permissions**, turn MCP control on again, and tap **Turn on**, then **Don't allow** if asked. **Expected:** MCP control still turns on, and a second line reads *Microphone not allowed: hearing a sharing phone's tones needs a person.* Allow the microphone again afterwards. **Optional:** after you restart the phone, and before you open Share Your Apps Server, then open it, the second line may read *Microphone: works once the app is opened.* +4. **Copy token.** Tap **Copy token**, and paste into any text field. + **Expected:** a long token pastes. The token is never shown on the server screen. On Android 12 and earlier a short *Token copied* message appears; later versions show Android's own copy confirmation. +5. **New token.** Tap **New token**. + **Expected:** a dialog, *Make a new token?*, says apps using the old token will be refused until they're given the new one. **Cancel** changes nothing. Tap **New token** again, then **Copy token** and paste: the token is different from step 4's. +6. **Help.** Long-press **MCP control**, tap **+ See more**, then the button under the detail. Then long-press **Copy token**. + **Expected:** a tooltip, *Lets apps on this phone control the server, through MCP. Off until you turn it on.*; then more detail, and a button that opens the **MCP control** help page, with no internet needed. The **Copy token** tooltip begins *The password apps send to use MCP control.* +7. **The store's port can't be 6176.** Set **Port** to `6176`, and tap **Start**. + **Expected:** the **Status** panel says *Port 6176 is kept for MCP control. Choose another port, such as 6175.* The server doesn't start. Put the port back to 6175 afterwards. +8. **Turning it off.** Turn it off from the notification's **Turn off** button. Then turn it on again, and turn it off with the switch. + **Expected:** each time, the notification goes, the switch is off, the line reads *Off. Turn on to let apps on this phone control the server.*, and **Copy token** and **New token** disappear. +9. **Optional, in a terminal on Phone A: the token is required.** With MCP control on: `curl -si -X POST http://127.0.0.1:6176/mcp -H 'Content-Type: application/json' -d '{}'` + **Expected:** `HTTP/1.1 401 Unauthorized`, a `WWW-Authenticate: Bearer realm="Share Your Apps Server"` header, and a message that begins *Missing or wrong token.* With MCP control off, the same command can't connect. +10. **Optional, in a terminal on Phone B: other phones can't reach it.** With MCP control on, on Phone A: use Phone A's own network address, the numbers in the store's address before the port, in `curl -m 5 http://PHONE_A_ADDRESS:6176/mcp -H 'Content-Type: application/json' -d '{}'` + **Expected:** the connection is refused or times out, with no reply from Share Your Apps Server. Only apps on Phone A itself can reach MCP control. + +What apps can do once they have the token, such as sharing a store or importing one, is checked with the scripts in the `mcp` folder of this pack: see `mcp/README.txt`. The same scenarios are in ADFA-6207's Steps to QA. + +## M. Sound handshake + +New in Share Your Apps Server 1.0.48. Instead of scanning or typing the share code, a phone can hear it: the owner taps **Play sound**, and the other phone taps **Listen**. Sound only carries the handshake; the store itself still goes over Wi-Fi. You'll need both phones close together, with the media volume up and the room fairly quiet. + +1. **Play sound.** On Phone A, serving a published store: **Manage server** → **Share this store…**. Tap **Play sound**. + **Expected:** a short run of tones plays from Phone A, and the button reads **Stop sound**. The tones repeat, for up to 30 seconds, then stop by themselves. A line under the button, *Playing sound… (N attempts remaining)*, counts down the bursts of the code still to play, to none, as the tones end; it follows what you hear. Tap **Stop sound** during them: they stop at once, and the button reads **Play sound** again. In **View logs**, a `[sound]` line says the tones were played. Long-pressing **Play sound** shows its help. With Phone A's media volume at its minimum, tap **Play sound** again: a message says *The media volume is low: turn it up so the other phone hears the tones.* +2. **Listen asks for the microphone, and shows what it hears.** On Phone B: **Manage server** → **Import a store…** → **Listen**. If Android asks to allow the microphone, allow it. Stay quiet for a few seconds, then talk or clap near the phone. Then rotate Phone B. + **Expected:** the button reads **Stop listening**, and the screen says *Listening… Ask the owner to tap Play sound.* It counts down the seconds left, from 30, and shows a **Microphone level** meter that is empty when it's quiet and rises with any sound. The line above it reads *Nothing heard yet.* when quiet, and *Hearing something faint: hold the phones closer.* for faint sound. Android shows its microphone indicator. Rotating the phone doesn't stop listening. +3. **Importing by sound.** On Phone A, serving, open **Share this store…**. On Phone B, tap **Listen**, then straight away, on Phone A, tap **Play sound**. Keep the phones close. + **Expected:** Phone B says *Hearing the tones.*, then the import starts by itself, with Phone B's name. Phone B shows four digits, and Phone A shows *Allow a copy?* with the same four digits and Phone B's name. Tap **In a month**, then **Allow**: Phone B receives the store, then shows *Imported …*. Phone A's tones stop by themselves once Phone B connects. In **View logs**, Phone A has a `[sound]` line for the tones played, and Phone B has one for a code heard. +4. **Nothing heard, and stopping.** On Phone B, tap **Listen**, with Phone A silent. After a few seconds, tap **Stop listening**. Then tap **Listen** again, and wait for the 30 seconds to end. + **Expected:** **Stop listening** ends it at once, with *Stopped.* If you wait, listening ends by itself, with *Didn't hear the code. Hold the phones closer, ask the owner to turn up the media volume, and try again.* Nothing is imported. +5. **Microphone refused.** On Phone B, take the microphone permission away in Android's **Settings**, then tap **Listen**, and choose **Don't allow**. + **Expected:** the screen says *Without the microphone, the app can't hear the code. Scan the owner's QR code, or type the code, instead.* Typing the code, then **Continue**, still imports a store. Allow the microphone again afterwards. +6. **Over Phone A's own hotspot, Android 10 or later.** Turn Phone A's Wi-Fi on but don't join a network, so it serves on its own hotspot. Join Phone B to a different network. Tap **Share this store…** on Phone A and **Play sound**, and **Listen** on Phone B. Android asks only the first time Phone B joins a hotspot of that name, so to see the prompt again, first change the name under **Wi-Fi Direct hotspot** on Phone A: tap **Save name & password**, then **Stop** and **Start**. + **Expected:** Android asks Phone B whether to connect to Phone A's hotspot. Tap **Connect** within 30 seconds, and the import goes ahead. When it ends, Phone B leaves that hotspot. On Android 9, or if you don't tap **Connect**, Phone B shows the hotspot's name and password: join it in Wi-Fi settings, then tap **Continue**. On ordinary Wi-Fi, the tones carry the network's name and never its password: if Phone B can't find Phone A, join that network, then tap **Continue**. +7. **The hotspot's password stays out of the log.** After step 6, open **View logs** on both phones. + **Expected:** the `[sound]` lines show that a code was played or heard, and never the hotspot's password. +8. **The one-phone self-test.** On Phone B's import screen, tap **Listen** three times quickly. + **Expected:** the screen says *Self-test: playing and listening on this phone…*, plays tones and listens, then says *Self-test passed: this phone heard its own tones*, with a short note in brackets. If the media volume is at its minimum, a message first says *The media volume is low: turn it up for the self-test.*, and the self-test then fails with *Self-test failed: this phone didn't hear its own tones. Turn the media volume up and try again.* A `[sound]` line in **View logs** records the result. diff --git a/plugins/Share-Your-Apps/docs/review-prompt.md b/plugins/Share-Your-Apps/docs/review-prompt.md new file mode 100644 index 000000000..ba7d7731c --- /dev/null +++ b/plugins/Share-Your-Apps/docs/review-prompt.md @@ -0,0 +1,45 @@ +Please review the attached design document, `share-your-apps-design.md`, for **Share Your Apps**: a plugin for Code On The Go, an Android IDE that runs on phones, plus a companion Android app, **Share Your Apps Server**. Together they let a phone's owner publish the apps they've built — APKs, source, or both — to a small web store that people nearby open in their phone's browser, over the same Wi-Fi network or the owner's phone's own hotspot. + +## Where things stand + +Everything in the document is built, except Appendix D, which is only a plan. It has been tested by hand on real phones, including a second phone as a buyer, and both projects have JUnit tests that pass on a phone. The main design is with testers. **Sharing a store with another seller**, Appendix E, is newer: it's built, and tested by hand between two phones, one on Android 16, but not yet with testers. So I'm not asking for a new design. I want to know **what's wrong with this one**: things that will break, mislead someone, or cause support trouble. + +The document has the design itself, *Developer notes* near the end, and five appendices. Appendix A is the default page template. Appendix B is wireframes that came before the build; the list at its top says where the build differs. Where a wireframe and the design disagree, the design is right, so don't report those differences. Appendix C holds the other store page templates, D a plan for extending templates, and E sharing a store. + +**The cryptography of sharing has its own review,** by someone who reviews cryptographic protocols, using `share-protocol-review.md`. Please don't duplicate it: the key exchange, the check code, key derivation, the encrypted stream and the copy's signature are covered there. Everything else about sharing is in scope here — its screens, its states and failure modes, its Android behaviour, and how it fits the rest of the design. + +## Decisions not to re-argue + +These were made deliberately. Mention one only if you find a concrete consequence the document doesn't already acknowledge. + +- **Simplicity over robustness machinery.** The design was cut down on purpose from an elaborate first draft. Don't propose adding back backups, rollback schemes, sessions, or a reconciliation pass unless you can show a specific failure the current design mishandles. +- **The scope and background section's non-goals:** no payment, no accounts, no internet, no buyer tracking; buyers need only a browser. +- **The known limitations:** plain HTTP, so the PIN crosses the network unencrypted; no minimum PIN length; PIN guesses limited per address only (5 free, then a wait from 30 seconds doubling to an hour); published files in shared storage, readable by other apps on the phone; no start after the phone restarts; downloads cut off when a publish switches directories. + +- **Sharing's decisions,** in Appendix E: a copy is read-only, and served exactly as published; it can't be passed on through Share Your Apps, which isn't copy protection, and says so; each seller sets their own PIN; a phone serves one store at a time, and holds at most one copy; a phone serving its own store can't import; publishing serves the owner's own store, keeping any copy; the owner keeps no record of copies, and a copy no record of where it came from; copies expire on the owner's date, a month by default; a clock set back more than five minutes expires a copy at once, silently, looking exactly like an ordinary expiry; importing restarts the clock; plain HTTP between the phones, since the copy has its own encryption; a phone without the app can download it from the owner's share screen. + +## What to look for + +- **Correctness.** Behaviour that's described wrongly, or that can't work as described. +- **Failure modes.** What happens when a publish is interrupted, storage fills up, Android kills a process, a permission is revoked or never granted, the hotspot disappears, the port is taken, or two things happen at once. Say whether the document handles each case. +- **Android specifics.** The apps support Android 9 through 16 (API 28–36). Check the design against platform rules that have changed across those versions, such as foreground-service types and background-start limits, storage access, Wi-Fi Direct and local-only hotspot behaviour, package installation, and permission changes. **Where you're not sure what Android actually does, say so, rather than stating it as fact.** +- **Security, within the stated model.** Anything that lets someone on the same network do more than the design intends. The obvious limits are already accepted; look for ones that aren't. Examples: reading files outside the store, forging authentication, or tampering with what's published. +- **Contradictions and ambiguity.** Sections that disagree with each other, or leave a question that a developer implementing or changing the design would have to guess at. +- **Sharing a store.** What happens when a share or an import is interrupted — by rotation, leaving the screen, the process being killed, the network changing, or either phone sleeping — or two things happen at once, such as publishing while a copy is served, or importing while one is. Whether the screens tell a seller what they need, and nothing they can't act on. Whether expiry really deletes a copy in every path, and can't be sidestepped within the app, such as by clearing its data, backing it up, or reinstalling. +- **Test gaps.** Important behaviour that neither the automated tests nor the acceptance checklist covers. +- **The developer notes.** Instructions that are wrong, incomplete, or likely to trip someone up. + +## How to report + +Give at most **15 findings**, most important first. For each: + +1. **Severity:** *blocker* (it doesn't work, or it loses data or exposes something), *high*, *medium* or *low*. +2. **Where:** the section name. +3. **The problem,** in a sentence or two. +4. **A concrete scenario** showing it — the steps, or the situation in which it happens. +5. **The smallest fix,** in keeping with the design's simplicity. +6. **Confidence:** *certain*, *likely* or *unsure*, especially for claims about Android's behaviour. + +After the findings, list any **questions** where the document is ambiguous and you couldn't tell what's intended. + +Please don't rewrite the document, summarize it back, or list what looks fine. Plain prose within each finding is best, without nested bullet lists. diff --git a/plugins/Share-Your-Apps/docs/share-protocol-review.md b/plugins/Share-Your-Apps/docs/share-protocol-review.md new file mode 100644 index 000000000..861a25f88 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/share-protocol-review.md @@ -0,0 +1,158 @@ +# Share Your Apps — sharing a store: a review packet + +This is for an independent review of how **Share Your Apps Server** shares a copy of a store with another seller's phone. It's self-contained: the protocol, the threat model, where the code is, what the tests cover, and the questions we most want answered. The wider design, including the reasons behind each decision, is Appendix E of `share-your-apps-design.md`. + +## What it's for + +An owner runs a small store of Android apps from their phone, served over local Wi-Fi to buyers' browsers. With the owner's permission, a second seller nearby can take a **copy** of that store, and serve it from their own phone. The copy: + +- is served **exactly as published**, and can't be changed; +- **can't be passed on** through Share Your Apps to a third phone; +- **expires** on a date the owner chose, and is then deleted from the seller's phone. + +Both phones run the same app, Share Your Apps Server, signed with the same key. The two phones are near each other, on the same Wi-Fi network or hotspot. The owner approves each copy on their own screen, after comparing a four-digit check code with the seller's screen. + +## Threat model + +**Defended against:** + +- **Someone else on the same network,** who can watch, block, alter, replay and inject traffic between the phones, answer broadcasts, and connect to either phone. They must not be able to obtain a copy, read the copy in transit, alter it undetectably, get a copy accepted as coming from the owner, or extend a copy's expiry. +- **A phone guessing share codes,** or asking without the owner's approval. +- **A seller forwarding the copy's files** to another phone: they must be useless there. +- **A seller editing the copy's expiry,** or moving the clock back to keep a copy. +- **A copy that's damaged, cut off or malicious,** such as one naming files outside the copy's folder. + +**Not defended against, by design:** + +- **Copying what a store serves.** Anything a store serves is ordinary web content, which anyone who can open it can copy and serve with other software. +- **A modified app.** Share Your Apps Server is open source (AGPL), so a modified build can ignore any rule, such as expiry. +- **A rooted or compromised phone,** at either end. +- **Moving the clock back gradually,** five minutes at a time, to delay expiry. The rule deters; it can't prevent. +- **An owner who approves a request without comparing the check code.** + +## The protocol + +All numbers are big-endian. `||` is concatenation. Public keys are X.509 SubjectPublicKeyInfo DER, as `PublicKey.getEncoded()` returns. Strings are UTF-8. Base32 is RFC 4648, upper case, unpadded. + +### Keys + +- **The store key:** an ECDSA P-256 key pair, made once on the owner's phone, and stored in the app's private storage as files: `files/share/store-key.p8` (PKCS#8 DER) and `store-key.pub`. Not in Android Keystore. It signs every copy's description, and is the store's identity. +- **The store identity:** `base32(SHA-256(storePublicKey)[0..10])`, 16 characters. +- **One-time exchange keys:** ECDH P-256. The owner makes a new pair for each request; the seller makes a new pair for each import. + +### Share codes + +- **Made:** 8 random bytes from `SecureRandom`, each taken modulo 32 into Crockford's base32 alphabet, `0123456789ABCDEFGHJKMNPQRSTVWXYZ`. 256 is a multiple of 32, so there's no bias: 40 bits. Shown as `LS-XXXX-XXXX`. +- **Read:** case-insensitive; spaces, dashes and the `LS` prefix ignored; `O` read as `0`, `I` and `L` as `1`. +- **Limits:** a code lasts 10 minutes, serves one phone, and closes after 5 wrong codes, even to the right one. + +### Finding the owner's phone + +When the seller types a code, rather than scanning a QR code, their phone broadcasts over UDP to port 6176: + +``` +"LSD1 " || hex(SHA-256("shareyourapps-discover v1" || code)[0..16]) +``` + +where `code` is the 8 normalized characters. Only a phone showing that code answers, with `"LSH1 " || httpPort`, and the seller connects to the sender's address. A QR code holds the address itself: `shareyourapps-share://:/LS-XXXX-XXXX`. + +### The exchange + +Plain HTTP on the owner's store port, under `/share/`, which exists only while the owner's share screen is open. + +1. **Seller → owner:** `POST /share/request`, JSON: `code`; `name`, the seller's phone name, up to 40 characters; and `commitment = SHA-256("shareyourapps-commit v1" || sellerPublic)`, base64. + The owner checks the code, then replies with `request`, 15 random bytes in base32, and `ownerKey`, the owner's one-time public key, base64. A second phone using the same code, once one is under way, is refused. +2. **Seller → owner:** `POST /share/reveal`: `request` and `sellerKey`, the seller's one-time public key. The owner checks it against the commitment; a mismatch closes the share. +3. **Both** compute the **check code**: the first 4 bytes of `SHA-256("shareyourapps-check v1" || ownerPublic || sellerPublic || code)`, as an unsigned integer, modulo 10000, as four digits. The owner's screen shows it, with the seller's phone name, beside **Allow** and **Deny**; the seller's screen shows it too. +4. **Both** derive the **session key**: `HKDF-SHA256(ikm = ECDH(own private, their public), salt = code, info = "shareyourapps-share v1" || ownerPublic || sellerPublic, length = 32)`, an AES-256 key. +5. **Seller:** polls `GET /share/status?request=…` each second, until *allowed*, *denied* or *expired*. Once allowed, the reply also carries the copy's expiry. +6. **Seller:** `GET /share/copy?request=…`. The owner streams the copy, encrypted as it's written. After one complete download, the share is done, and the code is dead. **A failed download may be retried while the share is allowed,** each attempt with the same session key and a fresh nonce prefix. + +The commitment is there so neither side's key can be chosen after seeing the other's: without it, someone in the middle could try keys until the four digits matched. + +### The encrypted stream + +``` +"LSC1" || prefix (8 random bytes) || chunk* +chunk = length (4 bytes) || AES-256-GCM(plaintext up to 64 KiB) +``` + +- **Nonce:** `prefix || chunkNumber (4 bytes)`, 12 bytes, chunks numbered from 0. +- **Associated data:** `chunkNumber (4 bytes) || last (1 byte, 1 for the final chunk)`. +- **Tag:** 128 bits. +- **The final chunk** is marked *last*, and may be empty. The reader rejects a stream that ends without it, or has data after it. A chunk that fails as an ordinary chunk is tried as the last. + +### The copy + +Inside the encrypted stream: + +``` +descriptionLength (4 bytes, at most 4 MiB) || description (JSON) +|| signatureLength (4 bytes, at most 256) || signature +|| every file's bytes, in the description's order +``` + +- **The description:** `format` (1), `storeId`, `storeName`, `storeKey` (the store's public key, base64), `created`, `expires` (ISO-8601, or null for never), and `files`, each a `path` and `size`. +- **The signature:** ECDSA P-256 with SHA-256, DER, over the description's exact bytes, by the store key. +- **The seller checks:** the format; that `storeId` is the identity of `storeKey`; the signature, with `storeKey`; that every path is relative, with no empty, `.` or `..` parts and no backslashes, and resolves inside the destination; sizes; enough free space; no data beyond the files. It writes to a temporary folder, renamed into place only once the last file is saved. +- **Replacing a copy:** a copy with the same `storeId` and a later `created` replaces the old one silently; an older one, or a different store's, asks the seller first. + +### Expiry + +- **The date** is in the signed description. The seller's server deletes the copy on that date, checking once a minute while serving, and whenever the app looks at the copy. +- **The clock rule:** the server keeps the latest time the phone has shown, in `files/share/latest-time`. A clock more than five minutes behind it expires the copy at once. Importing a copy restarts it at the current time, so a clock once set too far ahead can't condemn fresh copies. +- **Deliberately silent:** a copy deleted for the clock looks exactly like one that simply expired, on screen and in the log. + +### Also on the sharing address + +`GET /share/app`, while a share is open, sends the owner's own installed APK, so a phone without the app can install it. Its authenticity rests on Android's signature check at install: a phone that already has the app accepts only an update signed with the same key. + +### Transport + +Everything is plain HTTP. The app sets `android:usesCleartextTraffic="true"`, since Android 9 and later block an app's plain HTTP otherwise, and the owner's phone has no fixed address to allow by name. So on the network, anyone can read the share code, the seller's phone name, the store's name, both one-time public keys, the request identifier, the status replies, and the copy's size. Only the copy itself is encrypted. + +## The questions we most want answered + +1. **The exchange as a whole.** Is the commitment, then the reveal, then a four-digit check code compared by eye, a sound short-authentication-string protocol here? Is anything missing, such as binding the seller's phone name, or the request identifier, into the check code? +2. **Four digits.** With the commitment, is a 1-in-10,000 match enough, given that the share closes after one request, and a code after 5 wrong guesses? +3. **The key derivation.** Are the HKDF inputs right: the share code as salt, and both public keys in `info`? Is one key for one direction sound? +4. **Retried downloads.** Several streams may share a session key, told apart by a random 64-bit nonce prefix each. Is that acceptable, or should each attempt derive its own key? +5. **The stream construction.** Numbered chunks, a *last* flag in the associated data, and trying the last flag on failure: any weakness, such as truncation at a chunk boundary, or a reordering that survives? +6. **The store's identity.** The description carries its own key, so a first import trusts whatever key arrives over the check-code-authenticated channel. Later copies must match its identity. Is that trust on first use enough? What if a seller imports a copy of a *different* store with the same name? +7. **The store key at rest,** as plain files in the app's private storage, not Android Keystore. Is that acceptable for this threat model? +8. **The discovery broadcast** carries a hash of a 40-bit code, which an attacker could brute-force offline — though the code also crosses the network in plain text a moment later. Does discovery weaken anything? What can an attacker do by answering broadcasts? +9. **Plain HTTP.** Is there anything an eavesdropper learns, or can do, beyond the list above? Is the request identifier's secrecy relied on anywhere it shouldn't be? +10. **Expiry.** Beyond the gradual clock change we accept, is there an easier way to keep a copy, within an unmodified app? For example, backing up and restoring app data, clearing it, or reinstalling. +11. **The app download,** `/share/app`: any risk in offering it over plain HTTP, given Android's signature check at install? +12. **Anything else** that lets someone on the network do more than the design intends. + +## Where it is in the code + +In Share Your Apps Server's `app/src/main/java/org/appdevforall/shareyourapps/server/`: + +| File | What's there | +|---|---| +| `ShareCrypto.kt` | Every cryptographic operation: keys, signatures, the store identity, the commitment, the check code, the session key and HKDF, and the encrypted stream (`SealedOutputStream`, `SealedInputStream`). | +| `SharePackage.kt` | The copy: its description, signing, writing, and checking and importing it all or nothing. | +| `ShareRules.kt` | Share codes, the expiry clock, the store key file, the QR link, and applying expiry (`CopyExpiry`). | +| `ShareHost.kt` | The owner's side: one share, its states, and its limits. | +| `ShareClient.kt` | The seller's side of the exchange, and the download. | +| `ShareDiscovery.kt` | The broadcast and its answer. | +| `HttpServer.kt` | The sharing address, `shareRoute` and `shareApp`, and `stopAccepting`. | +| `ServerService.kt`, `ImportJob.kt`, `HostService.kt`, `MainActivity.kt` | Where the Android app uses all of the above. | + +## What the tests cover + +The server's JUnit tests, in `app/src/test/java/ShareTest.kt`, include: + +- **Cryptography:** signatures, with a wrong key and altered data refused; the store identity; the commitment, and a substitute key failing it; both phones' check codes agreeing, and a different key changing them; both sides deriving the same session key, and a third party not; HKDF against RFC 5869's first test case. +- **The stream:** round trips from empty to 300 KB, across chunk boundaries; a flipped byte, a cut-off stream — including on a chunk boundary — extra data after the end, swapped chunks, and a wrong key, all failing. +- **The copy:** arriving identical, replacing an older one; refusing an altered description, another key claiming the store's identity, six kinds of unsafe path even when signed by the store, too little space, and a cut-off copy, each leaving nothing behind. +- **A whole share between two servers:** through a store with a PIN; downloads before approval refused; a second phone refused; denial; a key not matching its commitment; an expired code; five wrong guesses; discovery, right and wrong; the app download only while a share is open; cancelling before and during a download. +- **Expiry:** by date, the clock rule, the restart at import, the notice saying nothing about why, and downloads under way finishing while new connections are refused. + +They pass on a phone, as well as on a desktop JVM. A whole share has also been tested by hand between two phones, one on Android 16. + +## How to report + +For each finding: its **severity** (*serious*, *moderate* or *minor*); **where** it is; the **problem**; a concrete **attack or failure**; the **smallest fix**; and your **confidence**. Answers to the questions above are most welcome, even where the answer is *that's fine*. diff --git a/plugins/Share-Your-Apps/docs/share-your-apps-design.md b/plugins/Share-Your-Apps/docs/share-your-apps-design.md new file mode 100644 index 000000000..cbacd00f4 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/share-your-apps-design.md @@ -0,0 +1,2962 @@ +# Share Your Apps — Design + +A CodeOnTheGo plugin that lets an owner publish their apps (APK, source, or both) to a small web store, and a separate Android app that serves that store to other devices on the same Wi-Fi network or hotspot. No internet, no accounts, no payment. + +*Developer notes*, at the end, covers building, releasing and testing. Appendix A describes the default store page, Appendix B is the UI wireframes, and Appendix C holds the store page templates: the default, annotated and as shipped, and four alternatives. Appendix D is a plan for letting owners extend templates, and Appendix E sharing a store with another seller, by QR code, typed code or sound. If a wireframe disagrees with the design, the design wins. + +## The two pieces + +**Plugin (Manage Catalog)** — runs inside CodeOnTheGo. The owner edits the catalog and taps Publish. The plugin writes the store's files to shared storage, installs and launches the server app, then checks the server is serving the right content. + +**Share Your Apps Server** — a separate, ordinary Android app. It serves the files the plugin wrote, controls the hotspot, and shows the two QR codes buyers scan. + +Two apps are needed because a plugin can't run a long-lived server; the server app reads the plugin's output from shared storage. + +## Scope and background + +- **Not goals, by decision:** no payment, pricing or licensing; local networks only — Wi-Fi or the phone's own hotspot, never the internet; no accounts, and no tracking of buyers. **Buyers need only a browser.** Features that would need Code On The Go on the buyer's phone are out of scope, not merely deferred. +- **Deliberate simplifications:** plain HTTP, no minimum PIN length, and a PIN-guess limit per buyer's address only (see *Limitations*). +- **References:** Code On The Go is at `github.com/appdevforall/CodeOnTheGo` (working branch `stage`); its wiki has the plugin developer guide. Example plugins are at `github.com/appdevforall/plugin-examples`. The Serve screen's design follows the **Share Access** screen in KnowledgeToGo. The ticket is ADFA-6207. + +## Files + +**The server reads only files inside the Store directory**, and writes nothing there except its compressed copies. Publishing copies into it everything the store needs — APKs, source zips, carousel media, header image — so the owner is free to change or delete the originals afterward. Every path in the store (the page's links and every request) is relative to the Store directory: no absolute paths, no `..`. The launch intent names the Store directory rather than giving a path to it. + +Plugin private storage (`getPluginDataDirectory()`): + +- `catalog.json` — the whole catalog, saved shortly after every change that alters it (see *Plugin UI*). + +Shared storage, the **Store directory**, `CodeOnTheGoProjects/Store_<8 random digits>/`. **Each publish builds a new one** with new random digits, alongside the one being served; once the server has switched to the new directory, the old one is deleted. The digits only keep the name unique and clear of any project named `Store`. + +``` +Store_48291736/ + README.txt what this folder is + index.html + index.html.gz gzip copy, made by the server in the background + accessible.html the accessible version, from Clear Access (Appendix C.6), and its .gz copy + header. header image, if over 10 KB + products// + .apk the APK, named after the product + -source.zip source, uncompressed zip — until its copy is made, when it's deleted + -source.zip.gz gzip copy, made by the server in the background; afterwards, the only copy + +
` or `… failed: `. On the phone's own Mobile hotspot, `[hotspot] using the phone's own Mobile hotspot, at
`. The main process passes these to the server in the start request, so the server remains the log's only writer; lines from a hotspot attempt that failed entirely are written at the next start. +- **Start intent:** carries the Store directory's name, a random token, the PIN (or none) and the store name. The server acts on it only if `getCallingPackage()` is CodeOnTheGo (`com.itsaky.androidide`) and the name matches `Store_<8 digits>`; any other start intent is ignored. The main process then restarts the server process on that directory and, once it has bound successfully, saves the directory name, PIN and store name in the app's private preferences — never in shared storage (see *Two processes*). The directory is fixed for that run — switching means another start. A manual Start in Manage Server uses the saved values. The server doesn't start by itself after the phone restarts; the owner taps Start, or publishes again. +- **Token:** the start intent's token is passed from the main process to the new server process and held in memory for that run only — never written to disk; in the access log, its value in request lines is replaced by `-`. A request with a matching `?token=` query parameter is authenticated without a PIN; that's how the plugin's verify step reads protected files. A new start replaces the token, so an old one stops working. +- **One thread decides; a thread per response sends.** A single **main thread** reads each request and decides its response — the PIN, cookie and token checks, routing, the file, `304`s and gzip — so none of that ever runs concurrently. It writes the response's headers and any small body into memory, then hands them to a **sender thread**, which writes them, streams the file if there is one, writes the log line and closes the connection. A buyer who stops receiving — a paused video, or a phone gone out of range — so holds up only their own sender. + - **What senders share:** only their *last progress* time, which each writes and the main thread reads, and the log, whose writes — including rotation — are synchronized. Each sender owns its connection and file outright. + - **With range requests** (see the *Range rule*), a video paused past the two-minute limit resumes where it stopped: its connection closes, but the browser then asks for the rest from that point. + - **The main thread owns the list of senders,** and wakes at least once a second to tidy it: it forgets finished senders, and closes the connection of any that has sent nothing for **two minutes**, logging `[server] closed a connection from
that received nothing for 120 s`. Closing is how a sender is stopped — Java can't kill threads — since its blocked write then fails and it ends by itself. The limit only frees resources, since a stalled sender holds up nobody; without it, one would wait until TCP gave up, which can take many minutes. + - **At 16 senders,** a new request gets a small *The store is busy. Try again in a moment.* page with `Retry-After: 5`, written by the main thread, which is small enough never to block. + - **`stop()`** closes the listening sockets and sends the main thread a *stop* message; the main thread then closes every sender's connection and waits for it, so only the main thread ever touches the senders. + - `Connection: close` on every response, so a sender's job always ends with its connection, and limits on reading each request: every read within 2 seconds, and the **whole request within 5 seconds** of the main thread taking it, so neither a browser's idle preconnect nor a client sending a byte a second can hold the main thread for long. +- **`minSdk` 28 (Android 9)**, the same as CodeOnTheGo: the server only ever runs on a phone that's running CodeOnTheGo. +- **Storage access** via `MANAGE_EXTERNAL_STORAGE` on Android 11 and later (confirmed working). On Android 9 and 10, where that permission doesn't exist, via `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE`, with `requestLegacyExternalStorage` for Android 10. **On a fresh install** the server has no storage access yet, so its launch screen asks for it — the All-files access screen, or the permission dialog on 9 and 10 — and carries on with the publish once it's granted; the launch timeout only starts after that. +- **Confined to the Store directory.** Every served file is opened through one function, which resolves the requested path with `getCanonicalPath()` — following symlinks — and refuses anything not inside the Store directory's canonical path. Nothing else in the server opens files in shared storage. + +Routes: + +| Request | Response | +|---|---| +| anything, when the Store directory has no `index.html` | 503 "This store hasn't been set up yet" | +| any page or file, PIN set, not authenticated | redirect to `/pin` | +| `GET /pin`, authenticated | redirect to `/` | +| `GET /pin`, not authenticated | PIN entry page, showing `storeName` | +| `POST /pin` | correct → set the `ls_auth` cookie, redirect to `/`; wrong → PIN page with an error; after 5 wrong PINs from one address → 429 and a wait of 30 seconds, doubling with each further wrong PIN up to an hour | +| `GET /` or `/index.html` | `index.html`, or its `.gz` copy (see below) | +| `GET /f/` | the file at `` inside the Store directory, or its `.gz` copy (see below); 404 if there's no such file | +| anything else | 404 | + +**Caching:** every publish reuses the same addresses — `/` and each product's files — for new content, so everything the server serves from the Store directory carries `Cache-Control: no-cache`, making browsers check back each time rather than show an old catalog or hand out an old APK. The PIN page, the message pages and redirects carry `no-store`. Every file also carries `Last-Modified`, and a request whose `If-None-Match` matches the file's weak `ETag` — which names the store's folder, the file's time and its size — or, without one, whose `If-Modified-Since` **equals** `Last-Modified` exactly, gets `304 Not Modified` with no body. Exact, rather than *not modified since*, because on Wi-Fi Direct every store is at 192.168.49.1: a browser's cached page may be another store's, and an older store mustn't confirm it, so a reload costs almost nothing. Each publish copies its files afresh, so their times change whenever their content can have. Carousel videos in the default template don't preload, so viewing the page doesn't start a large download; their posters show what they are instead. Preloading would also cost every buyer a download for every video on the page, and a browser that has fetched a video's start usually stops reading while keeping the connection open, holding a sender until the two-minute limit. + +**Every page the server itself sends buyers uses the default store's look** (`Brand.page`), whatever template the catalog page uses: the awning, then a card on the cream ground with the animated octopus above its content. These pages are built into the server app, which never sees the catalog's template. That's the PIN page — with the store's name, the PIN field and an orange **Enter** button — and the four short message pages: *This store hasn't been set up yet* (503), *Not found* (404), *Bad request* (400) and *Method not allowed* (405). The octopus is an `` with a `data:` URI rather than inline SVG, because an inline SVG's styles apply to the whole page. + +- **Background compression.** When the server starts on a directory, a background thread gzips the pages at the Store directory's top — `index.html` and `accessible.html` — and each source zip that has no `.gz` copy yet, at maximum compression. Each is written to a temporary name (`.gz.tmp`) and renamed to `.gz` only when finished, so a partial copy is never served. A copy that isn't smaller than the original is deleted instead, so it's never served either. On running out of space or any other error, the thread deletes its temporary file and gives up; the uncompressed file keeps being served. Nothing coordinates with it: a relaunch kills the server process, taking any compression in progress with it, and the leftover temporary file is in the old directory, which the plugin deletes. +- **A source zip keeps only its `.gz` copy** (from server step 70). Once the copy is complete, the server gives it the zip's date and deletes the zip, saving most of a store's space: for Code On The Go's project, measured, 42 MB on disk instead of 138 MB for the zip and its copy, while buyers still download 42 MB. Compressing inside the zip instead, with no copy, would have kept 49 MB, with 49 MB downloads and a slower publish. Serving: `HttpServer` sends the copy as-is to a client that accepts gzip, and otherwise the zip's own bytes, decompressed on the fly — whole, or for a range, decompressed up to its start, then the slice. The size comes from gzip's own record of it, and the date is the zip's, so the ETag, Last-Modified and Content-Length are exactly what they were before the zip was deleted, and browsers' caches and resumed downloads keep working. Sharing sends a zip deleted after its listing from its copy, decompressed, and the plugin's check after publishing compares a deleted zip with its copy the same way, opening the expected file once, so its length and contents can't come from different copies. Pages keep both copies, being tiny; so does a zip of 4 GB or more, since gzip records sizes modulo 4 GB. `GzOnlyTest`'s 12 checks cover it all, against a real server. The cost: a resumed download near the end of a big zip means decompressing everything before that point, a few seconds for the largest. + - **Logged to the access log**, through the same logger as request lines (see *One logger, thread-safe*), as plain-text lines starting with `[gzip]`: + - `[gzip] started: 3 files` when the pass begins; + - `[gzip] done: products/my-todo-app/my-todo-app-source.zip 48213504 -> 21907118 bytes in 41 s` for each file; + - `[gzip] not smaller: products/my-todo-app/my-todo-app-source.zip 48213504 -> 48250112 bytes; deleted` when the copy isn't smaller; + - `[gzip] failed: products/my-todo-app/my-todo-app-source.zip: no space left on device` when it gives up on a file, with the reason; + - `[gzip] finished: 3 compressed, 0 not smaller, 0 failed` when the pass ends. + - A pass cut short by a relaunch writes no `finished` line, since the process is killed; the next run's lines follow. + - Like the hotspot lines, these follow the log's size setting. +- **Gzip rule:** if the request's `Accept-Encoding` includes `gzip` and a `.gz` copy of the requested file exists, send the `.gz` copy with `Content-Encoding: gzip`, keeping the original file's `Content-Type` and download name. Otherwise send the file itself. +- **Range rule** (RFC 9110), for skipping ahead in a video, resuming a paused one, and resuming a download: every file response says `Accept-Ranges: bytes`. A single range — `bytes=a-b`, `bytes=a-` or `bytes=-n` — gets `206 Partial Content`, with `Content-Range`, and just that slice; one running past the end is cut short. A range starting past the end gets `416 Range Not Satisfiable`, with `Content-Range: bytes */`. Anything else — several ranges, another unit, or a malformed or backwards range — is ignored, and the whole file sent with `200`, as the standard allows. With `If-Range`, the slice is sent only if the date matches the file's; otherwise the browser's copy is stale, so it gets the whole, new file. Ranges always apply to the plain file, never its `.gz` copy, whose byte positions differ. The main thread works all this out; the sender just sends the given bytes from the given offset. +- **Headers on files:** `Content-Type` from the extension (`application/vnd.android.package-archive` for `.apk`, `application/zip`, image/video/audio types) and `Content-Disposition: attachment; filename=""` for APKs and zips, so downloads keep their real names and install. +- **Authentication cookie, no sessions.** On first start the server generates a random secret and saves it in its own private preferences. A correct PIN sets cookie `ls_auth=.`, where the signature is an HMAC-SHA256 of the issue time made with the secret, with `Max-Age=86400`, `Path=/`, `HttpOnly` and `SameSite=Lax`. The server itself rejects a cookie 24 hours after it was issued, whatever the browser keeps, so a copied cookie can't be reused indefinitely. A request is authenticated by a valid, unexpired cookie (or a matching `?token=`); the server keeps no list of sessions. The cookie never contains the secret. This matters because every Wi-Fi Direct group owner has the address 192.168.49.1, so a buyer's browser sends one store's cookie to any other store at that address. Changing the PIN doesn't affect existing cookies, and they survive a server restart. +- **Access log**, Apache format plus bytes/sec. It rotates at a configurable size (default 10 MB, 0 = off), keeping **at most five files** — the current one and four older ones; the oldest is deleted at each rotation. + - **A line for every response, including downloads a buyer stopped.** Each line's size is the body bytes actually handed to the network, counted in 8 KB slices: a lower bound, accurate to 8 KB. So a download stopped partway shows a size smaller than the file's — or `-`, none, if it stopped within its first slice, which on phones with small network buffers is common. A response with no body, such as a `304`, also logs `-`, as Apache's combined format does. The line appears as soon as the server's next write fails, or at the latest when the two-minute stall limit closes the connection; how soon a phone reports a hung-up buyer varies. + - **Server start and stop lines:** `[server] serving Store_48291736 on 192.168.1.5:6175` (with ` with a PIN` when one is set) when a start succeeds; `[server] failed to start: ` when it doesn't; and `[server] stopped serving Store_48291736: ` when a serving server is stopped gracefully. The reasons are *stopped by the owner in Manage Server*, *restarting for a new publish (Store_…)*, *restarted from Manage Server (Store_…)*, *paused: the screen turned off*, *the Wi-Fi network was lost*, *the phone's Mobile hotspot was turned off*, *the app's service was stopped*, and, when a hotspot disappears on its own, *the local-only hotspot stopped*, *the Wi-Fi Direct group stopped* or *Wi-Fi was switched off, which stopped the Wi-Fi Direct group*. A stop that also turns a hotspot off adds *; hotspot turned off*. Because the main process kills the server process, it first asks the server to log the reason and close its sockets, then kills it when the server confirms, or after two seconds regardless. A crash can't log, so it leaves no stop line. + - **One logger, thread-safe.** Every line — requests, `[hotspot]`, `[gzip]` — goes through a single `synchronized` method in the server process that appends the line, flushes, and, if the file has passed the size limit, rotates. Rotation happens inside the same lock, so no write can land in a file that's being closed or renamed. Only the server process writes; the main process never touches the file directly. + - **Manage Server's log viewer** runs in the main process and only reads. After a rotation it reopens the current file, and it may briefly show a partial last line. +- **Manage Server screen:** start/stop, port, when to run (*Run always*, or *Pause when the screen turns off*), the log size limit in MB (0–100, default 10, 0 turns logging off; takes effect at the next start; anything else — empty, not a whole number, below 0 or above 100 — gets Android's red error marker on the field and a red note, such as *500 is more than 100. Enter a whole number from 0 to 100. Until then, the limit stays at 10 MB.*, checked by `LogSize.kt`, from server step 65), the Wi-Fi Direct hotspot's name and password, **Show QR codes for buyers**, **Help**, and the access log, newest lines first, refreshing every 2 seconds, with long lines scrolling sideways. The directory to serve always comes from the plugin; Start serves the last one published — or an imported copy, on a phone that holds one, as Appendix E.2 describes. The run mode is checked each time the screen turns off, so changing it applies immediately. +- **Manage Server's layout:** five raised panels — **Status** (status, address, hotspot details, *Show QR codes for buyers*, storage access, last published), **Server** (port, Start, Stop, Help, and the MCP control switch with Copy token and New token), **When to run**, **Wi-Fi Direct hotspot**, and **Logs** (size limit, the live log, View and Export, the log folder). Each has a fake 3D bevel: a face shading from white to light grey, a thin inner highlight, a darker rim along the lower right, and a soft offset shadow, on a slightly darker page. Each panel's heading carries its help. +- **Start and Stop follow the server's state.** **Start** is green and enabled only while the server is stopped; **Stop** is red and enabled only while it is serving. A disabled button has a grey fill, with greyed text (`Palette.fillOff`: `#E6E8EB` by day, `#34383D` at night), so it never looks tappable, and the colors follow the phone's light or dark mode. Known limit: between tapping **Start** and the address appearing, **Start** stays enabled, because `ServerStatus` has no *starting* state. A single button that changed from *Start* to *Stop* was rejected: a second accidental tap would stop the server without the owner noticing. +- **MCP control.** A switch in the Server panel lets apps on the same phone, such as an AI assistant, control the server through MCP, the Model Context Protocol. It is off by default, and turning it on asks first, saying what apps will be able to do. + - **What speaks MCP.** JSON-RPC 2.0 over the Streamable HTTP transport: `initialize`, `ping`, `tools/list` and `tools/call`, with every POST answered in plain JSON and never an event stream. It accepts protocol versions 2025-06-18, 2025-03-26 and 2024-11-05. + - **Where.** `http://127.0.0.1:6176/mcp`, on the loopback address only, from a listener of its own (`McpHttp`) apart from the store's HTTP server, so no other device can reach it. A foreground service in the main process (`McpService`) runs it while the switch is on and the app has been opened since the phone started; nothing starts it at boot. Its notification has a **Turn off** button. The store's own port can't be 6176: **Start** says so and doesn't start. (The share code's discovery, in E.3, uses UDP on 6176, which doesn't clash.) + - **Who may ask.** Before any request reaches the protocol, the listener checks that the peer is a loopback address, that `Host` names `127.0.0.1` or `localhost` (on any port, since `adb forward` can bring a request in on another), that `Origin`, if sent, does too, so a web page can't reach it by DNS rebinding, and that `Authorization: Bearer ` matches, compared in constant time. Failures are plain HTTP answers: 401 for a missing or wrong token, 403 for a foreign `Host` or `Origin`, 404 for another path, 405 for GET, 413 for a body over 1 MB, 415 for a body that isn't JSON, and 400 for broken JSON. At most 8 connections at once; an idle one closes after 30 seconds. + - **The token.** A random secret kept in the app's private preferences (`mcp`), never logged and never shown on screen. **Copy token** puts it on the clipboard. **New token**, after a confirmation, replaces it at once, since the listener reads it on every request, and apps with the old one are refused. + - **The tools (12).** `server_status`, `store_info`, `server_start`, `server_stop`, `share_start`, `share_status`, `share_stop`, `import_start`, `import_status`, `import_cancel`, `share_play_sound` and `import_listen`. They report, start and stop the server as **Start** and **Stop** do, open and close a share, start and cancel an import, and play or hear the sound handshake (E.8). No tool changes the store's contents, deletes a copy, changes the hotspot's settings, or approves a copy: only a person tapping **Allow** on the sharing phone can. None reports the hotspot's password, the PIN, the plugin's token or the cookie secret. When something needs a person, a tool says so, with what to do, instead of failing. + - **The microphone.** `McpService` also holds the microphone service type, so `import_listen` can hear while the app is off screen. The line under the switch says *Microphone not allowed: hearing a sharing phone's tones needs a person.* when the permission is missing; MCP control still works without it. + - **Tests and scripts.** `McpProtocolTest` (33 tests) runs the protocol without Android. The tester pack's `mcp/` folder has curl and shell scripts, with a README, that play the MCP client on a phone or, over `adb forward`, on a computer; QA steps section L covers the switch, the token and the endpoint's refusals. +- **Logs on Manage Server:** the inset log is updated only when the file has changed, keeps its sideways scroll position across updates, and pauses while text is selected. **View logs** opens the full log; **Export logs** opens Android's share sheet with every log file attached. The log folder's path is shown and can be selected with a tap; it's in the app's private storage, deliberately, since the logs record buyers' IP addresses and browsers, so other apps and file managers can't open it and exporting is how logs leave the phone. +- **Full log view** (the wireframe's FullScreenLogView): one chip per file — *Current*, then older files by age, like *2h ago* — with a line count and size; a search box (case-insensitive, over the whole file); *All*, *Requests* and *Status* filters, since the log's failures are all in its `[server]`, `[gzip]` and `[hotspot]` status lines; pinch to zoom; panning in both directions; and **Share** for the chosen file. Newest lines first. It shows at most the newest 2,000 matching lines of a file and says when there are more. +- **Sharing** goes through a read-only content provider that serves only the five log files, as `share-your-apps-server-log.txt` and `share-your-apps-server-log-1.txt` to `-4.txt`, with one read grant per share. +- **Launcher icon:** the Eight-Armed Merchant, as an Android adaptive icon (`mipmap-anydpi-v26/ls_launcher.xml` and `ls_launcher_round.xml`) with two vector layers — `drawable/ls_icon_background.xml` (the teal ground and the awning) and `ls_icon_foreground.xml` (the octopus, its tiles and the counter) — drawn on the 108-dp adaptive grid, with everything important inside the zone every launcher mask keeps. A third layer, `drawable/ls_icon_monochrome.xml`, is the **themed icon** for Android 13 and later: a one-colour silhouette the phone tints to match the wallpaper — the awning with four scallops, the octopus's head behind the counter with its eyes cut out and pupils inside, and its two raised arms holding up upright, rounded tiles — drawn inside the 66-unit circle, since themed icons are always shown cropped to it. The stripes, smile and counter tiles are left out, since they'd blur when tinted and shrunk. They have names of their own, and the manifest points at them, so the template's `ic_launcher` files can't clash with them. +- **What Start will serve** (from server step 69): the line under **Show QR codes for buyers** says *Start will serve the last store published: Store_…*, or *Start will serve the imported copy of …, below.*, with *Start* in a hairline box, in the text's own colour (`BoxSpan`), so it reads as the name of the **Start** button. +- **Manage Server's address** (from server step 68): while serving, the Status panel shows the store's address, with a copy button on its right — the same icon, size and confirmation as the Share screen's — in place of the earlier *(tap to copy)*, which wrapped onto two lines and worked differently from everywhere else. The address itself isn't selectable, since its long-press shows its help. Android 13 and later confirm a copy themselves; older versions show *Address copied*. +- **Serve screen** (**Show QR codes for buyers** on Manage Server): a full-screen page to hold up for buyers, always black on white so cameras read it, portrait on phones, keeping the screen on. Step 1 is a QR code in the standard Wi-Fi format (`WIFI:T:WPA;S:…;P:…;;`, with `\ ; , : "` escaped) to join the network; step 2 is a QR code of the store's address, with the address below it. Codes come from ZXing core 3.5.3 (`implementation("com.google.zxing:core:3.5.3")`). **On the server's own hotspot**, step 1 is made from its name and password, and both are shown as text, since buyers may have to type them. **On Wi-Fi, or the phone's own Mobile hotspot**, Android doesn't let apps read the password, so the owner may type the network's name and password. On Wi-Fi the name is pre-filled when Android allows reading it, which needs location access this app only holds on Android 12 and earlier. The password is never shown as text; the code carries it. With no password typed, only the address code is shown. These owner-facing fields come first on the screen, above the codes. **Show the join code**, or the keyboard's **Done** key on the password, closes the keyboard, generates the code, and collapses the fields to one line — *Joining "…" · Change* — so buyers see just the codes; *Change* brings the fields back. If either field is empty, it says so. The collapsed state is kept across rotation along with the password, in memory only. **Copying:** each shown value — the network name, the hotspot password and the store address — copies when tapped, flashing a green *Copied!* in its place. On a hotspot, a brace drawn to the height of the name and password lines points to a copy icon that copies both, separated by a newline. Copies that include the hotspot password are marked sensitive, which hides them from the clipboard preview on Android 13+. A typed home-network password is never copyable: it isn't shown as text, and it stays off the clipboard. It follows the server's status while it's showing: if the store stops, pauses or moves to another address or hotspot, it redraws, showing *isn't being served* rather than stale codes, and the codes return by themselves when it's serving again. A typed password survives the redraw. On a network without internet — the server's own hotspot, or the phone's Mobile hotspot — it adds a tip under the store's code: *This network has no internet. If a buyer's phone can't open the store, have them turn on airplane mode, then turn Wi-Fi back on. Remind them to turn airplane mode off afterwards.* A buyer's phone may otherwise send their browser over mobile data instead. Airplane mode, then Wi-Fi, leaves Wi-Fi the only way out, and airplane mode is the easiest switch to find on any phone, under the same name; turning off mobile data would work too, but its name and place vary by maker. +- **A typed Wi-Fi or Mobile hotspot password is never written to disk** — not to preferences, files, or `savedInstanceState`. It's kept across rotation, font-size, light/dark and screen-size changes by the framework's retained instance (`onRetainNonConfigurationInstance`, the mechanism ViewModels are built on), in memory only, and is gone when the Serve screen is closed or the process ends. Its field uses the password input type, which blocks copying, with the keyboard's personalized learning turned off. + +## Server help (three tiers) + +The server app has its own three-tier help, like CodeOnTheGo's: a one-line tooltip on long-press (Tier 1), **+ See more** for detail and a button to a help page (Tier 2), and full help pages (Tier 3). **Every** entry has all three: each has a button to its section of a page. A **Help** button next to Start and Stop opens the main page, a table of contents. + +- **Database:** `web_server_documentation.db`, bundled in the APK's assets and built by `help/build_help_db.py`, which also holds the help text. SQLite can't open a file inside the APK, so the asset is copied to the app's `databases/` directory once per app version (so an update brings new help), then only ever **opened read-only** (`SQLiteDatabase.OPEN_READONLY`). It holds 49 tooltips, each with one button, and 9 help pages — serving, hotspots, sharing, importing, imported copies, running and logs, the access log, the index, and a test page — about 26 KB of text; the file is 96 KB, because SQLite stores each of the format's ten tables in whole 4 KB pages, even tables with a single row. +- **Format:** the same tables and columns as CodeOnTheGo's `documentation.db`, read with CodeOnTheGo's own three queries (tooltip by tag and category, its buttons in order, content by path), including its chunking: a row of exactly 1 MB continues as `-1`, `-2`, and so on. Tooltips are in the category `shareyourapps_server`. Every page is stored as plain HTML — `compression = 'none'` and no template — which that format allows, so the app needs neither Brotli nor Pebble. A row declaring either is refused with a clear message rather than misread. The database includes the `x.html` test page. +- **Tier 3** pages open in an in-app WebView that answers every request itself from the database, with JavaScript off, so it can't reach the network; links between help pages work normally. +- **The tooltip.** The summary sits beside a faint **ⓘ**, and **+ See more** is a link, underlined in the app's link colour, not a button, as CodeOnTheGo shows it — with a touch area at least 48 dp tall. It reveals the detail, and the button to the page, which stays a button. +- **Help is on a pale beige, `#F5ECD7`,** in every tier: the tooltips and their *+ See more* form (`HelpUi.kt`), and the Tier 3 pages (`build_help_db.py`'s stylesheet), with the help screen's WebView beige behind them too, so nothing flashes white while a page loads. It sets help apart from the grey screens and white panels around it. Code on the pages sits on a slightly deeper beige, `#EADFC6`. Text, links and code pass the contrast standard easily: 13.5, 9.1 and 12.0 to 1, against 4.5 needed. The tooltip keeps its thin border, and the ⓘ panel, for developers, stays white. +- **The help database uses 1 KB pages,** set by `build_help_db.py`, which also vacuums it. Of every page size SQLite allows, from 512 bytes to 64 KB, that gives the smallest database once compressed in the APK, and keeps it at 55 KB on the phone, against 98 KB with SQLite's default 4 KB pages. Vacuuming alone changed nothing, since the database is built fresh. +- **Tooltips stay on screen** (from server step 65): `HelpUi` places a tooltip below its button or heading if it fits, otherwise above, otherwise on the roomier side, scrolling; it stays within the visible screen with an 8 dp margin, clamped sideways, and is placed again after **+ See more**, since it grows. Before, tooltips always opened below, so those near the bottom — **Done** on the Serve screen, **Cancel** on Share — were cut off. `HelpUi` shows the app's only popups, so this covers every screen. +- **The ⓘ panel,** *Help data*, lists the documentation database rows behind the tooltip, as CodeOnTheGo's debug popup does: the database and its version; the tooltip's row, with its id, category, tag and text lengths; its button rows, with their targets; and each linked page's content row, with its type, compression, language, size and continuation chunks. Its text can be selected, to copy into a report. It's built from what the rows are, not from CodeOnTheGo's own popup, which couldn't be read, so its layout may differ. +- **Buttons link to sections:** `sharing.html#allow`, say. The WebView keeps the part after `#` to itself, and scrolls there once the page loads from the database. +- Every heading, button, checkbox and radio button on every screen has an entry. **Text fields don't:** they keep their own long-press, for selecting, copying and pasting — a seller may well paste a share code or a Wi-Fi password — so their help is on their labels. + +## Plugin UI + +Manage Catalog, per the wireframes: store name, store description, header image, PIN, the product list, template override, extra JSON, and the Publish button with its status line. There's no Cancel: every change is saved to `catalog.json` shortly after it's made, and when the owner leaves the tab. A save is skipped when the catalog's text is identical to what was last loaded or written, so leaving without changing anything never touches the file, and an edit that's undone doesn't count. **A catalog.json changed by something else** — say, a catalog installed by hand — is noticed by its modification time and size, recorded at each load and save. When the tab returns to the screen, it reloads the file. Publishing checks first too: if the file changed, it reloads it and asks the owner to check it before publishing, so a catalog they haven't seen is never published. With unsaved edits, the edits are kept instead, and the owner is told that saving them will replace the other version. Reloads are skipped while a save is being written, when the file briefly differs from its record. Saving is atomic — written to `catalog.json.tmp`, then renamed into place — so an interrupted or failed save leaves the previous file intact. + +- **Look:** the wireframes' palette and components (`wireframe.css`) — pale background, white bordered cards and fields, muted hints, a blue accent for Publish — with a matching dark palette chosen from the system setting, since Code On The Go is often used in dark mode. The form is grouped into **Store**, **Products** and **Advanced**, and the status line and Publish button sit in a bar along the bottom. +- **Publish asks first.** A dialog, *Publish Top Android apps?*, says how many products the store will have, names up to three left out with nothing to download, and says buyers keep the current version until the new one is ready. **Cancel** changes nothing. It comes after the checks that refuse a publish outright — invalid Extra JSON, or a catalog changed outside the plugin — so it appears only when a publish is about to start. +- **The screen stays on while a publish runs,** so a screen timeout can't pause a server in *Pause when the screen turns off* mode partway through, or slow the zipping down. +- **Left-out products are named.** A product with nothing to download — no APK chosen with *Publish the APK* ticked, and *Publish the source* unticked — is left out of the store, and its card shows *draft*. The message after publishing names each one and why, for example *Left out: Great Scott 2 has no APK chosen, and Publish the source isn't ticked.* +- **HTML check for descriptions.** The store description and every product description go into the page as raw HTML, so each is checked as the owner types, by a small checker in the plugin (no library): it tracks open tags on a stack, skipping comments, quoted attribute values and the raw text inside ` + + + + + + + +
+
+

Manage Catalog

+
+
+
+ +
+ + +
+ +
+ + +

Rendered as-is, unescaped, directly under the store name on the buyer's page

+
+ +
+ + + + + + + + + + + + + + + + +
+
Header image
+
share-your-apps-server-icon.svg (default)
+
+ Change +
+ +
+
+
+ + up to 6 digits +
+ +
+

Buyers enter this before reaching the store. Sent in cleartext — no HTTPS.

+
+ +
+ +
+
+ + +
+ +
+
+ + + + + + + + + + + + + +
+
+ My Todo App + +
+
+ Source – + APK ✓ 4.2 MB +
+ +
+
+ +
+ + + + + + + + + + + +? + +
+
+ Weather Widget + +
+
+ Source ✓ + APK ✓ 1.8 MB +
+ +
+
+ +
+ + + + + + + + + + + + + + + + + + + + +
+
+ Recipe Box (draft) + +
+
+ Source – + APK – +
+ +
+
+
+
+ +
+ +
+
+ + +
+ +

Currently using the default template. Tap the copy icon to load its source here as a starting point, then edit it — this field replaces the default when non-empty.

+
+ +
+ + +

Passed into the Pebble context alongside products

+
+ +
+
+ + +
+ + Publishing… +
+
+
+ + +
+
+
+ + + +``` + +## B.3 `Icon.dc.html` — Share Your Apps Server app icon + +Real color (App Dev for All blue/green), animated cart-wheel rotation via SMIL — the one artboard here that isn't a gray-box wireframe, since it's a finished asset rather than a layout sketch. + +```html + + + + +Share Your Apps Server — app icon + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + +``` + +## B.4 `ManageServer.dc.html` — Share Your Apps Server app — Manage Server + +The most-iterated screen; it shows the interaction decisions settled while designing it (busy/idle dot, running/stopped card color, tap-to-copy credentials, vertical Wi-Fi toggle, inline Port/Run-mode/log-size fields, the inset Combined-log panel). What was built differs; see the list at the top of this appendix. + +```html + + + + +Share Your Apps Server — Manage Server + + + + + + + + +
+
+

Manage Server

+
+
+
+ +
+
+ {{statusTitle}} + + + + +
+ + {{statusHint}} +
+
+
+ +
+ +
+
+ + 1024–65535 +
+ +
+ +
+ +
+
Run always
+
On-screen only
+
+
+ +
+
+ WiFi SSID + + Password + +
+
+
+
+
+ +
+ +
+ + +
+
+ + +
+ +
+
+ +
+
+ Combined log + +
+
+
192.168.1.42 - - [21/Sep:14:02:11] "GET /f/12" 200 41230 812B/s host=pixel-6a
+
192.168.1.55 - - [21/Sep:14:02:09] "GET /index.html" 200 8120 2.1kB/s host=-
+
[ERR] 14:02:05 write failed: broken pipe (192.168.1.55)
+
192.168.1.42 - - [21/Sep:14:01:58] "POST /pin" 200 12 118B/s host=pixel-6a
+
192.168.1.61 - - [21/Sep:14:01:44] "GET /manifest.json" 200 940 2.0kB/s host=-
+
192.168.1.70 - - [21/Sep:14:01:22] "GET /f/8" 200 18210 640B/s host=-
+
+
+
+
+
+
+ + + +``` + +## B.5 `ServeScreen.dc.html` — Share Your Apps Server app — Serve (customer-facing, full screen) + +Two-step QR flow: join Wi-Fi, then browse the store. + +**Read this before implementing from the markup below.** The markup shows Step 1's QR, the SSID, and the passphrase unconditionally, all as copyable text — accurate for **hotspot mode**, where the app generates the network and always knows its own passphrase. **LAN mode is different** (see *Serve screen* in *Server*): the passphrase isn't readable from a merely-joined network, so it comes from an optional, session-only field the owner types in — and **if it's blank, Step 1 is hidden entirely**, replaced by "Join [SSID] first if you're not already on it" as plain text with no QR and no passphrase line. The markup below has no representation of that hidden state; the design's *Serve screen* describes it. Everything else in this wireframe — the two-step structure, layout, copy affordances, Step 2 — is unaffected and still authoritative for both modes. + +```html + + + + +Share Your Apps Server — Serve + + + + + + + + +
+
+
+ + + + + + + + + + + + + + + + +
My Share Your Apps
+
+
+
+

{{storeDescriptionHtml}}

+
+
+ +
+
Scan to join Wi-Fi, then scan to browse — skip the first scan if you're already connected
+
+ + +
+
+ About this store + +
+
{{storeDescriptionHtml}}
+
+ + +
+
+
+ +
+ +
+ +
+ + + + + + + + + + + + + + + + +
+
+ SSID: {{ssid}} + +
+
+ Passphrase: {{passphrase}} + +
+
+ +
+ +
+ +
+ + + + + + + + + + + + + + + +
+ +
Enter PIN on that page
+
+
+ {{url}} + +
+
+ +
+
+
+ + + +``` + +## B.6 `FullScreenLogView.dc.html` — Share Your Apps Server app — full-screen combined log view + +Reached from Manage Server's inset panel's expand button; its file chips, search and filters are described in the design's *Full log view*. + +```html + + + + +Share Your Apps Server — Full-screen log + + + + + + + + +
+ +
+ +
+
Combined log
+
1,204 lines · 3.2 MB
+
+
+ +
+ Current + 2h ago + 6h ago + 1d ago + 2d ago +
+ +
+ + + +
+ +
+ + + All + Access + Errors +
+ +
+
192.168.1.42 - - [21/Sep:14:02:11] "GET /f/12" 200 41230 812B/s host=pixel-6a
+
192.168.1.55 - - [21/Sep:14:02:09] "GET /index.html" 200 8120 2.1kB/s host=-
+
[ERR] 14:02:05 write failed: broken pipe (192.168.1.55)
+
192.168.1.42 - - [21/Sep:14:01:58] "POST /pin" 200 12 118B/s host=pixel-6a
+
192.168.1.61 - - [21/Sep:14:01:44] "GET /manifest.json" 200 940 2.0kB/s host=-
+
192.168.1.61 - - [21/Sep:14:01:44] "GET /products/weather/icon.png" 200 3021 host=-
+
[ERR] 14:01:40 accept() timed out, retrying
+
192.168.1.70 - - [21/Sep:14:01:22] "GET /f/8" 200 18210 640B/s host=-
+
192.168.1.42 - - [21/Sep:14:00:59] "GET /index.html" 200 8120 1.4kB/s host=pixel-6a
+
192.168.1.55 - - [21/Sep:14:00:41] "GET /f/12" 200 41230 900B/s host=-
+
192.168.1.61 - - [21/Sep:14:00:30] "POST /pin" 401 0 host=-
+
[ERR] 14:00:30 pin rejected for 192.168.1.61
+
192.168.1.42 - - [21/Sep:14:00:12] "GET /manifest.json" 200 940 host=pixel-6a
+
+
+
+
Pinch to zoom · swipe to pan (mirrors scrollbars)
+ +
+
+ + + +``` + +## B.7 `BuyerCatalogPortrait.dc.html` — Buyer's browser — rendered catalog page, portrait phone + +```html + + + + +Buyer catalog — portrait phone + + + + + + + + +
+
+
+ + + + + + + + + + + + + + + + +

My Share Your Apps

+
+
+
+

{{storeDescriptionHtml}}

+
+
+ +
+
+
+
+
+ + + + + + + + + + + + +
+
+
+ My Todo App + Sep 19, 2026 +
+

A simple, offline-first to-do list. No account needed.

+ +
+
+ +
+
+ + + + + + + + + + +? + +
+
+
+ Weather Widget + Sep 12, 2026 +
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + +
+
+
+ Recipe Box + Sep 5, 2026 +
+

Family recipes, organized by course.

+ +
+
+ +
+ + +
+
+ About this store + +
+
{{storeDescriptionHtml}}
+
+ + +
+
+
+
+
+ + + +``` + +## B.8 `BuyerCatalogLandscape.dc.html` — Buyer's browser — rendered catalog page, landscape tablet + +```html + + + + +Buyer catalog — landscape tablet + + + + + + + + +
+
+
+ + + + + + + + + + + + + + + + +

My Share Your Apps

+
+
+
+

{{storeDescriptionHtml}}

+
+
+ +
+
+
+
+
+
+ + + + + + + + + + + + +
+
+
+ My Todo App + Sep 19, 2026 +
+

A simple, offline-first to-do list. No account needed.

+ +
+
+ +
+
+ + + + + + + + + + +? + +
+
+
+ Weather Widget + Sep 12, 2026 +
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + +
+
+
+ Recipe Box + Sep 5, 2026 +
+

Family recipes, organized by course.

+ +
+
+
+
+ + +
+
+ About this store + +
+
{{storeDescriptionHtml}}
+
+ + +
+
+
+
+
+ + + +``` + +## B.9 `ApkVariantPicker.dc.html` — Plugin — APK variant picker + +Grouped by build type (Release / Debug / per-ABI splits). The built picker is simpler; see the list at the top of this appendix. + +```html + + + + +Plugin — APK variant picker + + + + + + + + +
+
+

MyTodoApp — app/build/outputs/apk

+

Choose an APK

+
+
+ +
Release
+
+
+
+
app-release.apk
+
4.2 MB · built Sep 19, 9:41 AM
+
+ › +
+ +
Debug
+
+
+
+
app-debug.apk
+
6.8 MB · built Sep 19, 9:38 AM
+
+ › +
+
+
+
+
app-quickbuild.apk
+
7.1 MB · built Sep 18, 4:02 PM
+
+ › +
+ +
Per-ABI splits (release)
+
+
+
+
app-armeabi-v7a-release.apk
+
2.9 MB · built Sep 19, 9:41 AM
+
+ › +
+
+
+
+
app-arm64-v8a-release.apk
+
3.1 MB · built Sep 19, 9:41 AM
+
+ › +
+
+
+
+
app-x86-release.apk
+
3.0 MB · built Sep 19, 9:41 AM
+
+ › +
+ +
+
+
+ + + +``` + +## B.10 `PreflightErrorDialog.dc.html` — Plugin — pre-flight validation error dialog + +```html + + + + +Plugin — pre-flight error dialog + + + + + + + + +
+
+
+
+ +
+
+
Can't publish yet
+

Nothing has been changed or published.

+
+
+
+
+
Extra JSON is invalid
+
Unexpected token '}' at line 4, column 3
+

Fix the error shown above, then tap "Create / Install / Launch Store" again.

+
+ +
+
+
+ + + +``` + +## B.11 `ConfirmationDialogs.dc.html` — Plugin — Create/Install/Launch and Cancel confirmation dialogs + +```html + + + + +Plugin — confirmation dialogs + + + + + + + + +
+ +
+
Create / Install / Launch Store?
+
+ + Server idle — safe to publish +
+
+
This will:
+
+
• Copy 2 APKs and build 1 source zip
+
• Install the Share Your Apps Server app (if needed)
+
• Start the server on port 6175
+
+
+

Publishing now may interfere with anyone currently downloading from the store.

+
+ + +
+
+ +
+
Discard unsaved changes?
+

Leaving now will lose edits to your catalog that haven't been published yet.

+
+ + +
+
+ +
+
+ + + +``` + +## B.12 `PinEntryPage.dc.html` — Buyer's browser — PIN entry page, default and incorrect-PIN states + +```html + + + + +Buyer catalog — PIN entry page + + + + + + + + +
+ +
+
+
My Share Your Apps
+

Enter the PIN to continue

+
+ + +
+
+ +
+
+
My Share Your Apps
+

Enter the PIN to continue

+
+ +
Incorrect PIN
+ +
+
+ +
+
+ + + +``` + +## B.13 Canvas layout index (`canvas.json`) + +```json +{ + "v": 3, + "createdOnFiles": { "v": 1, "at": "2026-09-21T00:00:00Z" }, + "title": "Share Your Apps Plugin — Wireframes", + "launch": { "view": "canvas" }, + "pages": [], + "boards": { + "Main.dc.html": { "x": 0, "y": 0, "w": 390, "h": 844, "title": "Manage Catalog", "is_interactive": true }, + "Icon.dc.html": { "x": 470, "y": 0, "w": 160, "h": 160, "title": "App icon" }, + "ManageServer.dc.html": { "x": 710, "y": 0, "w": 390, "h": 844, "title": "Manage Server", "is_interactive": true }, + "ServeScreen.dc.html": { "x": 1180, "y": 0, "w": 390, "h": 844, "title": "Serve (customer-facing)", "is_interactive": true }, + "FullScreenLogView.dc.html": { "x": 1650, "y": 0, "w": 390, "h": 844, "title": "Full-screen log view" }, + "BuyerCatalogPortrait.dc.html": { "x": 0, "y": 964, "w": 390, "h": 844, "title": "Buyer catalog — portrait", "is_interactive": true }, + "BuyerCatalogLandscape.dc.html": { "x": 470, "y": 964, "w": 900, "h": 700, "title": "Buyer catalog — landscape", "is_interactive": true }, + "ApkVariantPicker.dc.html": { "x": 1450, "y": 964, "w": 390, "h": 844, "title": "APK variant picker" }, + "PreflightErrorDialog.dc.html": { "x": 0, "y": 1928, "w": 390, "h": 600, "title": "Pre-flight error dialog" }, + "ConfirmationDialogs.dc.html": { "x": 470, "y": 1928, "w": 420, "h": 880, "title": "Confirmation dialogs" }, + "PinEntryPage.dc.html": { "x": 1450, "y": 1928, "w": 820, "h": 844, "title": "PIN entry page" } + }, + "order": [ + "Main.dc.html", + "Icon.dc.html", + "ManageServer.dc.html", + "ServeScreen.dc.html", + "FullScreenLogView.dc.html", + "BuyerCatalogPortrait.dc.html", + "BuyerCatalogLandscape.dc.html", + "ApkVariantPicker.dc.html", + "PreflightErrorDialog.dc.html", + "ConfirmationDialogs.dc.html", + "PinEntryPage.dc.html" + ], + "notes": { + "row1": { "x": 0, "y": -80, "text": "Plugin & Share Your Apps Server app screens", "kind": "title1", "maxW": 1570 }, + "row2": { "x": 0, "y": 884, "text": "Buyer-facing pages & pickers", "kind": "title1", "maxW": 1840 }, + "row3": { "x": 0, "y": 1848, "text": "Dialogs", "kind": "title1", "maxW": 1840 } + }, + "designSystems": [] +} +``` + +--- + +# Appendix C — Store page templates + +The store page is a Pebble template. The plugin ships one, the default, which owners can replace under **Advanced** in Manage Catalog: paste a template into **Template override**, or tap **Choose a template file** to load a `.peb` file, starting in the phone's Download folder. Clearing the field, or tapping **Load the default template**, goes back to the default. *Writing a template*, in *Developer notes*, lists the Pebble rules that catch people out. + +This appendix holds six templates: + +- **C.1 — the default, annotated:** laid out for reading, with comments explaining how it works. It's a working template too, and renders the same page as C.2: published with the demo catalog and screenshotted, the two pages match pixel for pixel, apart from the octopus's animation. +- **C.2 — the default, as shipped:** exactly the text in the plugin's `Templates.kt`, minified so it costs buyers as little as possible. +- **C.3 to C.5 — three alternatives,** which present the same information in very different ways: Neon Arcade, Morning Edition and Aurora Deck. +- **C.6 — Clear Access,** for buyers who use a screen reader or have low vision. + +All of them use everything the page receives, as listed at the top of C.1. Every publish also renders C.6, Clear Access, as `accessible.html`, and each of the others links to it from its top left as *Accessible version*. All six pass axe-core's WCAG 2.2 level A and AA checks, and its best-practice rules, with the demo catalog; the only items left for review are video captions, which the catalog can't supply, and text over animated or gradient backgrounds, which axe can't measure. They work offline, with no web fonts or outside files, and stop animating for anyone whose phone asks for reduced motion. Each was published with the demo catalog through the plugin's own publisher and Pebble, produced valid HTML and a poster for each video, and was checked in phone-width screenshots in WebKit. + +## C.1 The default template, annotated + +``` +{# + BLOCKS: this template is split into blocks — styles, header, announcement, + card, downloads and footer. A template of your own can extend it and replace just one: + + {% extends "default" %} + {% block downloads %}Get it{% endblock %} + + {{ parent() }} inside a block keeps the original too. Other templates, and macros, go in the + template library, CodeOnTheGoProjects/ShareYourAppsTemplates/, for {% include %} and {% import %}. +#} +{# + The default Share Your Apps page, laid out and annotated. It renders the same page as the compact + copy the plugin ships. Comments like this one are Pebble comments: Pebble removes + them while rendering, so none reach buyers. The /* … */ comments in the CSS and script do reach + the page, as ordinary CSS and JavaScript comments. + + What the template receives: + lang the page's language, such as "en-US": Extra JSON's "lang" if set, else the phone's + publishedAt when this publish happened, as an ISO date and time; publishedLabel is "Sep 24, 2026" + shareYourAppsVersion the plugin's version, such as "1.0.0", for a "Made with Share Your Apps" line + contact from Extra JSON, checked: .name, .email, .phone and .url, each with an + .emailHref, .phoneHref or .urlHref only when it's a plausible address + announcement from Extra JSON: a short line of news, as plain text + accent, accentInk from Extra JSON: a colour, only ever #rrggbb, and black or white — whichever + reads better on it, which always reaches WCAG's 4.5 to 1 + storeName the store's name, as text + storeDescriptionHtml the owner's description, as HTML, or null + headerImage .src and .type ("image" or "video") — the octopus when none is chosen + products in Manage Catalog's order, each with: + .name, .ordinal, .slug (a stable ID, such as "termux"), .descriptionHtml (HTML or null) + .dateAddedLabel "Sep 24, 2026"; .dateAddedIso is the same as an ISO date and time + .carousel pictures, videos and sounds: .src, .type, .poster for a video, and + .width and .height where known + .apk .src, .sizeLabel ("6.8 MB") and .sizeBytes, or null; and what the plugin reads + from the APK: .versionName, .versionCode, .packageName, .minSdk and + .androidLabel ("Android 9 or later") — each null when it can't be read — + and .abis, its native-code architectures, with .abiLabel for buyers + ("64-bit phones", "32-bit phones", "32- and 64-bit phones", or "all + phones" when it has no native code) + .sourceZip .src, .sizeLabel and .sizeBytes, or null + .whatsNew, .license, .author + from the product's Extra JSON, checked: plain text, cut to 500, 80 and 80 + characters, or null. They sit on the product itself: p.whatsNew, not + p.extra.whatsNew + .website, .websiteHref + from the product's Extra JSON: the text, cut to 300 characters, and the same + as a link, only when it's an http or https address, else null + .extra the product's whole Extra JSON, exactly as typed and not checked: any key the + owner added is here, but nothing in it is safe to use as a link. Prefer the + checked values above + extra the store's whole Extra JSON, exactly as typed and not checked. Its "strings" + table feeds t("key", "fallback"), which picks the text for the store's + language; the other documented keys have checked values above (lang, + contact, announcement, accent) + accessibleHref the link to the accessible version of the page, accessible.html, which + every publish also makes from the Clear Access template + + Every .src is ready to use: a /f/… link to a file in the store, or, for anything of 10 KB or + less, the file itself as a data: URI. + + Pebble rules that differ from other template languages: a condition needs "is not empty" — + a bare {% if x %} is an error — and the sort filter takes no arguments, which is why products + arrive already in order. {{ … }} escapes HTML; |raw prints the owner's HTML as it is. +#} + + + + + +{{storeName}} +{% block styles %}{% endblock %} +{# The owner's accent colour, if any, for the download button: checked by the plugin, so it's only + ever a #rrggbb colour, with black or white text on it. #} +{% if accent is not empty %}{% endif %} + + +{# The accessible version, first on the page. It's in its own small region, so screen readers + list it among the page's regions. #} +{% if accessibleHref is not empty %}{% endif %} +{# The awning is decoration only, so screen readers skip it. #} + + +{# The header. The octopus arrives as headerImage when the owner hasn't chosen an image. A video + header plays by itself, silently and in a loop, like an animated picture. #} +{% block header %}
+ {% if headerImage.type=='video' %}{% else %}{% endif %} +
+

{{storeName}}

+ {% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %} +
+
{% endblock %} + +{# The owner's announcement, if any, above the products. #} +{% block announcement %}{% if announcement is not empty %}

{{announcement}}

{% endif %}{% endblock %} + +{# The products, one card each, in Manage Catalog's order. They're the page's main region, which + screen readers can jump straight to. #} +
+ {% for p in products %}{% block card %}
+ + {# The picture strip, if the product has any pictures, videos or sounds. It can take keyboard + focus, so it can be scrolled with the arrow keys, and screen readers announce its label. #} + {% if p.carousel is not empty %} +
+
+ {% for m in p.carousel %} +
+ {# Videos show their poster until played, and never preload: preloading would tie up + the server's single thread. Each item is labelled with its product and position, such + as "Termux, picture 1 of 3": the catalog has no descriptions of what pictures show. #} + {% if m.type=='video' %} + {% elseif m.type=='audio' %} + {% else %}{% endif %} +
+ {% endfor %} +
+ {# Arrows only when there's more than one item. The left one starts hidden, at the first + item; the script shows and hides both as the strip moves. #} + {% if p.carousel|length > 1 %} + + + {% endif %} +
+ {% endif %} + + {# The name, as a heading, with the date — in a
{% endblock %}{% endfor %} +
+ +{# The foot: the owner's contact details, each a link only when it's a real address, and the version. #} +{% block footer %}
+ {% if contact is not empty %}

Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

{% endif %} +

Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

+
{% endblock %} + + + + +``` + +## C.2 The default template, as shipped (`default-catalog-template.peb`) + +``` +{{storeName}}{% block styles %}{% endblock %}{% if accent is not empty %}{% endif %}{% if accessibleHref is not empty %}{% endif %}{% block header %}
{% if headerImage.type=='video' %}{% else %}{% endif %}

{{storeName}}

{% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %}
{% endblock %}{% block announcement %}{% if announcement is not empty %}

{{announcement}}

{% endif %}{% endblock %}
{% for p in products %}{% block card %}
{% if p.carousel is not empty %}
{% for m in p.carousel %}
{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}
{% endfor %}
{% if p.carousel|length > 1 %}{% endif %}
{% endif %}

{{p.name}}

{% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}
{% if p.descriptionHtml is not empty %}
{{p.descriptionHtml|raw}}
{% endif %}{% if p.whatsNew is not empty %}

What's new: {{p.whatsNew}}

{% endif %}{% block downloads %}
{% if p.sourceZip is not empty %}Download source{{p.sourceZip.sizeLabel}}{% endif %}{% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}
{% endblock %}{% if p.apk is not empty %}

{% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

{% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

{% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

{% endif %}
{% endblock %}{% endfor %}
{% block footer %}{% endblock %} +``` + +## C.3 Neon Arcade (`theme-neon-arcade.peb`) + +A dark synthwave arcade. The store's name is neon lettering that flickers now and then, over a striped sunset and a grid floor that runs toward the viewer. Products are cabinets whose glowing borders cycle through pink, cyan and yellow, with their pictures on a scanlined CRT screen and a count of pictures in its corner. The buttons are chunky and glowing. The colour cycling uses a CSS `@property` animation; browsers without it show a still border. + +``` +{{storeName}}{% if accent is not empty %}{% endif %}{% if accessibleHref is not empty %}{% endif %} +
{% if headerImage.type=='video' %}{% else %}{% endif %}

{{storeName}}

{% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %}
+{% if announcement is not empty %}

{{announcement}}

{% endif %}
{% for p in products %}
No. {{p.ordinal}}{% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}

{{p.name}}

{% if p.carousel is not empty %}
{% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
{% if p.carousel|length > 1 %}{% endif %}
{% endif %}{% if p.descriptionHtml is not empty %}
{{p.descriptionHtml|raw}}
{% endif %}{% if p.whatsNew is not empty %}

What's new: {{p.whatsNew}}

{% endif %}
{% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download source{{p.sourceZip.sizeLabel}}{% endif %}
{% if p.apk is not empty %}

{% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

{% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

{% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

{% endif %}
{% endfor %}
+

{{products|length}} apps on the floor

{% if contact is not empty %}

Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

{% endif %}

Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

+``` + +## C.4 Morning Edition (`theme-morning-edition.peb`) + +A newspaper. A ticker of product names scrolls across the top, above a masthead with a motto and a dateline. Products are articles in newspaper columns, each with a red drop cap, and pictures appear as grey photographs that take on colour when touched. The downloads are coupons, with dashed edges and scissors. On a phone set to dark mode, it becomes a dark *Night Edition*. + +``` +{{storeName}}{% if accent is not empty %}{% endif %}
{% if accessibleHref is not empty %}{% endif %} + +
{% if headerImage.type=='video' %}{% else %}{% endif %}

{{storeName}}

All the apps that are fit to install

+ +{% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %}
+{% if announcement is not empty %}

Stop press {{announcement}}

{% endif %}
{% for p in products %}
No. {{p.ordinal}}

{{p.name}}

Filed {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}
{% if p.carousel is not empty %}
{% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
{% if p.carousel|length > 1 %}{{p.carousel|length}} pictures — swipe for more. {% endif %}Touch a picture for colour.
{% endif %}{% if p.descriptionHtml is not empty %}
{{p.descriptionHtml|raw}}
{% endif %}{% if p.whatsNew is not empty %}

What's new: {{p.whatsNew}}

{% endif %}
{% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download source{{p.sourceZip.sizeLabel}}{% endif %}
{% if p.apk is not empty %}

{% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

{% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

{% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

{% endif %}
{% endfor %}
+ +
+``` + +## C.5 Aurora Deck (`theme-aurora-deck.peb`) + +Frosted glass over a slowly moving aurora. The store's name shimmers with a travelling gradient. Products are numbered glass cards in a deck that swipes sideways, each with its pictures in a mosaic, the first large and the rest in pairs. On screens 900 pixels wide or more, the deck becomes a grid. The glass uses `backdrop-filter`; without it, cards are still translucent, just not blurred. + +``` +{{storeName}}{% if accent is not empty %}{% endif %}{% if accessibleHref is not empty %}{% endif %} +
{% if headerImage.type=='video' %}{% else %}{% endif %}

{{storeName}}

{% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %}
+{% if announcement is not empty %}

{{announcement}}

{% endif %}
{{products|length}} appsSwipe →
+
{% for p in products %}
{% if p.carousel is not empty %}
{% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
{% endif %}

{{p.name}}

{% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}
{% if p.descriptionHtml is not empty %}
{{p.descriptionHtml|raw}}
{% endif %}{% if p.whatsNew is not empty %}

What's new: {{p.whatsNew}}

{% endif %}
{% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Source{{p.sourceZip.sizeLabel}}{% endif %}
{% if p.apk is not empty %}

{% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

{% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

{% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

{% endif %}
{% endfor %}
+``` + +## C.6 Clear Access (`theme-clear-access.peb`) + +For buyers who use a screen reader, or have low vision. It passes every WCAG 2.2 level A and AA check that axe-core makes, and its best-practice rules, with the demo catalog. The only item left for review is video captions, which the catalog can't supply (see *Known open items*). + +- **Structure a screen reader can navigate:** a *Skip to the apps* link first; the store's name as the main heading and each app as a subheading; page regions for the header, the contents, the apps and the footer; a contents list linking to every app, and a link back from each. +- **Downloads that make sense out of context,** since screen reader users often list a page's links: *Download Termux APK, 265 B* and *Download Termux source code*. They come straight after each app's description. +- **Pictures in one column,** not a sideways strip, each labelled with its app and position, such as *Termux, picture 1 of 3*. Every picture and video has a fixed-height box, so pictures loading as the page scrolls never move it, and the contents links land where they should. +- **For low vision:** text at 20 px by default, in units that grow with the phone's text size; black on white, or white on black in dark mode; a thick focus outline; underlined links; buttons at least 56 px tall. With the phone's *increase contrast* setting, borders thicken; with Windows' high-contrast mode, system colours are used. +- **Nothing moves,** and there's no script. +- **Built into the plugin,** which publishes it as `accessible.html` beside every other template's page. There, it links back at its top left, with *Standard version*. Its first line is the comment `share-your-apps:accessible`, which tells the plugin that a store using it as its own template needs no second copy. + +``` +{# share-your-apps:accessible — marks this as the accessible template, so the plugin makes no second copy of it. #} +{{storeName}} + +
+{% if standardHref is not empty %}{% endif %} +
{% if headerImage.type=='video' %}{% else %}{% endif %}

{{storeName}}

{% if storeDescriptionHtml is not empty %}
{{storeDescriptionHtml|raw}}
{% endif %}
+{% if announcement is not empty %}

{{announcement}}

{% endif %}{% if products is not empty %}{% endif %} +
{% for p in products %}

{{p.name}}

Added {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}

{% if p.descriptionHtml is not empty %}
{{p.descriptionHtml|raw}}
{% endif %}{% if p.whatsNew is not empty %}

What's new: {{p.whatsNew}}

{% endif %}
{% if p.apk is not empty %}Download {{p.name}} APK, {{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download {{p.name}} source code, {{p.sourceZip.sizeLabel}}{% endif %}
{% if p.apk is not empty %}

{% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

{% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

{% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

{% endif %}{% if p.carousel is not empty %}
    {% for m in p.carousel %}
  • {% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}
  • {% endfor %}
{% endif %}Back to the list of apps
{% endfor %}
+

{{storeName}} · Updated

{% if contact is not empty %}

Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

{% endif %}

Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

+
+``` + +--- + +# Appendix D — Extending templates + +Owners can add their own reusable pieces and logic to store page templates in three phases, cheapest and safest first. D.1 and D.2 are built. D.3 is not built: it is a design, kept for the day owners need something D.1 and D.2 can't do. + +A Pebble *extension* is Java code, not template text: its filters, tests, functions, operators, tags and attribute resolvers are classes implementing Pebble's interfaces, registered with the engine before any template is compiled — `new PebbleEngine.Builder().extension(new CustomExtension()).build()`. So owner-defined logic is either template text, which Pebble already supports as macros, or compiled code, which needs a way for the plugin to load it. + +## D.1 Reusable pieces, written in Pebble itself — built + +**As built.** Templates find each other through `TemplateLibrary`, the plugin's Pebble loader, for `{% extends %}`, `{% include %}`, `{% import %}` and `{% from … import %}`. The name `default` is the built-in default template; `accessible` is Clear Access; any other name is a file in `CodeOnTheGoProjects/ShareYourAppsTemplates/`, with `.peb` added if the name has none, relative to the library's top, never to the including template. A name that could leave the library — absolute, with an empty, `.` or `..` part, or a backslash — is refused, and so is a missing one, each stopping the publish with a message naming it. The default template has six blocks: `styles`, `header`, `announcement`, `card` — one product, inside the loop, so it sees `p` — `downloads`, inside `card`, and `footer`. They don't change its output at all: extending it without overriding anything gives exactly the default page, byte for byte, and `{{ parent() }}` inside a block keeps the original. The tests check each of these, through real publishes. + + +No code runs in this phase. The library folder, the default template's blocks and the macros an owner keeps in a library file are all built, as described above. + +## D.2 A curated set of built-in extensions — built + +**As built,** in `TemplateFunctions`, a Pebble extension registered with every render: + +- **`t("key")`**, or `t("key", "fallback")`: text from the Extra JSON `strings` table — `{"strings": {"sw": {"download": "Pakua"}, "en": {"download": "Download"}}}` — by the store's language, then its main language (`sw` for `sw-TZ`), then English, then the fallback, then the key itself. Its text is escaped like any other. +- **`plural(n, "# app", "# apps")`**: the first form for 1, the second otherwise, with `#` replaced by the number. It follows English's rule, which suits many languages but not all. +- **`markdown`**, a filter: paragraphs, lists of `- ` lines, `**bold**`, `*italic*`, `` `code` ``, and `[links](…)` to `http`, `https` or `mailto` only. The source is escaped first, so no HTML in it survives, and a link's address ends at an escaped quote or angle bracket, so it can never carry one. +- **`qr("text")`**, or `qr("text", "label")`: a QR code as an inline SVG image, `role="img"` with its label for screen readers. It uses ZXing's core library, the server's own version, which the plugin now bundles. +- **`bytes`**, a filter: a byte count as the store's own size labels show it. +- **`slugify`**, a filter: the store's slug rule. + +Pebble's own `abbreviate` filter already truncates text, so no `truncate` was needed. + + +These are real Pebble filters and functions, written and tested with the plugin and documented like the other values templates receive. Owners use them without writing code. + +## D.3 Owners' own compiled extensions (not built) + +For owners who write Kotlin, as many Code On The Go users do. + +- **Building one:** a small Code On The Go project, from a new *Share Your Apps extension* project template, compiled against Pebble 4.1.1 — the version Code On The Go supplies — into a `.dex` file. A properties file inside names the extension class, its version, and the Pebble version it needs. +- **Adding one:** in Manage Catalog, under **Advanced**, an **Extensions** list. Adding an extension shows a warning: *This runs as code, with Code On The Go's permissions. Add only extensions you built or trust.* The catalog records each extension's path and SHA-256 hash; if the file changes, the plugin asks again before using it. +- **Loading it at publish time:** the plugin copies the file into its private folder and marks it read-only, since Android 14 refuses to load writable code files. It then loads it with a `DexClassLoader` whose parent is the plugin's own class loader. That parent is essential: the extension must share the plugin's Pebble classes, not bring a copy of its own. Each extension is registered with the engine that renders the store's page. The accessible page keeps its built-in template, and no extensions, so it stays predictable. +- **Containing failures:** each publish renders on its own thread, with a time limit — ten seconds, say — so a runaway extension can't hang it. Any error, including a class that won't load, stops the publish with a message naming the extension, and the store keeps serving its previous version, as after any failed publish. +- **The rules for extension authors:** filters returning HTML must return Pebble's `SafeString`, or their output is escaped. Extensions shouldn't use the network, since stores work offline — a rule the plugin can't enforce, because extensions run inside it. Operators, custom tags and attribute resolvers are allowed, but documented as advanced. +- **No code from templates, ever:** a `.peb` file stays plain text, so a template shared by someone else can never bring code with it. + +## D.4 Recommendation and testing + +**D.1 and D.2 were built first.** Together they cover most of what owners are likely to want — reusable pieces, partial overrides, translation and common formatting — without running anyone's code. D.3 is real engineering with lasting costs: a compatibility promise to extension authors, a security warning owners may click through, and failures that are harder to support. Build it only when owners need something D.1 and D.2 can't do. A scripting engine, such as JavaScript for templates, isn't worth adding: D.3 gives developers more, for less. + +**Testing:** +- **D.1:** the loader's refusals, including `../` and absolute paths; and a template extending the default and replacing one block. +- **D.2:** each built-in, with known inputs and outputs. +- **D.3:** loading a sample extension from a real `.dex` on a phone; a changed file triggering the plugin to ask again; and a slow extension hitting the time limit. +- **All three:** axe-core's WCAG 2.2 AA checks on every page again, since blocks and extensions can change the markup. + +--- + +# Appendix E — Sharing a store with another seller + +Built. How an owner gives someone nearby a copy of their store, to serve from that person's own phone. Mockups of its screens, in the app's own look and wording as built, are in `store-sharing-screens/`: 1 to 3 on the owner's phone — Manage Server, the share screen and *Allow a copy?* — and on the new seller's, 4 Manage Server before importing, 4b *Can't import a store here*, 5 the import screen, 6 importing, 6b the finished import, 7 serving the copy, and 8 after it expires. + +## E.1 What a copy is + +- **A published store, served as it arrived.** It can't be changed: without Code On The Go and the plugin, the new seller has no Manage Catalog, and the copy is never rendered again. The server shows it as *Read-only*. +- **It can't be passed on** through Share Your Apps (see E.4). +- **It expires** on a date the owner chooses, when it's deleted from the seller's phone (see E.5). +- **The PIN belongs to serving, not to the store.** Each seller sets their own in the server, or leaves it blank; it's never part of a copy. +- **A phone serves one store at a time,** its own or one imported copy, and holds at most one copy. A phone serving **any** store — its own, or a copy — can't import one, so a copy is never replaced under a running server. Manage Server's *Import a store* panel says so **before any tap**: its button is disabled, and its caption reads *This phone is serving a store. To import one, stop serving it first, with Stop above, or import on another phone.* The import screen, which a QR link can open directly, says the same (screen 4b). + +## E.2 The flow + +On the owner's phone: +1. **Manage Server** has a panel, **Copies of this store**, with **Share this store…** (screen 1). +2. It shows a QR code, and the same as a typed code, such as `LS-7Q4K-9M2P`. The code works for one phone, for 10 minutes (screen 2). +3. When a phone asks, the owner sees its name and a four-digit **check code**, and chooses when the copy expires — in a week, in a month (the default), on a date, or never — then taps **Allow** or **Deny** (screen 3). Comparing the check code with the other screen confirms which nearby phone is asking. + +On the new seller's phone: +4. The server's start screen offers **Import a store…** (screen 4). While any store is served, its button is disabled, and its caption says why and what to do; the import screen, reached from a QR link, says the same (screen 4b). +5. The seller scans the owner's code, or types it, and confirms their phone's name, which starts as the phone's own name, and can be changed (screen 5). +6. Importing shows its steps, the check code, the copy's expiry and the transfer's progress (screen 6). **Cancel** works throughout. +7. The imported store shows as *Read-only*, with its expiry, **Serve this store**, the seller's PIN, and **Remove this store** (screen 7). +8. After expiry, the server says the store has been deleted, and that the seller can ask its owner for a new copy (screen 8). + +The owner's server keeps no record of the copies it has shared. + +**How the owner's side is built.** The screens follow the server app's own look — grey, with white, bevelled panels — not the mockups' store colours. The share lives in the server process, beside the HTTP server, since that's where requests arrive. The share screen, in the main process, binds to the server process directly, without starting it if it isn't running, and asks what's happening twice a second: `MSG_SHARE_OPEN`, `MSG_SHARE_POLL`, `MSG_SHARE_ALLOW` with the copy's expiry, `MSG_SHARE_DENY` and `MSG_SHARE_CLOSE`, answered by `MSG_SHARE_STATE`. Leaving the screen closes the share; rotating the phone, or another app coming over it, doesn't. **Sharing waits for compression:** right after a publish, the server is still writing the gzip copies, which change the store's files, so the share screen says *Getting the store ready to share…* and shows the code once it's done. If a transfer fails partway, the owner's screen says so, and the seller can try again while it stays open. The screen stays on while it's open, since a server paused for a dark screen can't share. If the server stops, sharing stops with it, and the screen says so. **Share this store…** works only while the server is serving the phone's own store. Otherwise it's disabled, and the panel's caption says why: *Start serving your store to share it*, or, while a copy is served, *This phone is serving a copy of someone else's store. Copies can't be passed on.* The store's key is kept in the app's private storage, `files/share/`. The QR code holds a `shareyourapps-share://
:/` link, which a phone's camera app recognises. An expiry *on a date* lasts to the end of that day, on the owner's phone. A button beside the typed code copies it, for pasting into a message. It's marked sensitive on the clipboard, so Android 13 and later hide it from the clipboard preview, and sync services and keyboards generally don't pass it on. **For a phone without the app,** the share screen shows a second, smaller QR code: *No Share Your Apps Server on the other phone? Scan this first.* Below it (from server step 65), *Or open this link in the other phone's browser:*, then the download link as selectable text, with a **Copy** button. The link may take two lines (from server step 67): `http://192.168.50.100:6175/share/app` is too wide for one on a narrow phone even at the smallest size, and was cut off, its second line showing only as dots. The share code keeps one line. **The Share screen names both phones throughout** (from server step 66): *this phone* is always the one sharing its store, and *the other phone* the one getting a copy — never *it*, *its* or *the phone*, which read ambiguously. The share code stays marked sensitive on the clipboard; the download link isn't. It opens `/share/app` in that phone's browser, which downloads the owner's own installed APK — the genuine app, signed with the server's key — named `share-your-apps-server.apk`. Like the rest of `/share/`, it's only there while the share screen is open, so it's never offered to buyers. The seller still sees Android's install prompt, and on some phones more — such as allowing the browser to install apps, or turning off Samsung's Auto Blocker — as *Limitations* describes. + +**How the seller's side is built.** Manage Server has an **Import a store** panel. On a phone serving its own store, it shows screen 4b's message instead, saying to use **Stop** above, since that screen is Manage Server. The import screen asks for the code and the phone's name, filled in from Android's device name. It also opens straight from the QR's link — a camera app offers to open `shareyourapps-share:` links, since the server registers them — with the owner's address and code already filled in, so no search is needed. A typed code is found by broadcast. The import runs in the background, in `ImportJob`, so the screen can rotate, or be left and reopened. It has four steps: finding the store, the owner allowing it, receiving, with a progress bar, and ready. **Cancel**, or Back, stops it at any point, leaving nothing. A copy is kept in the app's private storage, `files/imported//`, with its description beside it, `.json`, for its name and expiry. Importing replaces the phone's one copy as E.6 says, asking first when it's older, or a different store. The import runs inside a small foreground service, `ImportService`, with its progress in a notification, so Android doesn't freeze or kill it once the app leaves the screen. If a transfer fails partway, the import screen offers **Try again**, using the same exchange, while the owner's share stays open. **Every request goes over Wi-Fi explicitly**, bound to the Wi-Fi network: a network without internet, such as the owner's hotspot, isn't Android's default, and requests would otherwise go to mobile data, and fail. A phone that isn't on Wi-Fi is told to join the owner's network first. If the import happened over the owner's own network — the Wi-Fi's gateway is the owner's phone — the last screen says so: serving there would depend on the owner's phone, so the seller should join their own Wi-Fi, or turn Wi-Fi off so the phone starts its own hotspot. On a phone serving a copy, messages never suggest publishing again. The mockups' camera view on screen 5 became a hint to scan with the phone's own camera, since a built-in scanner would be a lot of code for no gain. + +**Serving a copy.** Manage Server shows a panel for the copy whenever the phone holds one (screen 7): its name, *Read-only*, and when it expires — nothing about where it came from, which the copy doesn't carry — then **Serve this store**, the seller's PIN, set or left blank, and **Remove this store**, after a confirmation. The import screen ends with **Serve it now**. Serving a copy is a second way for the server to start, `ACTION_SERVE_COPY`, passing the server process the copy's folder, its name, and the seller's PIN, without the plugin's token. The server process accepts the folder only if it's inside the app's own `files/imported/`, and skips the shared-storage checks a published store needs. Everything else — the Wi-Fi watch, the hotspot, pausing when the screen's off, the Serve screen and the log — works as for any store. The server remembers which kind it last served, so **Start**, unlocking and the first **Start** after a reboot bring back the right one — and on a phone with only a copy, **Start** serves the copy, since there's nothing else to serve. The Status panel says which **Start** will serve; serving a copy never overwrites the saved details of the phone's own store, so publishing from Code On The Go serves the owner's store, keeping the copy (E.6). While a copy is served, **Share this store…** is disabled, and the server process refuses to share one anyway. Importing is blocked while the phone serves any store, own or copy; to update a copy, a seller stops serving it first. + +## E.3 The transfer, and why it can be trusted + +- **The store's key.** Each owner's store has a key pair, created once and kept in the owner's server's private storage. It signs every copy, and it *is* the store's identity. +- **One copy, for one phone.** The seller's server asks the owner's server directly, over the local network, through a separate sharing address authorised by the share code — not the store's PIN, which is for buyers — sending its own public key. The owner's server encrypts the copy for that key alone, with authenticated encryption such as AES-GCM, so the copy is useless on any other phone, and any altered byte makes the transfer fail. +- **The exchange, and why the check code can't be forged.** (1) The seller's server sends the share code and a *commitment*: the hash of its public key. (2) The owner's server replies with its own one-time public key. (3) The seller's server reveals its key, which the owner's checks against the commitment. Both then show a four-digit check code computed from the two keys and the code. Without the commitment, someone in the middle of the network could try thousands of keys until the digits matched; with it, each side's key is fixed before it sees the other's, so their chance stays 1 in 10,000. Bluetooth pairing and ZRTP use the same idea. +- **The code for all of it** is in one file, `ShareCrypto.kt`, for the review: P-256 keys, ECDSA signatures, the store's identity, the commitment, the check code, ECDH with HKDF-SHA256, and AES-256-GCM in numbered 64 KB chunks, whose number and a *last* flag are authenticated too, so altering, reordering or cutting off a copy all fail. +- **The sharing address,** on the owner's server, answered before the PIN check, since sellers aren't buyers: `POST /share/request` (the code, the phone's name and the commitment), `POST /share/reveal` (the seller's key), `GET /share/status` (*waiting*, *allowed*, *denied* or *expired*), and `GET /share/copy`. It exists only while the owner's screen has a share; otherwise every path answers *not found*. While it exists, a seller can still hear *denied* or *expired*, and each route refuses what it should: a request once the share isn't open, a status for an unknown request, a copy before approval. +- **Waiting without blocking anyone.** The owner's main thread never waits on a person: the seller's server asks for the status every second instead. The share itself is guarded by one lock, held only for a moment each time. +- **The copy is made as it's sent,** encrypted in a sender thread like any other download, so it's never stored on the owner's phone, whatever its size. After one complete download, the share is done, and its code can't be used again. +- **Codes can't be guessed:** five wrong codes close the share, even to the right one. A code is also refused once it's been used, after 10 minutes, and while another phone is using it. +- **Finding the owner's server from a typed code:** the seller's server broadcasts *who has this code?* on UDP port 6176, as a hash of the code, so listening to the broadcast doesn't reveal it. Only the server showing that code answers, with its port. A QR code carries the address itself. +- **A protocol number.** Each side sends its sharing protocol's version, `ShareHost.PROTOCOL`, and a mismatch is refused — after the code is checked, so strangers can't probe versions — naming which phone needs updating: the seller's, from the owner's share screen's small QR code, or the owner's. +- **Every file stays inside the copy's folder.** Import refuses any path that's absolute, has an empty, `.` or `..` part, or a backslash, or whose canonical path leaves the temporary folder; and a copy listing a file twice. The folder's name is the store's identity, which import checks is derived from the store's key, so it's base32 only. These checks matter even though the copy is signed: a modified owner's app could send bad names. +- **A copy never includes temporary files,** such as the compressor's `.gz.tmp`, which vanish when renamed. +- **No separate checking pass.** The authenticated encryption, with the check code, already guarantees every file arrived intact and came from the owner. APKs' own signatures catch damage, but not an APK swapped for another; the transfer catches both, for every file. The one extra check is the copy's description file, whose signature is checked against the store's key when the transfer starts. +- **All or nothing.** Everything is written to a temporary folder, renamed into place only once the last file is saved, so a store is either complete or absent. A cancelled or interrupted import leaves nothing behind; the seller asks the owner again. +- **Space first.** The seller's server checks it has room before the transfer starts. +- **Plain HTTP between the phones.** Android 9 and later block an app's own plain-HTTP requests unless it opts in, so the server's manifest sets `android:usesCleartextTraffic="true"`. A narrower network security configuration can't help, since it only allows named hosts, not whatever private address the owner's phone has. Plain HTTP is safe here: the copy is protected by its own encryption, and the other requests carry nothing secret. +- **The technical choices:** P-256 keys with AES-GCM, both built into Android back to Android 9, the oldest version the server supports, so no cryptography library needs bundling; X25519 isn't built in on every version. The share code authorises the sharing address, because the store's PIN is for buyers. The check code has four digits, making a lucky match 1 in 10,000 — enough for a code compared by eye, once, within 10 minutes. +- **An independent review first.** This is a transfer protocol of our own design, combining key exchange, encryption and signatures. Before it's built, someone who reviews cryptographic protocols should check it. + +## E.4 Why a copy can't be passed on — and the limits of that + +- **Nothing is backed up, or moved to another phone:** the manifest sets `allowBackup="false"`, and data-extraction rules exclude everything from cloud backup and from device-to-device transfer, which Android 12 and later do even without backup. So a copy, the store's key and the logs of buyers' addresses stay on their phone. +- The server has no export for an imported store, and keeps it in its private storage, which other apps and file managers can't reach. +- Each copy is encrypted for one phone, so forwarding the files achieves nothing. +- Every copy is one the owner allowed, on their own screen. + +**It isn't copy protection,** and the design shouldn't claim it is. Anything a store serves is ordinary web content, which anyone who can open the store can copy with any web-copying tool, and serve with other software. And Share Your Apps Server is open source, so a modified build could ignore every rule here. + +## E.5 Expiry + +- **The date is in the copy's description, signed with the store's key,** so the seller can't change it. +- **On or after that date,** the server stops serving the store, lets downloads already under way finish, then deletes it. It checks once a minute while serving, and whenever the app looks at the copy, so an unserved copy past its date is deleted the next time the app runs — it can never be served in between. +- **How it's built.** One rule, `CopyExpiry`, in the core, decides: a copy is due on its date, or at once if the clock was set back more than five minutes; then it's deleted, leaving a notice. While a copy is served, the server process checks once a minute. When the copy is due, the HTTP server stops taking connections (`stopAccepting`) — on Android, a closed socket keeps listening until a blocked `accept()` returns, so a connection arriving just after is closed at once, rather than served — downloads under way finish, for up to 10 minutes, and then the copy is deleted, and the main process told, so the notification says why the server stopped. The same rule runs whenever the app looks at the copy — Manage Server coming to the front, **Serve this store**, **Start** — so an expired copy is never shown as servable, nor served again. Importing a copy restarts the clock at the current time: the rule exists to stop a seller extending a copy they already have, and a clock once set too far ahead — wrong after a reboot, say, then corrected — mustn't condemn every copy imported later. The expiry clock keeps its latest time in `files/share/latest-time`, outside the imported folder, so it outlives copies. +- **Screen 8,** *A store has expired*, is a panel at the top of Manage Server, until the seller taps **OK**: *Your copy of Top Android apps has expired, and has been deleted from this phone. Buyers can no longer open it. To serve it again, ask its owner for a new copy.* Its notice is `files/imported/expired-notice.json`, holding only the store's name, which importing a new copy removes. +- **A clock set back looks exactly like an ordinary expiry,** to the seller and in the log: the same words on screen 8, no date, since a date would read wrongly for a copy that went early, the same log line, and nothing in the notice or the help about the clock. A message would only teach someone how the rule works. +- **Clocks.** Expiry uses Android's universal time, so time zones and daylight saving don't affect it. The server remembers the latest time it has seen. A clock set back by up to five minutes — an ordinary correction — is accepted. A larger jump backwards expires the store at once, and its content is deleted immediately — if it has a date. The check runs when Manage Server opens and while the copy is served, so a copy on a stopped server is deleted when the app is next opened. A copy that never expires has no date to extend, so the rule spares it. A clock can still be set back gradually, five minutes at a time, so this deters rather than prevents. + +## E.6 Updating, replacing and recovering + +- **A newer copy from the same store replaces the older one,** and takes the new copy's expiry, so the owner can extend a copy by sharing again. +- **An older copy than the one there asks first.** +- **A different store** — including the same owner's, after a new key — asks before replacing the seller's copy, since a phone holds at most one. +- **Publishing on a phone that holds a copy.** An owner can stop serving their own store, then import a copy. When they next publish from Code On The Go, their own store is served, not the copy, without asking. The copy is kept, not deleted: it still expires on its date, and if the owner stops serving their own store again, Manage server offers to serve the copy. +- **A lost key** — the owner's phone reset, say — needs no recovery: the owner reinstalls the server, which makes a new key, and so a new store identity. Existing copies keep working until they expire. + +## E.7 Open decisions + +None. Before building, the transfer protocol should have its independent review (E.3). + +## E.8 The sound handshake + +Built. A phone whose camera is broken can't scan the QR code, and typing a code is slow, so the sharing phone can also play the code as sound, and the other phone can listen for it. Sound carries only the handshake: the copy still goes over Wi-Fi, and a person still taps **Allow**. + +- **The owner's phone.** The share screen has **Play sound** under the typed code. While it plays, the button reads **Stop sound**, and a line counts the attempts left: *Playing sound... (N attempts remaining)*. **Stop sound** stops it at once, and it stops by itself when a phone connects. If the media volume is muted or under a third of full, a message says so, since the other phone probably won't hear it. +- **The new seller's phone.** The import screen has **Listen**. The first time, Android asks to allow the microphone. Listening shows a countdown from 30 seconds, a **Microphone level** meter, which is empty when quiet and rises with any sound, and one of *Nothing heard yet.*, *Hearing something faint: hold the phones closer.* or *Hearing the tones.* A code heard starts the import by itself, with the phone's name and a check code, exactly as typing the code would. After 30 seconds without one, it says *Didn't hear the code. Hold the phones closer, ask the owner to turn up the media volume, and try again.* Tapping **Listen** three times quickly runs a self-test, in which the phone plays and listens to its own tones. +- **What the tones carry** (`SoundPayload`, about 46 bytes for the owner's own hotspot and 14 to 30 for other Wi-Fi): a version and flags (1 byte), the share code (5 bytes, 8 characters of 5 bits each), the owner's address and port when known (6 bytes), the network's name, and a CRC-16 (2 bytes). For the owner's **own hotspot** only, it also carries the hotspot's password, since a phone can't join without it. On other Wi-Fi it carries the network's name and **never** a password. The password is never logged: `toString()` leaves it out, and the log says *password received, not logged*. +- **How it sounds** (`SoundModem`). One burst is a rising sweep (2400 to 4800 Hz, 150 ms, the start signal), a 20 ms gap, a 3-byte header, then the data. Each byte is two tones, high 4 bits first, each one of 16 and held for 30 ms with soft edges so it doesn't click. Even and odd tones use separate, interleaved sets of 16 frequencies, so a room's echo of one tone can't pass for the next, and all 32 lie between 2400 and 4725 Hz, within one octave, so a distorting speaker's harmonics fall above them. A round is three bursts, one per *repeat*, each scrambled with its own key (the header isn't), so a value sent on a weak or noisy frequency in one repeat goes out on another in the next. A 100 ms pause separates bursts. +- **How long it plays** (`SoundModem.burstsFor`). As many bursts as fit in 30 seconds (`SoundModem.WINDOW_MS`), but at least four, so a listener that joins in the middle of a burst still hears three whole ones to combine. A short code gets dozens; a hotspot's name and password, whose bursts last about 7 seconds, get four. The attempts counter counts bursts from the speaker's own position (`AudioTrack.playbackHeadPosition`), so it follows what is actually heard. A listener listens for at most 30 seconds too. +- **Hearing** (`SoundDecoder`). The listener finds the sweep, reads the header, and combines up to three bursts symbol by symbol, so a damaged burst can be repaired by the others. A candidate is accepted only if its CRC passes. +- **After the code is heard.** The listening phone checks, for about 2 seconds, whether it can reach the owner's phone on its Wi-Fi. If it can, or the tones carry no hotspot password, the import starts. Otherwise, on Android 10 and later, Android asks to join the owner's own hotspot, and a person taps **Connect** within 30 seconds; the phone leaves that hotspot when the import ends. Android asks only the first time a phone joins a hotspot of that name, so to see the prompt again, change the name under **Wi-Fi Direct hotspot**. On Android 9, or with no tap, the import screen shows the hotspot's name and password to join by hand, then **Continue**. +- **The microphone.** Only the import screen (or MCP's `import_listen`, while MCP control's service holds the microphone type) listens, and it stops when the screen closes, so nothing listens off screen. If the permission is refused, the screen says to scan the owner's code or type it instead, and typing still works. +- **Logged.** `[sound]` lines in the access log: tones played, with how many bursts of how many; a code heard; joining the owner's hotspot, with its name and never its password; letting it go; and *can't listen* when the microphone isn't available. +- **Tests and QA.** `SoundModemTest`, `SoundPayloadTest`, `SoundLevelTest` and `SoundLogTest`; QA steps section M. diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/1-owner-manage-server.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/1-owner-manage-server.png new file mode 100644 index 000000000..7cc737773 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/1-owner-manage-server.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/2-owner-share-code.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/2-owner-share-code.png new file mode 100644 index 000000000..f62899580 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/2-owner-share-code.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/3-owner-allow-copy.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/3-owner-allow-copy.png new file mode 100644 index 000000000..60bb1e0dd Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/3-owner-allow-copy.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/4-seller-manage-server.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/4-seller-manage-server.png new file mode 100644 index 000000000..f45a91144 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/4-seller-manage-server.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/4b-seller-cant-import.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/4b-seller-cant-import.png new file mode 100644 index 000000000..b31e05d35 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/4b-seller-cant-import.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/5-seller-import.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/5-seller-import.png new file mode 100644 index 000000000..5bb506e5b Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/5-seller-import.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/6-seller-importing.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/6-seller-importing.png new file mode 100644 index 000000000..60497dd09 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/6-seller-importing.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/6b-seller-import-finished.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/6b-seller-import-finished.png new file mode 100644 index 000000000..1348d7f2c Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/6b-seller-import-finished.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/7-seller-serving-copy.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/7-seller-serving-copy.png new file mode 100644 index 000000000..b7ba207e1 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/7-seller-serving-copy.png differ diff --git a/plugins/Share-Your-Apps/docs/store-sharing-screens/8-seller-expired.png b/plugins/Share-Your-Apps/docs/store-sharing-screens/8-seller-expired.png new file mode 100644 index 000000000..e17b380f5 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/store-sharing-screens/8-seller-expired.png differ diff --git a/plugins/Share-Your-Apps/docs/tester-guide/README.md b/plugins/Share-Your-Apps/docs/tester-guide/README.md new file mode 100644 index 000000000..2a4538aec --- /dev/null +++ b/plugins/Share-Your-Apps/docs/tester-guide/README.md @@ -0,0 +1,10 @@ +# Tester guide + +`build_guide.py` builds `share-your-apps-tester-guide.pdf`, the one-page guide attached to ADFA-6207 for testers, in the store's look. + +``` +pip install reportlab +python3 build_guide.py +``` + +The PDF is written beside the script, or to the path given as its argument. It's a build output, so attach it to the ticket or release rather than committing it. The guide's text is in the script; after changing it, check the guide still fits on one page. diff --git a/plugins/Share-Your-Apps/docs/tester-guide/build_guide.py b/plugins/Share-Your-Apps/docs/tester-guide/build_guide.py new file mode 100644 index 000000000..534333371 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/tester-guide/build_guide.py @@ -0,0 +1,73 @@ +"""Builds share-your-apps-tester-guide.pdf: one page, in the store's look. + +Usage: python3 build_guide.py [output.pdf] (default: share-your-apps-tester-guide.pdf beside this script) +Needs reportlab: pip install reportlab +""" +import os, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "share-your-apps-tester-guide.pdf") +from reportlab.lib.pagesizes import letter +from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, ListFlowable, ListItem, KeepTogether, PageBreak +from reportlab.lib.styles import ParagraphStyle +from reportlab.lib import colors +from reportlab.lib.units import inch +INK=colors.HexColor('#2B1B3D'); TEAL=colors.HexColor('#0B6E6E'); RED=colors.HexColor('#FF4F3A'); CREAM=colors.HexColor('#FFF3D6'); MUTED=colors.HexColor('#5B5068') +body=ParagraphStyle('b',fontName='Helvetica',fontSize=9.1,leading=11.6,textColor=INK,spaceAfter=2.5) +h2=ParagraphStyle('h2',fontName='Helvetica-Bold',fontSize=11.5,leading=13.5,textColor=TEAL,spaceBefore=6,spaceAfter=2.5) +small=ParagraphStyle('s',parent=body,fontSize=8.2,leading=10.2,textColor=MUTED) +def P(t,s=body): return Paragraph(t,s) +def bullets(items, numbered=False): + return ListFlowable([ListItem(P(i),leftIndent=11,value=(n+1 if numbered else None)) for n,i in enumerate(items)], + bulletType='1' if numbered else 'bullet', start=1 if numbered else None, leftIndent=13, bulletFontSize=7.5 if not numbered else 9.1, + bulletColor=RED if not numbered else INK, bulletFontName='Helvetica-Bold' if numbered else 'Helvetica') +title=ParagraphStyle('t',fontName='Helvetica-Bold',fontSize=19,leading=22,textColor=colors.white) +sub=ParagraphStyle('st',fontName='Helvetica',fontSize=10,leading=13,textColor=CREAM) +W=7.5*inch +head=Table([[Image(os.path.join(HERE,'octopus.png'),0.72*inch,0.72*inch),[P('Share Your Apps — tester guide',title),P('Share the apps you build in Code On The Go with people nearby. No internet or accounts needed.',sub)]]],colWidths=[0.95*inch,W-0.95*inch]) +head.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),TEAL),('VALIGN',(0,0),(-1,-1),'MIDDLE'),('LEFTPADDING',(0,0),(-1,-1),10),('RIGHTPADDING',(0,0),(-1,-1),10),('TOPPADDING',(0,0),(-1,-1),8),('BOTTOMPADDING',(0,0),(-1,-1),8)])) +aw=Table([['']*20],colWidths=[W/20]*20,rowHeights=[7]) +aw.setStyle(TableStyle([('BACKGROUND',(i,0),(i,0),RED if i%2==0 else CREAM) for i in range(20)]+[('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(-1,-1),0)])) +s=[aw,head,Spacer(1,6), + P('Share Your Apps has two parts: the Share Your Apps plugin, which you install in Code On The Go, and the Share Your Apps Server app, which the plugin installs for you. People nearby open your store in their phone\'s browser, and download your APK, your source, or both.'), + P('You\'ll need: Android 9 or later, Code On The Go, and an app you\'ve built at least once, so it has an APK.'), + P('1. Install the plugin',h2), + bullets(['Download the .cgp file attached to ticket ADFA-6207.','In Code On The Go, open the Addons Manager. Uninstall any earlier Share Your Apps plugin, then install that file, and activate the plugin.','A Share Your Apps tab appears.'],True), + P('2. Make your store',h2), + bullets(['Enter a store name. The description and header image are optional.', + 'Tap + Add product, then Choose its project and its APK. Tick Publish the source to share the source code too; build output and signing files are left out automatically.', + 'Descriptions are written in HTML. If a tag is opened but never closed, or similar, a red warning appears under the field. It won\'t stop you publishing.', + 'A PIN of up to 6 digits is optional. Buyers enter it before they can see the store.', + 'Long-press any heading or button for help, then + See more for more, and a page.']), + P('Everything saves as you type, but buyers only see changes after you publish.'), + P('3. Publish',h2), + P('Tap Publish. The first time, Android asks you to allow three things; allow each one:'), + bullets(['Code On The Go installing apps — needed once, to install Share Your Apps Server.','All files access for Share Your Apps Server — so it can read your store.','Nearby devices — asked only when the server needs to start its own hotspot: no Wi-Fi, and no Mobile hotspot.'],True), + P('It ends with Published … files verified. If a product has nothing to download, the message names it as Left out, and says why.'), + P('4. Let buyers in',h2), + P('Open the Share Your Apps Server app and tap Show QR codes for buyers. Buyers scan the first code to join the network, then the second to open the store.'), + bullets(['On Wi-Fi: buyers must be on the same network. To show a join code, type your Wi-Fi password on that screen. It\'s never saved.', + 'Your phone\'s Mobile hotspot: if it\'s on and you\'re not on Wi-Fi, the server uses it. To show a join code, type its name and password, from Settings, on that screen. They\'re never saved.', + 'No Wi-Fi and no Mobile hotspot: the server starts a hotspot of its own, and the codes carry its name and password. With Wi-Fi switched on but not connected, it keeps the same name and password every time; with Wi-Fi off, Android picks new ones each time.']), + P('When buyers download an APK, their phone asks to allow their browser to install apps. That\'s normal for apps from outside the Play Store: allow it, then turn it off again afterwards. Some Samsung phones also need Auto Blocker turned off first; it turns itself back on.'), + P('On a hotspot, which has no internet, a buyer\'s phone may try mobile data instead. If a buyer can\'t open the store, have them turn on airplane mode, then turn Wi-Fi back on — and to turn airplane mode off afterwards.'), + PageBreak(), + P('5. Share your store with another seller',h2), + P('Someone nearby can serve a copy of your store from their own phone, so it reaches buyers where you aren\'t. They don\'t need Code On The Go.'), + bullets(['On your phone: Share Your Apps Server → Manage server → Share this store…', + 'If their phone doesn\'t have Share Your Apps Server, they scan the small QR code with its camera, and install the app it downloads.', + 'They scan the large QR code with the camera and open the link — or, in Share Your Apps Server, tap Import a store… and type the code.', + 'Check that both phones show the same four digits. Choose when their copy expires, and tap Allow.', + 'They tap Serve it now, with a PIN of their own if they like.'], numbered=True), + P('Their copy is served exactly as you published it: they can\'t change it, or pass it on. It\'s deleted from their phone on the date you chose. To give them a newer version, share again.'), + P('Both phones must be on the same Wi-Fi network, or theirs on your hotspot. A phone that\'s serving a store can\'t import one: stop serving it first.',small), + P('Good to know',h2), + bullets(['The PIN keeps casual visitors out, but isn\'t real security. The store doesn\'t use encryption, so anyone on the same network could see what\'s sent.', + 'Battery: under When to run in Share Your Apps Server, Pause when the screen turns off saves battery. The server and its hotspot pause while the screen is off, and resume when you unlock the phone.', + 'Hotspot name and password: if you change them, buyers who joined before must join again.']), + KeepTogether([P('Reporting a problem',h2), + P('Add a comment to ADFA-6207 with what you did, what you expected, and what happened instead; a screenshot if possible; and the logs — in Share Your Apps Server, tap Export logs.'), + P('The logs include buyers\' network addresses and browser names, so only share them on the ticket.',small)]), +] +doc=SimpleDocTemplate(OUT,pagesize=letter,leftMargin=0.5*inch,rightMargin=0.5*inch,topMargin=0.4*inch,bottomMargin=0.4*inch, + title='Share Your Apps — tester guide',author='App Dev for All',subject='ADFA-6207') +doc.build(s) diff --git a/plugins/Share-Your-Apps/docs/tester-guide/octopus.png b/plugins/Share-Your-Apps/docs/tester-guide/octopus.png new file mode 100644 index 000000000..295ab8809 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/tester-guide/octopus.png differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/build_user_guides.py b/plugins/Share-Your-Apps/docs/user-guides/build_user_guides.py new file mode 100644 index 000000000..0c7072c6d --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/build_user_guides.py @@ -0,0 +1,520 @@ +"""Builds Share Your Apps's three user guides, as PDFs, in the store's look: + + share-your-apps-plugin-guide.pdf — for owners: the Share Your Apps plugin in Code On The Go + share-your-apps-server-guide.pdf — for owners: the Share Your Apps Server app + serving-an-imported-store.pdf — for a seller who imported a copy of someone's store + +Usage: python3 build_user_guides.py [output folder] PDFs (default: beside this script) + python3 build_user_guides.py --markdown [output folder] Markdown, for importing into Help+Manual + python3 build_user_guides.py --shot-list [output folder] screenshot-list.pdf: every screen to capture +Needs reportlab: pip install reportlab + +Versions and the date: each guide says which versions it describes, and when it was published. The +builder reads the versions from the projects — the plugin's versionName from ../../build.gradle.kts, +and the server app's versionCode from ../../../Share Your Apps Server/app/build.gradle.kts, whose version +is 1.0. — and the date is the day it runs. To set any of them yourself: + --plugin-version 1.0.0 --server-version 1.0.57 --date 2026-09-27 + +Appendix A: if pebble-book.pdf — the Pebble project's documentation, from +https://pebbletemplates.io/wiki/book.pdf — is beside this script, the plugin guide gets it, unchanged, as +Appendix A, after a cover page, and its templates section refers to it. Without the file, neither appears. +Appending it needs pypdf: pip install pypdf + +The Markdown is made from the same text as the PDFs, so the two never differ. It's laid out as +Help+Manual imports Markdown: one folder per guide, which becomes a chapter, holding one file per +section, which becomes a topic. Files are numbered, so they sort in reading order. +""" +import os, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +import re, datetime +MARKDOWN = "--markdown" in sys.argv +SHOT_LIST = "--shot-list" in sys.argv +OPTS, ARGS, _argv = {}, [], sys.argv[1:] +while _argv: + a = _argv.pop(0) + if a in ("--markdown", "--shot-list"): continue + if a.startswith("--") and _argv: OPTS[a[2:]] = _argv.pop(0) + else: ARGS.append(a) +OUTDIR = ARGS[0] if ARGS else HERE + +def _read(path, pattern): + try: + m = re.search(pattern, open(path, encoding="utf-8").read()); return m.group(1) if m else None + except OSError: return None +PLUGIN_VERSION = OPTS.get("plugin-version") or _read(os.path.join(HERE, "..", "..", "build.gradle.kts"), r'versionName\s*=\s*"([^"$]+)"') or "unknown" +_code = _read(os.path.join(HERE, "..", "..", "..", "Share Your Apps Server", "app", "build.gradle.kts"), r"versionCode\s*=\s*(\d+)") +SERVER_VERSION = OPTS.get("server-version") or (f"1.0.{_code}" if _code else "unknown") +PUBLISHED = datetime.date.fromisoformat(OPTS["date"]) if "date" in OPTS else datetime.date.today() +PUBLISHED_TEXT = PUBLISHED.strftime("%B ") + str(PUBLISHED.day) + PUBLISHED.strftime(", %Y") +STAMP = f"For Share Your Apps {PLUGIN_VERSION} and Share Your Apps Server {SERVER_VERSION} · Published {PUBLISHED_TEXT}" +from reportlab.lib.pagesizes import letter +from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, ListFlowable, + ListItem, KeepTogether) +from reportlab.lib.styles import ParagraphStyle +from reportlab.lib import colors +from reportlab.lib.units import inch + +INK = colors.HexColor('#2B1B3D'); TEAL = colors.HexColor('#0B6E6E'); RED = colors.HexColor('#FF4F3A') +CREAM = colors.HexColor('#FFF3D6'); MUTED = colors.HexColor('#5B5068') +body = ParagraphStyle('b', fontName='Helvetica', fontSize=10, leading=13.4, textColor=INK, spaceAfter=4) +h1 = ParagraphStyle('h1', fontName='Helvetica-Bold', fontSize=14, leading=17, textColor=TEAL, spaceBefore=10, spaceAfter=4, keepWithNext=1) +h2 = ParagraphStyle('h2', fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=INK, spaceBefore=6, spaceAfter=2, keepWithNext=1) +small = ParagraphStyle('s', parent=body, fontSize=9, leading=12, textColor=MUTED) +title = ParagraphStyle('t', fontName='Helvetica-Bold', fontSize=20, leading=24, textColor=colors.white) +sub = ParagraphStyle('st', fontName='Helvetica', fontSize=10.5, leading=14, textColor=CREAM) +W = 7.5 * inch + +def P(t, s=body): return Paragraph(t, s) +def H1(t): return P(t, h1) +def H2(t): return P(t, h2) +def bullets(items, numbered=False): + return ListFlowable([ListItem(P(i), leftIndent=12, value=(n + 1 if numbered else None)) for n, i in enumerate(items)], + bulletType='1' if numbered else 'bullet', start=1 if numbered else None, leftIndent=14, + bulletFontSize=8 if not numbered else 10, bulletColor=RED if not numbered else INK, + bulletFontName='Helvetica-Bold' if numbered else 'Helvetica', spaceAfter=4) +def tip(t): + """A note that matters, in a cream box.""" + box = Table([[P(t)]], colWidths=[W]) + box.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), CREAM), ('BOX', (0, 0), (-1, -1), 0.8, RED), + ('LEFTPADDING', (0, 0), (-1, -1), 8), ('RIGHTPADDING', (0, 0), (-1, -1), 8), + ('TOPPADDING', (0, 0), (-1, -1), 5), ('BOTTOMPADDING', (0, 0), (-1, -1), 3)])) + return KeepTogether([Spacer(1, 3), box, Spacer(1, 5)]) +# ------------------------------------------------------------------ figures: screens with numbered callouts +import json +SCREENS = os.path.join(HERE, "screens") +try: SHOTS = json.load(open(os.path.join(SCREENS, "shots.json"), encoding="utf-8")) +except OSError: SHOTS = [] +keynum = ParagraphStyle('kn', parent=body, fontSize=9.5, leading=12.5) +caption = ParagraphStyle('cap', parent=body, fontName='Helvetica-Bold', fontSize=9.5, leading=12.5, spaceAfter=5) + +class Fig(KeepTogether): + """A screen with its callouts, and its key beside it: numbers in red, matching the picture's badges.""" + def __init__(self, shot, frame=True): + self.shot = shot + from PIL import Image as PILImage + path = screen_file(shot) + w, h = PILImage.open(path).size + iw = 2.3 * inch; ih = iw * h / w + if ih > 4.6 * inch: ih = 4.6 * inch; iw = ih * w / h + key = [P(f"Figure {shot['id']} · {shot['title']}", caption)] + key += [P(f'{n}  {t}', keynum) for n, t in shot["key"]] + t = Table([[Image(path, iw, ih), key]], colWidths=[iw + 0.25 * inch, W - iw - 0.25 * inch]) + t.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0)] + + ([('BOX', (0, 0), (0, 0), 0.5, FRAME)] if FRAMES and frame and light_edges(path) else []))) + KeepTogether.__init__(self, [Spacer(1, 4), t, Spacer(1, 8)]) + +def screen_file(shot): + """A real screenshot, as .jpg, if there is one; otherwise the drawing, as .png.""" + for ext in (".jpg", ".png"): + f = os.path.join(SCREENS, shot["id"] + ext) + if os.path.exists(f): return f + raise FileNotFoundError(shot["id"]) + +def light_edges(path): + """Whether a picture's edges are light, so it needs a frame to stand out from the white page.""" + from PIL import Image as PILImage, ImageStat + im = PILImage.open(path).convert('L'); w, h = im.size; e = max(w // 40, 4) + # The sides only, between the phone's status bar and navigation bar, which are dark on every screen. + strips = [im.crop((0, h // 10, e, h * 9 // 10)), im.crop((w - e, h // 10, w, h * 9 // 10))] + return sum(ImageStat.Stat(x).mean[0] for x in strips) / len(strips) > 150 + +FRAME = colors.HexColor('#C8C3CF') +FRAMES = False # no picture has a frame, in any guide or the screenshot list + +def with_figures(story, guide): + """Each guide's figures, at the end of the part they illustrate: before the next heading after theirs.""" + shots = [x for x in SHOTS if x["guide"] == guide] + out, current = [], None + def flush(): + for x in shots: + if x["section"] == current: out.append(Fig(x)) + for f in story: + if isinstance(f, Paragraph) and f.style in (h1, h2): + flush(); current = md_text(f.text) + out.append(f) + flush() + return out + +def header(name, subtitle): + aw = Table([[''] * 20], colWidths=[W / 20] * 20, rowHeights=[7]) + aw.setStyle(TableStyle([('BACKGROUND', (i, 0), (i, 0), RED if i % 2 == 0 else CREAM) for i in range(20)] + + [('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0)])) + stamp = ParagraphStyle('stamp', parent=sub, fontSize=8.5, leading=11, spaceBefore=3) + head = Table([[Image(os.path.join(HERE, 'octopus.png'), 0.72 * inch, 0.72 * inch), [P(name, title), P(subtitle, sub), P(STAMP, stamp)]]], + colWidths=[0.95 * inch, W - 0.95 * inch]) + head.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), TEAL), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), + ('LEFTPADDING', (0, 0), (-1, -1), 10), ('RIGHTPADDING', (0, 0), (-1, -1), 10), + ('TOPPADDING', (0, 0), (-1, -1), 8), ('BOTTOMPADDING', (0, 0), (-1, -1), 8)])) + return [aw, head, Spacer(1, 8)] + +def build(filename, name, subtitle, story): + def footer(canvas, doc): + canvas.saveState(); canvas.setFont('Helvetica', 8.5); canvas.setFillColor(MUTED) + canvas.drawString(0.5 * inch, 0.35 * inch, f"{name} · Share Your Apps {PLUGIN_VERSION} · {PUBLISHED_TEXT}") + canvas.drawRightString(8.0 * inch, 0.35 * inch, f"Page {doc.page}") + canvas.restoreState() + out = os.path.join(OUTDIR, filename) + appendix = os.path.join(HERE, 'pebble-book.pdf') if filename == 'share-your-apps-plugin-guide.pdf' else None + doc = SimpleDocTemplate(out, pagesize=letter, leftMargin=0.5 * inch, rightMargin=0.5 * inch, topMargin=0.45 * inch, + bottomMargin=0.6 * inch, title=f"{name}, {PLUGIN_VERSION}", author='App Dev for All', subject=STAMP) + doc.build(header(name, subtitle) + story, onFirstPage=footer, onLaterPages=footer) + if appendix and os.path.exists(appendix): add_appendix(out, name, appendix) + return out + +def add_appendix(out, name, book): + """Appends Pebble's documentation, unchanged, after a cover page saying what it is and whose it is.""" + from pypdf import PdfReader, PdfWriter + cover = out + '.cover.pdf' + first = len(PdfReader(out).pages) + 1 # the cover's page number, continuing the guide's + def footer(canvas, doc): + canvas.saveState(); canvas.setFont('Helvetica', 8.5); canvas.setFillColor(MUTED) + canvas.drawString(0.5 * inch, 0.35 * inch, f"{name} · Share Your Apps {PLUGIN_VERSION} · {PUBLISHED_TEXT}") + canvas.drawRightString(8.0 * inch, 0.35 * inch, f"Page {first}") + canvas.restoreState() + doc = SimpleDocTemplate(cover, pagesize=letter, leftMargin=0.5 * inch, rightMargin=0.5 * inch, topMargin=0.45 * inch, bottomMargin=0.6 * inch) + pages = len(PdfReader(book).pages) + doc.build(header('Appendix A — Pebble documentation', 'The template language the store page is made from.') + [ + P('The %d pages that follow are the Pebble project\'s own documentation of its template language — every tag, filter, function, test and operator — ' + 'as published at https://pebbletemplates.io/wiki/book.pdf. They\'re included unchanged, so they can be read without internet.' % pages), + P('Share Your Apps uses Pebble to make the store page. Its templates can use everything described here, apart from the parts about setting up Pebble ' + 'in a Java program, or with Spring, which Share Your Apps does for you. Share Your Apps adds a few functions and filters of its own, and the blocks of ' + 'its default template, which are described in Changing the store\'s look.'), + P('This appendix is the Pebble project\'s work, not App Dev for All\'s. See https://pebbletemplates.io for its copyright and licence.', small)], + onFirstPage=footer) + w = PdfWriter() + for f in (out, cover, book): + for pg in PdfReader(f).pages: w.add_page(pg) + with open(out, 'wb') as fh: w.write(fh) + os.remove(cover) + +# ------------------------------------------------------------------ 1. The plugin +plugin = [ + P('Share Your Apps shares the apps you build in Code On The Go with people nearby — no internet, and no accounts. It has two parts:'), + bullets(['The Share Your Apps plugin, in Code On The Go, where you describe your apps and publish them. This guide is about the plugin.', + 'The Share Your Apps Server app, which the plugin installs for you. It serves your store over Wi-Fi or a hotspot, and people open it in their phone\'s browser. It has its own guide.']), + P('You\'ll need: Android 9 or later, Code On The Go, and an app you\'ve built at least once, so it has an APK.'), + + H1('Installing the plugin'), + bullets(['Get the plugin\'s .cgp file.', + 'In Code On The Go, open the Addons Manager, install that file, and activate the plugin.', + 'A Share Your Apps tab appears. Everything below happens there.'], True), + + H1('Your store'), + P('The tab is in three parts: Store, Products and Advanced. Changes are saved as you make them; there\'s nothing to save by hand.'), + H2('Store name'), P('The name at the top of the store page, and in its browser tab.'), + H2('Store description'), P('Optional text under the name, written in HTML. If a tag is opened but never closed, or similar, a red warning appears under the field. It won\'t stop you publishing, but it may spoil the page\'s layout.'), + H2('Header image'), P('An optional picture or short video across the top of the page. Change picks one; Default puts back the built-in header. A video shows a still frame, and plays when a buyer taps it, so buyers don\'t each download it on every visit.'), + H2('PIN'), P('Up to 6 digits that buyers enter before reaching the store, or leave it empty for none. It keeps casual visitors out, but it isn\'t real security: the store doesn\'t use encryption, so someone on the same network could see what\'s sent.'), + + H1('Products'), + P('Each product is one of your apps. + Add product adds one at the end of the list. Tap a product\'s card to open it.'), + H2('Name'), P('The product\'s name, as buyers see it. It also names its downloads, such as todo-app.apk; a second product of the same name gets todo-app-2.'), + H2('Project and APK'), P('Project is the Code On The Go project the product comes from. APK is the installable app buyers download, chosen from the project\'s builds, newest first. The list marks builds that aren\'t signed: buyers can\'t install those, so choose a signed one.'), + H2('What to publish'), P('Publish the APK and Publish the source choose what buyers can download: the app, the project\'s source code as a zip, or both. A product with nothing to download is left out of the store, and its card says draft: not published.'), + H2('Pictures and video'), P('+ Add media adds pictures, videos or sounds, which buyers swipe through on the product\'s card. Beside each one:'), + bullets(['Describe says what it shows, for visually-impaired people, whose screen readers read it aloud in the picture\'s place. Say what matters for choosing the app — The chat screen, with two messages — not what kind of item it is.', + 'For a video, Describe can also add captions, for people who can\'t hear it: Choose captions file picks a WebVTT file, ending .vtt.', + 'Remove takes it out of the product, with its description and captions. The file itself stays on your phone.']), + H2('Description and Extra JSON'), P('Description is what buyers read about the product, in HTML. Extra JSON holds optional details in JSON: whatsNew, license, author and website appear on the product\'s card.'), + H2('Order, and removing a product'), P('Move up and Move down set the order buyers see. Remove takes a product out of the store at your next publish, after asking.'), + + H1('Publishing'), + P('Tap Publish. A dialog asks you to confirm, saying how many products the store will have, and which are left out. Tap Publish in it to go ahead, or Cancel to change nothing.'), + P('The first time, Android asks you to allow three things. Allow each one:'), + bullets(['Code On The Go installing apps — needed once, to install Share Your Apps Server.', + 'All files access for Share Your Apps Server — so it can read your store\'s files.', + 'Nearby devices — asked only when the server needs to start its own hotspot: no Wi-Fi, and no Mobile hotspot.'], True), + P('Publishing checks every file it needs, builds a new copy of the store beside the old one, installs or updates Share Your Apps Server if needed, then starts it on the new copy and checks every file it serves. Until the new store is ready, buyers keep the old one — unless Share Your Apps Server is being updated, which stops it briefly.'), + H2('What the messages mean'), + bullets(['Published … files verified: buyers can use the store now.', + 'Left out: products with nothing to download, and why.', + 'Notes: things to fix that don\'t stop a publish, such as an unsigned APK.', + 'Couldn\'t publish: nothing changed. The store still serves its previous version. The message says why.']), + + H1('Letting buyers in'), + P('Open the Share Your Apps Server app, and tap Show QR codes for buyers. Buyers scan the codes with their phone\'s camera: on a hotspot, the first joins its network, and the second opens the store. The Share Your Apps Server guide covers networks, hotspots and PINs in detail.'), + tip('When buyers download an APK, their phone asks them to allow their browser to install apps. That\'s normal for apps from outside the Play Store: they allow it, then can turn it off again afterwards. Some Samsung phones also need Auto Blocker turned off first.'), + + H1('Changing the store\'s look'), + P('The store page is made from a template. The built-in one suits most stores. Under Advanced:'), + bullets(['Choose a template file picks another template, such as the alternatives that come with Share Your Apps: Neon Arcade, Morning Edition, Aurora Deck and Clear Access.', + 'Load the default template puts the built-in one in the Template override field, to start editing from, or to go back to it.', + 'Extra JSON, for the whole store, holds settings templates use: announcement, a line above the products; accent, a colour; contact, your name, email, phone and web address, shown at the foot of the page so buyers can reach you; and lang, the page\'s language.']), + P('Every publish also makes an accessible version of the store page, plain and in large text, which every other template links to from its top left.'), + P('If you know a little Pebble, the template language, a template of your own can extend the built-in one and replace just one part — the header, each product\'s card, its download buttons, or the footer. Pieces shared between templates go in the folder CodeOnTheGoProjects/ShareYourAppsTemplates. The README beside the alternative templates explains how, with examples.' + + (' Pebble\'s own documentation, explaining every tag, filter and function, is Appendix A of this guide.' if os.path.exists(os.path.join(HERE, 'pebble-book.pdf')) else ''), small), + + H1('Sharing your store with another seller'), + P('Someone nearby can serve a copy of your store from their own phone, so it reaches people where you aren\'t. You do this in the Share Your Apps Server app, with Share this store…: its guide explains how. To give them a newer version later, publish, then share again.'), + + H1('Getting help'), + P('Long-press any heading, button or checkbox for a short explanation. + See more gives more, with a button that opens a help page. Code On The Go adds a note to each that it comes from a plugin. Long-pressing a text field selects its text, as usual; its heading has the help.'), + H2('If something goes wrong'), + bullets(['Couldn\'t publish: read the message; it says what\'s missing, such as a file that\'s been moved. Nothing changed, so buyers still have the previous store.', + 'A buyer can\'t install an app: check its APK isn\'t marked unsigned, and see the tip under Letting buyers in.', + 'A buyer can\'t open the store: see the Share Your Apps Server guide.']), +] + +# ------------------------------------------------------------------ 2. The server app +server = [ + P('Share Your Apps Server serves the store you publish with the Share Your Apps plugin, over Wi-Fi or a hotspot. People nearby open it in their phone\'s browser. The plugin installs and starts it for you, so you only open it to let buyers in, check on it, share your store, or change how it runs.'), + P('Open it from your phone\'s app list. Everything below is on its Manage server screen, unless it says otherwise.'), + + H1('Status'), + P('The Status panel says whether the server is serving, and which store. While it serves, it shows the store\'s address, with a button that copies it. The line below says what Start will serve.'), + P('If Grant storage access shows, tap it and allow access, once: the server needs it to read your store\'s files.'), + + H1('Starting and stopping'), + P('Publishing from the plugin starts the server for you. In the Server panel:'), + bullets(['Start serves the last store you published.', + 'Stop stops serving. Downloads under way end.', + 'Port is the number in the store\'s address, 6175 unless you change it. Change it only if another app already uses that port.', + 'Help opens the help pages.']), + + H1('Letting buyers in'), + P('Tap Show QR codes for buyers. Buyers scan the codes with their phone\'s camera:'), + bullets(['On a hotspot, the first code joins its network, and the second opens the store.', + 'On ordinary Wi-Fi, buyers join the same network themselves. If you type the network\'s password, the screen can show a code that joins it for them. The password is never saved.']), + P('Done closes the screen; the store keeps serving.'), + tip('A buyer\'s phone can\'t open the store? A hotspot has no internet, so their phone may try mobile data instead. Have them turn on airplane mode, then turn Wi-Fi back on — and turn airplane mode off afterwards.'), + + H1('Which network buyers use'), + bullets(['Wi-Fi: if your phone is on Wi-Fi, buyers join the same network.', + 'Your phone\'s Mobile hotspot: if it\'s on, and the phone isn\'t on Wi-Fi, the server uses it. Buyers join it with the name and password from your phone\'s Settings.', + 'A hotspot of the server\'s own: otherwise. With Wi-Fi switched on but not connected to a network, it\'s a Wi-Fi Direct hotspot, whose name and password stay the same every time. Without, it\'s Android\'s own hotspot, whose name and password change every time the server starts.']), + P('On Android 9 to 12, the server\'s own hotspot won\'t start while Location is off. If so, the server says to turn Location on, then tap Start.'), + H2('The Wi-Fi Direct hotspot\'s name and password'), + P('In the Wi-Fi Direct hotspot panel. Its name always starts DIRECT-LS-. Suggest a password fills in a strong one, and Save name & password keeps them for the next time the hotspot starts. Buyers who joined before must join again after a change.'), + + H1('The PIN'), + P('A store can have a PIN, up to 6 digits, which buyers enter before reaching it. You set it in the plugin, under Store. It keeps casual visitors out, but isn\'t real security: the store doesn\'t use encryption.'), + + H1('When to run'), + bullets(['Run always keeps serving whatever the screen does.', + 'Pause when the screen turns off saves battery. The server resumes when you unlock the phone.']), + + H1('Sharing your store with another seller'), + P('Someone nearby can serve a copy of your store from their own phone. Their copy is served exactly as you published it: they can\'t change it, or pass it on. They set their own PIN, and it\'s deleted from their phone on the date you choose.'), + bullets(['While your store is served, tap Share this store…, in the Copies of this store panel. Just after a publish, it may first say Getting the store ready to share…', + 'If their phone doesn\'t have Share Your Apps Server, they scan the small QR code with its camera, and install the app it downloads from your phone.', + 'In Share Your Apps Server, they tap Import a store…, then scan the large QR code, or type the code shown.', + 'Both phones show four digits. Check they\'re the same. Choose when their copy expires — in a week, in a month, on a date, or never — and tap Allow. If the digits differ, tap Deny.', + 'Keep the screen open until the copy has been sent.'], True), + P('Both phones must be on the same Wi-Fi network, or theirs on your hotspot. Each code works for one phone, for 10 minutes. Cancel, or leaving the screen, ends the share. To give them a newer version later, publish, then share again: their new copy replaces the old one.'), + tip('A copy isn\'t copy protection. Anything a store serves can be saved by anyone who opens it. What Share Your Apps prevents is a copy being passed on through Share Your Apps itself.'), + P('Their side is described in Serving an imported store, a short guide you can give them.', small), + + H1('Importing someone else\'s store'), + P('Your phone can serve someone else\'s store too, with their permission, in the Import a store panel. A phone that\'s serving a store can\'t import one: stop serving first. Serving an imported store explains the steps.'), + + H1('Logs'), + P('The Logs panel records buyers\' requests and what the server does, newest first. View logs shows them; Export logs sends every log file off the phone, such as to a chat or by email; Log size limit sets how large each file grows, and 0 turns logging off.'), + P('The logs include buyers\' network addresses and browser names, so share them only with people who need them. They\'re kept in the app\'s private storage, and aren\'t backed up.', small), + + H1('Getting help'), + P('Long-press any heading or button for a short explanation. + See more gives more, with a button that opens a help page. Long-pressing a text field selects its text, as usual; its label has the help. The faint i in a circle, in each explanation\'s corner, is for developers: it shows where the help text came from.'), + H2('If something goes wrong'), + bullets(['A buyer can\'t open the store: check they\'re on the same network, or joined your hotspot; then try the airplane mode tip above.', + 'The hotspot won\'t start: on Android 9 to 12, turn Location on. Otherwise, the Status panel says why.', + 'A buyer can\'t install an app: their phone must allow their browser to install apps; on some Samsung phones, Auto Blocker must be off too.', + 'Reporting a problem: say what you did and what happened, with a screenshot if you can, and send the logs with Export logs.']), +] + +# ------------------------------------------------------------------ 3. Serving an imported store +seller = [ + P('Someone has given you a copy of their app store, so you can share their apps with people near you. This guide shows you how. You don\'t need internet, or an account.'), + tip('Your copy: you can serve it to people near you, with your own PIN if you like. You can\'t change it, or pass it on to another phone. It may expire on a date the store\'s owner chose; then it\'s deleted from your phone.'), + + H1('1. Get the app'), + P('If your phone doesn\'t have Share Your Apps Server yet, the owner shows you a small QR code on their phone.'), + bullets(['Scan it with your phone\'s camera, and open the link.', + 'Your phone downloads the app. Open the download and install it. If your phone asks, allow your browser to install apps; you can turn that off again afterwards.', + 'On some Samsung phones, turn off Auto Blocker in Settings first.'], True), + P('Both phones must be on the same Wi-Fi network, or yours joined to the owner\'s hotspot.'), + + H1('2. Get the store'), + bullets(['Open Share Your Apps Server, and tap Import a store….', + 'Scan the owner\'s large QR code with your camera, and open the link. Or type the code their phone shows, such as LS-FM50-ZV7G.', + 'Tap Continue.', + 'Your phone shows four digits. The owner checks their phone shows the same, and taps Allow.', + 'Wait while the store arrives. Keep both phones close, with their screens on.', + 'When it says Imported, tap Serve it now.'], True), + P('If it stops partway, tap Try again, while the owner\'s phone still shows the code.'), + tip('Did you join the owner\'s hotspot to get the store? Before serving, leave it: join your own Wi-Fi, or turn Wi-Fi off, so your phone makes its own hotspot. The last screen reminds you.'), + + H1('3. Let people in'), + bullets(['In Share Your Apps Server, tap Show QR codes for buyers.', + 'People scan the codes with their phone\'s camera. On a hotspot, the first code joins its network, and the second opens the store.', + 'They see the store in their browser, and can download its apps.'], True), + tip('Someone\'s phone can\'t open the store? Have them turn on airplane mode, then turn Wi-Fi back on — and turn airplane mode off afterwards.'), + + H1('A PIN, if you want one'), + P('In Share Your Apps Server, the store has a panel with its name. Under Set a PIN or leave blank for no PIN, type up to 6 digits, then tap Serve this store — or, if it\'s already serving, Serve it again, with this PIN. People then enter your PIN before they reach the store.'), + + H1('Starting and stopping'), + P('Stop stops serving; Start serves the store again. To save battery, choose Pause when the screen turns off: it starts again when you unlock the phone.'), + + H1('When the store expires'), + P('When its date comes, the store is deleted from your phone, and Share Your Apps Server says A store has expired. Tap OK. To serve it again, ask its owner for a new copy.'), + P('A newer version: tap Stop, then get the store again from its owner, as in step 2. The new copy replaces the old one.'), + P('No longer need it? Tap Remove this store, in its panel.'), + + H1('Help'), + P('Long-press any heading or button in Share Your Apps Server for a short explanation, then + See more for more.'), +] + +# ------------------------------------------------------------------ Markdown, for Help+Manual +def md_text(html): + t = html.replace("\\'", "'") + t = re.sub(r"(.*?)", r"**\1**", t, flags=re.S) + t = re.sub(r"(.*?)", r"*\1*", t, flags=re.S) + t = re.sub(r"<[^>]+>", "", t) + return t.replace("&", "&").replace("<", "<").replace(">", ">").strip() + +def md_blocks(flowable): + """One flowable as Markdown: a heading, a paragraph, a list, or a note.""" + if isinstance(flowable, Paragraph): + t = md_text(flowable.text) + if flowable.style is h2: return f"## {t}" + return t + if isinstance(flowable, ListFlowable): + numbered = flowable._bulletType == '1' + items = [md_text(li._flowables[0].text) for li in flowable._flowables] + return "\n".join((f"{k + 1}. " if numbered else "- ") + it for k, it in enumerate(items)) + if isinstance(flowable, Fig): + sh = flowable.shot + return (f"![Figure {sh['id']} · {md_text(sh['title'])}]({os.path.basename(screen_file(sh))})\n\n*Figure {sh['id']} · {md_text(sh['title'])}*\n\n" + + "\n".join(f"{n}. {md_text(t)}" for n, t in sh["key"])) + if isinstance(flowable, KeepTogether): # a tip: its box holds one paragraph + box = [f for f in flowable._content if isinstance(f, Table)][0] + return "> " + md_text(box._cellvalues[0][0].text) + return None + +def safe(name): + return re.sub(r'[\\/:*?"<>|]', "", re.sub(r"^\d+\.\s*", "", name)).strip() + +def markdown(folder, name, subtitle, story, steps=False): + """A guide as a folder of topics: the introduction first, then one per section. A tutorial (steps=True) + has a topic per step instead; a section heading such as "On your phone" opens the steps that follow it.""" + d = os.path.join(OUTDIR, safe(name)); os.makedirs(d, exist_ok=True) + topics = [["Introduction", [f"*{subtitle}*", f"*{STAMP}*"]]]; group = None + for i, f in enumerate(story): + if steps and isinstance(f, Paragraph) and f.style is h1: + nxt = story[i + 1] if i + 1 < len(story) else None + if isinstance(nxt, Paragraph) and nxt.style is h2: group = md_text(f.text); continue # a group of steps + topics.append([md_text(f.text), []]); group = None; continue + if steps and isinstance(f, Paragraph) and f.style is h2: + topics.append([md_text(f.text), [f"**{group}**"] if group else []]); continue + if isinstance(f, Paragraph) and f.style is h1: topics.append([md_text(f.text), []]); continue + b = md_blocks(f) + if b: topics[-1][1].append(b) + import shutil + for f in story: + if isinstance(f, Fig): shutil.copy(screen_file(f.shot), d) + for k, (t, blocks) in enumerate(topics): + with open(os.path.join(d, f"{k:02d} {safe(t)}.md"), "w", encoding="utf-8") as out: + out.write(f"# {name if k == 0 else t}\n\n" + "\n\n".join(blocks) + "\n") + return d, len(topics) + +GUIDES = ( + ('share-your-apps-plugin-guide.pdf', 'Share Your Apps plugin — user guide', 'Describe your apps in Code On The Go, and publish them as a store for people nearby.', plugin), + ('share-your-apps-server-guide.pdf', 'Share Your Apps Server — user guide', 'Serve your store over Wi-Fi or a hotspot, let buyers in, and share it with other sellers.', server), + ('serving-an-imported-store.pdf', 'Serving an imported store', 'Share someone else\'s apps with people near you, with their permission.', seller)) +# ------------------------------------------------------------------ tutorials: one task each, step by step +def fig(i): + """A figure by its ID, placed by hand in a tutorial.""" + return Fig(next(x for x in SHOTS if x["id"] == i)) +def step(n, title, *body): + return [H2(f"Step {n}. {title}")] + [P(b) if isinstance(b, str) else b for b in body] + +tut_create = [ + P('In about ten minutes, you\'ll turn an app you\'ve built in Code On The Go into a store that people nearby can open in their phone\'s browser, and download from.'), + tip('You\'ll need: Android 9 or later, Code On The Go, the Share Your Apps plugin\'s .cgp file, and an app you\'ve built at least once, so it has an APK.'), + *step(1, 'Install the plugin', 'In Code On The Go, open the Addons Manager, choose the .cgp file, and tap Install. A Share Your Apps tab appears in the bottom panel.', fig('P01')), + *step(2, 'Name your store', 'In the Share Your Apps tab, under Store, type a Store name. Buyers see it at the top of the page. A description, a header picture and a PIN are optional; you can add them later.', fig('P02')), + *step(3, 'Add your app', 'Under Products, tap + Add product. Give it a Name, then tap Choose beside Project and pick your app\'s project, and Choose beside APK and pick its build. Leave Publish the APK ticked.', fig('P05')), + *step(4, 'Add a picture, and describe it', 'Tap + Add media and pick a screenshot of your app. Then tap Describe beside it, and say what it shows, for people who use a screen reader.', fig('P08')), + *step(5, 'Publish', 'Tap Publish. A dialog says how many products the store will have. Tap Publish in it.', fig('P11'), + 'The first time, Android asks to let Code On The Go install apps: tap Settings, and allow it. It also asks for All files access for Share Your Apps Server. Allow both; they\'re needed only once.', fig('P12')), + *step(6, 'Check the result', 'When it\'s done, the bottom of the tab says Published … files verified. Your store is ready, and Share Your Apps Server is already serving it.', fig('P13')), + H1('Next'), + P('To let people in, follow Serving your first store. To change anything, edit it in the tab and publish again: buyers keep the old version until the new one is ready.'), +] +tut_serve = [ + P('Your store is published. Now people nearby can open it: on the same Wi-Fi, or on your phone\'s hotspot when there\'s no Wi-Fi.'), + *step(1, 'Open Share Your Apps Server', 'Open Share Your Apps Server from your phone\'s app list. Status says it\'s serving your store, with its address. If it says Stopped, tap Start.', fig('S01')), + *step(2, 'Show the codes', 'Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store. On ordinary Wi-Fi, buyers join the network themselves, and scan the store\'s code.', fig('S04')), + *step(3, 'Let a buyer in', 'The buyer scans the codes with their phone\'s camera. The store opens in their browser. If you set a PIN, they type it first.', fig('B01'), + 'Each product has its pictures, its description, and its downloads. They tap Download APK, and their phone asks them to allow their browser to install apps.', fig('B02')), + tip('Their phone can\'t open the store? A hotspot has no internet, so their phone may try mobile data instead. Have them turn on airplane mode, then Wi-Fi back on — and airplane mode off afterwards.'), + *step(4, 'Choose when it runs', 'Under When to run, Run always keeps serving whatever the screen does. Pause when the screen turns off saves battery, and resumes when you unlock the phone.', fig('S07')), + *step(5, 'Stop, and start again', 'In the Server panel, Stop stops serving, and Start serves the last store you published.', fig('S03')), + H1('Next'), + P('To let someone else serve your store from their own phone, follow Sharing your first store with another phone.'), +] +tut_share = [ + P('Someone nearby can serve a copy of your store from their own phone, so it reaches people where you aren\'t. They can\'t change it or pass it on, and it\'s deleted on the date you choose. You\'ll need both phones, on the same Wi-Fi network, or theirs on your hotspot.'), + H1('On your phone'), + *step(1, 'Start the share', 'While your store is served, open Share Your Apps Server, and tap Share this store…, in Copies of this store.', fig('S08'), + 'The screen shows a large QR code, a code to type, and a smaller QR code, for a phone that doesn\'t have the app yet.', fig('S09')), + H1('On their phone'), + *step(2, 'Get the app, if needed', 'If their phone doesn\'t have Share Your Apps Server, they scan your small QR code with the camera, and download the app from your phone. Their browser warns about apps from outside the Play Store: they tap Download anyway, then install it.', fig('I01')), + *step(3, 'Ask for the copy', 'In Share Your Apps Server, they tap Import a store…. They scan your large QR code, or type the code, and tap Continue.', fig('I03')), + H1('On both phones'), + *step(4, 'Check the four digits', 'Their phone shows four digits. Yours shows Allow a copy? with the same four. Check they match: that proves you\'re sharing with the phone in front of you.', fig('I04')), + H1('On your phone'), + *step(5, 'Allow it', 'Choose when their copy expires, and tap Allow. If the digits don\'t match, tap Deny.', fig('S10')), + H1('On their phone'), + *step(6, 'Serve it', 'When it says Imported, they tap Serve it now. If they joined your hotspot to get it, they leave it first, as the screen says.', fig('I05'), + 'Their copy has a panel of its own in Manage server, where they can set their own PIN, and remove it.', fig('I07')), + H1('Next'), + P('They let people in just as you do, with Show QR codes for buyers. To give them a newer version later, publish, then share again.'), +] +TUTORIALS = ( + ('tutorial-creating-your-first-store.pdf', 'Tutorial: creating your first store', 'From an app you\'ve built to a store people nearby can open.', tut_create), + ('tutorial-serving-your-first-store.pdf', 'Tutorial: serving your first store', 'Let people nearby open your store, on Wi-Fi or your phone\'s hotspot.', tut_serve), + ('tutorial-sharing-your-first-store.pdf', 'Tutorial: sharing your first store with another phone', 'Let someone nearby serve a copy of your store from their own phone.', tut_share)) + +GUIDE_NAMES = {"plugin": "Share Your Apps plugin — user guide", "server": "Share Your Apps Server — user guide", "seller": "Serving an imported store"} + +from html import escape as _esc + +def shot_list(): + """Every screen the guides show, with how to capture the real one, so drawings can be replaced.""" + story = [ + P('The user guides show %d screens, with numbered callouts: %d real screenshots, and %d drawings, made from the apps\' code, for screens not yet captured. ' + 'The list below says how to reach each screen, and what its callouts mark, so any can be captured again.' % (len(SHOTS), sum(1 for x in SHOTS if x.get("captured")), sum(1 for x in SHOTS if not x.get("captured")))), + H2('Taking the screenshots'), + bullets(['Use a phone with Code On The Go and Share Your Apps installed, and a store published, preferably the demo store.', + 'Set the phone to the theme the drawings use: dark for the Share Your Apps tab, as Code On The Go is shown here; either for Share Your Apps Server.', + 'Capture the whole screen, in portrait, without cropping. Scroll so the items the callouts mark are on screen; a long screen can be two screenshots.', + 'Name each file by its ID, such as P05.png, and send them together. I\'ll add the callouts, and swap them into the guides.', + 'Drawn: a real screenshot is still needed marks the screens still shown as drawings.']), + ] + for guide in ("plugin", "server", "seller"): + story.append(H1(GUIDE_NAMES[guide])) + for x in [y for y in SHOTS if y["guide"] == guide]: + from PIL import Image as PILImage + path = screen_file(x); w, h = PILImage.open(path).size + iw = 1.45 * inch; ih = min(iw * h / w, 3.0 * inch); iw = ih * w / h + text = [P(f"{x['id']} · {x['title']}", caption), + P(f"In the guide under: {x['section']}", small), + P(("Real screenshot. " if x.get("captured") else "Drawn: a real screenshot is still needed. ") + f"How to get it: {_esc(x['how'])}"), + P("Callouts: " + "; ".join(f'{n} {t.rstrip(".")}' for n, t in x["key"]) + ".", keynum)] + t = Table([[Image(path, iw, ih), text]], colWidths=[iw + 0.2 * inch, W - iw - 0.2 * inch]) + t.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0)] + + ([('BOX', (0, 0), (0, 0), 0.5, FRAME)] if FRAMES and light_edges(path) else []) + [('LINEBELOW', (0, 0), (-1, -1), 0.4, colors.HexColor('#E3DEE8')), + ('BOTTOMPADDING', (0, 0), (-1, -1), 8), ('TOPPADDING', (0, 0), (-1, -1), 6)])) + story.append(KeepTogether([t])) + return build("screenshot-list.pdf", "Screenshots for the user guides", "Each screen the guides show, how to reach it, and what its callouts mark.", story) + +if SHOT_LIST: + print(shot_list()); sys.exit() + +for (f, n, st, story), guide in zip(GUIDES, ("plugin", "server", "seller")): + story = with_figures(story, guide) + if MARKDOWN: print(*markdown(f, n, st, story)) + else: print(build(f, n, st, story)) +for f, n, st, story in TUTORIALS: + if MARKDOWN: print(*markdown(f, n, st, story, steps=True)) + else: print(build(f, n, st, story)) diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/kit.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/kit.py new file mode 100644 index 000000000..edefdbd9d --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/kit.py @@ -0,0 +1,95 @@ +import os +"""Pieces for drawing Share Your Apps's screens, in each app's own look, with numbered callouts.""" +import sys, html as _h +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import server_look as S # the server app's pieces, drawn from its real screenshot +E = _h.escape + +def co(n, inner, grow=False, inline=False): + """Marks an item for callout n: the page's script outlines it, and badges it with n.""" + disp = 'inline-block' if inline else 'block' + return f'
{inner}
' + +CALLOUTS_JS = '''''' + +FONTS = '''''' + +def page(body, bg): + return f'{FONTS}
{body}
{CALLOUTS_JS}' + +# ---------------------------------------------------------------- the Share Your Apps tab, in Code On The Go's dark theme +BG = '#17181C'; CARD = '#22252C'; EDGE = '#5A616B'; BEDGE = '#3A3E47'; WHITE = '#E9EAEE'; GREY = '#9EA2AB' +SECTION = '#9DA1AD'; BLUE = '#A1B3D9'; RED = '#D75D5A'; PUB = '#9EB2E5'; PUBINK = '#111723'; GREEN = '#7FC89A' + +def cg_bar(title='Share Your Apps'): + """Code On The Go's editor, cut down: its status bar, and the tab strip, with the Share Your Apps tab chosen.""" + return (f'
' + f'4:05Wi‑Fi ▾ 86%
' + f'
' + f'Build outputApp logs' + f'{E(title)}
') +def section(t): return f'

{E(t)}

' +def label(t): return f'

{E(t)}

' +def hint(t, color=GREY): return f'

{t}

' +def field(v, mono=False, lines=1, placeholder=False, width=None): + fam = "'Roboto Mono',monospace" if mono else 'Roboto' + col = GREY if placeholder else WHITE + w = f'width:{width}px;' if width else '' + return (f'
{E(v)}
') +def btn(t, grow=True, disabled=False): + return (f'
{E(t)}
') +def row(*items, gap=10): return f'
{"".join(items)}
' +def check(t, on): + box = (f'{"✓" if on else ""}') + return f'
{box}{E(t)}
' +def card(*items, open_=True): return f'
{"".join(items)}
' +def product_head(name, status, in_store=True, open_=False): + return (f'
{E(name)}' + f'{E(status)}
') +def bottom(status='', error=False, busy=False, status_co=None): + s = hint(E(status).replace('\n', '
'), RED if error else GREY) if status else '' + if s and status_co: s = co(status_co, s) + return (f'
{s}' + f'
{"Publishing…" if busy else "Publish"}
') +def plugin_screen(*content, status='', error=False, show_bottom=True, status_co=None): + return page(cg_bar() + f'
{"".join(content)}
' + (bottom(status, error, status_co=status_co) if show_bottom else ''), BG) + +def dark_dialog(title, *content, buttons=()): + """A dialog in Code On The Go's dark theme, over a dimmed tab.""" + bs = ''.join(f'{E(b)}' for b in buttons) + return page(cg_bar() + f'
' + f'
' + f'

{title}

{"".join(content)}' + f'
{bs}
', BG) + +# ---------------------------------------------------------------- plain Android screens, for what Android or Code On The Go draws +def android_dialog(title, text, buttons, note='Drawn from memory: replace with a real screenshot.'): + bs = ''.join(co(n, f'{E(b)}', inline=True) if n else + f'{E(b)}' for b, n in buttons) + return page(S.status_bar() + f'
' + f'

{title}

{text}

' + f'
{bs}
' + f'

{E(note)}

', '#5c5c5c') diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/real/annotate.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/real/annotate.py new file mode 100644 index 000000000..7f5d1568b --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/real/annotate.py @@ -0,0 +1,94 @@ +import json, re, sys, os +from PIL import Image, ImageDraw, ImageFont +sys.path.insert(0, '/tmp/real'); from specs import SPECS +O = json.load(open('/tmp/real/ocr.json')) +MANUAL = { # boxes read off by eye, where OCR couldn't read the text (dimmed dialogs, small red text, a scrolled-off label) + 'P08': {1: (150, 1330, 1320, 1425), 2: (150, 1450, 1320, 1615)}, + 'P09': {1: (130, 1545, 740, 1590), 2: (150, 1590, 590, 1730), 3: (625, 1590, 985, 1730)}, + 'P11': {1: (165, 1285, 830, 1370), 2: (165, 1405, 1170, 1490)}, + 'P14': {1: (55, 2362, 1375, 2512)}, + 'P13': {1: (55, 2358, 975, 2506)}, + 'B01': {1: (20, 8, 580, 90)}, + 'P15': {1: (60, 575, 1380, 1228), 2: (62, 1245, 716, 1405), 3: (722, 1245, 1424, 1405), 4: (60, 1490, 1380, 2165)}, +} +CROP = {} # screenshots to cut short, such as one with a keyboard showing +# Where a bubble has no room outside its outline, it goes inside, a few pixels clear of the outline: +# at the left or right end, halfway down, or at the top right. +PLACE = {'P15': {2: 'inside-left', 3: 'inside-right', 4: 'inside-top-right'}, + 'B01': {1: 'right', 2: 'inside-top-right', 3: 'above'}, 'S15': {1: 'inside-top-right'}, 'B02': {1: 'inside-top-left', 2: 'right', 3: 'right'}} +def close(a, b, tol=22): return sum(abs(x - y) for x, y in zip(a, b)) <= tol +def grow(im, box): + """Widen a text box to the button around it, by following the button's colour outwards from the text.""" + x0, y0, x1, y1 = box; cy = (y0 + y1) // 2; cx = (x0 + x1) // 2; W, H = im.size + seed = im.getpixel((max(x0 - 8, 0), cy)) + l = x0 - 8 + while l > 0 and close(im.getpixel((l - 1, cy)), seed) and x0 - l < 700: l -= 1 + r = x1 + 8 + while r < W - 1 and close(im.getpixel((r + 1, cy)), seed) and r - x1 < 700: r += 1 + t = y0 - 4 + while t > 0 and close(im.getpixel((cx, t - 1)), seed) and y0 - t < 90: t -= 1 + b = y1 + 4 + while b < H - 1 and close(im.getpixel((cx, b + 1)), seed) and b - y1 < 90: b += 1 + return (l, t, r, b) +def boxes_for(k, im): + out = {} + for n, pats, *opt in SPECS[k]: + o = opt[0] if opt else {} + if k in MANUAL and n in MANUAL[k]: out[n] = MANUAL[k][n]; continue + hits = [] + for p in pats: + m = [l for l in O[k]['lines'] if re.search(p, l['text'])] + if o.get('first'): m = m[:1] + if o.get('last'): m = m[-1:] + hits += m + if not hits: print(' no anchor for', k, n); continue + # Buttons: widen each to its own edges first, then join them, so two buttons are both covered. + hb = [list(grow(im, h['box'])) if o.get('grow') else h['box'] for h in hits] + b = [min(h[0] for h in hb), min(h[1] for h in hb), max(h[2] for h in hb), max(h[3] for h in hb)] + if o.get('qr_above'): b = [b[0] - 260, b[1] - 830, b[2] + 260, b[3]] + if o.get('qr_below'): b = [b[0], b[1], b[2], b[3] + 650] + if o.get('widen'): b = [b[0] - o['widen'], b[1], b[2] + o['widen'], b[3]] + if o.get('span'): b = [o['span'][0], b[1], o['span'][1], b[3]] # a whole row, from edge to edge of its card + if o.get('down'): b = [b[0], b[1], b[2], b[3] + o['down']] # down to include the field under a label + if o.get('pady'): b = [b[0], b[1] - o['pady'], b[2], b[3] + o['pady']] + if 'xmin' in o: b[0] = min(b[0], o['xmin']) + if 'xmax' in o: b[2] = max(b[2], o['xmax']) + if 'bottom' in o: b[3] = o['bottom'] + if 'up_to' in o: b = [b[0], o['up_to'], b[2], b[1] - 30] # the area above the anchor: here, a product's pictures + if o.get('icon_right'): b = [im.width - 175, b[1] - 16, im.width - 95, b[1] + 60] # the tooltip's faint ⓘ, at its top right + out[n] = (b[0] - 14, b[1] - 12, b[2] + 14, b[3] + 12) + return out +def draw(k, src, dst, width=780): + im = Image.open(src).convert('RGB') + if k in CROP: im = im.crop((0, 0, im.width, CROP[k])) + bx = boxes_for(k, im); s = im.width / 390 # draw at the same visual weight as the drawings + d = ImageDraw.Draw(im) + font = ImageFont.truetype('/tmp/fonts/Roboto.ttf', int(15 * s)); font.set_variation_by_axes([700, 100]) if hasattr(font, 'set_variation_by_axes') else None + r = int(13 * s); gap = int(3 * s) + clip = {n: (max(b[0], 2), max(b[1], 2), min(b[2], im.width - 3), min(b[3], im.height - 3)) for n, b in bx.items()} + def clear(cx, cy, own): + # Clear of the screen's edges, and of every other outline, by at least the gap. + if cx - r < 1 or cy - r < 1 or cx + r > im.width - 1: return False + return all(not (cx + r + gap > b[0] and cx - r - gap < b[2] and cy + r + gap > b[1] and cy - r - gap < b[3]) + for m, b in clip.items() if m != own) + for n, (x0, y0, x1, y1) in sorted(clip.items()): + d.rounded_rectangle((x0, y0, x1, y1), radius=int(8 * s), outline=(229, 57, 53), width=max(int(1.2 * s), 2)) + # The bubble sits wholly outside its outline, a few pixels from it: to its left; or, if that would touch + # another outline or the screen's edge, above it; or else below it. + options = [(x0 - gap - r, y0 + min((y1 - y0) // 2, int(22 * s))), (x0 + r, y0 - gap - r), (x0 + r, y1 + gap + r)] + inside = {'inside-left': (x0 + gap + r, (y0 + y1) // 2), 'inside-right': (x1 - gap - r, (y0 + y1) // 2), + 'inside-top-right': (x1 - gap - r, y0 + gap + r), 'inside-top-left': (x0 + gap + r, y0 + gap + r), + 'right': (x1 + gap + r, (y0 + y1) // 2), 'above': (x0 + r, y0 - gap - r)} + where = PLACE.get(k, {}).get(n) + cx, cy = inside[where] if where else next((c for c in options if clear(c[0], c[1], n)), options[0]) + cx, cy = max(cx, r + 1), max(cy, r + 1) + d.ellipse((cx - r, cy - r, cx + r, cy + r), fill=(229, 57, 53)) + d.text((cx, cy), str(n), fill='white', font=font, anchor='mm') + im = im.resize((width, int(im.height * width / im.width)), Image.LANCZOS) + im.save(dst, quality=88, optimize=True) + return bx +if __name__ == '__main__': + os.makedirs('/tmp/real/out', exist_ok=True) + for k in SPECS: + draw(k, f'/tmp/real/{k}.jpg', f'/tmp/real/out/{k}.jpg') + print(len(SPECS), 'annotated') diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/real/specs.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/real/specs.py new file mode 100644 index 000000000..6ca415dee --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/real/specs.py @@ -0,0 +1,45 @@ +# For each real screenshot: its callouts, each as a list of text patterns (regular expressions) whose lines it surrounds. +# grow: widen the box to the button or field around the text. +SPECS = { + 'P01': [(1, [r'^Install$'])], + 'P02': [(1, [r'^Store name$', r'^Top Android apps$'], dict(span=(40, 1400))), (2, [r'Store description', r'^

The ten'], dict(span=(40, 1400))), (3, [r'^Header image$', r'Built-in icon', r'^Change$', r'^Default$'], dict(span=(40, 1400))), (4, [r'PIN'], dict(span=(40, 1400), pady=22))], + 'P03': [(1, [r'Check the HTML|closes before|won.t stop'])], + 'P04': [(1, [r'Add product'], dict(grow=True)), (2, [r'^F-Droid$', r'app store for free', r'catalogue']), (3, [r'^Termux$', r'draft'])], + 'P05': [(1, [r'^Name$'], dict(first=True, span=(62, 1375), down=125)), (2, [r'^Project$', r'^Choose$'], dict(first=True, span=(62, 1375), down=25)), (3, [r'^APK$', r'app-debug\.apk'], dict(first=True, span=(62, 1375), down=25)), (4, [r'Publish the APK', r'Publish the source'], dict(first=True, span=(62, 1375)))], + 'P07': [(1, [r'^logo\.png$', r'^demo\.mp4$']), (2, [r'^Describe$'], dict(first=True, grow=True)), (3, [r'^Remove$'], dict(first=True, grow=True)), (4, [r'Add media'], dict(grow=True))], + 'P08': [(1, [r'What this item shows|visually|not what kind']), (2, [r'For example: The chat|messages$'])], + 'P09': [(1, [r'[Cc]aptions: |\.vtt']), (2, [r'Choose captions file'], dict(grow=True)), (3, [r'^No captions$'], dict(grow=True))], + 'P10': [(1, [r'Description \(HTML', r'complete Android development'], dict(span=(62, 1375), down=500)), (2, [r'Extra JSON \(optional\)'], dict(span=(62, 1375), down=170)), (3, [r'^Move up$', r'^Move down$'], dict(grow=True)), (4, [r'^Remove$'], dict(last=True, grow=True))], + 'P11': [(1, [r'It will have']), (2, [r'Left out, with nothing'])], + 'P12': [(1, [r'^Settings$'], dict(grow=True))], + 'P13': [(1, [r'Published Store_|Left out'])], + 'P14': [(1, [r"Couldn.t publish|Nothing was changed"])], + 'P15': [(1, [r'Template override']), (2, [r'Choose a template file'], dict(grow=True)), (3, [r'Load the default template'], dict(grow=True)), (4, [r'Extra JSON \(optional\)', r'"lang"'])], + 'P16': [(1, [r'PIN buyers must enter|can see the store']), (2, [r'See more'])], + 'S01': [(1, [r'^Serving Store_']), (2, [r'tap to copy']), (3, [r'SHOW QR CODES FOR BUYERS'], dict(grow=True)), (4, [r'Start serves the last'])], + 'S02': [(1, [r'GRANT STORAGE ACCESS'], dict(grow=True))], + 'S03': [(1, [r'^Port$']), (2, [r'^START$'], dict(grow=True)), (3, [r'^STOP$'], dict(grow=True)), (4, [r'^HELP$'], dict(grow=True))], + 'S04': [(1, [r'1\. Join this Wi-Fi', r'^Network: ', r'^Password: '], dict(xmin=215, xmax=1225)), (2, [r'2\. Open the store', r'^http://10\.'], dict(widen=270)), (3, [r'This network has no internet', r'airplane mode'])], + 'S05': [(1, [r'For you, not buyers', r'enter its password']), (2, [r'Wi-Fi password'], dict(span=(70, 1370), down=20)), (3, [r'Show the join code'], dict(grow=True))], + 'S06': [(1, [r'^Network name$', r'DIRECT-LS-']), (2, [r'^Password$', r'16 characters']), (3, [r'SAVE NAME'], dict(grow=True)), (4, [r'SUGGEST A PASSWORD'], dict(grow=True))], + 'S07': [(1, [r'Run always']), (2, [r'Pause when the screen'])], + 'S08': [(1, [r'SHARE THIS STORE'], dict(grow=True))], + 'S09': [(1, [r'Or type this code'], dict(qr_above=True)), (2, [r'^LS-']), (3, [r'This code works for one phone']), (4, [r'No Share Your Apps Server on the other', r'Scan this first', r'phone and install it'], dict(bottom=3035))], + 'S10': [(1, [r'Check that their screen', r'^22 10$']), (2, [r'In a week', r'Never', r'Oct 27, 2026']), (3, [r'^DENY$'], dict(grow=True)), (4, [r'^ALLOW$'], dict(grow=True))], + 'S11': [(1, [r'Serve a copy of someone', r'near their phone']), (2, [r'IMPORT A STORE'], dict(grow=True))], + 'S12': [(1, [r'Log size limit', r'^10$'], dict(span=(40, 1390))), (2, [r'VIEW LOGS'], dict(grow=True)), (3, [r'EXPORT LOGS'], dict(grow=True))], + 'S13': [(1, [r'Start serving the last store you', r'^published\.$'], dict(span=(150, 1365))), (2, [r'See more'])], + 'S14': [(1, [r'Start serving the last store you', r'notification shows'], dict(span=(150, 1365))), (2, [r'^Serving'], dict(grow=True))], + 'I01': [(1, [r'Download anyway'], dict(grow=True))], + 'I02': [(1, [r'IMPORT A STORE'], dict(grow=True))], + 'I03': [(1, [r'^Code$', r'^LS-'], dict(span=(50, 1030))), (2, [r"Your phone.s name", r'Galaxy Z Fold'], dict(span=(50, 1030))), (3, [r'CONTINUE'], dict(grow=True))], + 'I04': [(1, [r'Their screen should show', r'^22 10$']), (2, [r'Found the store', r'Waiting for the owner', r'Receiving the store', r'Ready to serve'])], + 'I05': [(1, [r'owner.s network', r'hotspot\.$']), (2, [r'SERVE IT NOW'], dict(grow=True))], + 'I07': [(1, [r'SERVE THIS STORE'], dict(grow=True)), (2, [r'Set a PIN or leave']), (3, [r'REMOVE THIS STORE'], dict(grow=True))], + 'I08': [(1, [r'SHOW QR CODES FOR BUYERS'], dict(grow=True))], + 'I09': [(1, [r'^OK$'], dict(grow=True))], + 'B01': [(1, [r'Accessible version'], dict(pady=6)), (2, [r'^Top Android apps$', r'real one\.$'], dict(xmin=190, xmax=1250)), (3, [r'Download APK'], dict(first=True, grow=True, down=60, pady=8))], + 'B02': [(1, [r'Code on the Go \(32-bit\)'], dict(xmin=30, xmax=1060, up_to=40)), (2, [r'A complete Android development', r'Get it from'], dict(first=True, span=(40, 1330))), (3, [r'Download APK'], dict(first=True, grow=True, down=60, pady=8)), (4, [r'For 32-bit phones'])], + 'B03': [(1, [r'Standard version']), (2, [r'^15 apps$', r'PipePipe'], dict(xmax=560))], + 'S15': [(1, [r'^Start, Stop and the port$', r"codes change with it|another app already"], dict(span=(40, 1400)))], +} diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/render.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/render.py new file mode 100644 index 000000000..119d3a7ec --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/render.py @@ -0,0 +1,13 @@ +import os, subprocess, json, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import shots_plugin, shots_server +ALL = shots_plugin.SHOTS + shots_server.SHOTS +HERE = os.path.dirname(os.path.abspath(__file__)); os.makedirs(HERE + '/html', exist_ok=True); os.makedirs(HERE + '/png', exist_ok=True) +only = sys.argv[1:] +for s in ALL: + if only and s['id'] not in only: continue + h = HERE + f"/html/{s['id']}.html"; open(h, 'w').write(s['html']) + subprocess.run(['xvfb-run', '-a', 'python3', '/tmp/shot.py', 'file://' + h, HERE + f"/png/{s['id']}.png", '390', '1300'], + env={**os.environ, 'ZOOM': '2'}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=90) +json.dump([{k: v for k, v in s.items() if k != 'html'} for s in ALL], open(HERE + '/shots.json', 'w'), indent=1) +print(len(ALL), 'shots') diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/server_look.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/server_look.py new file mode 100644 index 000000000..669d84533 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/server_look.py @@ -0,0 +1,75 @@ +"""The server app's look, drawn from its real screenshot: pieces for the guides' drawings (see kit.py).""" +import json, os, re +INK='#20242B'; BODY='#3C4148'; MUTED='#6B7078'; LINK='#485D92'; DANGER='#A1261B' +def esc(s): return s.replace('&','&').replace('<','<').replace('>','>') +def text(t, size=15, bold=False, color=BODY, center=False, mono=False, extra=''): + fam = "'Roboto Mono', monospace" if mono else "Roboto, sans-serif" + return f'

{esc(t)}

' +def title(t): return f'

{esc(t)}

' +def heading(t): return f'

{esc(t)}

' +def btn(t, disabled=False, color=None, full=True, grow=False): + fg = '#A2A5A9' if disabled else (color or '#212121') + bg = '#E6E7E8' if disabled else '#D6D7D7' + shadow = 'none' if disabled else '0 1px 2px rgba(0,0,0,0.35)' + w = 'width: 100%;' if full else '' + g = 'flex: 1;' if grow else '' + return (f'') +def row(*items, gap=8, center=False): return f'
{"".join(items)}
' +def edit(value, mono=False, width=None, placeholder=False, size=17): + fam = "'Roboto Mono', monospace" if mono else "Roboto, sans-serif" + w = f'width: {width}px;' if width else 'flex: 1; width: 100%;' + col = MUTED if placeholder else INK + return f'
{esc(value)}
' +def radio(label, checked=False): + dot = f'' if checked else '' + ring = '#009688' if checked else '#6B7078' + return (f'
{dot}' + f'{esc(label)}
') +def qr(size): + cells=[] + import random; r=random.Random(size) + n=25; c=size/n + for y in range(n): + for x in range(n): + finder = any(fx<=x') + return f'
{"".join(cells)}
' +def copyicon(): return '' +def checkbox(label, code): return (f'
' + f'

{esc(label)}

{code}

') +def progress(pct): return f'
' +def step(label, state): + mark = '✓' if state=='done' else label[0] + lab = label[2:] if state!='done' else label[2:] + return f'

{mark}  {esc(lab)}

' +def panel(t, *items, highlight=False): + return (f'
{title(t) if t else ""}{"".join(items)}
') +def card(*items): + return f'
{"".join(items)}
' +def bar(t): return f'
{esc(t)}
' +def status_bar(): return '
4:05Wi‑Fi ▾ 86%
' +def screen(barTitle, *content): + return status_bar() + bar(barTitle) + f'
{"".join(content)}
' +def footer(): return text("Share Your Apps Server 1.0.26 · built Sep 27, 2026 4:12 PM", 12, color=MUTED, center=True, extra=" margin-top: 4px;") + +HINT = text("Long-press a heading or button for help.", 12, color=MUTED) +SHARE_CAPTION = "Give someone nearby a copy to serve from their own phone. They can serve it with their own PIN. They can't change it or pass it on." +IMPORT_CAPTION = "Serve a copy of someone else's store, with their permission. You'll need to be near their phone, on the same network." +def server_panel(): return panel("Server", row(text("Port", 15, color=MUTED, extra=" margin: 0;"), edit("6175", width=110)), row(btn("Start", full=False, grow=True), btn("Stop", full=False, grow=True), btn("Help", full=False, grow=True))) +def copies_panel(caption, enabled): return panel("Copies of this store", text(caption), btn("Share this store…", disabled=not enabled), text("You can set an expiration date.", 13, color=MUTED)) +def import_panel(serving): return panel("Import a store", + text("This phone is serving a store. To import one, stop serving it first, with Stop above, or import on another phone." if serving else IMPORT_CAPTION), + btn("Import a store…", disabled=serving)) +def run_panel(): return panel("When to run", radio("Run always", True), radio("Pause when the screen turns off")) +def status_panel(line, url, last): + items=[text(line, 16, bold=True, color=INK)] + if url: items.append(text(url, 16, color=LINK)) + items.append(btn("Show QR codes for buyers")); items.append(text(last, 15)) + return panel("Status", *items) + diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_plugin.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_plugin.py new file mode 100644 index 000000000..63935368b --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_plugin.py @@ -0,0 +1,118 @@ +from kit import * +SHOTS = [] +def shot(id, section, title, html, key, how, real=False): + SHOTS.append(dict(id=id, guide='plugin', section=section, title=title, html=html, key=key, how=how, real=real)) + +PIN_NOTE = "Up to 6 digits. Buyers enter it before reaching the store. It isn't real security." +shot('P01', 'Installing the plugin', "Code On The Go's Addons Manager, installing the plugin", + android_dialog('Install plugin?', 'Share Your Apps 1.0.0
org.appdevforall.shareyourapps

Shares the apps you build with people nearby, over Wi-Fi or a hotspot.', + [('Cancel', None), ('Install', 1)], note="Code On The Go draws this: replace with a real screenshot."), + [(1, 'Install the plugin.')], + 'In Code On The Go, open the Addons Manager, and choose the Share Your Apps .cgp file. Capture the screen that asks to install it.', real=True) +shot('P02', 'Your store', 'The Store section', + plugin_screen(section('Store'), + co(1, label('Store name') + field('Top Android apps')), + co(2, label('Store description (HTML, optional)') + field('

Apps made on this phone, free to try.

', mono=True, lines=2)), + co(3, label('Header image') + row(f'Pictures/header.png', btn('Choose', grow=False), btn('Default', grow=False))), + co(4, row(f'PIN (optional)', field('1234', width=110), gap=14) + hint(PIN_NOTE)), + show_bottom=False), + [(1, "The store's name, at the top of its page."), (2, 'An optional description, in HTML.'), (3, 'Choose a header picture or video, or Default for the built-in one.'), (4, 'An optional PIN, of up to 6 digits.')], + 'Open the Share Your Apps tab, and scroll to the top. Fill in a name, a description and a PIN, so each field shows something.') +shot('P03', 'Store description', 'A description with an HTML problem', + plugin_screen(section('Store'), label('Store description (HTML, optional)'), + field('

Apps made on this phone, free to try.

', mono=True, lines=2), + co(1, hint('<b> is opened but never closed.', RED)), show_bottom=False), + [(1, "The warning: here, a bold tag that's never closed. It won't stop a publish, but may spoil the page.")], + 'In the store description, type

Hello world

, leaving the unclosed. Capture the red warning under the field.') +shot('P04', 'Products', 'The product list', + plugin_screen(row(f'PRODUCTS (3)', co(1, btn('+ Add product', grow=False), inline=True)), + co(2, card(product_head('Todo App', 'Source ✓ APK ✓ 4.2 MB'))), + card(product_head('Weather Now', 'APK ✓ 6.8 MB')), + co(3, card(product_head('Great Scott 2', 'draft', in_store=False))), show_bottom=False), + [(1, 'Add a product.'), (2, "A product in the store, with what buyers can download. Tap it to open it."), (3, "draft: nothing to download, so it's left out.")], + 'In the Share Your Apps tab, scroll to Products, with at least two products, one of them a draft: no APK chosen, and Publish the source unticked.') +shot('P05', 'Project and APK', "A product's name, project and APK", + plugin_screen(card(product_head('Todo App', 'Source ✓ APK ✓ 4.2 MB'), + co(1, label('Name') + field('Todo App')), + co(2, label('Project') + row(f'TodoApp', btn('Choose', grow=False))), + co(3, label('APK') + row(f'…/release/app-release.apk · 4.2 MB', btn('Choose', grow=False))), + co(4, check('Publish the APK', True) + check('Publish the source', True))), show_bottom=False), + [(1, "The name buyers see."), (2, "The Code On The Go project it comes from."), (3, 'The APK buyers download.'), (4, 'What buyers can download: the app, its source, or both.')], + 'Open a product, and scroll to its top: its name, project, APK and the two checkboxes.') +shot('P06', 'Project and APK', 'Choosing an APK, with an unsigned build', + dark_dialog('Choose an APK', + co(1, f'

release · app-release.apk

{hint("4.2 MB · built Sep 27, 2026 4:12 PM")}
'), + co(2, f'

release · app-release-unsigned.apk

{hint("4.1 MB · built Sep 27, 2026 3:58 PM")}{hint("⚠ Unsigned: buyers can't install it", RED)}
'), + f'

debug · app-debug.apk

{hint("5.0 MB · built Sep 26, 2026 11:20 AM")}
', + buttons=('Cancel',)), + [(1, 'A signed build: choose this kind.'), (2, "An unsigned build, marked: buyers can't install it.")], + 'In a product, tap Choose beside APK, for a project that has both a signed and an unsigned build.') +shot('P07', 'Pictures and video', 'Pictures and video', + plugin_screen(card(label('Pictures and video (3)'), + co(1, row(f'chat.png · described', btn('Describe', grow=False), btn('Remove', grow=False))), + row(f'settings.png', co(2, btn('Describe', grow=False), inline=True), co(3, btn('Remove', grow=False), inline=True)), + row(f'demo.mp4 · described · captions', btn('Describe', grow=False), btn('Remove', grow=False)), + co(4, btn('+ Add media'))), show_bottom=False), + [(1, 'described: it has a description.'), (2, "Describe: say what it shows, and, for a video, add captions."), (3, 'Remove it from the product.'), (4, 'Add pictures, videos or sounds.')], + "Open a product with two pictures and a video, one picture described and the video with captions.") +shot('P08', 'Pictures and video', 'Describing a picture', + dark_dialog('Describe chat.png', + co(1, hint("What this item shows, for visually-impaired people. Say what matters for the user choosing the app, not what kind of item it is.")), + co(2, f'
The chat screen, with two messages
'), + buttons=('Cancel', 'Save')), + [(1, 'What to write.'), (2, 'The description, which screen readers read aloud in place of the picture.')], + 'Tap Describe beside a picture, and type a description, before tapping Save.') +shot('P09', 'Pictures and video', 'Captions for a video', + dark_dialog('Describe demo.mp4', + hint("What this item shows, for visually-impaired people. Say what matters for the user choosing the app, not what kind of item it is."), + f'
Adding a task, then ticking it off
', + co(1, hint('Captions: demo.vtt')), + row(co(2, btn('Choose captions file'), grow=True), co(3, btn('No captions'), grow=True)), + buttons=('Cancel', 'Save')), + [(1, 'The captions file chosen.'), (2, 'Choose a WebVTT captions file, ending .vtt.'), (3, 'Remove the captions.')], + 'Tap Describe beside a video, then Choose captions file, and pick a .vtt file.') +shot('P10', 'Order, and removing a product', "A product's description, order and removal", + plugin_screen(card(co(1, label('Description (HTML, optional)') + field('

A to-do list that works offline.

', mono=True, lines=2)), + co(2, label('Extra JSON (optional)') + field('{\n "whatsNew": "Faster sync",\n "license": "MIT"\n}', mono=True, lines=4)), + row(co(3, btn('Move up'), grow=True), btn('Move down'), co(4, btn('Remove'), grow=True))), show_bottom=False), + [(1, 'What buyers read about it, in HTML.'), (2, 'Optional details: whatsNew, license, author and website.'), (3, 'Move up and Move down set the order buyers see.'), (4, 'Remove the product, after asking.')], + "Open a product, and scroll to its end: description, Extra JSON, and the three buttons.") +shot('P11', 'Publishing', 'Confirming a publish', + dark_dialog('Publish Top Android apps?', + co(1, f'

It will have 12 products.

'), + co(2, f'

Left out, with nothing to download: Great Scott 2.

'), + f'

Buyers keep the current version until the new one is ready.

', + buttons=('Cancel', 'Publish')), + [(1, 'How many products the store will have.'), (2, "Any left out, and why.")], + 'Tap Publish, and capture the dialog before choosing.') +shot('P12', 'Publishing', "Android asking to allow installing apps", + android_dialog('Allow Code On The Go to install unknown apps?', 'Your phone and personal data are more vulnerable to attack by unknown apps.', [('Cancel', None), ('Settings', 1)]), + [(1, 'Open the setting, and allow Code On The Go to install apps. Needed once, for Share Your Apps Server.')], + 'On a phone where Code On The Go has never installed an app, publish for the first time, and capture Android\'s prompt.', real=True) +shot('P13', 'What the messages mean', 'A finished publish', + plugin_screen(section('Advanced'), label('Extra JSON (optional)'), field('{\n "announcement": "New this week"\n}', mono=True, lines=3), + status='Sep 27, 4:21:05 PM · Published Store_48213576 — 31 files verified.\nLeft out: Great Scott 2 has no APK chosen, and Publish the source isn\'t ticked.\nNote: "F-Droid" APK isn\'t signed, so buyers can\'t install it: f-droid.apk.', status_co=1), + [(1, "The result: Published … files verified, then any left out, and any notes.")], + 'Publish, and capture the bottom of the tab when it finishes, with at least one product left out.') +shot('P14', 'What the messages mean', "A publish that couldn't finish", + plugin_screen(section('Advanced'), label('Extra JSON (optional)'), field('{ }', mono=True, lines=1), + status='Sep 27, 4:25:40 PM · Couldn\'t publish: "Todo App" APK not found: TodoApp/app/build/outputs/apk/release/app-release.apk. Nothing was changed; the store is still serving the previous version.', error=True, status_co=1), + [(1, "What went wrong. Nothing changed: buyers keep the previous store.")], + 'Move a product\'s chosen APK away, then publish, and capture the red message.') +shot('P15', 'Changing the store\'s look', 'Templates and Extra JSON', + plugin_screen(section('Advanced'), + co(1, label('Template override (Pebble, optional)') + field('{% extends "default" %}\n{% block announcement %}

Hello

{% endblock %}', mono=True, lines=3)), + row(co(2, btn('Choose a template file'), grow=True), co(3, btn('Load the default template'), grow=True)), + hint("When this isn't empty, it replaces the default template."), + co(4, label('Extra JSON (optional)') + field('{\n "announcement": "New this week",\n "accent": "#1E88E5"\n}', mono=True, lines=4)), + hint('Passed into the template as extra.'), show_bottom=False), + [(1, 'Your own template, or empty for the built-in one.'), (2, 'Choose a template file, such as an alternative.'), (3, 'Start from the built-in template, or go back to it.'), (4, "Settings for the whole store: an announcement, a colour, the page's language.")], + 'In the Share Your Apps tab, scroll to Advanced, with a template and Extra JSON filled in.') +shot('P16', 'Getting help', 'Long-press help, in the Share Your Apps tab', + plugin_screen(section('Store'), f'
{label("PIN (optional)")}
', + co(1, f'
' + f'

Optional: buyers type this to open the store.

' + + co(2, f'

See more

', inline=True) + '
'), + show_bottom=False), + [(1, 'A short explanation, after long-pressing a heading.'), (2, 'See more, for detail and a help page.')], + "Long-press the PIN (optional) heading. Code On The Go draws this: capture its real look.", real=True) diff --git a/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_server.py b/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_server.py new file mode 100644 index 000000000..76c1ac8e4 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/drawings/shots_server.py @@ -0,0 +1,154 @@ +from kit import * +SHOTS = [] +SV = '#E2E5EA' +def shot(id, guide, section, title, html, key, how, real=False): + SHOTS.append(dict(id=id, guide=guide, section=section, title=title, html=html, key=key, how=how, real=real)) +def sp(title, *c): return page(S.screen(title, *c), SV) +T = S.text; INK = S.INK +URL = "http://192.168.1.5:6175/" +def status(line, url, last, qr_co=None, url_co=None, line_co=None, last_co=None): + items = [co(line_co, T(line, 16, bold=True, color=INK)) if line_co else T(line, 16, bold=True, color=INK)] + if url: items.append(co(url_co, T(url, 16, color=S.LINK)) if url_co else T(url, 16, color=S.LINK)) + b = S.btn('Show QR codes for buyers'); items.append(co(qr_co, b) if qr_co else b) + items.append(co(last_co, T(last, 15)) if last_co else T(last, 15)) + return S.panel('Status', *items) + +# ------------------------------------------------ the server app guide +shot('S01', 'server', 'Status', 'Manage server, serving', + sp('Share Your Apps Server', S.HINT, + status('Serving Store_48213576', URL, 'Start serves the last store published: Store_48213576', qr_co=3, url_co=2, line_co=1, last_co=4), + S.server_panel()), + [(1, 'What the server is doing, and which store.'), (2, "The store's address. The button beside it copies it."), (3, 'The codes buyers scan.'), (4, 'What Start will serve.')], + 'Open Share Your Apps Server while it serves your store, and capture the top of Manage server.') +shot('S02', 'server', 'Status', 'Storage access still needed', + sp('Share Your Apps Server', S.HINT, S.panel('Status', T('Grant storage access first.', 16, bold=True, color=INK), + co(1, S.btn('Grant storage access')), T('Start serves the last store published: Store_48213576', 15))), + [(1, "Tap it and allow access, once: the server needs it to read your store's files.")], + "Before allowing All files access to Share Your Apps Server, open it. (Or turn the access off in Android's Settings, capture, then turn it on again.)") +shot('S03', 'server', 'Starting and stopping', 'The Server panel', + sp('Share Your Apps Server', S.panel('Server', S.row(co(1, T('Port', 15, color=S.MUTED, extra=' margin: 0;'), inline=True), S.edit('6175', width=110)), + S.row(co(2, S.btn('Start'), grow=True), co(3, S.btn('Stop'), grow=True), co(4, S.btn('Help'), grow=True)))), + [(1, "The port, the number in the store's address. Its label has help; the field keeps its long-press for text."), (2, 'Start serving.'), (3, 'Stop serving.'), (4, 'The help pages.')], + 'In Manage server, capture the Server panel.') +shot('S04', 'server', 'Letting buyers in', 'The codes buyers scan, on a hotspot', + sp('Serve', S.card(co(1, S.text('1. Join this Wi-Fi network', 20, bold=True, color=INK) + S.qr(170) + T('DIRECT-LS-VDHX · password s5Fyp6EhcpjWANj3', 13, center=True))), + S.card(co(2, S.text('2. Open the store', 20, bold=True, color=INK) + S.qr(170) + T(URL, 14, center=True, color=S.LINK))), + co(3, T("This network has no internet. If a buyer's phone can't open the store, have them turn on airplane mode, then turn Wi-Fi back on. Remind them to turn airplane mode off afterwards.", 14)), + S.btn('Done')), + [(1, "The first code joins buyers to the hotspot."), (2, 'The second opens the store.'), (3, "The tip for a buyer whose phone can't open it.")], + 'Turn Wi-Fi off, tap Start, then Show QR codes for buyers. Capture the whole screen, scrolling if needed.') +shot('S05', 'server', 'Letting buyers in', 'Making a join code for ordinary Wi-Fi', + sp('Serve', S.card(S.text('1. Join this Wi-Fi network', 20, bold=True, color=INK), + co(1, T('For you, not buyers: to show a code for joining this Wi-Fi network, enter its password. It isn\'t saved.', 13, color=S.MUTED)), + S.edit('Home Wi-Fi'), co(2, S.edit('••••••••••')), co(3, S.btn('Show the join code')))), + [(1, 'What this is for: making a code that joins buyers to your Wi-Fi.'), (2, "The network's password, never saved."), (3, 'Show the code.')], + "On ordinary Wi-Fi, open Show QR codes for buyers, and capture the part asking for the network's password.") +shot('S06', 'server', 'The Wi-Fi Direct hotspot\'s name and password', 'The Wi-Fi Direct hotspot panel', + sp('Share Your Apps Server', S.panel('Wi-Fi Direct hotspot', T('When this phone isn\'t on Wi-Fi, the server starts a hotspot that buyers join. It uses this name and password.', 14), + co(1, T('Network name', 15, color=S.MUTED) + S.row(T('DIRECT-LS-', 16, color=S.MUTED, extra=' margin:0;'), S.edit('VDHX'))), + co(2, T('Password', 15, color=S.MUTED) + S.edit('s5Fyp6EhcpjWANj3')), + S.row(co(3, S.btn('Save name & password'), grow=True), co(4, S.btn('Suggest a password'), grow=True)))), + [(1, 'Its name, after DIRECT-LS-.'), (2, 'Its password, 8 to 63 characters.'), (3, 'Keep them, for the next time the hotspot starts.'), (4, 'Fill in a strong password.')], + 'In Manage server, capture the Wi-Fi Direct hotspot panel.') +shot('S07', 'server', 'When to run', 'When to run', + sp('Share Your Apps Server', S.panel('When to run', co(1, S.radio('Run always', True)), co(2, S.radio('Pause when the screen turns off')))), + [(1, 'Keep serving whatever the screen does.'), (2, 'Save battery: pause when the screen turns off, and resume on unlocking.')], + 'In Manage server, capture the When to run panel.') +shot('S08', 'server', 'Sharing your store with another seller', 'Starting a share', + sp('Share Your Apps Server', S.panel('Copies of this store', T(S.SHARE_CAPTION), co(1, S.btn('Share this store…')), T('You can set an expiration date.', 13, color=S.MUTED))), + [(1, 'Share a copy of your store, while it serves.')], + 'While your store serves, capture the Copies of this store panel.') +shot('S09', 'server', 'Sharing your store with another seller', 'The share code', + sp('Share this store', S.card(S.heading('Share this store'), + T("On the other phone, open Share Your Apps Server and tap Import a store. Then scan this code with the phone's camera, or type it."), + co(1, S.qr(210)), + co(2, S.row(f'LS-FM50-ZV7G', f'{S.copyicon()}', center=True, gap=4)), + co(3, T('This code works for one phone, for 9 more minutes.', 13))), + S.card(T('No Share Your Apps Server on the other phone?', 15, bold=True, color=INK), T('Scan this first with its camera, to download the app from this phone and install it.', 14), co(4, S.qr(130))), + S.btn('Cancel')), + [(1, 'The large code: the other phone scans it to import.'), (2, 'Or the other phone types this code; the icon copies it.'), (3, 'One phone, for 10 minutes.'), (4, "For a phone without the app: a small code, or a link to open in its browser, with a button that copies it, to download Share Your Apps Server from this phone.")], + 'Tap Share this store…, and capture the whole screen, scrolling if needed.') +shot('S10', 'server', 'Sharing your store with another seller', 'Allowing a copy', + sp('Share this store', S.card(S.heading('Allow a copy?'), T("Daniel's S23 Ultra is asking for a copy of Top Android apps.", 16), + co(1, S.checkbox('Check that their screen shows', '42 17')), + T('The copy expires', 14, bold=True, color=INK), + co(2, S.radio('In a week') + S.radio('In a month · Oct 27, 2026', True) + S.radio('On a date') + S.radio('Never'))), + S.row(co(3, S.btn('Deny'), grow=True), co(4, S.btn('Allow'), grow=True))), + [(1, 'These four digits must match the other phone\'s.'), (2, 'When their copy expires.'), (3, "Deny, if the digits don't match."), (4, 'Allow, if they do.')], + 'With a second phone importing, capture the Allow a copy? screen, before choosing.') +shot('S11', 'server', 'Importing someone else\'s store', 'The Import a store panel', + sp('Share Your Apps Server', S.panel('Import a store', co(1, T(S.IMPORT_CAPTION)), co(2, S.btn('Import a store…')))), + [(1, 'Serve a copy of someone else\'s store, with their permission.'), (2, "Start importing. It's disabled, saying why, while the phone serves a store.")], + 'With the server stopped, capture the Import a store panel.') +shot('S12', 'server', 'Logs', 'The Logs panel', + sp('Share Your Apps Server', S.panel('Logs', co(1, T('Log size limit (MB)', 15, color=S.MUTED) + S.edit('10')), + S.row(co(2, S.btn('View logs'), grow=True), co(3, S.btn('Export logs'), grow=True)), + T('Log folder: /data/user/0/org.appdevforall.shareyourapps.server/files/logs', 12, color=S.MUTED))), + [(1, 'How large each log file grows; 0 turns logging off.'), (2, 'Read the logs, newest first.'), (3, 'Send the log files off the phone.')], + 'In Manage server, capture the Logs panel.') +def tip(expanded): + body = (co(1, T('The number in the store\'s address, 6175 unless you change it.', 15, color='#222'), grow=True) + + co(2, 'ⓘ', inline=True)) + more = (T('Change it only if another app already uses that port; buyers\' codes change with it.', 14, color='#222') + co(3, S.btn('Serving the store'))) if expanded \ + else co(3, '+ See more', inline=True) + return sp('Share Your Apps Server', S.panel('Server', S.row(T('Port', 15, color=S.MUTED, extra=' margin: 0;'), S.edit('6175', width=110))), + f'
' + f'
{body}
{more}
') +shot('S13', 'server', 'Getting help', 'A tooltip', + tip(False), [(1, 'A short explanation, after long-pressing the Port label.'), (2, 'For developers: where the help came from.'), (3, '+ See more, for more.')], + 'Long-press the Port label, and capture the tooltip.') +shot('S14', 'server', 'Getting help', 'After + See more', + tip(True), [(1, 'The short explanation.'), (2, 'For developers.'), (3, 'The help page, opening at this topic.')], + 'Long-press the Port label, tap + See more, and capture the tooltip.') + +# ------------------------------------------------ the imported-store guide +shot('I01', 'seller', '1. Get the app', "Scanning the owner's small code", + android_dialog('Download share-your-apps-server.apk?', 'From 192.168.49.1 · 11 MB', [('Cancel', None), ('Download', 1)], note="Your browser draws this: replace with a real screenshot."), + [(1, 'Download the app, then open it to install.')], + "On the second phone, scan the owner's small QR code with the camera, open the link, and capture the browser's download prompt.", real=True) +shot('I02', 'seller', '2. Get the store', 'Starting an import', + sp('Share Your Apps Server', S.HINT, status('Stopped', None, 'Nothing published yet — publish from the Share Your Apps plugin, or import a store, below.'), + S.panel('Import a store', T(S.IMPORT_CAPTION), co(1, S.btn('Import a store…')))), + [(1, 'Tap Import a store….')], + 'On a phone with Share Your Apps Server but no store, open Manage server.') +shot('I03', 'seller', '2. Get the store', 'The code, and your phone\'s name', + sp('Import a store', S.card(S.heading('Import a store'), T("Scan the owner's QR code with this phone's camera, or type the code shown on their phone."), + co(1, T('Code', 14, bold=True, color=INK, extra=' margin-bottom: 0;') + S.edit('LS-FM50-ZV7G', mono=True, size=22)), + co(2, T("Your phone's name", 14, bold=True, color=INK, extra=' margin-bottom: 0;') + S.edit("Daniel's S23 Ultra"))), + co(3, S.btn('Continue'))), + [(1, "The owner's code, filled in from their QR code, or typed."), (2, 'What the owner sees.'), (3, 'Ask for the copy.')], + 'Tap Import a store…, type a code, and capture the screen before tapping Continue.') +shot('I04', 'seller', '2. Get the store', 'The four digits, then the store arriving', + sp('Import a store', S.card(S.heading('Top Android apps'), co(1, S.checkbox('Their screen should show', '42 17')), + S.step('1 Found the store', 'done'), S.step('2 The owner allowed it', 'done'), co(2, S.step('3 Receiving the store', 'now') + S.progress(64) + T('81 files · 4.1 of 6.4 MB', 14)), S.step('4 Ready to serve', 'todo')), + T('Keep both phones close, with their screens on.', 13), S.btn('Cancel')), + [(1, "These digits must match the owner's screen."), (2, 'The store arriving.')], + 'After Continue, and the owner allowing it, capture the screen while it receives the store.') +shot('I05', 'seller', '2. Get the store', 'Imported', + sp('Import a store', S.card(S.heading('Imported Top Android apps'), T('81 files · 6.4 MB. It expires on Oct 27, 2026.'), + T("It's served as it was published, with your own PIN. It can't be changed or passed on.", 14), + co(1, T("This phone is on the owner's network. To serve the store yourself, leave it first: join your own Wi-Fi, or turn Wi-Fi off, so this phone starts its own hotspot.", 14, color=S.DANGER))), + co(2, S.btn('Serve it now')), S.btn('Done')), + [(1, "Shown only if you joined the owner's hotspot: leave it first."), (2, 'Start serving the store.')], + "Import over the owner's hotspot, and capture the last screen.") +shot('I06', 'seller', '2. Get the store', 'If it stops partway', + sp('Import a store', S.card(S.heading('Top Android apps'), T("The import failed: the connection to the owner's phone was lost.", 15, color=S.DANGER)), + co(1, S.btn('Try again')), S.btn('Start over')), + [(1, "Try again, while the owner's phone still shows the code.")], + 'Start an import, turn Wi-Fi off on the second phone partway, then on, and capture the screen.') +shot('I07', 'seller', 'A PIN, if you want one', 'Your copy, and its PIN', + sp('Share Your Apps Server', S.panel('Top Android apps', T('Read-only · Expires Oct 27, 2026 · in 30 days', 15, bold=True, color=INK), + T("An imported copy of someone else's store. You can serve it; it can't be changed or passed on.", 14), + co(1, S.btn('Serve this store')), + co(2, T('Set a PIN or leave blank for no PIN', 15, bold=True, color=INK, extra=' margin-top: 8px;') + S.row(S.edit('••••', width=110), T('Up to 6 digits. Buyers enter it before reaching the store.', 13, extra=' margin: 0;'))), + co(3, S.btn('Remove this store', color=S.DANGER)))), + [(1, 'Serve it, with the PIN below.'), (2, 'Your own PIN, or none.'), (3, 'Remove it from this phone.')], + "With a copy imported and not serving, capture the store's panel in Manage server.") +shot('I08', 'seller', '3. Let people in', 'The codes, for your buyers', + sp('Share Your Apps Server', S.HINT, status('Serving a copy of Top Android apps', 'http://192.168.43.1:6175/', 'Start serves the imported copy of Top Android apps, below.', qr_co=1)), + [(1, 'Show the codes people scan.')], + 'While serving the copy, capture the top of Manage server.') +shot('I09', 'seller', 'When the store expires', 'After the store expires', + sp('Share Your Apps Server', S.panel('A store has expired', T('Your copy of Top Android apps has expired, and has been deleted from this phone. Buyers can no longer open it. To serve it again, ask its owner for a new copy.'), co(1, S.btn('OK')))), + [(1, 'Close the notice.')], + "After a copy's date has passed, open Manage server. To see it sooner, import with In a week, then move the phone's date 8 days ahead; turn automatic date and time back on afterwards.") diff --git a/plugins/Share-Your-Apps/docs/user-guides/octopus.png b/plugins/Share-Your-Apps/docs/user-guides/octopus.png new file mode 100644 index 000000000..295ab8809 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/octopus.png differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/pebble-book.pdf b/plugins/Share-Your-Apps/docs/user-guides/pebble-book.pdf new file mode 100644 index 000000000..f4c43dfdc Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/pebble-book.pdf differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/B01.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/B01.jpg new file mode 100644 index 000000000..a516b9955 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/B01.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/B02.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/B02.jpg new file mode 100644 index 000000000..7c9c93235 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/B02.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/B03.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/B03.jpg new file mode 100644 index 000000000..d03a59010 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/B03.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I01.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I01.jpg new file mode 100644 index 000000000..980df2a5d Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I01.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I02.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I02.jpg new file mode 100644 index 000000000..8b9c86627 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I02.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I03.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I03.jpg new file mode 100644 index 000000000..f7a2ee61f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I03.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I04.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I04.jpg new file mode 100644 index 000000000..e729e1308 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I04.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I05.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I05.jpg new file mode 100644 index 000000000..ea67172f0 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I05.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I06.png b/plugins/Share-Your-Apps/docs/user-guides/screens/I06.png new file mode 100644 index 000000000..a9aee1304 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I06.png differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I07.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I07.jpg new file mode 100644 index 000000000..34910f138 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I07.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I08.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I08.jpg new file mode 100644 index 000000000..7d8f48210 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I08.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/I09.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/I09.jpg new file mode 100644 index 000000000..0d53cb98f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/I09.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P01.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P01.jpg new file mode 100644 index 000000000..b173f1360 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P01.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P02.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P02.jpg new file mode 100644 index 000000000..aa06ea301 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P02.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P03.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P03.jpg new file mode 100644 index 000000000..b6ed27f1f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P03.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P04.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P04.jpg new file mode 100644 index 000000000..a4b8d05c8 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P04.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P05.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P05.jpg new file mode 100644 index 000000000..d861d96e1 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P05.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P06.png b/plugins/Share-Your-Apps/docs/user-guides/screens/P06.png new file mode 100644 index 000000000..f9029f042 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P06.png differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P07.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P07.jpg new file mode 100644 index 000000000..2fa707522 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P07.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P08.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P08.jpg new file mode 100644 index 000000000..98fb3359d Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P08.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P09.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P09.jpg new file mode 100644 index 000000000..21c99c705 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P09.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P10.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P10.jpg new file mode 100644 index 000000000..aa280ff79 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P10.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P11.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P11.jpg new file mode 100644 index 000000000..344e084ad Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P11.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P12.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P12.jpg new file mode 100644 index 000000000..b3d2139b1 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P12.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P13.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P13.jpg new file mode 100644 index 000000000..f4af37bf6 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P13.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P14.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P14.jpg new file mode 100644 index 000000000..d00a1c5ff Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P14.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P15.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P15.jpg new file mode 100644 index 000000000..8cd1bae39 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P15.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/P16.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/P16.jpg new file mode 100644 index 000000000..43958a333 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/P16.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S01.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S01.jpg new file mode 100644 index 000000000..fa2aa446f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S01.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S02.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S02.jpg new file mode 100644 index 000000000..a015e3610 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S02.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S03.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S03.jpg new file mode 100644 index 000000000..2ca8b8e3c Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S03.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S04.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S04.jpg new file mode 100644 index 000000000..d0a3c2a28 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S04.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S05.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S05.jpg new file mode 100644 index 000000000..0385eaa88 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S05.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S06.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S06.jpg new file mode 100644 index 000000000..6acf04109 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S06.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S07.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S07.jpg new file mode 100644 index 000000000..62ed3683a Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S07.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S08.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S08.jpg new file mode 100644 index 000000000..b2cb6743f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S08.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S09.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S09.jpg new file mode 100644 index 000000000..955e6ae5c Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S09.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S10.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S10.jpg new file mode 100644 index 000000000..61a1bbd4a Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S10.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S11.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S11.jpg new file mode 100644 index 000000000..2065225ad Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S11.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S12.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S12.jpg new file mode 100644 index 000000000..b54103cba Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S12.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S13.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S13.jpg new file mode 100644 index 000000000..b9a45ba3f Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S13.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S14.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S14.jpg new file mode 100644 index 000000000..1a1af8598 Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S14.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/S15.jpg b/plugins/Share-Your-Apps/docs/user-guides/screens/S15.jpg new file mode 100644 index 000000000..14a82e97a Binary files /dev/null and b/plugins/Share-Your-Apps/docs/user-guides/screens/S15.jpg differ diff --git a/plugins/Share-Your-Apps/docs/user-guides/screens/shots.json b/plugins/Share-Your-Apps/docs/user-guides/screens/shots.json new file mode 100644 index 000000000..dc3222206 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/screens/shots.json @@ -0,0 +1,887 @@ +[ + { + "id": "P01", + "guide": "plugin", + "section": "Installing the plugin", + "title": "Code On The Go's Addons Manager, installing the plugin", + "key": [ + [ + 1, + "Install the plugin." + ] + ], + "how": "In Code On The Go, open the Addons Manager, and choose the Share Your Apps .cgp file. Capture the screen that asks to install it.", + "real": true, + "captured": true + }, + { + "id": "P02", + "guide": "plugin", + "section": "Your store", + "title": "The Store section", + "key": [ + [ + 1, + "The store's name, at the top of its page." + ], + [ + 2, + "An optional description, in HTML." + ], + [ + 3, + "Change the header picture or video, or Default for the built-in one." + ], + [ + 4, + "An optional PIN, of up to 6 digits." + ] + ], + "how": "Open the Share Your Apps tab, and scroll to the top. Fill in a name, a description and a PIN, so each field shows something.", + "real": false, + "captured": true + }, + { + "id": "P03", + "guide": "plugin", + "section": "Store description", + "title": "A description with an HTML problem", + "key": [ + [ + 1, + "The warning: here, a bold tag that's never closed. It won't stop a publish, but may spoil the page." + ] + ], + "how": "In the store description, type

Hello world

, leaving the unclosed. Capture the red warning under the field.", + "real": false, + "captured": true + }, + { + "id": "P04", + "guide": "plugin", + "section": "Products", + "title": "The product list", + "key": [ + [ + 1, + "Add a product." + ], + [ + 2, + "A product in the store, with what buyers can download: here, its source. Tap it to open it." + ], + [ + 3, + "draft: not published: nothing to download, so it's left out." + ] + ], + "how": "In the Share Your Apps tab, scroll to Products, with at least two products, one of them a draft: no APK chosen, and Publish the source unticked.", + "real": false, + "captured": true + }, + { + "id": "P05", + "guide": "plugin", + "section": "Project and APK", + "title": "A product's name, project and APK", + "key": [ + [ + 1, + "The name buyers see." + ], + [ + 2, + "The Code On The Go project it comes from." + ], + [ + 3, + "The APK buyers download." + ], + [ + 4, + "What buyers can download: the app, its source, or both." + ] + ], + "how": "Open a product, and scroll to its top: its name, project, APK and the two checkboxes.", + "real": false, + "captured": true + }, + { + "id": "P06", + "guide": "plugin", + "section": "Project and APK", + "title": "Choosing an APK, with an unsigned build", + "key": [ + [ + 1, + "A signed build: choose this kind." + ], + [ + 2, + "An unsigned build, marked: buyers can't install it." + ] + ], + "how": "Build a project that has no release signing with assembleDebug and assembleRelease, so it has app-debug.apk and app-release-unsigned.apk. In a product using that project, tap Choose beside APK. Two builds are enough: one signed, one unsigned.", + "real": false, + "captured": false + }, + { + "id": "P07", + "guide": "plugin", + "section": "Pictures and video", + "title": "Pictures and video", + "key": [ + [ + 1, + "The pictures and video, by file name." + ], + [ + 2, + "Describe: say what it shows, and, for a video, add captions." + ], + [ + 3, + "Remove it from the product." + ], + [ + 4, + "Add pictures, videos or sounds." + ] + ], + "how": "Open a product with two pictures and a video, one picture described and the video with captions.", + "real": false, + "captured": true + }, + { + "id": "P08", + "guide": "plugin", + "section": "Pictures and video", + "title": "Describing a picture", + "key": [ + [ + 1, + "What to write." + ], + [ + 2, + "The description, which screen readers read aloud in place of the picture." + ] + ], + "how": "Tap Describe beside a picture, and type a description, before tapping Save.", + "real": false, + "captured": true + }, + { + "id": "P09", + "guide": "plugin", + "section": "Pictures and video", + "title": "Captions for a video", + "key": [ + [ + 1, + "The captions file chosen." + ], + [ + 2, + "Choose a WebVTT captions file, ending .vtt." + ], + [ + 3, + "Remove the captions." + ] + ], + "how": "Tap Describe beside a video, then Choose captions file, and pick a .vtt file.", + "real": false, + "captured": true + }, + { + "id": "P10", + "guide": "plugin", + "section": "Order, and removing a product", + "title": "A product's description, order and removal", + "key": [ + [ + 1, + "What buyers read about it, in HTML." + ], + [ + 2, + "Optional details: whatsNew, license, author and website." + ], + [ + 3, + "Move up and Move down set the order buyers see." + ], + [ + 4, + "Remove the product, after asking." + ] + ], + "how": "Open a product, and scroll to its end: description, Extra JSON, and the three buttons.", + "real": false, + "captured": true + }, + { + "id": "P11", + "guide": "plugin", + "section": "Publishing", + "title": "Confirming a publish", + "key": [ + [ + 1, + "How many products the store will have." + ], + [ + 2, + "Any left out, and why." + ] + ], + "how": "Tap Publish, and capture the dialog before choosing.", + "real": false, + "captured": true + }, + { + "id": "P12", + "guide": "plugin", + "section": "Publishing", + "title": "Android asking to allow installing apps", + "key": [ + [ + 1, + "Open Settings, and allow Code On The Go to install apps. Needed once, for Share Your Apps Server." + ] + ], + "how": "On a phone where Code On The Go has never installed an app, publish for the first time, and capture Android's prompt.", + "real": true, + "captured": true + }, + { + "id": "P13", + "guide": "plugin", + "section": "What the messages mean", + "title": "A finished publish", + "key": [ + [ + 1, + "The result: Published \u2026 files verified, then any left out, and any notes." + ] + ], + "how": "Publish, and capture the bottom of the tab when it finishes, with at least one product left out.", + "real": false, + "captured": true + }, + { + "id": "P14", + "guide": "plugin", + "section": "What the messages mean", + "title": "A publish that couldn't finish", + "key": [ + [ + 1, + "What went wrong. Nothing changed: buyers keep the previous store." + ] + ], + "how": "Move a product's chosen APK away, then publish, and capture the red message.", + "real": false, + "captured": true + }, + { + "id": "P15", + "guide": "plugin", + "section": "Changing the store's look", + "title": "Templates and Extra JSON", + "key": [ + [ + 1, + "Your own template, or empty for the built-in one." + ], + [ + 2, + "Choose a template file, such as an alternative." + ], + [ + 3, + "Start from the built-in template, or go back to it." + ], + [ + 4, + "Settings for the whole store: an announcement, a colour, the page's language." + ] + ], + "how": "In the Share Your Apps tab, scroll to Advanced, with a template and Extra JSON filled in.", + "real": false, + "captured": true + }, + { + "id": "P16", + "guide": "plugin", + "section": "Getting help", + "title": "Long-press help, in the Share Your Apps tab", + "key": [ + [ + 1, + "A short explanation, after long-pressing a heading. Code On The Go adds a note that it comes from a plugin." + ], + [ + 2, + "+ See more, for detail and a help page." + ] + ], + "how": "Long-press the PIN (optional) heading. Code On The Go draws this: capture its real look.", + "real": true, + "captured": true + }, + { + "id": "S01", + "guide": "server", + "section": "Status", + "title": "Manage server, serving", + "key": [ + [ + 1, + "What the server is doing, and which store." + ], + [ + 2, + "The store's address. The button beside it copies it." + ], + [ + 3, + "The codes buyers scan." + ], + [ + 4, + "What Start will serve." + ] + ], + "how": "Open Share Your Apps Server while it serves your store, and capture the top of Manage server.", + "real": false, + "captured": true + }, + { + "id": "S02", + "guide": "server", + "section": "Status", + "title": "Storage access still needed", + "key": [ + [ + 1, + "Tap it and allow access, once: the server needs it to read your store's files." + ] + ], + "how": "Before allowing All files access to Share Your Apps Server, open it. (Or turn the access off in Android's Settings, capture, then turn it on again.)", + "real": false, + "captured": true + }, + { + "id": "S03", + "guide": "server", + "section": "Starting and stopping", + "title": "The Server panel", + "key": [ + [ + 1, + "The port, the number in the store's address. Its label has help; the field keeps its long-press for text." + ], + [ + 2, + "Start serving." + ], + [ + 3, + "Stop serving." + ], + [ + 4, + "The help pages." + ] + ], + "how": "In Manage server, capture the Server panel.", + "real": false, + "captured": true + }, + { + "id": "S04", + "guide": "server", + "section": "Letting buyers in", + "title": "The codes buyers scan, on a hotspot", + "key": [ + [ + 1, + "The first code joins buyers to the hotspot." + ], + [ + 2, + "The second opens the store." + ], + [ + 3, + "The tip for a buyer whose phone can't open it." + ] + ], + "how": "Turn Wi-Fi off, tap Start, then Show QR codes for buyers. Capture the whole screen, scrolling if needed.", + "real": false, + "captured": true + }, + { + "id": "S05", + "guide": "server", + "section": "Letting buyers in", + "title": "Making a join code for ordinary Wi-Fi", + "key": [ + [ + 1, + "What this is for: making a code that joins buyers to your Wi-Fi." + ], + [ + 2, + "The network's password, never saved." + ], + [ + 3, + "Show the code." + ] + ], + "how": "On ordinary Wi-Fi, open Show QR codes for buyers, and capture the part asking for the network's password.", + "real": false, + "captured": true + }, + { + "id": "S06", + "guide": "server", + "section": "The Wi-Fi Direct hotspot's name and password", + "title": "The Wi-Fi Direct hotspot panel", + "key": [ + [ + 1, + "Its name, after DIRECT-LS-." + ], + [ + 2, + "Its password, 8 to 63 characters." + ], + [ + 3, + "Keep them, for the next time the hotspot starts." + ], + [ + 4, + "Fill in a strong password." + ] + ], + "how": "In Manage server, capture the Wi-Fi Direct hotspot panel.", + "real": false, + "captured": true + }, + { + "id": "S07", + "guide": "server", + "section": "When to run", + "title": "When to run", + "key": [ + [ + 1, + "Keep serving whatever the screen does." + ], + [ + 2, + "Save battery: pause when the screen turns off, and resume on unlocking." + ] + ], + "how": "In Manage server, capture the When to run panel.", + "real": false, + "captured": true + }, + { + "id": "S08", + "guide": "server", + "section": "Sharing your store with another seller", + "title": "Starting a share", + "key": [ + [ + 1, + "Share a copy of your store, while it serves." + ] + ], + "how": "While your store serves, capture the Copies of this store panel.", + "real": false, + "captured": true + }, + { + "id": "S09", + "guide": "server", + "section": "Sharing your store with another seller", + "title": "The share code", + "key": [ + [ + 1, + "The large code: the other phone scans it to import." + ], + [ + 2, + "Or the other phone types this code; the icon copies it." + ], + [ + 3, + "One phone, for 10 minutes." + ], + [ + 4, + "For a phone without the app: a small code, or a link to open in its browser, with a button that copies it, to download Share Your Apps Server from this phone." + ] + ], + "how": "Tap Share this store\u2026, and capture the whole screen, scrolling if needed.", + "real": false, + "captured": true + }, + { + "id": "S10", + "guide": "server", + "section": "Sharing your store with another seller", + "title": "Allowing a copy", + "key": [ + [ + 1, + "These four digits must match the other phone's." + ], + [ + 2, + "When their copy expires." + ], + [ + 3, + "Deny, if the digits don't match." + ], + [ + 4, + "Allow, if they do." + ] + ], + "how": "With a second phone importing, capture the Allow a copy? screen, before choosing.", + "real": false, + "captured": true + }, + { + "id": "S11", + "guide": "server", + "section": "Importing someone else's store", + "title": "The Import a store panel", + "key": [ + [ + 1, + "Serve a copy of someone else's store, with their permission." + ], + [ + 2, + "Start importing. It's disabled, saying why, while the phone serves a store." + ] + ], + "how": "With the server stopped, capture the Import a store panel.", + "real": false, + "captured": true + }, + { + "id": "S12", + "guide": "server", + "section": "Logs", + "title": "The Logs panel", + "key": [ + [ + 1, + "How large each log file grows; 0 turns logging off." + ], + [ + 2, + "Read the logs, newest first." + ], + [ + 3, + "Send the log files off the phone." + ] + ], + "how": "In Manage server, capture the Logs panel.", + "real": false, + "captured": true + }, + { + "id": "S13", + "guide": "server", + "section": "Getting help", + "title": "A tooltip", + "key": [ + [ + 1, + "A short explanation, after long-pressing Start." + ], + [ + 2, + "+ See more, for more." + ] + ], + "how": "In Manage server, long-press the START button, and capture the tooltip.", + "real": false, + "captured": true + }, + { + "id": "S14", + "guide": "server", + "section": "Getting help", + "title": "After + See more", + "key": [ + [ + 1, + "The short explanation, and more." + ], + [ + 2, + "The help page, opening at this topic." + ] + ], + "how": "Long-press the START button, tap + See more, and capture the tooltip.", + "real": false, + "captured": true + }, + { + "id": "S15", + "guide": "server", + "section": "Getting help", + "title": "A help page", + "captured": true, + "real": false, + "how": "Long-press the START button, tap + See more, then tap Serving the store, and capture the page.", + "key": [ + [ + 1, + "The section the button opened: here, Start, Stop and the port. Scroll for the rest of the page." + ] + ] + }, + { + "id": "I01", + "guide": "seller", + "section": "1. Get the app", + "title": "Downloading the app", + "key": [ + [ + 1, + "Download anyway. Browsers warn about any app from outside the Play Store." + ] + ], + "how": "On the second phone, scan the owner's small QR code with the camera, open the link, and capture the browser's download prompt.", + "real": true, + "captured": true + }, + { + "id": "I02", + "guide": "seller", + "section": "2. Get the store", + "title": "Starting an import", + "key": [ + [ + 1, + "Tap Import a store\u2026." + ] + ], + "how": "On a phone with Share Your Apps Server but no store, open Manage server.", + "real": false, + "captured": true + }, + { + "id": "I03", + "guide": "seller", + "section": "2. Get the store", + "title": "The code, and your phone's name", + "key": [ + [ + 1, + "The owner's code, filled in from their QR code, or typed." + ], + [ + 2, + "What the owner sees." + ], + [ + 3, + "Ask for the copy." + ] + ], + "how": "Tap Import a store\u2026, type a code, and capture the screen before tapping Continue.", + "real": false, + "captured": true + }, + { + "id": "I04", + "guide": "seller", + "section": "2. Get the store", + "title": "The four digits, then its progress", + "key": [ + [ + 1, + "These digits must match the owner's screen." + ], + [ + 2, + "Its progress: here, waiting for the owner to allow it." + ] + ], + "how": "After Continue, and the owner allowing it, capture the screen while it receives the store.", + "real": false, + "captured": true + }, + { + "id": "I05", + "guide": "seller", + "section": "2. Get the store", + "title": "Imported", + "key": [ + [ + 1, + "Shown only if you joined the owner's hotspot: leave it first." + ], + [ + 2, + "Start serving the store." + ] + ], + "how": "Import over the owner's hotspot, and capture the last screen.", + "real": false, + "captured": true + }, + { + "id": "I06", + "guide": "seller", + "section": "2. Get the store", + "title": "If it stops partway", + "key": [ + [ + 1, + "Try again, while the owner's phone still shows the code." + ] + ], + "how": "Start an import, turn Wi-Fi off on the second phone partway, then on, and capture the screen.", + "real": false, + "captured": false + }, + { + "id": "I07", + "guide": "seller", + "section": "A PIN, if you want one", + "title": "Your copy, and its PIN", + "key": [ + [ + 1, + "Serve it, with the PIN below." + ], + [ + 2, + "Your own PIN, or none." + ], + [ + 3, + "Remove it from this phone." + ] + ], + "how": "With a copy imported and not serving, capture the store's panel in Manage server.", + "real": false, + "captured": true + }, + { + "id": "I08", + "guide": "seller", + "section": "3. Let people in", + "title": "The codes, for your buyers", + "key": [ + [ + 1, + "Show the codes people scan." + ] + ], + "how": "While serving the copy, capture the top of Manage server.", + "real": false, + "captured": true + }, + { + "id": "I09", + "guide": "seller", + "section": "When the store expires", + "title": "After the store expires", + "key": [ + [ + 1, + "Close the notice." + ] + ], + "how": "After a copy's date has passed, open Manage server. To see it sooner, import with In a week, then move the phone's date 8 days ahead; turn automatic date and time back on afterwards.", + "real": false, + "captured": true + }, + { + "id": "B01", + "guide": "buyer", + "section": "", + "title": "The store, in a buyer's browser", + "captured": true, + "real": false, + "how": "Not captured on a phone: the demo store, published with the plugin's code and served with the server's code, then shown in a phone-sized browser.", + "key": [ + [ + 1, + "Accessible version: the same store, plain and in large text." + ], + [ + 2, + "The store's name and description." + ], + [ + 3, + "Download APK: download the app." + ] + ] + }, + { + "id": "B02", + "guide": "buyer", + "section": "", + "title": "A product, with pictures", + "captured": true, + "real": false, + "how": "Not captured on a phone: the demo store, published with the plugin's code and served with the server's code, then shown in a phone-sized browser.", + "key": [ + [ + 1, + "The product's pictures and videos: swipe, or tap the arrow." + ], + [ + 2, + "What the app is, and which version." + ], + [ + 3, + "Download APK." + ], + [ + 4, + "Which phones this version is for." + ] + ] + }, + { + "id": "B03", + "guide": "buyer", + "section": "", + "title": "The accessible version", + "captured": true, + "real": false, + "how": "Not captured on a phone: the demo store, published with the plugin's code and served with the server's code, then shown in a phone-sized browser.", + "key": [ + [ + 1, + "Standard version: back to the usual page." + ], + [ + 2, + "Every app, as a list." + ] + ] + } +] \ No newline at end of file diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/README.md b/plugins/Share-Your-Apps/docs/user-guides/video/README.md new file mode 100644 index 000000000..2b2556b59 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/README.md @@ -0,0 +1,13 @@ +# The demo videos + +- `scenes.py` — both videos' scenes: the screen, the callouts to zoom to, the titles, and the narration. Each scene lasts as long as its narration takes at 144 words a minute, plus a pause. +- `render.py` — draws every frame from the annotated screens in `../screens/`, and encodes them with ffmpeg: `python3 render.py LONG share-your-apps-demo.mp4`, or `SHORT`. +- `script.py` — writes the narration files, timed to the videos: a readable script, SRT and VTT subtitles, JSON, and plain lines. + +- `slow.sh` — slows a recording, keeping its pitch, with ffmpeg's atempo: `sh slow.sh recording.mp3 slowed.wav 0.9`. Run it before `align.py`, and use the slowed file from then on. +- `align.py` — matches a recorded narration's lines to the scenes, from the recording's pauses, choosing all the boundaries together so every line fits one speaking rate: `python3 align.py dp`. +- `soundtrack.py` — re-times each scene to its recorded line, places each line at its scene's start, re-times the subtitles, and combines picture, voice and subtitles. + +With a recording: `python3 align.py dp`, then `python3 render.py LONG picture.mp4 LONG-segs.json`, then `python3 soundtrack.py LONG recording.mp3 picture.mp4 share-your-apps-demo.mp4 share-your-apps-demo-narration`. The same with `SHORT` for the short video. + +The scripts were written for the machine that rendered the videos; their paths to the screens, fonts and callout tool are at their tops. diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/align.py b/plugins/Share-Your-Apps/docs/user-guides/video/align.py new file mode 100644 index 000000000..e3ec2db21 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/align.py @@ -0,0 +1,65 @@ +import subprocess, re, sys, json +sys.path.insert(0, '/tmp/video'); import scenes +def silences(path, d=0.3): + out = subprocess.run(['ffmpeg', '-v', 'info', '-i', path, '-af', f'silencedetect=noise=-35dB:d={d}', '-f', 'null', '-'], capture_output=True, text=True).stderr + s = [float(x) for x in re.findall(r'silence_start: ([0-9.]+)', out)]; e = [float(x) for x in re.findall(r'silence_end: ([0-9.]+)', out)] + return list(zip(s, e)) +def duration(path): + return float(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', path], capture_output=True, text=True).stdout) +def align(path, which): + S = getattr(scenes, which); words = [len(s[4].split()) for s in S]; total = duration(path); sil = silences(path) + start = sil[0][1] if sil and sil[0][0] < 0.05 else 0.0; end = sil[-1][0] if sil and sil[-1][1] > total - 0.05 else total + cum = 0; bounds = []; used = set() + for k in range(len(S) - 1): + cum += words[k]; expect = start + (end - start) * cum / sum(words) + cands = [i for i, (a, b) in enumerate(sil) if i not in used and a > (sil[bounds[-1]][1] if bounds else start)] + i = min(cands, key=lambda i: abs((sil[i][0] + sil[i][1]) / 2 - expect)); bounds.append(i); used.add(i) + segs = []; a = start + for k in range(len(S)): + b = sil[bounds[k]][0] if k < len(S) - 1 else end + segs.append((round(max(a - 0.04, 0), 3), round(min(b + 0.08, total), 3))) + if k < len(S) - 1: a = sil[bounds[k]][1] + return segs +if __name__ == '__main__' and 'dp' not in sys.argv: + for which, f in (('SHORT', 'share_Your_Apps_promo'), ('LONG', 'Share_Your_Apps_demo')): + segs = align(f'/mnt/user-data/uploads/{f}.mp3', which); S = getattr(scenes, which) + json.dump(segs, open(f'/tmp/video/{which}-segs.json', 'w')) + print(f"== {which}: {len(segs)} lines") + for (a, b), s in zip(segs, S): + w = len(s[4].split()); print(f" {a:7.2f}-{b:7.2f} {b-a:5.2f}s {w:2d} words {w/(b-a)*60:4.0f} wpm {s[4][:60]}") + +def align_dp(path, which): + """Choose all line boundaries at once, from the recording's pauses, so every line's length best fits one speaking rate.""" + S = getattr(scenes, which); words = [len(s[4].split()) for s in S]; L = len(S) + total = duration(path); sil = silences(path, 0.25) + start = sil[0][1] if sil and sil[0][0] < 0.05 else 0.0; end = sil[-1][0] if sil and sil[-1][1] > total - 0.05 else total + inner = [(a, b) for a, b in sil if a > start + 0.05 and b < end - 0.05] + pts = [(None, start)] + inner + [(end, None)] # boundary k: speech ends at pts[k][0], next starts at pts[k][1] + spw = (end - start) / sum(words) + for _ in range(4): + INF = float('inf'); M = len(pts) + dp = [[INF] * M for _ in range(L + 1)]; back = [[-1] * M for _ in range(L + 1)]; dp[0][0] = 0 + for k in range(1, L + 1): + for j in range(1, M): + if k == L and j != M - 1: continue + if k < L and j == M - 1: continue + for i in range(j): + if dp[k - 1][i] == INF: continue + d = pts[j][0] - pts[i][1] + if d <= 0: continue + c = dp[k - 1][i] + ((d - words[k - 1] * spw) ** 2) / (words[k - 1] * spw) + if c < dp[k][j]: dp[k][j] = c; back[k][j] = i + js = [M - 1] + for k in range(L, 0, -1): js.append(back[k][js[-1]]) + js = js[::-1] + segs = [(pts[js[k]][1], pts[js[k + 1]][0]) for k in range(L)] + spw = sum(b - a for a, b in segs) / sum(words) + return [(round(max(a - 0.04, 0), 3), round(min(b + 0.08, total), 3)) for a, b in segs], spw + +if __name__ == '__main__' and 'dp' in sys.argv: + for which, f in (('SHORT', 'share_Your_Apps_promo'), ('LONG', 'Share_Your_Apps_demo')): + segs, spw = align_dp(f'/mnt/user-data/uploads/{f}.mp3', which); S = getattr(scenes, which) + json.dump(segs, open(f'/tmp/video/{which}-segs.json', 'w')) + rates = [len(s[4].split()) / (b - a) * 60 for (a, b), s in zip(segs, S)] + print(f"== {which}: {len(segs)} lines, overall {60/spw:.0f} wpm, lines from {min(rates):.0f} to {max(rates):.0f} wpm") + for (a, b), s, r in zip(segs, S, rates): print(f" {a:7.2f}-{b:7.2f} {b-a:5.2f}s {r:4.0f} wpm {s[4][:58]}") diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/render.py b/plugins/Share-Your-Apps/docs/user-guides/video/render.py new file mode 100644 index 000000000..24725d81e --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/render.py @@ -0,0 +1,131 @@ +"""Renders a demo video from the guides' annotated screens: scene by scene, zooming to each scene's callout.""" +import sys, os, json, math, subprocess, textwrap +sys.path.insert(0, '/tmp/video'); sys.path.insert(0, '/tmp/real') +from PIL import Image, ImageDraw, ImageFont, ImageFilter +import scenes, annotate +W, H, FPS = 1920, 1080, 30 +INK = (23, 19, 31); PANEL = (34, 29, 45); RED = (255, 79, 58); CREAM = (255, 243, 214); WHITE = (245, 242, 248); MUTED = (170, 162, 184); TEAL = (11, 110, 110) +def font(size, weight=400): + f = ImageFont.truetype('/tmp/fonts/Roboto.ttf', size) + try: f.set_variation_by_axes([weight, 100]) # weight first, then width + except Exception: pass + return f +F_PART, F_TITLE, F_CAP, F_SMALL, F_CARD, F_CARDCAP = font(30, 700), font(76, 700), font(40, 400), font(26, 500), font(120, 800), font(44, 400) +OCTO = Image.open('/home/claude/repo-docs/docs/user-guides/octopus.png').convert('RGBA') +SCREENS = '/tmp/real/out' +VH = 900; VW = int(VH * 1440 / 3088) # the phone's screen, on the video +PX, PY = 300, (H - VH) // 2 - 10 # its top-left corner + +def background(): + bg = Image.new('RGB', (W, H), INK); d = ImageDraw.Draw(bg) + for y in range(H): # a gentle vertical glow + k = 1 - abs(y - H * 0.45) / H; d.line((0, y, W, y), fill=tuple(int(c + 10 * k) for c in INK)) + return bg +BG = background() + +def wrap(d, text, f, width): + words, lines, cur = text.split(), [], '' + for w in words: + t = (cur + ' ' + w).strip() + if d.textlength(t, font=f) <= width: cur = t + else: lines.append(cur); cur = w + if cur: lines.append(cur) + return lines + +def chrome(img, t_total, t_now): + """The wordmark, and a thin progress bar along the bottom.""" + d = ImageDraw.Draw(img) + o = OCTO.resize((44, 44)); img.paste(o, (60, H - 70), o) + d.text((116, H - 60), 'Share Your Apps', font=F_SMALL, fill=MUTED) + d.rectangle((0, H - 6, W, H), fill=(45, 39, 58)); d.rectangle((0, H - 6, int(W * t_now / t_total), H), fill=RED) + +def text_panel(img, part, title, caption): + d = ImageDraw.Draw(img); x = PX + VW + 150; wmax = W - x - 110; y = 300 + if part: d.text((x, y), part.upper(), font=F_PART, fill=RED); y += 60 + for line in wrap(d, title, F_TITLE, wmax): d.text((x, y), line, font=F_TITLE, fill=WHITE); y += 90 + y += 30 + for line in wrap(d, caption, F_CAP, wmax): d.text((x, y), line, font=F_CAP, fill=CREAM); y += 56 + +def card(part, title, caption): + img = BG.copy(); d = ImageDraw.Draw(img) + o = OCTO.resize((170, 170)); img.paste(o, ((W - 170) // 2, 170), o) + y = 380 + if part: tw = d.textlength(part.upper(), font=F_PART); d.text(((W - tw) / 2, y), part.upper(), font=F_PART, fill=RED); y += 60 + tw = d.textlength(title, font=F_CARD); d.text(((W - tw) / 2, y), title, font=F_CARD, fill=WHITE); y += 170 + for line in wrap(d, caption, F_CARDCAP, 1300): + tw = d.textlength(line, font=F_CARDCAP); d.text(((W - tw) / 2, y), line, font=F_CARDCAP, fill=CREAM); y += 62 + return img + +def phone_base(part, title, caption): + """Everything but the moving screen: the background, the phone's body, and the text.""" + img = BG.copy(); d = ImageDraw.Draw(img) + sh = Image.new('RGBA', (VW + 80, VH + 80), (0, 0, 0, 0)); ImageDraw.Draw(sh).rounded_rectangle((20, 30, VW + 60, VH + 70), 56, fill=(0, 0, 0, 150)) + sh = sh.filter(ImageFilter.GaussianBlur(18)); img.paste(sh, (PX - 40, PY - 30), sh) + d.rounded_rectangle((PX - 16, PY - 16, PX + VW + 16, PY + VH + 16), 50, fill=(8, 6, 12), outline=(70, 62, 86), width=3) + text_panel(img, part, title, caption) + return img + +def target_box(sid, im): + """The zoom's target: the scene's callout box, in the annotated screen's pixels.""" + src = f'/tmp/real/{sid}.jpg'; orig = Image.open(src).convert('RGB') + if sid in annotate.CROP: orig = orig.crop((0, 0, orig.width, annotate.CROP[sid])) + return {n: tuple(v * im.width / orig.width for v in b) for n, b in annotate.boxes_for(sid, orig).items()} + +def ease(u): return 0.5 - 0.5 * math.cos(math.pi * min(max(u, 0), 1)) + +def frames(scene, t0, total): + sid, co, part, title, cap = scene + dur = scenes.duration(cap); n = int(round(dur * FPS)) + if sid == 'card': + base = card(part, title, cap); get = lambda f: base + else: + base = phone_base(part, title, cap) + im = Image.open(f'{SCREENS}/{sid}.jpg').convert('RGB'); iw, ih = im.size + ar = VW / VH; w0 = iw; h0 = w0 / ar + if co: + tb = target_box(sid, im); cs = co if isinstance(co, tuple) else (co,) # several callouts: zoom to all of them + bs = [tb[c] for c in cs]; bx = (min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)) + cx, cy = (bx[0] + bx[2]) / 2, (bx[1] + bx[3]) / 2 + # Zoom in only as far as the whole outline still fits, with room for its bubble on either side. + need = (bx[2] - bx[0]) + 0.2 * iw + z = max(min(0.82 * iw / max(bx[2] - bx[0], 1), 1.9, iw / need), 1.0) + else: cx, cy, z = iw / 2, h0 / 2, 1.06 + w1 = iw / z; h1 = w1 / ar + def win(w, h, cx, cy): + x = min(max(cx - w / 2, 0), iw - w); y = min(max(cy - h / 2, 0), max(ih - h, 0)); return x, y, w, h + start = win(w0, h0, cx, cy); end = win(w1, h1, cx, cy) + pad = h0 > ih + def get(f): + u = ease((f / n - 0.12) / 0.6) + x, y, w, h = [a + (b - a) * u for a, b in zip(start, end)] + x = min(max(x, 0), iw - w) + if y + h > ih: # a screen shorter than the phone: letterbox it below + canvas = Image.new('RGB', (iw, int(math.ceil(y + h)) + 2), (20, 20, 24)); canvas.paste(im, (0, 0)); src = canvas + else: src = im + view = src.resize((VW, VH), Image.BILINEAR, box=(x, max(y, 0), x + w, max(y, 0) + h)) + out = base.copy(); mask = Image.new('L', (VW, VH), 0); ImageDraw.Draw(mask).rounded_rectangle((0, 0, VW - 1, VH - 1), 36, fill=255) + out.paste(view, (PX, PY), mask); return out + fade = int(0.35 * FPS) + for f in range(n): + img = get(f).copy(); chrome(img, total, t0 + f / FPS) + a = min(1, f / fade, (n - 1 - f) / fade) if fade else 1 + if a < 1: img = Image.blend(BG, img, max(a, 0)) + yield img + return dur + +def render(which, out): + S = getattr(scenes, which); total = sum(scenes.duration(s[4]) for s in S) + p = subprocess.Popen(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{W}x{H}', '-r', str(FPS), '-i', '-', + '-c:v', 'libx264', '-preset', 'medium', '-crf', '19', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out], stdin=subprocess.PIPE) + t = 0 + for sc in S: + for img in frames(sc, t, total): p.stdin.write(img.tobytes()) + t += scenes.duration(sc[4]) + p.stdin.close(); p.wait(); return total + +if __name__ == '__main__': + if sys.argv[1] == 'frame': + S = getattr(scenes, sys.argv[2]); sc = S[int(sys.argv[3])]; fs = list(frames(sc, 0, 100)); fs[int(len(fs) * 0.85)].save(sys.argv[4]) + else: + if len(sys.argv) > 3: scenes.timed(sys.argv[1], json.load(open(sys.argv[3]))) # times from a recorded narration + print(render(sys.argv[1], sys.argv[2])) diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/scenes.py b/plugins/Share-Your-Apps/docs/user-guides/video/scenes.py new file mode 100644 index 000000000..8871eaf82 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/scenes.py @@ -0,0 +1,58 @@ +# Each scene: (screen ID or 'card', the callout to zoom to — or None for the whole screen, part, title, narration). +LONG = [ + ('card', None, '', 'Share Your Apps', "Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts."), + ('card', None, '', 'Two parts', "It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot."), + ('card', None, 'Part one', 'Creating your store', "First, creating your store."), + ('P01', None, 'Creating your store', 'Install the plugin', "Install the plugin from Code On The Go's Addons Manager."), + ('P02', 1, 'Creating your store', 'Name your store', "In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional."), + ('P04', 2, 'Creating your store', 'Add your apps', "Add a product for each app. Each card shows what buyers can download."), + ('P05', 3, 'Creating your store', 'Choose the APK', "Choose the app's project, and the APK that buyers will install."), + ('P07', 4, 'Creating your store', 'Add pictures', "Add screenshots and videos, so buyers can see what they're getting."), + ('P08', 2, 'Creating your store', 'Describe them', "Describe each picture, for buyers who use a screen reader."), + ('P11', (1, 2), 'Creating your store', 'Publish', "Then tap Publish, and confirm."), + ('P12', 1, 'Creating your store', 'Allow, once', "The first time, Android asks you to allow a few things. Each one is needed just once."), + ('P15', 2, 'Creating your store', 'Change the look', "Choose a template to change the store's look, or write your own."), + ('P13', 1, 'Creating your store', 'Done', "When it's done, every file has been checked. And the store is already being served."), + ('card', None, 'Part two', 'Serving your store', "Next, letting people in."), + ('S01', 1, 'Serving your store', 'Share Your Apps Server', "Share Your Apps Server shows what it's serving, and where."), + ('S04', 1, 'Serving your store', 'The codes', "Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store."), + ('S06', 1, 'Serving your store', 'No Wi-Fi? No problem', "With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose."), + ('B01', 2, 'Serving your store', "The buyer's view", "Buyers see your store in their browser."), + ('B02', 1, 'Serving your store', 'Pictures and downloads', "Each app has its pictures, its description, and its downloads. One tap, and it's on their phone."), + ('B03', 2, 'Serving your store', 'Accessible, too', "And every store has an accessible version, plain and in large text."), + ('S07', 1, 'Serving your store', 'When to run', "Keep serving when the screen is off, or pause to save battery."), + ('card', None, 'Part three', 'Sharing with another seller', "Finally, sharing your store with another phone."), + ('S08', 1, 'Sharing your store', 'Share this store', "Someone nearby can serve a copy of your store from their own phone. Tap Share this store."), + ('S09', 1, 'Sharing your store', 'Two codes', "Their phone scans the large code. The small one lets a phone without the app download it first."), + ('I03', 1, 'Sharing your store', 'Import a store', "On their phone, they tap Import a store, and scan the code, or type it."), + ('I04', (1, 2), 'Sharing your store', 'Four digits', "Both phones show the same four digits, so you know you're sharing with the phone in front of you."), + ('S10', (1, 3, 4), 'Sharing your store', 'Allow a copy', "You choose when their copy expires, and tap Allow."), + ('I05', 2, 'Sharing your store', 'Imported', "The copy arrives, and they tap Serve it now."), + ('I07', 2, 'Sharing your store', 'Their own PIN', "They can set their own PIN. But they can't change the store, or pass it on."), + ('I08', 1, 'Sharing your store', 'Their buyers', "They let people in the same way, with codes of their own."), + ('I09', 1, 'Sharing your store', 'When it expires', "And on the date you chose, the copy is deleted from their phone."), + ('card', None, '', 'Share Your Apps', "Share Your Apps, from App Dev for All. Share what you build, with the people around you."), +] +SHORT = [ + ('card', None, '', 'Share Your Apps', "Share Your Apps: share the apps you build, with people nearby."), + ('P11', (1, 2), 'Publish', 'From Code On The Go', "Publish your apps, right from Code On The Go."), + ('S04', 1, 'Let people in', 'Scan to join', "Buyers scan one code to join your phone's hotspot, and another to open the store."), + ('B01', 2, 'No internet needed', 'Your store', "No internet, and no accounts. Just your store, in their browser."), + ('B02', 3, 'One tap', 'Download', "One tap, and the app is on their phone."), + ('card', None, '', 'Share Your Apps', "Share Your Apps, from App Dev for All."), +] +WPS = 2.4 # words a second: 144 a minute +PAUSE = 1.1 # seconds of silence after each line +DUR = {} # scene lengths set from a recorded narration, by each line's text; otherwise, from its words +def duration(text, minimum=3.2): + if text in DUR: return DUR[text] + return round(max(len(text.split()) / WPS + PAUSE, minimum), 2) + +LEAD = {'LONG': 0.4, 'SHORT': 0.3}; GAP = {'LONG': 1.5, 'SHORT': 1.0} +def timed(which, segs): + """Sets each scene's length from its recorded line: a lead-in, the line, and a pause. Returns each line's start in the video.""" + S = globals()[which]; t = 0; starts = [] + for (a, b), sc in zip(segs, S): + d = round(max(LEAD[which] + (b - a) + GAP[which], 3.0), 2); DUR[sc[4]] = d + starts.append(round(t + LEAD[which], 3)); t += d + return starts, round(t, 2) diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/script.py b/plugins/Share-Your-Apps/docs/user-guides/video/script.py new file mode 100644 index 000000000..5190e46b1 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/script.py @@ -0,0 +1,31 @@ +import sys, json; sys.path.insert(0, '/tmp/video'); import scenes +LEAD = 0.3; TAIL = 0.4 +def ts(t, sep=','): + h, r = divmod(t, 3600); m, s = divmod(r, 60); return f"{int(h):02d}:{int(m):02d}:{int(s):02d}{sep}{int(round((s % 1) * 1000)):03d}" +def build(which, stem, title): + S = getattr(scenes, which); t = 0; rows = [] + for n, (sid, co, part, head, text) in enumerate(S, 1): + d = scenes.duration(text); a = t + LEAD; b = t + d - TAIL + rows.append(dict(scene=n, start=round(a, 2), end=round(b, 2), max_seconds=round(b - a, 2), words=len(text.split()), + on_screen=('Title card' if sid == 'card' else f"Screen {sid}") + f": {head}", part=part, text=text)) + t += d + total = round(t, 2) + with open(f'{stem}.srt', 'w') as f: + for r in rows: f.write(f"{r['scene']}\n{ts(r['start'])} --> {ts(r['end'])}\n{r['text']}\n\n") + with open(f'{stem}.vtt', 'w') as f: + f.write("WEBVTT\n\n") + for r in rows: f.write(f"{ts(r['start'], '.')} --> {ts(r['end'], '.')}\n{r['text']}\n\n") + json.dump(dict(title=title, duration_seconds=total, words_per_minute=int(scenes.WPS * 60), lines=rows), open(f'{stem}.json', 'w'), indent=1) + open(f'{stem}-lines.txt', 'w').write('\n'.join(r['text'] for r in rows) + '\n') + md = [f"# {title}: narration script", "", + f"Length **{int(total // 60)}:{total % 60:04.1f}**, at about **{int(scenes.WPS * 60)} words a minute**. Each line starts {LEAD} s into its scene, after the fade-in, and must end by its *End* time; the rest of the scene is a pause.", "", + "**For a voice tool:** import the `.srt` or `.vtt` file, whose timings match the video, or read the lines from the `-lines.txt` file, one per scene. If a generated line runs longer than its *Max*, speed it up slightly, or shorten the pause after it. The `.json` file has the same timings, for tools that take structured input.", "", + "**Voice:** warm, clear and unhurried, like a friendly guide showing someone an app. Neutral accent. Pause briefly at each full stop.", "", + "**Pronunciations:** *APK* is spelled out, A-P-K. *PIN* rhymes with *tin*. *Wi-Fi* is *why-fye*. *Code On The Go* is one name, said evenly.", "", + "| # | Start | End | Max | On screen | Narration |", "|---|---|---|---|---|---|"] + for r in rows: md.append(f"| {r['scene']} | {ts(r['start'], '.')[3:]} | {ts(r['end'], '.')[3:]} | {r['max_seconds']:.1f} s | {r['on_screen']} | {r['text']} |") + open(f'{stem}-script.md', 'w').write('\n'.join(md) + '\n') + return total, len(rows) +if __name__ == '__main__': + print(build('LONG', '/tmp/video/share-your-apps-demo-narration', 'Share Your Apps demo')) + print(build('SHORT', '/tmp/video/share-your-apps-demo-short-narration', 'Share Your Apps demo, short')) diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/slow.sh b/plugins/Share-Your-Apps/docs/user-guides/video/slow.sh new file mode 100644 index 000000000..c5b5c5da0 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/slow.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Slows a recorded narration, keeping its pitch, with ffmpeg's atempo filter — which sounded better on this voice +# than Rubber Band. The videos use 0.9: halfway between the recording's own pace and 0.8, which was usable but slow. +# Usage: sh slow.sh input.mp3 output.wav [tempo] — tempo defaults to 0.9 +T=${3:-0.9} +ffmpeg -y -i "$1" -af "atempo=$T" -ar 44100 -ac 1 "$2" diff --git a/plugins/Share-Your-Apps/docs/user-guides/video/soundtrack.py b/plugins/Share-Your-Apps/docs/user-guides/video/soundtrack.py new file mode 100644 index 000000000..d4467d6d4 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/video/soundtrack.py @@ -0,0 +1,23 @@ +import sys, json, subprocess; sys.path.insert(0, '/tmp/video'); import scenes +from script import ts +def build(which, mp3, video, out, stem): + segs = json.load(open(f'/tmp/video/{which}-segs.json')); starts, total = scenes.timed(which, segs); S = getattr(scenes, which) + parts = [f"[0:a]atrim=start={a}:end={b},asetpts=PTS-STARTPTS,afade=t=in:d=0.02,afade=t=out:st={max(b - a - 0.06, 0):.3f}:d=0.06,adelay={int(st * 1000)}:all=1[a{k}]" + for k, ((a, b), st) in enumerate(zip(segs, starts))] + mix = ''.join(f'[a{k}]' for k in range(len(segs))) + f"amix=inputs={len(segs)}:normalize=0,apad,atrim=end={total}[mix]" + subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', mp3, '-filter_complex', ';'.join(parts + [mix]), '-map', '[mix]', '-c:a', 'pcm_s16le', f'/tmp/video/{which}.wav'], check=True) + # Subtitles, timed to the voice: each line from its start to its end in the video. + rows = [(st, st + (b - a), sc[4]) for (a, b), st, sc in zip(segs, starts, S)] + with open(f'{stem}.srt', 'w') as f: + for n, (a, b, t) in enumerate(rows, 1): f.write(f"{n}\n{ts(a)} --> {ts(b)}\n{t}\n\n") + with open(f'{stem}.vtt', 'w') as f: + f.write("WEBVTT\n\n") + for a, b, t in rows: f.write(f"{ts(a, '.')} --> {ts(b, '.')}\n{t}\n\n") + subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', video, '-i', f'/tmp/video/{which}.wav', '-i', f'{stem}.srt', + '-map', '0:v', '-map', '1:a', '-map', '2', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '160k', '-c:s', 'mov_text', + '-metadata:s:a:0', 'language=eng', '-metadata:s:s:0', 'language=eng', '-metadata:s:s:0', 'title=Narration', + '-t', f'{total}', '-movflags', '+faststart', out], check=True) + return total, rows +if __name__ == '__main__': + which, mp3, video, out, stem = sys.argv[1:6] + total, rows = build(which, mp3, video, out, stem); print(which, total, 's,', len(rows), 'lines placed') diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-lines.txt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-lines.txt new file mode 100644 index 000000000..cc518012b --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-lines.txt @@ -0,0 +1,32 @@ +Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts. +It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot. +First, creating your store. +Install the plugin from Code On The Go's Addons Manager. +In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional. +Add a product for each app. Each card shows what buyers can download. +Choose the app's project, and the APK that buyers will install. +Add screenshots and videos, so buyers can see what they're getting. +Describe each picture, for buyers who use a screen reader. +Then tap Publish, and confirm. +The first time, Android asks you to allow a few things. Each one is needed just once. +Choose a template to change the store's look, or write your own. +When it's done, every file has been checked. And the store is already being served. +Next, letting people in. +Share Your Apps Server shows what it's serving, and where. +Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store. +With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose. +Buyers see your store in their browser. +Each app has its pictures, its description, and its downloads. One tap, and it's on their phone. +And every store has an accessible version, plain and in large text. +Keep serving when the screen is off, or pause to save battery. +Finally, sharing your store with another phone. +Someone nearby can serve a copy of your store from their own phone. Tap Share this store. +Their phone scans the large code. The small one lets a phone without the app download it first. +On their phone, they tap Import a store, and scan the code, or type it. +Both phones show the same four digits, so you know you're sharing with the phone in front of you. +You choose when their copy expires, and tap Allow. +The copy arrives, and they tap Serve it now. +They can set their own PIN. But they can't change the store, or pass it on. +They let people in the same way, with codes of their own. +And on the date you chose, the copy is deleted from their phone. +Share Your Apps, from App Dev for All. Share what you build, with the people around you. diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-script.md b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-script.md new file mode 100644 index 000000000..0961e0788 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration-script.md @@ -0,0 +1,38 @@ +# Share Your Apps demo: narration, as recorded + +Recorded narration: `Share_Your_Apps_demo.mp3, slowed to 0.9 with atempo`. The video is **3:14.8** long. Each line plays at its *Start* in the video, taken from *Recording* in the slowed file. + +| # | Start | End | Recording | On screen | Narration | +|---|---|---|---|---|---| +| 1 | 00:00.400 | 00:08.402 | 0.00–8.00 s | Title card: Share Your Apps | Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts. | +| 2 | 00:10.300 | 00:20.145 | 8.40–18.25 s | Title card: Two parts | It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot. | +| 3 | 00:22.050 | 00:23.683 | 18.81–20.44 s | Title card: Creating your store | First, creating your store. | +| 4 | 00:25.580 | 00:28.667 | 20.92–24.01 s | Screen P01: Install the plugin | Install the plugin from Code On The Go's Addons Manager. | +| 5 | 00:30.570 | 00:36.705 | 24.45–30.59 s | Screen P02: Name your store | In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional. | +| 6 | 00:38.600 | 00:42.905 | 31.06–35.36 s | Screen P04: Add your apps | Add a product for each app. Each card shows what buyers can download. | +| 7 | 00:44.810 | 00:48.415 | 35.74–39.35 s | Screen P05: Choose the APK | Choose the app's project, and the APK that buyers will install. | +| 8 | 00:50.320 | 00:53.675 | 39.79–43.15 s | Screen P07: Add pictures | Add screenshots and videos, so buyers can see what they're getting. | +| 9 | 00:55.570 | 00:58.465 | 43.58–46.47 s | Screen P08: Describe them | Describe each picture, for buyers who use a screen reader. | +| 10 | 01:00.360 | 01:02.365 | 46.90–48.90 s | Screen P11: Publish | Then tap Publish, and confirm. | +| 11 | 01:04.260 | 01:09.314 | 49.35–54.40 s | Screen P12: Allow, once | The first time, Android asks you to allow a few things. Each one is needed just once. | +| 12 | 01:11.210 | 01:15.503 | 54.80–59.10 s | Screen P15: Change the look | Choose a template to change the store's look, or write your own. | +| 13 | 01:17.400 | 01:22.005 | 59.28–63.88 s | Screen P13: Done | When it's done, every file has been checked. And the store is already being served. | +| 14 | 01:23.900 | 01:24.912 | 64.03–65.05 s | Title card: Serving your store | Next, letting people in. | +| 15 | 01:26.900 | 01:29.917 | 65.44–68.46 s | Screen S01: Share Your Apps Server | Share Your Apps Server shows what it's serving, and where. | +| 16 | 01:31.820 | 01:39.018 | 68.88–76.08 s | Screen S04: The codes | Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store. | +| 17 | 01:40.920 | 01:46.381 | 76.49–81.95 s | Screen S06: No Wi-Fi? No problem | With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose. | +| 18 | 01:48.280 | 01:50.347 | 82.34–84.41 s | Screen B01: The buyer's view | Buyers see your store in their browser. | +| 19 | 01:52.250 | 01:58.009 | 84.79–90.55 s | Screen B02: Pictures and downloads | Each app has its pictures, its description, and its downloads. One tap, and it's on their phone. | +| 20 | 01:59.910 | 02:03.843 | 90.97–94.91 s | Screen B03: Accessible, too | And every store has an accessible version, plain and in large text. | +| 21 | 02:05.740 | 02:09.197 | 95.29–98.75 s | Screen S07: When to run | Keep serving when the screen is off, or pause to save battery. | +| 22 | 02:11.100 | 02:13.640 | 99.31–101.85 s | Title card: Sharing with another seller | Finally, sharing your store with another phone. | +| 23 | 02:15.540 | 02:20.826 | 102.26–107.55 s | Screen S08: Share this store | Someone nearby can serve a copy of your store from their own phone. Tap Share this store. | +| 24 | 02:22.730 | 02:28.093 | 107.94–113.30 s | Screen S09: Two codes | Their phone scans the large code. The small one lets a phone without the app download it first. | +| 25 | 02:29.990 | 02:34.427 | 113.75–118.18 s | Screen I03: Import a store | On their phone, they tap Import a store, and scan the code, or type it. | +| 26 | 02:36.330 | 02:40.842 | 118.58–123.09 s | Screen I04: Four digits | Both phones show the same four digits, so you know you're sharing with the phone in front of you. | +| 27 | 02:42.740 | 02:45.915 | 123.49–126.66 s | Screen S10: Allow a copy | You choose when their copy expires, and tap Allow. | +| 28 | 02:47.810 | 02:50.537 | 127.09–129.82 s | Screen I05: Imported | The copy arrives, and they tap Serve it now. | +| 29 | 02:52.440 | 02:56.488 | 130.22–134.27 s | Screen I07: Their own PIN | They can set their own PIN. But they can't change the store, or pass it on. | +| 30 | 02:58.390 | 03:01.285 | 134.67–137.57 s | Screen I08: Their buyers | They let people in the same way, with codes of their own. | +| 31 | 03:03.190 | 03:06.411 | 138.00–141.22 s | Screen I09: When it expires | And on the date you chose, the copy is deleted from their phone. | +| 32 | 03:08.310 | 03:13.343 | 141.72–146.75 s | Title card: Share Your Apps | Share Your Apps, from App Dev for All. Share what you build, with the people around you. | diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.json b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.json new file mode 100644 index 000000000..5983ea9e1 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.json @@ -0,0 +1,295 @@ +{ + "title": "Share Your Apps demo", + "recording": "Share_Your_Apps_demo.mp3, slowed to 0.9 with atempo", + "duration_seconds": 194.84, + "lines": [ + { + "scene": 1, + "start": 0.4, + "end": 8.402, + "recording_from": 0, + "recording_to": 8.002, + "on_screen": "Title card: Share Your Apps", + "text": "Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts." + }, + { + "scene": 2, + "start": 10.3, + "end": 20.145, + "recording_from": 8.403, + "recording_to": 18.248, + "on_screen": "Title card: Two parts", + "text": "It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot." + }, + { + "scene": 3, + "start": 22.05, + "end": 23.683, + "recording_from": 18.807, + "recording_to": 20.44, + "on_screen": "Title card: Creating your store", + "text": "First, creating your store." + }, + { + "scene": 4, + "start": 25.58, + "end": 28.667, + "recording_from": 20.92, + "recording_to": 24.007, + "on_screen": "Screen P01: Install the plugin", + "text": "Install the plugin from Code On The Go's Addons Manager." + }, + { + "scene": 5, + "start": 30.57, + "end": 36.705, + "recording_from": 24.454, + "recording_to": 30.589, + "on_screen": "Screen P02: Name your store", + "text": "In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional." + }, + { + "scene": 6, + "start": 38.6, + "end": 42.905, + "recording_from": 31.057, + "recording_to": 35.362, + "on_screen": "Screen P04: Add your apps", + "text": "Add a product for each app. Each card shows what buyers can download." + }, + { + "scene": 7, + "start": 44.81, + "end": 48.415, + "recording_from": 35.745, + "recording_to": 39.35, + "on_screen": "Screen P05: Choose the APK", + "text": "Choose the app's project, and the APK that buyers will install." + }, + { + "scene": 8, + "start": 50.32, + "end": 53.675, + "recording_from": 39.792, + "recording_to": 43.147, + "on_screen": "Screen P07: Add pictures", + "text": "Add screenshots and videos, so buyers can see what they're getting." + }, + { + "scene": 9, + "start": 55.57, + "end": 58.465, + "recording_from": 43.575, + "recording_to": 46.47, + "on_screen": "Screen P08: Describe them", + "text": "Describe each picture, for buyers who use a screen reader." + }, + { + "scene": 10, + "start": 60.36, + "end": 62.365, + "recording_from": 46.895, + "recording_to": 48.9, + "on_screen": "Screen P11: Publish", + "text": "Then tap Publish, and confirm." + }, + { + "scene": 11, + "start": 64.26, + "end": 69.314, + "recording_from": 49.346, + "recording_to": 54.4, + "on_screen": "Screen P12: Allow, once", + "text": "The first time, Android asks you to allow a few things. Each one is needed just once." + }, + { + "scene": 12, + "start": 71.21, + "end": 75.503, + "recording_from": 54.803, + "recording_to": 59.096, + "on_screen": "Screen P15: Change the look", + "text": "Choose a template to change the store's look, or write your own." + }, + { + "scene": 13, + "start": 77.4, + "end": 82.005, + "recording_from": 59.277, + "recording_to": 63.882, + "on_screen": "Screen P13: Done", + "text": "When it's done, every file has been checked. And the store is already being served." + }, + { + "scene": 14, + "start": 83.9, + "end": 84.912, + "recording_from": 64.034, + "recording_to": 65.046, + "on_screen": "Title card: Serving your store", + "text": "Next, letting people in." + }, + { + "scene": 15, + "start": 86.9, + "end": 89.917, + "recording_from": 65.443, + "recording_to": 68.46, + "on_screen": "Screen S01: Share Your Apps Server", + "text": "Share Your Apps Server shows what it's serving, and where." + }, + { + "scene": 16, + "start": 91.82, + "end": 99.018, + "recording_from": 68.879, + "recording_to": 76.077, + "on_screen": "Screen S04: The codes", + "text": "Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store." + }, + { + "scene": 17, + "start": 100.92, + "end": 106.381, + "recording_from": 76.492, + "recording_to": 81.953, + "on_screen": "Screen S06: No Wi-Fi? No problem", + "text": "With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose." + }, + { + "scene": 18, + "start": 108.28, + "end": 110.347, + "recording_from": 82.342, + "recording_to": 84.409, + "on_screen": "Screen B01: The buyer's view", + "text": "Buyers see your store in their browser." + }, + { + "scene": 19, + "start": 112.25, + "end": 118.009, + "recording_from": 84.789, + "recording_to": 90.548, + "on_screen": "Screen B02: Pictures and downloads", + "text": "Each app has its pictures, its description, and its downloads. One tap, and it's on their phone." + }, + { + "scene": 20, + "start": 119.91, + "end": 123.843, + "recording_from": 90.975, + "recording_to": 94.908, + "on_screen": "Screen B03: Accessible, too", + "text": "And every store has an accessible version, plain and in large text." + }, + { + "scene": 21, + "start": 125.74, + "end": 129.197, + "recording_from": 95.288, + "recording_to": 98.745, + "on_screen": "Screen S07: When to run", + "text": "Keep serving when the screen is off, or pause to save battery." + }, + { + "scene": 22, + "start": 131.1, + "end": 133.64, + "recording_from": 99.308, + "recording_to": 101.848, + "on_screen": "Title card: Sharing with another seller", + "text": "Finally, sharing your store with another phone." + }, + { + "scene": 23, + "start": 135.54, + "end": 140.826, + "recording_from": 102.263, + "recording_to": 107.549, + "on_screen": "Screen S08: Share this store", + "text": "Someone nearby can serve a copy of your store from their own phone. Tap Share this store." + }, + { + "scene": 24, + "start": 142.73, + "end": 148.093, + "recording_from": 107.935, + "recording_to": 113.298, + "on_screen": "Screen S09: Two codes", + "text": "Their phone scans the large code. The small one lets a phone without the app download it first." + }, + { + "scene": 25, + "start": 149.99, + "end": 154.427, + "recording_from": 113.745, + "recording_to": 118.182, + "on_screen": "Screen I03: Import a store", + "text": "On their phone, they tap Import a store, and scan the code, or type it." + }, + { + "scene": 26, + "start": 156.33, + "end": 160.842, + "recording_from": 118.582, + "recording_to": 123.094, + "on_screen": "Screen I04: Four digits", + "text": "Both phones show the same four digits, so you know you're sharing with the phone in front of you." + }, + { + "scene": 27, + "start": 162.74, + "end": 165.915, + "recording_from": 123.489, + "recording_to": 126.664, + "on_screen": "Screen S10: Allow a copy", + "text": "You choose when their copy expires, and tap Allow." + }, + { + "scene": 28, + "start": 167.81, + "end": 170.537, + "recording_from": 127.09, + "recording_to": 129.817, + "on_screen": "Screen I05: Imported", + "text": "The copy arrives, and they tap Serve it now." + }, + { + "scene": 29, + "start": 172.44, + "end": 176.488, + "recording_from": 130.221, + "recording_to": 134.269, + "on_screen": "Screen I07: Their own PIN", + "text": "They can set their own PIN. But they can't change the store, or pass it on." + }, + { + "scene": 30, + "start": 178.39, + "end": 181.285, + "recording_from": 134.672, + "recording_to": 137.567, + "on_screen": "Screen I08: Their buyers", + "text": "They let people in the same way, with codes of their own." + }, + { + "scene": 31, + "start": 183.19, + "end": 186.411, + "recording_from": 138.001, + "recording_to": 141.222, + "on_screen": "Screen I09: When it expires", + "text": "And on the date you chose, the copy is deleted from their phone." + }, + { + "scene": 32, + "start": 188.31, + "end": 193.343, + "recording_from": 141.715, + "recording_to": 146.748, + "on_screen": "Title card: Share Your Apps", + "text": "Share Your Apps, from App Dev for All. Share what you build, with the people around you." + } + ] +} \ No newline at end of file diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.srt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.srt new file mode 100644 index 000000000..8c28380b3 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.srt @@ -0,0 +1,128 @@ +1 +00:00:00,400 --> 00:00:08,402 +Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts. + +2 +00:00:10,300 --> 00:00:20,145 +It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot. + +3 +00:00:22,050 --> 00:00:23,683 +First, creating your store. + +4 +00:00:25,580 --> 00:00:28,667 +Install the plugin from Code On The Go's Addons Manager. + +5 +00:00:30,570 --> 00:00:36,705 +In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional. + +6 +00:00:38,600 --> 00:00:42,905 +Add a product for each app. Each card shows what buyers can download. + +7 +00:00:44,810 --> 00:00:48,415 +Choose the app's project, and the APK that buyers will install. + +8 +00:00:50,320 --> 00:00:53,675 +Add screenshots and videos, so buyers can see what they're getting. + +9 +00:00:55,570 --> 00:00:58,465 +Describe each picture, for buyers who use a screen reader. + +10 +00:01:00,360 --> 00:01:02,365 +Then tap Publish, and confirm. + +11 +00:01:04,260 --> 00:01:09,314 +The first time, Android asks you to allow a few things. Each one is needed just once. + +12 +00:01:11,210 --> 00:01:15,503 +Choose a template to change the store's look, or write your own. + +13 +00:01:17,400 --> 00:01:22,005 +When it's done, every file has been checked. And the store is already being served. + +14 +00:01:23,900 --> 00:01:24,912 +Next, letting people in. + +15 +00:01:26,900 --> 00:01:29,917 +Share Your Apps Server shows what it's serving, and where. + +16 +00:01:31,820 --> 00:01:39,018 +Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store. + +17 +00:01:40,920 --> 00:01:46,381 +With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose. + +18 +00:01:48,280 --> 00:01:50,347 +Buyers see your store in their browser. + +19 +00:01:52,250 --> 00:01:58,009 +Each app has its pictures, its description, and its downloads. One tap, and it's on their phone. + +20 +00:01:59,910 --> 00:02:03,843 +And every store has an accessible version, plain and in large text. + +21 +00:02:05,740 --> 00:02:09,197 +Keep serving when the screen is off, or pause to save battery. + +22 +00:02:11,100 --> 00:02:13,640 +Finally, sharing your store with another phone. + +23 +00:02:15,540 --> 00:02:20,826 +Someone nearby can serve a copy of your store from their own phone. Tap Share this store. + +24 +00:02:22,730 --> 00:02:28,093 +Their phone scans the large code. The small one lets a phone without the app download it first. + +25 +00:02:29,990 --> 00:02:34,427 +On their phone, they tap Import a store, and scan the code, or type it. + +26 +00:02:36,330 --> 00:02:40,842 +Both phones show the same four digits, so you know you're sharing with the phone in front of you. + +27 +00:02:42,740 --> 00:02:45,915 +You choose when their copy expires, and tap Allow. + +28 +00:02:47,810 --> 00:02:50,537 +The copy arrives, and they tap Serve it now. + +29 +00:02:52,440 --> 00:02:56,488 +They can set their own PIN. But they can't change the store, or pass it on. + +30 +00:02:58,390 --> 00:03:01,285 +They let people in the same way, with codes of their own. + +31 +00:03:03,190 --> 00:03:06,411 +And on the date you chose, the copy is deleted from their phone. + +32 +00:03:08,310 --> 00:03:13,343 +Share Your Apps, from App Dev for All. Share what you build, with the people around you. + diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.vtt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.vtt new file mode 100644 index 000000000..54c2fa42a --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-narration.vtt @@ -0,0 +1,98 @@ +WEBVTT + +00:00:00.400 --> 00:00:08.402 +Share Your Apps lets you share the Android apps you build in Code On The Go with people nearby. No internet, no app store, and no accounts. + +00:00:10.300 --> 00:00:20.145 +It has two parts. The Share Your Apps plugin, where you describe your apps and publish them. And the Share Your Apps Server app, which serves them over Wi-Fi, or your phone's hotspot. + +00:00:22.050 --> 00:00:23.683 +First, creating your store. + +00:00:25.580 --> 00:00:28.667 +Install the plugin from Code On The Go's Addons Manager. + +00:00:30.570 --> 00:00:36.705 +In the Share Your Apps tab, give your store a name. A description, a header picture and a PIN are optional. + +00:00:38.600 --> 00:00:42.905 +Add a product for each app. Each card shows what buyers can download. + +00:00:44.810 --> 00:00:48.415 +Choose the app's project, and the APK that buyers will install. + +00:00:50.320 --> 00:00:53.675 +Add screenshots and videos, so buyers can see what they're getting. + +00:00:55.570 --> 00:00:58.465 +Describe each picture, for buyers who use a screen reader. + +00:01:00.360 --> 00:01:02.365 +Then tap Publish, and confirm. + +00:01:04.260 --> 00:01:09.314 +The first time, Android asks you to allow a few things. Each one is needed just once. + +00:01:11.210 --> 00:01:15.503 +Choose a template to change the store's look, or write your own. + +00:01:17.400 --> 00:01:22.005 +When it's done, every file has been checked. And the store is already being served. + +00:01:23.900 --> 00:01:24.912 +Next, letting people in. + +00:01:26.900 --> 00:01:29.917 +Share Your Apps Server shows what it's serving, and where. + +00:01:31.820 --> 00:01:39.018 +Tap Show QR codes for buyers. On a hotspot, the first code joins its network, and the second opens the store. + +00:01:40.920 --> 00:01:46.381 +With no Wi-Fi around, the server makes a hotspot of its own, with a name and password you choose. + +00:01:48.280 --> 00:01:50.347 +Buyers see your store in their browser. + +00:01:52.250 --> 00:01:58.009 +Each app has its pictures, its description, and its downloads. One tap, and it's on their phone. + +00:01:59.910 --> 00:02:03.843 +And every store has an accessible version, plain and in large text. + +00:02:05.740 --> 00:02:09.197 +Keep serving when the screen is off, or pause to save battery. + +00:02:11.100 --> 00:02:13.640 +Finally, sharing your store with another phone. + +00:02:15.540 --> 00:02:20.826 +Someone nearby can serve a copy of your store from their own phone. Tap Share this store. + +00:02:22.730 --> 00:02:28.093 +Their phone scans the large code. The small one lets a phone without the app download it first. + +00:02:29.990 --> 00:02:34.427 +On their phone, they tap Import a store, and scan the code, or type it. + +00:02:36.330 --> 00:02:40.842 +Both phones show the same four digits, so you know you're sharing with the phone in front of you. + +00:02:42.740 --> 00:02:45.915 +You choose when their copy expires, and tap Allow. + +00:02:47.810 --> 00:02:50.537 +The copy arrives, and they tap Serve it now. + +00:02:52.440 --> 00:02:56.488 +They can set their own PIN. But they can't change the store, or pass it on. + +00:02:58.390 --> 00:03:01.285 +They let people in the same way, with codes of their own. + +00:03:03.190 --> 00:03:06.411 +And on the date you chose, the copy is deleted from their phone. + +00:03:08.310 --> 00:03:13.343 +Share Your Apps, from App Dev for All. Share what you build, with the people around you. + diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-lines.txt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-lines.txt new file mode 100644 index 000000000..9c771066d --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-lines.txt @@ -0,0 +1,6 @@ +Share Your Apps: share the apps you build, with people nearby. +Publish your apps, right from Code On The Go. +Buyers scan one code to join your phone's hotspot, and another to open the store. +No internet, and no accounts. Just your store, in their browser. +One tap, and the app is on their phone. +Share Your Apps, from App Dev for All. diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-script.md b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-script.md new file mode 100644 index 000000000..db8f2c71c --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration-script.md @@ -0,0 +1,12 @@ +# Share Your Apps demo, short: narration, as recorded + +Recorded narration: `share_Your_Apps_promo.mp3, slowed to 0.9 with atempo`. The video is **0:26.6** long. Each line plays at its *Start* in the video, taken from *Recording* in the slowed file. + +| # | Start | End | Recording | On screen | Narration | +|---|---|---|---|---|---| +| 1 | 00:00.300 | 00:03.943 | 0.00–3.64 s | Title card: Share Your Apps | Share Your Apps: share the apps you build, with people nearby. | +| 2 | 00:05.240 | 00:07.553 | 4.07–6.38 s | Screen P11: From Code On The Go | Publish your apps, right from Code On The Go. | +| 3 | 00:08.850 | 00:13.264 | 6.83–11.24 s | Screen S04: Scan to join | Buyers scan one code to join your phone's hotspot, and another to open the store. | +| 4 | 00:14.560 | 00:18.557 | 11.59–15.58 s | Screen B01: Your store | No internet, and no accounts. Just your store, in their browser. | +| 5 | 00:19.860 | 00:21.967 | 15.97–18.08 s | Screen B02: Download | One tap, and the app is on their phone. | +| 6 | 00:23.270 | 00:25.592 | 18.55–20.87 s | Title card: Share Your Apps | Share Your Apps, from App Dev for All. | diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.json b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.json new file mode 100644 index 000000000..ce9999f95 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.json @@ -0,0 +1,61 @@ +{ + "title": "Share Your Apps demo, short", + "recording": "share_Your_Apps_promo.mp3, slowed to 0.9 with atempo", + "duration_seconds": 26.59, + "lines": [ + { + "scene": 1, + "start": 0.3, + "end": 3.943, + "recording_from": 0, + "recording_to": 3.643, + "on_screen": "Title card: Share Your Apps", + "text": "Share Your Apps: share the apps you build, with people nearby." + }, + { + "scene": 2, + "start": 5.24, + "end": 7.553, + "recording_from": 4.072, + "recording_to": 6.385, + "on_screen": "Screen P11: From Code On The Go", + "text": "Publish your apps, right from Code On The Go." + }, + { + "scene": 3, + "start": 8.85, + "end": 13.264, + "recording_from": 6.831, + "recording_to": 11.245, + "on_screen": "Screen S04: Scan to join", + "text": "Buyers scan one code to join your phone's hotspot, and another to open the store." + }, + { + "scene": 4, + "start": 14.56, + "end": 18.557, + "recording_from": 11.587, + "recording_to": 15.584, + "on_screen": "Screen B01: Your store", + "text": "No internet, and no accounts. Just your store, in their browser." + }, + { + "scene": 5, + "start": 19.86, + "end": 21.967, + "recording_from": 15.974, + "recording_to": 18.081, + "on_screen": "Screen B02: Download", + "text": "One tap, and the app is on their phone." + }, + { + "scene": 6, + "start": 23.27, + "end": 25.592, + "recording_from": 18.548, + "recording_to": 20.87, + "on_screen": "Title card: Share Your Apps", + "text": "Share Your Apps, from App Dev for All." + } + ] +} \ No newline at end of file diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.srt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.srt new file mode 100644 index 000000000..41fc15115 --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.srt @@ -0,0 +1,24 @@ +1 +00:00:00,300 --> 00:00:03,943 +Share Your Apps: share the apps you build, with people nearby. + +2 +00:00:05,240 --> 00:00:07,553 +Publish your apps, right from Code On The Go. + +3 +00:00:08,850 --> 00:00:13,264 +Buyers scan one code to join your phone's hotspot, and another to open the store. + +4 +00:00:14,560 --> 00:00:18,557 +No internet, and no accounts. Just your store, in their browser. + +5 +00:00:19,860 --> 00:00:21,967 +One tap, and the app is on their phone. + +6 +00:00:23,270 --> 00:00:25,592 +Share Your Apps, from App Dev for All. + diff --git a/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.vtt b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.vtt new file mode 100644 index 000000000..d57b120df --- /dev/null +++ b/plugins/Share-Your-Apps/docs/user-guides/videos/share-your-apps-demo-short-narration.vtt @@ -0,0 +1,20 @@ +WEBVTT + +00:00:00.300 --> 00:00:03.943 +Share Your Apps: share the apps you build, with people nearby. + +00:00:05.240 --> 00:00:07.553 +Publish your apps, right from Code On The Go. + +00:00:08.850 --> 00:00:13.264 +Buyers scan one code to join your phone's hotspot, and another to open the store. + +00:00:14.560 --> 00:00:18.557 +No internet, and no accounts. Just your store, in their browser. + +00:00:19.860 --> 00:00:21.967 +One tap, and the app is on their phone. + +00:00:23.270 --> 00:00:25.592 +Share Your Apps, from App Dev for All. + diff --git a/plugins/Share-Your-Apps/gradle.properties b/plugins/Share-Your-Apps/gradle.properties new file mode 100644 index 000000000..c65c48504 --- /dev/null +++ b/plugins/Share-Your-Apps/gradle.properties @@ -0,0 +1,8 @@ +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official +org.gradle.jvmargs=-Xmx2560m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8 +org.gradle.caching=true + +# The Kotlin library comes from Code On The Go at run time; build.gradle.kts has it as compileOnly. +kotlin.stdlib.default.dependency=false diff --git a/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.jar b/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..a4b76b953 Binary files /dev/null and b/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.jar differ diff --git a/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.properties b/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..322c8d733 --- /dev/null +++ b/plugins/Share-Your-Apps/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/plugins/Share-Your-Apps/gradlew b/plugins/Share-Your-Apps/gradlew new file mode 100644 index 000000000..f5feea6d6 --- /dev/null +++ b/plugins/Share-Your-Apps/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/plugins/Share-Your-Apps/proguard-rules.pro b/plugins/Share-Your-Apps/proguard-rules.pro new file mode 100644 index 000000000..fc4c5a232 --- /dev/null +++ b/plugins/Share-Your-Apps/proguard-rules.pro @@ -0,0 +1,34 @@ +# Rules for R8, which would shrink the plugin's release build. R8 is off (isMinifyEnabled = false, in +# build.gradle.kts), and AndroidX is compileOnly; these rules record what R8 needs here, if it's ever turned back on. + +# Keep every class of the plugin's own, with all its members, unchanged: Code On The Go loads the plugin by its +# class names, and Pebble reads the objects passed to templates by their property names. The plugin's own code is +# small, so this costs little; R8 still removes the unused parts of AndroidX and ZXing. +-keep class org.appdevforall.shareyourapps.** { *; } + +# No renaming, so error reports from testers keep readable names. +-dontobfuscate + +# Code On The Go loads classes parent-first: when the plugin uses an AndroidX class that Code On The Go also has, +# Code On The Go's copy runs, not the plugin's (a NoSuchMethodError showed this, for ActivityResultLauncher). So R8 +# may remove unused library code, but must never change what's left: no optimising — R8 had specialised +# launch(Object) to launch(Intent) in the bundled copy, which Code On The Go's copy doesn't have — and every +# library class the plugin uses keeps its exact methods and signatures. +-dontoptimize +-keep,allowshrinking class androidx.** { *; } +-keep,allowshrinking class com.google.zxing.** { *; } + +# Code On The Go, not the plugin, calls the plugin's callbacks — the result of an activity, for one — so R8 saw no +# caller, removed ActivityResultCallback.onActivityResult, and with it the bodies of both of the plugin's result +# callbacks: an AbstractMethodError, when the server answered. Keep every method of the AndroidX interfaces and the +# abstract methods of the AndroidX classes that remain, so whatever the plugin implements keeps its code. +-keepclassmembers interface androidx.** { ; } +-keepclassmembers abstract class androidx.** { abstract ; } + +# These come from Code On The Go at run time, not from the plugin, so R8 won't find them in it. +-dontwarn io.pebbletemplates.** +-dontwarn com.itsaky.androidide.** +-dontwarn org.slf4j.** +-dontwarn kotlin.** +-dontwarn kotlinx.** +-dontwarn org.jetbrains.annotations.** diff --git a/plugins/Share-Your-Apps/server/.gitignore b/plugins/Share-Your-Apps/server/.gitignore new file mode 100644 index 000000000..902b1c5e1 --- /dev/null +++ b/plugins/Share-Your-Apps/server/.gitignore @@ -0,0 +1,27 @@ +# Build output and caches +build/ +.gradle/ +.kotlin/ +.cxx/ +.externalNativeBuild/ +captures/ +*.hprof + +# IDE and editor state (.cg is CodeOnTheGo's) +.cg/ +.idea/ +*.iml +.DS_Store +Thumbs.db + +# Machine-specific settings +local.properties + +# Signing: the keystore and its passwords must never be committed +release.keystore +release.properties +keystore.properties +*.jks +*.keystore +*.p12 +*.pfx diff --git a/plugins/Share-Your-Apps/server/CODE_REVIEW.md b/plugins/Share-Your-Apps/server/CODE_REVIEW.md new file mode 100644 index 000000000..09e530da0 --- /dev/null +++ b/plugins/Share-Your-Apps/server/CODE_REVIEW.md @@ -0,0 +1,80 @@ +# Code Review: Share Your Apps Server + +**Scope:** Architecture, Concurrency, Audio/DSP implementation, Networking, Lifecycle & State, Error Handling, and Maintainability. *(Note: Security analysis omitted per instructions)*. + +--- + +## 1. Architecture & Process Separation + +### Observations & Strengths +- **Dual-Process Design:** The application uses a decoupled multi-process architecture (`:server` process vs. the main UI/foreground service process). The HTTP server and share endpoints run in an isolated process to protect long-running transfers from UI memory pressure. +- **IPC Protocol Design:** Clean, type-safe messaging protocol via `Messenger` and `Bundle` contracts defined in `Ipc.kt` / `Shared.kt`. +- **Process Supervision:** `HostService` acts as a lifecycle supervisor, managing foreground notifications, checking server health, and monitoring process death. + +### Potential Issues & Areas for Improvement +- **Process Termination & Port Rebinding Race:** In `HostService`, stopping or restarting the server sends an explicit kill or relies on process exit with a fixed wait (`DEATH_WAIT_MS = 3000L`). If the Linux kernel takes longer to reclaim bound TCP ports, immediate subsequent `start()` calls can throw `BindException`. +- **Service Disconnection Fallback:** When `ShareActivity` or `ImportActivity` unbinds or gets `onServiceDisconnected`, several state machine variables (`server`, `bound`) reset, but pending handler messages (`main.postDelayed`) are not always cancelled, which can trigger null-messenger calls after disconnection. + +--- + +## 2. Concurrency & Threading + +### Observations & Strengths +- **Strict Thread Ownership in HttpServer:** `HttpServer` uses an explicit "single main thread router + worker sender threads" model (`MAX_SENDERS = 16`), preventing concurrent race conditions over request routing, cookie validation, and session tables. +- **Volatile & Atomic Synchronization:** Proper use of `@Volatile` across cancellation flags (`stopped`, `accepting`, `running`) in `SoundIo` and `HttpServer`. + +### Potential Issues & Areas for Improvement +- **Thread Creation Overhead (`kotlin.concurrent.thread`):** + - In `HttpServer`, each client connection spawns a new unpooled thread: `thread(name = "sender-...")`. Under bursting local client traffic (multiple buyer devices or multiple simultaneous image/asset downloads), this can lead to thread exhaustion or high GC pauses on memory-constrained low-end Android devices. A bounded `ThreadPoolExecutor` or Kotlin Coroutines dispatcher would reduce overhead. +- **Audio Thread Latency & Loop Timing:** In `SoundIo.Player.run()`, audio writes occur in 4096-sample chunks. While streaming via `AudioTrack.write`, thread sleep (`Thread.sleep(250)`) is used to let buffers drain. However, the deadline check relies on system wall-clock time rather than audio frame positions, which can cause jitter or premature loop termination under audio pipeline backpressure. +- **Blocking Queue Poisoning:** In `HttpServer`, `LinkedBlockingQueue` holds incoming connections. When calling `stop()`, `queue.offer(Stop)` is used, but if multiple threads or stop calls occur concurrently, drain sequences must ensure no leaked open client sockets remain in the queue. + +--- + +## 3. Audio Modulation & DSP (`Sound*.kt`) + +### Observations & Strengths +- **Mathematical Robustness:** `SoundModem` uses chirp sweeps for frame sync, paired with Goertzel tone detection (`SoundDsp.coeff`) within symbol intervals, skipping transition edges to eliminate phase-click harmonic distortion. +- **Frequency Interleaving:** Even and odd symbol slots use separated frequency sub-bands, mitigating room acoustic multipath echoes. +- **Scrambled Burst Redundancy:** 3-fold key scrambling ensures that spectral nulls in room acoustics do not corrupt the same symbol across bursts. + +### Potential Issues & Areas for Improvement +- **Decoder Buffer Memory Allocation:** `SoundDecoder` resizes an internal dynamic float buffer (`buf = FloatArray(1 shl 17)` up to multiples of power of two) and allocates new `DoubleArray(fftSize)` inside its `search()` loop on every window evaluation. Moving these temporary arrays to pre-allocated scratch buffers would eliminate GC thrashing during continuous microphone listening. +- **Goertzel Precision & Floating Point Drift:** The tone analysis calculates energy without normalization against instantaneous RMS power of the symbol window. High ambient noise or loud talking can elevate tone power estimates across adjacent bins, causing false positives before CRC rejection. + +--- + +## 4. Networking, Wi-Fi Direct & Hotspot Management + +### Observations & Strengths +- **Adaptive Connectivity:** Clean hierarchical fallback: uses existing Wi-Fi when available, falls back to Wi-Fi Direct Local Group, and ultimately to Android's `LocalOnlyHotspot`. +- **Range Request Support:** `HttpServer` implements HTTP 206 `Range` header slicing, allowing client video/audio streaming and resilient file downloads. + +### Potential Issues & Areas for Improvement +- **Wi-Fi Direct Group Leaks:** In `Hotspot.kt`, failure or abrupt activity termination during Wi-Fi Direct group negotiation sometimes leaves the P2P group in an indeterminate state on OEM devices (especially Samsung/Xiaomi). Ensuring `WifiP2pManager.removeGroup` is invoked in an explicit teardown hook prevents subsequent connection failures. +- **Local-Only Hotspot Reservation State:** `startLocalOnlyHotspot` callbacks (`onStarted`, `onFailed`, `onStopped`) are asynchronous. If a user quickly presses Stop and then Start, race conditions can occur if the previous reservation has not fully unmounted in Android's `WifiManager`. + +--- + +## 5. UI, Lifecycle & State Management + +### Observations & Strengths +- **Declarative Programmatic UI:** Clean, reactive programmatic layouts avoiding heavy XML inflation overhead, styled with a cohesive palette (`Palette.kt`) and responsive elevation effects (`panel`, `BoxSpan`). +- **Window Flags & Screen-On Hygiene:** `ShareActivity` and `ImportActivity` manage `FLAG_KEEP_SCREEN_ON` appropriately so transfers aren't severed by standard screen timeout sleep states. + +### Potential Issues & Areas for Improvement +- **State Retention on Configuration Changes:** `MainActivity` and `ShareActivity` manually serialize small state variables into `onSaveInstanceState`. However, transient UI state (such as countdown progress counters or ongoing audio player instances) is torn down on orientation changes, forcing tone transmission to restart from attempt 1. +- **Dynamic View Building in Polling Loops:** In `MainActivity.refreshCopy()` and `ShareActivity.showCode()`, views are repeatedly rebuilt via `removeAllViews()` and reconstructed upon state changes. Reusing views or updating properties in-place would prevent visual flicker and improve layout pass performance. + +--- + +## 6. Code Quality & Maintainability + +### Observations & Strengths +- Highly readable, cohesive codebase with clear domain separation (`Mcp*`, `Sound*`, `Share*`, `Store*`). +- Extensive contextual comments linking design appendix specifications to code behavior. + +### Recommended Next Steps +1. **Refactor Sender Thread Pool:** Replace raw `thread { ... }` in `HttpServer` with an `ExecutorService` (e.g. `Executors.newFixedThreadPool(16)`). +2. **Zero-Allocation Decoding Loop:** Refactor `SoundDecoder.search()` to reuse static work buffers rather than instantiating arrays per audio frame. +3. **Hotspot State Machine:** Introduce an explicit `State` enum (`IDLE`, `STARTING`, `RUNNING`, `STOPPING`) in `Hotspot.kt` to guard against rapid start/stop toggling. diff --git a/plugins/Share-Your-Apps/server/LICENSE b/plugins/Share-Your-Apps/server/LICENSE new file mode 100644 index 000000000..0c97efd25 --- /dev/null +++ b/plugins/Share-Your-Apps/server/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/plugins/Share-Your-Apps/server/README.md b/plugins/Share-Your-Apps/server/README.md new file mode 100644 index 000000000..bffa0c7fe --- /dev/null +++ b/plugins/Share-Your-Apps/server/README.md @@ -0,0 +1,102 @@ +# Share Your Apps Server + +An Android app that serves the store published by the **Share Your Apps** plugin for +[Code On The Go](https://github.com/appdevforall/CodeOnTheGo). People on the same Wi-Fi +network or hotspot open the store in their phone's browser to download the owner's apps +and their source. No internet or accounts are needed. + +The plugin builds the store and starts this server on it; the owner rarely opens the app +except to check it's running, change a setting, or read the log. + +## What it does + +- Serves a Store directory (`CodeOnTheGoProjects/Store_<8 digits>/`) that the plugin writes, + and nothing outside it. +- An optional PIN, with a 24-hour browser cookie. +- Serves a gzip copy of `index.html` and each source zip to browsers that accept it, + compressing them in the background after each start. +- Runs as a foreground service in its main process; the HTTP server runs in a separate + process that's replaced on every restart. +- Access log (Apache format), at most five files, with a configurable size limit. +- Three-tier help from a bundled database. +- A hotspot when the phone isn't on Wi-Fi (Wi-Fi Direct first, then Android's local-only hotspot), + and a Serve screen with QR codes for joining the network and opening the store (ZXing core). + +The full design is in the Share Your Apps design document (ADFA-6207). + +## Building + +Open the project in Code On The Go and build it. `minSdk` is 28, the same as Code On The Go. + +Release builds are signed in CI with the server's own release key, from repository secrets; see +*The release signing key* in the design document. The copy the plugin bundles and the copy +installed on a phone must always be signed with the same key. + +## Releasing a new build through the plugin + +The plugin installs this app when it's missing or older than the copy it carries, so: + +1. Raise `versionCode` in `app/build.gradle.kts`. +2. Build, then copy `app/build/outputs/apk/debug/app-debug.apk` into the plugin as + `src/main/assets/share-your-apps-server.apk`. +3. Rebuild the plugin. + +## Help + +The help text lives in `help/build_help_db.py`, which generates +`app/src/main/assets/web_server_documentation.db`. It uses the same tables, columns and +queries as Code On The Go's `documentation.db`, with every page stored as plain HTML. + +The app copies the database only when its `versionCode` changes. If you edit the help +text, rebuild the database, then raise `versionCode` before building, or the old help stays +in place: + + python3 help/build_help_db.py app/src/main/assets/web_server_documentation.db + +## Running the tests + +The tests are in `app/src/test/java`: eight JUnit tests covering the server's core — the HTTP +server, PIN and cookies, compression, the help database, network selection, QR codes, the log +filters, the hotspot settings, and the page look. Each runs a list of named checks and, if any +fail, names them. They run on a computer's Java, not on Android: + + ./gradlew testDebugUnitTest + +**On the phone,** two things differ from a computer: + +- **Start Gradle with `sh`.** Shared storage doesn't keep the executable bit, so `./gradlew` won't + run there. Use `sh ./gradlew testDebugUnitTest` instead. +- **Use CodeOnTheGo's `aapt2`.** Run from a terminal, Gradle downloads the standard `aapt2`, which + is built for Linux computers and can't run on a phone. The build then fails at + `processDebugResources` with `Syntax error: word unexpected (expecting ")")`. CodeOnTheGo + supplies its own `aapt2` to builds it starts, but not to a terminal, so pass it to Gradle: + + sh ./gradlew testDebugUnitTest -Pandroid.aapt2FromMavenOverride=/data/data/com.itsaky.androidide/files/home/android-sdk/build-tools/36.0.0/aapt2 + + That's where CodeOnTheGo keeps it, with build tools 36.0.0. If a different version of + CodeOnTheGo keeps it elsewhere, find it with + + find /data/data/com.itsaky.androidide/files -name aapt2 -type f 2>/dev/null | grep -v transforms + + and check a copy with ` version`, which should print `Android Asset Packaging Tool (aapt) 2.…`. + + Give it on the command line like this, not in `gradle.properties`: that file goes with the + project, and the setting would break the build on every computer. + +They need two test libraries in `app/build.gradle.kts`: + + testImplementation("junit:junit:4.13.2") + testImplementation("org.xerial:sqlite-jdbc:3.46.1.3") + +**Writing tests:** unit tests compile against Android's version of Java's library (from +`android.jar`), but run on the computer's or phone's full Java. So they may only use Java +features Android also has. Reach anything newer through reflection, as `PublishTest.kt` does for +Unix-domain sockets, or the tests won't compile under Gradle. + +## Documentation + +The design document, covering both this app and the Share Your Apps plugin, is in the plugin's repository at `docs/share-your-apps-design.md`. Its *Developer notes* cover building, signing, updating the help and running the tests. + +## License + +GNU Affero General Public License v3.0 or later. See `LICENSE`. diff --git a/plugins/Share-Your-Apps/server/app/.gitignore b/plugins/Share-Your-Apps/server/app/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/build.gradle.kts b/plugins/Share-Your-Apps/server/app/build.gradle.kts new file mode 100644 index 000000000..f92eeb5cc --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/build.gradle.kts @@ -0,0 +1,159 @@ + +import java.util.Properties +import java.io.FileInputStream + +plugins { + id("com.android.application") +} + +// Release signing. CI sets the four SERVER_SIGNING_* variables from repository secrets (see the +// design document's "The release signing key"). Without them, the values come from release.properties +// in Code On The Go's private folder, for a build on the phone. Neither is ever in the project. +val keystorePropsFile = File("/data/data/com.itsaky.androidide/files/home/keys/release.properties") +val keystoreProps = Properties() + +if (System.getenv("SERVER_SIGNING_STORE_FILE") != null) { + keystoreProps["storeFile"] = System.getenv("SERVER_SIGNING_STORE_FILE") + System.getenv("SERVER_SIGNING_STORE_PASSWORD")?.let { keystoreProps["storePassword"] = it } + System.getenv("SERVER_SIGNING_KEY_ALIAS")?.let { keystoreProps["keyAlias"] = it } + System.getenv("SERVER_SIGNING_KEY_PASSWORD")?.let { keystoreProps["keyPassword"] = it } +} else if (keystorePropsFile.exists()) { + FileInputStream(keystorePropsFile).use { keystoreProps.load(it) } +} + +val hasValidSigningProps = listOf("storeFile", "storePassword", "keyAlias", "keyPassword").all { key -> + keystoreProps[key] != null +} + + +android { + namespace = "org.appdevforall.shareyourapps.server" + compileSdk = 36 + + // disable linter + lint { + checkReleaseBuilds = false + } + + signingConfigs { + if (hasValidSigningProps) { + create("release") { + // All four come from release.properties, which is never committed. storeFile may be + // absolute, such as a key kept in Code On The Go's private folder. + storeFile = rootProject.file(keystoreProps["storeFile"] as String) + storePassword = keystoreProps["storePassword"] as String + keyAlias = keystoreProps["keyAlias"] as String + keyPassword = keystoreProps["keyPassword"] as String + } + } + } + + defaultConfig { + applicationId = "org.appdevforall.shareyourapps.server" + minSdk = 28 + targetSdk = 36 + versionCode = 50 + versionName = "1.0.$versionCode" + buildConfigField("long", "BUILD_TIME", "${System.currentTimeMillis()}L") + + vectorDrawables { + useSupportLibrary = true + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + buildTypes { + release { + if (hasValidSigningProps) { + signingConfig = signingConfigs.getByName("release") + } + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + buildFeatures { + viewBinding = true + buildConfig = true + buildFeatures { +} + + } + packaging { + dex { useLegacyPackaging = true } // compress the code: about 150 KB smaller + resources { + resources.excludes.add("/META-INF/{AL2.0,LGPL2.1}") + resources.excludes.add("META-INF/kotlinx_coroutines_core.version") + // Kotlin reflection metadata: unused, since the server uses no Kotlin reflection. + resources.excludes.add("**/*.kotlin_builtins") + + // The part below is only needed for compose builds. + // This packaging block is required to solve interdependency conflicts. + // They arise only when using local maven repo, so I suppose online repos have some way of solving such issues. + + // Caused by: com.android.builder.merge.DuplicateRelativeFileException: 4 files found with path 'commonMain/default/linkdata/module' from inputs: + // - AndroidIDE\libs_source\gradle\localMvnRepository\androidx\collection\collection\1.4.2\collection-1.4.2.jar + // - AndroidIDE\libs_source\gradle\localMvnRepository\androidx\lifecycle\lifecycle-common\2.8.7\lifecycle-common-2.8.7.jar + // - AndroidIDE\libs_source\gradle\localMvnRepository\androidx\annotation\annotation\1.8.1\annotation-1.8.1.jar + // - AndroidIDE\libs_source\gradle\localMvnRepository\org\jetbrains\kotlinx\kotlinx-coroutines-core\1.7.3\kotlinx-coroutines-core-1.7.3.jar + // And some others. + resources.pickFirsts.add("nonJvmMain/default/linkdata/package_androidx/0_androidx.knm") + resources.pickFirsts.add("nonJvmMain/default/linkdata/root_package/0_.knm") + resources.pickFirsts.add("nonJvmMain/default/linkdata/module") + + resources.pickFirsts.add("nativeMain/default/linkdata/root_package/0_.knm") + resources.pickFirsts.add("nativeMain/default/linkdata/module") + + resources.pickFirsts.add("commonMain/default/linkdata/root_package/0_.knm") + resources.pickFirsts.add("commonMain/default/linkdata/module") + resources.pickFirsts.add("commonMain/default/linkdata/package_androidx/0_androidx.knm") + + resources.pickFirsts.add("META-INF/kotlin-project-structure-metadata.json") + + resources.merges.add("commonMain/default/manifest") + resources.merges.add("nonJvmMain/default/manifest") + resources.merges.add("nativeMain/default/manifest") + } + } + + configurations.all { + resolutionStrategy { + // Force the use of Kotlin stdlib 1.9.22 for all modules + force("org.jetbrains.kotlin:kotlin-stdlib:2.3.21") + force("org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.3.21") + force("org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.3.21") + + // Force specific AndroidX versions to avoid conflicts + force("androidx.collection:collection:1.4.2") + force("androidx.annotation:annotation:1.8.1") + force("androidx.core:core-ktx:1.8.0") + force("androidx.lifecycle:lifecycle-runtime-ktx:2.3.1") + force("androidx.collection:collection-ktx:1.4.2") + } + } +} + +tasks.withType { + options.compilerArgs.add("-Xlint:deprecation") +} + +kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) + } +} + + + +dependencies { + testImplementation("org.json:json:20240303") + testImplementation("junit:junit:4.13.2") + testImplementation("org.xerial:sqlite-jdbc:3.46.1.3") + + implementation("com.google.zxing:core:3.5.3") +} diff --git a/plugins/Share-Your-Apps/server/app/proguard-rules.pro b/plugins/Share-Your-Apps/server/app/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/src/main/AndroidManifest.xml b/plugins/Share-Your-Apps/server/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..1d20010b3 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/AndroidManifest.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/assets/web_server_documentation.db b/plugins/Share-Your-Apps/server/app/src/main/assets/web_server_documentation.db new file mode 100644 index 000000000..92a55a4d0 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/assets/web_server_documentation.db differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/BoxSpan.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/BoxSpan.kt new file mode 100644 index 000000000..447d45123 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/BoxSpan.kt @@ -0,0 +1,29 @@ +package org.appdevforall.shareyourapps.server + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.text.style.ReplacementSpan +import kotlin.math.roundToInt + +/** + * Draws its text inside a thin, rounded box, in the text's own colour, so it follows light and dark mode. Used for + * a button's name in running text, such as "Start" in "Start will serve…", so it reads as the button above. + */ +class BoxSpan(private val density: Float) : ReplacementSpan() { + private val padX get() = 4 * density + + override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int { + fm?.let { paint.getFontMetricsInt(it) } // the line keeps its normal height + return (paint.measureText(text, start, end) + 2 * padX).roundToInt() + } + + override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { + val w = paint.measureText(text, start, end); val fm = paint.fontMetrics + val style = paint.style; val stroke = paint.strokeWidth + paint.style = Paint.Style.STROKE; paint.strokeWidth = maxOf(1f, 0.75f * density) // a hairline + canvas.drawRoundRect(RectF(x + 0.5f, y + fm.ascent - density, x + w + 2 * padX - 0.5f, y + fm.descent + density), 3 * density, 3 * density, paint) + paint.style = style; paint.strokeWidth = stroke + canvas.drawText(text, start, end, x + padX, y.toFloat(), paint) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Brand.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Brand.kt new file mode 100644 index 000000000..f8b54093f --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Brand.kt @@ -0,0 +1,47 @@ +package org.appdevforall.shareyourapps.server + +import java.util.Base64 + +/** + * The store's look, from the Eight-Armed Merchant icon: its awning across the top, a cream + * ground, and outlined "sticker" cards and buttons. Shared by every page the server itself sends + * buyers — the PIN page and the short message pages. The catalog page's template uses the same + * palette. No web fonts: stores run offline. + */ +object Brand { + + /** The icon, animated, as a self-contained image. Kept in an , so its styles can't touch the page. */ + const val OCTOPUS_SVG = """""" + + val octopusDataUri: String = "data:image/svg+xml;base64," + Base64.getEncoder().encodeToString(OCTOPUS_SVG.toByteArray(Charsets.UTF_8)) + + const val INK = "#2B1B3D" + + private const val CSS = + "*{box-sizing:border-box;margin:0}" + + "body{background:#FFF3D6;color:#2B1B3D;font-family:ui-rounded,\"SF Pro Rounded\",system-ui,sans-serif}" + + // The awning: red and cream stripes with scalloped edges, over the teal of the icon. + ".aw{height:26px;background:radial-gradient(circle at 12px 14px,#FF4F3A 11.5px,transparent 12px) 0 0/48px 26px repeat-x," + + "radial-gradient(circle at 36px 14px,#FFF3D6 11.5px,transparent 12px) 0 0/48px 26px repeat-x," + + "repeating-linear-gradient(90deg,#FF4F3A 0 24px,#FFF3D6 24px 48px) 0 0/100% 14px no-repeat,#0B6E6E}" + + "main{max-width:22em;margin:0 auto;padding:28px 16px}" + + ".k{background:#fff;border:3px solid #2B1B3D;border-radius:16px;box-shadow:5px 5px 0 #2B1B3D;padding:22px 20px;text-align:center}" + + ".k img{width:96px;height:96px;border-radius:22px;border:3px solid #2B1B3D;display:block;margin:0 auto 14px}" + + "h1{font-size:22px;font-weight:800;margin-bottom:14px;overflow-wrap:anywhere}" + + "p{font-size:17px;line-height:1.45}" + + "label{display:block;font-weight:700;text-align:left}" + + "input{font:inherit;font-size:1.4em;width:100%;padding:.45em .6em;margin:.4em 0 .9em;border:3px solid #2B1B3D;" + + "border-radius:12px;letter-spacing:.3em;text-align:center;background:#fff;color:#2B1B3D}" + + "input:focus,button:focus-visible{outline:3px solid #8E5BFF;outline-offset:2px}" + + "button{font:inherit;font-size:1.15em;font-weight:800;width:100%;padding:.6em;background:#FF9E2C;color:#2B1B3D;" + + "border:3px solid #2B1B3D;border-radius:12px;box-shadow:3px 3px 0 #2B1B3D;cursor:pointer}" + + "button:active{transform:translate(3px,3px);box-shadow:none}" + + ".er{color:#C2261A;font-weight:700;margin-bottom:12px}" + + /** A complete page: the awning, then a card holding the octopus and [body]. [title] must already be escaped. */ + fun page(title: String, body: String): String = + "" + + "$title" + + "
" + + "\"\"$body
" +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Compressor.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Compressor.kt new file mode 100644 index 000000000..446913dd3 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Compressor.kt @@ -0,0 +1,111 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.nio.file.Files +import java.nio.file.LinkOption +import java.util.stream.Collectors +import java.util.zip.Deflater +import java.util.zip.GZIPOutputStream +import kotlin.concurrent.thread + +/** + * Gzips the pages at the Store directory's top and every source zip, in the background, so + * publishing doesn't wait for it. Each copy is written to `.gz.tmp` and renamed to + * `.gz` only when finished, so a partial copy is never served. A copy that isn't smaller + * than the original is deleted instead of renamed. On any error the temporary file is deleted + * and that file is skipped, and the uncompressed file keeps being served. Once a source zip's + * copy is complete, the zip itself is deleted, and HttpServer serves it from the copy. + * + * Nothing coordinates with this thread: a relaunch kills the whole server process. + */ +class Compressor(root: File, private val log: StoreLog) { + + private val rootDir = root.canonicalFile + + /** The files to compress, relative to the Store directory: the pages at its top — index.html and accessible.html — and every .zip, without a .gz. */ + fun pending(): List { + val base = rootDir.toPath() + return Files.walk(base).use { paths -> // doesn't follow symlinks, so it stays inside + paths.filter { Files.isRegularFile(it, LinkOption.NOFOLLOW_LINKS) } + .map { base.relativize(it).toString().replace(File.separatorChar, '/') } + .filter { (it.endsWith(".html") && '/' !in it) || it.endsWith(".zip") } + .filter { !File(rootDir, "$it.gz").exists() } + .sorted() + .collect(Collectors.toList()) // not Stream.toList(): that's API 34+ on Android + } + } + + fun start(): Thread = thread(name = "gzip", isDaemon = true, priority = Thread.MIN_PRIORITY) { run() } + + fun run() { + val todo = try { pending() } catch (e: Exception) { + log.status("gzip", "failed: couldn't list files: ${e.message}") + return + } + log.status("gzip", "started: ${todo.size} files") + var ok = 0 + var skipped = 0 + var failed = 0 + for (rel in todo) { + when (compress(rel)) { + Outcome.COMPRESSED -> ok++ + Outcome.NOT_SMALLER -> skipped++ + Outcome.FAILED -> failed++ + } + } + log.status("gzip", "finished: $ok compressed, $skipped not smaller, $failed failed") + } + + private enum class Outcome { COMPRESSED, NOT_SMALLER, FAILED } + + private fun compress(rel: String): Outcome { + val src = File(rootDir, rel) + val tmp = File(rootDir, "$rel.gz.tmp") + val dst = File(rootDir, "$rel.gz") + // nanoTime, not the wall clock: it can't jump if the clock is set while compressing. + val started = System.nanoTime() + return try { + FileInputStream(src).use { input -> + BestGzip(FileOutputStream(tmp)).use { out -> input.copyTo(out, 64 * 1024) } + } + val took = duration((System.nanoTime() - started) / 1_000_000) + if (tmp.length() >= src.length()) { + // Serving it would save nothing, so it never becomes a .gz. + log.status("gzip", "not smaller: $rel ${src.length()} -> ${tmp.length()} bytes in $took; deleted") + tmp.delete() + return Outcome.NOT_SMALLER + } + if (!tmp.renameTo(dst)) throw IOException("couldn't rename ${tmp.name}") + log.status("gzip", "done: $rel ${src.length()} -> ${dst.length()} bytes in $took") + // A source zip keeps only its copy, to save space: the server decompresses it for the rare client that + // doesn't take gzip, and for ranges. The copy takes the zip's date, so its ETag and Last-Modified don't + // change. Pages keep both, being tiny; so does a zip of 4 GB or more, since gzip records sizes modulo 4 GB. + if (rel.endsWith(".zip") && src.length() < GZ_SIZE_LIMIT) { + dst.setLastModified(src.lastModified()) + if (src.delete()) log.status("gzip", "kept only the copy: $rel") else log.status("gzip", "couldn't delete $rel; serving both") + } + Outcome.COMPRESSED + } catch (e: Exception) { + tmp.delete() + log.status("gzip", "failed: $rel: ${e.message ?: e.toString()}") + Outcome.FAILED + } + } + + companion object { + /** gzip records the original size modulo 2^32, so a larger zip keeps its original. */ + const val GZ_SIZE_LIMIT = 1L shl 32 + + /** A duration for the log: "37 ms" under a second, else seconds to a tenth, like "5.2 s". */ + fun duration(ms: Long): String = + if (ms < 1000) "$ms ms" else "${ms / 1000}.${(ms % 1000) / 100} s" + } + + private class BestGzip(out: OutputStream) : GZIPOutputStream(out, 64 * 1024) { + init { def.setLevel(Deflater.BEST_COMPRESSION) } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/CopyIcon.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/CopyIcon.kt new file mode 100644 index 000000000..ef1e7bbf6 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/CopyIcon.kt @@ -0,0 +1,26 @@ +package org.appdevforall.shareyourapps.server + +import android.graphics.Canvas +import android.graphics.ColorFilter +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.RectF +import android.graphics.drawable.Drawable + +/** The usual copy symbol, two overlapping rounded sheets, drawn in code: Android has no public copy icon. */ +class CopyIcon(private val color: Int) : Drawable() { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeJoin = Paint.Join.ROUND } + + override fun draw(canvas: Canvas) { + val b = bounds; val s = minOf(b.width(), b.height()).toFloat() + val left = b.left + (b.width() - s) / 2; val top = b.top + (b.height() - s) / 2 + paint.color = color; paint.strokeWidth = s * 0.09f + val r = s * 0.08f + canvas.drawRoundRect(RectF(left + s * 0.34f, top + s * 0.14f, left + s * 0.86f, top + s * 0.70f), r, r, paint) // the sheet behind + canvas.drawRoundRect(RectF(left + s * 0.14f, top + s * 0.30f, left + s * 0.66f, top + s * 0.86f), r, r, paint) // the sheet in front + } + + override fun setAlpha(alpha: Int) { paint.alpha = alpha } + override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter } + @Deprecated("Deprecated in Java") override fun getOpacity() = PixelFormat.TRANSLUCENT +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpDb.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpDb.kt new file mode 100644 index 000000000..a37aed1f0 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpDb.kt @@ -0,0 +1,50 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.database.Cursor +import android.database.sqlite.SQLiteDatabase +import java.io.File + +/** + * The bundled help database. SQLite can't open a file inside the APK, so the asset is copied + * to the app's databases directory — once per app version, so an update brings new help — and + * then only ever opened read-only. + */ +object HelpDb { + + private const val NAME = "web_server_documentation.db" + private const val PREF_VERSION = "helpDbVersion" + private var store: HelpStore? = null + + @Synchronized + fun store(ctx: Context): HelpStore { + store?.let { return it } + val app = ctx.applicationContext + val file = app.getDatabasePath(NAME) + val prefs = app.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val version = app.packageManager.getPackageInfo(app.packageName, 0).longVersionCode + if (!file.exists() || prefs.getLong(PREF_VERSION, -1) != version) { + file.parentFile?.mkdirs() + val tmp = File(file.path + ".tmp") + app.assets.open(NAME).use { i -> tmp.outputStream().use { o -> i.copyTo(o) } } + if (!tmp.renameTo(file)) throw HelpException("couldn't install the help database") + prefs.edit().putLong(PREF_VERSION, version).apply() + } + val db = SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY) + return HelpStore { sql, args -> + db.rawQuery(sql, args).use { c -> + val rows = mutableListOf>() + while (c.moveToNext()) rows += (0 until c.columnCount).map { i -> value(c, i) } + rows + } + }.also { store = it } + } + + private fun value(c: Cursor, i: Int): Any? = when (c.getType(i)) { + Cursor.FIELD_TYPE_NULL -> null + Cursor.FIELD_TYPE_INTEGER -> c.getLong(i) + Cursor.FIELD_TYPE_FLOAT -> c.getDouble(i) + Cursor.FIELD_TYPE_BLOB -> c.getBlob(i) + else -> c.getString(i) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpStore.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpStore.kt new file mode 100644 index 000000000..96af54a5b --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpStore.kt @@ -0,0 +1,88 @@ +package org.appdevforall.shareyourapps.server + +import java.io.ByteArrayOutputStream + +/** Just enough of a database to run the help queries: rows of column values (String, Long, ByteArray, null). */ +fun interface HelpSql { + fun rows(sql: String, args: Array): List> +} + +class HelpTooltip(val id: Long, val summary: String, val detail: String, val buttons: List>) +class HelpPage(val mimeType: String, val bytes: ByteArray) +class HelpException(message: String) : Exception(message) + +/** + * Reads web_server_documentation.db, which uses CodeOnTheGo's documentation.db tables and + * columns, with the same queries. Its pages are stored as plain HTML (compression 'none', no + * template), so neither Brotli nor Pebble is needed; a row declaring either is refused clearly + * rather than misread. + */ +class HelpStore(private val sql: HelpSql) { + + companion object { + const val CATEGORY = "shareyourapps_server" + /** CodeOnTheGo's CONTENT_CHUNK_SIZE: a row this long continues as -1, -2, … */ + const val CHUNK_SIZE = 1024 * 1024 + + private const val QUERY_TOOLTIP = "SELECT T.rowid, T.id, T.summary, T.detail FROM Tooltips AS T, " + + "TooltipCategories AS TC WHERE T.categoryId = TC.id AND T.tag = ? AND TC.category = ?" + private const val QUERY_BUTTONS = "SELECT description, uri FROM TooltipButtons WHERE tooltipId = ? ORDER BY buttonNumberId" + private const val QUERY_CONTENT = "SELECT C.content, CT.value, CT.compression, C.templateId FROM Content C, " + + "ContentTypes CT WHERE C.contentTypeID = CT.id AND C.path = ?" + private const val QUERY_CHUNK = "SELECT content FROM Content WHERE path = ?" + } + + fun tooltip(tag: String): HelpTooltip? { + val row = sql.rows(QUERY_TOOLTIP, arrayOf(tag, CATEGORY)).firstOrNull() ?: return null + val id = (row[1] as Number).toLong() + val buttons = sql.rows(QUERY_BUTTONS, arrayOf(id.toString())).map { it[0] as String to it[1] as String } + return HelpTooltip(id, row[2] as String, row[3] as? String ?: "", buttons) + } + + /** + * The documentation database rows behind a tooltip, for the ⓘ panel (as CodeOnTheGo's debug popup): + * the database's version; the tooltip's row and category; its button rows; and, for each button's + * page, its content row and any continuation chunks. Each section is a title and its lines. + */ + fun debug(tag: String): List>> { + val out = mutableListOf>>() + val version = runCatching { sql.rows("SELECT version FROM DocumentationDatabaseVersion", emptyArray()).firstOrNull()?.get(0) }.getOrNull() + out += "Database" to listOf("web_server_documentation.db", "version ${version ?: "unknown"}", "category $CATEGORY") + val row = sql.rows("SELECT T.rowid, T.id, T.categoryId, TC.category, T.tag, length(T.summary), length(T.detail) FROM Tooltips AS T, " + + "TooltipCategories AS TC WHERE T.categoryId = TC.id AND T.tag = ? AND TC.category = ?", arrayOf(tag, CATEGORY)).firstOrNull() + if (row == null) { out += "Tooltips" to listOf("no row for tag \"$tag\" in category $CATEGORY"); return out } + out += "Tooltips" to listOf("rowid ${row[0]} · id ${row[1]}", "categoryId ${row[2]} (${row[3]})", "tag ${row[4]}", + "summary ${row[5]} characters · detail ${row[6]} characters") + val buttons = sql.rows("SELECT rowid, buttonNumberId, description, uri FROM TooltipButtons WHERE tooltipId = ? ORDER BY buttonNumberId", + arrayOf(row[1].toString())) + out += "TooltipButtons" to (buttons.map { "rowid ${it[0]} · #${it[1]} · \"${it[2]}\" → ${it[3]}" }.ifEmpty { listOf("none") }) + for (path in buttons.map { (it[3] as String).substringBefore('#') }.distinct()) { + val c = sql.rows("SELECT C.rowid, C.path, CT.value, CT.compression, C.languageId, C.templateId, length(C.content) FROM Content C, " + + "ContentTypes CT WHERE C.contentTypeID = CT.id AND C.path = ?", arrayOf(path)).firstOrNull() + val chunks = sql.rows("SELECT count(*) FROM Content WHERE path LIKE ?", arrayOf("$path-%")).firstOrNull()?.get(0) + out += "Content: $path" to (if (c == null) listOf("no row") else listOf("rowid ${c[0]} · ${c[2]}, compression ${c[3]}", + "languageId ${c[4]} · templateId ${c[5]}", "${c[6]} bytes · ${chunks ?: 0} continuation chunks")) + } + return out + } + + /** A Tier-3 page by path, or null if there's no such page. */ + fun page(path: String): HelpPage? { + val row = sql.rows(QUERY_CONTENT, arrayOf(path)).firstOrNull() ?: return null + val compression = row[2] as? String ?: "none" + val templateId = (row[3] as? Number)?.toLong() ?: 0 + if (compression != "none") throw HelpException("$path is stored with $compression compression, which this app doesn't read") + if (templateId != 0L) throw HelpException("$path uses a template, which this app doesn't render") + val first = row[0] as ByteArray + if (first.size != CHUNK_SIZE) return HelpPage(row[1] as String, first) + val out = ByteArrayOutputStream().apply { write(first) } + var n = 1 + var chunk = first + while (chunk.size == CHUNK_SIZE) { + chunk = sql.rows(QUERY_CHUNK, arrayOf("$path-$n")).firstOrNull()?.get(0) as? ByteArray ?: break + out.write(chunk) + n++ + } + return HelpPage(row[1] as String, out.toByteArray()) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpUi.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpUi.kt new file mode 100644 index 000000000..0270a9a6c --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HelpUi.kt @@ -0,0 +1,206 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.graphics.Color +import android.graphics.drawable.GradientDrawable +import android.os.Build +import android.os.Bundle +import android.text.Html +import android.view.KeyEvent +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.webkit.WebChromeClient +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.Button +import android.widget.LinearLayout +import android.widget.PopupWindow +import android.widget.ScrollView +import android.widget.TextView +import android.window.OnBackInvokedDispatcher +import java.io.ByteArrayInputStream + +/** Long-press help: Tier 1 is the summary, "See more" adds Tier 2 and links to Tier-3 pages. */ +object HelpUi { + + fun V.help(tag: String): V = apply { + setOnLongClickListener { v -> show(v, tag); true } + } + + fun show(anchor: View, tag: String) { + val ctx = anchor.context + val pal = Palette.of(ctx) + val tip = try { HelpDb.store(ctx).tooltip(tag) } catch (e: Exception) { null } + val dp = ctx.resources.displayMetrics.density + val pad = (14 * dp).toInt() + val box = LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL; setPadding(pad, pad, pad, pad) } + val scroll = ScrollView(ctx).apply { + addView(box) + background = GradientDrawable().apply { setColor(pal.help); cornerRadius = 10 * dp; setStroke((1 * dp).toInt(), pal.helpEdge) } + elevation = 8 * dp + } + val screen = ctx.resources.displayMetrics + val popup = PopupWindow(scroll, minOf((360 * dp).toInt(), (screen.widthPixels * 0.9).toInt()), + ViewGroup.LayoutParams.WRAP_CONTENT, true) + popup.elevation = 8 * dp + + fun text(html: String, size: Float) = TextView(ctx).apply { + text = Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT); textSize = size; setTextColor(pal.helpInk); setLinkTextColor(pal.link) + } + if (tip == null) { + box.addView(text("No help for this yet.", 15f)) + } else { + // Tier 1, with a faint ⓘ in the corner: the documentation rows behind this help, as in CodeOnTheGo. + val info = TextView(ctx).apply { + text = "ⓘ"; textSize = 16f; setTextColor(pal.helpInk); alpha = 0.35f + val touch = (48 * dp).toInt(); minWidth = touch; minHeight = touch; gravity = Gravity.TOP or Gravity.END + contentDescription = "Help data, for developers" + setOnClickListener { showRows(ctx, tag) } + } + box.addView(LinearLayout(ctx).apply { + orientation = LinearLayout.HORIZONTAL + addView(text(tip.summary, 15f), LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + addView(info) + }) + if (tip.detail.isNotBlank() || tip.buttons.isNotEmpty()) { + // "+ See more": a link, not a button, as CodeOnTheGo shows it — still a full-size touch target. + val more = TextView(ctx).apply { + text = android.text.SpannableString("+ See more").apply { setSpan(android.text.style.UnderlineSpan(), 0, length, 0) } + textSize = 15f; setTextColor(pal.link); minHeight = (48 * dp).toInt(); gravity = Gravity.CENTER_VERTICAL + isClickable = true; isFocusable = true + } + more.setOnClickListener { + box.removeView(more) + if (tip.detail.isNotBlank()) box.addView(text(tip.detail, 14f).apply { setPadding(0, pad / 2, 0, 0) }) + for ((label, uri) in tip.buttons) box.addView(Button(ctx).apply { + text = label; isAllCaps = false + setOnClickListener { popup.dismiss(); HelpActivity.open(ctx, uri) } + }) + place(popup, anchor, box, showing = true) + } + box.addView(more) + } + } + place(popup, anchor, box, showing = false) + } + + // Help sits on beige, or in dark mode a warm dark brown (Palette.help), apart from the screens around it. + + /** The ⓘ panel: which documentation database rows supplied this help. Selectable, so it can be copied into a report. */ + private fun showRows(ctx: android.content.Context, tag: String) { + val sections = try { HelpDb.store(ctx).debug(tag) } catch (e: Exception) { listOf("Error" to listOf(e.toString())) } + val text = sections.joinToString("\n\n") { (title, lines) -> title + "\n" + lines.joinToString("\n") { " $it" } } + val pad = (16 * ctx.resources.displayMetrics.density).toInt() + val view = TextView(ctx).apply { + this.text = text; typeface = android.graphics.Typeface.MONOSPACE; textSize = 12f; setTextIsSelectable(true) + setPadding(pad, pad / 2, pad, 0) // the dialog's own text colour, light or dark + } + android.app.AlertDialog.Builder(ctx).setTitle("Help data").setView(ScrollView(ctx).apply { addView(view) }) + .setPositiveButton("OK", null).show() + } + + /** + * Puts the popup wholly on the screen, beside [anchor]: below it if it fits there, else above it, else on whichever + * side has more room, scrolling inside. showAsDropDown only ever went below, so help for a button at the bottom + * of a screen (Done, Cancel) was cut off. Placed again after "See more", since the popup grows. + */ + private fun place(popup: PopupWindow, anchor: View, box: View, showing: Boolean) { + val dp = anchor.resources.displayMetrics.density + val margin = (8 * dp).toInt() + // The part of the screen the app can use, without the status and navigation bars. + val frame = android.graphics.Rect().also { anchor.getWindowVisibleDisplayFrame(it) } + val at = IntArray(2).also { anchor.getLocationOnScreen(it) } + box.measure( + View.MeasureSpec.makeMeasureSpec(popup.width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), + ) + // A long detail scrolls inside the popup instead of filling the screen. + val wanted = minOf(box.measuredHeight, (frame.height() * 0.7).toInt()) + val below = frame.bottom - margin - (at[1] + anchor.height) + val above = at[1] - margin - (frame.top + margin) + val (y, height) = when { + wanted <= below -> at[1] + anchor.height to wanted + wanted <= above -> at[1] - wanted to wanted + below >= above -> at[1] + anchor.height to below + else -> at[1] - above to above + } + val x = at[0].coerceIn(frame.left + margin, maxOf(frame.left + margin, frame.right - margin - popup.width)) + if (showing) popup.update(x, y, popup.width, height) + else { popup.height = height; popup.showAtLocation(anchor, Gravity.TOP or Gravity.START, x, y) } + } +} + +/** + * Tier-3 help pages, read from the help database. The WebView answers every request itself, + * from the database, so it can't reach the network; links between help pages work normally. + */ +class HelpActivity : Activity() { + + companion object { + private const val EXTRA_PATH = "path" + private const val HOST = "help.shareyourapps.invalid" + + fun open(ctx: Context, path: String) { + ctx.startActivity(Intent(ctx, HelpActivity::class.java).putExtra(EXTRA_PATH, path)) + } + } + + private lateinit var web: WebView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + title = "Help" + // Beige behind the page too, like the pages themselves, so nothing flashes white while one loads. + web = WebView(this).apply { setBackgroundColor(Palette.of(this@HelpActivity).help) } + web.settings.javaScriptEnabled = false + web.settings.allowFileAccess = false + web.settings.allowContentAccess = false + web.webChromeClient = object : WebChromeClient() { + override fun onReceivedTitle(view: WebView, t: String?) { if (!t.isNullOrBlank()) title = t } + } + web.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = + request.url.host != HOST // help pages only; anything else goes nowhere + + override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse { + val url = request.url + if (url.host != HOST) return reply(403, "text/plain", "Help pages can't reach the network.".toByteArray()) + val path = url.path.orEmpty().removePrefix("/").ifEmpty { "index.html" } + return try { + val page = HelpDb.store(this@HelpActivity).page(path) + if (page == null) reply(404, "text/html", "

There's no help page called $path.".toByteArray()) + else reply(200, page.mimeType, page.bytes) + } catch (e: Exception) { + reply(500, "text/html", "

This help page couldn't be read: ${e.message}".toByteArray()) + } + } + } + setContentView(web) + SystemBars.fit(web) + web.loadUrl("https://$HOST/" + (intent.getStringExtra(EXTRA_PATH) ?: "index.html")) + // Android 13+ delivers Back through this callback; apps targeting Android 16 get predictive + // back by default, and then onBackPressed() is never called at all. + if (Build.VERSION.SDK_INT >= 33) { + onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) { back() } + } + } + + private fun reply(code: Int, mime: String, body: ByteArray) = + WebResourceResponse(mime, "utf-8", code, if (code == 200) "OK" else "Error", emptyMap(), ByteArrayInputStream(body)) + + /** Back goes back a page within help, and leaves help from the first page. */ + private fun back() { + if (web.canGoBack()) web.goBack() else finish() + } + + /** Before Android 13, Back arrives as a key event. */ + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + if (Build.VERSION.SDK_INT < 33 && keyCode == KeyEvent.KEYCODE_BACK) { back(); return true } + return super.onKeyDown(keyCode, event) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HostService.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HostService.kt new file mode 100644 index 000000000..305dc4e34 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HostService.kt @@ -0,0 +1,526 @@ +package org.appdevforall.shareyourapps.server + +import android.net.ConnectivityManager +import android.net.LinkProperties +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.ServiceConnection +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import android.os.Process +import android.os.RemoteException + +/** + * The foreground service, in the app's main process. It keeps the app alive while the owner + * is in CodeOnTheGo, and owns the server process: every start kills the old server process, + * waits for it to die (so the port is free), and starts a fresh one. + */ +class HostService : Service() { + + companion object { + const val ACTION_START = "org.appdevforall.shareyourapps.server.START" + const val ACTION_STOP = "org.appdevforall.shareyourapps.server.STOP" + /** Serve the imported copy (design, Appendix E), with the seller's own PIN. */ + const val ACTION_SERVE_COPY = "org.appdevforall.shareyourapps.server.SERVE_COPY" + /** Which kind of store was last served, "own" or "copy", so Start, unlocking and a reboot bring back the right one. */ + const val PREF_SOURCE = "source" + /** The seller's PIN for the imported copy; the phone's own store keeps its own. */ + const val PREF_COPY_PIN = "copyPin" + const val EXTRA_DIR = "dir" + const val EXTRA_PORT = "port" + /** With ACTION_STOP: why, for the log. Absent means the owner stopped it in Manage Server. */ + const val EXTRA_REASON = "reason" + /** Set by LaunchActivity: the PIN, store name and token come from the plugin, not from saved settings. */ + const val EXTRA_FROM_PLUGIN = "fromPlugin" + const val PREFS = "server" + private const val PREF_PIN = "pin" + const val PREF_STORE_NAME = "storeName" + private const val PREF_SECRET = "cookieSecret" + /** "always", or "screenOff": stop when the screen turns off. */ + const val PREF_RUN_MODE = "runMode" + /** The access log's size limit in MB; 0 turns logging off. */ + const val PREF_LOG_MB = "logMb" + const val DEFAULT_LOG_MB = 10 + private const val CHANNEL = "server" + private const val NOTIFICATION = 1 + private const val DEATH_WAIT_MS = 3000L + private const val STOP_ACK_WAIT_MS = 2000L + } + + private val main = Handler(Looper.getMainLooper()) + private val replies = Messenger(Handler(Looper.getMainLooper()) { msg -> onReply(msg); true }) + + private var connection: ServiceConnection? = null + private var serverMessenger: Messenger? = null + private var serverPid = 0 + private var request: Bundle? = null + private var stopAck: (() -> Unit)? = null + private var stopAckGen = -1 + /** Buyers need these to join the hotspot, until the Serve screen shows them as a QR code. */ + private var hotspotLine: String? = null + /** Log lines from a failed hotspot attempt, written when a server next starts. */ + private val pendingLines = mutableListOf() + + /** Bumped by every request; a callback from an older request does nothing. */ + private var requestSeq = 0 + /** Bumped by every server start, and echoed by that server in its replies. */ + private var serverGen = 0 + /** The only server whose started/failed replies count; -1 once its stop has begun. */ + private var acceptGen = -1 + /** A stop is in progress; later stop requests wait for it instead of racing it. */ + private var stopping = false + private val afterStop = mutableListOf<() -> Unit>() + + override fun onBind(intent: Intent?): IBinder? = null + + /** + * Android only delivers the screen-off event to receivers registered while running, so the + * service registers one for as long as it runs, and checks the run mode each time. + */ + private val screenOff = object : BroadcastReceiver() { + override fun onReceive(c: Context, intent: Intent) { + val mode = getSharedPreferences(PREFS, MODE_PRIVATE).getString(PREF_RUN_MODE, "always") + if (mode != "screenOff" || connection == null) return + val mySeq = ++requestSeq + stopServer(withHotspot("paused: the screen turned off")) { if (mySeq == requestSeq) pause() } + } + } + + /** + * Resumes a paused server when the phone is unlocked — not merely when the screen lights up, + * so a notification waking the screen doesn't restart anything. Takes the same path as a + * manual Start, with the saved values. + */ + private val unlocked = object : BroadcastReceiver() { + override fun onReceive(c: Context, intent: Intent) { + if (!paused) return + paused = false + pendingLines += "[server] resuming: the phone was unlocked" + startService(Intent(this@HostService, HostService::class.java).setAction(ACTION_START)) + } + } + + /** Paused by screen-off: nothing is served and the hotspot is off, but the service stays, to notice the unlock. */ + @Volatile private var paused = false + + private fun pause() { + Hotspot.stop() + hotspotLine = null + unwatchWifi() + paused = true + ServerStatus.set("Paused while the screen is off. It resumes when you unlock the phone.") + goForeground("Paused while the screen is off — resumes when you unlock the phone") + } + + // ---------------------------------------------------------------- watching the Wi-Fi network + + /** The Wi-Fi address the running server is bound to, when it's on Wi-Fi; checked whenever Wi-Fi changes. */ + private var boundWifi: String? = null + private var wifiWatch: ConnectivityManager.NetworkCallback? = null + /** Set when a start chooses Wi-Fi or the Mobile hotspot; the watch begins once the server has bound. */ + private var startingOnWifi: String? = null + private var startingOnPhoneHotspot = false + /** Serving on the phone's Mobile hotspot rather than Wi-Fi: changes the reason, and what the owner is told. */ + private var watchingPhoneHotspot = false + /** Android tells apps nothing when the Mobile hotspot is turned off, so the address is also checked every few seconds. */ + private val poll = object : Runnable { + override fun run() { if (boundWifi == null) return; checkWifi(confirming = false); main.postDelayed(this, 5_000) } + } + + private fun watchWifi(address: String, phoneHotspot: Boolean) { + unwatchWifi() + boundWifi = address + watchingPhoneHotspot = phoneHotspot + main.postDelayed(poll, 5_000) + val cm = getSystemService(ConnectivityManager::class.java) ?: return + val cb = object : ConnectivityManager.NetworkCallback() { + override fun onLost(network: Network) { main.post { checkWifi(confirming = false) } } + override fun onLinkPropertiesChanged(network: Network, lp: LinkProperties) { main.post { checkWifi(confirming = false) } } + } + try { + cm.registerNetworkCallback(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build(), cb) + wifiWatch = cb + } catch (e: Exception) { } + } + + private fun unwatchWifi() { + wifiWatch?.let { cb -> try { getSystemService(ConnectivityManager::class.java)?.unregisterNetworkCallback(cb) } catch (e: Exception) { } } + wifiWatch = null + boundWifi = null + main.removeCallbacks(poll) + } + + /** + * Stops the server if the phone no longer has the address it's bound to — it left the + * network, or got a new address. Checked again two seconds later first, so a brief blip + * during a change can't stop anything. + */ + private fun checkWifi(confirming: Boolean) { + val address = boundWifi ?: return + val stillThere = systemInterfaces().any { i -> i.up && i.addresses.any { it.hostAddress == address } } + if (stillThere) return + if (!confirming) { main.postDelayed({ checkWifi(confirming = true) }, 2_000); return } + val phone = watchingPhoneHotspot + unwatchWifi() + val why = if (phone) "the phone's Mobile hotspot was turned off" else "the Wi-Fi network was lost" + val advice = if (phone) "Turn it on again and tap Start, or tap Start to use the server's own hotspot." + else "Connect to Wi-Fi again, or tap Start to use a hotspot instead." + val mySeq = ++requestSeq + stopServer(why) { if (mySeq == requestSeq) finish("Stopped: $why. $advice") } + } + + override fun onCreate() { + super.onCreate() + // A local-only hotspot can be stopped by the system; the store can't be reached without it. + Hotspot.onLost = { why -> + val mySeq = ++requestSeq + stopServer(why) { if (mySeq == requestSeq) finish("Stopped: $why. " + if (ServerStatus.servingCopy) "Tap Start to start again." else "Tap Start, or publish again, to start a new one.") } + } + // Only the system can send SCREEN_OFF and USER_PRESENT, so the receivers may be exported. + for ((receiver, action) in listOf(screenOff to Intent.ACTION_SCREEN_OFF, unlocked to Intent.ACTION_USER_PRESENT)) { + val filter = IntentFilter(action) + if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED) + else registerReceiver(receiver, filter) + } + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + // startForegroundService() requires startForeground() promptly, whatever the action. + goForeground(if (intent?.action == ACTION_START || intent?.action == ACTION_SERVE_COPY) "Starting…" else "Stopping…") + val mySeq = ++requestSeq + val current = { mySeq == requestSeq } + // Any request ends a pause, and the Wi-Fi watch restarts with the next successful start. + paused = false + unwatchWifi() + when (intent?.action) { + ACTION_SERVE_COPY -> serveCopy(current) + ACTION_START -> { + val prefs = getSharedPreferences(PREFS, MODE_PRIVATE) + val fromPlugin = intent.getBooleanExtra(EXTRA_FROM_PLUGIN, false) + // A manual Start, unlocking or a reboot brings back a copy if a copy was last served. + // Publishing from the plugin always serves this phone's own store (Appendix E.6). + // A phone with no store of its own, only a copy, has nothing else it could serve. + val ownSaved = prefs.getString(EXTRA_DIR, null) != null + if (!fromPlugin && intent.getStringExtra(EXTRA_DIR) == null && ImportJob.currentCopy(this) != null && + (prefs.getString(PREF_SOURCE, "own") == "copy" || !ownSaved)) { + serveCopy(current); return START_NOT_STICKY + } + // The plugin names the directory; a manual Start serves the last one published. + val dir = intent.getStringExtra(EXTRA_DIR) ?: prefs.getString(EXTRA_DIR, null) + if (dir == null) { + stopServer("no request") { if (current()) finish("Failed: nothing has been published yet. Publish from the Share Your Apps plugin first.") } + return START_NOT_STICKY + } + val req = Bundle().apply { + putString(Ipc.KEY_DIR, dir) + putInt(Ipc.KEY_PORT, intent.getIntExtra(EXTRA_PORT, prefs.getInt(EXTRA_PORT, Store.DEFAULT_PORT))) + putLong(Ipc.KEY_LOG_LIMIT, prefs.getInt(PREF_LOG_MB, DEFAULT_LOG_MB).toLong() * 1024 * 1024) + putString(Ipc.KEY_SECRET, cookieSecret()) + if (fromPlugin) { + putString(Ipc.KEY_PIN, intent.getStringExtra(LaunchContract.EXTRA_PIN)) + putString(Ipc.KEY_STORE_NAME, intent.getStringExtra(LaunchContract.EXTRA_STORE_NAME)) + putString(Ipc.KEY_TOKEN, intent.getStringExtra(LaunchContract.EXTRA_TOKEN)) // memory only + } else { + // A manual Start, or a start after a reboot, uses the saved values; no token. + putString(Ipc.KEY_PIN, prefs.getString(PREF_PIN, null)) + putString(Ipc.KEY_STORE_NAME, prefs.getString(PREF_STORE_NAME, null)) + } + } + ServerStatus.set("Starting…") + // The reason is Manage Server's unless the caller names another, as MCP control does ("restarted by an MCP client"). + val why = if (fromPlugin) "restarting for a new publish ($dir)" + else intent.getStringExtra(EXTRA_REASON)?.let { "$it ($dir)" } ?: "restarted from Manage Server ($dir)" + stopServer(why) { if (current()) chooseNetwork(req, current) { startServer(req) } } + } + // The reason is the owner's unless the caller names another, as MCP control does ("stopped by an MCP client"). + ACTION_STOP -> stopServer(withHotspot(intent.getStringExtra(EXTRA_REASON) ?: "stopped by the owner in Manage Server")) { if (current()) finish("Stopped") } + else -> stopServer("no request") { if (current()) finish("Stopped") } + } + return START_NOT_STICKY + } + + /** Serves the imported copy, from the app's private storage, with the seller's PIN and no token. */ + private fun serveCopy(current: () -> Boolean) { + val prefs = getSharedPreferences(PREFS, MODE_PRIVATE) + // An expired copy is deleted before it could be served again (Appendix E.5). + val expired = CopyExpiry.enforce(ImportJob.importedDir(this), ExpiryClock(CopyExpiry.clockFile(filesDir))) + val copy = ImportJob.currentCopy(this) + if (copy == null) { + val why = expired?.let { "Stopped: the copy of ${it.storeName} expired, and was deleted." } ?: "Failed: there's no imported store on this phone." + stopServer("no copy") { if (current()) finish(why) } + return + } + val req = Bundle().apply { + putString(Ipc.KEY_COPY_PATH, java.io.File(ImportJob.importedDir(this@HostService), copy.storeId).path) + putString(Ipc.KEY_DIR, copy.storeName) + putInt(Ipc.KEY_PORT, prefs.getInt(EXTRA_PORT, Store.DEFAULT_PORT)) + putLong(Ipc.KEY_LOG_LIMIT, prefs.getInt(PREF_LOG_MB, DEFAULT_LOG_MB).toLong() * 1024 * 1024) + putString(Ipc.KEY_SECRET, cookieSecret()) + putString(Ipc.KEY_PIN, prefs.getString(PREF_COPY_PIN, null)) + putString(Ipc.KEY_STORE_NAME, copy.storeName) + } + ServerStatus.set("Starting…") + stopServer("serving the imported copy of ${copy.storeName}") { if (current()) chooseNetwork(req, current) { startServer(req) } } + } + + override fun onDestroy() { + for (r in listOf(screenOff, unlocked)) try { unregisterReceiver(r) } catch (e: IllegalArgumentException) { } + unwatchWifi() + stopServer("the app's service was stopped") { } + } + + private fun startServer(req: Bundle) { + serverGen++ + acceptGen = serverGen + req.putInt(Ipc.KEY_GEN, serverGen) + request = req + val conn = object : ServiceConnection { + /** Set when the server process died on its own, so its restart is logged. */ + var restarting = false + override fun onServiceConnected(name: ComponentName, service: IBinder) { + if (connection !== this) return + val m = Messenger(service) + serverMessenger = m + val data = Bundle(req) + if (restarting) { + restarting = false + data.putStringArrayList(Ipc.KEY_LOG_LINES, arrayListOf("[server] restarted after the server process stopped unexpectedly")) + } + val msg = Message.obtain(null, Ipc.MSG_START).apply { this.data = data; replyTo = replies } + try { m.send(msg) } catch (e: RemoteException) { finish("Failed: the server process didn't respond") } + } + override fun onServiceDisconnected(name: ComponentName) { + // The server process died on its own. BIND_AUTO_CREATE restarts it, and + // onServiceConnected sends the same request again. + if (connection === this) { restarting = true; ServerStatus.set("Restarting after the server stopped unexpectedly…") } + } + } + connection = conn + val bound = bindService(Intent(this, ServerService::class.java), conn, + Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) + if (!bound) { + connection = null + finish("Failed: couldn't start the server process") + } + } + + /** + * Stops the server process and calls [then] once it's gone. First asks the server to log + * [reason] and close its sockets; when it confirms — or after [STOP_ACK_WAIT_MS] regardless — + * kills the process and waits for its death, so the port is free for the next start. + */ + private fun stopServer(reason: String, then: () -> Unit) { + if (stopping) { afterStop += then; return } + val conn = connection + val m = serverMessenger + val pid = serverPid + connection = null + serverMessenger = null + serverPid = 0 + if (conn == null) { then(); return } + val stoppingGen = acceptGen + acceptGen = -1 // from here on, a late "started" from this server is ignored + + stopping = true + var finished = false + val finishOnce = { + if (!finished) { + finished = true + stopping = false + then() + val queued = afterStop.toList() + afterStop.clear() + queued.forEach { it() } + } + } + + var killed = false + val kill = { + if (!killed) { + killed = true + stopAck = null + var waiting = false + if (m != null) { + try { + m.binder.linkToDeath({ main.post(finishOnce) }, 0) + waiting = true + } catch (e: RemoteException) { + // already dead + } + } + try { unbindService(conn) } catch (e: IllegalArgumentException) { } + if (pid > 0) Process.killProcess(pid) + if (waiting) main.postDelayed(finishOnce, DEATH_WAIT_MS) else finishOnce() + } + } + + if (m == null) { kill(); return } + stopAck = kill + stopAckGen = stoppingGen + try { + m.send(Message.obtain(null, Ipc.MSG_STOP).apply { + data = Bundle().apply { putString(Ipc.KEY_REASON, reason) } + replyTo = replies + }) + main.postDelayed(kill, STOP_ACK_WAIT_MS) + } catch (e: RemoteException) { + kill() + } + } + + private fun onReply(msg: Message) { + val gen = msg.data?.getInt(Ipc.KEY_GEN, -1) ?: -1 + if (msg.what == Ipc.MSG_STOPPED) { + if (gen == stopAckGen) stopAck?.invoke() + return + } + if (gen != acceptGen) return // from a server being stopped or already replaced + serverPid = msg.arg1 + when (msg.what) { + Ipc.MSG_STARTED -> { + val req = request ?: return + val dir = req.getString(Ipc.KEY_DIR) + val url = "http://${msg.data.getString(Ipc.KEY_ADDRESS)}:${msg.arg2}/" + // Saved only after a successful bind, so a failed start never replaces a good setup. + // Serving a copy never overwrites the saved details of the phone's own store. + val isCopy = req.getString(Ipc.KEY_COPY_PATH) != null + val edit = getSharedPreferences(PREFS, MODE_PRIVATE).edit().putString(PREF_SOURCE, if (isCopy) "copy" else "own") + if (!isCopy) edit.putString(EXTRA_DIR, dir).putInt(EXTRA_PORT, req.getInt(Ipc.KEY_PORT)) + .putString(PREF_PIN, req.getString(Ipc.KEY_PIN)) + .putString(PREF_STORE_NAME, req.getString(Ipc.KEY_STORE_NAME)) + edit.apply() + ServerStatus.servingCopy = isCopy + val what = if (isCopy) "a copy of $dir" else dir + ServerStatus.set("Serving $what", url, hotspotLine, phoneHotspot = startingOnPhoneHotspot) + goForeground("Serving $what at $url") + startingOnWifi?.let { watchWifi(it, startingOnPhoneHotspot) } + LaunchResult.deliver(msg.arg2, null) + } + Ipc.MSG_COPY_EXPIRED -> { + val name = msg.data.getString(Ipc.KEY_STORE_NAME) ?: "the store" + val seq = requestSeq + stopServer("the copy of $name expired, and was deleted") { if (seq == requestSeq) finish("Stopped: the copy of $name expired, and was deleted.") } + } + Ipc.MSG_FAILED -> { + val error = msg.data.getString(Ipc.KEY_ERROR) ?: "unknown error" + LaunchResult.deliver(0, error) + val seq = requestSeq + stopServer("the start failed") { if (seq == requestSeq) finish("Failed: $error") } + } + } + } + + /** Generated once, kept in this process's private preferences; the cookie value buyers get. */ + private fun cookieSecret(): String { + val prefs = getSharedPreferences(PREFS, MODE_PRIVATE) + prefs.getString(PREF_SECRET, null)?.let { return it } + val bytes = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) } + val secret = bytes.joinToString("") { "%02x".format(it) } + prefs.edit().putString(PREF_SECRET, secret).apply() + return secret + } + + /** + * Picks what the server binds to, then runs [go]: a hotspot already running (buyers may be + * on it), else the joined Wi-Fi network, else a new hotspot — Wi-Fi Direct first, then + * Android's local-only hotspot. + */ + private fun chooseNetwork(req: Bundle, current: () -> Boolean, go: () -> Unit) { + startingOnWifi = null + startingOnPhoneHotspot = false + Hotspot.info?.let { useHotspot(req, it, arrayListOf()); go(); return } + val wifi = Store.wifiAddress() + if (wifi != null) { + req.putString(Ipc.KEY_BIND_ADDRESS, wifi.hostAddress) + // Lines waiting for a start — such as a resume, or a failed hotspot attempt — are logged on Wi-Fi too. + req.putStringArrayList(Ipc.KEY_LOG_LINES, ArrayList(pendingLines)) + pendingLines.clear() + startingOnWifi = wifi.hostAddress + go(); return + } + // The phone's own Mobile hotspot, turned on in Settings: buyers may already be on it, so serve there. + val phone = Store.phoneHotspotAddress() + if (phone != null) { + req.putString(Ipc.KEY_BIND_ADDRESS, phone.hostAddress) + req.putStringArrayList(Ipc.KEY_LOG_LINES, ArrayList(pendingLines + "[hotspot] using the phone's own Mobile hotspot, at ${phone.hostAddress}")) + pendingLines.clear() + startingOnWifi = phone.hostAddress + startingOnPhoneHotspot = true + hotspotLine = "On this phone's Mobile hotspot" + go(); return + } + if (!Store.hasHotspotPermission(this)) { + val what = if (Build.VERSION.SDK_INT >= 33) "Nearby devices" else "Location" + finish("Failed: not connected to Wi-Fi, and starting a hotspot needs the $what permission. Open Share Your Apps Server and tap Start to grant it.") + return + } + ServerStatus.set("Not on Wi-Fi — starting a hotspot…") + val lines = arrayListOf("[hotspot] not connected to Wi-Fi, so starting a hotspot") + Hotspot.start(this, lines) { h -> + if (!current()) return@start + if (h == null) { + // Nothing is running to write the log, so these lines wait for the next start. + pendingLines += lines + finish("Failed: not connected to Wi-Fi, and no hotspot could be started. ${lines.last().substringAfter("] ")}") + } else { + useHotspot(req, h, lines); go() + } + } + } + + private fun useHotspot(req: Bundle, h: Hotspot.Info, lines: ArrayList) { + req.putString(Ipc.KEY_BIND_ADDRESS, h.address.hostAddress) + req.putStringArrayList(Ipc.KEY_LOG_LINES, ArrayList(pendingLines + lines)) + pendingLines.clear() + hotspotLine = "Hotspot “${h.ssid}”, password ${h.password}" + } + + private fun withHotspot(reason: String) = if (Hotspot.info != null) "$reason; hotspot turned off" else reason + + private fun finish(status: String) { + if (status.startsWith("Failed")) LaunchResult.deliver(0, status.removePrefix("Failed: ")) + paused = false + unwatchWifi() + // With nothing to serve, the hotspot only drains the battery. + Hotspot.stop() + hotspotLine = null + ServerStatus.set(status) + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + + private fun goForeground(text: String) { + val nm = getSystemService(NotificationManager::class.java) + nm.createNotificationChannel(NotificationChannel(CHANNEL, "Share Your Apps Server", NotificationManager.IMPORTANCE_LOW)) + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val n = Notification.Builder(this, CHANNEL) + .setSmallIcon(android.R.drawable.stat_sys_upload_done) + .setContentTitle("Share Your Apps Server") + .setContentText(text) + .setContentIntent(open) + .setOngoing(true) + .build() + if (Build.VERSION.SDK_INT >= 29) { + startForeground(NOTIFICATION, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE) + } else { + startForeground(NOTIFICATION, n) + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Hotspot.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Hotspot.kt new file mode 100644 index 000000000..3eab31ba7 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Hotspot.kt @@ -0,0 +1,289 @@ +package org.appdevforall.shareyourapps.server + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.wifi.WifiManager +import android.net.wifi.p2p.WifiP2pConfig +import android.net.wifi.p2p.WifiP2pManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import java.net.Inet4Address +import java.net.InetAddress +import java.net.NetworkInterface +import java.security.SecureRandom + +/** + * The hotspot the server uses when the phone isn't on Wi-Fi. Main process only. + * + * Tries a Wi-Fi Direct group first: its network name and password are chosen once and kept, so a + * phone that joined before rejoins by itself. Wi-Fi Direct is part of Wi-Fi, so it can't start + * while Wi-Fi is switched off, and it needs Android 10 for a fixed name and password. If it + * fails, falls back to Android's local-only hotspot, whose name and password Android picks + * afresh each time. Buyers join either one as an ordinary Wi-Fi network. + */ +object Hotspot { + + enum class Kind { WIFI_DIRECT, LOCAL_ONLY } + class Info(val kind: Kind, val ssid: String, val password: String, val address: InetAddress) + + private const val PREF_NAME = "p2pName" + private const val PREF_PASS = "p2pPass" + private const val POLLS = 20 // × 500 ms: how long to wait for the hotspot's address + private val main = Handler(Looper.getMainLooper()) + + @Volatile var info: Info? = null + private set + private var p2p: WifiP2pManager? = null + private var channel: WifiP2pManager.Channel? = null + private var reservation: WifiManager.LocalOnlyHotspotReservation? = null + private var watcher: BroadcastReceiver? = null + private var appCtx: Context? = null + /** Called on the main thread if a running hotspot stops without being asked to. */ + var onLost: ((String) -> Unit)? = null + + /** + * Starts a hotspot, or reuses the running one. Appends `[hotspot]` log lines to [log] as it + * goes; [done] runs on the main thread with the hotspot, or null if neither kind would start. + */ + fun start(ctx: Context, log: MutableList, done: (Info?) -> Unit) { + info?.let { done(it); return } + val app = ctx.applicationContext + appCtx = app + if (Build.VERSION.SDK_INT >= 29) { + startWifiDirect(app, log) { i -> if (i != null) done(i) else startLocalOnly(app, log, done) } + } else { + log += "[hotspot] Wi-Fi Direct skipped: a fixed network name needs Android 10 or later" + startLocalOnly(app, log, done) + } + } + + /** Turns the hotspot off. Returns what was stopped, for the log, or null if nothing was running. */ + fun stop(): String? { + val was = info ?: return null + info = null + unwatch() + when (was.kind) { + Kind.WIFI_DIRECT -> { + val m = p2p; val ch = channel + try { if (m != null && ch != null) m.removeGroup(ch, null) } catch (e: Exception) { } + if (Build.VERSION.SDK_INT >= 27) try { ch?.close() } catch (e: Exception) { } + channel = null; p2p = null + } + Kind.LOCAL_ONLY -> { try { reservation?.close() } catch (e: Exception) { }; reservation = null } + } + return if (was.kind == Kind.WIFI_DIRECT) "Wi-Fi Direct group" else "local-only hotspot" + } + + // ------------------------------------------------------------------ Wi-Fi Direct + + private fun startWifiDirect(app: Context, log: MutableList, next: (Info?) -> Unit) { + fun fail(why: String) { + log += "[hotspot] Wi-Fi Direct group failed: $why" + if (Build.VERSION.SDK_INT >= 27) try { channel?.close() } catch (e: Exception) { } + channel = null; p2p = null + next(null) + } + val mgr = app.getSystemService(WifiP2pManager::class.java) ?: return fail("Wi-Fi Direct isn't available on this phone") + val ch = mgr.initialize(app, Looper.getMainLooper(), null) ?: return fail("Wi-Fi Direct couldn't be initialized") + p2p = mgr; channel = ch + val (name, pass) = credentials(app) + val config = WifiP2pConfig.Builder().setNetworkName(name).setPassphrase(pass).build() + val create = { + try { + mgr.createGroup(ch, config, object : WifiP2pManager.ActionListener { + override fun onSuccess() = waitForGroup(mgr, ch, name, pass, log, POLLS, next, ::fail) + override fun onFailure(reason: Int) = fail(p2pReason(reason)) + }) + } catch (e: SecurityException) { fail("permission denied: ${e.message}") } + } + // Clear any group left from an earlier run, whatever the outcome, then create ours. + try { + mgr.removeGroup(ch, object : WifiP2pManager.ActionListener { + override fun onSuccess() = create() + override fun onFailure(reason: Int) = create() + }) + } catch (e: SecurityException) { fail("permission denied: ${e.message}") } + } + + private fun waitForGroup( + mgr: WifiP2pManager, ch: WifiP2pManager.Channel, name: String, pass: String, + log: MutableList, triesLeft: Int, next: (Info?) -> Unit, fail: (String) -> Unit, + ) { + try { + mgr.requestGroupInfo(ch) { g -> + val addr = g?.`interface`?.let { ipv4Of(it) } + when { + g != null && addr != null -> { + val i = Info(Kind.WIFI_DIRECT, g.networkName ?: name, g.passphrase ?: pass, addr) + info = i + log += "[hotspot] Wi-Fi Direct group up: ${i.ssid} at ${addr.hostAddress}" + watchGroup(mgr, ch) + next(i) + } + triesLeft > 0 -> main.postDelayed({ waitForGroup(mgr, ch, name, pass, log, triesLeft - 1, next, fail) }, 500) + else -> fail("the group started but never got an address") + } + } + } catch (e: SecurityException) { fail("permission denied: ${e.message}") } + } + + /** + * Notices a Wi-Fi Direct group disappearing while the server uses it. Wi-Fi Direct turning + * off (as it does when Wi-Fi is switched off) ends the group at once. A connection change — + * also sent when buyers join or leave — prompts a check that the group still exists, and it + * only counts as lost if it's still missing a second later, so a momentary gap can't stop + * the server. + */ + private fun watchGroup(mgr: WifiP2pManager, ch: WifiP2pManager.Channel) { + val app = appCtx ?: return + unwatch() + fun check(confirming: Boolean) { + if (info?.kind != Kind.WIFI_DIRECT) return + try { + mgr.requestGroupInfo(ch) { g -> + if (g != null || info?.kind != Kind.WIFI_DIRECT) return@requestGroupInfo + if (confirming) lost("the Wi-Fi Direct group stopped") + else main.postDelayed({ check(confirming = true) }, 1000) + } + } catch (e: SecurityException) { } + } + val r = object : BroadcastReceiver() { + override fun onReceive(c: Context, i: Intent) { + if (info?.kind != Kind.WIFI_DIRECT) return + val p2pOff = i.action == WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION && + i.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1) == WifiP2pManager.WIFI_P2P_STATE_DISABLED + if (p2pOff) lost("Wi-Fi was switched off, which stopped the Wi-Fi Direct group") else check(confirming = false) + } + } + val filter = IntentFilter().apply { + addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) + addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION) + } + // Only the system can send these, so the receiver may be exported. + if (Build.VERSION.SDK_INT >= 33) app.registerReceiver(r, filter, Context.RECEIVER_EXPORTED) else app.registerReceiver(r, filter) + watcher = r + } + + private fun unwatch() { + val r = watcher ?: return + watcher = null + try { appCtx?.unregisterReceiver(r) } catch (e: IllegalArgumentException) { } + } + + /** The running group vanished on its own: tidy up, then let the service stop the server. */ + private fun lost(why: String) { + if (info?.kind != Kind.WIFI_DIRECT) return + info = null + unwatch() + if (Build.VERSION.SDK_INT >= 27) try { channel?.close() } catch (e: Exception) { } + channel = null; p2p = null + onLost?.invoke(why) + } + + /** + * The Wi-Fi Direct name and password: generated once and kept, so phones that joined before + * rejoin by themselves, until the owner changes them in Manage Server. + */ + fun credentials(ctx: Context): Pair { + val prefs = ctx.applicationContext.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val name = prefs.getString(PREF_NAME, null) + val pass = prefs.getString(PREF_PASS, null) + if (name != null && pass != null) return name to pass + val rnd = SecureRandom() + val letters = "ABCDEFGHJKMNPQRSTUVWXYZ" + val n = HotspotSettings.PREFIX + (1..4).map { letters[rnd.nextInt(letters.length)] }.joinToString("") + val p = HotspotSettings.randomPassword() + prefs.edit().putString(PREF_NAME, n).putString(PREF_PASS, p).apply() + return n to p + } + + /** Saves the owner's choice; used the next time a Wi-Fi Direct group starts. Checked by the caller. */ + fun saveCredentials(ctx: Context, name: String, password: String) { + ctx.applicationContext.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE).edit() + .putString(PREF_NAME, name).putString(PREF_PASS, password).apply() + } + + private fun ipv4Of(ifaceName: String): InetAddress? = try { + NetworkInterface.getByName(ifaceName)?.inetAddresses?.toList()?.firstOrNull { it is Inet4Address } + } catch (e: Exception) { null } + + private fun p2pReason(r: Int) = when (r) { + WifiP2pManager.P2P_UNSUPPORTED -> "this phone doesn't support Wi-Fi Direct" + WifiP2pManager.BUSY -> "Wi-Fi is busy or switched off" + WifiP2pManager.ERROR -> "Android reported an error (Wi-Fi may be switched off)" + else -> "reason $r" + } + + // ------------------------------------------------------------------ local-only hotspot + + private fun startLocalOnly(app: Context, log: MutableList, done: (Info?) -> Unit) { + // Android 9 to 12 won't start a local-only hotspot while Location is off, and say only that it failed. + if (Build.VERSION.SDK_INT in 28..31) { + val lm = app.getSystemService(android.location.LocationManager::class.java) + if (lm != null && !lm.isLocationEnabled) { + log += "[hotspot] local-only hotspot failed: Location is off. This version of Android won't start the store's hotspot without it: turn Location on in Settings, then tap Start." + done(null); return + } + } + val wifi = app.getSystemService(WifiManager::class.java) + if (wifi == null) { log += "[hotspot] local-only hotspot failed: Wi-Fi isn't available"; done(null); return } + try { + wifi.startLocalOnlyHotspot(object : WifiManager.LocalOnlyHotspotCallback() { + override fun onStarted(r: WifiManager.LocalOnlyHotspotReservation) { + reservation = r + val (ssid, pass) = localOnlyCredentials(r) + waitForAddress(ssid, pass, log, POLLS, done) + } + override fun onStopped() { + if (info?.kind == Kind.LOCAL_ONLY) { info = null; reservation = null; onLost?.invoke("the local-only hotspot stopped") } + } + override fun onFailed(reason: Int) { + log += "[hotspot] local-only hotspot failed: ${lohsReason(reason)}" + done(null) + } + }, main) + } catch (e: Exception) { + log += "[hotspot] local-only hotspot failed: ${e.message ?: e.toString()}" + done(null) + } + } + + private fun waitForAddress(ssid: String, pass: String, log: MutableList, triesLeft: Int, done: (Info?) -> Unit) { + val addr = pickHotspotAddress(systemInterfaces()) + when { + addr != null -> { + val i = Info(Kind.LOCAL_ONLY, ssid, pass, addr) + info = i + log += "[hotspot] local-only hotspot up: $ssid at ${addr.hostAddress}" + done(i) + } + triesLeft > 0 -> main.postDelayed({ waitForAddress(ssid, pass, log, triesLeft - 1, done) }, 500) + else -> { + try { reservation?.close() } catch (e: Exception) { } + reservation = null + log += "[hotspot] local-only hotspot failed: it started but never got an address" + done(null) + } + } + } + + @Suppress("DEPRECATION") + private fun localOnlyCredentials(r: WifiManager.LocalOnlyHotspotReservation): Pair = + if (Build.VERSION.SDK_INT >= 30) { + val c = r.softApConfiguration + (c.ssid ?: "?") to (c.passphrase ?: "") + } else { + val c = r.wifiConfiguration + (c?.SSID?.trim('"') ?: "?") to (c?.preSharedKey?.trim('"') ?: "") + } + + private fun lohsReason(r: Int) = when (r) { + WifiManager.LocalOnlyHotspotCallback.ERROR_NO_CHANNEL -> "no Wi-Fi channel was available" + WifiManager.LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE -> "the phone's own hotspot or another Wi-Fi mode is in use" + WifiManager.LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED -> "hotspots are disallowed on this phone" + else -> "Android reported an error" + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HotspotSettings.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HotspotSettings.kt new file mode 100644 index 000000000..041fd088a --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HotspotSettings.kt @@ -0,0 +1,42 @@ +package org.appdevforall.shareyourapps.server + +import java.security.SecureRandom + +/** The owner's choices for the Wi-Fi Direct hotspot's name and password, checked against Android's rules. */ +object HotspotSettings { + + /** Android requires "DIRECT-" and two letters or digits; "LS" marks it as Share Your Apps's. */ + const val PREFIX = "DIRECT-LS-" + /** Android's limit for the whole name, in UTF-8 bytes. */ + const val MAX_NAME_BYTES = 32 + + fun name(suffix: String) = PREFIX + suffix.trim() + + /** Why [suffix] can't be used, or null if it can. */ + fun nameProblem(suffix: String): String? { + val s = suffix.trim() + val room = MAX_NAME_BYTES - PREFIX.length + return when { + s.isEmpty() -> "Enter something after $PREFIX." + s.any { it.isISOControl() } -> "The name can't contain control characters." + name(s).toByteArray(Charsets.UTF_8).size > MAX_NAME_BYTES -> + "That's too long: after $PREFIX there's room for $room bytes (accented letters and emoji take more than one)." + else -> null + } + } + + /** Why [password] can't be used, or null if it can: 8–63 ordinary keyboard characters, as Wi-Fi requires. */ + fun passwordProblem(password: String): String? = when { + password.length < 8 -> "The password needs at least 8 characters." + password.length > 63 -> "The password can be at most 63 characters." + password.any { it.code !in 32..126 } -> "Use only letters, digits, spaces and ordinary punctuation." + else -> null + } + + /** 16 characters, leaving out 0/O and 1/l/I, since buyers may type it. */ + fun randomPassword(): String { + val chars = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789" + val rnd = SecureRandom() + return (1..16).map { chars[rnd.nextInt(chars.length)] }.joinToString("") + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HttpServer.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HttpServer.kt new file mode 100644 index 000000000..5a436152b --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/HttpServer.kt @@ -0,0 +1,780 @@ +package org.appdevforall.shareyourapps.server + +import java.util.Base64 + +import org.json.JSONObject + +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.net.URLDecoder +import java.io.FilterOutputStream +import java.security.MessageDigest +import java.time.Instant +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec +import kotlin.concurrent.thread + +/** + * Who may see the store. [pin] null means no PIN. A request is authenticated by a valid `ls_auth` + * cookie, or by a `?token=` equal to [token] (the plugin's verify step). + * + * The cookie is the time it was issued and an HMAC of that time made with [cookieSecret], so the + * server itself rejects it after 24 hours — whatever a browser keeps — without a session list. It + * still survives restarts and PIN changes, since the secret doesn't change. + */ +class Auth( + val pin: String?, val cookieSecret: String, val token: String?, + private val now: () -> Long = { System.currentTimeMillis() / 1000 }, +) { + companion object { + val NONE = Auth(null, "", null) + const val LIFETIME_S = 86_400L + } + + /** A fresh cookie value: `.`. */ + fun issueCookie(): String { val t = now(); return "$t.${sign(t)}" } + + fun cookieValid(value: String): Boolean { + if (cookieSecret.isEmpty()) return false + val t = value.substringBefore('.', "").toLongOrNull() ?: return false + val age = now() - t + if (age < -60 || age >= LIFETIME_S) return false // a minute's grace for clock steps + return MessageDigest.isEqual(value.substringAfter('.', "").toByteArray(), sign(t).toByteArray()) + } + + private fun sign(t: Long): String { + val mac = Mac.getInstance("HmacSHA256") + mac.init(SecretKeySpec(cookieSecret.toByteArray(), "HmacSHA256")) + return mac.doFinal(t.toString().toByteArray()).joinToString("") { "%02x".format(it) } + } +} + +/** + * Serves one Store directory. **One main thread decides every response** — it reads the request, + * checks the PIN, cookie and token, routes, and chooses the file — so none of that ever runs + * concurrently. **Sending is left to a sender thread per response,** which writes the response, + * streams any file, writes the log line and closes the connection, so a buyer who stops + * receiving — a paused video, or a phone gone out of range — holds up nobody else. + * + * A sender shares only its last-progress time, which it writes and the main thread reads, and + * the log, whose writes are synchronized. The main thread alone owns the list of senders: it + * forgets finished ones and closes the connection of any that has sent nothing for [stallMs], + * and it also runs [stop]'s shutdown. At [MAX_SENDERS], new requests get a small "busy" page. + * Every response closes its connection, and each request's line and headers must arrive within + * [READ_TIMEOUT_MS], so an idle browser preconnect can't hold the main thread. + */ +class HttpServer( + private val root: File, + private val addresses: List, + private val port: Int, + private val log: StoreLog, + private val auth: Auth = Auth.NONE, + private val storeName: String = "Share Your Apps", + private val stallMs: Long = STALL_MS, + private val clock: () -> Long = System::currentTimeMillis, +) { + companion object { + const val READ_TIMEOUT_MS = 2000 + /** A whole request must arrive within this long of the main thread taking it. */ + const val REQUEST_DEADLINE_MS = 5000L + /** A stalled sender is closed after this long: it holds up nobody, so this only frees resources. */ + const val STALL_MS = 120_000L + /** At most this many responses being sent at once; beyond it, buyers get a "busy" page. */ + const val MAX_SENDERS = 16 + private const val MAX_HEADER_BYTES = 16 * 1024 + private const val MAX_FORM_BYTES = 1024 + /** Wrong PINs a client may enter before it must wait; each wrong PIN after that doubles the wait. */ + const val PIN_FREE_TRIES = 5 + const val PIN_LOCKOUT_MS = 30_000L + private const val PIN_LOCKOUT_MAX_MS = 3_600_000L + const val COOKIE = "ls_auth" + const val COOKIE_MAX_AGE = Auth.LIFETIME_S + private val STATUS = mapOf( + 200 to "OK", 206 to "Partial Content", 302 to "Found", 304 to "Not Modified", 400 to "Bad Request", 403 to "Forbidden", + 404 to "Not Found", 405 to "Method Not Allowed", 409 to "Conflict", 410 to "Gone", 426 to "Upgrade Required", 416 to "Range Not Satisfiable", 429 to "Too Many Requests", 503 to "Service Unavailable", + ) + } + + private val files = StoreFiles(root) + private val sockets = mutableListOf() + /** New connections, and [Stop], for the main thread. */ + private val queue = LinkedBlockingQueue() + private object Stop + private val threads = mutableListOf() + @Volatile private var running = false + /** False once [stopAccepting] has run: the main thread then closes any connection it's handed. */ + @Volatile private var accepting = true + /** The share the owner is showing, if any (design, Appendix E): set by the owner's screen, read by the main thread. */ + @Volatile var share: ShareHost? = null + + /** The responses being sent. The main thread's alone: nothing else reads or changes it. */ + private val senders = mutableListOf() + /** How many responses are being sent, as of the main thread's last tidy-up; for [stopAccepting]'s caller. */ + @Volatile var sending = 0 + private set + + /** The port actually bound (useful when [port] is 0). */ + var boundPort: Int = port + private set + + /** Binds every address. Throws IOException with a readable message if any bind fails. */ + fun start() { + var p = port + try { + for (a in addresses) { + val s = ServerSocket() + sockets += s + s.reuseAddress = true + s.bind(InetSocketAddress(a, p), 50) + if (p == 0) p = s.localPort + } + } catch (e: IOException) { + stop() + throw IOException("Can't listen on port $port: ${e.message}", e) + } + boundPort = p + running = true + for (s in sockets) { + threads += thread(name = "accept-${s.inetAddress.hostAddress}", isDaemon = true) { acceptLoop(s) } + } + threads += thread(name = "main", isDaemon = true) { mainLoop() } + } + + /** + * Stops taking new connections, but lets responses already being sent finish (design, Appendix + * E.5: a copy that expires lets downloads under way finish). Watch [sending] fall to 0, then [stop]. + */ + fun stopAccepting() { + accepting = false + running = false + for (s in sockets) try { s.close() } catch (e: IOException) { } + } + + /** + * Stops listening, and asks the main thread to close every response being sent — it owns the + * senders, so it does that itself — then waits, so the port is truly free when this returns: + * on some platforms, Android's among them, a socket a thread is blocked in accept() on isn't + * released until that thread returns. + */ + fun stop() { + running = false + for (s in sockets) try { s.close() } catch (e: IOException) { } + sockets.clear() + queue.put(Stop) + threads.forEach { try { it.join(3_000) } catch (e: InterruptedException) { } } + threads.clear() + while (true) { + val c = queue.poll() ?: break + if (c is Socket) try { c.close() } catch (e: IOException) { } + } + } + + private fun acceptLoop(s: ServerSocket) { + while (running) { + try { + val c = s.accept() + // On Android, a closed socket keeps listening until a blocked accept() returns, so one + // more connection can arrive after stopAccepting: close it, and end, releasing the port. + if (!running) { try { c.close() } catch (e: IOException) { }; return } + queue.put(c) + } catch (e: IOException) { + if (!running || s.isClosed) return + } catch (e: InterruptedException) { + return + } + } + } + + /** Takes each connection and decides its response, then hands it to a sender; tidies up at least once a second. */ + private fun mainLoop() { + val tick = (stallMs / 4).coerceIn(50, 1000) + while (true) { + val item = try { queue.poll(tick, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { Stop } + reap() + if (item === Stop) break + if (item is Socket) take(item) + } + // Stopping: close every response still being sent, and wait for its sender. + for (s in senders) try { s.x.socket.close() } catch (e: IOException) { } + for (s in senders) try { s.join(1_000) } catch (e: InterruptedException) { } + senders.clear() + } + + private fun take(c: Socket) { + // However a connection got here after stopAccepting — queued just before, or accepted at the + // last moment while Android was still closing the socket — it isn't served. + if (!accepting) { try { c.close() } catch (e: IOException) { }; return } + val x = Exchange(c, c.inetAddress?.hostAddress ?: "-") + try { handle(x) } catch (e: Exception) { x.status = 0 } // one bad request must never stop the server + if (x.status == 0) { try { c.close() } catch (e: IOException) { }; return } + if (senders.size >= MAX_SENDERS) return busy(x) + val sender = Sender(x) + senders += sender + sender.start() + } + + /** + * At [MAX_SENDERS]: a small "busy" page instead, written here — it's small enough that + * writing it can't block — so the main thread never waits for a sender to finish. + */ + private fun busy(x: Exchange) { + val req = x.req ?: return + val reply = Exchange(x.socket, x.client).also { it.req = req } + respondText(reply, req, 503, "The store is busy. Try again in a moment.", mapOf("Retry-After" to "5")) + try { + x.socket.getOutputStream().apply { write(reply.out.toByteArray()); flush() } + log.access(x.client, req.line, 503, reply.inlineBytes, req.headers["referer"], req.headers["user-agent"], 0) + } catch (e: IOException) { + } finally { + try { x.socket.close() } catch (e: IOException) { } + } + } + + /** Forgets finished senders, and closes the connection of any that has sent nothing for [stallMs]. */ + private fun reap() { + senders.removeAll { !it.isAlive } + sending = senders.size + val now = System.currentTimeMillis() + for (s in senders) { + if (s.closing || now - s.lastProgress <= stallMs) continue + s.closing = true + log.status("server", "closed a connection from ${s.x.client} that received nothing for ${stallMs / 1000} s") + try { s.x.socket.close() } catch (e: IOException) { } // its blocked write then fails, and the sender ends + } + } + + /** A socket's input, for reading a request: each read waits no longer than what's left of [deadline]. */ + private class Deadline(private val socket: Socket, private val deadline: Long) : InputStream() { + private val input = socket.getInputStream() + private fun arm() { + val left = deadline - System.currentTimeMillis() + if (left <= 0) throw SocketTimeoutException("the request took too long to arrive") + socket.soTimeout = minOf(READ_TIMEOUT_MS.toLong(), left).toInt().coerceAtLeast(1) + } + override fun read(): Int { arm(); return input.read() } + override fun read(b: ByteArray, off: Int, len: Int): Int { arm(); return input.read(b, off, len) } + } + + /** One request's response, as the main thread decided it, for a sender to send. */ + private class Exchange(val socket: Socket, val client: String) { + var req: Request? = null + /** The head, and any small body. */ + val out = ByteArrayOutputStream() + /** Content made as it's sent, such as an encrypted copy of the store; it writes to what it's given, which it mustn't close. */ + var producer: ((OutputStream) -> Unit)? = null + /** A file to stream after [out], for a GET of a file: [fileCount] bytes from [fileOffset]. */ + var file: File? = null + var fileOffset = 0L + var fileCount = 0L + /** For the log line; 0 means there's no response to send. */ + var status = 0 + var inlineBytes = 0L + } + + /** Sends one response, streams its file, writes its log line and closes its connection. */ + private inner class Sender(val x: Exchange) : Thread("sender") { + /** When it last handed anything to the network; the only thing it shares, read by the main thread. */ + @Volatile var lastProgress = System.currentTimeMillis() + /** Set by the main thread only, once it has closed this sender's connection. */ + var closing = false + /** Bytes handed to the network, headers included: the sender's own, for its log line. */ + var handedOver = 0L + + init { isDaemon = true } + + override fun run() { + val started = System.currentTimeMillis() + try { + val out = BufferedOutputStream(Progress(x.socket.getOutputStream(), this), 64 * 1024) + out.write(x.out.toByteArray()) + x.producer?.let { produce -> produce(object : FilterOutputStream(out) { + override fun write(b: ByteArray, off: Int, len: Int) { out.write(b, off, len) } + override fun close() { flush() } // the sender closes the connection itself + }) } + x.file?.let { f -> + FileInputStream(f).use { input -> + input.channel.position(x.fileOffset) // a range starts partway through + val buf = ByteArray(64 * 1024) + var left = x.fileCount + while (left > 0) { + val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()) + if (n < 0) break + out.write(buf, 0, n); left -= n + } + } + } + out.flush() + } catch (e: Exception) { + // The buyer went away, or the main thread closed a stalled connection. + } finally { + // Logged even when the send failed partway, with the body bytes actually handed to + // the network — so the log shows a download a buyer stopped, as a size smaller than the file's. + val req = x.req + val headLength = x.out.size() - x.inlineBytes + val body = (handedOver - headLength).coerceAtLeast(0) + if (req != null) log.access(x.client, req.line, x.status, body, req.headers["referer"], + req.headers["user-agent"], if (x.file != null || x.producer != null) System.currentTimeMillis() - started else 0) + try { x.socket.close() } catch (e: IOException) { } + } + } + } + + /** + * Notes each chunk actually handed to the network: its time, for the main thread's check on + * stalled senders, and its size, for the log. Writes go out in 8 KB slices, so a send that + * fails partway is counted to within 8 KB. + */ + private class Progress(out: OutputStream, private val sender: Sender) : FilterOutputStream(out) { + override fun write(b: ByteArray, off: Int, len: Int) { + var i = off + while (i < off + len) { + val n = minOf(8 * 1024, off + len - i) + out.write(b, i, n); i += n + sender.handedOver += n + sender.lastProgress = System.currentTimeMillis() + } + } + override fun write(b: Int) { out.write(b); sender.handedOver++; sender.lastProgress = System.currentTimeMillis() } + } + + private class Request( + val method: String, val target: String, val line: String, + val headers: Map, + ) { + val path: String get() = target.substringBefore('?') + fun query(name: String): String? = target.substringAfter('?', "").split('&') + .firstOrNull { it.substringBefore('=') == name }?.substringAfter('=', "") + ?.let { runCatching { URLDecoder.decode(it, "UTF-8") }.getOrNull() } + fun cookie(name: String): String? = headers["cookie"]?.split(';')?.map { it.trim() } + ?.firstOrNull { it.substringBefore('=') == name }?.substringAfter('=', "") + } + + /** Reads the request and decides its response, into [x]; leaves x.status at 0 when there's nothing to send. */ + private fun handle(x: Exchange) { + x.socket.soTimeout = READ_TIMEOUT_MS + // The whole request — headers, and any body — must arrive within REQUEST_DEADLINE_MS, not just + // each read within READ_TIMEOUT_MS: a client sending a byte a second can't hold the main thread. + val input = BufferedInputStream(Deadline(x.socket, System.currentTimeMillis() + REQUEST_DEADLINE_MS)) + + val req = try { + readRequest(input) + } catch (e: SocketTimeoutException) { + return // an idle connection, such as a browser preconnect: close quietly + } ?: return + x.req = req + + if (!files.hasIndex()) { + return respondText(x, req, 503, "This store hasn't been set up yet.") + } + + val path = req.path + // Sellers aren't buyers, so the sharing address comes before the PIN. + if (path.startsWith("/share/")) return shareRoute(input, x, req) + if (path == "/pin") return pinRoute(input, x, req) + if (req.method != "GET" && req.method != "HEAD") { + return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET, HEAD")) + } + if (auth.pin != null && !authenticated(req)) return redirect(x, req, "/pin") + + val relative = when { + path == "/" || path == "/index.html" -> "index.html" + path.startsWith("/f/") -> percentDecode(path.removePrefix("/f/")) + ?: return respondText(x, req, 400, "Bad request.") + else -> return respondText(x, req, 404, "Not found.") + } + val file = files.resolve(relative) + if (file != null) return serveFile(x, req, file, relative) + // A source zip the compressor has replaced by its .gz copy, to save space. + val gzOnly = if (relative.endsWith(".zip")) files.resolve("$relative.gz") else null + if (gzOnly != null) return serveFile(x, req, null, relative, gzOnly) + respondText(x, req, 404, "Not found.") + } + + /** + * The sharing address (design, Appendix E.3): request, reveal, status and copy. Only while the + * owner's screen has a share; otherwise every path answers not found, as if it didn't exist. + */ + private fun shareRoute(input: InputStream, x: Exchange, req: Request) { + // While the owner's screen has a share, open or not, so a seller can still hear "denied" or + // "expired"; each route refuses what it should. Leaving the sharing screen removes the share. + val host = share ?: return respondText(x, req, 404, "Not found.") + val route = req.path.removePrefix("/share/") + // A phone that doesn't have the app yet gets it here: the genuine APK, signed with the server's key. + if (route == "app") return shareApp(x, req, host) + val post = route == "request" || route == "reveal" + if (post && req.method != "POST") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "POST")) + if (!post && req.method != "GET") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET")) + try { + when (route) { + "request" -> { + val body = readJson(input, req) ?: return respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + val (id, ownerKey) = host.request(body.optString("code"), body.optString("name"), + Base64.getDecoder().decode(body.optString("commitment")), body.optInt("protocol", 1)) + log.status("share", "${host.phoneName()} asked for a copy of ${host.storeName}") + respondJson(x, req, 200, JSONObject().put("request", id).put("ownerKey", Base64.getEncoder().encodeToString(ownerKey)) + .put("protocol", ShareHost.PROTOCOL)) + } + "reveal" -> { + val body = readJson(input, req) ?: return respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + host.reveal(body.optString("request"), Base64.getDecoder().decode(body.optString("sellerKey"))) + respondJson(x, req, 200, JSONObject().put("ok", true)) + } + "status" -> { + val state = host.status(req.query("request").orEmpty()) + val reply = JSONObject().put("state", state).put("storeName", host.storeName) + if (state == "allowed") reply.put("expires", host.copyExpiry()?.toString() ?: JSONObject.NULL) + respondJson(x, req, 200, reply) + } + "copy" -> { + val copy = host.copyFor(req.query("request").orEmpty()) + writeHead(x.out, 200, linkedMapOf("Content-Type" to "application/octet-stream", "Cache-Control" to "no-store")) + x.status = 200 + // Encrypted as it's written, so the copy is never stored on this phone. + x.producer = { out -> + try { + SealedOutputStream(out, copy.key).use { SharePackage.write(it, copy.storeDir, copy.description, copy.storeKey) } + } catch (e: Exception) { host.transferFailed(); throw e } + host.sent() + log.status("share", "sent a copy of ${host.storeName} to ${host.phoneName()}") + } + } + else -> respondText(x, req, 404, "Not found.") + } + } catch (e: ShareHost.Refused) { + respondJson(x, req, e.refusal.status, JSONObject().put("error", e.refusal.message)) + } catch (e: IllegalArgumentException) { // bad base64 + respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + } + } + + private fun shareApp(x: Exchange, req: Request, host: ShareHost) { + if (req.method != "GET" && req.method != "HEAD") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET")) + val apk = host.appApk?.takeIf { it.isFile } ?: return respondText(x, req, 404, "Not found.") + writeHead(x.out, 200, linkedMapOf( + "Content-Type" to "application/vnd.android.package-archive", + "Content-Length" to apk.length().toString(), + "Content-Disposition" to "attachment; filename=\"share-your-apps-server.apk\"", + "Cache-Control" to "no-store", + )) + if (req.method == "GET") { x.file = apk; x.fileOffset = 0; x.fileCount = apk.length() } + x.status = 200 + } + + private fun readJson(input: InputStream, req: Request): JSONObject? { + val length = req.headers["content-length"]?.toIntOrNull() ?: return null + if (length < 0 || length > MAX_FORM_BYTES) return null + val body = ByteArray(length); var read = 0 + while (read < length) { val n = input.read(body, read, length - read); if (n < 0) return null; read += n } + return try { JSONObject(String(body, Charsets.UTF_8)) } catch (e: Exception) { null } + } + + private fun respondJson(x: Exchange, req: Request, status: Int, json: JSONObject) { + val bytes = json.toString().toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf("Content-Type" to "application/json", "Content-Length" to bytes.size.toString(), "Cache-Control" to "no-store")) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = if (req.method == "HEAD") 0 else bytes.size.toLong() + } + + private fun authenticated(req: Request): Boolean { + val cookie = req.cookie(COOKIE) + if (cookie != null && auth.cookieValid(cookie)) return true + val token = req.query("token") + return token != null && auth.token != null && same(token, auth.token) + } + + private fun same(a: String, b: String) = MessageDigest.isEqual(a.toByteArray(), b.toByteArray()) + + /** A client's wrong PINs, and until when it must wait. Main thread only, like everything [pinRoute] touches. */ + private class PinFails(var count: Int = 0, var lockedUntil: Long = 0) + private val pinFails = HashMap() + + /** + * GET shows the PIN page (or redirects home if there's nothing to enter); POST checks the PIN. + * After [PIN_FREE_TRIES] wrong PINs a client waits [PIN_LOCKOUT_MS], doubling with each further + * wrong one, so a short PIN can't simply be tried in full. A waiting client is answered at once. + */ + private fun pinRoute(input: InputStream, x: Exchange, req: Request) { + val pin = auth.pin + if (pin == null || authenticated(req)) return redirect(x, req, "/") + when (req.method) { + "GET", "HEAD" -> respondHtml(x, req, pinPage(null)) + "POST" -> { + val entered = readForm(input, req)?.get("pin") + ?: return respondText(x, req, 400, "Bad request.") + val now = clock() + val fails = pinFails[x.client] + if (fails != null && now < fails.lockedUntil) { + val seconds = (fails.lockedUntil - now + 999) / 1000 + return respondHtml(x, req, pinPage("Too many wrong PINs. Try again in $seconds seconds."), 429) + } + if (entered.isNotEmpty() && same(entered, pin)) { + pinFails.remove(x.client) + redirect(x, req, "/", mapOf("Set-Cookie" to + "$COOKIE=${auth.issueCookie()}; Max-Age=$COOKIE_MAX_AGE; Path=/; HttpOnly; SameSite=Lax")) + } else { + // ponytail: per-client only; many addresses guessing together aren't slowed. Add a store-wide budget if that's seen. + if (pinFails.size > 1000) pinFails.clear() + val f = pinFails.getOrPut(x.client) { PinFails() } + f.count++ + if (f.count >= PIN_FREE_TRIES) { + f.lockedUntil = now + minOf(PIN_LOCKOUT_MS shl minOf(f.count - PIN_FREE_TRIES, 20), PIN_LOCKOUT_MAX_MS) + } + respondHtml(x, req, pinPage("That PIN isn't right.")) + } + } + else -> respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET, POST")) + } + } + + private fun readForm(input: InputStream, req: Request): Map? { + val length = req.headers["content-length"]?.toIntOrNull() ?: return null + if (length < 0 || length > MAX_FORM_BYTES) return null + val body = ByteArray(length) + var read = 0 + while (read < length) { + val n = input.read(body, read, length - read) + if (n < 0) return null + read += n + } + return String(body, Charsets.UTF_8).split('&').filter { it.isNotEmpty() }.associate { + val k = it.substringBefore('=') + val v = it.substringAfter('=', "") + k to (runCatching { URLDecoder.decode(v, "UTF-8") }.getOrNull() ?: "") + } + } + + private fun pinPage(error: String?): String { + val name = htmlEscape(storeName) + val err = if (error != null) "

${htmlEscape(error)}

" else "" + return Brand.page(name, "

$name

$err" + + "
" + + "
") + } + + private fun redirect(x: Exchange, req: Request, to: String, extra: Map = emptyMap()) { + writeHead(x.out, 302, linkedMapOf("Location" to to, "Content-Length" to "0", "Cache-Control" to "no-store") + extra) + x.status = 302 + } + + private fun respondHtml(x: Exchange, req: Request, html: String, status: Int = 200) { + val bytes = html.toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf( + "Content-Type" to "text/html; charset=utf-8", + "Content-Length" to bytes.size.toString(), + "Cache-Control" to "no-store", + )) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = bytes.size.toLong() + } + + /** + * Sends [file], or its `.gz` copy if the client accepts gzip and one exists. Or, with [file] null, a source zip + * kept only as its copy, [gzOnly]: the copy as-is to a client that accepts gzip, and otherwise the zip's own bytes, + * decompressed on the fly — whole, or a range, skipped to. Its size, date and ETag are the zip's, exactly as they + * were before it was deleted, since the copy has its date, and gzip records its size. + */ + private fun serveFile(x: Exchange, req: Request, file: File?, relative: String, gzOnly: File? = null) { + val name = relative.substringAfterLast('/') + val length = file?.length() ?: StoreFiles.gzipSize(gzOnly!!) + // Each publish copies its files afresh, so a file's time changes whenever its content can have. + val modified = (file ?: gzOnly!!).lastModified() / 1000 * 1000 + // 304 only for this very file of this very store. On Wi-Fi Direct every store is at the same + // address, so a browser's cached page may be another store's: an exact date match, or an + // ETag naming the store, rather than "not modified since", keeps one from confirming another. + val etag = "W/\"${root.name}-$modified-$length\"" + val inm = req.headers["if-none-match"] + val since = req.headers["if-modified-since"]?.let(::parseHttpDate) + val unchanged = if (inm != null) inm.split(',').map { it.trim().removePrefix("W/") }.any { it == "*" || it == etag.removePrefix("W/") } + else since != null && modified == since + if (unchanged) { + writeHead(x.out, 304, linkedMapOf("ETag" to etag, "Last-Modified" to httpDate(modified), "Vary" to "Accept-Encoding", "Cache-Control" to "no-cache")) + x.status = 304 + return + } + // A range request — skipping in a video, or resuming a download — gets just that slice of + // the plain file, never of its gzip copy, whose byte positions differ. If-Range with an old + // date means the browser's copy is stale, so it gets the whole, new file instead. + val range = req.headers["range"]?.takeIf { ifRangeHolds(req.headers["if-range"], modified) }?.let { parseRange(it, length) } + if (range == ByteRange.UNSATISFIABLE) { + writeHead(x.out, 416, linkedMapOf("Content-Range" to "bytes */$length", "Content-Length" to "0", "Accept-Ranges" to "bytes")) + x.status = 416 + return + } + val gz = if (range == null && acceptsGzip(req.headers["accept-encoding"])) (gzOnly ?: files.resolve("$relative.gz")) else null + val body = gz ?: file // null: decompressed from gzOnly, below + val offset = range?.start ?: 0L + val count = range?.let { it.end - it.start + 1 } ?: (body?.length() ?: length) + val headers = linkedMapOf( + "Content-Type" to StoreFiles.contentType(name), + "Content-Length" to count.toString(), + "Accept-Ranges" to "bytes", + "Vary" to "Accept-Encoding", + // Every publish reuses the same addresses — "/" and each product's files — for new + // content, so browsers must check back each time rather than reuse an old copy. + "Cache-Control" to "no-cache", + "Last-Modified" to httpDate(modified), + "ETag" to etag, + ) + if (range != null) headers["Content-Range"] = "bytes ${range.start}-${range.end}/$length" + if (gz != null) headers["Content-Encoding"] = "gzip" + StoreFiles.disposition(name)?.let { headers["Content-Disposition"] = it } + + val status = if (range != null) 206 else 200 + writeHead(x.out, status, headers) + if (req.method == "GET") { + if (body != null) { x.file = body; x.fileOffset = offset; x.fileCount = count } // the sender streams it + else x.producer = { out -> StoreFiles.gunzipSlice(gzOnly!!, offset, count, out) } // the zip, decompressed + } + x.status = status + } + + private fun respondText( + x: Exchange, req: Request, status: Int, message: String, + extra: Map = emptyMap(), + ) { + // The same look as the PIN page: every page a buyer can reach is themed. + val bytes = Brand.page(htmlEscape(storeName).ifEmpty { "Share Your Apps" }, "

$message

").toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf( + "Content-Type" to "text/html; charset=utf-8", + "Content-Length" to bytes.size.toString(), + "Cache-Control" to "no-store", + ) + extra) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = if (req.method == "HEAD") 0 else bytes.size.toLong() + } + + private fun writeHead(out: OutputStream, status: Int, headers: Map) { + val sb = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: ""}\r\n") + for ((k, v) in headers) sb.append(k).append(": ").append(v).append("\r\n") + sb.append("Connection: close\r\n\r\n") + out.write(sb.toString().toByteArray(Charsets.ISO_8859_1)) + } + + /** Reads the request line and headers. Returns null if the request is malformed or too big. */ + private fun readRequest(input: InputStream): Request? { + val buf = ByteArrayOutputStream() + var last4 = 0 + while (true) { + val b = input.read() + if (b < 0) return null + buf.write(b) + last4 = (last4 shl 8) or b + if (last4 == 0x0d0a0d0a || (last4 and 0xffff) == 0x0a0a) break + if (buf.size() > MAX_HEADER_BYTES) return null + } + val lines = buf.toString("ISO-8859-1").split("\n").map { it.trimEnd('\r') } + val requestLine = lines.firstOrNull() ?: return null + val parts = requestLine.split(' ') + if (parts.size != 3 || !parts[2].startsWith("HTTP/")) return null + val headers = HashMap() + for (l in lines.drop(1)) { + val i = l.indexOf(':') + if (i > 0) headers[l.substring(0, i).trim().lowercase()] = l.substring(i + 1).trim() + } + // The verify token is never written to disk, so it's blanked in the line that gets logged. + val logged = requestLine.replace(Regex("""([?&]token=)[^&\s]*"""), "\$1-") + return Request(parts[0], parts[1], logged, headers) + } +} + +/** An HTTP date, such as "Thu, 24 Sep 2026 10:00:00 GMT". */ +/** A single byte range, inclusive; or [UNSATISFIABLE], for a range that starts past the end. */ +data class ByteRange(val start: Long, val end: Long) { + companion object { val UNSATISFIABLE = ByteRange(-1, -1) } +} + +/** + * A Range header, for a file of [length] bytes, following RFC 9110: a single `bytes=a-b`, `bytes=a-` + * or `bytes=-n`. Several ranges, another unit, or anything malformed returns null, meaning the + * header is ignored and the whole file sent, which the standard allows. A range that starts at or + * past the end is [ByteRange.UNSATISFIABLE]; one that runs past the end is cut short. + */ +fun parseRange(header: String, length: Long): ByteRange? { + val h = header.trim() + if (!h.startsWith("bytes=", ignoreCase = true)) return null + val spec = h.substring(6).trim() + if (',' in spec) return null + val dash = spec.indexOf('-').takeIf { it >= 0 } ?: return null + val a = spec.substring(0, dash).trim(); val b = spec.substring(dash + 1).trim() + if (!a.all(Char::isDigit) || !b.all(Char::isDigit)) return null + return when { + a.isEmpty() && b.isEmpty() -> null + a.isEmpty() -> { // the last n bytes + val n = b.toLongOrNull() ?: return null + if (n == 0L || length == 0L) ByteRange.UNSATISFIABLE else ByteRange(maxOf(0, length - n), length - 1) + } + else -> { + val start = a.toLongOrNull() ?: return null + val end = if (b.isEmpty()) length - 1 else (b.toLongOrNull() ?: return null) + when { + b.isNotEmpty() && end < start -> null + start >= length -> ByteRange.UNSATISFIABLE + else -> ByteRange(start, minOf(end, length - 1)) + } + } + } +} + +/** Whether a range request's If-Range still matches the file: absent, or the file's own date. We send no ETags. */ +fun ifRangeHolds(ifRange: String?, modified: Long): Boolean = ifRange == null || parseHttpDate(ifRange.trim()) == modified + +fun httpDate(millis: Long): String = + DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(millis).atOffset(ZoneOffset.UTC)) + +/** The time an HTTP date names, in milliseconds, or null if it isn't one. */ +fun parseHttpDate(s: String): Long? = + try { ZonedDateTime.parse(s.trim(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() } catch (e: Exception) { null } + +/** True if an Accept-Encoding header accepts gzip (q=0 means refused). */ +fun acceptsGzip(header: String?): Boolean { + if (header == null) return false + return header.split(',').any { part -> + val bits = part.split(';').map { it.trim() } + val coding = bits[0].lowercase() + val q = bits.drop(1).firstOrNull { it.startsWith("q=") }?.substring(2)?.toDoubleOrNull() ?: 1.0 + (coding == "gzip" || coding == "x-gzip") && q > 0.0 + } +} + +/** Decodes %XX escapes in a URL path as UTF-8. Returns null on a malformed escape or a NUL. */ +fun percentDecode(s: String): String? { + val out = ByteArrayOutputStream() + var i = 0 + while (i < s.length) { + val ch = s[i] + if (ch == '%') { + if (i + 2 >= s.length) return null + val v = s.substring(i + 1, i + 3).toIntOrNull(16) ?: return null + out.write(v) + i += 3 + } else { + out.write(ch.toString().toByteArray(Charsets.UTF_8)) + i++ + } + } + val r = out.toString("UTF-8") + return if (r.contains('\u0000')) null else r +} + +fun htmlEscape(s: String): String = + s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportActivity.kt new file mode 100644 index 000000000..c2044305d --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportActivity.kt @@ -0,0 +1,536 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Activity +import android.app.AlertDialog +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.text.InputType +import android.view.Gravity +import android.view.View +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.ScrollView +import android.widget.TextView +import java.net.InetSocketAddress +import java.text.DateFormat +import java.util.Date +import org.appdevforall.shareyourapps.server.HelpUi.help + +/** + * Importing a copy of someone else's store (design, Appendix E.2; screens 5 and 6). Opened from + * Manage Server's Import panel, or from a share's QR link, shareyourapps-share://…, which a camera app + * offers to open — then the owner's address and code are already filled in. The import itself runs + * in [ImportJob], so this screen can rotate, or be left and reopened, without breaking it. + */ +class ImportActivity : Activity() { + private lateinit var body: LinearLayout + private val pad by lazy { (16 * resources.displayMetrics.density).toInt() } + private var linkAddress: InetSocketAddress? = null + private var linkCode: String? = null + private var shownPhase: ImportJob.Phase? = null + private var asked: ImportJob.Question? = null + private var progress: ProgressBar? = null + private var progressText: TextView? = null + private val listener: () -> Unit = { render() } + + // ---- Listen: hearing the code from the owner's Play sound ---- + /** The listener while it listens, and the button, which reads Stop listening meanwhile. */ + private var soundListener: SoundIo.Listener? = null + private var listenButton: Button? = null + private var listenStatus: TextView? = null + /** The name field, so a heard code imports with the name as shown. */ + private var nameField: EditText? = null + /** Counts listeners started and stopped, so a finished one's callback can't reset a newer one. */ + private var listenRun = 0 + /** Taps on Listen within [TAP_MS] of each other: three run the self-test; one listens. */ + private var taps = 0 + private val tapDone = Runnable { val n = taps; taps = 0; if (n >= 3) selfTest() else toggleListen() } + /** The self-test's player, while it plays. */ + private var testPlayer: SoundIo.Player? = null + private val ui = android.os.Handler(android.os.Looper.getMainLooper()) + /** What to do once the microphone permission is answered: listen, or run the self-test. */ + private var afterPermission: (() -> Unit)? = null + /** The line under Listen, kept so a redraw of the form shows it again. */ + private var listenMessage = "" + /** The code was heard, not scanned: the form says so. */ + private var heard = false + /** What the tones said about the owner's network, shown if the import from them fails: join it, then Continue. */ + private var heardNetwork: String? = null + /** While listening: the microphone's loudness meter and the seconds left. Hidden otherwise. */ + private var meter: ProgressBar? = null + private var meterText: TextView? = null + private var countdownText: TextView? = null + /** The last level reported, so a redraw of the form shows the meter and countdown as they were. */ + private var lastLevel: SoundIo.Level? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + title = "Import a store" + body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(pad, pad, pad, pad) } + setContentView(ScrollView(this).apply { setBackgroundColor(pal.screen); addView(body) }.also { SystemBars.fit(it) }) + if (Build.VERSION.SDK_INT >= 33) onBackInvokedDispatcher.registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT) { back() } + intent?.data?.toString()?.let { ShareLink.parse(it) }?.let { (address, port, code) -> + linkAddress = InetSocketAddress(address, port); linkCode = code + } + } + + override fun onResume() { + super.onResume() + ImportJob.observe(listener) + shownScreen = this + // A join that got no Connect tap while an earlier screen was showing (before a rotation): show its text here. + pendingByHand?.let { b -> pendingByHand = null; if (!ImportJob.snapshot.busy) applyByHand(b) } + } + override fun onPause() { + if (shownScreen === this) shownScreen = null + ImportJob.remove(listener) + super.onPause() + } + + /** Back cancels an import in progress, as Cancel does; otherwise it leaves. Two ways, as elsewhere in the app. */ + private fun back() { if (ImportJob.snapshot.busy) ImportJob.cancel() else finish() } + + override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean { + if (Build.VERSION.SDK_INT < 33 && keyCode == android.view.KeyEvent.KEYCODE_BACK) { back(); return true } + return super.onKeyDown(keyCode, event) + } + + private fun render() { + val s = ImportJob.snapshot + ImportJob.question?.let { q -> if (q !== asked) { asked = q; ask(q) } } + if (s.phase == ImportJob.Phase.RECEIVING && shownPhase == ImportJob.Phase.RECEIVING) return updateProgress(s) + shownPhase = s.phase + body.removeAllViews() + // "Imported" only while that copy is still on this phone: it may have been removed, expired or replaced since. + val done = s.phase == ImportJob.Phase.DONE && s.storeId != null && ImportJob.currentCopy(this)?.storeId == s.storeId + when { + // A phone serving its own store can't import one (Appendix E.1; screen 4b). + !s.busy && !done && ServerStatus.url != null -> { + body.addView(card(heading("Can't import a store here"), + text("This phone is serving a store. To import a copy: stop serving it, in Manage server, or import on another phone."))) + body.addView(button("OK") { finish() }.help("import.cant")) + } + s.busy -> showProgress(s) + done -> showDone(s) + else -> showForm(s) + } + } + + // ---- screen 5: the code and the phone's name ---- + private fun showForm(s: ImportJob.Snapshot) { + val code = EditText(this).apply { + hint = "LS-XXXX-XXXX"; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS + setText(linkCode?.let { ShareCodes.display(it) } ?: ""); textSize = 22f; typeface = Typeface.MONOSPACE + } + val name = EditText(this).apply { setText(defaultPhoneName()); inputType = InputType.TYPE_CLASS_TEXT; filters = arrayOf(android.text.InputFilter.LengthFilter(40)) } + nameField = name + val error = when (s.phase) { + ImportJob.Phase.FAILED, ImportJob.Phase.DENIED, ImportJob.Phase.CANCELLED -> + // A heard code whose import failed: the owner may be on a network this phone isn't on. + if (heard && heardNetwork != null && s.phase == ImportJob.Phase.FAILED) "${s.message}\n\n$heardNetwork" else s.message + else -> null + } + body.addView(card( + heading("Import a store").help("import.code"), + text(when { + heard -> "The code was heard from the owner's phone." + linkAddress != null -> "The code from the owner's QR code is filled in." + else -> "Scan the owner's QR code with this phone's camera, type the code shown on their phone, or tap Listen while their phone plays it." + }), + label("Code").help("import.code"), code, + label("Your phone's name").help("import.name"), name, + text("The owner sees this when you ask for a copy. It starts as your phone's own name.", 13f), + text("Both phones must be on the same Wi-Fi network or hotspot.", 13f), + *(if (error != null) arrayOf(text(error, 15f).apply { setTextColor(pal.danger) }) else emptyArray()), + )) + // Listen: one tap listens for the owner's Play sound; three quick taps run the one-phone self-test. + body.addView(button(if (soundListener != null || testPlayer != null) "Stop listening" else "Listen") { listenTapped() } + .help("import.listen").also { listenButton = it }) + body.addView(text(listenMessage, 14f).also { listenStatus = it; it.visibility = if (listenMessage.isEmpty()) View.GONE else View.VISIBLE }) + // While listening: the seconds left, and a meter of how loud the microphone hears things. Hidden otherwise. + body.addView(text("", 15f).also { countdownText = it }) + body.addView(ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { + max = 100; contentDescription = "Microphone level" + }.also { meter = it }) + body.addView(text("", 13f).also { meterText = it }) + showLevel(if (soundListener != null) lastLevel else null) + // A transfer that failed partway can be tried again, with the same exchange, while the owner's share is open. + if (s.canRetry) body.addView(button("Try again") { ImportJob.retry(this) }.help("import.retry")) + body.addView(button(if (s.canRetry) "Start over" else "Continue") { + val normalized = ShareCodes.normalize(code.text.toString()) + if (normalized == null) { code.error = "That isn't a share code: LS, then two groups of four letters and digits."; return@button } + val address = if (normalized == linkCode) linkAddress else null + ImportJob.start(this, normalized, name.text.toString(), address) + }.help("import.continue")) + } + + /** The phone's own name, at most 40 characters: the companion's [defaultPhoneName], which import_start uses too. */ + private fun defaultPhoneName(): String = defaultPhoneName(this) + + // ---- Listen ---- + /** One tap listens, after a short wait in case more follow; three quick taps run the self-test. A tap while listening stops. */ + private fun listenTapped() { + if (soundListener != null || testPlayer != null) { + stopListening("Stopped.") + SoundLog.write(this, SoundLog.stopped()) + return + } + taps++ + ui.removeCallbacks(tapDone) + if (taps >= 3) tapDone.run() else ui.postDelayed(tapDone, TAP_MS) + } + + private fun toggleListen() = withMicrophone { startListening(null) } + + /** Runs [action] once the app may use the microphone, asking first if needed. */ + private fun withMicrophone(action: () -> Unit) { + if (SoundIo.canListen(this)) { action(); return } + afterPermission = action + requestPermissions(arrayOf(android.Manifest.permission.RECORD_AUDIO), REQUEST_MIC) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode != REQUEST_MIC) return + val then = afterPermission; afterPermission = null + if (grantResults.firstOrNull() == android.content.pm.PackageManager.PERMISSION_GRANTED) then?.invoke() + else { + setListenMessage("Without the microphone, the app can't hear the code. Scan the owner's QR code, or type the code, instead.") + SoundLog.write(this, SoundLog.microphoneRefused()) + } + } + + /** Listens for the owner's tones; with [test], for this phone's own self-test tones instead. */ + private fun startListening(test: SoundPayload?) { + if (ImportJob.snapshot.busy || soundListener != null) return + val run = ++listenRun + val doing = if (test != null) "Self-test: playing and listening on this phone…" else "Listening… Ask the owner to tap Play sound." + setListenMessage(doing) + var strongest = 0.0 + lastLevel = null + soundListener = SoundIo.Listener(this, + level = { v -> + strongest = maxOf(strongest, v.signal) + if (run == listenRun) { lastLevel = v; setListenMessage("$doing\n${signal(v.signal)}"); showLevel(v) } + }, + heard = { p, how -> if (run == listenRun) { endListening(); heardCode(p, how, test) } }, + ended = { end, why -> + if (run == listenRun) { + endListening(); setListenMessage(endMessage(end, why, test != null)) + SoundLog.write(this, when { + test != null -> SoundLog.selfTest(false, if (end == SoundIo.End.NOTHING_HEARD) SoundLog.nothingHeard(SoundIo.WINDOW_MS / 1000, strongest) else why) + end == SoundIo.End.NOTHING_HEARD -> SoundLog.nothingHeard(SoundIo.WINDOW_MS / 1000, strongest) + else -> SoundLog.listenFailed(why) + }) + } + }, + ).start() + listenButton?.text = "Stop listening" + } + + private fun signal(v: Double) = when { + v < 0.15 -> "Nothing heard yet." + v < SoundDecoder.THRESHOLD -> "Hearing something faint: hold the phones closer." + else -> "Hearing the tones." + } + + private fun endMessage(end: SoundIo.End, why: String, test: Boolean) = when (end) { + SoundIo.End.NOTHING_HEARD -> if (test) "Self-test failed: this phone didn't hear its own tones. Turn the media volume up and try again." + else "Didn't hear the code. Hold the phones closer, ask the owner to turn up the media volume, and try again." + else -> why + } + + /** The listener finished by itself: tidy up, and stop the self-test's tones. */ + private fun endListening() { + soundListener = null + testPlayer?.stop(); testPlayer = null + listenButton?.text = "Listen" + lastLevel = null + showLevel(null) + } + + /** + * The countdown and the microphone meter while listening; hidden with null. The meter shows the loudest moment + * since the last report, from SoundDsp.METER_FLOOR_DB (empty) to full scale (full). + */ + private fun showLevel(v: SoundIo.Level?) { + val visible = if (v != null) View.VISIBLE else View.GONE + countdownText?.visibility = visible + meter?.visibility = visible + meterText?.visibility = visible + if (v == null) return + val seconds = (v.msLeft + 999) / 1000 + countdownText?.text = "Listening for ${if (seconds == 1L) "1 more second" else "$seconds more seconds"}" + meter?.progress = SoundDsp.meterPercent(v.db) + meterText?.text = "Microphone level: ${String.format(java.util.Locale.ROOT, "%.0f", v.db)} dB" + + if (v.db <= SoundDsp.METER_FLOOR_DB) " (silent)" else "" + } + + /** Stops listening, and the self-test's tones, at once; [message] replaces the line under Listen. */ + private fun stopListening(message: String) { + listenRun++ + soundListener?.stop() + endListening() + setListenMessage(message) + } + + private fun setListenMessage(t: String) { + listenMessage = t + listenStatus?.let { it.text = t; it.visibility = if (t.isEmpty()) View.GONE else View.VISIBLE } + } + + /** A code was heard: the self-test compares it; otherwise the import starts at once, as if Continue were tapped. */ + private fun heardCode(p: SoundPayload, how: String, test: SoundPayload?) { + if (test != null) { + val passed = p == test + setListenMessage(if (passed) "Self-test passed: this phone heard its own tones ($how)." + else "Self-test: heard a different code, so the tones came from another phone.") + SoundLog.write(this, SoundLog.selfTest(passed, if (passed) how else "heard a different code, from another phone")) + return + } + SoundLog.write(this, SoundLog.heard(p, how)) // never the password + heard = true + linkCode = p.code + linkAddress = p.address?.let { InetSocketAddress(it, p.port) } + heardNetwork = when { + p.ssid == null -> null + p.password != null -> "The owner's phone serves on its own hotspot, ${p.ssid}, password ${p.password}. Join it in Wi-Fi settings, then tap Continue." + else -> "The owner's phone is on the Wi-Fi network ${p.ssid}. Join it, then tap Continue." + } + setListenMessage("Heard the code. Checking the network…") + val name = nameField?.text?.toString()?.takeIf { it.isNotBlank() } ?: defaultPhoneName() + val code = p.code + val address = linkAddress + val run = ++joinRun + // First the phone's current Wi-Fi, for about 2 s (WifiJoin.REACH_MS), off the main thread. + kotlin.concurrent.thread(name = "sound-reach") { + val ok = WifiJoin.reachable(applicationContext, code, address) + ui.post { if (run == joinRun && !isDestroyed) afterReach(p, name, ok) } + } + } + + /** Counts heard codes, so a late answer about an older one is ignored. */ + private var joinRun = 0 + + /** + * After the reachability check: start the import on the current Wi-Fi; or join the owner's own hotspot first + * (Android 10+, the person taps Connect); or, on Android 9 or with no tap in 30 s, show its name and password + * so the person joins by hand, then taps Continue. On other Wi-Fi the tones carry no password: the import + * starts, and if it fails, the form says which network to join. + */ + private fun afterReach(p: SoundPayload, name: String, reachable: Boolean) { + val ssid = p.ssid + val password = p.password + if (reachable || ssid == null || password == null) { + setListenMessage("Heard the code.") + ImportJob.start(this, p.code, name, linkAddress) + return + } + if (!WifiJoin.canJoin) { + SoundLog.write(this, "the owner's hotspot $ssid must be joined by hand (Android 9)") + setListenMessage(heardNetwork.orEmpty()) + render() + return + } + SoundLog.write(this, "joining the owner's hotspot $ssid") + setListenMessage("Joining the owner's hotspot, $ssid. Tap Connect when Android asks.") + val run = joinRun + // The join outlives a rotation: the import starts with the app's context, and the new screen shows it, + // since ImportJob's listeners redraw it. Leaving the screen for good, or a newer heard code, releases the + // join first (WifiJoin.release), so this answer never comes then. + val app = applicationContext + val address = linkAddress + val byHand = heardNetwork.orEmpty() + WifiJoin.join(this, ssid, password) { network -> + val shown = run == joinRun && !isDestroyed + if (network != null) { + SoundLog.write(app, "joined the owner's hotspot $ssid") + if (shown) setListenMessage("Joined the owner's hotspot.") + ImportJob.start(app, p.code, name, address, network) + WifiJoin.holdUntilImportEnds() // after start: the import is busy by now + } else { + SoundLog.write(app, "didn't join the owner's hotspot $ssid: no Connect tap within ${WifiJoin.CONNECT_TAP_MS / 1000} s, or refused") + // After a rotation this screen is gone: the new one shows the join-by-hand text, with the code filled in. + val b = ByHand(p.code, address, byHand) + if (shown) applyByHand(b) else deliverByHand(b) + } + } + } + + /** What the form needs to show the join-by-hand text for a heard code: the code, the owner's address, and the text. */ + class ByHand(val code: String, val address: InetSocketAddress?, val text: String) + + /** Shows the join-by-hand text on this screen, with the heard code filled in, so the person joins, then taps Continue. */ + private fun applyByHand(b: ByHand) { + heard = true + linkCode = b.code + linkAddress = b.address + heardNetwork = b.text + setListenMessage(b.text) + render() + } + + /** + * The screen that asked is gone (a rotation): the screen showing now gets the join-by-hand text, or, if none is + * showing yet, the next one to resume does. + */ + private fun deliverByHand(b: ByHand) { + val now = shownScreen + if (now != null && !now.isDestroyed) now.applyByHand(b) else pendingByHand = b + } + + /** Triple tap: this phone plays a made-up own-hotspot payload and listens to itself, to test the sound path with one phone. */ + private fun selfTest() = withMicrophone { + if (ImportJob.snapshot.busy || soundListener != null) return@withMicrophone + val code = ShareCodes.normalize(ShareCodes.newCode()) ?: return@withMicrophone + val address = java.net.InetAddress.getByAddress(byteArrayOf(192.toByte(), 168.toByte(), 49, 1)) as java.net.Inet4Address + val test = SoundPayload(code, address, 6175, true, "DIRECT-LS-TEST", "selftest-password") + if (SoundIo.volumeLow(this)) android.widget.Toast.makeText(this, "The media volume is low: turn it up for the self-test.", android.widget.Toast.LENGTH_LONG).show() + startListening(test) + val run = listenRun + // A moment for the microphone to start before the tones do. + ui.postDelayed({ + if (run == listenRun && soundListener != null) testPlayer = SoundIo.Player(test.encode(), { error -> + if (error != null && run == listenRun) stopListening(error) + }, null).start() + }, 300) + } + + /** Nothing listens or plays once the screen is left: Android would record silence anyway. */ + override fun onStop() { + ui.removeCallbacks(tapDone); taps = 0 + if (soundListener != null || testPlayer != null) { + stopListening("Stopped: the screen was left.") + SoundLog.write(this, SoundLog.stopped() + ": the screen was left") + } + super.onStop() + } + + /** + * Leaving the screen for good lets go of a joined hotspot, unless an import is still running on it (it carries on + * in the background, and WifiJoin lets go when it ends). A failed transfer kept for Try again is given up then. + */ + override fun onDestroy() { + joinRun++ // a join still being asked for answers no one + if (isFinishing && !isChangingConfigurations && !ImportJob.snapshot.busy) { + WifiJoin.release() + // A finished result (done, denied, cancelled, failed with no Try again) isn't shown on the next visit. + ImportJob.clearFinished() + } + super.onDestroy() + } + + // ---- screen 6: importing ---- + private fun showProgress(s: ImportJob.Snapshot) { + val step = when (s.phase) { ImportJob.Phase.FINDING, ImportJob.Phase.CONNECTING -> 1; ImportJob.Phase.WAITING -> 2; else -> 3 } + val views = mutableListOf(heading(s.storeName ?: "Importing a store")) + s.checkCode?.let { views += checkBox(it) } + views += stepLine(1, if (step > 1) "Found the store" else s.message, step) + views += stepLine(2, if (step > 2) "The owner allowed it" else if (step == 2) s.message else "The owner allows it", step) + views += stepLine(3, "Receiving the store", step) + if (step == 3) { + views += ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000 }.also { progress = it } + views += text("", 14f).also { progressText = it } + } + views += stepLine(4, "Ready to serve", step) + body.addView(card(*views.toTypedArray()).help("import.check")) + body.addView(text("Keep both phones close, with their screens on.", 13f)) + body.addView(button("Cancel") { ImportJob.cancel() }.help("import.cancel")) + if (step == 3) updateProgress(s) + } + + private fun updateProgress(s: ImportJob.Snapshot) { + val fraction = if (s.total > 0) (s.received * 1000 / s.total).toInt() else 0 + progress?.progress = fraction + progressText?.text = "${s.files} files · ${mb(s.received)} of ${mb(s.total)}" + } + + private fun mb(bytes: Long) = if (bytes < 1_000_000) "${(bytes + 999) / 1000} KB" else String.format("%.1f MB", bytes / 1_000_000.0) + + private fun stepLine(n: Int, label: String, current: Int) = TextView(this).apply { + text = (if (n < current) "✓ " else "$n ") + label + textSize = 16f; setTextColor(pal.ink) + setTypeface(typeface, if (n == current) Typeface.BOLD else Typeface.NORMAL) + alpha = if (n > current) 0.6f else 1f + } + + // ---- done ---- + private fun showDone(s: ImportJob.Snapshot) { + val expiry = s.expires?.let { "It expires on ${DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date.from(it))}." } ?: "It never expires." + body.addView(card(heading("Imported ${s.storeName}"), + text("${s.files} files · ${mb(s.total)}. $expiry"), + text("It's served as it was published, with your own PIN. It can't be changed or passed on.", 14f), + // Serving it on the owner's network would depend on the owner's phone. + // Checked now, not when the import ended: Wi-Fi may have been turned off or changed since. + *(if (ImportJob.onOwnersNetworkNow(this)) arrayOf(text("This phone is on the owner's network. To serve the store yourself, leave it first: " + + "join your own Wi-Fi, or turn Wi-Fi off, so this phone starts its own hotspot.", 14f).apply { setTextColor(pal.danger) }) else emptyArray()))) + body.addView(button("Serve it now") { + startForegroundService(android.content.Intent(this, HostService::class.java).setAction(HostService.ACTION_SERVE_COPY)) + startActivity(android.content.Intent(this, MainActivity::class.java).addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP)) + finish() + }.help("import.serve_now")) + body.addView(button("Done") { finish() }.help("import.done")) + } + + private fun ask(q: ImportJob.Question) { + AlertDialog.Builder(this).setTitle(q.title).setMessage(q.message).setCancelable(false) + .setPositiveButton("Replace") { _, _ -> q.answer(true) } + .setNegativeButton("Keep mine") { _, _ -> q.answer(false) } + .show() + } + + // ---- building blocks, in the app's style ---- + private fun card(vararg views: View) = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + val dp = resources.displayMetrics.density + background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(pal.panelTop, pal.cardBottom)).apply { + cornerRadius = 12 * dp; setStroke((1 * dp).toInt(), pal.stroke) + } + setPadding(pad, pad, pad, pad) + layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = pad } + views.forEach { v -> addView(v, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = pad / 2 }) } + } + + private fun heading(t: String) = TextView(this).apply { text = t; textSize = 20f; setTypeface(typeface, Typeface.BOLD); setTextColor(pal.ink) } + private fun label(t: String) = TextView(this).apply { text = t; textSize = 14f; setTypeface(typeface, Typeface.BOLD); setTextColor(pal.ink) } + private fun text(t: String, size: Float = 15f) = TextView(this).apply { text = t; textSize = size; setTextColor(pal.ink) } + private fun button(t: String, onClick: () -> Unit) = Button(this).apply { text = t; setOnClickListener { onClick() } } + + private fun checkBox(check: String) = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER + val dp = resources.displayMetrics.density + background = GradientDrawable().apply { setColor(pal.digits); cornerRadius = 10 * dp; setStroke((2 * dp).toInt(), pal.ink) } + setPadding(pad, pad / 2, pad, pad / 2) + addView(TextView(this@ImportActivity).apply { text = "Their screen should show"; textSize = 13f; gravity = Gravity.CENTER; setTextColor(pal.ink) }) + addView(TextView(this@ImportActivity).apply { + text = check.chunked(2).joinToString(" "); textSize = 34f; gravity = Gravity.CENTER; setTextColor(pal.ink) + setTypeface(typeface, Typeface.BOLD); letterSpacing = 0.15f + }) + } + + private val pal by lazy { Palette.of(this) } + + companion object { + /** Taps on Listen closer together than this count as one series: three run the self-test. */ + private const val TAP_MS = 400L + private const val REQUEST_MIC = 41 + private const val LOG_TAG = "ShareYourAppsSound" + /** The import screen in front, between onResume and onPause; null otherwise. Main thread only. */ + private var shownScreen: ImportActivity? = null + /** Join-by-hand text for a screen that isn't in front yet (after a rotation); the next one to resume shows it. */ + private var pendingByHand: ByHand? = null + + /** + * The name the owner sees when this phone asks for a copy: the phone's own name, or its model. At most 40 + * characters, as the import screen's field allows. Public so an MCP import (import_start) uses the same default. + */ + fun defaultPhoneName(context: android.content.Context): String = + ((if (Build.VERSION.SDK_INT >= 25) Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME) else null) + ?.takeIf { it.isNotBlank() } ?: Build.MODEL).take(40) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportJob.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportJob.kt new file mode 100644 index 000000000..0cd8715fa --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportJob.kt @@ -0,0 +1,218 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.os.Handler +import android.os.Looper +import java.io.File +import java.io.IOException +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread + +/** + * Importing a copy of someone else's store (design, Appendix E.2–E.3, E.6; screens 5 and 6), in the + * background, so rotating or leaving the import screen doesn't break it. Main process only; + * listeners run on the main thread. + * + * Copies are kept in the app's private storage, `files/imported//`, each with its + * description beside it, `.json`, for the store's name and expiry. A phone holds at most one. + */ +object ImportJob { + enum class Phase { IDLE, FINDING, CONNECTING, WAITING, RECEIVING, DONE, FAILED, DENIED, CANCELLED } + + class Snapshot( + val phase: Phase, val message: String = "", val checkCode: String? = null, val storeName: String? = null, + val received: Long = 0, val total: Long = 0, val files: Int = 0, val expires: java.time.Instant? = null, + /** A transfer that failed partway, which can be tried again while the owner's share is open. */ + val canRetry: Boolean = false, + /** Imported over the owner's own network: serving it there would depend on the owner's phone. */ + val onOwnersNetwork: Boolean = false, + /** Once DONE: the imported copy's store ID, so the screen can check the copy is still on this phone. */ + val storeId: String? = null, + ) { + val busy: Boolean get() = phase in setOf(Phase.FINDING, Phase.CONNECTING, Phase.WAITING, Phase.RECEIVING) + } + + /** A question for the seller before replacing a copy; the import waits for the answer. */ + class Question(val title: String, val message: String, val answer: (Boolean) -> Unit) + + private val main = Handler(Looper.getMainLooper()) + private val listeners = CopyOnWriteArrayList<() -> Unit>() + @Volatile var snapshot = Snapshot(Phase.IDLE); private set + @Volatile var question: Question? = null; private set + @Volatile private var client: ShareClient? = null + /** The allowed client kept after a failed transfer, for Try again; and where the owner is. */ + @Volatile private var retryClient: ShareClient? = null + @Volatile private var ownerAddress: java.net.InetAddress? = null + @Volatile private var lastCheck: String? = null + @Volatile private var cancelled = false + + fun observe(l: () -> Unit) { listeners += l; l() } + fun remove(l: () -> Unit) { listeners -= l } + private fun set(s: Snapshot) { snapshot = s; main.post { listeners.forEach { it() } } } + + fun importedDir(context: Context) = File(context.filesDir, "imported") + + /** The copy on this phone, if any: its description. */ + fun currentCopy(context: Context): SharePackage.Description? = CopyExpiry.copies(importedDir(context)).firstOrNull() + + /** Whether the current (or last) import was started by an MCP client, not a person on the import screen. */ + @Volatile var startedByMcp = false; private set + + /** + * Starts importing, from [address] if known — from a QR link or the owner's tones — or by searching for the code. + * [network]: the network to use, such as the owner's hotspot that WifiJoin joined; null uses the phone's Wi-Fi. + * [byMcp]: started by an MCP client, so replacing a different store needs no person; an older copy still does. + * Returns null once started, or why it didn't start: an import is already running, or Android refused the + * foreground service. Only an MCP start gives up then; a person's start runs on, as before. + * Synchronized: MCP calls this from its own threads, the import screen from the main thread. + */ + @Synchronized + fun start(context: Context, code: String, phoneName: String, address: InetSocketAddress?, + network: android.net.Network? = null, byMcp: Boolean = false): String? { + if (snapshot.busy) return "An import is already running." + val app = context.applicationContext + cancelled = false; retryClient = null; startedByMcp = byMcp + val before = snapshot + // Busy before the service starts: it stops itself as soon as it sees an import that isn't busy. + set(Snapshot(Phase.FINDING, "Looking for the phone showing that code…")) + // A foreground service, so Android doesn't freeze the import once the app leaves the screen. + if (!ImportService.start(app) && byMcp) { + set(before) + return "person needed: Android didn't let the import start in the background. Open Share Your Apps Server, then try again." + } + thread(name = "import") { + try { run(app, code, phoneName, address, network) } + catch (e: IOException) { failed(e) } + catch (e: Exception) { failed(IOException("The import failed: ${e.message}")) } + finally { client = null; question = null } + } + return null + } + + fun cancel() { cancelled = true; client?.cancel(); question?.answer?.invoke(false); retryClient = null } + + /** Tries a failed transfer again, with the same exchange, while the owner's share is still open. */ + fun retry(context: Context) { + val c = retryClient ?: return + if (snapshot.busy) return + val app = context.applicationContext + cancelled = false + set(Snapshot(Phase.RECEIVING, "Receiving", lastCheck)) + ImportService.start(app) + thread(name = "import") { + try { client = c; receive(app, c, lastCheck.orEmpty()) } + catch (e: IOException) { failed(e) } + catch (e: Exception) { failed(IOException("The import failed: ${e.message}")) } + finally { client = null; question = null } + } + } + + private fun failed(e: IOException) { + set(if (cancelled) Snapshot(Phase.CANCELLED, "Cancelled. Nothing was imported.") + else Snapshot(Phase.FAILED, e.message ?: "The import failed.", canRetry = retryClient != null)) + } + + /** The Wi-Fi network, which a network without internet — such as the owner's hotspot — isn't by default. */ + @Suppress("DEPRECATION") + private fun wifiNetwork(context: Context): android.net.Network? { + val cm = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return null + return cm.allNetworks.firstOrNull { cm.getNetworkCapabilities(it)?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_WIFI) == true } + } + + /** Whether this phone's Wi-Fi is the owner's own network: its gateway is the owner's phone. */ + private fun onOwnersNetwork(context: Context, wifi: android.net.Network): Boolean { + val owner = ownerAddress ?: return false + val cm = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return false + return cm.getLinkProperties(wifi)?.routes?.any { it.isDefaultRoute && it.gateway == owner } == true + } + + private fun run(context: Context, code: String, phoneName: String, known: InetSocketAddress?, joined: android.net.Network?) { + // Everything goes over Wi-Fi explicitly: a network without internet, such as the owner's hotspot, + // isn't Android's default, and requests would otherwise go to mobile data, and fail. A network WifiJoin + // joined (the owner's hotspot) comes first: it may not be the first Wi-Fi network Android lists. + val wifi = joined ?: wifiNetwork(context) ?: throw IOException("This phone isn't on Wi-Fi. Join the owner's Wi-Fi network or hotspot, then try again.") + val address = known ?: ShareDiscovery.find(code, bind = { wifi.bindSocket(it) }) + ?: throw IOException("Couldn't find a phone showing that code. Check both phones are on the same Wi-Fi network or hotspot, and that the code is still showing.") + if (cancelled) throw IOException("Cancelled.") + ownerAddress = address.address + set(Snapshot(Phase.CONNECTING, "Connecting to the owner's phone…")) + val c = ShareClient("http://${address.address.hostAddress}:${address.port}", code, phoneName, opener = { wifi.openConnection(it) }); client = c + val check = c.ask(); lastCheck = check + set(Snapshot(Phase.WAITING, "Waiting for the owner to allow it…", check)) + val deadline = System.currentTimeMillis() + ShareHost.CODE_LIFETIME_MS + while (true) { + if (cancelled) throw IOException("Cancelled.") + when (c.status()) { + "allowed" -> break + "denied" -> { set(Snapshot(Phase.DENIED, "The owner denied the request. Nothing was imported.")); return } + "expired" -> throw IOException("The code expired before the owner allowed it. Ask for a new one.") + } + if (System.currentTimeMillis() > deadline) throw IOException("The owner didn't answer in time. Ask for a new code.") + Thread.sleep(1000) + } + // Allowed: from now on, a failed transfer can be tried again with this exchange. + retryClient = c + receive(context, c, check) + } + + private fun receive(context: Context, c: ShareClient, check: String) { + if (c.status() != "allowed") throw IOException("The owner's share has ended. Ask them to share again.") + val dir = importedDir(context) + var described: SharePackage.Description? = null + val (desc, _) = c.download(dir, accept = { d -> described = d; confirmReplacing(context, d) }) { written, total -> + set(Snapshot(Phase.RECEIVING, "Receiving", check, described?.storeName, written, total, described?.files?.size ?: 0)) + } + // One copy per phone: this one, and its description beside it. + File(dir, "${desc.storeId}.json").writeText(desc.json.toString()) + dir.listFiles()?.filter { !it.name.startsWith(".") && it.name != desc.storeId && it.name != "${desc.storeId}.json" }?.forEach { it.deleteRecursively() } + // A fresh copy restarts the expiry clock at the current time (Appendix E.5): a clock once set too far + // ahead mustn't condemn it. An old expiry notice goes with the old copy. + ExpiryClock(CopyExpiry.clockFile(context.filesDir)).restart(System.currentTimeMillis()) + retryClient = null + val owners = wifiNetwork(context)?.let { onOwnersNetwork(context, it) } == true + set(Snapshot(Phase.DONE, "Imported", check, desc.storeName, desc.totalBytes, desc.totalBytes, desc.files.size, desc.expires, + onOwnersNetwork = owners, storeId = desc.storeId)) + } + + /** + * Forgets a finished import (done, denied, cancelled, or failed with no Try again), so the next visit to the import + * screen shows the empty form, not an old result. A failed transfer that can be tried again is kept, as is a busy one. + * Synchronized with [start], so an import an MCP client starts at the same moment is never wiped. + */ + @Synchronized + fun clearFinished() { + val s = snapshot + if (s.busy || s.phase == Phase.IDLE || s.canRetry) return + set(Snapshot(Phase.IDLE)) + } + + /** + * Whether this phone is on the owner's network now, not when the import ended: Wi-Fi may have been turned off or + * changed since. False with no Wi-Fi, or if no owner is known. + */ + fun onOwnersNetworkNow(context: Context): Boolean = + wifiNetwork(context.applicationContext)?.let { onOwnersNetwork(context.applicationContext, it) } == true + + /** Appendix E.6: a newer copy of the same store replaces it; an older one, or a different store, asks first. */ + private fun confirmReplacing(context: Context, incoming: SharePackage.Description) { + val current = currentCopy(context) ?: return + // An MCP import answers "Replace?" for a different store itself (decision 4); an older copy still asks a person. + if (startedByMcp && current.storeId != incoming.storeId) return + val q = when { + current.storeId != incoming.storeId -> "Replace ${current.storeName}?" to + "This phone has a copy of ${current.storeName}. Importing ${incoming.storeName} replaces it." + incoming.created < current.created -> "Import an older copy?" to + "This copy of ${incoming.storeName} is older than the one on this phone. Importing it replaces the newer one." + else -> return + } + val latch = CountDownLatch(1); var yes = false + question = Question(q.first, q.second) { a -> yes = a; latch.countDown() } + main.post { listeners.forEach { it() } } + latch.await(2, TimeUnit.MINUTES) + question = null + if (!yes) throw IOException(if (cancelled) "Cancelled." else "Not imported: the copy on this phone was kept.") + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportService.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportService.kt new file mode 100644 index 000000000..199a2d4fb --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ImportService.kt @@ -0,0 +1,118 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder + +/** + * Keeps an import running while the app is off the screen (design, Appendix E.2): a foreground + * service, so Android doesn't freeze or kill the process mid-transfer. It shows the import's progress + * in its notification, and stops itself once the import is no longer busy. The work itself is + * [ImportJob]'s; this only keeps the process alive. + */ +class ImportService : Service() { + private val listener: () -> Unit = { update() } + /** Observing ImportJob: once per service, though a retry or a second import starts it again while it runs. */ + private var observing = false + /** The question the heads-up notification shows, so it's posted once, not on every progress update. */ + private var shownQuestion: ImportJob.Question? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + // The notification's Cancel, as on the import screen. The service is already in the foreground then, + // or there's nothing left to cancel and it stops. + if (intent?.action == ACTION_CANCEL) { + ImportJob.cancel() + if (!observing) stopSelf() + return START_NOT_STICKY + } + val n = notification("Importing a store…", null) + if (Build.VERSION.SDK_INT >= 29) startForeground(NOTIFICATION, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + else startForeground(NOTIFICATION, n) + if (!observing) { observing = true; ImportJob.observe(listener) } else update() + return START_NOT_STICKY + } + + private fun update() { + val s = ImportJob.snapshot + // Only an MCP import's question: a person importing is on the import screen, which asks it. + showQuestion(ImportJob.question?.takeIf { ImportJob.startedByMcp && s.busy }) + if (!s.busy) { stopSelf(); return } + val text = when (s.phase) { + ImportJob.Phase.WAITING -> "Waiting for the owner to allow it…" + ImportJob.Phase.RECEIVING -> if (s.total > 0) "Receiving ${s.storeName ?: "the store"}: ${s.received * 100 / s.total}%" else "Receiving…" + else -> "Importing a store…" + } + getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION, notification(text, s.storeName)) + } + + override fun onDestroy() { + ImportJob.remove(listener); observing = false + showQuestion(null) + super.onDestroy() + } + + /** [store]: the store's name, once known (it arrives when receiving starts), for the title. */ + private fun notification(text: String, store: String?): Notification { + val nm = getSystemService(NotificationManager::class.java) + if (nm?.getNotificationChannel(CHANNEL) == null) + nm?.createNotificationChannel(NotificationChannel(CHANNEL, "Importing a store", NotificationManager.IMPORTANCE_LOW)) + val open = PendingIntent.getActivity(this, 1, Intent(this, ImportActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val cancel = PendingIntent.getService(this, 2, Intent(this, ImportService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE) + return Notification.Builder(this, CHANNEL) + .setSmallIcon(android.R.drawable.stat_sys_download) + .setContentTitle(store?.let { "Importing $it" } ?: "Share Your Apps Server") + .setContentText(text) + .setContentIntent(open) + .addAction(Notification.Action.Builder(null, "Cancel", cancel).build()) + .setOngoing(true) + .build() + } + + /** + * An MCP import's question (an older copy replacing a newer one), which no screen may be showing: a heads-up + * notification that opens the import screen, which asks it. Null removes it. The import waits 2 minutes. + */ + private fun showQuestion(q: ImportJob.Question?) { + val nm = getSystemService(NotificationManager::class.java) ?: return + if (q == null) { shownQuestion = null; nm.cancel(QUESTION_TAG, NOTIFICATION); return } + if (q === shownQuestion) return + shownQuestion = q + if (nm.getNotificationChannel(QUESTION_CHANNEL) == null) + nm.createNotificationChannel(NotificationChannel(QUESTION_CHANNEL, "Import questions", NotificationManager.IMPORTANCE_HIGH).apply { + description = "When an import started by an MCP client needs a person: replacing a newer copy with an older one." + }) + val open = PendingIntent.getActivity(this, 3, Intent(this, ImportActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val text = "${q.message} Tap to answer within 2 minutes." + nm.notify(QUESTION_TAG, NOTIFICATION, Notification.Builder(this, QUESTION_CHANNEL) + .setSmallIcon(android.R.drawable.stat_sys_warning) + .setContentTitle(q.title) + .setContentText(text) + .setStyle(Notification.BigTextStyle().bigText(text)) + .setContentIntent(open) + .setAutoCancel(true) + .build()) + } + + companion object { + private const val CHANNEL = "import" + private const val NOTIFICATION = 2 + /** High importance, for a heads-up; the "import" channel is low, and a channel's importance can't be raised. */ + private const val QUESTION_CHANNEL = "import_question" + /** With [NOTIFICATION]: a tag keeps it apart from the progress notification, and from other ids in the app. */ + private const val QUESTION_TAG = "question" + const val ACTION_CANCEL = "org.appdevforall.shareyourapps.server.IMPORT_CANCEL" + + /** Whether Android let the service start: it refuses foreground starts while the app is in the background. */ + fun start(context: Context): Boolean = + try { context.startForegroundService(Intent(context, ImportService::class.java)) != null } catch (e: Exception) { false } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Interfaces.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Interfaces.kt new file mode 100644 index 000000000..82a7d7e36 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Interfaces.kt @@ -0,0 +1,53 @@ +package org.appdevforall.shareyourapps.server + +import java.net.Inet4Address +import java.net.InetAddress +import java.net.NetworkInterface + +/** A network interface reduced to what address selection needs, so it can be tested off-device. */ +data class Iface(val name: String, val up: Boolean, val loopback: Boolean, val addresses: List) + +/** + * The external address to bind: the Wi-Fi interface's IPv4 address, preferring interfaces + * named `wlan*`, otherwise any other up, non-loopback interface with a private IPv4 address. + * (Hotspot interfaces come later; this is the LAN case.) + */ +fun pickExternalAddress(ifaces: List): InetAddress? { + fun v4(i: Iface) = i.addresses.firstOrNull { it is Inet4Address && it.isSiteLocalAddress } + val usable = ifaces.filter { it.up && !it.loopback } + return usable.filter { it.name.startsWith("wlan") }.firstNotNullOfOrNull(::v4) + ?: usable.firstNotNullOfOrNull(::v4) +} + +fun systemInterfaces(): List = + NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().map { + Iface(it.name, it.isUp, it.isLoopback, it.inetAddresses.toList()) + } + +/** Mobile data, VPN and tunnel interfaces: buyers can never reach the phone through these. */ +private val UNREACHABLE = listOf("rmnet", "ccmni", "pdp", "tun", "v4-", "clat", "dummy", "ipsec", "lo") + +private fun privateV4(i: Iface) = i.addresses.firstOrNull { it is Inet4Address && it.isSiteLocalAddress } + +/** By Android convention, a phone's own Wi-Fi connection is always this interface. */ +const val WIFI_CLIENT = "wlan0" + +/** The joined Wi-Fi network's address: a private IPv4 address on [WIFI_CLIENT]. */ +fun pickWifiAddress(ifaces: List): InetAddress? = + ifaces.filter { it.up && !it.loopback && it.name == WIFI_CLIENT }.firstNotNullOfOrNull(::privateV4) + +/** + * Interfaces that phones use for their own Mobile hotspot: `swlan0` on Samsung, `ap0` or + * `softap0` on many others, and `wlan1` and up where the hotspot shares Wi-Fi's naming. Android + * has no public way for apps to ask whether the Mobile hotspot is on, so it's recognized by name. + * USB (`rndis`, `usb`, `ncm`) and Bluetooth (`bt-pan`) tethering are left out: buyers aren't on those. + */ +private val PHONE_HOTSPOT = Regex("""^(swlan|softap|ap)\d+$|^wlan[1-9]\d*$""") + +/** The address of the phone's own Mobile hotspot, turned on in Settings, if it's on. */ +fun pickPhoneHotspotAddress(ifaces: List): InetAddress? = + ifaces.filter { it.up && !it.loopback && PHONE_HOTSPOT.matches(it.name) }.firstNotNullOfOrNull(::privateV4) + +/** The address of a hotspot the phone is hosting: a private IPv4 address on any interface buyers could reach. */ +fun pickHotspotAddress(ifaces: List): InetAddress? = + ifaces.filter { i -> i.up && !i.loopback && UNREACHABLE.none { i.name.startsWith(it) } }.firstNotNullOfOrNull(::privateV4) diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LaunchActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LaunchActivity.kt new file mode 100644 index 000000000..f7c2692bb --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LaunchActivity.kt @@ -0,0 +1,120 @@ +package org.appdevforall.shareyourapps.server + +import android.Manifest +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.os.Handler +import android.os.Looper + +/** + * The plugin's way in. CodeOnTheGo launches this with startActivityForResult, passing the + * Store directory's name, a token, the PIN and the store name ([LaunchContract]). It checks the + * caller, asks HostService to restart the server on that directory, waits until the new server + * has bound its socket, and returns the port — or an error — then finishes, so the owner + * stays in CodeOnTheGo. It has no UI of its own. + * + * On a fresh install the server has no storage access yet, so this asks for it first — the + * All-files access screen on Android 11+, the permission dialog on 9 and 10 — and carries on + * with the publish once it's granted. + */ +class LaunchActivity : Activity() { + + companion object { + private const val TIMEOUT_MS = 20_000L + } + + private val main = Handler(Looper.getMainLooper()) + private var done = false + private var dir = "" + /** Sent to the All-files access screen; checked again when the owner comes back. */ + private var awayForAccess = false + private var sentForAccess = false + private val onResult: (Int, String?) -> Unit = { port, error -> reply(port, error) } + private val timeout = Runnable { reply(0, "the server didn't start in time") } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // getCallingPackage() is only set for startActivityForResult, and it comes from the + // system, not from the sender — so another app can't claim to be CodeOnTheGo. + if (callingPackage != LaunchContract.CALLER) return reply(0, "not launched by CodeOnTheGo", unchanged = true) + dir = intent.getStringExtra(LaunchContract.EXTRA_DIR).orEmpty() + if (!Store.validName(dir)) return reply(0, "\"$dir\" isn't a Store directory name", unchanged = true) + if (Store.hasStorageAccess(this)) accessDecided() else askForAccess() + } + + private fun askForAccess() { + if (Build.VERSION.SDK_INT >= 30) { + sentForAccess = true + startActivity(Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName"))) + } else { + requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1) + } + } + + override fun onPause() { + super.onPause() + if (sentForAccess) awayForAccess = true + } + + override fun onResume() { + super.onResume() + // Only after actually leaving for the settings screen and coming back. + if (!awayForAccess) return + awayForAccess = false + sentForAccess = false + accessDecided() + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + // 1 = storage access (Android 9 and 10); 2 = the hotspot permission. A denied hotspot + // permission still proceeds: the service reports it clearly. + if (requestCode == 1) accessDecided() else proceed() + } + + private fun accessDecided() { + if (!Store.hasStorageAccess(this)) return reply(0, "Storage access wasn't granted to Share Your Apps Server, so it can't serve the store.", unchanged = true) + // Not on Wi-Fi: a hotspot will be needed, and starting one needs a permission. + if (Store.needsHotspot() && !Store.hasHotspotPermission(this)) requestPermissions(Store.hotspotPermissions(), 2) + else proceed() + } + + /** Restarts the server on the directory and waits for its answer. */ + private fun proceed() { + LaunchResult.await(onResult) + main.postDelayed(timeout, TIMEOUT_MS) + startForegroundService( + Intent(this, HostService::class.java) + .setAction(HostService.ACTION_START) + .putExtra(HostService.EXTRA_FROM_PLUGIN, true) + .putExtra(HostService.EXTRA_DIR, dir) + .putExtra(LaunchContract.EXTRA_TOKEN, intent.getStringExtra(LaunchContract.EXTRA_TOKEN)) + .putExtra(LaunchContract.EXTRA_PIN, intent.getStringExtra(LaunchContract.EXTRA_PIN)) + .putExtra(LaunchContract.EXTRA_STORE_NAME, intent.getStringExtra(LaunchContract.EXTRA_STORE_NAME)) + ) + } + + override fun onDestroy() { + LaunchResult.cancel(onResult) + main.removeCallbacks(timeout) + super.onDestroy() + } + + /** [unchanged]: the failure came before anything was stopped, so what was being served still is. */ + private fun reply(port: Int, error: String?, unchanged: Boolean = false) { + if (done) return + done = true + main.removeCallbacks(timeout) + LaunchResult.cancel(onResult) + if (error == null) { + setResult(RESULT_OK, Intent().putExtra(LaunchContract.RESULT_PORT, port)) + } else { + setResult(RESULT_CANCELED, Intent().putExtra(LaunchContract.RESULT_ERROR, error).putExtra(LaunchContract.RESULT_UNCHANGED, unchanged)) + } + finish() + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogActivity.kt new file mode 100644 index 000000000..137efe0e2 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogActivity.kt @@ -0,0 +1,204 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Activity +import android.content.Context +import android.graphics.Color +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.text.Editable +import android.text.TextWatcher +import android.util.TypedValue +import android.view.Gravity +import android.view.MotionEvent +import android.view.ScaleGestureDetector +import android.widget.Button +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import java.io.File +import kotlin.concurrent.thread + +/** + * The full access log, per the wireframe (FullScreenLogView): one chip per file (Current, then + * older ones by age), search, All/Requests/Status filters, pinch to zoom, pan in both directions, + * and Share to send the chosen file off the phone. Newest lines first. To stay smooth it shows at + * most the newest [CAP] matching lines, and says so; search always covers the whole file. + */ +class LogActivity : Activity() { + + companion object { private const val CAP = 2000 } + + private val main = Handler(Looper.getMainLooper()) + private val pal by lazy { Palette.of(this) } + private val accent by lazy { pal.link } + private lateinit var files: List + private var selected = 0 + private var kind = LogFilter.Kind.ALL + private var query = "" + private var lines: List = emptyList() + + private lateinit var summary: TextView + private lateinit var note: TextView + private lateinit var body: TextView + private lateinit var fileChips: LinearLayout + private lateinit var kindChips: LinearLayout + private val applySoon = Runnable { applyFilter() } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + title = "Access log" + val dp = resources.displayMetrics.density + val pad = (12 * dp).toInt() + files = LogProvider.files(this) + + val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(pad, pad, pad, 0) } + summary = TextView(this).apply { textSize = 13f; layoutParams = LinearLayout.LayoutParams(0, -2, 1f) } + root.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL + addView(summary) + addView(Button(this@LogActivity).apply { + text = "Share"; isAllCaps = false + setOnClickListener { files.getOrNull(selected)?.let { LogProvider.share(this@LogActivity, listOf(it.name)) } } + }) + }) + + fileChips = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL } + root.addView(HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(fileChips) }) + + val search = EditText(this).apply { + hint = "Search"; setSingleLine(); layoutParams = LinearLayout.LayoutParams(0, -2, 1f) + addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun afterTextChanged(s: Editable?) { query = s?.toString().orEmpty(); main.removeCallbacks(applySoon); main.postDelayed(applySoon, 250) } + }) + } + root.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL + addView(search) + addView(Button(this@LogActivity).apply { text = "✕"; setOnClickListener { search.setText("") } }) + }) + + kindChips = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL } + root.addView(kindChips) + note = TextView(this).apply { textSize = 12f; alpha = 0.7f } + root.addView(note) + + body = TextView(this).apply { + typeface = Typeface.MONOSPACE; textSize = 11f; setTextIsSelectable(true); setPadding(0, pad / 2, pad, pad) + } + // Pan in both directions; pinch to zoom the text. + val panes = ScrollView(this).apply { addView(HorizontalScrollView(this@LogActivity).apply { addView(body) }) } + root.addView(ZoomFrame(this, body).apply { addView(panes) }, LinearLayout.LayoutParams(-1, 0, 1f)) + root.addView(TextView(this).apply { text = "Pinch to zoom · swipe to pan"; textSize = 11f; alpha = 0.6f; gravity = Gravity.CENTER; setPadding(0, 4, 0, pad / 2) }) + setContentView(root) + SystemBars.fit(root) + + renderChips() + load(0) + } + + private fun renderChips() { + fileChips.removeAllViews() + if (files.isEmpty()) fileChips.addView(TextView(this).apply { text = "No log files yet." }) + val now = System.currentTimeMillis() + files.forEachIndexed { i, f -> fileChips.addView(chip(LogFilter.ageLabel(i, f.lastModified(), now), i == selected) { load(i) }) } + kindChips.removeAllViews() + listOf(LogFilter.Kind.ALL to "All", LogFilter.Kind.REQUESTS to "Requests", LogFilter.Kind.STATUS to "Status").forEach { (k, label) -> + kindChips.addView(chip(label, k == kind) { kind = k; renderChips(); applyFilter() }) + } + } + + private fun chip(label: String, on: Boolean, onClick: () -> Unit) = Button(this).apply { + text = label; isAllCaps = false; textSize = 13f; stateListAnimator = null + val dp = resources.displayMetrics.density + background = GradientDrawable().apply { + cornerRadius = 16 * dp; setColor(if (on) accent else pal.panelTop); setStroke((1 * dp).toInt(), accent) + } + setTextColor(if (on) pal.onLink else accent) + minHeight = 0; minimumHeight = 0; setPadding((14 * dp).toInt(), (6 * dp).toInt(), (14 * dp).toInt(), (6 * dp).toInt()) + layoutParams = LinearLayout.LayoutParams(-2, -2).apply { marginEnd = (8 * dp).toInt(); topMargin = (4 * dp).toInt(); bottomMargin = (4 * dp).toInt() } + setOnClickListener { onClick() } + } + + /** Reads a file in the background; tapping the current chip again reloads it. */ + private fun load(i: Int) { + selected = i + renderChips() + val f = files.getOrNull(i) ?: run { summary.text = "Access log"; body.text = ""; return } + summary.text = "Loading…" + thread(name = "read-log") { + val read = try { f.readLines() } catch (e: Exception) { listOf("[this file couldn't be read: ${e.message}]") } + main.post { + if (selected != i) return@post + lines = read + summary.text = "${read.count { it.isNotEmpty() }} lines · ${sizeLabel(f.length())}" + applyFilter() + } + } + } + + private fun applyFilter() { + val snapshot = lines; val k = kind; val q = query + thread(name = "filter-log") { + val r = LogFilter.apply(snapshot, k, q, CAP) + main.post { + if (snapshot !== lines || k != kind || q != query) return@post // superseded + body.text = r.lines.joinToString("\n") + note.text = when { + r.matches == 0 -> "No matching lines." + r.matches > r.lines.size -> "Showing the newest ${r.lines.size} of ${r.matches} matching lines. Search to narrow it down." + else -> "${r.matches} matching lines, newest first." + } + } + } + } + + private fun sizeLabel(b: Long) = when { + b < 1024 -> "$b B" + b < 1024 * 1024 -> String.format("%.1f KB", b / 1024.0) + else -> String.format("%.1f MB", b / (1024.0 * 1024)) + } +} + +/** Passes pinches to a zoom on [text] while leaving scrolling to the views inside. */ +private class ZoomFrame(ctx: Context, private val text: TextView) : FrameLayout(ctx) { + // Zoom in pixels, within limits of 6 sp and 28 sp converted once: TypedValue respects the + // phone's font scale, including Android 14's nonlinear scaling. + private val minPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 6f, ctx.resources.displayMetrics) + private val maxPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 28f, ctx.resources.displayMetrics) + private val zoom = ScaleGestureDetector(ctx, object : ScaleGestureDetector.SimpleOnScaleGestureListener() { + override fun onScale(d: ScaleGestureDetector): Boolean { + text.setTextSize(TypedValue.COMPLEX_UNIT_PX, (text.textSize * d.scaleFactor).coerceIn(minPx, maxPx)) + return true + } + }) + + private var pinching = false + + override fun dispatchTouchEvent(ev: MotionEvent): Boolean { + zoom.onTouchEvent(ev) + if (zoom.isInProgress) { + // A pinch has started: tell the scroll views to let go once, then keep it to ourselves. + if (!pinching) { + pinching = true + val cancel = MotionEvent.obtain(ev).apply { action = MotionEvent.ACTION_CANCEL } + super.dispatchTouchEvent(cancel) + cancel.recycle() + } + return true + } + if (ev.actionMasked == MotionEvent.ACTION_UP || ev.actionMasked == MotionEvent.ACTION_CANCEL) { + val wasPinching = pinching + pinching = false + if (wasPinching) return true + } + return if (pinching) true else super.dispatchTouchEvent(ev) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogFilter.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogFilter.kt new file mode 100644 index 000000000..22b98c0ba --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogFilter.kt @@ -0,0 +1,47 @@ +package org.appdevforall.shareyourapps.server + +/** The full-screen log view's search and filters, kept apart from the screen so they can be tested. */ +object LogFilter { + + enum class Kind { ALL, REQUESTS, STATUS } + + /** + * Status lines are the server's own, written by [StoreLog.status]: a timestamp in brackets, then a tag in + * brackets, e.g. `[03/Oct/2026:17:30:20 -0700] [server] …`. Request lines start with the buyer's address. + */ + private val STATUS = Regex("""^\[[^\]]+\] \[[A-Za-z0-9_-]+\]""") + + fun isStatus(line: String) = STATUS.containsMatchIn(line) + + class Result(val lines: List, val matches: Int) + + /** + * The lines matching [kind] and [query] (case-insensitive), newest first, at most [cap] of + * them; [Result.matches] counts all matches, so the screen can say when it's showing fewer. + */ + fun apply(fileLines: List, kind: Kind, query: String, cap: Int): Result { + val q = query.trim().lowercase() + val out = ArrayList(minOf(cap, fileLines.size)) + var matches = 0 + for (i in fileLines.indices.reversed()) { + val l = fileLines[i] + if (l.isEmpty()) continue + val kindOk = when (kind) { Kind.ALL -> true; Kind.REQUESTS -> !isStatus(l); Kind.STATUS -> isStatus(l) } + if (!kindOk || (q.isNotEmpty() && !l.lowercase().contains(q))) continue + matches++ + if (out.size < cap) out += l + } + return Result(out, matches) + } + + /** "Current" for the live file; otherwise how long ago it was last written, like "2h ago". */ + fun ageLabel(index: Int, lastModified: Long, now: Long): String { + if (index == 0) return "Current" + val mins = maxOf(0L, (now - lastModified) / 60_000) + return when { + mins < 60 -> "${mins}m ago" + mins < 24 * 60 -> "${mins / 60}h ago" + else -> "${mins / (24 * 60)}d ago" + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogProvider.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogProvider.kt new file mode 100644 index 000000000..3e92e3869 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogProvider.kt @@ -0,0 +1,80 @@ +package org.appdevforall.shareyourapps.server + +import android.content.ClipData +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.content.Intent +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.os.ParcelFileDescriptor +import android.provider.OpenableColumns +import java.io.File + +/** + * Hands the access log files to other apps through the share sheet — read-only, one grant per + * share, and only those five files. The logs live in private storage because they record + * buyers' IP addresses and browsers, so this is the only way they leave the app. + */ +class LogProvider : ContentProvider() { + + companion object { + const val AUTHORITY = "org.appdevforall.shareyourapps.server.logs" + private val NAME = Regex("""access\.log(\.[1-4])?""") + + fun uri(name: String): Uri = Uri.parse("content://$AUTHORITY/$name") + + /** "share-your-apps-server-log.txt" for the current file, "share-your-apps-server-log-2.txt" for older ones. */ + fun displayName(name: String) = "share-your-apps-server-log" + name.removePrefix("access.log").replace(".", "-") + ".txt" + + /** The existing log files, current first, then oldest last. */ + fun files(ctx: Context): List = (listOf(StoreLog.FILE_NAME) + (1 until StoreLog.KEEP).map { "${StoreLog.FILE_NAME}.$it" }) + .map { File(Store.logDir(ctx), it) }.filter { it.isFile } + + /** Opens the share sheet with [names] attached, so the owner can send them anywhere. */ + fun share(ctx: Context, names: List) { + if (names.isEmpty()) return + val uris = ArrayList(names.map { uri(it) }) + val send = if (uris.size == 1) Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris[0]) + else Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris) + send.type = "text/plain" + send.putExtra(Intent.EXTRA_SUBJECT, "Share Your Apps Server logs") + // The clip carries the read grant for every file to whichever app is chosen. + send.clipData = ClipData.newRawUri("", uris[0]).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } } + send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + ctx.startActivity(Intent.createChooser(send, "Send logs")) + } + } + + override fun onCreate() = true + + private fun file(uri: Uri): File? { + val name = uri.lastPathSegment ?: return null + if (!NAME.matches(name)) return null + return File(Store.logDir(context ?: return null), name).takeIf { it.isFile } + } + + override fun getType(uri: Uri) = "text/plain" + + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { + if (mode != "r") throw SecurityException("the logs can only be read") + val f = file(uri) ?: throw java.io.FileNotFoundException(uri.toString()) + return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY) + } + + /** Name and size, which receiving apps use to label the attachment. */ + override fun query(uri: Uri, projection: Array?, selection: String?, args: Array?, sort: String?): Cursor { + val f = file(uri) + val cols = projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE) + val c = MatrixCursor(cols) + if (f != null) c.addRow(cols.map { col -> + when (col) { OpenableColumns.DISPLAY_NAME -> displayName(f.name); OpenableColumns.SIZE -> f.length(); else -> null } + }) + return c + } + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + override fun update(uri: Uri, values: ContentValues?, s: String?, a: Array?) = 0 + override fun delete(uri: Uri, s: String?, a: Array?) = 0 +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogSize.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogSize.kt new file mode 100644 index 000000000..f723d8a46 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/LogSize.kt @@ -0,0 +1,27 @@ +package org.appdevforall.shareyourapps.server + +/** The access log's size limit, as the owner types it on the main screen: a whole number of MB. */ +object LogSize { + + const val MIN_MB = 0 + const val MAX_MB = 100 + + private val range = "Enter a whole number from $MIN_MB to $MAX_MB." + + /** The limit [text] gives, in MB, or null if it isn't one. */ + fun mb(text: String): Int? = text.trim().toIntOrNull()?.takeIf { it in MIN_MB..MAX_MB } + + /** Why [text] can't be used, naming the valid range, or null if it can. */ + fun problem(text: String): String? { + val s = text.trim() + // BigInteger, so a number too long for an Int still reads as too big, not as "not a number". + val n = s.toBigIntegerOrNull() + return when { + s.isEmpty() -> range + n == null -> "“$s” isn't a whole number. $range" + n < MIN_MB.toBigInteger() -> "$s is less than $MIN_MB. $range" + n > MAX_MB.toBigInteger() -> "$s is more than $MAX_MB. $range" + else -> null + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/MainActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/MainActivity.kt new file mode 100644 index 000000000..6d5418797 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/MainActivity.kt @@ -0,0 +1,707 @@ +package org.appdevforall.shareyourapps.server + +import android.Manifest +import android.app.Activity +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Intent +import android.graphics.Color +import android.graphics.Typeface +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.text.InputType +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.LayerDrawable +import android.text.Editable +import android.text.TextWatcher +import android.view.Gravity +import android.view.View +import android.widget.Button +import android.widget.EditText +import android.widget.HorizontalScrollView +import android.widget.RadioButton +import android.widget.RadioGroup +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import java.io.File +import org.appdevforall.shareyourapps.server.HelpUi.help + +/** + * A minimal Manage Server screen: start and stop the server, set the port, and look at the + * access log. The directory to serve always comes from the plugin; Start will serve the last one + * published, so there's nothing here to go stale. + */ +class MainActivity : Activity() { + + private val pal by lazy { Palette.of(this) } + + companion object { + private const val SHARE_CAPTION = "Give someone nearby a copy to serve from their own phone. They can serve it with their own PIN. They can't change it or pass it on." + private const val IMPORT_CAPTION = "Serve a copy of someone else's store, with their permission. You'll need to be near their phone, on the same network." + /** Asking for the microphone after MCP control is turned on, for import_listen. */ + private const val REQUEST_MCP_MIC = 4 + } + + private lateinit var status: TextView + private lateinit var address: TextView + private lateinit var addressRow: LinearLayout + private lateinit var hotspotInfo: TextView + private lateinit var lastPublished: TextView + private lateinit var portField: EditText + private lateinit var grant: Button + private lateinit var startButton: Button + private lateinit var stopButton: Button + private lateinit var logView: TextView + private lateinit var logPan: HorizontalScrollView + /** Refreshes the MCP switch and its state line; set in onCreate, observed while the screen is showing. */ + private var mcpListener: () -> Unit = {} + private val ticker = Handler(Looper.getMainLooper()) + private val tick = object : Runnable { + override fun run() { refreshLog(); ticker.postDelayed(this, 2000) } + } + private val statusListener: () -> Unit = { showStatus(); refreshLog(); refreshLastPublished() } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val prefs = getSharedPreferences(HostService.PREFS, MODE_PRIVATE) + val pad = (16 * resources.displayMetrics.density).toInt() + + val column = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(pad, pad, pad, pad) + } + fun label(t: String) = TextView(this).apply { text = t; setPadding(0, pad / 2, 0, 0) } + + status = TextView(this).apply { textSize = 16f; setTypeface(typeface, Typeface.BOLD) } + address = TextView(this).apply { + textSize = 16f + setPadding(0, pad / 4, 0, pad / 4) + setTextColor(pal.link) + } + // The address, with a copy button on its right, as the Share screen's codes have. The address itself isn't + // selectable: its long-press shows its help. + addressRow = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL + addView(address, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) + val size = (48 * resources.displayMetrics.density).toInt() + addView(android.widget.ImageButton(this@MainActivity).apply { + setImageDrawable(CopyIcon(pal.ink)) + val inset = (12 * resources.displayMetrics.density).toInt(); setPadding(inset, inset, inset, inset) + scaleType = android.widget.ImageView.ScaleType.FIT_CENTER + val ripple = android.util.TypedValue(); context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, ripple, true) + setBackgroundResource(ripple.resourceId) + contentDescription = "Copy the address" + setOnClickListener { copyAddress() } + }, LinearLayout.LayoutParams(size, size)) + } + hotspotInfo = TextView(this).apply { textSize = 15f; setTextIsSelectable(true); setPadding(0, 0, 0, pad / 4) } + grant = Button(this).apply { text = "Grant storage access"; setOnClickListener { requestStorage() } } + lastPublished = TextView(this).apply { setPadding(0, pad / 2, 0, 0) } + portField = EditText(this).apply { + inputType = InputType.TYPE_CLASS_NUMBER + setText(prefs.getInt(HostService.EXTRA_PORT, Store.DEFAULT_PORT).toString()) + } + startButton = Button(this).apply { text = "Start"; setOnClickListener { startServer() } } + stopButton = Button(this).apply { + text = "Stop" + setOnClickListener { + startForegroundService(Intent(this@MainActivity, HostService::class.java).setAction(HostService.ACTION_STOP)) + } + } + // When to run. Saved immediately; the service checks it each time the screen turns off. + val alwaysId = View.generateViewId() + val screenId = View.generateViewId() + val runMode = RadioGroup(this).apply { + addView(RadioButton(this@MainActivity).help("server.run_mode").apply { id = alwaysId; text = "Run always" }) + addView(RadioButton(this@MainActivity).help("server.run_mode").apply { id = screenId; text = "Pause when the screen turns off" }) + check(if (prefs.getString(HostService.PREF_RUN_MODE, "always") == "screenOff") screenId else alwaysId) + setOnCheckedChangeListener { _, id -> + prefs.edit().putString(HostService.PREF_RUN_MODE, if (id == screenId) "screenOff" else "always").apply() + } + } + + // The log's size limit, saved as it's typed when it's a whole number from 0 to 100. Anything else isn't + // saved, and says so plainly — in red, under the field and beside it — with the valid range and the limit kept. + val logHint = "0 turns logging off. Takes effect the next time the server starts." + val logNote = TextView(this).apply { textSize = 12f; setTextColor(pal.muted); text = logHint } + val logSize = EditText(this).apply { + inputType = InputType.TYPE_CLASS_NUMBER + setText(prefs.getInt(HostService.PREF_LOG_MB, HostService.DEFAULT_LOG_MB).toString()) + addTextChangedListener(object : android.text.TextWatcher { + override fun beforeTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {} + override fun onTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {} + override fun afterTextChanged(e: android.text.Editable?) { + val text = e?.toString().orEmpty() + val mb = LogSize.mb(text) + if (mb != null) { + prefs.edit().putInt(HostService.PREF_LOG_MB, mb).apply() + error = null + logNote.setTextColor(pal.muted); logNote.text = logHint + } else { + val problem = LogSize.problem(text) + val kept = prefs.getInt(HostService.PREF_LOG_MB, HostService.DEFAULT_LOG_MB) + error = problem + logNote.setTextColor(pal.bad); logNote.text = "$problem Until then, the limit stays at $kept MB." + } + } + }) + } + + // Newest lines first, so the latest is always in view without scrolling. Long lines + // scroll sideways rather than wrapping: the pane around the text does the scrolling, and + // the text doesn't scroll itself, which is what used to snap it back to the left edge. + logView = TextView(this).apply { + typeface = Typeface.MONOSPACE + textSize = 11f + setTextIsSelectable(true) + } + logPan = HorizontalScrollView(this).apply { addView(logView) } + + // Long-press help on headings and buttons; text fields keep their own long-press. + val helpButton = Button(this).apply { text = "Help"; setOnClickListener { HelpActivity.open(this@MainActivity, "index.html") } } + column.addView(TextView(this).apply { text = "Long-press a heading or button for help."; textSize = 12f; alpha = 0.7f; setPadding(pad / 4, 0, 0, pad / 2) }) + + column.addView(panel("Status", "server.status", + status.help("server.status"), + addressRow.also { address.help("server.status") }, + hotspotInfo.help("server.hotspot"), + Button(this).apply { + text = "Show QR codes for buyers" + setOnClickListener { startActivity(Intent(this@MainActivity, ServeActivity::class.java)) } + }.help("server.serve"), + grant.help("server.grant"), + lastPublished.help("server.last_published"), + )) + + // MCP control, off by default: apps on this phone may start and stop the server, share and import. + // Turning it on asks first. The token is never shown, only copied, and marked sensitive. + val mcpSwitch = android.widget.Switch(this).apply { text = "MCP control"; textSize = 16f } + val mcpState = TextView(this).apply { textSize = 13f; setTextColor(pal.muted) } + val mcpTokenRow = LinearLayout(this).apply { + gravity = Gravity.CENTER_VERTICAL + addView(Button(this@MainActivity).apply { + text = "Copy token" + setOnClickListener { + val clip = ClipData.newPlainText("MCP token", McpService.token(this@MainActivity)) + if (Build.VERSION.SDK_INT >= 33) clip.description.extras = android.os.PersistableBundle().apply { + putBoolean(android.content.ClipDescription.EXTRA_IS_SENSITIVE, true) + } + getSystemService(ClipboardManager::class.java).setPrimaryClip(clip) + if (Build.VERSION.SDK_INT < 33) android.widget.Toast.makeText(this@MainActivity, "Token copied", android.widget.Toast.LENGTH_SHORT).show() + } + }.help("server.mcp_token")) + addView(Button(this@MainActivity).apply { + text = "New token" + setOnClickListener { + android.app.AlertDialog.Builder(this@MainActivity).setTitle("Make a new token?") + .setMessage("Apps using the old token will be refused until they're given the new one.") + .setNegativeButton("Cancel", null) + .setPositiveButton("New token") { _, _ -> McpService.newToken(this@MainActivity) } + .show() + } + }.help("server.mcp_token")) + } + var settingMcpSwitch = false + fun showMcp() { + val on = McpService.enabled(this@MainActivity) + settingMcpSwitch = true; mcpSwitch.isChecked = on; settingMcpSwitch = false + mcpState.text = if (on) McpStatus.text else "Off. Turn on to let apps on this phone control the server." + mcpTokenRow.visibility = if (on) View.VISIBLE else View.GONE + } + mcpListener = { showMcp() } + mcpSwitch.setOnCheckedChangeListener { _, on -> + if (settingMcpSwitch) return@setOnCheckedChangeListener + if (!on) { McpService.setEnabled(this@MainActivity, false); showMcp(); return@setOnCheckedChangeListener } + // Not on until the person has read what it allows. + settingMcpSwitch = true; mcpSwitch.isChecked = false; settingMcpSwitch = false + android.app.AlertDialog.Builder(this@MainActivity).setTitle("Turn on MCP control?") + .setMessage("Apps on this phone will be able to start and stop the server, share this store and import a store.\n\n" + + "They can't change the store or approve a copy. You still tap Allow.\n\n" + + "This also lets the app use the microphone to hear the sound a sharing phone plays. It only listens while " + + "it's receiving a handshake, and Android shows its microphone indicator while it does.\n\n" + + "Each app needs the token: use Copy token, below the switch.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Turn on") { _, _ -> + McpService.setEnabled(this@MainActivity, true); showMcp() + // The microphone, for import_listen: asked now, while the person is here. Refused: MCP is on anyway. + if (!SoundIo.canListen(this@MainActivity)) + this@MainActivity.requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_MCP_MIC) + } + .show() + } + + column.addView(panel("Server", "server.overview", + // Port and its field on one line. + LinearLayout(this).apply { + gravity = android.view.Gravity.CENTER_VERTICAL + addView(TextView(this@MainActivity).apply { text = "Port"; setPadding(0, 0, pad / 2, 0) }.help("server.port")) + addView(portField.apply { setEms(5) }, LinearLayout.LayoutParams(-2, -2)) + }, + LinearLayout(this).apply { + addView(startButton.help("server.start")); addView(stopButton.help("server.stop")); addView(helpButton.help("server.overview")) + }, + mcpSwitch.help("server.mcp"), + mcpState.help("server.mcp"), + mcpTokenRow, + )) + + // Sharing a copy of the store with another seller (design, Appendix E; screen 1). + shareButton = Button(this).apply { text = "Share this store…"; setOnClickListener { ShareActivity.open(this@MainActivity) } } + shareCaption = TextView(this).apply { text = SHARE_CAPTION; textSize = 15f; setPadding(0, 0, 0, pad / 4) } + column.addView(panel("Copies of this store", "server.copies", + shareCaption.help("server.copies"), + shareButton.help("server.share"), + TextView(this).apply { text = "You can set an expiration date."; textSize = 13f; alpha = 0.75f }, + )) + + // The imported copy, when there is one (design, Appendix E; screen 7). Rebuilt on every refresh. + copyHolder = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + column.addView(copyHolder) + + // Importing someone else's store (design, Appendix E; screens 4 and 4b). + importCaption = TextView(this).apply { text = IMPORT_CAPTION; textSize = 15f; setPadding(0, 0, 0, pad / 4) } + importButton = Button(this).apply { text = "Import a store…"; setOnClickListener { startActivity(Intent(this@MainActivity, ImportActivity::class.java)) } } + column.addView(panel("Import a store", "server.import", + importCaption.help("server.import"), + importButton.help("server.import"), + )) + + + column.addView(panel("When to run", "server.run_mode", runMode)) + + column.addView(panel("Wi-Fi Direct hotspot", "server.p2p_settings", p2pSettings())) + + column.addView(panel("Logs", "server.log", + label("Log size limit (MB)").help("server.log_size"), + logSize, + logNote, + label("Access log — newest first, updates every 2 seconds").help("server.log"), + LinearLayout(this).apply { + addView(Button(this@MainActivity).apply { + text = "View logs"; setOnClickListener { startActivity(Intent(this@MainActivity, LogActivity::class.java)) } + }.help("server.view_logs")) + addView(Button(this@MainActivity).help("server.export_logs").apply { + text = "Export logs" + setOnClickListener { + val names = LogProvider.files(this@MainActivity).map { it.name } + if (names.isEmpty()) status.text = "There are no log files yet." else LogProvider.share(this@MainActivity, names) + } + }.help("server.export_logs")) + }, + logPan, + // Where the logs are: private storage, which other apps and file managers can't open. + label("Log folder").help("server.log_folder"), + TextView(this).apply { + text = Store.logDir(this@MainActivity).absolutePath + typeface = Typeface.MONOSPACE; textSize = 12f + // Tap to select the whole path. + setTextIsSelectable(true); setSelectAllOnFocus(true) + }, + TextView(this).apply { + text = "This folder is private to this app, because the logs record buyers' addresses. Other apps and file managers can't open it; use Export logs to send the logs elsewhere." + textSize = 12f; alpha = 0.7f + }, + )) + // A slightly darker page, so the raised panels stand up from it. + // Which build this is, at a glance: useful when two phones must match. + column.addView(TextView(this).apply { + val built = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT).format(java.util.Date(BuildConfig.BUILD_TIME)) + text = "Share Your Apps Server ${BuildConfig.VERSION_NAME} · built $built" + textSize = 12f; alpha = 0.7f; gravity = android.view.Gravity.CENTER; setPadding(0, pad / 2, 0, pad) + }) + setContentView(ScrollView(this).apply { setBackgroundColor(pal.screen); addView(column) }.also { SystemBars.fit(it) }) + + // Only when missing: asking again opens the system's permission screen briefly even when it's granted, + // which pauses and resumes this screen, so onResume ran twice (and started MCP control twice). + if (Build.VERSION.SDK_INT >= 33 && + checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED + ) requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1) + } + + override fun onResume() { + super.onResume() + grant.visibility = if (Store.hasStorageAccess(this)) View.GONE else View.VISIBLE + ServerStatus.observe(statusListener) // runs the listener once now, which refreshes everything + // MCP control starts when the app is opened with the switch on (nothing starts it at boot). + McpService.start(this) + McpStatus.observe(mcpListener) + ticker.post(tick) + } + + override fun onPause() { + super.onPause() + ServerStatus.remove(statusListener) + McpStatus.remove(mcpListener) + ticker.removeCallbacks(tick) + } + + /** + * One topic in a raised panel, with a fake 3D bevel: a face shading from white at the top to + * light grey at the bottom, a thin inner highlight, and a soft shadow offset below and to + * the right. + */ + private fun panel(title: String, helpTag: String, vararg views: View): View { + val dp = resources.displayMetrics.density + val lift = (5 * dp).toInt() + val radius = 12 * dp + val shadow = GradientDrawable().apply { setColor(pal.shadow); cornerRadius = radius } + // The lower edge of the bevel: a darker rim showing just below and right of the face. + val rim = GradientDrawable().apply { setColor(pal.rim); cornerRadius = radius } + val face = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(pal.panelTop, pal.panelBottom)).apply { + cornerRadius = radius; setStroke((1 * dp).toInt(), pal.stroke) + } + val highlight = GradientDrawable().apply { setColor(0x00000000); cornerRadius = radius - dp; setStroke((1.5f * dp).toInt(), pal.highlight) } + val edge = (2 * dp).toInt() + val bg = LayerDrawable(arrayOf(shadow, rim, face, highlight)).apply { + setLayerInset(0, lift, lift, 0, 0) // shadow: down and right + setLayerInset(1, edge, edge, lift - edge, lift - edge) // the rim, peeking out below the face + setLayerInset(2, 0, 0, lift, lift) // the face + setLayerInset(3, (1 * dp).toInt(), (1 * dp).toInt(), lift + (1 * dp).toInt(), lift + (1 * dp).toInt()) + } + val pad = (14 * dp).toInt() + return LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + background = bg + setPadding(pad, (12 * dp).toInt(), pad + lift, pad + lift) + layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (14 * dp).toInt() } + addView(TextView(this@MainActivity).apply { + text = title; textSize = 17f; setTypeface(typeface, Typeface.BOLD); setTextColor(pal.ink) + setPadding(0, 0, 0, (4 * dp).toInt()) + }.help(helpTag)) + views.forEach { addView(it) } + } + } + + /** + * The Wi-Fi Direct hotspot's name and password. The limits show as you type, the trade-off of + * changing them is stated up front, and nothing changes until Save. + */ + private fun p2pSettings(): View { + val box = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + val ink = pal.ink; val muted = pal.muted; val bad = pal.bad; val good = pal.good + fun note(size: Float = 12f) = TextView(this).apply { textSize = size; setTextColor(muted) } + + box.addView(note(13f).apply { + setTextColor(ink) + text = "When this phone isn't on Wi-Fi, the server starts a hotspot that buyers join. It uses this name and password. " + + "If you change either one, phones that joined before won't reconnect by themselves: buyers will need to join again, " + + "using the new details on the Serve screen. Changes take effect the next time the hotspot starts." + }) + + val room = HotspotSettings.MAX_NAME_BYTES - HotspotSettings.PREFIX.length + box.addView(TextView(this).apply { text = "Network name"; setPadding(0, 12, 0, 0); setTypeface(typeface, Typeface.BOLD) }.help("server.hotspot_name")) + val suffix = EditText(this).apply { setSingleLine(); layoutParams = LinearLayout.LayoutParams(0, -2, 1f) } + box.addView(LinearLayout(this).apply { + gravity = Gravity.CENTER_VERTICAL + addView(TextView(this@MainActivity).apply { text = HotspotSettings.PREFIX; typeface = Typeface.MONOSPACE; textSize = 15f }) + addView(suffix) + }) + val nameLimit = note() + box.addView(nameLimit) + + box.addView(TextView(this).apply { text = "Password"; setPadding(0, 12, 0, 0); setTypeface(typeface, Typeface.BOLD) }.help("server.hotspot_password")) + // The hotspot's password is the app's own, shown to buyers anyway, so it's visible here. + val password = EditText(this).apply { + setSingleLine(); inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + } + box.addView(password) + val passLimit = note() + box.addView(passLimit) + + val result = note(13f).apply { setPadding(0, 8, 0, 0) } + + fun showLimits() { + val used = HotspotSettings.name(suffix.text.toString()).toByteArray(Charsets.UTF_8).size - HotspotSettings.PREFIX.length + val nameProblem = HotspotSettings.nameProblem(suffix.text.toString()) + nameLimit.setTextColor(if (nameProblem != null) bad else muted) + nameLimit.text = when { + used > room -> "Too long: $used of $room used. Shorten it by ${used - room}." + else -> "$used of $room used after ${HotspotSettings.PREFIX}. Letters, digits, spaces and punctuation count 1 each; accented letters count 2, and emoji 4." + } + if (nameProblem != null && used <= room) " " + nameProblem else "" + val n = password.text.length + val passProblem = HotspotSettings.passwordProblem(password.text.toString()) + passLimit.setTextColor(if (passProblem != null) bad else muted) + passLimit.text = "$n characters. It needs 8 to 63: letters, digits, spaces and ordinary punctuation, no accented letters or emoji." + + if (passProblem != null && n in 8..63) " $passProblem" else "" + } + fun showUnsaved() { + val (savedName, savedPass) = Hotspot.credentials(this) + val changed = HotspotSettings.name(suffix.text.toString()) != savedName || password.text.toString() != savedPass + if (changed) { result.setTextColor(ink); result.text = "Not saved yet: the hotspot still uses its current name and password." } + else if (result.text.startsWith("Not saved yet")) result.text = "" + } + val watcher = object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun afterTextChanged(s: Editable?) { showLimits(); showUnsaved() } + } + val (name, pass) = Hotspot.credentials(this) + suffix.setText(name.removePrefix(HotspotSettings.PREFIX)) + password.setText(pass) + suffix.addTextChangedListener(watcher) + password.addTextChangedListener(watcher) + showLimits() + + // Side by side, each taking half the row; a label wraps rather than pushing the other off the edge. + box.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + addView(Button(this@MainActivity).help("server.hotspot_save").apply { + text = "Save name & password" + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + setOnClickListener { + val problem = HotspotSettings.nameProblem(suffix.text.toString()) ?: HotspotSettings.passwordProblem(password.text.toString()) + if (problem != null) { result.setTextColor(bad); result.text = "Not saved. $problem"; return@setOnClickListener } + val newName = HotspotSettings.name(suffix.text.toString()) + val (savedName, savedPass) = Hotspot.credentials(this@MainActivity) + if (newName == savedName && password.text.toString() == savedPass) { + result.setTextColor(muted); result.text = "Nothing to save: that's already the name and password in use." + return@setOnClickListener + } + Hotspot.saveCredentials(this@MainActivity, newName, password.text.toString()) + result.setTextColor(good) + result.text = "Saved. The hotspot will be “$newName” with the new password from the next time it starts — " + + "tap Stop, then Start, to switch now. Buyers will need to join again with the new details." + } + }.help("server.p2p_settings")) + addView(Button(this@MainActivity).help("server.hotspot_suggest").apply { + text = "Suggest a password" + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + setOnClickListener { + password.setText(HotspotSettings.randomPassword()) + result.setTextColor(ink) + result.text = "A new 16-character password is in the box above, but nothing has changed yet. " + + "Tap Save name & password to switch the hotspot to it; until you do, it keeps its current password." + } + }.help("server.p2p_settings")) + }) + box.addView(result) + return box + } + + private lateinit var shareButton: Button + private lateinit var copyHolder: LinearLayout + private var shownCopy: String? = null + + /** Screen 7: the imported copy — read-only, its expiry, serving it with the seller's own PIN, and removing it. */ + private fun refreshCopy() { + if (!::copyHolder.isInitialized) return + val imported = ImportJob.importedDir(this) + // An expired copy is deleted as soon as it's due (Appendix E.5), unless it's being served: + // then the server process lets downloads under way finish first. + val serving = ServerStatus.servingCopy && ServerStatus.url != null + if (!serving) CopyExpiry.enforce(imported, ExpiryClock(CopyExpiry.clockFile(filesDir))) + val copy = ImportJob.currentCopy(this) + val notice = CopyExpiry.notice(imported) + val key = "${copy?.storeId}|${copy?.created}|$serving|${notice?.storeName}" + if (key == shownCopy) return + shownCopy = key + copyHolder.removeAllViews() + val pad = (16 * resources.displayMetrics.density).toInt() + // Screen 8: a copy that expired, until the seller dismisses it. + if (notice != null) copyHolder.addView(panel("A store has expired", "server.copy_expired", + // The same words however the copy came to expire: nothing says why. + TextView(this).apply { + text = "Your copy of ${notice.storeName} has expired, and has been deleted from this phone. " + + "Buyers can no longer open it. To serve it again, ask its owner for a new copy." + textSize = 15f + }, + Button(this).help("server.copy_expired").apply { text = "OK"; setOnClickListener { CopyExpiry.dismiss(imported); shownCopy = null; refreshCopy() } }, + )) + if (copy == null) return + val prefs = getSharedPreferences(HostService.PREFS, MODE_PRIVATE) + val expires = copy.expires?.let { + val days = java.time.Duration.between(java.time.Instant.now(), it).toDays() + "Expires " + java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).format(java.util.Date.from(it)) + + if (days >= 1) " · in $days ${if (days == 1L) "day" else "days"}" else " · today" + } ?: "Never expires" + val pin = EditText(this).apply { + inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD + filters = arrayOf(android.text.InputFilter.LengthFilter(6)); setEms(5) + setText(prefs.getString(HostService.PREF_COPY_PIN, "").orEmpty()) + addTextChangedListener(object : android.text.TextWatcher { + override fun beforeTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {} + override fun onTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {} + override fun afterTextChanged(e: android.text.Editable?) { + prefs.edit().putString(HostService.PREF_COPY_PIN, e?.toString()?.takeIf { it.isNotEmpty() }).apply() + } + }) + } + copyHolder.addView(panel(copy.storeName, "server.copy", + TextView(this).apply { text = "Read-only · $expires"; textSize = 15f; setTypeface(typeface, Typeface.BOLD) }.help("server.copy"), + TextView(this).apply { + text = if (serving) "Serving it now." else "An imported copy of someone else's store. You can serve it; it can't be changed or passed on." + textSize = 14f; setPadding(0, pad / 4, 0, pad / 4) + }, + Button(this).apply { + text = if (serving) "Serve it again, with this PIN" else "Serve this store" + setOnClickListener { startForegroundService(Intent(this@MainActivity, HostService::class.java).setAction(HostService.ACTION_SERVE_COPY)) } + }.help("server.copy_serve"), + TextView(this).apply { text = "Set a PIN or leave blank for no PIN"; setTypeface(typeface, Typeface.BOLD); setPadding(0, pad / 2, 0, 0) }.help("server.copy_pin"), + LinearLayout(this).apply { + gravity = android.view.Gravity.CENTER_VERTICAL + addView(pin, LinearLayout.LayoutParams(-2, -2)) + addView(TextView(this@MainActivity).apply { text = "Up to 6 digits. Buyers enter it before reaching the store."; textSize = 13f; setPadding(pad / 2, 0, 0, 0) }, + LinearLayout.LayoutParams(0, -2, 1f)) + }, + Button(this).apply { + text = "Remove this store"; setTextColor(pal.danger) + setOnClickListener { removeCopy(copy) } + }.help("server.copy_remove"), + )) + } + + private fun removeCopy(copy: SharePackage.Description) { + android.app.AlertDialog.Builder(this) + .setTitle("Remove ${copy.storeName}?") + .setMessage("It's deleted from this phone. To serve it again, ask its owner for a new copy.") + .setPositiveButton("Remove") { _, _ -> + if (ServerStatus.servingCopy && ServerStatus.url != null) + startForegroundService(Intent(this, HostService::class.java).setAction(HostService.ACTION_STOP)) + val dir = ImportJob.importedDir(this) + java.io.File(dir, copy.storeId).deleteRecursively(); java.io.File(dir, "${copy.storeId}.json").delete() + shownCopy = null; refreshCopy() + } + .setNegativeButton("Keep it", null) + .show() + } + + /** A phone serving its own store can't import one (design, Appendix E.1; screen 4b). */ + private lateinit var shareCaption: TextView + private lateinit var importCaption: TextView + private lateinit var importButton: Button + + /** + * The sharing panels say whether their buttons can be used, and why not, before anyone taps: + * sharing needs this phone's own store to be served; importing needs no store served at all, + * so a copy is never replaced under a running server (design, Appendix E.1). + */ + private fun refreshSharingPanels() { + if (!::shareButton.isInitialized) return + val serving = ServerStatus.url != null + shareButton.isEnabled = serving && !ServerStatus.servingCopy + shareCaption.text = when { + !serving -> "Start serving your store to share it." + ServerStatus.servingCopy -> "This phone is serving a copy of someone else's store. Copies can't be passed on." + else -> SHARE_CAPTION + } + importButton.isEnabled = !serving + importCaption.text = if (serving) "This phone is serving a store. To import one, stop serving it first, with Stop above, or import on another phone." + else IMPORT_CAPTION + } + + /** + * Start is for a stopped server and Stop for a running one, so the screen shows which it is. + * Between a tap on Start and the server being up, Start stays enabled: ServerStatus has no + * "starting" state. + */ + private fun refreshServerButtons() { + if (!::startButton.isInitialized) return + val serving = ServerStatus.url != null + startButton.isEnabled = !serving + stopButton.isEnabled = serving + startButton.fill(pal.startFill) + stopButton.fill(pal.stopFill) + + } + + /** + * A solid fill while the button is enabled, with white text on it. A disabled button is grey, like the app's other + * disabled buttons, with the text faded. Call it after setting [Button.isEnabled]. + */ + private fun Button.fill(on: Int) { + backgroundTintList = android.content.res.ColorStateList.valueOf(if (isEnabled) on else pal.fillOff) + val textStates = arrayOf(intArrayOf(android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_enabled)) + setTextColor(android.content.res.ColorStateList(textStates, intArrayOf(pal.onFill, pal.onFillOff))) + } + + private fun showStatus() { + refreshServerButtons() + // Copies can't be passed on, so sharing needs this phone's own store. + refreshSharingPanels() + refreshCopy() + status.text = ServerStatus.text + val h = ServerStatus.hotspot + hotspotInfo.visibility = if (h == null) View.GONE else View.VISIBLE + hotspotInfo.text = h.orEmpty() + val url = ServerStatus.url + addressRow.visibility = if (url == null) View.GONE else View.VISIBLE + if (url != null) address.text = url + } + + /** What Start will serve: this phone's own last published store, or its imported copy (the same rule as HostService). */ + private fun refreshLastPublished() { + val prefs = getSharedPreferences(HostService.PREFS, MODE_PRIVATE) + val last = prefs.getString(HostService.EXTRA_DIR, null) + val copy = ImportJob.currentCopy(this) + val line = when { + copy != null && (last == null || prefs.getString(HostService.PREF_SOURCE, "own") == "copy") -> + "Start will serve the imported copy of ${copy.storeName}, below." + last != null -> "Start will serve the last store published: $last" + else -> "Nothing published yet — publish from the Share Your Apps plugin, or import a store, below." + } + // "Start" in a hairline box, naming the button above. + lastPublished.text = if (line.startsWith("Start ")) android.text.SpannableString(line).apply { + setSpan(BoxSpan(resources.displayMetrics.density), 0, 5, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + } else line + } + + /** Copies the store's address. Android 13 and later confirm a copy themselves; older versions get a message. */ + private fun copyAddress() { + val url = ServerStatus.url ?: return + getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Share Your Apps address", url)) + if (android.os.Build.VERSION.SDK_INT < 33) android.widget.Toast.makeText(this, "Address copied", android.widget.Toast.LENGTH_SHORT).show() + } + + private fun startServer() { + val port = portField.text.toString().toIntOrNull() + when { + port == null || port !in 1024..65535 -> status.text = "The port must be between 1024 and 65535." + // Kept for MCP control, which listens on 127.0.0.1:6176 (and share discovery uses UDP 6176). + port == McpHttp.DEFAULT_PORT -> status.text = "Port ${McpHttp.DEFAULT_PORT} is kept for MCP control. Choose another port, such as ${Store.DEFAULT_PORT}." + !Store.hasStorageAccess(this) -> status.text = "Grant storage access first." + // Not on Wi-Fi: a hotspot will be needed, and starting one needs a permission. + Store.needsHotspot() && !Store.hasHotspotPermission(this) -> requestPermissions(Store.hotspotPermissions(), 3) + else -> startForegroundService( + Intent(this, HostService::class.java).setAction(HostService.ACTION_START) + .putExtra(HostService.EXTRA_PORT, port) + ) + } + } + + private fun requestStorage() { + if (Build.VERSION.SDK_INT >= 30) { + startActivity(Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName"))) + } else { + requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 2) + } + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + grant.visibility = if (Store.hasStorageAccess(this)) View.GONE else View.VISIBLE + if (requestCode == 3) { + if (Store.hasHotspotPermission(this)) startServer() + else status.text = "Without that permission, the server can't start a hotspot. Connect to Wi-Fi instead, or tap Start to be asked again." + } + // Allowed or refused: MCP control starts again, with or without the microphone type, and its line says which. + if (requestCode == REQUEST_MCP_MIC) McpService.start(this) + } + + /** + * Updates the pane only when the log has changed, keeps the sideways scroll position, and + * leaves it alone while you have text selected, so reading and selecting aren't interrupted. + */ + private fun refreshLog() { + if (logView.hasSelection()) return + val f = File(Store.logDir(this), StoreLog.FILE_NAME) + val next = if (f.exists()) f.readLines().takeLast(200).asReversed().joinToString("\n") else "(no log yet)" + if (next == logView.text.toString()) return + val x = logPan.scrollX + logView.text = next + logPan.post { logPan.scrollTo(x, 0) } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpHttp.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpHttp.kt new file mode 100644 index 000000000..45244cf93 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpHttp.kt @@ -0,0 +1,313 @@ +package org.appdevforall.shareyourapps.server + +import java.io.BufferedInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.net.URI +import java.security.MessageDigest +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread +import org.json.JSONObject + +/** + * The MCP endpoint's HTTP side: a small HTTP/1.1 listener on 127.0.0.1 only, apart from the store's + * own HttpServer, so it's never reachable from another device. Before [McpProtocol] sees a request, + * it checks who's asking: + * - the peer is a loopback address (it can't be otherwise, but it's checked anyway); + * - Host names 127.0.0.1 or localhost, and Origin, if sent, does too, so a web page can't reach it + * by DNS rebinding; + * - Authorization: Bearer , the token shown on the server screen, compared in constant time. + * + * POST /mcp carries JSON-RPC; DELETE /mcp ends a session; GET gets 405, since this server never + * opens an event stream. Each connection has its own thread, as a tool may wait a while; at most + * [MAX_CONNECTIONS] at once. Plain Kotlin, so unit tests can run it without Android. + */ +class McpHttp( + private val protocol: McpProtocol, + /** The current token: read on every request, so a new one takes effect at once. */ + private val token: () -> String, + private val port: Int = DEFAULT_PORT, + /** Problems worth a line in the log. Never given the token. */ + private val log: (String) -> Unit = {}, +) { + companion object { + const val DEFAULT_PORT = 6176 + const val PATH = "/mcp" + const val MAX_CONNECTIONS = 8 + private const val MAX_HEADER_BYTES = 16 * 1024 + const val MAX_BODY_BYTES = 1024 * 1024 + /** A connection with no request for this long is closed. */ + const val IDLE_TIMEOUT_MS = 30_000 + private val STATUS = mapOf( + 200 to "OK", 202 to "Accepted", 204 to "No Content", 400 to "Bad Request", 401 to "Unauthorized", + 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed", 413 to "Payload Too Large", + 415 to "Unsupported Media Type", 431 to "Request Header Fields Too Large", 500 to "Internal Server Error", + 501 to "Not Implemented", 503 to "Service Unavailable", + ) + private val LOOPBACK_NAMES = setOf("127.0.0.1", "localhost") + } + + private class Request(val method: String, val target: String, val version: String, val headers: Map, val body: ByteArray) + private class HttpError(val status: Int, message: String) : Exception(message) + + @Volatile private var socket: ServerSocket? = null + @Volatile private var running = false + private val open = AtomicInteger(0) + private val clients: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) + + /** The port actually bound (useful when [port] is 0, as in tests). */ + val boundPort: Int get() = socket?.localPort ?: port + + /** Binds 127.0.0.1:[port]. Throws IOException with a readable message if the port is taken. */ + fun start() { + val s = ServerSocket() + try { + s.reuseAddress = true + s.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), port), 16) + } catch (e: IOException) { + try { s.close() } catch (ignored: IOException) { } + throw IOException("Can't listen on 127.0.0.1:$port: ${e.message}", e) + } + socket = s + running = true + thread(name = "mcp-accept", isDaemon = true) { acceptLoop(s) } + } + + /** Stops listening and closes every connection. */ + fun stop() { + running = false + try { socket?.close() } catch (ignored: IOException) { } + socket = null + clients.forEach { close(it) } + clients.clear() + } + + private fun acceptLoop(s: ServerSocket) { + while (running && !s.isClosed) { + val c = try { s.accept() } catch (e: IOException) { + if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") + continue + } + if (!c.inetAddress.isLoopbackAddress) { close(c); continue } + if (open.incrementAndGet() > MAX_CONNECTIONS) { + open.decrementAndGet() + try { + c.soTimeout = 1000 + respond(c.getOutputStream(), 503, rpcError("Too many connections at once; try again."), emptyMap(), close = true) + } catch (ignored: IOException) { } + close(c) + continue + } + clients += c + thread(name = "mcp-connection", isDaemon = true) { + try { + serve(c) + } catch (ignored: IOException) { + // The client went away. + } catch (e: Exception) { + log("a connection failed: ${e.javaClass.simpleName}: ${e.message}") + } finally { + clients -= c + close(c) + open.decrementAndGet() + } + } + } + } + + private fun serve(c: Socket) { + c.soTimeout = IDLE_TIMEOUT_MS + c.tcpNoDelay = true + val input = BufferedInputStream(c.getInputStream()) + val out = c.getOutputStream() + while (running) { + val req = try { + readRequest(input) ?: return + } catch (e: SocketTimeoutException) { + return + } catch (e: HttpError) { + respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) + return + } + if (!handle(req, out)) return + } + } + + /** Answers one request. Returns whether the connection stays open for another. */ + private fun handle(r: Request, out: OutputStream): Boolean { + val close = r.version == "HTTP/1.0" || r.headers["connection"]?.lowercase()?.contains("close") == true + fun send(status: Int, body: String?, headers: Map = emptyMap()): Boolean { + respond(out, status, body, headers, close) + return !close + } + if (!hostAllowed(r.headers["host"])) return send(403, rpcError("The Host header must be 127.0.0.1 or localhost.")) + val origin = r.headers["origin"] + if (origin != null && !originAllowed(origin)) return send(403, rpcError("Requests from web pages aren't accepted.")) + if (r.target.substringBefore('?') != PATH) return send(404, rpcError("Not found: the MCP endpoint is $PATH.")) + if (!authorized(r.headers["authorization"])) { + return send(401, rpcError("Missing or wrong token. Copy it from Share Your Apps Server's server screen, and send it as Authorization: Bearer ."), + mapOf("WWW-Authenticate" to "Bearer realm=\"Share Your Apps Server\"")) + } + val session = r.headers["mcp-session-id"] + val reply = when (r.method) { + "POST" -> { + val type = r.headers["content-type"]?.substringBefore(';')?.trim()?.lowercase() + if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) + try { + protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) + } catch (e: Exception) { + log("a request failed: ${e.javaClass.simpleName}: ${e.message}") + McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) + } + } + "DELETE" -> protocol.delete(session) + "GET" -> return send(405, rpcError("This server doesn't offer an event stream: use POST."), mapOf("Allow" to "POST, DELETE")) + else -> return send(405, rpcError("Use POST."), mapOf("Allow" to "POST, DELETE")) + } + return send(reply.status, reply.body, reply.headers) + } + + // ---------------------------------------------------------------- checks + + /** 127.0.0.1 or localhost, on any port: adb forward may bring the request in from another port. */ + private fun hostAllowed(host: String?): Boolean { + val h = host?.trim()?.lowercase() ?: return false + val name = if (h.count { it == ':' } == 1) h.substringBefore(':') else h + if (h.count { it == ':' } == 1 && h.substringAfter(':').let { it.isEmpty() || it.any { ch -> !ch.isDigit() } }) return false + return name in LOOPBACK_NAMES + } + + private fun originAllowed(origin: String): Boolean = try { + val u = URI(origin.trim()) + (u.scheme == "http" || u.scheme == "https") && u.host?.lowercase() in LOOPBACK_NAMES + } catch (e: Exception) { false } + + private fun authorized(header: String?): Boolean { + val expected = token() + if (header == null || expected.isEmpty()) return false + val h = header.trim() + if (!h.regionMatches(0, "Bearer ", 0, 7, ignoreCase = true)) return false + return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8)) + } + + // ---------------------------------------------------------------- reading and writing HTTP + + /** One request, or null if the connection closed before one began. */ + private fun readRequest(input: InputStream): Request? { + var budget = MAX_HEADER_BYTES + fun line(): String? { + val b = ByteArrayOutputStream() + while (true) { + val ch = input.read() + if (ch < 0) { if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") } + if (--budget < 0) throw HttpError(431, "The request's headers are too long.") + if (ch == '\n'.code) break + b.write(ch) + } + return b.toString("ISO-8859-1").removeSuffix("\r") + } + var first = line() ?: return null + while (first.isEmpty()) first = line() ?: return null // stray line ends between requests + val parts = first.split(' ') + if (parts.size != 3 || !parts[2].startsWith("HTTP/1.")) throw HttpError(400, "That isn't an HTTP/1.x request.") + val headers = HashMap() + while (true) { + val l = line() ?: throw HttpError(400, "The request ended early.") + if (l.isEmpty()) break + val colon = l.indexOf(':') + if (colon <= 0) throw HttpError(400, "A header line without a colon.") + val name = l.substring(0, colon).trim().lowercase() + val value = l.substring(colon + 1).trim() + // A repeated header is joined, so two Host headers fail the Host check. + headers[name] = headers[name]?.let { "$it, $value" } ?: value + } + return Request(parts[0], parts[1], parts[2], headers, readBody(input, headers)) + } + + private fun readBody(input: InputStream, h: Map): ByteArray { + val te = h["transfer-encoding"] + if (te != null) { + if (!te.equals("chunked", ignoreCase = true)) throw HttpError(501, "Transfer-Encoding $te isn't supported.") + if (h.containsKey("content-length")) throw HttpError(400, "Both Content-Length and Transfer-Encoding were sent.") + return readChunked(input) + } + val len = h["content-length"] ?: return ByteArray(0) + val n = len.toLongOrNull()?.takeIf { it >= 0 } ?: throw HttpError(400, "Content-Length isn't a number.") + if (n > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") + return readExactly(input, n.toInt()) + } + + private fun readChunked(input: InputStream): ByteArray { + val out = ByteArrayOutputStream() + while (true) { + val sizeLine = shortLine(input, 1024) ?: throw HttpError(400, "The request ended early.") + val size = sizeLine.substringBefore(';').trim().toIntOrNull(16)?.takeIf { it >= 0 } ?: throw HttpError(400, "A bad chunk size.") + if (out.size().toLong() + size > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") + if (size == 0) { + // Trailers, if any, up to a blank line. + var lines = 0 + while (true) { + val t = shortLine(input, 1024) ?: break + if (t.isEmpty()) break + if (++lines > 32) throw HttpError(431, "Too many trailers.") + } + return out.toByteArray() + } + out.write(readExactly(input, size)) + if (shortLine(input, 2) != "") throw HttpError(400, "A chunk without its line end.") + } + } + + private fun shortLine(input: InputStream, max: Int): String? { + val b = ByteArrayOutputStream() + var left = max + while (true) { + val ch = input.read() + if (ch < 0) return if (b.size() == 0) null else throw HttpError(400, "The request ended early.") + if (--left < 0) throw HttpError(400, "A line in the request is too long.") + if (ch == '\n'.code) break + b.write(ch) + } + return b.toString("ISO-8859-1").removeSuffix("\r") + } + + private fun readExactly(input: InputStream, n: Int): ByteArray { + val b = ByteArray(n) + var off = 0 + while (off < n) { + val r = input.read(b, off, n - off) + if (r < 0) throw HttpError(400, "The request ended early.") + off += r + } + return b + } + + private fun respond(out: OutputStream, status: Int, body: String?, headers: Map, close: Boolean) { + val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) + val head = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: "Status"}\r\n") + if (body != null) head.append("Content-Type: application/json; charset=utf-8\r\n") + if (status != 204) head.append("Content-Length: ${bytes.size}\r\n") + head.append("Cache-Control: no-store\r\n") + if (close) head.append("Connection: close\r\n") + for ((k, v) in headers) head.append(k).append(": ").append(v.replace("\r", "").replace("\n", "")).append("\r\n") + head.append("\r\n") + out.write(head.toString().toByteArray(Charsets.ISO_8859_1)) + if (status != 204) out.write(bytes) + out.flush() + } + + /** An HTTP-level refusal, as a JSON-RPC error with no id, which MCP clients know how to show. */ + private fun rpcError(message: String): String = JSONObject().put("jsonrpc", "2.0").put("id", JSONObject.NULL) + .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)).toString() + + private fun close(s: Socket) { try { s.close() } catch (ignored: IOException) { } } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpProtocol.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpProtocol.kt new file mode 100644 index 000000000..d479e4fff --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpProtocol.kt @@ -0,0 +1,173 @@ +package org.appdevforall.shareyourapps.server + +import org.json.JSONArray +import org.json.JSONObject +import org.json.JSONTokener + +/** + * A tool an MCP client can call. [run] gets the call's arguments (an empty object when none were + * sent) and returns what happened, as JSON; it throws [McpToolError] for a failure the client + * should read, such as "a person is needed". + */ +class McpTool( + val name: String, + val title: String, + val description: String, + val inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), + /** Only reports; changes nothing. Shown to clients as a hint, not relied on. */ + val readOnly: Boolean = true, + val run: (JSONObject) -> JSONObject, +) { + fun describe(): JSONObject = JSONObject() + .put("name", name).put("title", title).put("description", description) + .put("inputSchema", inputSchema) + .put("annotations", JSONObject().put("title", title).put("readOnlyHint", readOnly) + .put("destructiveHint", false).put("openWorldHint", false)) +} + +/** A tool's failure, told to the client as a tool result with isError, with [details] when there are any. */ +class McpToolError(message: String, val details: JSONObject? = null) : Exception(message) + +/** + * The Model Context Protocol, as Share Your Apps Server speaks it: JSON-RPC 2.0 over the Streamable HTTP + * transport, answering every POST with plain JSON, never an event stream. Plain Kotlin and org.json, + * so unit tests run it without Android. [McpHttp] does the sockets and checks who's asking; this + * decides what to answer, and keeps the sessions. + * + * Methods: initialize, ping, tools/list, tools/call. Notifications, and responses a client sends, + * are accepted and need no answer (HTTP 202). + */ +class McpProtocol( + private val tools: List, + private val serverVersion: String, + private val newSessionId: () -> String, + private val maxSessions: Int = 16, +) { + companion object { + /** Newest first: offered when a client asks for a version this server doesn't know. */ + val VERSIONS = listOf("2025-06-18", "2025-03-26", "2024-11-05") + const val SERVER_NAME = "share-your-apps-server" + const val SESSION_HEADER = "Mcp-Session-Id" + const val PARSE_ERROR = -32700 + const val INVALID_REQUEST = -32600 + const val METHOD_NOT_FOUND = -32601 + const val INVALID_PARAMS = -32602 + const val INSTRUCTIONS = "Controls Share Your Apps Server on this phone. Tools report on the server and the store, " + + "and start and stop things. No tool can change the store's contents or approve a copy: " + + "only a person, tapping Allow on the sharing phone, can do that." + } + + /** What to send back: an HTTP status, a JSON body (or none), and extra headers. */ + class Reply(val status: Int, val body: String?, val headers: Map = emptyMap()) + + /** Live sessions, oldest first; the oldest is dropped when there are too many. */ + private val sessions = LinkedHashSet() + + /** A POST to the endpoint: one JSON-RPC message, or a batch of them. */ + fun post(body: String, sessionId: String?, versionHeader: String?): Reply { + val parsed = try { JSONTokener(body).nextValue() } catch (e: Exception) { null } + if (parsed !is JSONObject && parsed !is JSONArray) return Reply(400, error(null, PARSE_ERROR, "That isn't a JSON object or array.").toString()) + val messages: List = if (parsed is JSONArray) (0 until parsed.length()).map { parsed.opt(it) } else listOf(parsed) + if (messages.isEmpty()) return Reply(400, error(null, INVALID_REQUEST, "An empty batch.").toString()) + + if (messages.any { (it as? JSONObject)?.optString("method") == "initialize" }) { + if (messages.size != 1) return Reply(400, error(null, INVALID_REQUEST, "Send initialize on its own, not in a batch.").toString()) + return initialize(messages[0] as JSONObject) + } + if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header: send initialize first.").toString()) + if (!touch(sessionId)) return Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist: send initialize again.").toString()) + if (versionHeader != null && versionHeader !in VERSIONS) { + return Reply(400, error(null, INVALID_REQUEST, "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}.").toString()) + } + val replies = messages.mapNotNull { handle(it) } + if (replies.isEmpty()) return Reply(202, null) + return Reply(200, if (parsed is JSONArray) JSONArray(replies).toString() else replies[0].toString()) + } + + /** A DELETE: the client is done with its session. */ + fun delete(sessionId: String?): Reply { + if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header.").toString()) + val removed = synchronized(sessions) { sessions.remove(sessionId) } + return if (removed) Reply(204, null) else Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist.").toString()) + } + + /** Ends every session, so clients must initialize again. */ + fun endAll() = synchronized(sessions) { sessions.clear() } + + fun sessionCount(): Int = synchronized(sessions) { sessions.size } + + private fun touch(id: String): Boolean = synchronized(sessions) { + if (!sessions.remove(id)) return false + sessions += id // most recently used goes last, so it's dropped last + true + } + + private fun initialize(m: JSONObject): Reply { + val id = m.opt("id") + if (!validId(id)) return Reply(400, error(null, INVALID_REQUEST, "initialize needs an id, a string or a number.").toString()) + if (m.optString("jsonrpc") != "2.0") return Reply(400, error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".").toString()) + val asked = m.optJSONObject("params")?.optString("protocolVersion", "") ?: "" + val version = if (asked in VERSIONS) asked else VERSIONS[0] + val session = newSessionId() + synchronized(sessions) { + sessions += session + while (sessions.size > maxSessions) sessions.remove(sessions.first()) + } + val result = JSONObject() + .put("protocolVersion", version) + .put("capabilities", JSONObject().put("tools", JSONObject().put("listChanged", false))) + .put("serverInfo", JSONObject().put("name", SERVER_NAME).put("title", "Share Your Apps Server").put("version", serverVersion)) + .put("instructions", INSTRUCTIONS) + return Reply(200, ok(id, result).toString(), mapOf(SESSION_HEADER to session)) + } + + /** One message of a POST; null when it needs no answer. */ + private fun handle(raw: Any?): JSONObject? { + val m = raw as? JSONObject ?: return error(null, INVALID_REQUEST, "Each message must be a JSON object.") + val hasId = m.has("id") + val id = m.opt("id") + val method = m.opt("method") as? String + if (method == null) { + // A response to something this server asked: it never asks, so there's nothing to do. + if (m.has("result") || m.has("error")) return null + return error(if (validId(id)) id else null, INVALID_REQUEST, "A request needs a method.") + } + if (!hasId) return null // a notification, such as notifications/initialized: no answer + if (!validId(id)) return error(null, INVALID_REQUEST, "id must be a string or a number.") + if (m.optString("jsonrpc") != "2.0") return error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".") + return when (method) { + "ping" -> ok(id, JSONObject()) + "tools/list" -> ok(id, JSONObject().put("tools", JSONArray().also { a -> tools.forEach { a.put(it.describe()) } })) + "tools/call" -> call(id, m.opt("params")) + else -> error(id, METHOD_NOT_FOUND, "Unknown method \"$method\".") + } + } + + private fun call(id: Any, rawParams: Any?): JSONObject { + val params = rawParams as? JSONObject ?: return error(id, INVALID_PARAMS, "tools/call needs params, with the tool's name.") + val name = params.opt("name") as? String ?: return error(id, INVALID_PARAMS, "tools/call needs the tool's name.") + val tool = tools.firstOrNull { it.name == name } ?: return error(id, INVALID_PARAMS, "Unknown tool \"$name\".") + val args = when (val a = params.opt("arguments")) { + null, JSONObject.NULL -> JSONObject() + is JSONObject -> a + else -> return error(id, INVALID_PARAMS, "arguments must be an object.") + } + val result = try { + val out = tool.run(args) + JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) + } catch (e: McpToolError) { + JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> + e.details?.let { r.put("structuredContent", it) } + } + } catch (e: Exception) { + JSONObject().put("content", JSONArray().put(text("The tool failed: ${e.message ?: e.javaClass.simpleName}"))).put("isError", true) + } + return ok(id, result) + } + + private fun validId(id: Any?) = id is String || id is Number + private fun text(t: String) = JSONObject().put("type", "text").put("text", t) + private fun ok(id: Any, result: JSONObject) = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + private fun error(id: Any?, code: Int, message: String) = JSONObject().put("jsonrpc", "2.0").put("id", id ?: JSONObject.NULL) + .put("error", JSONObject().put("code", code).put("message", message)) +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpService.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpService.kt new file mode 100644 index 000000000..3bb3d946a --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpService.kt @@ -0,0 +1,220 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.util.Log +import java.util.concurrent.CopyOnWriteArrayList +import kotlin.concurrent.thread + +/** + * MCP control (the switch on the server screen): a foreground service in the main process that + * listens on 127.0.0.1:[McpHttp.DEFAULT_PORT] for MCP clients on this phone. Off by default. Main + * process, so tools reach [ServerStatus], [ImportJob] and HostService directly. + * + * The switch's setting is kept in [PREFS]; the service runs while it's on and the app has been + * opened since the phone started (nothing starts it at boot). The token clients send is kept there + * too, private to the app, and is never logged. + */ +class McpService : Service() { + + companion object { + const val PREFS = "mcp" + private const val PREF_ENABLED = "enabled" + private const val PREF_TOKEN = "token" + const val ACTION_TURN_OFF = "org.appdevforall.shareyourapps.server.MCP_TURN_OFF" + /** + * Minimum importance: silent, with a collapsed card in the shade's silent section. Android still shows a + * status-bar icon for a foreground service even on a MIN channel (checked on the phone: importance=1, not + * user-set), so MCP's notification uses its own sync icon, apart from the server's upload icon. A channel's + * importance can't be lowered once created, so this is a new channel; the old one, [OLD_CHANNEL], is deleted. + */ + private const val CHANNEL = "mcp_quiet" + private const val OLD_CHANNEL = "mcp" + private const val NOTIFICATION = 6176 + private const val TAG = "ShareYourAppsMcp" + + fun enabled(ctx: Context): Boolean = + ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ENABLED, false) + + /** Saves the switch and starts or stops the service. Call [start] only from a screen the person is using. */ + fun setEnabled(ctx: Context, on: Boolean) { + ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(PREF_ENABLED, on).apply() + if (on) start(ctx) else ctx.stopService(Intent(ctx, McpService::class.java)) + } + + /** Starts the service if the switch is on. Safe to call when it's already running. */ + fun start(ctx: Context) { + if (!enabled(ctx)) return + try { + ctx.startForegroundService(Intent(ctx, McpService::class.java)) + } catch (e: Exception) { + // Android refuses foreground starts from the background; the next opening of the app tries again. + McpStatus.set(McpStatus.State.FAILED, "Couldn't start: ${e.message ?: e.javaClass.simpleName}. Open the app to try again.") + } + } + + /** The token clients send as Authorization: Bearer ; made the first time it's needed. */ + fun token(ctx: Context): String { + val prefs = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + prefs.getString(PREF_TOKEN, null)?.let { return it } + return newToken(ctx) + } + + /** Replaces the token: clients using the old one are refused from their next request. */ + fun newToken(ctx: Context): String { + val t = hex(ShareCrypto.randomBytes(24)) + ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(PREF_TOKEN, t).apply() + return t + } + + private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) } + } + + private val main = Handler(Looper.getMainLooper()) + @Volatile private var http: McpHttp? = null + /** Whether the service runs with the microphone type, so import_listen can hear tones with the app off screen. */ + @Volatile private var micType = false + private var protocol: McpProtocol? = null + private var starting = false + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + // startForegroundService() needs startForeground() promptly, whatever happens next. + goForeground() + if (intent?.action == ACTION_TURN_OFF) { + getSharedPreferences(PREFS, MODE_PRIVATE).edit().putBoolean(PREF_ENABLED, false).apply() + stopSelf() + return START_NOT_STICKY + } + if (!enabled(this)) { stopSelf(); return START_NOT_STICKY } + if (http != null || starting) { + // Already running: the microphone type may have changed (the app opened, the microphone allowed or refused). + http?.let { McpStatus.set(McpStatus.State.ON, onText(it.boundPort)) } + return START_NOT_STICKY + } + starting = true + McpStatus.set(McpStatus.State.STARTING, "Starting…") + val app = applicationContext + val p = McpProtocol(McpTools.all(app), BuildConfig.VERSION_NAME, { hex(ShareCrypto.randomBytes(16)) }) + val h = McpHttp(p, { token(app) }, McpHttp.DEFAULT_PORT, log = { line -> Log.w(TAG, line) }) + // Binding is network work: off the main thread. + thread(name = "mcp-start") { + val error = try { h.start(); null } catch (e: Exception) { e.message ?: e.javaClass.simpleName } + main.post { + starting = false + if (error != null) { + Log.w(TAG, "failed to start: $error") + McpStatus.set(McpStatus.State.FAILED, "Failed: $error. Is another app using port ${McpHttp.DEFAULT_PORT}?") + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } else if (!enabled(this)) { + h.stop() // turned off while it was starting + stopSelf() + } else { + http = h; protocol = p + Log.i(TAG, "listening on 127.0.0.1:${h.boundPort}") + McpStatus.set(McpStatus.State.ON, onText(h.boundPort)) + } + } + } + return START_NOT_STICKY + } + + override fun onDestroy() { + http?.stop(); http = null + protocol?.endAll(); protocol = null + // A share an MCP client opened ends with MCP control; one a person opened carries on. Off the main + // thread: ShareControl may wait briefly for the server process, whose replies arrive on the main thread. + thread(name = "mcp-share-shutdown") { ShareControl.shutdown() } + // Tones an MCP client started, and listening for one, end with MCP control. + McpSoundTools.stopPlaying() + SoundImport.stop(this) + // A failure stays on show; otherwise the switch's state says why it stopped. + if (McpStatus.state != McpStatus.State.FAILED) { + McpStatus.set(McpStatus.State.OFF, if (enabled(this)) "Not running. Open the app to start it." else "Off") + } + Log.i(TAG, "stopped") + } + + private fun goForeground() { + val nm = getSystemService(NotificationManager::class.java) + // The old channel had low importance, which still shows a status-bar icon; channels can't be lowered, so it goes. + nm.deleteNotificationChannel(OLD_CHANNEL) + nm.createNotificationChannel(NotificationChannel(CHANNEL, "MCP control", NotificationManager.IMPORTANCE_MIN).apply { + description = "Shown while MCP control is on. Silent." + setShowBadge(false) + }) + // Android still shows a status-bar icon for a foreground service, even on a MIN channel (confirmed on the + // phone: importance=1, not user-set). So MCP gets its own icon, distinct from the server's upload icon. + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val off = PendingIntent.getService(this, 1, Intent(this, McpService::class.java).setAction(ACTION_TURN_OFF), PendingIntent.FLAG_IMMUTABLE) + val n = Notification.Builder(this, CHANNEL) + .setSmallIcon(android.R.drawable.stat_notify_sync) + .setContentTitle("MCP control is on") + .setContentText("Apps on this phone can control Share Your Apps Server. They can't change the store or approve a copy.") + .setContentIntent(open) + .addAction(Notification.Action.Builder(null, "Turn off", off).build()) + .setOngoing(true) + .build() + // The microphone type too, when the app may use the microphone, so import_listen hears tones with the app off + // screen. Android refuses that type unless the app is on screen (it isn't after a reboot, or from the + // background): then MCP runs as before, without it, and the next opening of the app adds it (onResume). + // Android 9 and 10 have no microphone type: any foreground service may use the microphone there. + val mic = SoundIo.canListen(this) + if (Build.VERSION.SDK_INT >= 30 && mic) { + val special = if (Build.VERSION.SDK_INT >= 34) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0 + try { + startForeground(NOTIFICATION, n, special or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + micType = true + return + } catch (e: Exception) { + Log.w(TAG, "the microphone type was refused (${e.javaClass.simpleName}); running without it until the app is opened") + } + } + micType = mic && Build.VERSION.SDK_INT < 30 + if (Build.VERSION.SDK_INT >= 34) { + startForeground(NOTIFICATION, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + } else { + startForeground(NOTIFICATION, n) + } + } + + /** The line under the switch while it's on: the address, and whether import_listen can use the microphone. */ + private fun onText(port: Int): String = "On, at http://127.0.0.1:$port${McpHttp.PATH}" + when { + !SoundIo.canListen(this) -> "\nMicrophone not allowed: hearing a sharing phone's tones needs a person." + !micType -> "\nMicrophone: works once the app is opened." + else -> "" + } +} + +/** MCP control's state, for the server screen. Main process only; listeners run on the main thread. */ +object McpStatus { + enum class State { OFF, STARTING, ON, FAILED } + + private val main = Handler(Looper.getMainLooper()) + private val listeners = CopyOnWriteArrayList<() -> Unit>() + + @Volatile var state = State.OFF + private set + @Volatile var text = "Off" + private set + + fun set(s: State, t: String) { + state = s; text = t + main.post { listeners.forEach { it() } } + } + + fun observe(l: () -> Unit) { listeners += l; l() } + fun remove(l: () -> Unit) { listeners -= l } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpSoundTools.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpSoundTools.kt new file mode 100644 index 000000000..dba040024 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpSoundTools.kt @@ -0,0 +1,217 @@ +package org.appdevforall.shareyourapps.server + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import kotlin.concurrent.thread +import org.json.JSONObject + +/** + * Step C's sound tools for MCP clients. share_play_sound: the sharing phone plays the open share's code as tones, as + * the share screen's Play sound does. import_listen: the importing phone listens for them, through [SoundImport]. + * Kept apart from [McpTools] and [ShareControl]: ShareControl may only open, poll and close a share, so the "played" + * line goes to the server's log over a short connection of its own here. The hotspot's password is never reported. + */ +object McpSoundTools { + private val lock = Any() + @Volatile private var player: SoundIo.Player? = null + /** Counts players started and stopped, so a finished player's callback, or its watcher, can't touch a newer one. */ + @Volatile private var soundRun = 0 + @Volatile private var playingCode: String? = null + + fun all(context: Context): List { + val app = context.applicationContext + return listOf(sharePlaySound(app), importListen(app)) + } + + private fun boolArg(args: JSONObject, key: String): Boolean = when (val v = args.opt(key)) { + null, JSONObject.NULL -> false + is Boolean -> v + else -> throw McpToolError("$key must be true or false.") + } + + private fun personNeeded(what: String) = + McpToolError("A person is needed: $what", JSONObject().put("state", "person_needed").put("person_needed", what)) + + // ---------------------------------------------------------------- share_play_sound + + private fun sharePlaySound(ctx: Context) = McpTool( + name = "share_play_sound", + title = "Play the share code as sound", + description = "Plays the open share's code as a short run of tones through this phone's speaker, as the share screen's Play sound " + + "does, so a phone nearby can hear it instead of scanning or typing it: import_listen there, or Listen on its import screen. " + + "Needs a share waiting for a phone: call share_start first. Repeats for up to 30 seconds, and stops by itself once a phone " + + "connects or the share ends; stop true stops it sooner. On this phone's own hotspot the tones also carry the hotspot's " + + "name and password, so anyone close enough to hear them gets them. The password is never in this tool's answer.", + inputSchema = JSONObject().put("type", "object").put("properties", JSONObject() + .put("stop", JSONObject().put("type", "boolean").put("description", "true: stop the tones now."))) + .put("additionalProperties", false), + readOnly = false, + ) { args -> if (boolArg(args, "stop")) stopTool() else play(ctx) } + + private fun play(ctx: Context): JSONObject { + if (ServerStatus.url == null) throw McpToolError("The server isn't serving, so there's no share to play. Call server_start, then share_start.", + JSONObject().put("state", "not_serving")) + val share = ShareControl.status(ctx, 0) + val code = share.optString("code", "") + val link = share.optString("link", "") + if (share.optString("state") != "waiting_for_phone" || code.isEmpty()) + throw McpToolError("Sound only works while a share is waiting for a phone. Call share_start first.", + JSONObject().put("state", "no_share_waiting").put("share", share)) + synchronized(lock) { + if (player != null && playingCode == code) return JSONObject().put("playing", true).put("already_playing", true).put("code", code) + } + val payload = payload(code, link) ?: throw McpToolError("Couldn't turn this share's code into sound.") + val low = SoundIo.volumeLow(ctx) + val r = synchronized(lock) { + player?.stop() + val n = ++soundRun + playingCode = code + lateinit var p: SoundIo.Player + p = SoundIo.Player(payload.encode(), { error -> + synchronized(lock) { if (n == soundRun) { player = null; playingCode = null } } + log(ctx, SoundLog.played(p.burstsPlayed, p.bursts, p.stoppedEarly, low, payload.ownHotspot, error) + ", for an MCP client") + }, null) + player = p.start() + n + } + watch(ctx, r, code) + val withHotspot = payload.ssid != null && payload.password != null + val out = JSONObject().put("playing", true).put("already_playing", false).put("code", code) + .put("seconds", SoundIo.WINDOW_MS / 1000).put("own_hotspot", payload.ownHotspot) + .put("carries", if (withHotspot) "the code, the server's address, and this phone's hotspot name and password" else "the code and the server's address") + .put("next", "On the other phone, call import_listen, or tap Listen on its import screen. Follow this share with share_status.") + if (low) out.put("warning", "The media volume is low: the other phone may not hear the tones. A person can turn it up.") + return out + } + + private fun stopTool(): JSONObject { + val was = stopPlaying() + val out = JSONObject().put("playing", false).put("stopped", was) + if (!was) out.put("note", "No sound was playing.") + return out + } + + /** Stops the tones, if any are playing; their "played" line is still logged. Also called when MCP control is turned off. */ + fun stopPlaying(): Boolean { + synchronized(lock) { + val p = player ?: return false + soundRun++ + p.stop(); player = null; playingCode = null + return true + } + } + + /** Once a second: the tones stop when the share leaves waiting_for_phone, the code changes, or the server stops. */ + private fun watch(ctx: Context, r: Int, code: String) { + thread(name = "sound-share-watch", isDaemon = true) { + while (true) { + try { Thread.sleep(1000) } catch (e: InterruptedException) { return@thread } + if (r != soundRun || player == null) return@thread + val s = try { ShareControl.status(ctx, 0) } catch (e: Exception) { null } + val movedOn = s != null && (s.optString("state") != "waiting_for_phone" || s.optString("code") != code) + if (movedOn || ServerStatus.url == null) { + synchronized(lock) { if (r == soundRun) { soundRun++; player?.stop(); player = null; playingCode = null } } + return@thread + } + } + } + } + + /** + * What the tones carry, as on the share screen: the code and the server's address from the share link; on this + * phone's own hotspot, also its name and password. On other Wi-Fi, neither (Hotspot.info is null there). + */ + private fun payload(code: String, link: String): SoundPayload? { + val normalized = ShareCodes.normalize(code) ?: return null + val parsed = ShareLink.parse(link) + val address = parsed?.let { try { java.net.InetAddress.getByName(it.first) as? java.net.Inet4Address } catch (e: Exception) { null } } + val port = if (address != null && parsed != null) parsed.second else 0 + val hotspot = Hotspot.info + fun fits(s: String) = s.isNotEmpty() && s.toByteArray(Charsets.UTF_8).size <= SoundPayload.MAX_FIELD + val ssid = hotspot?.ssid?.takeIf { it != "?" && fits(it) } + val password = hotspot?.password?.takeIf { ssid != null && fits(it) } + return try { SoundPayload(normalized, if (port > 0) address else null, port, hotspot != null, ssid, password) } + catch (e: IllegalArgumentException) { null } + } + + /** The "played" line: to the server's log while it serves (its process owns the file), else here. */ + private fun log(ctx: Context, message: String) { + val app = ctx.applicationContext + if (ServerStatus.url == null) { SoundLog.write(app, message); return } + val line = SoundLog.line(message) + android.util.Log.i("ShareYourAppsSound", line) + Handler(Looper.getMainLooper()).post { LogOnce(app, line).send() } + } + + /** Binds the server process without starting it, sends one log line, and lets go; gives up after 3 s. */ + private class LogOnce(private val app: Context, private val line: String) : ServiceConnection { + private var done = false + fun send() { + val bound = try { app.bindService(Intent(app, ServerService::class.java), this, 0) } catch (e: Exception) { false } + if (!bound) finish() else Handler(Looper.getMainLooper()).postDelayed({ finish() }, 3000) + } + override fun onServiceConnected(name: ComponentName, service: IBinder) { + try { Messenger(service).send(Message.obtain(null, Ipc.MSG_LOG).apply { data = Bundle().apply { putString(Ipc.KEY_LINE, line) } }) } + catch (e: Exception) { } + finish() + } + override fun onServiceDisconnected(name: ComponentName) { } + private fun finish() { + if (done) return + done = true + try { app.unbindService(this) } catch (e: Exception) { } + } + } + + // ---------------------------------------------------------------- import_listen + + private fun importListen(ctx: Context) = McpTool( + name = "import_listen", + title = "Listen for a share code", + description = "Listens with this phone's microphone, for up to 30 seconds, for the share code another phone plays as sound: " + + "share_play_sound there, or Play sound on its share screen. Once it hears the code, the import starts, as import_start would. " + + "Returns at once: follow it with import_status, whose listen part is one of listening, checking, joining, import_started, " + + "nothing_heard, person_needed, failed or stopped. If the other phone serves on its own hotspot, Android asks a person here " + + "to tap Connect to join it. The hotspot's password is never reported. stop true stops listening; import_cancel does too. " + + "Refused while this phone is serving, starting or paused: call server_stop first. Refused while an import is running.", + inputSchema = JSONObject().put("type", "object").put("properties", JSONObject() + .put("phone_name", JSONObject().put("type", "string").put("maxLength", 40) + .put("description", "The name the other phone's owner sees, at most 40 characters. Default: this phone's name.")) + .put("stop", JSONObject().put("type", "boolean").put("description", "true: stop listening now."))) + .put("additionalProperties", false), + readOnly = false, + ) { args -> if (boolArg(args, "stop")) stopListening(ctx) else listen(ctx, args) } + + private fun stopListening(ctx: Context): JSONObject { + val was = SoundImport.stop(ctx) + val out = SoundImport.status().put("stopped", was) + if (!was) out.put("note", "Nothing was listening.") + return out + } + + private fun listen(ctx: Context, args: JSONObject): JSONObject { + val name = McpTools.phoneNameArg(args) ?: ImportActivity.defaultPhoneName(ctx) + // As import_start: a phone serving its own store can't import one. Starting and paused count too. + val server = McpTools.stateOf(ServerStatus.text, ServerStatus.url) + if (server == "serving" || server == "starting" || server == "paused") + throw McpToolError("This phone is serving a store, or about to, and can't import one while it does. Stop the server first, with server_stop.", + JSONObject().put("state", "server_running").put("server", McpTools.status(ctx))) + val why = SoundImport.start(ctx, name) + if (why != null) { + if (why.startsWith("person needed: ")) throw personNeeded(why.removePrefix("person needed: ")) + throw McpToolError(why, JSONObject().put("state", if (SoundImport.busy) "listening" else "importing").put("listen", SoundImport.status())) + } + return SoundImport.status().put("phone_name", name) + .put("next", "Ask the owner to play the code: Play sound on their share screen, or share_play_sound on their phone. " + + "Follow with import_status, wait_seconds up to 25: its listen part says what was heard, and the import's own fields follow once it starts.") + } +} +// END OF McpSoundTools.kt diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpTools.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpTools.kt new file mode 100644 index 000000000..8e4b02735 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/McpTools.kt @@ -0,0 +1,453 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.content.Intent +import org.json.JSONArray +import org.json.JSONObject + +/** + * The tools MCP clients can call. Each runs on one of [McpHttp]'s connection threads and reads what + * the main process already knows: [ServerStatus], [Hotspot.info], the saved settings and the imported + * copy's description. server_start and server_stop send HostService the same requests the server + * screen's Start and Stop do; the share tools go through [ShareControl], which can't approve a copy. + * + * Never reported: the hotspot's password, the PIN, the plugin's token, the cookie secret. + * No tool changes the store's contents, deletes a copy, or changes the hotspot's settings. + */ +object McpTools { + + /** Reason HostService logs when server_stop stops the server. */ + const val STOP_REASON = "stopped by an MCP client" + private const val DEFAULT_START_WAIT_S = 10 + /** The app's context, kept by [all], so import_status can check the network now, not when the import ended. */ + @Volatile private var appCtx: Context? = null + + fun all(context: Context): List { + val app = context.applicationContext + appCtx = app + // Step C's sound tools, share_play_sound and import_listen, are in McpSoundTools. + return listOf(serverStatus(app), storeInfo(app), serverStart(app), serverStop(app), + shareStart(app), shareStatus(app), shareStop(app), + importStartTool(app), importStatusTool(app), importCancelTool(app)) + McpSoundTools.all(app) + } + + // ---------------------------------------------------------------- server_status + + private fun serverStatus(ctx: Context) = McpTool( + name = "server_status", + title = "Server status", + description = "Whether Share Your Apps Server is serving on this phone, and what: this phone's own store or an imported copy, " + + "at which address, on which kind of network (Wi-Fi, the phone's Mobile hotspot, or the app's own hotspot, with its name). " + + "state is one of serving, starting, paused, stopped, failed. The hotspot's password is never included.", + ) { _ -> status(ctx) } + + fun status(ctx: Context): JSONObject { + val prefs = ctx.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val text = ServerStatus.text + val url = ServerStatus.url + val out = JSONObject() + .put("state", stateOf(text, url)) + .put("status", text) + .put("url", url ?: JSONObject.NULL) + .put("serving", if (url == null) JSONObject.NULL else if (ServerStatus.servingCopy) "copy" else "own") + .put("port_setting", prefs.getInt(HostService.EXTRA_PORT, Store.DEFAULT_PORT)) + .put("run_mode", if (prefs.getString(HostService.PREF_RUN_MODE, "always") == "screenOff") "pause_when_screen_off" else "always") + if (url != null) out.put("network", network()) + return out + } + + /** The kind of network being served on. The hotspot's name only, never its password. */ + private fun network(): JSONObject { + val h = Hotspot.info + return when { + h != null -> JSONObject() + .put("kind", if (h.kind == Hotspot.Kind.WIFI_DIRECT) "app_hotspot_wifi_direct" else "app_hotspot_local_only") + .put("ssid", h.ssid) + .put("address", h.address.hostAddress ?: JSONObject.NULL) + ServerStatus.onPhoneHotspot -> JSONObject().put("kind", "phone_mobile_hotspot") + else -> JSONObject().put("kind", "wifi") + } + } + + /** The status line, as one word a client can act on. Plain Kotlin, for tests. */ + fun stateOf(text: String, url: String?): String = when { + url != null -> "serving" + text.startsWith("Failed") -> "failed" + text.startsWith("Paused") -> "paused" + text.startsWith("Stopped") -> "stopped" + text.contains("tarting") -> "starting" // Starting…, Restarting…, Not on Wi-Fi — starting a hotspot… + else -> "stopped" + } + + // ---------------------------------------------------------------- store_info + + private fun storeInfo(ctx: Context) = McpTool( + name = "store_info", + title = "Store information", + description = "What this phone has to serve: its own published store (the folder last published from the Share Your Apps plugin, and its name), " + + "and the imported copy of someone else's store, if there is one (its name, size and expiry). Also which one was served last.", + ) { _ -> storeInfo(ctx, Unit) } + + @Suppress("UNUSED_PARAMETER") + private fun storeInfo(ctx: Context, unit: Unit): JSONObject { + val prefs = ctx.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val own = JSONObject() + val dir = prefs.getString(HostService.EXTRA_DIR, null) + if (dir == null) { + own.put("published", false) + } else { + own.put("published", true) + .put("directory", dir) + .put("name", prefs.getString(HostService.PREF_STORE_NAME, null) ?: JSONObject.NULL) + val storage = Store.hasStorageAccess(ctx) + own.put("storage_access", storage) + if (storage && Store.validName(dir)) own.put("exists", Store.dir(dir).isDirectory) + } + val copy = try { ImportJob.currentCopy(ctx) } catch (e: Exception) { null } + val copyJson: Any = if (copy == null) JSONObject.NULL else JSONObject() + .put("name", copy.storeName) + .put("store_id", copy.storeId) + .put("created", runCatching { copy.created.toString() }.getOrNull() ?: JSONObject.NULL) + .put("expires", runCatching { copy.expires?.toString() }.getOrNull() ?: JSONObject.NULL) + .put("files", runCatching { copy.files.size }.getOrDefault(0)) + .put("bytes", runCatching { copy.totalBytes }.getOrDefault(0L)) + return JSONObject() + .put("own_store", own) + .put("imported_copy", copyJson) + .put("last_served", prefs.getString(HostService.PREF_SOURCE, "own")) + .put("serving", if (ServerStatus.url == null) JSONObject.NULL else if (ServerStatus.servingCopy) "copy" else "own") + } + + // ---------------------------------------------------------------- arguments and refusals + + private fun schema(vararg props: Pair): JSONObject = JSONObject().put("type", "object") + .put("properties", JSONObject().also { p -> props.forEach { (k, v) -> p.put(k, v) } }) + .put("additionalProperties", false) + + private fun waitProp(what: String): JSONObject = JSONObject().put("type", "integer").put("minimum", 0) + .put("maximum", ShareControl.MAX_WAIT_S).put("description", what) + + /** wait_seconds: a number from 0 to [ShareControl.MAX_WAIT_S], or [default] when not sent. Internal, for tests. */ + internal fun waitArg(args: JSONObject, default: Int): Int { + if (!args.has("wait_seconds") || args.isNull("wait_seconds")) return default + val v = args.opt("wait_seconds") as? Number + ?: throw McpToolError("wait_seconds must be a number of seconds, from 0 to ${ShareControl.MAX_WAIT_S}.") + return v.toInt().coerceIn(0, ShareControl.MAX_WAIT_S) + } + + /** server_start's store: "own", "copy", or null when not sent (then whichever Start would serve). Internal, for tests. */ + internal fun storeArg(args: JSONObject): String? = when (val s = args.opt("store")) { + null, JSONObject.NULL -> null + "own", "copy" -> s as String + else -> throw McpToolError("store must be \"own\" or \"copy\".") + } + + /** Something only a person can do: the client is told what, and why. */ + private fun personNeeded(what: String) = + McpToolError("A person is needed: $what", JSONObject().put("state", "person_needed").put("person_needed", what)) + + /** + * Sends HostService [intent], as the server screen's buttons do, then waits up to [waitSeconds] for the + * status to change and settle where [done] says. Returns whether it settled in time. + */ + private fun sendAndWait(ctx: Context, intent: Intent, waitSeconds: Int, done: (String) -> Boolean): Boolean { + val changes = java.util.concurrent.atomic.AtomicInteger(-1) // observe() calls the listener once at once + val lock = Object() + val listener: () -> Unit = { changes.incrementAndGet(); synchronized(lock) { lock.notifyAll() } } + ServerStatus.observe(listener) + try { + try { + ctx.startForegroundService(intent) + } catch (e: Exception) { + // Android 12+ may refuse a foreground start while the app isn't on screen. + throw personNeeded("Android didn't let the app start its server service from the background " + + "(${e.javaClass.simpleName}). Ask a person to open Share Your Apps Server, then try again.") + } + val deadline = System.currentTimeMillis() + waitSeconds * 1000L + while (true) { + if (changes.get() > 0 && done(stateOf(ServerStatus.text, ServerStatus.url))) return true + val left = deadline - System.currentTimeMillis() + if (left <= 0) return false + synchronized(lock) { lock.wait(minOf(left, 250L)) } + } + } finally { + ServerStatus.remove(listener) + } + } + + // ---------------------------------------------------------------- server_start + + private fun serverStart(ctx: Context) = McpTool( + name = "server_start", + title = "Start the server", + description = "Starts serving, as the server screen's Start button does; restarts it if it's already serving. " + + "store \"own\" serves this phone's own published store, \"copy\" the imported copy; without it, whichever Start would serve. " + + "Waits up to wait_seconds (default $DEFAULT_START_WAIT_S) for it to be serving, then reports as server_status does. " + + "Reports person_needed when a person must act first, such as granting a permission.", + inputSchema = schema( + "store" to JSONObject().put("type", "string").put("enum", JSONArray().put("own").put("copy")) + .put("description", "\"own\": this phone's published store. \"copy\": the imported copy."), + "wait_seconds" to waitProp("How long to wait for the server to be serving, 0 to ${ShareControl.MAX_WAIT_S}. Default $DEFAULT_START_WAIT_S."), + ), + readOnly = false, + ) { args -> startServer(ctx, args) } + + private fun startServer(ctx: Context, args: JSONObject): JSONObject { + val asked = storeArg(args) + val wait = waitArg(args, DEFAULT_START_WAIT_S) + val prefs = ctx.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val ownDir = prefs.getString(HostService.EXTRA_DIR, null) + val copy = try { ImportJob.currentCopy(ctx) } catch (e: Exception) { null } + // Without a choice, the same as Start: the copy if it was served last, or if there's no store of this phone's own. + val which = asked ?: if (copy != null && (prefs.getString(HostService.PREF_SOURCE, "own") == "copy" || ownDir == null)) "copy" else "own" + if (which == "copy" && copy == null) { + throw McpToolError("There's no imported copy on this phone to serve.", JSONObject().put("state", "no_copy")) + } + if (which == "own") { + if (ownDir == null) throw McpToolError("Nothing has been published on this phone yet: publish from the Share Your Apps plugin in Code on the Go first.", + JSONObject().put("state", "nothing_published")) + if (!Store.hasStorageAccess(ctx)) throw personNeeded("storage access hasn't been granted. Ask a person to open Share Your Apps Server and tap Grant storage access.") + } + val port = prefs.getInt(HostService.EXTRA_PORT, Store.DEFAULT_PORT) + if (port == McpHttp.DEFAULT_PORT) throw personNeeded("the store's port is set to ${McpHttp.DEFAULT_PORT}, which MCP control uses. Ask a person to choose another port on the server screen.") + // A copy is never replaced under a running server, so nothing starts while one is arriving. + if (ImportJob.snapshot.busy) throw McpToolError("A store is being imported on this phone. Wait for the import to finish.", + JSONObject().put("state", "importing")) + if (Store.needsHotspot() && !Store.hasHotspotPermission(ctx)) { + val perm = if (android.os.Build.VERSION.SDK_INT >= 33) "Nearby devices" else "Location" + throw personNeeded("this phone isn't on Wi-Fi, so the server must start a hotspot, which needs the $perm permission. " + + "Ask a person to open Share Your Apps Server and tap Start, or to join a Wi-Fi network first.") + } + val intent = Intent(ctx, HostService::class.java) + if (which == "copy") intent.action = HostService.ACTION_SERVE_COPY + // The log names MCP control, not Manage Server, as the reason for the restart. + else intent.setAction(HostService.ACTION_START).putExtra(HostService.EXTRA_DIR, ownDir) + .putExtra(HostService.EXTRA_REASON, "restarted by an MCP client") + val settled = sendAndWait(ctx, intent, wait) { it != "starting" } + val out = status(ctx).put("requested", which) + if (out.optString("state") == "failed") { + val why = ServerStatus.text.removePrefix("Failed: ") + if (why.contains("permission")) out.put("person_needed", why) + throw McpToolError("The server didn't start: $why", out) + } + if (!settled) out.put("next", "Still starting. Call server_status to see when it's serving.") + return out + } + + // ---------------------------------------------------------------- server_stop + + private fun serverStop(ctx: Context) = McpTool( + name = "server_stop", + title = "Stop the server", + description = "Stops serving, as the server screen's Stop button does, and turns off the app's hotspot if it started one. " + + "Any share or download under way ends. The log records that an MCP client stopped it. " + + "Waits up to wait_seconds (default $DEFAULT_START_WAIT_S) for it to stop.", + inputSchema = schema("wait_seconds" to waitProp("How long to wait for the server to stop, 0 to ${ShareControl.MAX_WAIT_S}. Default $DEFAULT_START_WAIT_S.")), + readOnly = false, + ) { args -> stopServer(ctx, args) } + + private fun stopServer(ctx: Context, args: JSONObject): JSONObject { + val wait = waitArg(args, DEFAULT_START_WAIT_S) + val before = stateOf(ServerStatus.text, ServerStatus.url) + if (before == "stopped" || before == "failed") return status(ctx).put("stopped", false).put("note", "The server wasn't running.") + val intent = Intent(ctx, HostService::class.java).setAction(HostService.ACTION_STOP).putExtra(HostService.EXTRA_REASON, STOP_REASON) + val settled = sendAndWait(ctx, intent, wait) { it == "stopped" || it == "failed" } + val out = status(ctx).put("stopped", settled) + if (!settled) out.put("next", "Still stopping. Call server_status to see when it has stopped.") + return out + } + + // ---------------------------------------------------------------- share_start, share_status, share_stop + + private fun shareStart(ctx: Context) = McpTool( + name = "share_start", + title = "Share this store", + description = "Opens a share of this phone's own store, for another phone nearby to import: returns its code and link. " + + "The other phone imports with them; then a person on this phone must check four digits and tap Allow, which no tool can do. " + + "A notification asks them. If a share is already under way, it's returned with already_open true, never replaced. " + + "Needs the server serving this phone's own store: an imported copy can't be shared.", + readOnly = false, + ) { _ -> ShareControl.start(ctx) } + + private fun shareStatus(ctx: Context) = McpTool( + name = "share_status", + title = "Share status", + description = "The share's state: preparing, waiting_for_phone, phone_connecting, waiting_for_allow (a person must tap Allow), " + + "sending, transfer_failed, done, denied, expired, closed (with the reason) or not_serving. " + + "With wait_seconds, waits up to that long for the state to change (changed tells whether it did).", + inputSchema = schema("wait_seconds" to waitProp("How long to wait for a change, 0 to ${ShareControl.MAX_WAIT_S}. Default 0.")), + ) { args -> ShareControl.status(ctx, waitArg(args, 0)) } + + private fun shareStop(ctx: Context) = McpTool( + name = "share_stop", + title = "Stop sharing", + description = "Closes the share started with share_start: its code stops working. A copy already allowed and being sent is stopped too.", + readOnly = false, + ) { _ -> ShareControl.stop(ctx) } + + // ---------------------------------------------------------------- import_start, import_status, import_cancel + + /** The import screen's limit for the name the other phone's owner sees. */ + private const val MAX_PHONE_NAME = 40 + + private fun importStartTool(ctx: Context) = McpTool( + name = "import_start", + title = "Import a store", + description = "Starts importing a copy of another phone's store, from its share code (LS-XXXX-XXXX) or its share link " + + "(shareyourapps-share://…): give exactly one. Both phones must be on the same Wi-Fi network or hotspot. Returns at once; " + + "follow it with import_status. A person on the other phone must check the check code and tap Allow, which no tool can do. " + + "The copy replaces an imported copy of a different store without asking; replacing a newer copy of the same store with an " + + "older one needs a person on this phone (import_status reports person_needed). This phone's own store is never touched. " + + "Refused while this phone is serving, starting or paused (call server_stop first), or while an import is running.", + inputSchema = schema( + "code" to JSONObject().put("type", "string").put("description", "The share code shown on the other phone, such as LS-AB12-CD34."), + "link" to JSONObject().put("type", "string").put("description", "The share link from the other phone's QR code: shareyourapps-share://
:/."), + "phone_name" to JSONObject().put("type", "string").put("maxLength", MAX_PHONE_NAME) + .put("description", "The name the other phone's owner sees, at most $MAX_PHONE_NAME characters. Default: this phone's name."), + ), + readOnly = false, + ) { args -> startImport(ctx, args) } + + private fun startImport(ctx: Context, args: JSONObject): JSONObject { + val (code, address) = importTarget(args) + val name = phoneNameArg(args) ?: ImportActivity.defaultPhoneName(ctx) + // A phone serving its own store can't import one (Appendix E.1). Starting and paused count too: either brings a server back. + val server = stateOf(ServerStatus.text, ServerStatus.url) + if (server == "serving" || server == "starting" || server == "paused") { + throw McpToolError("This phone is serving a store, or about to, and can't import one while it does. Stop the server first (server_stop).", + JSONObject().put("state", "server_running").put("server", status(ctx))) + } + if (ImportJob.snapshot.busy) throw McpToolError("An import is already running. Follow it with import_status, or end it with import_cancel.", + JSONObject().put("state", "importing").put("import", importStatus())) + if (SoundImport.busy) throw McpToolError("import_listen is still listening or joining. Wait for it, or stop it with import_cancel.", + JSONObject().put("state", "listening").put("listen", SoundImport.status())) + val why = ImportJob.start(ctx, code, name, address, byMcp = true) + if (why != null) { + if (why.startsWith("person needed: ")) throw personNeeded(why.removePrefix("person needed: ")) + throw McpToolError(why, JSONObject().put("state", "importing").put("import", importStatus())) + } + return importStatus().put("phone_name", name) + } + + /** import_start's code or link, exactly one: the normalized code, and the owner's address when a link gives it. Internal, for tests. */ + internal fun importTarget(args: JSONObject): Pair { + fun str(key: String): String? = when (val v = args.opt(key)) { + null, JSONObject.NULL -> null + is String -> v.trim().takeIf { it.isNotEmpty() } + else -> throw McpToolError("$key must be a string.") + } + val code = str("code") + val link = str("link") + if ((code == null) == (link == null)) throw McpToolError("Give either code or link: exactly one of them.") + if (code != null) { + val normalized = ShareCodes.normalize(code) + ?: throw McpToolError("That isn't a share code: LS, then two groups of four letters and digits, such as LS-AB12-CD34.") + return normalized to null + } + val (address, port, linkCode) = ShareLink.parse(link!!) + ?: throw McpToolError("That isn't a share link: it looks like shareyourapps-share://192.168.1.5:6175/.") + return linkCode to java.net.InetSocketAddress(address, port) + } + + /** import_start's phone_name: 1 to [MAX_PHONE_NAME] characters, or null when not sent. Internal, for tests. */ + internal fun phoneNameArg(args: JSONObject): String? { + val v = args.opt("phone_name") + if (v == null || v == JSONObject.NULL) return null + val s = (v as? String)?.trim() ?: throw McpToolError("phone_name must be a string.") + if (s.isEmpty()) throw McpToolError("phone_name can't be empty: leave it out to use this phone's name.") + if (s.length > MAX_PHONE_NAME) throw McpToolError("phone_name can be at most $MAX_PHONE_NAME characters.") + return s + } + + /** The import's state, for import_status and the other import tools. */ + fun importStatus(): JSONObject { + val s = ImportJob.snapshot + val q = ImportJob.question + val out = JSONObject() + .put("phase", s.phase.name.lowercase()) + .put("busy", s.busy) + .put("message", s.message) + .put("started_by", if (s.phase == ImportJob.Phase.IDLE) JSONObject.NULL else if (ImportJob.startedByMcp) "mcp" else "person") + .put("check_code", s.checkCode ?: JSONObject.NULL) + .put("store", s.storeName ?: JSONObject.NULL) + if (s.phase == ImportJob.Phase.RECEIVING || s.phase == ImportJob.Phase.DONE) { + out.put("received", s.received).put("total", s.total).put("files", s.files) + } + if (s.phase == ImportJob.Phase.DONE) { + // Checked now, not when the import ended: Wi-Fi may have been turned off or changed since. And whether the + // copy is still on this phone: it may have been removed, expired or replaced since. + val owners = appCtx?.let { ImportJob.onOwnersNetworkNow(it) } ?: s.onOwnersNetwork + val still = appCtx?.let { c -> runCatching { ImportJob.currentCopy(c)?.storeId == s.storeId }.getOrDefault(true) } ?: true + out.put("expires", s.expires?.toString() ?: JSONObject.NULL).put("on_owners_network", owners).put("copy_on_phone", still) + if (owners) out.put("note", "This phone is on the other phone's network. To serve the copy, leave it first: join another Wi-Fi network, or turn Wi-Fi off so this phone starts its own hotspot.") + } + if (s.canRetry) out.put("can_retry", true) + .put("retry", "The transfer failed partway. A person can tap Try again on the import screen while the other phone's share is open.") + if (q != null && s.busy) { + out.put("state", "person_needed") + .put("person_needed", "${q.title} ${q.message} A person must answer on this phone within 2 minutes; a notification opens the question.") + .put("question", JSONObject().put("title", q.title).put("message", q.message)) + } + // import_listen's part, once it has been used: listening, checking, joining, import_started, nothing_heard ... + if (SoundImport.state.phase != SoundImport.Phase.IDLE) out.put("listen", SoundImport.status()) + return out + } + + /** Waits up to [seconds] for the import's phase or question to change; progress alone doesn't count. Returns whether it changed. */ + private fun waitForImport(seconds: Int): Boolean { + if (seconds <= 0) return false + // import_listen's phase counts too: the loop below looks every 250 ms. + val key = { Triple(ImportJob.snapshot.phase, ImportJob.question, SoundImport.state.phase) } + val start = key() + val lock = Object() + val listener: () -> Unit = { synchronized(lock) { lock.notifyAll() } } + ImportJob.observe(listener) + try { + val deadline = System.currentTimeMillis() + seconds * 1000L + while (true) { + if (key() != start) return true + val left = deadline - System.currentTimeMillis() + if (left <= 0) return false + synchronized(lock) { lock.wait(minOf(left, 250L)) } + } + } finally { + ImportJob.remove(listener) + } + } + + @Suppress("UNUSED_PARAMETER") + private fun importStatusTool(ctx: Context) = McpTool( + name = "import_status", + title = "Import status", + description = "The import's phase: idle, finding, connecting, waiting (for the other phone's owner to tap Allow), receiving, done, " + + "failed, denied or cancelled, with a message, who started it (mcp or person), the check code the other phone's screen " + + "should show, the store's name and progress once receiving, and its expiry once done. person_needed when a person on this " + + "phone must answer a question. With wait_seconds, waits up to that long for the phase to change (changed tells whether it did).", + inputSchema = schema("wait_seconds" to waitProp("How long to wait for a change, 0 to ${ShareControl.MAX_WAIT_S}. Default 0.")), + ) { args -> + val wait = waitArg(args, 0) + val changed = waitForImport(wait) + val out = importStatus() + if (wait > 0) out.put("changed", changed) + out + } + + @Suppress("UNUSED_PARAMETER") + private fun importCancelTool(ctx: Context) = McpTool( + name = "import_cancel", + title = "Cancel the import", + description = "Cancels the import under way, as the import screen's Cancel does: nothing is kept, and the copy already on this phone stays. " + + "Reports cancelled false when no import is running.", + readOnly = false, + ) { _ -> + // Listening, checking or joining for import_listen stops too; an import it already started is cancelled below. + val stoppedListening = SoundImport.stop(ctx) + if (!ImportJob.snapshot.busy) { + if (stoppedListening) importStatus().put("cancelled", true).put("note", "Stopped listening. No import had started.") + else importStatus().put("cancelled", false).put("note", "No import is running.") + } else { + ImportJob.cancel() + importStatus().put("cancelled", true).put("note", "Cancelling. Call import_status to see it end.") + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Palette.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Palette.kt new file mode 100644 index 000000000..10109af3e --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Palette.kt @@ -0,0 +1,42 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.content.res.Configuration + +/** + * Every colour the server draws itself, in a light and a dark version, chosen from the phone's light or dark mode. + * Android's own controls follow the same setting through the app's day-and-night theme (res/values-night). + * Android recreates each screen when the mode changes, so each takes its palette once, when it starts. + * The Serve screen is the exception: it's always light, since cameras read QR codes best black on white. + */ +class Palette private constructor(val night: Boolean) { + val screen = if (night) 0xFF121418.toInt() else 0xFFE2E5EA.toInt() // behind the panels + val panelTop = if (night) 0xFF2B3038.toInt() else 0xFFFFFFFF.toInt() // a panel's face, top to bottom + val panelBottom = if (night) 0xFF1F232A.toInt() else 0xFFDCE0E6.toInt() + val cardBottom = if (night) 0xFF23272E.toInt() else 0xFFF0F2F5.toInt() // the Share and Import screens' cards + val stroke = if (night) 0xFF3B414B.toInt() else 0xFFB9C0CA.toInt() // panels' and cards' edges + val rim = if (night) 0xFF0A0C0F.toInt() else 0xFF9AA3AE.toInt() // the bevel's lower edge + val shadow = if (night) 0x99000000.toInt() else 0x55000000 + val highlight = if (night) 0x22FFFFFF else 0xE6FFFFFF.toInt() // the bevel's upper edge + val ink = if (night) 0xFFE6E8EC.toInt() else 0xFF20242B.toInt() // text + val muted = if (night) 0xFFA3AAB5.toInt() else 0xFF5B6270.toInt() + val link = if (night) 0xFFA9BCF5.toInt() else 0xFF485D92.toInt() + val onLink = if (night) 0xFF121418.toInt() else 0xFFFFFFFF.toInt() // text on a link-coloured button + val good = if (night) 0xFF81C784.toInt() else 0xFF2E7D32.toInt() + val bad = if (night) 0xFFF28B82.toInt() else 0xFFC2261A.toInt() + val danger = if (night) 0xFFF28B82.toInt() else 0xFFA1261B.toInt() // Remove this store, failures + val startFill = 0xFF2E7D32.toInt() // Start button, enabled + val stopFill = if (night) 0xFFB3261E.toInt() else 0xFFC2261A.toInt() // Stop button, enabled + val fillOff = if (night) 0xFF34383D.toInt() else 0xFFE6E8EB.toInt() // a disabled Start or Stop: grey, like Share this store... + val onFill = 0xFFFFFFFF.toInt() // text on those fills + val onFillOff = if (night) 0xFF8A9088.toInt() else 0xFF5B6270.toInt() + val copied = if (night) 0xFF81C784.toInt() else 0xFF4CAF50.toInt() // an address, just copied + val digits = if (night) 0xFF4A3F22.toInt() else 0xFFFFF3D6.toInt() // the four digits' box + val help = if (night) 0xFF3A332A.toInt() else 0xFFF5ECD7.toInt() // help: beige, or a warm dark brown + val helpInk = if (night) 0xFFEDE6D8.toInt() else 0xFF222222.toInt() + val helpEdge = if (night) 0x33FFFFFF else 0x33000000 + + companion object { + fun of(c: Context) = Palette((c.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/QrCodes.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/QrCodes.kt new file mode 100644 index 000000000..184d05d56 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/QrCodes.kt @@ -0,0 +1,31 @@ +package org.appdevforall.shareyourapps.server + +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.qrcode.QRCodeWriter +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel + +/** The Serve screen's QR codes: joining the network, and opening the store. */ +object QrCodes { + + /** + * The standard Wi-Fi QR format that phone cameras recognise, for a WPA network. Backslash, + * semicolon, comma, colon and double quote are escaped with a backslash, as the format + * requires, so a name or password containing them still joins correctly. + */ + fun wifi(ssid: String, password: String): String = "WIFI:T:WPA;S:${esc(ssid)};P:${esc(password)};;" + + private fun esc(s: String) = buildString { for (c in s) { if (c in "\\;,:\"") append('\\'); append(c) } } + + /** Black-on-white ARGB pixels, [size] × [size], with the standard four-module quiet zone, so a code sits on + * clear white, whatever the panel behind it, and scans readily. One module let the panel's grey show close around it. */ + fun pixels(text: String, size: Int): IntArray { + val hints = mapOf( + EncodeHintType.CHARACTER_SET to "UTF-8", + EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M, + EncodeHintType.MARGIN to 4, + ) + val m = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hints) + return IntArray(size * size) { i -> if (m.get(i % size, i / size)) 0xFF000000.toInt() else 0xFFFFFFFF.toInt() } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServeActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServeActivity.kt new file mode 100644 index 000000000..e4c0c7d4f --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServeActivity.kt @@ -0,0 +1,322 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Activity +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.net.wifi.WifiManager +import android.os.Bundle +import android.os.PersistableBundle +import android.text.Editable +import android.text.InputType +import android.text.TextWatcher +import android.view.Gravity +import android.view.View +import android.view.WindowManager +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.Button +import android.widget.EditText +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import org.appdevforall.shareyourapps.server.HelpUi.help + +/** + * The screen the owner holds up for buyers: step 1, a QR code to join the network; step 2, a QR + * code to open the store. Always black on white, so cameras read it easily, and it keeps the + * screen on while it's showing. + * + * On a hotspot, step 1 carries its name and password. On Wi-Fi, Android doesn't let apps read the + * joined network's password, so the owner may type it. It's held only in memory — kept across + * rotation, font-size and theme changes by the framework's retained instance, never written to + * disk — and gone when the screen closes. With no password typed, only step 2 is shown. + */ +class ServeActivity : Activity() { + + /** Kept across configuration changes, in memory only. */ + private class Typed(var ssid: String, var password: String, var done: Boolean = false) + private lateinit var typed: Typed + /** What this screen was drawn for; any change redraws it, so buyers never see stale codes. */ + private var shownUrl: String? = null + private var shownHotspot: String? = null + private val statusListener: () -> Unit = { + if (ServerStatus.url != shownUrl || ServerStatus.hotspot != shownHotspot) recreate() + } + + private lateinit var step1: LinearLayout + private var step2Label: TextView? = null + private lateinit var scroll: ScrollView + private var ownerBox: LinearLayout? = null + private var pad = 0 + private var qrSize = 0 + private val ink = Color.parseColor("#20242b") + private val muted = Color.parseColor("#6b7280") + private val copiedGreen = Color.parseColor("#4CAF50") + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + @Suppress("DEPRECATION") + // The name Android can report is a joined network's, never the phone's own Mobile hotspot's. + typed = (lastNonConfigurationInstance as? Typed) ?: Typed(if (ServerStatus.onPhoneHotspot) "" else joinedSsid(), "") + + val dm = resources.displayMetrics + val dp = dm.density + qrSize = minOf((dm.widthPixels * 0.72).toInt(), (320 * dp).toInt()) + pad = (20 * dp).toInt() + val column = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL; setPadding(pad, pad, pad, pad) + } + scroll = ScrollView(this).apply { setBackgroundColor(Color.WHITE); addView(column) } + setContentView(scroll) + SystemBars.fit(scroll) + + val storeName = getSharedPreferences(HostService.PREFS, MODE_PRIVATE).getString(HostService.PREF_STORE_NAME, null) ?: "Share Your Apps" + column.addView(text(storeName, 26f, bold = true)) + val url = ServerStatus.url + shownUrl = url + shownHotspot = ServerStatus.hotspot + if (url == null) { + column.addView(text("The store isn't being served right now. Start the server, or publish from the Share Your Apps plugin; the codes appear here as soon as it's serving.", 16f).apply { setPadding(0, pad, 0, pad) }) + column.addView(Button(this).help("serve.close").apply { text = "Close"; setOnClickListener { finish() } }) + return + } + + step1 = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL } + val h = Hotspot.info + if (h == null) { + // Owner-facing, so it comes first: the joined network's name and, optionally, its password. + ownerBox = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(pad / 2, pad / 2, pad / 2, pad / 2) + background = GradientDrawable().apply { setColor(Color.parseColor("#eef0f3")); cornerRadius = pad / 2f } + } + column.addView(ownerBox, LinearLayout.LayoutParams(-1, -2).apply { topMargin = pad / 2; bottomMargin = pad }) + renderOwnerBox() + } + column.addView(step1) + if (h != null) showStep1(h.ssid, h.password, showPassword = true) else refreshStep1() + + step2Label = text("", 20f, bold = true).apply { setPadding(0, pad, 0, pad / 2) } + column.addView(step2Label) + numberSteps() + column.addView(qr(url)) + column.addView(copyable(url, url).apply { setPadding(0, pad / 2, 0, 0) }) + // These networks have no internet, so a buyer's phone may send the browser over mobile data instead; + // airplane mode, then Wi-Fi, leaves Wi-Fi the only way out. Airplane mode is also the easiest switch to find. + if (h != null || ServerStatus.onPhoneHotspot) column.addView(text( + "This network has no internet. If a buyer's phone can't open the store, have them turn on airplane mode, then turn Wi-Fi back on. " + + "Remind them to turn airplane mode off afterwards.", 14f) + .apply { setPadding(0, pad, 0, 0) }) + column.addView(Button(this).help("serve.done").apply { text = "Done"; setOnClickListener { finish() } }, + LinearLayout.LayoutParams(-2, -2).apply { topMargin = pad }) + } + + @Suppress("OVERRIDE_DEPRECATION") + override fun onRetainNonConfigurationInstance(): Any = typed + + override fun onResume() { super.onResume(); ServerStatus.observe(statusListener) } + override fun onPause() { super.onPause(); ServerStatus.remove(statusListener) } + + private fun refreshStep1() { + if (typed.ssid.isNotBlank() && typed.password.isNotEmpty()) showStep1(typed.ssid, typed.password, showPassword = false) + else { + step1.removeAllViews() + if (typed.ssid.isNotBlank()) step1.addView(text("Buyers need to be on the Wi-Fi network “${typed.ssid}” first.", 15f).apply { setTextColor(muted) }) + } + numberSteps() + } + + /** "2. Open the store" when there's a step 1 code above it; just "Open the store" otherwise. */ + private fun numberSteps() { + val hasJoinCode = step1.childCount > 1 + step2Label?.text = if (hasJoinCode) "2. Open the store" else "Open the store" + } + + private fun showStep1(ssid: String, password: String, showPassword: Boolean) { + step1.removeAllViews() + step1.addView(text("1. Join this Wi-Fi network", 20f, bold = true).apply { setPadding(0, 0, 0, qrSize / 20) }) + step1.addView(qr(QrCodes.wifi(ssid, password))) + // A hotspot's password is the app's own, and buyers may have to type it. A home + // network's password stays off the screen, and off the clipboard: the code carries it. + val gap = qrSize / 20 + val network = copyable("Network: $ssid", ssid) + if (!showPassword) { + step1.addView(network.apply { setPadding(0, gap, 0, 0) }) + return + } + val pass = copyable("Password: $password", password, sensitive = true) + // The two lines, a brace as tall as both, and an icon that copies both. + network.gravity = Gravity.START + pass.gravity = Gravity.START + val lines = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; addView(network); addView(pass) } + val dp = resources.displayMetrics.density + val row = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL; setPadding(0, gap, 0, 0) + addView(lines) + addView(BraceView(this@ServeActivity, ink), LinearLayout.LayoutParams((14 * dp).toInt(), LinearLayout.LayoutParams.MATCH_PARENT).apply { + marginStart = (8 * dp).toInt(); marginEnd = (6 * dp).toInt() + }) + addView(CopyIconView(this@ServeActivity, ink).apply { + contentDescription = "Copy the network name and password" + setOnClickListener { copy("$ssid\n$password", sensitive = true); flash(network); flash(pass) } + }, LinearLayout.LayoutParams((44 * dp).toInt(), (44 * dp).toInt())) + } + step1.addView(row) + } + + /** A line that copies [value] when tapped, and flashes a green "Copied!" in its place. */ + private fun copyable(label: String, value: String, sensitive: Boolean = false) = text(label, 16f).apply { + tag = label + setOnClickListener { copy(value, sensitive); flash(this) } + } + + private fun copy(value: String, sensitive: Boolean) { + val clip = ClipData.newPlainText("Share Your Apps", value) + // Hides a password from the clipboard preview on Android 13+; ignored before that. + if (sensitive) clip.description.extras = PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) } + getSystemService(ClipboardManager::class.java).setPrimaryClip(clip) + } + + private fun flash(v: TextView) { + v.text = "Copied!" + v.setTextColor(copiedGreen) + v.animate().alpha(0.2f).setDuration(120).withEndAction { v.animate().alpha(1f).setDuration(120) } + v.postDelayed({ v.text = v.tag as String; v.setTextColor(ink) }, 1200) + } + + /** The Wi-Fi fields while they're being filled in; afterwards, one line with a way back. */ + private fun renderOwnerBox() { + val box = ownerBox ?: return + box.removeAllViews() + if (typed.done) { + box.addView(text("Joining “${typed.ssid}” · Change", 14f).apply { + setTextColor(muted) + setOnClickListener { typed.done = false; renderOwnerBox() } + }) + return + } + val phone = ServerStatus.onPhoneHotspot + box.addView(text(if (phone) "For you, not buyers: to show a code for joining your Mobile hotspot, enter its name and password, from Settings. They aren't saved." + else "For you, not buyers: to show a code for joining this Wi-Fi network, enter its password. It isn't saved.", 13f).apply { setTextColor(muted) }.help("server.serve_wifi")) + val problem = text("", 13f).apply { setTextColor(Color.parseColor("#f44336")); visibility = View.GONE } + box.addView(field(if (phone) "Mobile hotspot name" else "Wi-Fi network name", typed.ssid, password = false, onDone = null) { typed.ssid = it; refreshStep1() }) + box.addView(field(if (phone) "Mobile hotspot password" else "Wi-Fi password", typed.password, password = true, onDone = { finishEntry(problem) }) { typed.password = it; refreshStep1() }) + box.addView(problem) + box.addView(Button(this).help("serve.show_join").apply { text = "Show the join code"; isAllCaps = false; setOnClickListener { finishEntry(problem) } }) + } + + /** Closes the keyboard, collapses the fields, and brings the codes into view. */ + private fun finishEntry(problem: TextView) { + if (typed.ssid.isBlank() || typed.password.isEmpty()) { + problem.text = "Enter both the network name and its password." + problem.visibility = View.VISIBLE + return + } + getSystemService(InputMethodManager::class.java).hideSoftInputFromWindow(window.decorView.windowToken, 0) + typed.done = true + renderOwnerBox() + refreshStep1() + scroll.post { scroll.smoothScrollTo(0, 0) } + } + + private fun field(hint: String, value: String, password: Boolean, onDone: (() -> Unit)?, onChange: (String) -> Unit) = EditText(this).apply { + this.hint = hint + setText(value) + setTextColor(ink) + setSingleLine() + // The keyboard's action key: Next on the name, Done on the password, which shows the code. + imeOptions = if (onDone != null) EditorInfo.IME_ACTION_DONE else EditorInfo.IME_ACTION_NEXT + if (password) { + // Kept out of the keyboard's learning and suggestions; the password type also blocks copying. + inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + imeOptions = imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING + } + if (onDone != null) setOnEditorActionListener { _, action, _ -> + if (action == EditorInfo.IME_ACTION_DONE) { onDone(); true } else false + } + addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {} + override fun afterTextChanged(s: Editable?) { onChange(s?.toString().orEmpty()) } + }) + } + + private fun qr(content: String) = ImageView(this).apply { + setImageBitmap(Bitmap.createBitmap(QrCodes.pixels(content, qrSize), qrSize, qrSize, Bitmap.Config.ARGB_8888)) + layoutParams = LinearLayout.LayoutParams(qrSize, qrSize) + contentDescription = "QR code" + } + + private fun text(t: String, size: Float, bold: Boolean = false) = TextView(this).apply { + text = t; textSize = size; setTextColor(ink); gravity = Gravity.CENTER + if (bold) setTypeface(typeface, Typeface.BOLD) + } + + /** + * The joined network's name, when Android will tell us: reading it needs location access, + * which this app only holds on Android 12 and earlier. Otherwise the owner types it. + */ + private fun joinedSsid(): String = try { + @Suppress("DEPRECATION") + val raw = (applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager).connectionInfo?.ssid + raw?.trim('"')?.takeIf { it.isNotBlank() && it != "" } ?: "" + } catch (e: Exception) { "" } +} + +/** A "}" drawn to exactly the height it's given, so it spans the lines beside it. */ +private class BraceView(ctx: Context, color: Int) : View(ctx) { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + this.color = color; style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND + strokeWidth = 2 * ctx.resources.displayMetrics.density + } + private val path = Path() + + override fun onDraw(canvas: Canvas) { + val s = paint.strokeWidth + val w = width.toFloat() - s + val h = height.toFloat() + val m = w / 2 + path.reset() + path.moveTo(s, s) + path.quadTo(m, s, m, h * 0.22f) + path.lineTo(m, h * 0.40f) + path.quadTo(m, h / 2, w, h / 2) // the point + path.quadTo(m, h / 2, m, h * 0.60f) + path.lineTo(m, h * 0.78f) + path.quadTo(m, h - s, s, h - s) + canvas.drawPath(path, paint) + } +} + +/** The familiar copy symbol: two overlapping rounded squares. */ +private class CopyIconView(ctx: Context, color: Int) : View(ctx) { + private val dp = ctx.resources.displayMetrics.density + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = 2 * dp } + private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE; style = Paint.Style.FILL } + + init { isClickable = true; isFocusable = true } + + override fun onDraw(canvas: Canvas) { + val side = 15 * dp + val shift = 5 * dp + val r = 3 * dp + val x = (width - side - shift) / 2f + val y = (height - side - shift) / 2f + val back = RectF(x + shift, y, x + shift + side, y + side) + val front = RectF(x, y + shift, x + side, y + shift + side) + canvas.drawRoundRect(back, r, r, line) + canvas.drawRoundRect(front, r, r, fill) // covers the back square where they overlap + canvas.drawRoundRect(front, r, r, line) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServerService.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServerService.kt new file mode 100644 index 000000000..d1be845fa --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ServerService.kt @@ -0,0 +1,239 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Service +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import android.os.Process +import android.os.RemoteException +import java.net.InetAddress +import kotlin.concurrent.thread + +/** + * Runs in its own process (android:process=":server"). Serves one Store directory for its + * whole life: the main process kills this process and starts a fresh one for every change, + * so nothing leaks from one run to the next. + */ +class ServerService : Service() { + + private var server: HttpServer? = null + private var log: StoreLog? = null + private var serving = "" + @Volatile private var gen = -1 + // The store being served, for sharing: where it is, its name, and the address buyers use. + private var servingDir: java.io.File? = null + private var servingName = "" + private var externalAddress = "" + private var share: ShareHost? = null + private var servingCopy = false + private var startReply: Messenger? = null + private val main = Handler(Looper.getMainLooper()) + + /** + * While a copy is served, once a minute: is it due (Appendix E.5)? Then stop taking new + * connections, let downloads under way finish, for up to 10 minutes, delete it, and say so. + */ + private val expiryCheck = object : Runnable { + override fun run() { + val dir = servingDir ?: return + val copy = CopyExpiry.copies(dir.parentFile ?: return).firstOrNull { it.storeId == dir.name } ?: return + val status = CopyExpiry.status(copy, ExpiryClock(CopyExpiry.clockFile(filesDir))) + if (status == ExpiryClock.Status.OK) { main.postDelayed(this, 60_000); return } + val setBack = status == ExpiryClock.Status.CLOCK_SET_BACK + log?.status("server", "the copy of ${copy.storeName} expired: not taking new connections, and deleting it once downloads under way finish") + server?.stopAccepting() + val deadline = System.currentTimeMillis() + 10 * 60_000L + main.post(object : Runnable { + override fun run() { + if ((server?.sending ?: 0) > 0 && System.currentTimeMillis() < deadline) { main.postDelayed(this, 1000); return } + server?.stop(); server = null + CopyExpiry.delete(dir.parentFile!!, copy, setBack) + log?.status("server", "deleted the expired copy of ${copy.storeName}") + send(startReply, Message.obtain(null, Ipc.MSG_COPY_EXPIRED).apply { + data = Bundle().apply { putString(Ipc.KEY_STORE_NAME, copy.storeName); putInt(Ipc.KEY_GEN, gen) } + }) + } + }) + } + } + private var discovery: ShareDiscovery.Listener? = null + /** The compressor's thread; a share waits until it's done, since it changes the store's files. */ + private var compressor: Thread? = null + private var shareWaiting = false + + private val handler = object : Handler(Looper.getMainLooper()) { + override fun handleMessage(msg: Message) { + when (msg.what) { + Ipc.MSG_START -> { + val data = Bundle(msg.data) + val reply = msg.replyTo + thread(name = "start") { start(data, reply) } // binding is network work: keep it off the main thread + } + Ipc.MSG_STOP -> stopGracefully(msg.data.getString(Ipc.KEY_REASON) ?: "no reason given", msg.replyTo) + Ipc.MSG_LOG -> msg.data.getString(Ipc.KEY_LINE)?.let { log?.statusLine(it) } + Ipc.MSG_SHARE_OPEN -> { openShare(); replyShare(msg.replyTo) } + Ipc.MSG_SHARE_POLL -> replyShare(msg.replyTo) + Ipc.MSG_SHARE_ALLOW -> { + val ms = msg.data.getLong(Ipc.KEY_SHARE_COPY_EXPIRES, -1) + val expires = if (ms < 0) null else java.time.Instant.ofEpochMilli(ms) + share?.let { h -> + h.allow(expires) + log?.status("share", "allowed ${h.phoneName()} a copy, " + (expires?.let { "expiring $it" } ?: "never expiring")) + } + replyShare(msg.replyTo) + } + Ipc.MSG_SHARE_DENY -> { share?.let { h -> h.deny(); log?.status("share", "denied ${h.phoneName()} a copy") }; replyShare(msg.replyTo) } + Ipc.MSG_SHARE_CLOSE -> closeShare() + } + } + } + private val messenger = Messenger(handler) + + override fun onBind(intent: Intent): IBinder = messenger.binder + + /** + * Logs why the server is stopping and closes its sockets, then tells the main process it + * can kill this process. Only a server that was actually serving gets a "stopped" line; + * a failed start has already logged why. + */ + private fun stopGracefully(reason: String, reply: Messenger?) { + main.removeCallbacksAndMessages(null) + closeShare() + val s = server + server = null + if (s != null) { + s.stop() + log?.status("server", "stopped serving $serving: $reason") + } + log?.close() + send(reply, Message.obtain(null, Ipc.MSG_STOPPED, Process.myPid(), 0).apply { + data = Bundle().apply { putInt(Ipc.KEY_GEN, gen) } + }) + } + + /** The process ends when the main process unbinds or kills it; there's nothing worth keeping. */ + override fun onDestroy() { + closeShare() + server?.stop() + log?.close() + Process.killProcess(Process.myPid()) + } + + private fun start(data: Bundle, reply: Messenger?) { + gen = data.getInt(Ipc.KEY_GEN, -1) + val name = data.getString(Ipc.KEY_DIR).orEmpty() + val port = data.getInt(Ipc.KEY_PORT, Store.DEFAULT_PORT) + val l = StoreLog(Store.logDir(this), data.getLong(Ipc.KEY_LOG_LIMIT, Store.DEFAULT_LOG_LIMIT)) + log = l + data.getStringArrayList(Ipc.KEY_LOG_LINES)?.forEach { l.statusLine(it) } + + fun fail(error: String) { + l.status("server", "failed to start: $error") + send(reply, Message.obtain(null, Ipc.MSG_FAILED, Process.myPid(), 0).apply { + this.data = Bundle().apply { putString(Ipc.KEY_ERROR, error); putInt(Ipc.KEY_GEN, gen) } + }) + } + + // An imported copy lives in this app's private storage; a published store in shared storage. + val copyPath = data.getString(Ipc.KEY_COPY_PATH) + val dir = if (copyPath != null) { + val f = java.io.File(copyPath) + val imported = java.io.File(filesDir, "imported").canonicalPath + java.io.File.separator + if (!f.canonicalPath.startsWith(imported) || !f.isDirectory) return fail("the imported copy isn't where it should be") + f + } else { + if (!Store.validName(name)) return fail("\"$name\" isn't a Store directory name (Store_ and 8 digits)") + if (!Store.hasStorageAccess(this)) return fail("storage access hasn't been granted") + Store.dir(name).also { if (!it.isDirectory) return fail("${it.path} doesn't exist") } + } + servingCopy = copyPath != null + startReply = reply + val external = data.getString(Ipc.KEY_BIND_ADDRESS)?.let { InetAddress.getByName(it) } + ?: pickExternalAddress(systemInterfaces()) + ?: return fail("not connected to a Wi-Fi network") + + val auth = Auth( + data.getString(Ipc.KEY_PIN)?.takeIf { it.isNotEmpty() }, + data.getString(Ipc.KEY_SECRET).orEmpty(), + data.getString(Ipc.KEY_TOKEN)?.takeIf { it.isNotEmpty() }, + ) + val storeName = data.getString(Ipc.KEY_STORE_NAME) ?: "Share Your Apps" + val s = HttpServer(dir, listOf(InetAddress.getByName("127.0.0.1"), external), port, l, auth, storeName) + try { + s.start() + } catch (e: Exception) { + return fail(e.message ?: e.toString()) + } + server = s + serving = name + servingDir = dir; servingName = storeName; externalAddress = external.hostAddress ?: "" + val address = external.hostAddress ?: "?" + l.status("server", "serving ${if (servingCopy) "an imported copy of $name" else name} on $address:${s.boundPort}" + if (auth.pin != null) " with a PIN" else "") + compressor = Compressor(dir, l).start() + if (servingCopy) main.post(expiryCheck) + send(reply, Message.obtain(null, Ipc.MSG_STARTED, Process.myPid(), s.boundPort).apply { + this.data = Bundle().apply { putString(Ipc.KEY_ADDRESS, address); putInt(Ipc.KEY_GEN, gen) } + }) + } + + /** A new share code for the store being served, replacing any share already showing. */ + private fun openShare() { + val s = server ?: return + val dir = servingDir ?: return + if (compressor?.isAlive == true) { shareWaiting = true; return } // opened once it's done + shareWaiting = false + if (servingCopy) { log?.status("share", "refused to share an imported copy: copies can't be passed on"); return } + closeShare() + val key = StoreKeyFile.loadOrCreate(java.io.File(filesDir, "share")) + val h = ShareHost(dir, servingName, key) + h.appApk = java.io.File(applicationInfo.sourceDir) // this app's own installed APK, for a phone without it + share = h; s.share = h + discovery = try { + ShareDiscovery.Listener({ share }, s.boundPort).also { it.start() } + } catch (e: Exception) { + log?.status("share", "can't answer typed codes, only QR codes: ${e.message}"); null + } + log?.status("share", "showing a share code for $servingName") + } + + private fun closeShare() { + shareWaiting = false + discovery?.close(); discovery = null + server?.share = null + share?.close(); share = null + } + + /** The share's state, for the share screen. */ + private fun replyShare(to: Messenger?) { + val b = Bundle() + val h = share + val s = server + if (shareWaiting && compressor?.isAlive != true) openShare() + when { + s == null -> b.putString(Ipc.KEY_SHARE_STATE, "NONE") + shareWaiting -> b.putString(Ipc.KEY_SHARE_STATE, "PREPARING") + h == null -> { b.putString(Ipc.KEY_SHARE_STATE, "ERROR") + b.putString(Ipc.KEY_SHARE_ERROR, if (servingCopy) "This phone is serving a copy of someone else's store. Copies can't be passed on." else "No share is open.") } + else -> { + b.putString(Ipc.KEY_SHARE_STATE, h.state().name) + b.putString(Ipc.KEY_SHARE_CODE, h.displayCode) + b.putString(Ipc.KEY_SHARE_LINK, ShareLink.make(externalAddress, s.boundPort, h.code)) + b.putString(Ipc.KEY_SHARE_APP_URL, "http://$externalAddress:${s.boundPort}/share/app") + b.putLong(Ipc.KEY_SHARE_CODE_EXPIRES, h.expiresAt) + b.putString(Ipc.KEY_SHARE_STORE, h.storeName) + b.putString(Ipc.KEY_SHARE_PHONE, h.phoneName()) + h.pending()?.let { b.putString(Ipc.KEY_SHARE_CHECK, it.checkCode) } + b.putInt(Ipc.KEY_SHARE_FAILURES, h.failures()) + } + } + send(to, Message.obtain(null, Ipc.MSG_SHARE_STATE).apply { data = b }) + } + + private fun send(to: Messenger?, msg: Message) { + try { to?.send(msg) } catch (e: RemoteException) { } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareActivity.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareActivity.kt new file mode 100644 index 000000000..a280d22b6 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareActivity.kt @@ -0,0 +1,436 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Activity +import android.app.DatePickerDialog +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.graphics.Bitmap +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.os.Bundle +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import android.os.RemoteException +import android.view.Gravity +import android.view.View +import android.view.WindowManager +import android.widget.Button +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.RadioButton +import android.widget.RadioGroup +import android.widget.ScrollView +import android.widget.TextView +import java.text.DateFormat +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZonedDateTime +import java.util.Date +import org.appdevforall.shareyourapps.server.HelpUi.help + +/** + * Sharing a copy of the store with another seller (design, Appendix E.2; screens 2 and 3). Binds + * to the server process, where the share lives beside the HTTP server, asks it what's happening + * twice a second, and shows: the code and QR while waiting; "Allow a copy?" once a phone has asked, + * with the check code and the copy's expiry; then the outcome. + * + * A share already under way when the screen opens — one an MCP client started, opened from its + * "asks for a copy" notification, or one this screen showed before — is joined, not replaced, so its + * code keeps working. Otherwise the screen opens a share of its own. Leaving the screen closes only a + * share it opened itself; Cancel closes either kind. Allow and Deny are only ever sent from here, by a person. + * The screen stays on while it's open, since a server paused for a dark screen can't share. Play sound plays the + * code as tones, for a phone that taps Listen; they stop when the share moves on or the screen closes. + */ +class ShareActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private var server: Messenger? = null + private var bound = false + /** Whether this screen has chosen its share: joined one already under way, or opened its own. Kept across rotation. */ + private var opened = false + /** + * This screen opened the share, so leaving it closes the share. A share it joined — one an MCP client + * started, opened from the "asks for a copy" notification — stays open when the screen is left; + * only Cancel, a deliberate choice, closes it. + */ + private var ownShare = false + private var lastState = "" + /** Play sound: the player while the code plays, and its button, which reads Stop sound meanwhile. */ + private var player: SoundIo.Player? = null + private var playButton: Button? = null + private lateinit var body: LinearLayout + private val pad by lazy { (16 * resources.displayMetrics.density).toInt() } + + // The expiry choice, kept while the owner decides. + private var choice = MONTH + private var chosenDate: LocalDate = LocalDate.now().plusMonths(1) + + private val replies = Messenger(Handler(Looper.getMainLooper()) { msg -> + if (msg.what == Ipc.MSG_SHARE_STATE) show(msg.data); true + }) + + private val conn = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + server = Messenger(service) + // Not opened yet: the first poll's answer decides, in show(), whether to join a share + // already under way or open a new one. + main.post(poll) + } + override fun onServiceDisconnected(name: ComponentName) { + server = null + showMessage("The server stopped", "Sharing stopped with it. Start the server, then share again.") + } + } + + private val poll = object : Runnable { + override fun run() { if (server != null) { send(Ipc.MSG_SHARE_POLL); main.postDelayed(this, 500) } } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // A rotation recreates this screen: the share it opened or joined carries on, rather than a new one opening. + opened = savedInstanceState?.getBoolean("opened") == true + ownShare = savedInstanceState?.getBoolean("ownShare") == true + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(pad, pad, pad, pad) } + setContentView(ScrollView(this).apply { setBackgroundColor(pal.screen); addView(body) }.also { SystemBars.fit(it) }) + title = "Share this store" + showMessage("Share this store", "Connecting to the server…") + // No BIND_AUTO_CREATE: if the server isn't running, it isn't started just for this. + bound = bindService(Intent(this, ServerService::class.java), conn, 0) + main.postDelayed({ + if (server == null) showMessage("The server isn't running", "Start the server in Manage server, then share again.") + }, 1500) + } + + override fun onSaveInstanceState(out: Bundle) { + super.onSaveInstanceState(out); out.putBoolean("opened", opened); out.putBoolean("ownShare", ownShare) + } + + override fun onDestroy() { + // Nothing plays off the screen: leaving it, or rotating, stops the tones. The "played" line is sent now, + // while the connection to the server is still open, rather than when the player thread ends. + val wasPlaying = player != null + stopSound() + if (wasPlaying) logPlayedNow?.invoke() + logPlayedNow = null + main.removeCallbacksAndMessages(null) + // Only leaving the screen closes the share, and only one this screen opened; a rotation, or another + // app on top, doesn't. A share it joined (an MCP client's) stays open: Cancel closes that one. + if (isFinishing && !isChangingConfigurations && ownShare) send(Ipc.MSG_SHARE_CLOSE) + if (bound) try { unbindService(conn) } catch (e: IllegalArgumentException) { } + super.onDestroy() + } + + private fun send(what: Int, data: Bundle? = null) { + val m = server ?: return + try { m.send(Message.obtain(null, what).apply { replyTo = replies; if (data != null) this.data = data }) } catch (e: RemoteException) { } + } + + /** Redraws only when the state changes, so a choice being made isn't reset by the next poll. */ + private fun show(b: Bundle) { + val state = b.getString(Ipc.KEY_SHARE_STATE) ?: return + // The first answer decides: a share still under way (an MCP client's, say, opened from its + // "asks for a copy" notification) is joined, not replaced, so its code keeps working. Anything + // else gets a new share of this screen's own. Not serving: nothing to open. + if (!opened && state != "NONE") { + opened = true + if (state !in UNDER_WAY) { + ownShare = true; lastState = "" + send(Ipc.MSG_SHARE_OPEN) + return + } + } + val key = state + "|" + (b.getString(Ipc.KEY_SHARE_CHECK) ?: "") + "|" + b.getInt(Ipc.KEY_SHARE_FAILURES) + if (state == "OPEN") refreshCountdown(b.getLong(Ipc.KEY_SHARE_CODE_EXPIRES)) + if (key == lastState) return + lastState = key + // The other phone has connected, or the share ended: the tones have done their job. + if (state != "OPEN") stopSound() + val store = b.getString(Ipc.KEY_SHARE_STORE).orEmpty() + val phone = b.getString(Ipc.KEY_SHARE_PHONE).orEmpty() + when (state) { + "OPEN" -> showCode(b.getString(Ipc.KEY_SHARE_CODE).orEmpty(), b.getString(Ipc.KEY_SHARE_LINK).orEmpty(), b.getLong(Ipc.KEY_SHARE_CODE_EXPIRES), + b.getString(Ipc.KEY_SHARE_APP_URL)) + "PREPARING" -> showMessage("Share this store", "Getting the store ready to share… This takes a moment after publishing.") + "ASKED" -> showMessage("A phone is connecting", "Waiting for the other phone to finish connecting…") + "REVEALED" -> showAllow(store, phone, b.getString(Ipc.KEY_SHARE_CHECK).orEmpty()) + "ALLOWED" -> if (b.getInt(Ipc.KEY_SHARE_FAILURES) > 0) + showMessage("The copy didn't arrive", "The transfer to $phone didn't finish. $phone can try again while this screen stays open.") + else showMessage("Sending the copy", "Sending $store to $phone. Keep this screen open until it's done.") + "DONE" -> showMessage("Copy sent", "$phone has a copy of $store.", done = true) + "DENIED" -> showMessage("Request denied", "$phone didn't get a copy.", done = true, again = true) + "CLOSED" -> showMessage("This share has ended", "Its code expired, or was used wrongly too often. Share again for a new code.", done = true, again = true) + "NONE" -> showMessage("The server isn't serving", "Start the server in Manage server, then share again.", done = true) + else -> showMessage("Can't share", b.getString(Ipc.KEY_SHARE_ERROR) ?: "Something went wrong.", done = true, again = true) + } + } + + // ---- screen 2: the code and QR ---- + private var countdown: TextView? = null + + private fun showCode(code: String, link: String, expiresAt: Long, appUrl: String?) { + body.removeAllViews() + body.addView(card( + heading("Share this store").help("share.code"), + text("On the other phone, open Share Your Apps Server and tap Import a store. Then scan this code with the other phone's camera, or type the code below into it."), + qr(link), + text("Or type this code", 13f, center = true), + codeRow(code), + soundButton(code, link), + text("Both phones must be on the same Wi-Fi network or hotspot. You'll be asked to allow the request before anything is sent.", 14f), + text("", 13f).apply { visibility = View.GONE }.also { countdown = it }, + )) + // A phone that doesn't have the app yet can get it from this one first. + if (appUrl != null) body.addView(card( + text("No Share Your Apps Server on the other phone?", 15f, bold = true).help("share.app"), + text("Scan this first with the other phone's camera, to download Share Your Apps Server from this phone and install it on the other phone. Then scan the code above.", 14f), + qr(appUrl, 140), + text("Or open this link in the other phone's browser:", 13f, center = true), + copyRow(appUrl, 18f, clipLabel = "Share Your Apps Server download link", description = "Copy the link", + copied = "Link copied", sensitive = false, lines = 2), + )) + // Cancel always ends the share, a joined one too: it's the person's clear choice. Leaving by Back doesn't, for a joined share. + body.addView(button("Cancel") { send(Ipc.MSG_SHARE_CLOSE); finish() }.help("share.cancel")) + refreshCountdown(expiresAt) + } + + /** The code, with a button beside it that copies it for pasting into a message. */ + private fun codeRow(code: String) = copyRow(code, 30f, clipLabel = "Share code", description = "Copy the code", + copied = "Code copied", sensitive = true) + + // ---- Play sound ---- + /** Counts players started and stopped, so a finished player's callback can't reset a newer one's button. */ + private var soundRun = 0 + + /** Play sound, or Stop sound while the tones play. */ + private fun soundButton(code: String, link: String): Button = + button(if (player != null) "Stop sound" else "Play sound") { if (player != null) stopSound() else playSound(code, link) } + .help("share.sound").also { playButton = it } + + /** + * Logs the playing player's "played" line at once, as stopped early. onDestroy calls it while the connection to + * the server is still open; the player's own callback, coming later, then logs nothing. + */ + private var logPlayedNow: (() -> Unit)? = null + + private fun playSound(code: String, link: String) { + val payload = soundPayload(code, link) ?: return toast("Couldn't turn this code into sound.") + val low = SoundIo.volumeLow(this) + if (low) toast("The media volume is low: turn it up so the other phone hears the tones.") + val run = ++soundRun + var logged = false + lateinit var p: SoundIo.Player + p = SoundIo.Player(payload.encode(), { error -> + if (run == soundRun) { player = null; playButton?.text = "Play sound" } + if (error != null) toast(error) + if (!logged) { logged = true; logSound(SoundLog.played(p.burstsPlayed, p.bursts, p.stoppedEarly, low, payload.ownHotspot, error)) } + main.post { countdown?.text = ""; countdown?.visibility = View.GONE } // Clear and hide countdown when sound ends + }, { played -> + // Update the countdown on the main thread + main.post { + val remainingAttempts = p.bursts - played + if (remainingAttempts > 0) { + countdown?.text = attemptsText(remainingAttempts) + countdown?.visibility = View.VISIBLE + } else { + countdown?.text = ""; countdown?.visibility = View.GONE // Clear and hide when done + } + } + }) + logPlayedNow = { if (!logged) { logged = true; logSound(SoundLog.played(p.burstsPlayed, p.bursts, true, low, payload.ownHotspot, null)) } } + player = p.start() + playButton?.text = "Stop sound" + // Initial countdown display + countdown?.text = attemptsText(p.bursts) + countdown?.visibility = View.VISIBLE + } + + /** The countdown line: each attempt is one burst of the code. */ + private fun attemptsText(n: Int) = "Playing sound... ($n ${if (n == 1) "attempt" else "attempts"} remaining)" + + /** The server process owns the log file while it serves, so the line goes to it, over the share's connection. */ + private fun logSound(message: String) { + val line = SoundLog.line(message) + android.util.Log.i("ShareYourAppsSound", line) + send(Ipc.MSG_LOG, Bundle().apply { putString(Ipc.KEY_LINE, line) }) + } + + private fun stopSound() { + soundRun++ + player?.stop(); player = null + playButton?.text = "Play sound" + countdown?.visibility = View.GONE + } + + /** + * What the tones carry: the code and the server's address from the share link; on this phone's own hotspot, + * also its name and password. On other Wi-Fi, neither name nor password (Hotspot.info is null there). + */ + private fun soundPayload(code: String, link: String): SoundPayload? { + val normalized = ShareCodes.normalize(code) ?: return null + val parsed = ShareLink.parse(link) + val address = parsed?.let { try { java.net.InetAddress.getByName(it.first) as? java.net.Inet4Address } catch (e: Exception) { null } } + val port = if (address != null && parsed != null) parsed.second else 0 + val hotspot = Hotspot.info + fun fits(s: String) = s.isNotEmpty() && s.toByteArray(Charsets.UTF_8).size <= SoundPayload.MAX_FIELD + val ssid = hotspot?.ssid?.takeIf { it != "?" && fits(it) } + val password = hotspot?.password?.takeIf { ssid != null && fits(it) } + return try { SoundPayload(normalized, if (port > 0) address else null, port, hotspot != null, ssid, password) } + catch (e: IllegalArgumentException) { null } + } + + private fun toast(t: String) { android.widget.Toast.makeText(this, t, android.widget.Toast.LENGTH_LONG).show() } + + /** + * A QR code's text, with a button beside it that copies it. [sensitive] keeps it out of the clipboard preview, + * for the share code; the app's download link is fine to show. [lines] is how many lines the text may take: one for + * the share code; two for the download link, which on a narrow phone doesn't fit on one even at the smallest size, + * and was cut off, showing only the tops of its second line's characters as dots. + */ + private fun copyRow(value: String, maxSp: Float, clipLabel: String, description: String, copied: String, sensitive: Boolean, lines: Int = 1) = LinearLayout(this).apply { + gravity = Gravity.CENTER + // The text takes the width the copy button leaves, shrinking to fit rather than overflowing. + addView(text(value, maxSp, bold = true, center = true).apply { + setTextIsSelectable(true); typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD); maxLines = lines + setAutoSizeTextTypeUniformWithConfiguration(minOf(12, maxSp.toInt()), maxSp.toInt(), 1, android.util.TypedValue.COMPLEX_UNIT_SP) + }, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) + val size = (48 * resources.displayMetrics.density).toInt() + addView(android.widget.ImageButton(this@ShareActivity).apply { + setImageDrawable(CopyIcon(pal.ink)) + val inset = (12 * resources.displayMetrics.density).toInt(); setPadding(inset, inset, inset, inset) + scaleType = ImageView.ScaleType.FIT_CENTER + val ripple = android.util.TypedValue(); context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, ripple, true) + setBackgroundResource(ripple.resourceId) + contentDescription = description + setOnClickListener { + // Sensitive: Android 13+ hides it from the clipboard preview, and sync services and keyboards + // generally don't pass it on. The share code is what lets a phone ask for a copy, so it shouldn't travel far. + val clip = android.content.ClipData.newPlainText(clipLabel, value) + if (sensitive) clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) } + (getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager).setPrimaryClip(clip) + // Android 13 and later confirm a copy themselves. + if (android.os.Build.VERSION.SDK_INT < 33) android.widget.Toast.makeText(this@ShareActivity, copied, android.widget.Toast.LENGTH_SHORT).show() + } + }, LinearLayout.LayoutParams(size, size).apply { marginStart = pad / 2 }) + } + + private fun refreshCountdown(expiresAt: Long) { + val minutes = ((expiresAt - System.currentTimeMillis()) / 60_000 + 1).coerceAtLeast(0) + if (player == null) { + countdown?.text = "This code works for one phone, for ${if (minutes == 1L) "1 more minute" else "$minutes more minutes"}." + countdown?.visibility = View.VISIBLE + } + } + + // ---- screen 3: Allow a copy? ---- + private fun showAllow(store: String, phone: String, check: String) { + countdown = null + body.removeAllViews() + val month = LocalDate.now().plusMonths(1) + val dateButton = Button(this).help("share.expiry").apply { text = shortDate(chosenDate); isEnabled = choice == DATE } + val group = RadioGroup(this).apply { + fun option(id: Int, label: String) = addView(RadioButton(this@ShareActivity).apply { this.id = id; text = label; textSize = 16f; minHeight = (44 * resources.displayMetrics.density).toInt() }) + option(WEEK, "In a week"); option(MONTH, "In a month · ${shortDate(month)}"); option(DATE, "On a date"); option(NEVER, "Never") + check(choice) + setOnCheckedChangeListener { _, id -> choice = id; dateButton.isEnabled = id == DATE } + }.help("share.expiry") + dateButton.setOnClickListener { + DatePickerDialog(this, { _, y, m, d -> chosenDate = LocalDate.of(y, m + 1, d); dateButton.text = shortDate(chosenDate) }, + chosenDate.year, chosenDate.monthValue - 1, chosenDate.dayOfMonth).apply { + datePicker.minDate = System.currentTimeMillis() + 86_400_000L + }.show() + } + body.addView(card( + heading("Allow a copy?").help("share.allow"), + text("$phone is asking for a copy of $store.", 16f), + checkBox(check), + text("The copy expires", 14f, bold = true), + group, + dateButton, + text("On that date it's deleted from their phone. Until then they serve it with their own PIN. They can't change it or pass it on.", 14f), + )) + body.addView(LinearLayout(this).apply { + addView(button("Deny") { send(Ipc.MSG_SHARE_DENY) }.help("share.deny"), LinearLayout.LayoutParams(0, -2, 1f)) + addView(button("Allow") { send(Ipc.MSG_SHARE_ALLOW, Bundle().apply { putLong(Ipc.KEY_SHARE_COPY_EXPIRES, expiryMs()) }) }.help("share.allow"), + LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = pad / 2 }) + }) + } + + /** The chosen expiry, as the end of that day on this phone, or -1 for never. */ + private fun expiryMs(): Long { + val zone = ZoneId.systemDefault() + return when (choice) { + NEVER -> -1 + WEEK -> ZonedDateTime.now(zone).plusWeeks(1).toInstant().toEpochMilli() + DATE -> chosenDate.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - 1 + else -> ZonedDateTime.now(zone).plusMonths(1).toInstant().toEpochMilli() + } + } + + private fun shortDate(d: LocalDate): String = + DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date.from(d.atStartOfDay(ZoneId.systemDefault()).toInstant())) + + // ---- messages and outcomes ---- + private fun showMessage(title: String, message: String, done: Boolean = false, again: Boolean = false) { + countdown = null + body.removeAllViews() + body.addView(card(heading(title), text(message, 16f))) + // A new share from this screen is its own: leaving the screen closes it. + if (again) body.addView(button("Share again") { ownShare = true; lastState = ""; send(Ipc.MSG_SHARE_OPEN) }.help("share.again")) + if (done) body.addView(button("Done") { finish() }.help("share.done")) + } + + // ---- building blocks, in the app's style ---- + private fun card(vararg views: View) = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + val dp = resources.displayMetrics.density + background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(pal.panelTop, pal.cardBottom)).apply { + cornerRadius = 12 * dp; setStroke((1 * dp).toInt(), pal.stroke) + } + setPadding(pad, pad, pad, pad) + layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = pad } + views.forEach { v -> addView(v, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = pad / 2 }) } + } + + private fun heading(t: String) = TextView(this).apply { text = t; textSize = 20f; setTypeface(typeface, Typeface.BOLD); setTextColor(pal.ink) } + + private fun text(t: String, size: Float = 15f, bold: Boolean = false, center: Boolean = false) = TextView(this).apply { + text = t; textSize = size; setTextColor(pal.ink) + if (bold) setTypeface(typeface, Typeface.BOLD) + if (center) gravity = Gravity.CENTER + } + + private fun checkBox(check: String) = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER + val dp = resources.displayMetrics.density + background = GradientDrawable().apply { setColor(pal.digits); cornerRadius = 10 * dp; setStroke((2 * dp).toInt(), pal.ink) } + setPadding(pad, pad / 2, pad, pad / 2) + addView(text("Check that the other phone's screen shows", 13f, center = true)) + addView(text(check.chunked(2).joinToString(" "), 34f, bold = true, center = true).apply { letterSpacing = 0.15f }) + } + + private fun qr(content: String, dp: Int = 220) = ImageView(this).apply { + val size = (dp * resources.displayMetrics.density).toInt() + setImageBitmap(Bitmap.createBitmap(QrCodes.pixels(content, size), size, size, Bitmap.Config.ARGB_8888)) + layoutParams = LinearLayout.LayoutParams(size, size).apply { gravity = Gravity.CENTER_HORIZONTAL } + contentDescription = if (dp == 220) "QR code for importing this store" else "QR code for downloading Share Your Apps Server" + } + + private fun button(t: String, onClick: () -> Unit) = Button(this).apply { text = t; setOnClickListener { onClick() } } + + private val pal by lazy { Palette.of(this) } + + companion object { + private val WEEK = View.generateViewId(); private val MONTH = View.generateViewId() + private val DATE = View.generateViewId(); private val NEVER = View.generateViewId() + /** A share in these states is still under way: this screen joins it rather than opening a new one. */ + private val UNDER_WAY = setOf("OPEN", "PREPARING", "ASKED", "REVEALED", "ALLOWED") + + fun open(context: Context) = context.startActivity(Intent(context, ShareActivity::class.java)) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareClient.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareClient.kt new file mode 100644 index 000000000..06bf3e83e --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareClient.kt @@ -0,0 +1,81 @@ +package org.appdevforall.shareyourapps.server + +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.util.Base64 + +/** + * The seller's side of importing a store (design, Appendix E.2–E.3): the three-step exchange with + * the owner's server, asking whether the owner has allowed the copy, then downloading it straight + * into [SharePackage.import]. [base] is the owner's server, such as http://192.168.1.5:6175. + */ +class ShareClient( + private val base: String, code: String, private val phoneName: String, + /** Opens each connection; on Android, through the Wi-Fi network, which a network without internet isn't by default. */ + private val opener: (URL) -> java.net.URLConnection = { it.openConnection() }, +) { + private val code = ShareCodes.normalize(code) ?: throw IOException("That isn't a share code.") + private val sellerKey = ShareCrypto.newKeyPair() + private var requestId: String? = null + private var sessionKey: ByteArray? = null + @Volatile private var cancelled = false + @Volatile private var connection: HttpURLConnection? = null + + /** Stops whatever this client is doing, from any thread: a download in progress fails, leaving nothing. */ + fun cancel() { cancelled = true; connection?.disconnect() } + + /** Steps 1 to 3. Returns the check code, for the seller's screen. */ + fun ask(): String { + val first = post("/share/request", JSONObject() + .put("code", code).put("name", phoneName) + .put("commitment", b64(ShareCrypto.commitment(sellerKey.public.encoded))).put("protocol", ShareHost.PROTOCOL)) + val id = first.getString("request") + val ownerPublic = Base64.getDecoder().decode(first.getString("ownerKey")) + val owner = try { ShareCrypto.publicKey(ownerPublic) } catch (e: Exception) { throw IOException("The owner's phone sent a key that can't be read.") } + post("/share/reveal", JSONObject().put("request", id).put("sellerKey", b64(sellerKey.public.encoded))) + requestId = id + sessionKey = ShareCrypto.sessionKey(sellerKey.private, owner, code, ownerPublic, sellerKey.public.encoded) + return ShareCrypto.checkCode(ownerPublic, sellerKey.public.encoded, code) + } + + /** waiting, allowed, denied or expired. */ + fun status(): String = get("/share/status?request=${requestId ?: throw IOException("Ask first.")}").getString("state") + + /** Downloads the allowed copy into [destParent], all or nothing. */ + fun download(destParent: File, usableSpace: Long? = null, accept: (SharePackage.Description) -> Unit = {}, + progress: (Long, Long) -> Unit = { _, _ -> }): Pair { + val c = open("/share/copy?request=${requestId ?: throw IOException("Ask first.")}") + if (c.responseCode != 200) throw IOException(errorOf(c)) + return c.inputStream.use { SharePackage.import(SealedInputStream(it, sessionKey!!), destParent, usableSpace, accept, progress) } + } + + private fun open(path: String): HttpURLConnection { + if (cancelled) throw IOException("Cancelled.") + return (opener(URL(base + path)) as HttpURLConnection).apply { + connectTimeout = 5_000; readTimeout = 30_000 + connection = this + } + } + + private fun post(path: String, body: JSONObject): JSONObject { + val c = open(path).apply { requestMethod = "POST"; doOutput = true; setRequestProperty("Content-Type", "application/json") } + c.outputStream.use { it.write(body.toString().toByteArray()) } + return reply(c) + } + + private fun get(path: String): JSONObject = reply(open(path)) + + private fun reply(c: HttpURLConnection): JSONObject { + if (c.responseCode != 200) throw IOException(errorOf(c)) + return JSONObject(c.inputStream.use { String(it.readBytes()) }) + } + + private fun errorOf(c: HttpURLConnection): String = try { + JSONObject(c.errorStream.use { String(it.readBytes()) }).getString("error") + } catch (e: Exception) { "The owner's phone answered ${c.responseCode}." } + + private fun b64(b: ByteArray) = Base64.getEncoder().encodeToString(b) +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareControl.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareControl.kt new file mode 100644 index 000000000..9ddca7503 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareControl.kt @@ -0,0 +1,374 @@ +package org.appdevforall.shareyourapps.server + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import android.os.RemoteException +import java.time.Instant +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import org.json.JSONObject + +/** + * Sharing the store for MCP clients (share_start, share_status, share_stop). Main process only. + * + * Talks to the server process the way the share screen does: binds without starting it, and asks + * what's happening. It only ever sends three messages — open a share, ask its state, close it — + * and [send] refuses any other, so nothing here can approve or deny a copy. Allow and Deny are only + * sent from [ShareActivity], by a person. + * + * While a share an MCP client started (or joined) is under way, a watcher asks its state once a + * second, and when a phone asks for a copy, posts a notification that opens the share screen — + * which joins that share rather than replacing it — for a person to check the digits and choose. + */ +object ShareControl { + private const val CHANNEL = "share_requests" + private const val NOTIFICATION = 6177 + private const val BIND_WAIT_MS = 1500L + private const val REPLY_WAIT_MS = 2000L + private const val WATCH_MS = 1000L + const val MAX_WAIT_S = 25 + + /** States of a share still under way, and of one that has finished. */ + private val UNDER_WAY = setOf("OPEN", "PREPARING", "ASKED", "REVEALED", "ALLOWED") + private val FINISHED = setOf("DONE", "DENIED", "CLOSED") + /** The only messages this may send. Never MSG_SHARE_ALLOW or MSG_SHARE_DENY. */ + private val ALLOWED_MESSAGES = setOf(Ipc.MSG_SHARE_OPEN, Ipc.MSG_SHARE_POLL, Ipc.MSG_SHARE_CLOSE) + + @Volatile private var app: Context? = null + + // ---------------------------------------------------------------- the connection + + @Volatile private var server: Messenger? = null + @Volatile private var connected = CountDownLatch(1) + private var bound = false + + private val conn = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + server = Messenger(service); connected.countDown() + } + override fun onServiceDisconnected(name: ComponentName) { + // The server process stopped. Android may reconnect this binding to the next server process, + // but doesn't always (server_stop then server_start left it unconnected): connect() binds afresh. + server = null; connected = CountDownLatch(1) + } + /** The binding will never reconnect: drop it, so the next connect() binds afresh. */ + override fun onBindingDied(name: ComponentName) { dropBinding() } + override fun onNullBinding(name: ComponentName) { dropBinding() } + } + + /** One request at a time: replies carry nothing to match them to their request. */ + private val requestLock = Any() + @Volatile private var waiting: CountDownLatch? = null + @Volatile private var reply: Bundle? = null + private val replies by lazy { + Messenger(Handler(Looper.getMainLooper()) { msg -> + if (msg.what == Ipc.MSG_SHARE_STATE) { reply = Bundle(msg.data); waiting?.countDown() } + true + }) + } + + /** Forgets the binding and its messenger, so the next connect() binds afresh. */ + private fun dropBinding() { + synchronized(this) { + if (bound) { try { app?.unbindService(conn) } catch (e: IllegalArgumentException) { }; bound = false } + server = null; connected = CountDownLatch(1) + } + } + + /** + * The server process's messenger, binding first if needed; null if it doesn't answer. A binding left + * from an earlier server process may never reconnect, so if no live messenger arrives in time, the + * binding is dropped and made afresh, once. + */ + private fun connect(ctx: Context): Messenger? { + val a = ctx.applicationContext + app = a + for (attempt in 0..1) { + if (attempt > 0) dropBinding() + val latch = synchronized(this) { + // No BIND_AUTO_CREATE: the server process is never started just for this. + if (!bound) bound = a.bindService(Intent(a, ServerService::class.java), conn, 0) + connected + } + server?.takeIf { it.binder.isBinderAlive }?.let { return it } + latch.await(BIND_WAIT_MS, TimeUnit.MILLISECONDS) + server?.takeIf { it.binder.isBinderAlive }?.let { return it } + } + return null + } + + private fun send(what: Int, expectReply: Boolean): Bundle? { + require(what in ALLOWED_MESSAGES) { "ShareControl never sends message $what" } + synchronized(requestLock) { + val m = server ?: return null + val latch = CountDownLatch(1) + reply = null + waiting = if (expectReply) latch else null + try { + m.send(Message.obtain(null, what).apply { replyTo = replies }) + } catch (e: RemoteException) { + // The server process is gone: the next request binds afresh. + waiting = null; dropBinding(); return null + } + if (!expectReply) return null + latch.await(REPLY_WAIT_MS, TimeUnit.MILLISECONDS) + waiting = null + if (reply == null && !m.binder.isBinderAlive) dropBinding() + return reply + } + } + + /** The share's state now: NONE when the server isn't serving. Throws when the server process doesn't answer. */ + private fun poll(ctx: Context): Bundle { + if (ServerStatus.url == null) return Bundle().apply { putString(Ipc.KEY_SHARE_STATE, "NONE") } + connect(ctx) ?: throw McpToolError("Couldn't reach the server process. Try again in a moment.") + return send(Ipc.MSG_SHARE_POLL, true) ?: throw McpToolError("The server process didn't answer. Try again in a moment.") + } + + // ---------------------------------------------------------------- the share an MCP client is following + + private val track = Any() + /** A share an MCP client started or joined is being followed. */ + @Volatile private var following = false + /** Whether an MCP client opened it (true), or joined one a person opened (false). */ + @Volatile private var startedByClient = false + /** Its code; null while the store is still being prepared. */ + @Volatile private var followedCode: String? = null + @Volatile private var stoppedByClient = false + /** Why the followed share ended, once it has. */ + @Volatile private var ended: String? = null + @Volatile private var notifiedKey: String? = null + + /** Updates what's followed from a fresh state; posts or clears the "asks for a copy" notification. */ + private fun observe(b: Bundle) { + val state = b.getString(Ipc.KEY_SHARE_STATE) ?: "NONE" + val code = b.getString(Ipc.KEY_SHARE_CODE) + synchronized(track) { + if (!following) { clearNotification(); return } + if (followedCode == null && code != null && state in UNDER_WAY) followedCode = code + val ours = (followedCode != null && code == followedCode) || (followedCode == null && state == "PREPARING") + if (!ours) { + ended = when { + stoppedByClient -> "stopped with share_stop" + state == "NONE" -> "the server stopped, which ended the share" + code != null -> "a new share was opened on this phone, replacing it" + else -> "it was ended on this phone: Cancel, or leaving the share screen that opened it" + } + following = false + clearNotification() + return + } + } + if (state == "REVEALED") notifyAsk(b.getString(Ipc.KEY_SHARE_PHONE).orEmpty(), b.getString(Ipc.KEY_SHARE_STORE).orEmpty(), + b.getString(Ipc.KEY_SHARE_CHECK).orEmpty()) + else clearNotification() + } + + private var watchThread: HandlerThread? = null + private var watchHandler: Handler? = null + private val watchTick = object : Runnable { + override fun run() { + val ctx = app ?: return + if (!following) return + val b = try { poll(ctx) } catch (e: Exception) { null } + if (b != null) observe(b) + val state = b?.getString(Ipc.KEY_SHARE_STATE) + if (following && state !in FINISHED) watchHandler?.postDelayed(this, WATCH_MS) + } + } + + private fun watch() { + synchronized(this) { + if (watchThread == null) { + watchThread = HandlerThread("share-watch").also { it.start() } + watchHandler = Handler(watchThread!!.looper) + } + watchHandler?.removeCallbacks(watchTick) + watchHandler?.postDelayed(watchTick, WATCH_MS) + } + } + + // ---------------------------------------------------------------- the tools + + /** share_start: opens a share, or returns the one already under way (with already_open). */ + fun start(ctx: Context): JSONObject { + if (ServerStatus.url == null) throw McpToolError("The server isn't serving, so there's nothing to share. Call server_start first.", + JSONObject().put("state", "not_serving")) + if (ServerStatus.servingCopy) throw McpToolError("This phone is serving an imported copy of someone else's store. Copies can't be passed on, so it can't be shared.", + JSONObject().put("state", "cant_share")) + val now = poll(ctx) + val state = now.getString(Ipc.KEY_SHARE_STATE) + if (state in UNDER_WAY) { + // A share is already under way — this client's, or a person's on the share screen: return it, never replace it. + val code = now.getString(Ipc.KEY_SHARE_CODE) + synchronized(track) { + val same = following && (code == followedCode || followedCode == null) + if (!same) { startedByClient = false; followedCode = code } + following = true; stoppedByClient = false; ended = null + } + observe(now); watch() + return describe(now).put("already_open", true).put("started_by", if (startedByClient) "mcp" else "person") + } + val opened = send(Ipc.MSG_SHARE_OPEN, true) ?: throw McpToolError("The server process didn't answer. Try again in a moment.") + val openedState = opened.getString(Ipc.KEY_SHARE_STATE) + if (openedState !in UNDER_WAY) { + throw McpToolError(opened.getString(Ipc.KEY_SHARE_ERROR) ?: "The share didn't open (state $openedState).", describe(opened)) + } + synchronized(track) { + following = true; startedByClient = true; stoppedByClient = false; ended = null + followedCode = opened.getString(Ipc.KEY_SHARE_CODE) + notifiedKey = null + } + observe(opened); watch() + val out = describe(opened).put("already_open", false).put("started_by", "mcp") + val prefs = ctx.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + if (prefs.getString(HostService.PREF_RUN_MODE, "always") == "screenOff") { + out.put("warning", "\"Pause when the screen turns off\" is chosen on this phone: if its screen turns off, the server pauses, and this share ends.") + } + return out + } + + /** share_status: the followed share's state; with [waitSeconds], waits up to that long for it to change. */ + fun status(ctx: Context, waitSeconds: Int): JSONObject { + val first = current(ctx) + val wait = waitSeconds.coerceIn(0, MAX_WAIT_S) + if (wait == 0) return first + val deadline = System.currentTimeMillis() + wait * 1000L + var last = first + while (System.currentTimeMillis() < deadline) { + Thread.sleep(500) + last = current(ctx) + if (last.optString("state") != first.optString("state") || last.optString("phone") != first.optString("phone")) return last.put("changed", true) + } + return last.put("changed", false) + } + + private fun current(ctx: Context): JSONObject { + val b = poll(ctx) + observe(b) + return when { + following -> describe(b).put("started_by", if (startedByClient) "mcp" else "person") + ended != null -> JSONObject().put("state", "closed").put("reason", ended) + .put("next", "Call share_start for a new share.") + else -> describe(b).put("started_by", if (b.getString(Ipc.KEY_SHARE_STATE) in UNDER_WAY) "person" else JSONObject.NULL) + } + } + + /** share_stop: closes the share being followed. */ + fun stop(ctx: Context): JSONObject { + if (!following) return JSONObject().put("stopped", false).put("state", "closed") + .put("reason", ended ?: "No share started with share_start is open.") + if (ServerStatus.url != null && connect(ctx) != null) send(Ipc.MSG_SHARE_CLOSE, false) + synchronized(track) { + stoppedByClient = true; following = false; ended = "stopped with share_stop" + } + clearNotification() + return JSONObject().put("stopped", true).put("state", "closed").put("reason", ended) + } + + /** MCP control turned off: a share an MCP client opened ends with it; one a person opened carries on. */ + fun shutdown() { + val closeOurs = following && startedByClient + synchronized(track) { following = false; ended = null; followedCode = null } + if (closeOurs && ServerStatus.url != null && server != null) send(Ipc.MSG_SHARE_CLOSE, false) + clearNotification() + synchronized(this) { + watchHandler?.removeCallbacksAndMessages(null) + watchThread?.quitSafely(); watchThread = null; watchHandler = null + if (bound) { try { app?.unbindService(conn) } catch (e: IllegalArgumentException) { }; bound = false } + server = null; connected = CountDownLatch(1) + } + } + + // ---------------------------------------------------------------- what the client is told + + /** One word a client can act on, for a share's state. */ + fun stateWord(state: String?, failures: Int, servingCopy: Boolean): String = when (state) { + "OPEN" -> "waiting_for_phone" + "PREPARING" -> "preparing" + "ASKED" -> "phone_connecting" + "REVEALED" -> "waiting_for_allow" + "ALLOWED" -> if (failures > 0) "transfer_failed" else "sending" + "DONE" -> "done" + "DENIED" -> "denied" + "CLOSED" -> "expired" + "NONE", null -> "not_serving" + "ERROR" -> if (servingCopy) "cant_share" else "closed" + else -> state.lowercase() + } + + private fun describe(b: Bundle): JSONObject { + val state = b.getString(Ipc.KEY_SHARE_STATE) + val failures = b.getInt(Ipc.KEY_SHARE_FAILURES) + val word = stateWord(state, failures, ServerStatus.servingCopy) + val out = JSONObject().put("state", word) + b.getString(Ipc.KEY_SHARE_STORE)?.let { out.put("store", it) } + b.getString(Ipc.KEY_SHARE_CODE)?.let { out.put("code", it) } + b.getString(Ipc.KEY_SHARE_LINK)?.let { out.put("link", it) } + val expires = b.getLong(Ipc.KEY_SHARE_CODE_EXPIRES, 0) + if (expires > 0) out.put("code_expires", Instant.ofEpochMilli(expires).toString()) + b.getString(Ipc.KEY_SHARE_PHONE)?.takeIf { it.isNotEmpty() }?.let { out.put("phone", it) } + b.getString(Ipc.KEY_SHARE_CHECK)?.let { out.put("check_code", it) } + if (failures > 0) out.put("failed_transfers", failures) + b.getString(Ipc.KEY_SHARE_ERROR)?.let { out.put("message", it) } + when (word) { + "preparing" -> out.put("next", "The store is being prepared after a publish. Call share_status with wait_seconds until the code appears.") + "waiting_for_phone" -> out.put("next", "On the other phone, import with this code or link. The code works for one phone, for 10 minutes.") + "waiting_for_allow" -> { + val notificationsOn = app?.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() ?: false + out.put("person_needed", "A person must check that the four digits match on both phones, choose when the copy expires, " + + "and tap Allow or Deny on this phone. No tool can do this. " + + if (notificationsOn) "A notification asks them." else "Notifications are off for this app: ask them to open Share Your Apps Server and tap Share this store…") + } + "transfer_failed" -> out.put("next", "The other phone can try the transfer again while this share stays open.") + "not_serving" -> out.put("next", "Call server_start first.") + } + return out + } + + // ---------------------------------------------------------------- the notification + + private fun notifyAsk(phone: String, store: String, check: String) { + val ctx = app ?: return + val key = "$phone|$check" + if (key == notifiedKey) return + notifiedKey = key + val nm = ctx.getSystemService(NotificationManager::class.java) ?: return + // High importance: a heads-up notification, so the person sees it whatever app they're in. + nm.createNotificationChannel(NotificationChannel(CHANNEL, "Requests for a copy", NotificationManager.IMPORTANCE_HIGH).apply { + description = "A phone asks for a copy of a share an app started. Only you can allow it." + }) + val open = PendingIntent.getActivity(ctx, 2, + Intent(ctx, ShareActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val n = Notification.Builder(ctx, CHANNEL) + .setSmallIcon(android.R.drawable.stat_sys_upload) + .setContentTitle("${phone.ifEmpty { "A phone" }} asks for a copy of ${store.ifEmpty { "your store" }}") + .setContentText("Tap to check the four digits, then Allow or Deny.") + .setContentIntent(open) + .setAutoCancel(true) + .setOnlyAlertOnce(true) + .setCategory(Notification.CATEGORY_STATUS) + .build() + try { nm.notify(NOTIFICATION, n) } catch (e: SecurityException) { } // notifications not allowed + } + + private fun clearNotification() { + if (notifiedKey == null) return + notifiedKey = null + app?.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareCrypto.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareCrypto.kt new file mode 100644 index 000000000..d9e21a980 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareCrypto.kt @@ -0,0 +1,194 @@ +package org.appdevforall.shareyourapps.server + +import java.io.DataInputStream +import java.io.EOFException +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.nio.ByteBuffer +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.MessageDigest +import java.security.PrivateKey +import java.security.PublicKey +import java.security.SecureRandom +import java.security.Signature +import java.security.spec.ECGenParameterSpec +import java.security.spec.PKCS8EncodedKeySpec +import java.security.spec.X509EncodedKeySpec +import javax.crypto.Cipher +import javax.crypto.KeyAgreement +import javax.crypto.Mac +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * The cryptography for sharing a store with another seller (design, Appendix E.3), kept in this + * one file so it can be reviewed on its own. P-256 throughout, since Android has it built in back + * to Android 9: ECDSA signs a copy's description with the store's key; ECDH, then HKDF-SHA256, + * derives a key only one pair of phones can know; AES-256-GCM, in numbered chunks, encrypts the + * copy with it. + * + * The exchange, whose check code the owner compares by eye (screen 3 with screens 5 and 6): + * 1. seller → owner: the share code, and a commitment — the hash of the seller's public key; + * 2. owner → seller: the owner's one-time public key; + * 3. seller → owner: the seller's public key, which the owner checks against the commitment. + * Each side's key is fixed before it sees the other's, so someone in the middle can't try keys + * until the four digits match: their chance stays 1 in 10,000. + */ +object ShareCrypto { + private val random = SecureRandom() + + fun newKeyPair(): KeyPair = + KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1"), random) }.generateKeyPair() + + fun publicKey(encoded: ByteArray): PublicKey = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(encoded)) + fun privateKey(encoded: ByteArray): PrivateKey = KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(encoded)) + + fun sign(key: PrivateKey, data: ByteArray): ByteArray = + Signature.getInstance("SHA256withECDSA").run { initSign(key); update(data); sign() } + + fun verify(key: PublicKey, data: ByteArray, signature: ByteArray): Boolean = try { + Signature.getInstance("SHA256withECDSA").run { initVerify(key); update(data); verify(signature) } + } catch (e: Exception) { false } + + fun sha256(vararg parts: ByteArray): ByteArray = + MessageDigest.getInstance("SHA-256").run { parts.forEach { update(it) }; digest() } + + /** A store's identity: its public key's SHA-256, first 10 bytes, in base32 — 16 characters. */ + fun storeId(key: PublicKey): String = Base32.encode(sha256(key.encoded).copyOf(10)) + + /** Step 1's commitment to the seller's public key. */ + fun commitment(sellerPublic: ByteArray): ByteArray = sha256("shareyourapps-commit v1".toByteArray(), sellerPublic) + + fun commitmentHolds(commitment: ByteArray, sellerPublic: ByteArray): Boolean = + MessageDigest.isEqual(commitment, commitment(sellerPublic)) + + /** The four digits both phones show. They match only if both hold the same two public keys and code. */ + fun checkCode(ownerPublic: ByteArray, sellerPublic: ByteArray, code: String): String { + val h = sha256("shareyourapps-check v1".toByteArray(), ownerPublic, sellerPublic, code.toByteArray()) + val n = ByteBuffer.wrap(h, 0, 4).int.toLong() and 0xffffffffL + return "%04d".format(n % 10_000) + } + + /** The key for one pair of phones: ECDH, then HKDF bound to the share code and both public keys. */ + fun sessionKey(own: PrivateKey, theirs: PublicKey, code: String, ownerPublic: ByteArray, sellerPublic: ByteArray): ByteArray { + val secret = KeyAgreement.getInstance("ECDH").run { init(own); doPhase(theirs, true); generateSecret() } + return hkdf(secret, code.toByteArray(), "shareyourapps-share v1".toByteArray() + ownerPublic + sellerPublic, 32) + } + + /** HKDF-SHA256, RFC 5869. */ + fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray { + val prk = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(if (salt.isEmpty()) ByteArray(32) else salt, "HmacSHA256")); doFinal(ikm) } + val out = java.io.ByteArrayOutputStream(); var t = ByteArray(0); var i = 1 + while (out.size() < length) { + t = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(prk, "HmacSHA256")); update(t); update(info); update(i.toByte()); doFinal() } + out.write(t); i++ + } + return out.toByteArray().copyOf(length) + } + + fun randomBytes(n: Int): ByteArray = ByteArray(n).also { random.nextBytes(it) } +} + +/** + * AES-256-GCM over a stream, in chunks of up to 64 KB, so a copy of any size is encrypted without + * holding it in memory. A header of magic bytes and an 8-byte random nonce prefix; then each chunk + * as its length and ciphertext, with nonce = prefix + chunk number, and the number and a "last" + * flag authenticated with it. So altering, reordering, or cutting off the stream all fail. + */ +class SealedOutputStream(private val out: OutputStream, key: ByteArray) : OutputStream() { + private val cipherKey = SecretKeySpec(key, "AES") + private val prefix = ShareCrypto.randomBytes(8) + private val buf = ByteArray(CHUNK); private var n = 0; private var counter = 0; private var closed = false + + init { out.write(MAGIC); out.write(prefix) } + + override fun write(b: Int) { if (n == CHUNK) flushChunk(false); buf[n++] = b.toByte() } + override fun write(b: ByteArray, off: Int, len: Int) { + var i = off; val end = off + len + while (i < end) { + if (n == CHUNK) flushChunk(false) + val k = minOf(CHUNK - n, end - i); System.arraycopy(b, i, buf, n, k); n += k; i += k + } + } + + private fun flushChunk(last: Boolean) { + val c = Cipher.getInstance("AES/GCM/NoPadding") + c.init(Cipher.ENCRYPT_MODE, cipherKey, GCMParameterSpec(128, nonce(prefix, counter))) + c.updateAAD(aad(counter, last)) + val sealed = c.doFinal(buf, 0, n) + out.write(ByteBuffer.allocate(4).putInt(sealed.size).array()); out.write(sealed) + counter++; n = 0 + } + + /** Writes the last chunk — possibly empty — so the reader knows the stream really ended. */ + override fun close() { if (closed) return; closed = true; flushChunk(true); out.flush(); out.close() } + + companion object { + const val CHUNK = 64 * 1024 + val MAGIC = "LSC1".toByteArray() + fun nonce(prefix: ByteArray, counter: Int): ByteArray = prefix + ByteBuffer.allocate(4).putInt(counter).array() + fun aad(counter: Int, last: Boolean): ByteArray = ByteBuffer.allocate(5).putInt(counter).put(if (last) 1 else 0).array() + } +} + +/** Reads a [SealedOutputStream]'s stream; any altered, reordered or missing chunk throws IOException. */ +class SealedInputStream(input: InputStream, key: ByteArray) : InputStream() { + private val src = DataInputStream(input) + private val cipherKey = SecretKeySpec(key, "AES") + private val prefix: ByteArray + private var plain = ByteArray(0); private var pos = 0; private var counter = 0; private var ended = false + + init { + val magic = ByteArray(4); src.readFully(magic) + if (!magic.contentEquals(SealedOutputStream.MAGIC)) throw IOException("not a sealed Share Your Apps copy") + prefix = ByteArray(8); src.readFully(prefix) + } + + private fun nextChunk(): Boolean { + if (ended) return false + val len = try { src.readInt() } catch (e: EOFException) { throw IOException("the copy was cut off") } + if (len < 16 || len > SealedOutputStream.CHUNK + 16) throw IOException("a chunk of the copy is damaged") + val sealed = ByteArray(len); try { src.readFully(sealed) } catch (e: EOFException) { throw IOException("the copy was cut off") } + // A chunk authenticates as the last, or not; try the ordinary case first. + plain = open(sealed, false) ?: open(sealed, true)?.also { ended = true } ?: throw IOException("a chunk of the copy failed its check") + pos = 0; counter++ + if (ended && src.read() != -1) throw IOException("the copy has data after its end") + return true + } + + private fun open(sealed: ByteArray, last: Boolean): ByteArray? = try { + Cipher.getInstance("AES/GCM/NoPadding").run { + init(Cipher.DECRYPT_MODE, cipherKey, GCMParameterSpec(128, SealedOutputStream.nonce(prefix, counter))) + updateAAD(SealedOutputStream.aad(counter, last)); doFinal(sealed) + } + } catch (e: javax.crypto.AEADBadTagException) { null } + + override fun read(): Int { + while (pos >= plain.size) if (!nextChunk()) return -1 + return plain[pos++].toInt() and 0xff + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (len == 0) return 0 + while (pos >= plain.size) if (!nextChunk()) return -1 + val k = minOf(len, plain.size - pos); System.arraycopy(plain, pos, b, off, k); pos += k; return k + } + + /** True once the last chunk has been read and fully consumed: the copy arrived whole. */ + val complete: Boolean get() = ended && pos >= plain.size +} + +/** RFC 4648 base32, upper case, without padding. */ +object Base32 { + private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + fun encode(b: ByteArray): String { + val sb = StringBuilder(); var buffer = 0; var bits = 0 + for (x in b) { buffer = (buffer shl 8) or (x.toInt() and 0xff); bits += 8 + while (bits >= 5) { sb.append(ALPHABET[(buffer shr (bits - 5)) and 31]); bits -= 5 } } + if (bits > 0) sb.append(ALPHABET[(buffer shl (5 - bits)) and 31]) + return sb.toString() + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareDiscovery.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareDiscovery.kt new file mode 100644 index 000000000..10e38441d --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareDiscovery.kt @@ -0,0 +1,77 @@ +package org.appdevforall.shareyourapps.server + +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.NetworkInterface +import java.net.SocketTimeoutException + +/** + * Finding the owner's server from a typed code (design, Appendix E.2). The seller's server + * broadcasts "who has this code?" — as a hash of the code, so the broadcast doesn't reveal it — and + * only the server showing that code answers, with its port. A QR code carries the address itself, + * so scanning needs no search. + */ +object ShareDiscovery { + const val PORT = 6176 + + fun probe(code: String): String = "LSD1 " + ShareCrypto.sha256("shareyourapps-discover v1".toByteArray(), code.toByteArray()) + .copyOf(16).joinToString("") { "%02x".format(it) } + + /** Answers probes for whichever share [host] returns, while it's open. */ + class Listener(private val host: () -> ShareHost?, private val httpPort: Int, port: Int = PORT) : Thread("share-discovery") { + private val socket = DatagramSocket(null).apply { reuseAddress = true; bind(InetSocketAddress(port)) } + val port: Int get() = socket.localPort + init { isDaemon = true } + + override fun run() { + val buf = ByteArray(512) + while (!socket.isClosed) { + val p = DatagramPacket(buf, buf.size) + try { socket.receive(p) } catch (e: Exception) { break } + val h = host() ?: continue + if (!h.isOpen()) continue + if (String(p.data, 0, p.length) != probe(h.code)) continue + val reply = "LSH1 $httpPort".toByteArray() + try { socket.send(DatagramPacket(reply, reply.size, p.socketAddress)) } catch (e: Exception) { } + } + } + + fun close() = socket.close() + } + + /** The owner's server's address, or null if no server answered within [timeoutMs]. */ + fun find(code: String, targets: List = broadcastTargets(), port: Int = PORT, timeoutMs: Int = 3_000, + bind: (DatagramSocket) -> Unit = {}): InetSocketAddress? { + val normalized = ShareCodes.normalize(code) ?: return null + DatagramSocket().use { s -> + bind(s) // on Android, to the Wi-Fi network + s.broadcast = true; s.soTimeout = timeoutMs + val msg = probe(normalized).toByteArray() + for (t in targets) try { s.send(DatagramPacket(msg, msg.size, t, port)) } catch (e: Exception) { } + val buf = ByteArray(64) + val deadline = System.currentTimeMillis() + timeoutMs + while (System.currentTimeMillis() < deadline) { + val p = DatagramPacket(buf, buf.size) + try { s.receive(p) } catch (e: SocketTimeoutException) { return null } + val text = String(p.data, 0, p.length) + val httpPort = text.removePrefix("LSH1 ").toIntOrNull() + if (text.startsWith("LSH1 ") && httpPort != null && httpPort in 1..65535) return InetSocketAddress(p.address, httpPort) + } + } + return null + } + + /** Every IPv4 broadcast address of the phone's networks, and the general one. */ + fun broadcastTargets(): List { + val out = mutableListOf(InetAddress.getByName("255.255.255.255")) + try { + for (ni in NetworkInterface.getNetworkInterfaces()) { + if (!ni.isUp || ni.isLoopback) continue + ni.interfaceAddresses.mapNotNullTo(out) { it.broadcast } + } + } catch (e: Exception) { } + return out.distinct() + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareHost.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareHost.kt new file mode 100644 index 000000000..12f78cccb --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareHost.kt @@ -0,0 +1,145 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.security.KeyPair +import java.time.Instant + +/** + * The owner's side of sharing a store (design, Appendix E.2–E.3): one share at a time, for one + * phone. The server's main thread answers the seller's requests through it, and the owner's screen + * reads and decides through it, so its methods are synchronized — the only lock besides the log's, + * held only for a moment each time. + * + * A share opens with a new code, good for [CODE_LIFETIME_MS]. The seller's server asks with the + * code, its phone's name and a commitment to its key; then reveals the key. The owner sees the name + * and the check code, and allows — choosing the copy's expiry — or denies. An allowed copy can be + * downloaded until one download completes; then the share is done. + */ +class ShareHost( + val storeDir: File, + val storeName: String, + private val storeKey: KeyPair, + private val now: () -> Long = System::currentTimeMillis, +) { + enum class State { OPEN, ASKED, REVEALED, ALLOWED, DENIED, DONE, CLOSED } + + /** Why a request was refused; the sharing address turns each into an HTTP status. */ + enum class Refusal(val status: Int, val message: String) { + WRONG_CODE(404, "That code isn't being shown here."), + EXPIRED(410, "That code has expired. Ask the owner for a new one."), + TAKEN(409, "Another phone is already using that code."), + BAD_KEY(403, "This phone's key didn't match what it promised."), + NOT_ALLOWED(403, "The owner hasn't allowed this copy."), + SELLER_OLDER(426, "This phone's Share Your Apps Server is older than the owner's. Get the newer one from the owner's share screen — the small QR code — then try again."), + SELLER_NEWER(426, "The owner's Share Your Apps Server is older than this phone's. The owner needs to update it first."), + UNKNOWN(404, "That request isn't known here."), + } + + class Refused(val refusal: Refusal) : Exception(refusal.message) + + /** What the owner's screen shows while deciding: the phone's name and the check code. */ + class Pending(val phoneName: String, val checkCode: String) + + /** An allowed copy, ready to stream: its session key and signed description. */ + class Copy(val key: ByteArray, val description: SharePackage.Description, val storeKey: KeyPair, val storeDir: File) + + /** The server's own installed APK, offered at /share/app to a phone that doesn't have the app yet; null offers nothing. */ + @Volatile var appApk: File? = null + + val code: String = ShareCodes.normalize(ShareCodes.newCode())!! + val displayCode: String get() = ShareCodes.display(code) + private val openedAt = now() + val expiresAt: Long = openedAt + CODE_LIFETIME_MS + + private var state = State.OPEN + private var wrongGuesses = 0 + private var requestId: String? = null + private var phoneName = "" + private var commitment = ByteArray(0) + private var ownerKey: KeyPair? = null + private var checkCode: String? = null + private var sessionKey: ByteArray? = null + private var copyExpires: Instant? = null + + @Synchronized fun state(): State = if (state in LIVE && now() >= expiresAt) State.CLOSED.also { state = it } else state + + /** Whether the sharing address should answer at all. */ + @Synchronized fun isOpen(): Boolean = state() in LIVE || state == State.ALLOWED + + /** Step 1: the code, the phone's name and a commitment. Returns the request's id and the owner's one-time public key. */ + @Synchronized fun request(codeInput: String, name: String, commitment: ByteArray, protocol: Int = PROTOCOL): Pair { + if (state() == State.CLOSED && now() >= expiresAt) throw Refused(Refusal.EXPIRED) + if (!isOpen()) throw Refused(Refusal.WRONG_CODE) + if (ShareCodes.normalize(codeInput) != code) { + if (++wrongGuesses >= MAX_WRONG_GUESSES) state = State.CLOSED // guessing can't go on + throw Refused(Refusal.WRONG_CODE) + } + // After the code, so strangers can't probe which version a phone runs. + if (protocol < PROTOCOL) throw Refused(Refusal.SELLER_OLDER) + if (protocol > PROTOCOL) throw Refused(Refusal.SELLER_NEWER) + if (state != State.OPEN) throw Refused(Refusal.TAKEN) + val id = Base32.encode(ShareCrypto.randomBytes(15)) + val key = ShareCrypto.newKeyPair() + requestId = id; phoneName = name.trim().take(40).ifEmpty { "A phone" }; this.commitment = commitment; ownerKey = key + state = State.ASKED + return id to key.public.encoded + } + + /** Step 3: the seller's key, checked against its commitment. Returns the check code. */ + @Synchronized fun reveal(id: String, sellerPublic: ByteArray): String { + if (id != requestId || state() != State.ASKED) throw Refused(Refusal.UNKNOWN) + if (!ShareCrypto.commitmentHolds(commitment, sellerPublic)) { state = State.CLOSED; throw Refused(Refusal.BAD_KEY) } + val owner = ownerKey!! + val seller = try { ShareCrypto.publicKey(sellerPublic) } catch (e: Exception) { state = State.CLOSED; throw Refused(Refusal.BAD_KEY) } + checkCode = ShareCrypto.checkCode(owner.public.encoded, sellerPublic, code) + sessionKey = ShareCrypto.sessionKey(owner.private, seller, code, owner.public.encoded, sellerPublic) + state = State.REVEALED + return checkCode!! + } + + /** For the owner's screen: who's asking, once their key is revealed. */ + @Synchronized fun pending(): Pending? = if (state() == State.REVEALED) Pending(phoneName, checkCode!!) else null + + @Synchronized fun allow(expires: Instant?) { if (state() == State.REVEALED) { copyExpires = expires; state = State.ALLOWED } } + @Synchronized fun deny() { if (state() in LIVE) state = State.DENIED } + @Synchronized fun close() { if (state != State.DONE) state = State.CLOSED } + + /** What the seller's server hears when it asks: waiting, allowed, denied or expired. */ + @Synchronized fun status(id: String): String { + if (id != requestId) throw Refused(Refusal.UNKNOWN) + return when (state()) { + State.ASKED, State.REVEALED -> "waiting" + State.ALLOWED, State.DONE -> "allowed" + State.DENIED -> "denied" + else -> "expired" + } + } + + @Synchronized fun copyExpiry(): Instant? = copyExpires + + /** The copy to stream, only once allowed. */ + @Synchronized fun copyFor(id: String): Copy { + if (id != requestId) throw Refused(Refusal.UNKNOWN) + if (state() != State.ALLOWED) throw Refused(Refusal.NOT_ALLOWED) + val description = SharePackage.describe(storeDir, storeName, storeKey, Instant.ofEpochMilli(now()), copyExpires) + return Copy(sessionKey!!, description, storeKey, storeDir) + } + + private var failures = 0 + /** A transfer of the allowed copy failed partway; the seller may try again while the share is open. */ + @Synchronized fun transferFailed() { failures++ } + @Synchronized fun failures(): Int = failures + + /** One download finished: the share is done, and the code can't be used again. */ + @Synchronized fun sent() { if (state == State.ALLOWED) state = State.DONE } + + @Synchronized fun phoneName(): String = phoneName + + companion object { + const val CODE_LIFETIME_MS = 10 * 60 * 1000L + const val MAX_WRONG_GUESSES = 5 + /** The sharing protocol's version; both phones must match. Raise it with any change to the exchange or the copy's format. */ + const val PROTOCOL = 1 + private val LIVE = setOf(State.OPEN, State.ASKED, State.REVEALED) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SharePackage.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SharePackage.kt new file mode 100644 index 000000000..52b39fd00 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SharePackage.kt @@ -0,0 +1,135 @@ +package org.appdevforall.shareyourapps.server + +import org.json.JSONArray +import org.json.JSONObject +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.security.KeyPair +import java.time.Instant +import java.util.Base64 + +/** + * A copy of a published store (design, Appendix E): its signed description, then its files. The + * whole copy travels inside a [SealedOutputStream], so this layer only has to describe and order + * the files, and refuse anything unsafe when importing. + * + * The description is JSON: format, storeId, storeName, storeKey (the store's public key, X.509, + * base64), created, expires (null for never), and files, each with its path and size. + */ +object SharePackage { + const val FORMAT = 1 + const val MAX_DESCRIPTION = 4 * 1024 * 1024 + + class Description(val json: JSONObject) { + val storeId: String get() = json.getString("storeId") + val storeName: String get() = json.getString("storeName") + val storeKey: ByteArray get() = Base64.getDecoder().decode(json.getString("storeKey")) + val created: Instant get() = Instant.parse(json.getString("created")) + val expires: Instant? get() = if (json.isNull("expires")) null else Instant.parse(json.getString("expires")) + val files: List> get() = json.getJSONArray("files").let { a -> (0 until a.length()).map { a.getJSONObject(it).let { f -> f.getString("path") to f.getLong("size") } } } + val totalBytes: Long get() = files.sumOf { it.second } + } + + /** Every file of a published store, by path under it, in a fixed order. */ + fun filesOf(storeDir: File): List> = + // Never a temporary file, such as the compressor's .gz.tmp, which may vanish while it's being shared. + storeDir.walkTopDown().filter { it.isFile && !it.name.endsWith(".tmp") }.map { it.relativeTo(storeDir).invariantSeparatorsPath to it }.sortedBy { it.first }.toList() + + fun describe(storeDir: File, storeName: String, storeKey: KeyPair, created: Instant, expires: Instant?): Description { + val files = JSONArray(); filesOf(storeDir).forEach { (p, f) -> files.put(JSONObject().put("path", p).put("size", f.length())) } + return Description(JSONObject() + .put("format", FORMAT).put("storeId", ShareCrypto.storeId(storeKey.public)).put("storeName", storeName) + .put("storeKey", Base64.getEncoder().encodeToString(storeKey.public.encoded)) + .put("created", created.toString()).put("expires", expires?.toString() ?: JSONObject.NULL).put("files", files)) + } + + /** Writes the signed description, then every file it lists, to [out] — normally a SealedOutputStream. */ + fun write(out: OutputStream, storeDir: File, description: Description, storeKey: KeyPair) { + val d = DataOutputStream(out) + val bytes = description.json.toString().toByteArray(Charsets.UTF_8) + val signature = ShareCrypto.sign(storeKey.private, bytes) + d.writeInt(bytes.size); d.write(bytes); d.writeInt(signature.size); d.write(signature) + val buf = ByteArray(64 * 1024) + for ((path, size) in description.files) { + // A source zip the compressor replaced by its .gz copy after the listing: the same bytes, decompressed. + val f = File(storeDir, path); val gz = File(storeDir, "$path.gz") + val source: InputStream = if (!f.exists() && path.endsWith(".zip") && gz.isFile) java.util.zip.GZIPInputStream(FileInputStream(gz), 64 * 1024) else FileInputStream(f) + source.use { input -> + var left = size + while (left > 0) { val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) throw IOException("$path shrank while being shared"); d.write(buf, 0, n); left -= n } + } + } + d.flush() + } + + /** Reads just the signed description, checking its signature; throws IOException if it's wrong. */ + fun readDescription(input: InputStream): Description { + val d = DataInputStream(input) + val len = d.readInt(); if (len <= 0 || len > MAX_DESCRIPTION) throw IOException("the copy's description is damaged") + val bytes = ByteArray(len).also { d.readFully(it) } + val sigLen = d.readInt(); if (sigLen <= 0 || sigLen > 256) throw IOException("the copy's signature is damaged") + val signature = ByteArray(sigLen).also { d.readFully(it) } + val desc = try { Description(JSONObject(String(bytes, Charsets.UTF_8))) } catch (e: Exception) { throw IOException("the copy's description can't be read") } + if (desc.json.optInt("format") != FORMAT) throw IOException("this copy was made by a newer Share Your Apps Server") + val key = try { ShareCrypto.publicKey(desc.storeKey) } catch (e: Exception) { throw IOException("the copy's store key can't be read") } + if (ShareCrypto.storeId(key) != desc.storeId) throw IOException("the copy's store identity doesn't match its key") + if (!ShareCrypto.verify(key, bytes, signature)) throw IOException("the copy's signature doesn't match") + desc.files.forEach { (p, s) -> if (!safePath(p) || s < 0) throw IOException("the copy lists an unsafe file: $p") } + if (desc.files.map { it.first }.toSet().size != desc.files.size) throw IOException("the copy lists a file twice") + return desc + } + + /** A path that stays inside the store: relative, with no empty, "." or ".." parts, and no backslashes. */ + fun safePath(p: String): Boolean = + p.isNotEmpty() && !p.startsWith("/") && '\\' !in p && '\u0000' !in p && p.split('/').none { it.isEmpty() || it == "." || it == ".." } + + /** + * Imports a copy from [input], already decrypted, into [destParent]/. Everything goes + * into a temporary folder first, renamed into place only once the last file is saved, so a store + * is either complete or absent. The free space — [usableSpace], if given, else the phone's — is + * checked against the description's total first. + * [accept] sees the description before any file is written, and can refuse it by throwing. + */ + fun import(input: InputStream, destParent: File, usableSpace: Long? = null, accept: (Description) -> Unit = {}, + progress: (written: Long, total: Long) -> Unit = { _, _ -> }): Pair { + val desc = readDescription(input) + accept(desc) + // A folder that doesn't exist yet reports no space, so measure the nearest one that does. + val space = usableSpace ?: generateSequence(destParent.absoluteFile) { it.parentFile }.first { it.exists() }.usableSpace + if (desc.totalBytes + 1024 * 1024 > space) throw IOException("there isn't enough space on this phone for the copy") + destParent.mkdirs() + val tmp = File(destParent, ".incoming-" + Base32.encode(ShareCrypto.randomBytes(5))) + try { + val buf = ByteArray(64 * 1024) + var written = 0L + progress(0, desc.totalBytes) + for ((path, size) in desc.files) { + val f = File(tmp, path); f.parentFile?.mkdirs() + if (!f.canonicalPath.startsWith(tmp.canonicalPath + File.separator)) throw IOException("the copy lists an unsafe file: $path") + FileOutputStream(f).use { out -> + var left = size + while (left > 0) { + val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) throw IOException("the copy was cut off") + out.write(buf, 0, n); left -= n; written += n; progress(written, desc.totalBytes) + } + } + } + if (input.read() != -1) throw IOException("the copy has more data than it lists") + if (input is SealedInputStream && !input.complete) throw IOException("the copy was cut off") + val dest = File(destParent, desc.storeId) + val old = File(destParent, ".replaced-" + desc.storeId) + if (dest.exists()) { old.deleteRecursively(); if (!dest.renameTo(old)) throw IOException("the previous copy couldn't be moved aside") } + if (!tmp.renameTo(dest)) { old.renameTo(dest); throw IOException("the copy couldn't be put in place") } + old.deleteRecursively() + return desc to dest + } catch (e: Exception) { + tmp.deleteRecursively(); throw e + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareRules.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareRules.kt new file mode 100644 index 000000000..5233ecd73 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/ShareRules.kt @@ -0,0 +1,167 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import org.json.JSONObject +import java.time.Instant +import java.security.KeyPair + +/** + * Share codes, as the owner's screen shows them and a seller types them: LS-XXXX-XXXX, from + * Crockford's base32, which leaves out I, L, O and U. Reading one forgives case, spaces, dashes, + * the LS prefix, and the look-alikes O for 0 and I or L for 1. + */ +object ShareCodes { + private const val ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + + fun newCode(): String { + val b = ShareCrypto.randomBytes(8) + val chars = b.map { ALPHABET[(it.toInt() and 0xff) % 32] }.joinToString("") + return "LS-${chars.take(4)}-${chars.drop(4)}" + } + + /** The code's 8 characters, or null if the input isn't one. */ + fun normalize(input: String): String? { + var s = input.uppercase().filter { it.isLetterOrDigit() } + if (s.startsWith("LS") && s.length == 10) s = s.drop(2) + s = s.map { when (it) { 'O' -> '0'; 'I', 'L' -> '1'; else -> it } }.joinToString("") + return s.takeIf { it.length == 8 && it.all { c -> c in ALPHABET } } + } + + fun display(normalized: String): String = "LS-${normalized.take(4)}-${normalized.drop(4)}" +} + +/** + * A copy's expiry, against a phone clock that can be set back (design, Appendix E.5). The latest + * time ever seen is kept in [stateFile]. A clock up to five minutes behind it is an ordinary + * correction; further behind, the copy expires at once, and the caller deletes it. + */ +class ExpiryClock(private val stateFile: File) { + enum class Status { OK, EXPIRED, CLOCK_SET_BACK } + + /** The latest time this phone's clock has shown, in epoch milliseconds, or 0. */ + fun latestSeen(): Long = try { stateFile.readText().trim().toLong() } catch (e: Exception) { 0L } + + fun check(nowMs: Long, expiresMs: Long?): Status { + val latest = latestSeen() + if (latest > 0 && nowMs < latest - ALLOWED_BACK_MS) return Status.CLOCK_SET_BACK + if (nowMs > latest) { + stateFile.parentFile?.mkdirs() + val tmp = File(stateFile.path + ".tmp"); tmp.writeText(nowMs.toString()); tmp.renameTo(stateFile) + } + return if (expiresMs != null && nowMs >= expiresMs) Status.EXPIRED else Status.OK + } + + /** + * Starts again from [nowMs], for a fresh copy: the rule stops a seller extending a copy they + * already have, and a clock once set too far ahead mustn't condemn every copy imported later. + */ + fun restart(nowMs: Long) { + stateFile.parentFile?.mkdirs() + val tmp = File(stateFile.path + ".tmp"); tmp.writeText(nowMs.toString()); tmp.renameTo(stateFile) + } + + companion object { const val ALLOWED_BACK_MS = 5 * 60 * 1000L } +} + +/** + * The store's key pair (design, Appendix E.3): made once, and kept in the app's private storage. + * Each file is written to a temporary name, then renamed, so a crash can't leave half a key. + * Losing it needs no recovery: a new key simply makes a new store identity. + */ +object StoreKeyFile { + fun loadOrCreate(dir: File): KeyPair { + val pub = File(dir, "store-key.pub"); val priv = File(dir, "store-key.p8") + if (pub.isFile && priv.isFile) try { + return KeyPair(ShareCrypto.publicKey(pub.readBytes()), ShareCrypto.privateKey(priv.readBytes())) + } catch (e: Exception) { } + val k = ShareCrypto.newKeyPair() + dir.mkdirs() + write(priv, k.private.encoded); write(pub, k.public.encoded) + return k + } + + private fun write(f: File, bytes: ByteArray) { + val tmp = File(f.path + ".tmp"); tmp.writeBytes(bytes) + if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) } + } +} + +/** + * The link a share's QR code holds: shareyourapps-share://
:/. A phone's own camera + * app recognises it, and opening it takes the seller straight to importing, with the code filled in. + */ +object ShareLink { + const val SCHEME = "shareyourapps-share" + + fun make(address: String, port: Int, code: String): String = "$SCHEME://$address:$port/${ShareCodes.display(code)}" + + /** The address, port and code, or null if the text isn't a share link. */ + fun parse(link: String): Triple? { + val m = Regex("^$SCHEME://([0-9.]{7,15}):(\\d{1,5})/([A-Za-z0-9-]+)/?$").matchEntire(link.trim()) ?: return null + val (address, port, code) = m.destructured + val p = port.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null + val c = ShareCodes.normalize(code) ?: return null + if (address.split('.').let { it.size != 4 || it.any { o -> (o.toIntOrNull() ?: 256) > 255 } }) return null + return Triple(address, p, c) + } +} + +/** + * A copy's expiry, applied (design, Appendix E.5). A copy is due on its date, or at once if the + * phone's clock has been set back more than five minutes. Then it's deleted, and a notice left for + * the seller — screen 8, "A store has expired" — until they dismiss it. The two cases look the same + * to the seller and in the log: nothing says which it was, so nothing teaches how the rule works. + * + * Copies live in the imported folder as /, with their description beside them as + * .json. The notice is [NOTICE], in the same folder. + */ +object CopyExpiry { + const val NOTICE = "expired-notice.json" + + class Expired(val storeName: String, val expires: Instant?, val clockSetBack: Boolean) + + /** Every copy's description in [importedDir]: every .json except the notice. */ + fun copies(importedDir: File): List = + importedDir.listFiles { f -> f.isFile && f.name.endsWith(".json") && f.name != NOTICE }.orEmpty().mapNotNull { f -> + try { SharePackage.Description(JSONObject(f.readText())).also { it.storeId; it.storeName } } catch (e: Exception) { null } + } + + /** Whether [copy] is still fine, due, or on a phone whose clock was set back. Updates the clock's latest time. */ + fun status(copy: SharePackage.Description, clock: ExpiryClock, nowMs: Long = System.currentTimeMillis()): ExpiryClock.Status { + val s = clock.check(nowMs, copy.expires?.toEpochMilli()) + // A copy that never expires has no date to extend, so the clock rule spares it. + return if (copy.expires == null && s == ExpiryClock.Status.CLOCK_SET_BACK) ExpiryClock.Status.OK else s + } + + /** Deletes [copy] and leaves the notice. */ + fun delete(importedDir: File, copy: SharePackage.Description, clockSetBack: Boolean): Expired { + File(importedDir, copy.storeId).deleteRecursively() + File(importedDir, "${copy.storeId}.json").delete() + val e = Expired(copy.storeName, copy.expires, clockSetBack) + val tmp = File(importedDir, "$NOTICE.tmp") + tmp.writeText(JSONObject().put("storeName", e.storeName).toString()) // just the name: nothing says why + tmp.renameTo(File(importedDir, NOTICE)) + return e + } + + /** Checks every copy, deleting any that's due; returns the last one deleted, or null. */ + fun enforce(importedDir: File, clock: ExpiryClock, nowMs: Long = System.currentTimeMillis()): Expired? { + var last: Expired? = null + for (c in copies(importedDir)) { + val s = status(c, clock, nowMs) + if (s != ExpiryClock.Status.OK) last = delete(importedDir, c, s == ExpiryClock.Status.CLOCK_SET_BACK) + } + return last + } + + /** The notice left by a deleted copy, until the seller dismisses it. */ + fun notice(importedDir: File): Expired? = try { + val j = JSONObject(File(importedDir, NOTICE).readText()) + Expired(j.getString("storeName"), null, false) + } catch (e: Exception) { null } + + fun dismiss(importedDir: File) { File(importedDir, NOTICE).delete() } + + /** Where the expiry clock keeps the latest time it has seen: outside the imported folder, so it outlives copies. */ + fun clockFile(filesDir: File) = File(filesDir, "share/latest-time") +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Shared.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Shared.kt new file mode 100644 index 000000000..cda643f2a --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/Shared.kt @@ -0,0 +1,174 @@ +package org.appdevforall.shareyourapps.server + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.os.Environment +import android.os.Handler +import android.os.Looper +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList + +/** Messages between the main process (HostService) and the server process (ServerService). */ +object Ipc { + const val MSG_START = 1 // main → server: data = dir, port, logLimit + const val MSG_STARTED = 2 // server → main: arg1 = pid, arg2 = port, data = address + const val MSG_FAILED = 3 // server → main: arg1 = pid, data = error + const val MSG_STOP = 4 // main → server: data = reason. The server logs it, closes its sockets, replies. + const val MSG_STOPPED = 5 // server → main: ready to be killed + const val MSG_LOG = 6 // main → server: data = line. Lets the main process log while the server writes the file. + + // Sharing a store with another seller (design, Appendix E). The share screen binds to the + // server process directly, and asks what's happening twice a second. + const val MSG_SHARE_OPEN = 7 // main → server: show a new share code for the store being served + const val MSG_SHARE_POLL = 8 // main → server: what's happening? + const val MSG_SHARE_ALLOW = 9 // main → server: data = shareCopyExpires (epoch ms, or -1 for never) + const val MSG_SHARE_DENY = 10 // main → server + const val MSG_SHARE_CLOSE = 11 // main → server: the share screen closed + const val MSG_SHARE_STATE = 12 // server → main: data = the share's state, below + const val MSG_COPY_EXPIRED = 13 // server → main: the copy being served expired, and was deleted; data = storeName + + const val KEY_DIR = "dir" + const val KEY_PORT = "port" + const val KEY_LOG_LIMIT = "logLimit" + const val KEY_ADDRESS = "address" + const val KEY_ERROR = "error" + const val KEY_PIN = "pin" + const val KEY_STORE_NAME = "storeName" + const val KEY_SECRET = "secret" + const val KEY_TOKEN = "token" + const val KEY_REASON = "reason" + /** Which server start a reply belongs to, so replies from a server being replaced are ignored. */ + const val KEY_GEN = "gen" + /** The external address to bind: the Wi-Fi address, or the hotspot's. Chosen by the main process. */ + const val KEY_BIND_ADDRESS = "bindAddress" + /** `[hotspot]` lines from the main process, written to the log before anything else. */ + const val KEY_LOG_LINES = "logLines" + const val KEY_LINE = "line" + /** A ShareHost.State name, or "NONE" when the server isn't serving, or "ERROR" with shareError. */ + const val KEY_SHARE_STATE = "shareState" + const val KEY_SHARE_CODE = "shareCode" + const val KEY_SHARE_LINK = "shareLink" + const val KEY_SHARE_CODE_EXPIRES = "shareCodeExpires" + const val KEY_SHARE_PHONE = "sharePhone" + const val KEY_SHARE_CHECK = "shareCheck" + const val KEY_SHARE_STORE = "shareStore" + const val KEY_SHARE_COPY_EXPIRES = "shareCopyExpires" + const val KEY_SHARE_ERROR = "shareError" + /** Where a phone without the app downloads it, while the share is open. */ + const val KEY_SHARE_APP_URL = "shareAppUrl" + /** How many transfers of the allowed copy failed partway; the seller may try again. */ + const val KEY_SHARE_FAILURES = "shareFailures" + /** Serving an imported copy (design, Appendix E): its folder in the app's private storage, instead of KEY_DIR. */ + const val KEY_COPY_PATH = "copyPath" +} + +/** + * What the plugin sends to [LaunchActivity], and what it gets back. The plugin launches with + * startActivityForResult, naming this component explicitly. + */ +object LaunchContract { + const val PACKAGE = "org.appdevforall.shareyourapps.server" + const val ACTIVITY = "org.appdevforall.shareyourapps.server.LaunchActivity" + const val CALLER = "com.itsaky.androidide" // CodeOnTheGo + + const val EXTRA_DIR = "dir" // Store_ and 8 digits + const val EXTRA_TOKEN = "token" // random; lets the verify step past the PIN + const val EXTRA_PIN = "pin" // digit string, or absent for no PIN + const val EXTRA_STORE_NAME = "storeName" + + const val RESULT_PORT = "port" // Int, with RESULT_OK + const val RESULT_ERROR = "error" // String, with RESULT_CANCELED + /** + * Boolean, with RESULT_CANCELED: true only if the launch failed before touching the server, so + * whatever was being served still is. False once a start has begun, since the old store is + * stopped first. Absent (from older servers) means false. + */ + const val RESULT_UNCHANGED = "unchanged" +} + +/** Hands one start result from HostService to the waiting LaunchActivity. Main process only. */ +object LaunchResult { + private var waiting: ((port: Int, error: String?) -> Unit)? = null + + fun await(callback: (port: Int, error: String?) -> Unit) { + waiting?.invoke(0, "superseded by a newer launch") + waiting = callback + } + fun cancel(callback: (port: Int, error: String?) -> Unit) { if (waiting === callback) waiting = null } + fun deliver(port: Int, error: String?) { + val w = waiting ?: return + waiting = null + w(port, error) + } +} + +object Store { + const val DEFAULT_PORT = 6175 + const val DEFAULT_LOG_LIMIT = 10L * 1024 * 1024 + private val NAME = Regex("""Store_[0-9]{8}""") + + fun validName(name: String) = NAME.matches(name) + + /** CodeOnTheGoProjects/ in shared storage. Only called with a name that passed [validName]. */ + fun dir(name: String) = File(Environment.getExternalStorageDirectory(), "CodeOnTheGoProjects/$name") + + fun logDir(context: Context) = File(context.filesDir, "logs") + + /** The joined Wi-Fi network's address, or null when the phone isn't on Wi-Fi. */ + fun wifiAddress(): java.net.InetAddress? = pickWifiAddress(systemInterfaces()) + + /** The phone's own Mobile hotspot's address, when it's turned on in Settings. */ + fun phoneHotspotAddress(): java.net.InetAddress? = pickPhoneHotspotAddress(systemInterfaces()) + + /** Starting a hotspot needs Nearby devices on Android 13+, and location on 12 and earlier. */ + fun hotspotPermissions(): Array = + if (Build.VERSION.SDK_INT >= 33) arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES) + else arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + + fun hasHotspotPermission(context: Context): Boolean = + hotspotPermissions().all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED } + + /** A hotspot would be needed: not on Wi-Fi, and none running yet. */ + fun needsHotspot(): Boolean = wifiAddress() == null && phoneHotspotAddress() == null && Hotspot.info == null + + /** MANAGE_EXTERNAL_STORAGE on Android 11+, the older storage permissions on Android 9 and 10. */ + fun hasStorageAccess(context: Context): Boolean = + if (Build.VERSION.SDK_INT >= 30) Environment.isExternalStorageManager() + else context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && + context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED +} + +/** + * The server's state as the main process sees it: a status line, and the store's address while + * it's serving. Main process only; listeners run on the main thread. + */ +object ServerStatus { + private val main = Handler(Looper.getMainLooper()) + private val listeners = CopyOnWriteArrayList<() -> Unit>() + + @Volatile var text: String = "Stopped" + private set + @Volatile var url: String? = null + private set + /** Whether what's being served is an imported copy, not this phone's own store. Set by HostService. */ + @Volatile var servingCopy: Boolean = false + /** While a hotspot is up: its network name and password, for buyers to join. */ + @Volatile var hotspot: String? = null + private set + /** Serving on the phone's own Mobile hotspot, whose name and password apps can't read. */ + @Volatile var onPhoneHotspot = false + private set + + fun set(t: String, address: String? = null, hotspotLine: String? = null, phoneHotspot: Boolean = false) { + onPhoneHotspot = phoneHotspot + text = t + url = address + hotspot = hotspotLine + main.post { listeners.forEach { it() } } + } + + fun observe(l: () -> Unit) { listeners += l; l() } + fun remove(l: () -> Unit) { listeners -= l } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDecoder.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDecoder.kt new file mode 100644 index 000000000..062c23a9a --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDecoder.kt @@ -0,0 +1,181 @@ +package org.appdevforall.shareyourapps.server + +import java.util.Locale +import kotlin.math.sqrt + +/** + * Listens for [SoundModem] bursts in audio fed in chunks of any size, as recording delivers them. Plain Kotlin. + * + * Finds each start signal by correlating with the sweep (FFT, overlap-save, normalized so loudness doesn't + * matter), reads the header, then measures every tone with Goertzel over the middle of the symbol, skipping the + * edges where the previous tone's echo lingers. Each burst is tried on its own; if [accept] refuses it (a wrong + * CRC), its tone strengths, un-scrambled and scaled, are added to those of the recent bursts of the same length + * and the sum is tried too. The first bytes [accept] takes are the [result]; later audio is ignored. + */ +class SoundDecoder( + private val modem: SoundModem = SoundModem(), + private val accept: (ByteArray) -> Boolean, +) { + /** The accepted bytes, once heard. */ + var result: ByteArray? = null; private set + /** How the result was heard, for the log: which repeat, or how many combined, and the start signal's strength. */ + var how: String = ""; private set + /** The strongest start signal heard so far, 0 to 1: a rough "hearing something" level. */ + var bestSignal = 0.0; private set + + private class Candidate(val at: Long, val signal: Double) + private class Frame(val at: Long, val length: Int, val powers: Array) + + private val chirpLength = modem.chirpLength + private val sym = modem.symbolLength + private val winFrom = sym * 20 / 100 + private val winLength = sym * 65 / 100 + private val fftSize: Int = run { var n = 1; while (n < 2 * chirpLength) n = n shl 1; n } + private val step = fftSize - chirpLength + 1 + private val chirpRe = DoubleArray(fftSize) + private val chirpIm = DoubleArray(fftSize) + private val chirpNorm: Double + private val coeffs = Array(2) { p -> DoubleArray(SoundModem.TONES) { t -> SoundDsp.coeff(SoundModem.toneHz(p, t), modem.sampleRate) } } + + private var buf = FloatArray(1 shl 17) + private var base = 0L // the absolute position of buf[0] + private var size = 0 // samples held + private val end get() = base + size + private var searchAt = 0L // the next position to test for a start signal + private var peakAt = -1L + private var peakValue = 0.0 + private val pending = ArrayList() + private val heard = ArrayList() + + init { + var e = 0.0 + for (i in 0 until chirpLength) { val v = modem.chirp[i].toDouble(); chirpRe[i] = v; e += v * v } + chirpNorm = sqrt(e) + SoundDsp.fft(chirpRe, chirpIm) + } + + /** Takes [n] samples of [x] from [from]; returns the result once heard, else null. */ + fun feed(x: FloatArray, from: Int = 0, n: Int = x.size - from): ByteArray? { + if (result != null) return result + append(x, from, n) + search() + decodePending() + compact() + return result + } + + /** The audio has ended: pads with silence so a burst at the very end is still read. */ + fun finish(): ByteArray? = feed(FloatArray(fftSize + modem.frameLength(SoundModem.MAX_BYTES))) + + private fun append(x: FloatArray, from: Int, n: Int) { + if (size + n > buf.size) { + var cap = buf.size + while (cap < size + n) cap = cap shl 1 + buf = buf.copyOf(cap) + } + x.copyInto(buf, size, from, from + n) + size += n + } + + private fun search() { + val re = DoubleArray(fftSize); val im = DoubleArray(fftSize) + while (searchAt + fftSize <= end) { + val off = (searchAt - base).toInt() + for (i in 0 until fftSize) { re[i] = buf[off + i].toDouble(); im[i] = 0.0 } + SoundDsp.fft(re, im) + for (i in 0 until fftSize) { // times the sweep's spectrum, conjugated: correlation + val r = re[i] * chirpRe[i] + im[i] * chirpIm[i] + val m = im[i] * chirpRe[i] - re[i] * chirpIm[i] + re[i] = r; im[i] = m + } + SoundDsp.fft(re, im, inverse = true) + var energy = 0.0 + for (i in 0 until chirpLength) { val v = buf[off + i].toDouble(); energy += v * v } + for (t in 0 until step) { + if (t > 0) { + val a = buf[off + t - 1].toDouble(); val b = buf[off + t + chirpLength - 1].toDouble() + energy += b * b - a * a + } + consider(searchAt + t, if (energy > 1e-9) re[t] / (chirpNorm * sqrt(energy)) else 0.0) + } + searchAt += step + } + } + + /** Keeps the strongest start signal within half a sweep; once past it, it becomes a candidate. */ + private fun consider(at: Long, v: Double) { + if (v > bestSignal) bestSignal = v + if (peakAt >= 0 && at - peakAt > chirpLength / 2) { pending += Candidate(peakAt, peakValue); peakAt = -1 } + if (v >= THRESHOLD && (peakAt < 0 || v > peakValue)) { peakAt = at; peakValue = v } + } + + private fun decodePending() { + while (pending.isNotEmpty() && result == null) { + val c = pending[0] + val start = c.at + chirpLength + modem.gapLength + if (start + HEADER_SYMBOLS.toLong() * sym > end) return + val h = IntArray(HEADER_SYMBOLS) { k -> argmax(tonePowers(start, k)) } + val n = (h[0] shl 4) or h[1] + val inv = (h[2] shl 4) or h[3] + val r = h[4] + if (n == 0 || inv != (n xor 0xFF) || r >= SoundModem.REPEATS || h[5] != (r.inv() and 0x0F)) { pending.removeAt(0); continue } + if (start + (HEADER_SYMBOLS + 2L * n) * sym > end) return + pending.removeAt(0) + frame(c, start, n, r) + } + } + + private fun frame(c: Candidate, start: Long, n: Int, repeat: Int) { + val powers = Array(2 * n) { i -> + val p = tonePowers(start, HEADER_SYMBOLS + i) + val key = SoundModem.key(repeat, i) + val sum = p.sum() + // Indexed by the value sent, not the tone; scaled, so a loud repeat doesn't outweigh the others. + DoubleArray(SoundModem.TONES) { v -> if (sum > 0) p[v xor key] / sum else 0.0 } + } + bytes(powers)?.let { done(it, "repeat ${repeat + 1}", c); return } + val memory = (SoundModem.REPEATS + 1L) * (modem.frameLength(n) + modem.repeatGap) + heard.removeAll { it.length != n || c.at - it.at > memory } + heard += Frame(c.at, n, powers) + while (heard.size > SoundModem.REPEATS) heard.removeAt(0) + if (heard.size > 1) { + val sum = Array(2 * n) { i -> DoubleArray(SoundModem.TONES) { v -> heard.sumOf { it.powers[i][v] } } } + bytes(sum)?.let { done(it, "${heard.size} repeats combined", c) } + } + } + + private fun bytes(powers: Array): ByteArray? { + val b = ByteArray(powers.size / 2) { i -> ((argmax(powers[2 * i]) shl 4) or argmax(powers[2 * i + 1])).toByte() } + return if (accept(b)) b else null + } + + private fun done(b: ByteArray, label: String, c: Candidate) { + result = b + how = "$label, start signal ${String.format(Locale.ROOT, "%.2f", c.signal)}" + } + + /** The strength of each of the 16 tones in symbol [k] of the burst whose header starts at [start]. */ + private fun tonePowers(start: Long, k: Int): DoubleArray { + val from = (start + k.toLong() * sym - base).toInt() + winFrom + return DoubleArray(SoundModem.TONES) { t -> SoundDsp.power(buf, from, winLength, coeffs[k and 1][t]) } + } + + private fun argmax(p: DoubleArray): Int { var best = 0; for (i in 1 until p.size) if (p[i] > p[best]) best = i; return best } + + /** Drops audio no candidate or search still needs. */ + private fun compact() { + var keep = searchAt + if (peakAt >= 0) keep = minOf(keep, peakAt) + pending.firstOrNull()?.let { keep = minOf(keep, it.at) } + val drop = (keep - base).toInt() + if (drop <= 0 || drop < buf.size / 4) return + buf.copyInto(buf, 0, drop, size) + size -= drop; base += drop + } + + companion object { + /** Normalized correlation a start signal must reach; noise stays near 0.05, a clear sweep near 1. */ + const val THRESHOLD = 0.35 + const val HEADER_SYMBOLS = SoundModem.HEADER_BYTES * 2 + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDsp.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDsp.kt new file mode 100644 index 000000000..388e0b648 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundDsp.kt @@ -0,0 +1,84 @@ +package org.appdevforall.shareyourapps.server + +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin + +/** + * The signal maths the sound handshake needs, in plain Kotlin with no library: a radix-2 FFT, for finding + * the start signal, and Goertzel, for measuring one tone's strength. + */ +object SoundDsp { + + /** In-place complex FFT of [re] and [im], whose size must be a power of two. [inverse] also divides by the size. */ + fun fft(re: DoubleArray, im: DoubleArray, inverse: Boolean = false) { + val n = re.size + require(n == im.size && n > 0 && (n and (n - 1)) == 0) { "the size must be a power of two" } + // Bit-reversed order. + var j = 0 + for (i in 1 until n) { + var bit = n shr 1 + while ((j and bit) != 0) { j = j xor bit; bit = bit shr 1 } + j = j xor bit + if (i < j) { + val r = re[i]; re[i] = re[j]; re[j] = r + val m = im[i]; im[i] = im[j]; im[j] = m + } + } + var len = 2 + while (len <= n) { + val angle = 2 * PI / len * (if (inverse) 1 else -1) + val wr = cos(angle); val wi = sin(angle) + val half = len / 2 + var start = 0 + while (start < n) { + var cr = 1.0; var ci = 0.0 + for (k in 0 until half) { + val a = start + k; val b = a + half + val xr = re[b] * cr - im[b] * ci + val xi = re[b] * ci + im[b] * cr + re[b] = re[a] - xr; im[b] = im[a] - xi + re[a] += xr; im[a] += xi + val nr = cr * wr - ci * wi + ci = cr * wi + ci * wr; cr = nr + } + start += len + } + len = len shl 1 + } + if (inverse) for (i in 0 until n) { re[i] /= n; im[i] /= n } + } + + /** Goertzel's coefficient for [freq] Hz at [sampleRate]. */ + fun coeff(freq: Double, sampleRate: Int): Double = 2 * cos(2 * PI * freq / sampleRate) + + /** The power of one frequency, given by its [coeff], in samples [from] until [from] + [n] of [x]. */ + fun power(x: FloatArray, from: Int, n: Int, coeff: Double): Double { + var s1 = 0.0; var s2 = 0.0 + for (i in from until from + n) { + val s = x[i] + coeff * s1 - s2 + s2 = s1; s1 = s + } + return s1 * s1 + s2 * s2 - coeff * s1 * s2 + } + + /** The quietest level the listening meter shows, in dB of full scale; anything quieter shows as empty. */ + const val METER_FLOOR_DB = -60.0 + + /** + * The loudness of samples [from] until [from] + [n] of [x] (each -1 to 1), in dB of full scale: 0 for a full-scale + * square wave, about -3 for a full-scale tone, and [METER_FLOOR_DB] for silence or anything quieter. + */ + fun rmsDb(x: FloatArray, from: Int = 0, n: Int = x.size - from): Double { + if (n <= 0) return METER_FLOOR_DB + var sum = 0.0 + for (i in from until from + n) { val v = x[i].toDouble(); sum += v * v } + val rms = kotlin.math.sqrt(sum / n) + if (rms <= 0.0) return METER_FLOOR_DB + return maxOf(METER_FLOOR_DB, 20 * kotlin.math.log10(rms)) + } + + /** A level in dB of full scale as the meter's fill, 0 to 100: [METER_FLOOR_DB] or quieter is 0, full scale is 100. */ + fun meterPercent(db: Double): Int = + (((db - METER_FLOOR_DB) / -METER_FLOOR_DB) * 100).toInt().coerceIn(0, 100) +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundImport.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundImport.kt new file mode 100644 index 000000000..d6090fec5 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundImport.kt @@ -0,0 +1,193 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.os.Handler +import android.os.Looper +import java.net.InetSocketAddress +import kotlin.concurrent.thread +import org.json.JSONObject + +/** + * Hearing a share code for an MCP client (import_listen), with no screen: the same steps as the import screen's + * Listen (project B), which this leaves unchanged. Main process only; the listener's and WifiJoin's answers run on + * the main thread. + * + * 1. Listens for up to 30 s (SoundIo.WINDOW_MS), while McpService runs with the microphone type. + * 2. Heard: can this phone reach the owner's phone on its Wi-Fi (WifiJoin.reachable, about 2 s)? + * 3. Reachable, or the tones carry no hotspot password: the import starts, as import_start would (byMcp). + * 4. Otherwise, on Android 10 and later, WifiJoin asks Android to join the owner's own hotspot: a person taps + * Connect within 30 s. Joined: the import starts on that network, which is let go once the import ends. + * 5. Android 9, or no tap: a person is needed, who uses Listen on the import screen; it shows the hotspot's name + * and password for joining by hand. + * + * The hotspot's password is never put in the state, the client's answers or the log. + */ +object SoundImport { + enum class Phase { IDLE, LISTENING, CHECKING, JOINING, IMPORT_STARTED, NOTHING_HEARD, PERSON_NEEDED, FAILED, STOPPED } + + /** What import_listen reports. [ssid]: the owner's network name, from the tones; never its password. */ + class State(val phase: Phase, val message: String, val secondsLeft: Long = 0, val signal: Double = 0.0, + val code: String? = null, val ssid: String? = null) + + private val main = Handler(Looper.getMainLooper()) + @Volatile var state = State(Phase.IDLE, "Not listening."); private set + @Volatile private var listener: SoundIo.Listener? = null + /** Counts listens started and stopped, so a late answer about an older one is ignored. */ + @Volatile private var run = 0 + + /** Listening, checking the network, or waiting for a person's Connect tap. */ + val busy: Boolean get() = state.phase in setOf(Phase.LISTENING, Phase.CHECKING, Phase.JOINING) + + /** + * Starts listening. Returns null once started, or why not: "person needed: ..." when only a person can fix it. + * The caller checks first that this phone isn't serving, as import_start does. + */ + @Synchronized + fun start(context: Context, phoneName: String): String? { + val app = context.applicationContext + if (!SoundIo.canListen(app)) { + SoundLog.write(app, SoundLog.microphoneRefused()) + return "person needed: the app isn't allowed to use the microphone. Ask a person to open Share Your Apps Server, " + + "turn MCP control off and on again, and allow the microphone." + } + if (busy) return "Already listening: follow it with import_status, or stop it with import_cancel." + if (ImportJob.snapshot.busy) return "An import is already running. Follow it with import_status, or end it with import_cancel." + val r = ++run + var strongest = 0.0 + var loudest = SoundDsp.METER_FLOOR_DB + state = State(Phase.LISTENING, "Listening. Ask the owner to tap Play sound on their share screen.", SoundIo.WINDOW_MS / 1000) + SoundLog.write(app, "listening for a share code, for an MCP client") + listener = SoundIo.Listener(app, + level = { v -> + if (r == run) { + strongest = maxOf(strongest, v.signal) + loudest = maxOf(loudest, v.db) + state = State(Phase.LISTENING, hearing(v.signal), (v.msLeft + 999) / 1000, v.signal) + } + }, + heard = { p, how -> if (r == run) { listener = null; onHeard(app, r, p, how, phoneName) } }, + ended = { end, why -> + if (r == run) { + listener = null + val seconds = SoundIo.WINDOW_MS / 1000 + when (end) { + SoundIo.End.NOTHING_HEARD -> { + SoundLog.write(app, SoundLog.nothingHeard(seconds, strongest)) + // Only silence: Android may be blocking the microphone while the app is off screen. + state = if (loudest <= SoundDsp.METER_FLOOR_DB) + State(Phase.PERSON_NEEDED, "The microphone heard only silence for $seconds s. Android may block it while the app " + + "is off screen: ask a person to open Share Your Apps Server, then call import_listen again.") + else State(Phase.NOTHING_HEARD, "Didn't hear the code in $seconds s. The phones may need to be closer, or the owner's " + + "media volume higher. Call import_listen again while the owner's phone plays its sound.") + } + SoundIo.End.NO_MICROPHONE -> { + SoundLog.write(app, SoundLog.listenFailed(why)) + state = State(Phase.PERSON_NEEDED, "$why Ask a person to open Share Your Apps Server, then call import_listen again.") + } + else -> { + SoundLog.write(app, SoundLog.listenFailed(why)) + state = State(Phase.FAILED, why) + } + } + } + }, + ).start() + return null + } + + private fun hearing(signal: Double) = "Listening. " + when { + signal < 0.15 -> "Nothing heard yet." + signal < SoundDecoder.THRESHOLD -> "Hearing something faint: the phones may need to be closer." + else -> "Hearing the tones." + } + + /** A code was heard: first, whether this phone can already reach the owner's phone, off the main thread. */ + private fun onHeard(app: Context, r: Int, p: SoundPayload, how: String, name: String) { + SoundLog.write(app, SoundLog.heard(p, how)) // never the password + val address = p.address?.let { InetSocketAddress(it, p.port) } + state = State(Phase.CHECKING, "Heard the code ${ShareCodes.display(p.code)}. Checking whether this phone can reach the owner's phone.", + code = p.code, ssid = p.ssid) + thread(name = "sound-reach-mcp") { + val ok = WifiJoin.reachable(app, p.code, address) + main.post { if (r == run) afterReach(app, r, p, name, address, ok) } + } + } + + /** As the import screen does: import at once; or join the owner's own hotspot first; or a person is needed. */ + private fun afterReach(app: Context, r: Int, p: SoundPayload, name: String, address: InetSocketAddress?, reachable: Boolean) { + val ssid = p.ssid + val password = p.password + if (reachable || ssid == null || password == null) { + val hint = if (!reachable && ssid != null) " The owner's phone is on the Wi-Fi network $ssid: if the import can't find it, " + + "a person must join that network, then call import_start with the code." else "" + startImport(app, p, name, address, null, hint) + return + } + if (!WifiJoin.canJoin) { + SoundLog.write(app, "the owner's hotspot $ssid must be joined by hand (Android 9)") + state = byHand(p, "This phone runs Android 9, which can't join the owner's hotspot $ssid by itself.") + return + } + val tapSeconds = WifiJoin.CONNECT_TAP_MS / 1000 + SoundLog.write(app, "joining the owner's hotspot $ssid, for an MCP client") + state = State(Phase.JOINING, "Joining the owner's hotspot $ssid. A person must tap Connect when Android asks, within $tapSeconds s.", + code = p.code, ssid = ssid) + WifiJoin.join(app, ssid, password) { network -> + if (r != run) return@join + if (network != null) { + SoundLog.write(app, "joined the owner's hotspot $ssid") + startImport(app, p, name, address, network, "") + // After start: the import is busy by now, so the hotspot is let go once it ends; at once if it didn't start. + if (ImportJob.snapshot.busy) WifiJoin.holdUntilImportEnds() else WifiJoin.release() + } else { + SoundLog.write(app, "didn't join the owner's hotspot $ssid: no Connect tap within $tapSeconds s, or refused") + state = byHand(p, "Nobody tapped Connect within $tapSeconds s, so this phone didn't join the owner's hotspot $ssid.") + } + } + } + + /** A person must join the owner's hotspot. The client never gets its password: the import screen shows it. */ + private fun byHand(p: SoundPayload, why: String) = State(Phase.PERSON_NEEDED, "$why A person must open Share Your Apps Server, " + + "tap Import a store, then Listen while the owner's phone plays its sound again, and follow the screen: it joins the " + + "hotspot, or shows its name and password.", code = p.code, ssid = p.ssid) + + private fun startImport(app: Context, p: SoundPayload, name: String, address: InetSocketAddress?, network: android.net.Network?, hint: String) { + val why = ImportJob.start(app, p.code, name, address, network = network, byMcp = true) + state = when { + why == null -> State(Phase.IMPORT_STARTED, "Heard the code ${ShareCodes.display(p.code)}, and the import has started: " + + "follow it with import_status.$hint", code = p.code, ssid = p.ssid) + why.startsWith("person needed: ") -> State(Phase.PERSON_NEEDED, why.removePrefix("person needed: "), code = p.code, ssid = p.ssid) + else -> State(Phase.FAILED, why, code = p.code, ssid = p.ssid) + } + } + + /** Stops listening, checking or joining; an import already started carries on (import_cancel ends that). */ + @Synchronized + fun stop(context: Context): Boolean { + if (!busy) return false + val joining = state.phase == Phase.JOINING + run++ + listener?.stop(); listener = null + // A join still being asked for is let go, on the main thread, where WifiJoin runs. + if (joining) main.post { WifiJoin.release() } + SoundLog.write(context.applicationContext, SoundLog.stopped() + ": by an MCP client") + state = State(Phase.STOPPED, "Stopped.") + return true + } + + /** import_listen's and import_status's report. Never the hotspot's password. */ + fun status(): JSONObject { + val s = state + val out = JSONObject().put("phase", s.phase.name.lowercase()).put("message", s.message) + if (s.phase == Phase.LISTENING) out.put("seconds_left", s.secondsLeft).put("hearing", when { + s.signal < 0.15 -> "nothing" + s.signal < SoundDecoder.THRESHOLD -> "faint" + else -> "tones" + }) + s.code?.let { out.put("code", ShareCodes.display(it)) } + s.ssid?.let { out.put("owner_network", it) } + if (s.phase == Phase.PERSON_NEEDED) out.put("person_needed", s.message) + return out + } +} +// END OF SoundImport.kt diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundIo.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundIo.kt new file mode 100644 index 000000000..ebe4418ad --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundIo.kt @@ -0,0 +1,197 @@ +package org.appdevforall.shareyourapps.server + +import android.Manifest +import android.annotation.SuppressLint +import android.content.Context +import android.content.pm.PackageManager +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioManager +import android.media.AudioRecord +import android.media.AudioTrack +import android.media.MediaRecorder +import android.os.Handler +import android.os.Looper +import kotlin.concurrent.thread +import org.appdevforall.shareyourapps.server.SoundModem + +/** + * Moves the sound handshake through the phone's speaker and microphone. [SoundModem] and [SoundDecoder] do the + * signal work; this only plays and records, on background threads. Callbacks run on the main thread. The screens + * own a [Player] or [Listener] and stop it when they close, so nothing plays or listens off the screen. + */ +object SoundIo { + /** About how long a player plays, and the longest a listener listens, from the moment each starts. */ + const val WINDOW_MS = SoundModem.WINDOW_MS + /** How long a player waits for the speaker to finish what it was given. */ + private const val TAIL_MS = 2_000L + private val main = Handler(Looper.getMainLooper()) + + /** Whether the media volume is muted, or under a third of full: likely too quiet for the other phone. */ + fun volumeLow(context: Context): Boolean { + val am = context.getSystemService(AudioManager::class.java) ?: return false + val max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC) + return max > 0 && am.getStreamVolume(AudioManager.STREAM_MUSIC) * 3 < max + } + + fun canListen(context: Context): Boolean = + context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + + private fun pcm(x: FloatArray) = ShortArray(x.size) { i -> (x[i].coerceIn(-1f, 1f) * 32767).toInt().toShort() } + + /** + * Plays [data] as media sound: [bursts] bursts in a row, as many as fit in [WINDOW_MS] (see + * [SoundModem.burstsFor]), until they are all played or [stop]. [progress] gets the number of bursts played so + * far, counted from what the speaker has played, not from what is queued. [ended] gets null, or why it failed. + */ + class Player(private val data: ByteArray, private val ended: (String?) -> Unit, private val progress: ((Int) -> Unit)?) { + @Volatile private var stopped = false + /** How many bursts it plays in all, if it isn't stopped. */ + val bursts: Int = SoundModem().burstsFor(data.size) + /** Bursts played so far, for the log; read it in [ended]. */ + @Volatile var burstsPlayed = 0; private set + /** Whether [stop] ended it, rather than it playing all its bursts; read it in [ended]. */ + val stoppedEarly: Boolean get() = stopped + + fun start(): Player { thread(name = "sound-play") { run() }; return this } + fun stop() { stopped = true } + + private fun run() { + val modem = SoundModem() + var error: String? = null + var track: AudioTrack? = null + try { + val period = modem.burstPeriod(data.size) + // The three repeats, played over until all the bursts are out: the same sound as [bursts] bursts, made at once. + val round = pcm(modem.play(data, SoundModem.REPEATS)) + val total = bursts * period + val min = AudioTrack.getMinBufferSize(modem.sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) + val t = AudioTrack.Builder() + .setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()) + .setAudioFormat(AudioFormat.Builder().setSampleRate(modem.sampleRate) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build()) + .setTransferMode(AudioTrack.MODE_STREAM) + .setBufferSizeInBytes(maxOf(min, modem.sampleRate / 5 * 2)) // about 200 ms + .build() + track = t + t.play() + // The speaker's own count of what it has played, so the countdown follows the sound. + fun report() { + val done = minOf(bursts, t.playbackHeadPosition / period) + if (done > burstsPlayed) { burstsPlayed = done; main.post { progress?.invoke(done) } } + } + var at = 0 + while (at < total && !stopped) { + val from = at % round.size + val n = t.write(round, from, minOf(4096, round.size - from, total - at)) + if (n < 0) { error = "The speaker refused the sound (error $n)."; break } + at += n + report() + } + // Let the buffer finish playing, reporting the last bursts as they sound. + val tail = System.currentTimeMillis() + TAIL_MS + while (error == null && !stopped && t.playbackHeadPosition < total && System.currentTimeMillis() < tail) { + report(); Thread.sleep(50) + } + if (error == null && !stopped && t.playbackHeadPosition >= total && burstsPlayed < bursts) { + burstsPlayed = bursts; main.post { progress?.invoke(bursts) } + } else report() + } catch (e: Exception) { + error = "Couldn't play the sound: ${e.message ?: e.toString()}" + } finally { + try { track?.pause(); track?.flush() } catch (e: Exception) { } + track?.release() + } + main.post { ended(error) } + } + } + + enum class End { STOPPED, NOTHING_HEARD, NO_MICROPHONE, FAILED } + + /** How often a listener reports its [Level]: about ten times a second, smooth enough for a meter. */ + const val LEVEL_MS = 100L + + /** + * What a listener reports while it listens: [signal], the strongest start signal so far (0 to 1); [db], the + * microphone's loudest moment since the last report, in dB of full scale (SoundDsp.METER_FLOOR_DB to 0); + * and [msLeft], the time left before it gives up. + */ + class Level(val signal: Double, val db: Double, val msLeft: Long) + + /** + * Records at [SoundModem.SAMPLE_RATE] until it hears a valid [SoundPayload], [stop], or [WINDOW_MS]. [level] gets a + * [Level] about ten times a second: the strongest start signal so far, the microphone's loudness, and the time + * left; [heard] gets the payload and how it was heard (for the log); otherwise [ended] says why it stopped. + * The caller asks for RECORD_AUDIO first. + */ + class Listener( + private val context: Context, + private val level: (Level) -> Unit, + private val heard: (SoundPayload, String) -> Unit, + private val ended: (End, String) -> Unit, + ) { + @Volatile private var stopped = false + + fun start(): Listener { thread(name = "sound-listen") { run() }; return this } + fun stop() { stopped = true } + + /** UNPROCESSED where the phone supports it: noise suppression can remove tones. Else VOICE_RECOGNITION, also lightly processed. */ + private fun source(): Int { + val am = context.getSystemService(AudioManager::class.java) + return if (am?.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED) == "true") + MediaRecorder.AudioSource.UNPROCESSED else MediaRecorder.AudioSource.VOICE_RECOGNITION + } + + @SuppressLint("MissingPermission") // checked by the screen before starting; a SecurityException is caught + private fun run() { + val modem = SoundModem() + var payload: SoundPayload? = null + val decoder = SoundDecoder(modem) { b -> SoundPayload.decode(b)?.also { payload = it } != null } + var record: AudioRecord? = null + var end = End.STOPPED + var why = "Stopped." + var found: SoundPayload? = null + try { + val rate = modem.sampleRate + val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) + if (min <= 0) { end = End.FAILED; why = "This phone can't record at $rate Hz."; return } + val r = AudioRecord(source(), rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate)) + record = r + if (r.state != AudioRecord.STATE_INITIALIZED) { end = End.NO_MICROPHONE; why = "The microphone couldn't be opened."; return } + r.startRecording() + val chunk = ShortArray(2048) + val f = FloatArray(chunk.size) + val deadline = System.currentTimeMillis() + WINDOW_MS + var lastLevel = 0L + // The loudest chunk since the last report, so a short tone isn't missed between reports. + var loudest = SoundDsp.METER_FLOOR_DB + while (!stopped) { + val now = System.currentTimeMillis() + if (now > deadline) { end = End.NOTHING_HEARD; why = "Didn't hear the code."; break } + val n = r.read(chunk, 0, chunk.size) + if (n < 0) { end = End.FAILED; why = "The microphone stopped (error $n)."; break } + for (i in 0 until n) f[i] = chunk[i] / 32768f + if (n > 0) loudest = maxOf(loudest, SoundDsp.rmsDb(f, 0, n)) + if (decoder.feed(f, 0, n) != null) { found = payload; break } + if (now - lastLevel >= LEVEL_MS) { + lastLevel = now + val v = Level(decoder.bestSignal, loudest, maxOf(0L, deadline - now)) + loudest = SoundDsp.METER_FLOOR_DB + main.post { level(v) } + } + } + } catch (e: SecurityException) { + end = End.NO_MICROPHONE; why = "The app isn't allowed to use the microphone." + } catch (e: Exception) { + end = End.FAILED; why = "Couldn't listen: ${e.message ?: e.toString()}" + } finally { + try { record?.stop() } catch (e: Exception) { } + record?.release() + val p = found + val how = decoder.how + if (p != null) main.post { heard(p, how) } else main.post { ended(end, why) } + } + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundLog.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundLog.kt new file mode 100644 index 000000000..4e16b4265 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundLog.kt @@ -0,0 +1,75 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import java.util.Locale + +/** + * The sound handshake's `[sound]` lines in the app's own log, so they show in View logs. + * + * The lines' text is built by plain functions, unit-tested, which never include a password. Where a line goes: + * - On the sharing phone the server is running (sharing needs it), and its process owns the log file, so + * ShareActivity sends [line] to it with Ipc.MSG_LOG over the connection it already has. + * - On the importing phone the server isn't running (importing is refused while serving), so [write] appends + * the line here, in the main process. It writes nothing while a server serves, so two processes never + * write the file at once; the line still goes to logcat. + */ +object SoundLog { + const val TAG = "sound" + private const val LOGCAT_TAG = "ShareYourAppsSound" + + /** The whole line, as the server's log writes it: `[sound] message`. */ + fun line(message: String) = "[$TAG] $message" + + fun played(burstsPlayed: Int, bursts: Int, stoppedEarly: Boolean, volumeLow: Boolean, ownHotspot: Boolean, error: String?): String { + val what = if (ownHotspot) "the code and this phone's hotspot name and password" else "the code" + // Stopped before one whole burst: "part of the first burst", which reads better than "0 of 36". + val count = if (burstsPlayed == 0 && error == null) "part of the first burst" else "$burstsPlayed of $bursts bursts" + val b = StringBuilder("played $what: $count") + when { + error != null -> b.append(", failed: ").append(error) + stoppedEarly -> b.append(", stopped early") + else -> b.append(", all bursts played") + } + if (volumeLow) b.append("; media volume was low") + return b.toString() + } + + /** A code heard from another phone: never its password, only whether one came. */ + fun heard(p: SoundPayload, how: String): String { + val b = StringBuilder("heard code ${ShareCodes.display(p.code)} ($how)") + if (p.address != null) b.append(", server ").append(p.address.hostAddress).append(':').append(p.port) + when { + p.ssid != null && p.password != null -> b.append(", its own hotspot ").append(p.ssid).append(" (password received, not logged)") + p.ssid != null -> b.append(", on Wi-Fi ").append(p.ssid) + p.ownHotspot -> b.append(", its own hotspot") + else -> b.append(", no network name") + } + return b.toString() + } + + fun nothingHeard(seconds: Long, strongest: Double) = + "heard nothing in $seconds s (strongest start signal ${String.format(Locale.ROOT, "%.2f", strongest)})" + + fun microphoneRefused() = "can't listen: the microphone permission was refused" + + fun listenFailed(why: String) = "listening failed: $why" + + fun stopped() = "stopped listening" + + fun selfTest(passed: Boolean, detail: String) = + if (passed) "self-test passed ($detail)" else "self-test failed: $detail" + + /** Appends a line from the main process, when no server is writing the log; always to logcat too. */ + fun write(context: Context, message: String) { + android.util.Log.i(LOGCAT_TAG, line(message)) + if (ServerStatus.url != null) return // the server process owns the log file while it serves + try { + val prefs = context.getSharedPreferences(HostService.PREFS, Context.MODE_PRIVATE) + val limit = prefs.getInt(HostService.PREF_LOG_MB, HostService.DEFAULT_LOG_MB).toLong() * 1024 * 1024 + val log = StoreLog(Store.logDir(context), limit) + try { log.status(TAG, message) } finally { log.close() } + } catch (e: Exception) { + // Logging must never break the handshake. + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundModem.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundModem.kt new file mode 100644 index 000000000..d39613d8c --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundModem.kt @@ -0,0 +1,144 @@ +package org.appdevforall.shareyourapps.server + +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin + +/** + * Turns handshake bytes into sound; [SoundDecoder] turns sound back into bytes. Plain Kotlin, no Android code. + * The modem doesn't know what the bytes mean: the listener checks each candidate (with SoundPayload's CRC). + * + * One burst: a rising sweep (the start signal), a short gap, a header of 3 bytes — the length, the length + * inverted, and the repeat number with its inverse in the low 4 bits — then the data. Each byte is two tones, + * high 4 bits first; each tone is one of 16, held for [SYMBOL_MS] with soft edges so it doesn't click. + * Even and odd tones use separate, interleaved sets of 16 frequencies, so a room's echo of one tone can't pass + * for the next. All 32 frequencies lie within one octave (2400 to 4725 Hz), so a distorting speaker's + * harmonics fall above them. + * + * Each repeat scrambles the data with its own key (the header isn't scrambled): a value sent on a weak or noisy + * frequency in one repeat goes out on another in the next. At every position, the three repeats' keys differ. + */ +class SoundModem(val sampleRate: Int = SAMPLE_RATE) { + val chirpLength = ms(CHIRP_MS) + val gapLength = ms(GAP_MS) + val symbolLength = ms(SYMBOL_MS) + val repeatGap = ms(REPEAT_GAP_MS) + private val edge = ms(EDGE_MS) + + /** The start signal, at full scale: a linear sweep from [CHIRP_LOW_HZ] to [CHIRP_HIGH_HZ]. */ + val chirp: FloatArray = run { + val seconds = chirpLength.toDouble() / sampleRate + val ends = ms(5.0) + FloatArray(chirpLength) { i -> + val t = i.toDouble() / sampleRate + val phase = 2 * PI * (CHIRP_LOW_HZ * t + (CHIRP_HIGH_HZ - CHIRP_LOW_HZ) * t * t / (2 * seconds)) + (sin(phase) * ramp(i, chirpLength, ends)).toFloat() + } + } + + fun ms(m: Double): Int = (m * sampleRate / 1000).toInt() + + /** Samples in one burst carrying [dataBytes] bytes. */ + fun frameLength(dataBytes: Int): Int = chirpLength + gapLength + (HEADER_BYTES + dataBytes) * 2 * symbolLength + + /** Samples from the start of one burst carrying [dataBytes] bytes to the start of the next. */ + fun burstPeriod(dataBytes: Int): Int = frameLength(dataBytes) + repeatGap + + /** + * How many bursts a player plays for [dataBytes] bytes: as many as fit in [WINDOW_MS], but at least [MIN_BURSTS], + * so a listener that joins in the middle of a burst still hears [REPEATS] whole ones to combine. A short code gets + * dozens; a hotspot's name and password, whose bursts last about 7 s, get 4. + */ + fun burstsFor(dataBytes: Int): Int = + maxOf(MIN_BURSTS, (WINDOW_MS * sampleRate / 1000 / burstPeriod(dataBytes)).toInt()) + + /** One burst: the start signal, the header and [data], scrambled for [repeat] (0 to [REPEATS] - 1). */ + fun burst(data: ByteArray, repeat: Int): FloatArray { + require(data.size in 1..MAX_BYTES) { "a burst carries 1 to $MAX_BYTES bytes" } + require(repeat in 0 until REPEATS) { "the repeat must be 0 to ${REPEATS - 1}" } + val out = FloatArray(frameLength(data.size)) + for (i in chirp.indices) out[i] = (chirp[i] * VOLUME).toFloat() + var at = chirpLength + gapLength + for ((k, tone) in symbols(data, repeat).withIndex()) { + val w = 2 * PI * toneHz(k, tone) / sampleRate + for (i in 0 until symbolLength) out[at + i] = (VOLUME * sin(w * i) * ramp(i, symbolLength, edge)).toFloat() + at += symbolLength + } + return out + } + + /** [count] bursts in a row, repeats 0, 1, 2, 0, …, with a short gap after each. */ + fun play(data: ByteArray, count: Int = REPEATS): FloatArray { + val one = burstPeriod(data.size) + val out = FloatArray(one * count) + for (r in 0 until count) burst(data, r % REPEATS).copyInto(out, r * one) + return out + } + + companion object { + const val SAMPLE_RATE = 44100 + const val LOW_HZ = 2400.0 + const val SPACING_HZ = 75.0 + const val TONES = 16 + const val CHIRP_LOW_HZ = 2400.0 + const val CHIRP_HIGH_HZ = 4800.0 + const val CHIRP_MS = 150.0 + const val GAP_MS = 20.0 + const val SYMBOL_MS = 30.0 + const val EDGE_MS = 3.0 + const val REPEAT_GAP_MS = 100.0 + /** Of full scale: loud enough for a noisy room, quiet enough not to distort a small speaker. */ + const val VOLUME = 0.7 + const val REPEATS = 3 + /** How long a player plays and a listener listens, from the moment each starts. */ + const val WINDOW_MS = 30_000L + /** The fewest bursts a player plays, however long each is. */ + const val MIN_BURSTS = REPEATS + 1 + const val HEADER_BYTES = 3 + const val MAX_BYTES = 255 + const val MAX_SYMBOLS = 2 * MAX_BYTES + + /** The frequency of tone [tone] (0–15) at symbol position [k]: even and odd positions use different sets. */ + fun toneHz(k: Int, tone: Int): Double = LOW_HZ + SPACING_HZ * (2 * tone + (k and 1)) + + /** The tone numbers (0–15) of a burst, in order: the header plain, the data scrambled for [repeat]. */ + fun symbols(data: ByteArray, repeat: Int): IntArray { + val n = data.size + val header = intArrayOf(n, n xor 0xFF, (repeat shl 4) or (repeat.inv() and 0x0F)) + val out = IntArray((HEADER_BYTES + n) * 2) + var k = 0 + for (b in header) { out[k++] = b shr 4; out[k++] = b and 0x0F } + for ((i, b) in data.withIndex()) { + val v = b.toInt() and 0xFF + out[k++] = (v shr 4) xor key(repeat, 2 * i) + out[k++] = (v and 0x0F) xor key(repeat, 2 * i + 1) + } + return out + } + + /** The scrambling key for data symbol [i] of [repeat]: XOR with it moves each value to a different tone. */ + fun key(repeat: Int, i: Int): Int = KEYS[repeat][i] + + private val KEYS: Array = run { + var s = 0x2545F4914F6CDD1DL + fun next(): Int { s = s * 6364136223846793005L + 1442695040888963407L; return ((s ushr 33) and 0x7FFFFFFF).toInt() } + val k0 = IntArray(MAX_SYMBOLS); val k1 = IntArray(MAX_SYMBOLS); val k2 = IntArray(MAX_SYMBOLS) + for (i in 0 until MAX_SYMBOLS) { + k0[i] = next() and 15 + val d1 = 1 + next() % 15 + var d2 = 1 + next() % 15 + if (d2 == d1) d2 = 1 + d2 % 15 + k1[i] = k0[i] xor d1; k2[i] = k0[i] xor d2 + } + arrayOf(k0, k1, k2) + } + + /** A raised-cosine fade over the first and last [e] of [n] samples. */ + fun ramp(i: Int, n: Int, e: Int): Double = when { + e <= 0 -> 1.0 + i < e -> 0.5 - 0.5 * cos(PI * i / e) + i >= n - e -> 0.5 - 0.5 * cos(PI * (n - 1 - i) / e) + else -> 1.0 + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundPayload.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundPayload.kt new file mode 100644 index 000000000..d4b60d874 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SoundPayload.kt @@ -0,0 +1,173 @@ +package org.appdevforall.shareyourapps.server + +import java.io.ByteArrayOutputStream +import java.net.Inet4Address +import java.net.InetAddress +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import java.nio.charset.StandardCharsets + +/** + * What a sharing phone plays as sound for the handshake: the share code, where its server is, and, for the + * sender's own hotspot only, how to join it. Sound is for the handshake only; the copy itself still goes over + * Wi-Fi, and a person still taps Allow. Plain Kotlin, with no Android code, so it's unit-tested on its own. + * + * Layout, in bytes: + * - 1: version (high 4 bits, now 1) and flags (low 4 bits: own hotspot, has address, has SSID, has password) + * - 5: the share code, 8 characters of 5 bits each + * - 6: IPv4 address and port, if it has an address + * - 1 + n: SSID length and SSID (UTF-8), if it has one + * - 1 + n: password length and password (UTF-8), if it has one + * - 2: CRC-16/CCITT-FALSE of everything before it + * + * Typically about 46 bytes for the sender's own hotspot, and 14 to 30 for other Wi-Fi. Lengths are fields, so + * the only limit is what one length byte holds: 255 bytes each. + * + * Rules: a password is sent only for the sender's own hotspot, never for other Wi-Fi, and only with the + * network's name. [toString] never shows the password, so a payload can be logged. + */ +data class SoundPayload( + /** The normalized share code: 8 characters of [ALPHABET], as ShareCodes.normalize returns it. */ + val code: String, + val address: Inet4Address? = null, + /** The store server's port; 0 when there's no address. */ + val port: Int = 0, + /** The sender serves on its own hotspot (Wi-Fi Direct or local-only), not on other Wi-Fi. */ + val ownHotspot: Boolean = false, + val ssid: String? = null, + val password: String? = null, +) { + init { + require(code.length == CODE_CHARS && code.all { it in ALPHABET }) { "not a normalized share code" } + if (address != null) require(port in 1..65535) { "the port must be 1 to 65535" } + else require(port == 0) { "a port needs an address" } + if (ssid != null) require(ssid.isNotEmpty() && utf8(ssid).size <= MAX_FIELD) { "the network name must be 1 to $MAX_FIELD bytes" } + if (password != null) { + require(ownHotspot) { "a password is only sent for the sender's own hotspot" } + require(ssid != null) { "a password needs the network's name" } + require(password.isNotEmpty() && utf8(password).size <= MAX_FIELD) { "the password must be 1 to $MAX_FIELD bytes" } + } + } + + fun encode(): ByteArray { + val out = ByteArrayOutputStream() + var flags = 0 + if (ownHotspot) flags = flags or OWN_HOTSPOT + if (address != null) flags = flags or HAS_ADDRESS + if (ssid != null) flags = flags or HAS_SSID + if (password != null) flags = flags or HAS_PASSWORD + out.write((VERSION shl 4) or flags) + packCode(code).let { out.write(it, 0, it.size) } + if (address != null) { + val a = address.address + out.write(a, 0, a.size) + out.write(port shr 8); out.write(port and 0xFF) + } + ssid?.let { field(out, it) } + password?.let { field(out, it) } + val body = out.toByteArray() + val crc = crc16(body, body.size) + out.write(crc shr 8); out.write(crc and 0xFF) + return out.toByteArray() + } + + override fun toString(): String = + "SoundPayload(code=$code, address=${address?.hostAddress}, port=$port, ownHotspot=$ownHotspot, " + + "ssid=$ssid, password=${if (password != null) "hidden" else "none"})" + + companion object { + const val VERSION = 1 + const val OWN_HOTSPOT = 1 + const val HAS_ADDRESS = 2 + const val HAS_SSID = 4 + const val HAS_PASSWORD = 8 + /** The share code's characters, Crockford base32, as in ShareCodes. */ + const val ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + const val CODE_CHARS = 8 + const val CODE_BYTES = 5 + /** The most one length byte holds. */ + const val MAX_FIELD = 255 + /** Version and flags, the code, and the CRC: a payload with nothing else. */ + const val MIN_SIZE = 1 + CODE_BYTES + 2 + + /** + * Reads a payload, or returns null if it isn't one exactly: a wrong CRC or version, cut-off or extra + * bytes, text that isn't UTF-8, or fields that break the rules (such as a password for other Wi-Fi). + */ + fun decode(bytes: ByteArray): SoundPayload? { + if (bytes.size < MIN_SIZE) return null + val body = bytes.size - 2 + val crc = ((bytes[body].toInt() and 0xFF) shl 8) or (bytes[body + 1].toInt() and 0xFF) + if (crc16(bytes, body) != crc) return null + val head = bytes[0].toInt() and 0xFF + if ((head shr 4) != VERSION) return null + val flags = head and 0x0F + var i = 1 + val code = unpackCode(bytes, i); i += CODE_BYTES + var address: Inet4Address? = null + var port = 0 + if ((flags and HAS_ADDRESS) != 0) { + if (i + 6 > body) return null + address = InetAddress.getByAddress(bytes.copyOfRange(i, i + 4)) as Inet4Address + port = ((bytes[i + 4].toInt() and 0xFF) shl 8) or (bytes[i + 5].toInt() and 0xFF) + i += 6 + } + fun field(): String? { + if (i >= body) return null + val n = bytes[i].toInt() and 0xFF + i++ + if (n == 0 || i + n > body) return null + val s = utf8Strict(bytes, i, n) ?: return null + i += n + return s + } + val ssid = if ((flags and HAS_SSID) != 0) (field() ?: return null) else null + val password = if ((flags and HAS_PASSWORD) != 0) (field() ?: return null) else null + if (i != body) return null + return try { + SoundPayload(code, address, port, (flags and OWN_HOTSPOT) != 0, ssid, password) + } catch (e: IllegalArgumentException) { null } + } + + /** CRC-16/CCITT-FALSE (polynomial 0x1021, starting at 0xFFFF) of the first [length] bytes. */ + fun crc16(b: ByteArray, length: Int): Int { + var crc = 0xFFFF + for (k in 0 until length) { + crc = crc xor ((b[k].toInt() and 0xFF) shl 8) + repeat(8) { + crc = if ((crc and 0x8000) != 0) ((crc shl 1) xor 0x1021) and 0xFFFF else (crc shl 1) and 0xFFFF + } + } + return crc + } + + private fun packCode(code: String): ByteArray { + var v = 0L + for (c in code) v = (v shl 5) or ALPHABET.indexOf(c).toLong() + return ByteArray(CODE_BYTES) { k -> (v shr (8 * (CODE_BYTES - 1 - k))).toByte() } + } + + private fun unpackCode(b: ByteArray, at: Int): String { + var v = 0L + for (k in 0 until CODE_BYTES) v = (v shl 8) or (b[at + k].toLong() and 0xFF) + return (0 until CODE_CHARS).map { k -> ALPHABET[((v shr (5 * (CODE_CHARS - 1 - k))) and 31).toInt()] }.joinToString("") + } + + private fun utf8(s: String) = s.toByteArray(StandardCharsets.UTF_8) + + private fun field(out: ByteArrayOutputStream, s: String) { + val b = utf8(s) + out.write(b.size) + out.write(b, 0, b.size) + } + + /** Decodes UTF-8, refusing malformed bytes rather than replacing them. */ + private fun utf8Strict(b: ByteArray, at: Int, n: Int): String? = try { + StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(b, at, n)).toString() + } catch (e: CharacterCodingException) { null } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreFiles.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreFiles.kt new file mode 100644 index 000000000..5b7df5755 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreFiles.kt @@ -0,0 +1,77 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.IOException + +/** + * The only way the server finds files to serve. Every request path is resolved against the + * Store directory's canonical path — which follows symlinks — and anything that doesn't + * land inside it is refused. + */ +class StoreFiles(root: File) { + + private val rootDir: File = root.canonicalFile + private val rootPrefix: String = rootDir.path + File.separator + + fun hasIndex(): Boolean = resolve("index.html") != null + + /** The regular file at [relative] inside the Store directory, or null. */ + fun resolve(relative: String): File? { + if (relative.isEmpty() || relative.startsWith("/") || relative.contains('\u0000')) return null + if (relative.split('/').any { it == ".." }) return null + val f = try { File(rootDir, relative).canonicalFile } catch (e: IOException) { return null } + if (!f.path.startsWith(rootPrefix)) return null + return if (f.isFile) f else null + } + + companion object { + /** A .gz file's original size, from its last four bytes — modulo 4 GB, so only for smaller files. */ + fun gzipSize(gz: File): Long = java.io.RandomAccessFile(gz, "r").use { f -> + f.seek(f.length() - 4); val b = ByteArray(4); f.readFully(b) + (b[0].toLong() and 0xff) or ((b[1].toLong() and 0xff) shl 8) or ((b[2].toLong() and 0xff) shl 16) or ((b[3].toLong() and 0xff) shl 24) + } + + /** Writes [count] bytes of [gz]'s original contents, from [offset], decompressing it on the way. */ + fun gunzipSlice(gz: File, offset: Long, count: Long, out: java.io.OutputStream) { + java.util.zip.GZIPInputStream(java.io.BufferedInputStream(java.io.FileInputStream(gz), 64 * 1024), 64 * 1024).use { input -> + var skip = offset + while (skip > 0) { val n = input.skip(skip); if (n <= 0) { if (input.read() < 0) return; skip-- } else skip -= n } + val buf = ByteArray(64 * 1024); var left = count + while (left > 0) { val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) break; out.write(buf, 0, n); left -= n } + } + } + + private val TYPES = mapOf( + "apk" to "application/vnd.android.package-archive", + "zip" to "application/zip", + "html" to "text/html; charset=utf-8", "htm" to "text/html; charset=utf-8", + "txt" to "text/plain; charset=utf-8", + "css" to "text/css", "js" to "text/javascript", "json" to "application/json", + "png" to "image/png", "jpg" to "image/jpeg", "jpeg" to "image/jpeg", + "gif" to "image/gif", "webp" to "image/webp", "svg" to "image/svg+xml", + "ico" to "image/x-icon", + "mp4" to "video/mp4", "webm" to "video/webm", + "mp3" to "audio/mpeg", "ogg" to "audio/ogg", "wav" to "audio/wav", "m4a" to "audio/mp4", + ) + + fun contentType(name: String): String = + TYPES[name.substringAfterLast('.', "").lowercase()] ?: "application/octet-stream" + + /** APKs and zips download under their real name; everything else displays inline. */ + fun disposition(name: String): String? { + val ext = name.substringAfterLast('.', "").lowercase() + if (ext != "apk" && ext != "zip") return null + val ascii = name.map { if (it.code in 0x20..0x7e && it != '"' && it != '\\') it else '_' } + .joinToString("") + return "attachment; filename=\"$ascii\"; filename*=UTF-8''${pctEncode(name)}" + } + + private fun pctEncode(s: String): String = buildString { + for (b in s.toByteArray(Charsets.UTF_8)) { + val c = b.toInt() and 0xff + if (c.toChar().isLetterOrDigit() && c < 0x80 || c.toChar() in "-._~") append(c.toChar()) + else append('%').append("%02X".format(c)) + } + } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreLog.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreLog.kt new file mode 100644 index 000000000..1197db2df --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/StoreLog.kt @@ -0,0 +1,93 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * The access log. Thread-safe: every write and every rotation happen under one lock, + * so no line can land in a file that is being closed or renamed. + * + * Keeps at most five files: access.log plus access.log.1 … access.log.4. + * maxBytes = 0 turns logging off. + */ +class StoreLog(private val dir: File, private val maxBytes: Long) { + + companion object { + const val FILE_NAME = "access.log" + const val KEEP = 5 + } + + private val file = File(dir, FILE_NAME) + private var out: FileOutputStream? = null + private val dateFormat = SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US) + + @Synchronized + fun write(line: String) { + if (maxBytes <= 0) return + try { + val o = out ?: open().also { out = it } + o.write((line + "\n").toByteArray(Charsets.UTF_8)) + o.flush() + if (file.length() >= maxBytes) rotate() + } catch (e: IOException) { + // Logging must never break serving. + } + } + + /** + * A plain-text status line, timestamped like a request line, e.g. + * `[03/Oct/2026:17:30:20 -0700] [server] serving Store_12345678 on 192.168.1.5:6175`. + * Synchronized: [dateFormat] isn't thread-safe. [LogFilter.isStatus] relies on this shape. + */ + @Synchronized + fun status(tag: String, message: String) = write("[${dateFormat.format(Date())}] [$tag] $message") + + /** + * A status line already written as `[tag] message`, such as the `[hotspot]` and `[server]` lines the main + * process sends over (Ipc.MSG_LOG, Ipc.KEY_LOG_LINES): timestamped here, when it's written, like [status]. + */ + @Synchronized + fun statusLine(line: String) = write("[${dateFormat.format(Date())}] $line") + + /** One Apache combined-format line, plus the transfer rate. */ + @Synchronized + fun access( + client: String, requestLine: String, status: Int, bytes: Long, + referer: String?, userAgent: String?, millis: Long, + ) { + val rate = if (millis > 0) bytes * 1000 / millis else bytes + val size = if (bytes > 0) bytes.toString() else "-" + write( + "$client - - [${dateFormat.format(Date())}] \"${q(requestLine)}\" $status $size " + + "\"${q(referer ?: "-")}\" \"${q(userAgent ?: "-")}\" ${rate}B/s" + ) + } + + @Synchronized + fun close() { + try { out?.close() } catch (e: IOException) { } + out = null + } + + private fun open(): FileOutputStream { + dir.mkdirs() + return FileOutputStream(file, true) + } + + private fun rotate() { + try { out?.close() } catch (e: IOException) { } + out = null + File(dir, "$FILE_NAME.${KEEP - 1}").delete() + for (i in KEEP - 2 downTo 1) { + val f = File(dir, "$FILE_NAME.$i") + if (f.exists()) f.renameTo(File(dir, "$FILE_NAME.${i + 1}")) + } + file.renameTo(File(dir, "$FILE_NAME.1")) + } + + private fun q(s: String) = s.replace("\\", "\\\\").replace("\"", "\\\"") +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SystemBars.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SystemBars.kt new file mode 100644 index 000000000..d7b656fe3 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/SystemBars.kt @@ -0,0 +1,55 @@ +package org.appdevforall.shareyourapps.server + +import android.graphics.Insets +import android.os.Build +import android.view.View +import android.view.ViewGroup +import android.view.WindowInsets + +/** + * Edge-to-edge (Android 15 and later): apps targeting Android 15+ are drawn behind the status and + * navigation bars, and must keep their content clear themselves. This app targets Android 16, which + * ignores the old opt-out. So each screen's content pads itself by how much the bars — and any + * camera cutout — actually overlap it, measured where it really sits. On Android 16 the title bar + * (the action bar) overlaps the content too, so its bottom edge counts as well, found and measured + * in the window: where the title bar already pushes the content down, the content is below it, and + * nothing more is added. On Android 14 and older, nothing changes. + */ +object SystemBars { + fun fit(root: View) { + if (Build.VERSION.SDK_INT < 35) return + val base = intArrayOf(root.paddingLeft, root.paddingTop, root.paddingRight, root.paddingBottom) + (root as? ViewGroup)?.clipToPadding = false // scrolling content can pass under the bars, but always scroll clear of them + root.setOnApplyWindowInsetsListener { v, insets -> + val bars = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()) + v.post { pad(v, bars, base) } // after layout, so its position in the window is known + insets + } + root.requestApplyInsets() + } + + /** Where the title bar ends in the window, if one is showing; 0 if not. */ + private fun titleBarBottom(v: View, statusBarBottom: Int): Int { + val activity = v.context as? android.app.Activity ?: return 0 + val bar = activity.actionBar?.takeIf { it.isShowing } ?: return 0 + val id = v.resources.getIdentifier("action_bar_container", "id", "android") + val view = if (id != 0) activity.window.decorView.findViewById(id) else null + if (view != null && view.height > 0) { + val at = IntArray(2); view.getLocationInWindow(at) + return at[1] + view.height + } + return statusBarBottom + bar.height // below the status bar, if its view can't be found + } + + private fun pad(v: View, bars: Insets, base: IntArray) { + val at = IntArray(2); v.getLocationInWindow(at) + val window = v.rootView + val left = (bars.left - at[0]).coerceAtLeast(0) + val top = (maxOf(bars.top, titleBarBottom(v, bars.top)) - at[1]).coerceAtLeast(0) + val right = (at[0] + v.width - (window.width - bars.right)).coerceAtLeast(0) + val bottom = (at[1] + v.height - (window.height - bars.bottom)).coerceAtLeast(0) + val want = intArrayOf(base[0] + left, base[1] + top, base[2] + right, base[3] + bottom) + if (want[0] != v.paddingLeft || want[1] != v.paddingTop || want[2] != v.paddingRight || want[3] != v.paddingBottom) + v.setPadding(want[0], want[1], want[2], want[3]) + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/WifiJoin.kt b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/WifiJoin.kt new file mode 100644 index 000000000..95ea6c842 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/java/org/appdevforall/shareyourapps/server/WifiJoin.kt @@ -0,0 +1,127 @@ +package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.net.wifi.WifiNetworkSpecifier +import android.os.Build +import android.os.Handler +import android.os.Looper +import java.net.InetSocketAddress +import java.net.Socket + +/** + * Gets this phone onto the owner's network after hearing their tones (project B, step B5). Main process only; + * [join]'s answer and the release run on the main thread. + * + * 1. [reachable]: is the owner's server already reachable on this phone's Wi-Fi? Tried for about [REACH_MS]: + * a connection to the heard address, or, with none, a search for the code. + * 2. If not, and the tones carried the owner's own hotspot with its password, [join] asks Android to join it, on + * Android 10 and later. Android shows a "Connect?" prompt, and the person taps it. The network is this app's + * alone: where the phone can hold two Wi-Fi networks its other connections carry on; where it can't, they + * pause meanwhile. + * 3. Android keeps such a network only while the app holds its request. [holdUntilImportEnds] lets it go once + * the import is over (done, denied, cancelled, or failed with no Try again); [release] lets it go at once. + * A failed transfer that can be tried again keeps it, so Try again works; leaving the import screen then + * lets it go. + * + * On Android 9, or when the person doesn't tap Connect within [CONNECT_TAP_MS], the person joins by hand. + * The password is never logged. + */ +object WifiJoin { + /** How long to try the phone's current Wi-Fi before asking to join. */ + const val REACH_MS = 2_000 + /** How long to wait for the person to tap Connect. */ + const val CONNECT_TAP_MS = 30_000 + + private val main = Handler(Looper.getMainLooper()) + private var appCtx: Context? = null + private var cm: ConnectivityManager? = null + private var callback: ConnectivityManager.NetworkCallback? = null + private var holder: (() -> Unit)? = null + private var joinedSsid: String? = null + /** Whether Android joined the network asked for, as opposed to still asking or having refused. */ + private var joined = false + + /** Whether [join] can work on this phone: Android 10 or later. */ + val canJoin: Boolean get() = Build.VERSION.SDK_INT >= 29 + + /** Whether a join is still waiting for the person's Connect tap. */ + val asking: Boolean get() = callback != null && !joined + + /** + * Whether the owner's server answers on this phone's Wi-Fi: a connection to [address], or, with none, a search + * for [code], each for about [REACH_MS]. Blocks: call it off the main thread. + */ + fun reachable(context: Context, code: String, address: InetSocketAddress?): Boolean { + val wifi = wifiNetwork(context) ?: return false + return try { + if (address != null) Socket().use { s -> wifi.bindSocket(s); s.connect(address, REACH_MS); true } + else ShareDiscovery.find(code, timeoutMs = REACH_MS, bind = { wifi.bindSocket(it) }) != null + } catch (e: Exception) { false } + } + + /** + * Asks Android to join the hotspot [ssid] with [password], for this app only. [done] runs on the main thread, + * once: with the network, or null if the person didn't tap Connect within [CONNECT_TAP_MS], refused, or this + * phone can't. Nothing runs if [release] came first. The network stays joined until it's released. + */ + fun join(context: Context, ssid: String, password: String, done: (Network?) -> Unit) { + release() + if (Build.VERSION.SDK_INT < 29) { done(null); return } + val app = context.applicationContext + val c = app.getSystemService(ConnectivityManager::class.java) ?: run { done(null); return } + val request = try { + NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) // a hotspot has no internet + .setNetworkSpecifier(WifiNetworkSpecifier.Builder().setSsid(ssid).setWpa2Passphrase(password).build()) + .build() + } catch (e: Exception) { done(null); return } // a name or password Android won't take + var answered = false + lateinit var cb: ConnectivityManager.NetworkCallback + fun answer(n: Network?) { + if (answered || callback !== cb) return + answered = true + if (n == null) release() else joined = true + done(n) + } + cb = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { main.post { answer(network) } } + override fun onUnavailable() { main.post { answer(null) } } + } + appCtx = app; cm = c; callback = cb; joinedSsid = ssid + try { c.requestNetwork(request, cb, CONNECT_TAP_MS) } + catch (e: Exception) { callback = null; joinedSsid = null; done(null) } + } + + /** Lets the joined network go once the import is over: done, denied, cancelled, or failed with no Try again. */ + fun holdUntilImportEnds() { + holder?.let { ImportJob.remove(it) } + val l: () -> Unit = { val s = ImportJob.snapshot; if (!s.busy && !s.canRetry) release() } + holder = l + ImportJob.observe(l) + } + + /** Lets the joined network go now, if one is held or being asked for; the phone returns to its own Wi-Fi. */ + fun release() { + holder?.let { ImportJob.remove(it) } + holder = null + val cb = callback ?: return + callback = null + try { cm?.unregisterNetworkCallback(cb) } catch (e: Exception) { } + val ssid = joinedSsid + val wasJoined = joined + joinedSsid = null; joined = false + // Only a network Android actually joined is "let go of"; a request that got no Connect tap logs nothing here. + if (wasJoined) appCtx?.let { SoundLog.write(it, "let go of the owner's hotspot ${ssid ?: ""}".trimEnd()) } + } + + @Suppress("DEPRECATION") + private fun wifiNetwork(context: Context): Network? { + val c = context.getSystemService(ConnectivityManager::class.java) ?: return null + return c.allNetworks.firstOrNull { c.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true } + } +} diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/plugins/Share-Your-Apps/server/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 000000000..2b068d114 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_background.xml b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 000000000..07d5da9cb --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_round.webp new file mode 100644 index 000000000..ead67900d Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_background.xml b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_background.xml new file mode 100644 index 000000000..e15073caa --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_background.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_foreground.xml b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_foreground.xml new file mode 100644 index 000000000..3ecc97b0a --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_foreground.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_monochrome.xml b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_monochrome.xml new file mode 100644 index 000000000..f825331e7 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/drawable/ls_icon_monochrome.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..eca70cfe5 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..eca70cfe5 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher.xml b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher.xml new file mode 100644 index 000000000..1bce0e62e --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher_round.xml b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher_round.xml new file mode 100644 index 000000000..1bce0e62e --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-anydpi-v26/ls_launcher_round.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 000000000..d7bb5af94 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 000000000..bc9b71e29 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 000000000..b61d7366f Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 000000000..b003c0366 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 000000000..33b4e9935 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..a62f3b0c8 Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 000000000..21a284e0c Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..ead67900d Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 000000000..aa7d6427e Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..9126ae37c Binary files /dev/null and b/plugins/Share-Your-Apps/server/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/values-night/colors.xml b/plugins/Share-Your-Apps/server/app/src/main/res/values-night/colors.xml new file mode 100644 index 000000000..a6b3daec9 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/values-night/colors.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Share-Your-Apps/server/app/src/main/res/values-night/themes.xml b/plugins/Share-Your-Apps/server/app/src/main/res/values-night/themes.xml new file mode 100644 index 000000000..f5149ff89 --- /dev/null +++ b/plugins/Share-Your-Apps/server/app/src/main/res/values-night/themes.xml @@ -0,0 +1,5 @@ + + + + """ + +def page(title, body): + return f"{title}{STYLE}

{title}

{body}" + +PAGES = { + "index.html": page("Share Your Apps Server", """ +

Share Your Apps Server serves the store you publish with the Share Your Apps plugin in Code On The Go. +People on the same Wi-Fi network or hotspot open it in their phone's browser to download your apps and their source.

+

How it fits together

+
    +
  1. In Code On The Go, open the Share Your Apps tab, fill in your catalog, and tap Publish.
  2. +
  3. The plugin builds a new copy of the store and starts this server on it. You stay in Code On The Go.
  4. +
  5. This screen then shows Serving and the store's address, with a button beside it that copies it.
  6. +
+

Keeping it running

+

The server runs as a foreground service, shown by a notification, so it keeps serving while you use other apps. +Under When to run, choose Run always, or Pause when the screen turns off to save battery; it resumes when you unlock the phone.

+

Start serves the last store you published, or, on a phone holding an imported copy, the copy. To change what's in the store, publish again from the plugin.

+

No Wi-Fi? A hotspot

+

If you've turned on your phone's own Mobile hotspot in Settings, the server serves on it; buyers join it with the name and password from Settings. +Turning it off stops the server.

+

Otherwise, if the phone isn't on Wi-Fi when the server starts, it starts a hotspot of its own, and Manage Server shows its name and password. +Buyers join that network, then open the store's address. Switch Wi-Fi on (without joining a network) to get a Wi-Fi Direct hotspot, +whose name and password stay the same every time.

+

Storage access

+

The server needs permission to read the store's files from shared storage. If Grant storage access is showing, +tap it and allow access; it only needs doing once.

+

Help topics

+"""), + "log.html": page("Reading the access log", """ +

The log shows what the server has done, newest lines first. It keeps at most five files and starts a new one when +the current file reaches the size limit you set. A limit of 0 turns logging off.

+

Requests

+

Each request buyers make is one line, in the standard Apache format: the phone's address, the time, what was asked for, +the result code, the bytes sent, the browser, and the transfer rate. Code 200 means the file was sent, +302 is a redirect such as to the PIN page, and 404 means there was no such file.

+

Status lines

+

The server's own lines start with the time, then a tag in brackets, for example +[03/Oct/2026:17:30:20 -0700] [server] serving …. The tags are:

+
    +
  • [server] serving … — the server started, with the store it serves and its address.
  • +
  • [server] stopped serving …: reason — it stopped, and why.
  • +
  • [server] failed to start: … — it couldn't start, for the reason given.
  • +
  • [gzip] … — the server compressing the page and source zips in the background, so they download faster. Once a source zip's compressed copy is done, the zip itself is deleted, to save space — kept only the copy — and buyers are served from the copy. +not smaller means a compressed copy wouldn't have saved anything, so it was discarded.
  • +
  • [hotspot] … — the hotspot turning on or off.
  • +
  • [sound] … — Play sound and Listen: the tones played, a code heard (with which repeat it came from and how +strong the start signal was), nothing heard, or the self-test's result. A hotspot password heard in the tones is never written to the log.
  • +
+

Back to Share Your Apps Server

"""), + "serving.html": page("Serving the store", """ +

Status

+

The Status panel says whether the server is serving, and which store: your own, or an imported copy. While it serves, it shows +the store's address, with a button that copies it. The line below says what Start will serve.

+

Start, Stop and the port

+

Start serves the last store you published, or an imported copy, on a phone that holds one. Stop stops serving; +downloads under way end. The port is the number in the store's address, 6175 unless you change it. Change it only if another app +already uses that port; buyers' codes change with it.

+

The codes buyers scan

+

Show QR codes for buyers opens the Serve screen. On a hotspot, the first code joins buyers to its network, and the second +opens the store. On ordinary Wi-Fi, buyers join the same network themselves; the screen can make a join code if you type the +network's name and password, which are never saved. Done closes the screen; the store keeps serving.

+

A hotspot has no internet, so a buyer's phone may try mobile data instead, and fail to open the store. The Serve screen says so: +have them turn on airplane mode, then turn Wi-Fi back on, and turn airplane mode off afterwards.

+

Storage access

+

The server reads the store's files from shared storage. If Grant storage access shows, tap it and allow access, once.

+

Back to Share Your Apps Server

"""), + "hotspot.html": page("Hotspots", """ +

Which network buyers join

+
    +
  • Wi-Fi: if the phone is on Wi-Fi, buyers join the same network.
  • +
  • Your phone's Mobile hotspot: if it's on, and the phone isn't on Wi-Fi, the server uses it. Buyers join it with the name and +password from Settings.
  • +
  • A hotspot of the server's own: otherwise. With Wi-Fi switched on but not connected, it's a Wi-Fi Direct hotspot, whose name +and password stay the same. Without, it's Android's own hotspot, whose name and password change every time.
  • +
+

The Wi-Fi Direct hotspot's name and password

+

Its name is DIRECT-LS- and up to 22 more: letters, digits, spaces and punctuation count 1 each, accented letters 2, +and emoji 4. Its password is 8 to 63 letters, digits, spaces and ordinary punctuation, with no accented letters or emoji. +Suggest a password fills in a strong one; Save name & password keeps them, for the next time the hotspot starts. +Buyers who joined before must join again after a change.

+

Location, on Android 9 to 12

+

These versions won't start the server's own hotspot while Location is off. The server says so: turn Location on, then tap Start.

+

Back to Share Your Apps Server

"""), + "sharing.html": page("Sharing your store", """ +

Someone nearby can serve a copy of your store from their own phone. The copy is served exactly as you published it: they can't change +it, or pass it on. They set their own PIN, and it's deleted from their phone on the date you choose.

+

Sharing

+
    +
  1. While your own store is served, tap Share this store…. Right after a publish, it may first say Getting the store ready to share…
  2. +
  3. On their phone, they open Share Your Apps Server and tap Import a store, then scan the large QR code, or type the code.
  4. +
  5. You check the four digits and choose Allow, and the copy is sent.
  6. +
+

Each code serves one phone, for 10 minutes, and closes after five wrong codes. Both phones must be on the same Wi-Fi network, or +theirs on your hotspot. Cancel, or leaving the screen, ends the share; rotating the phone doesn't. Share again makes a +new code; Done closes the screen.

+

A phone without Share Your Apps Server

+

They scan the small QR code with the camera, and install the app it downloads from your phone. Then they scan the large one.

+

Play sound

+

Play sound plays the code as a short run of tones, so the other phone can hear it instead of scanning it: on their phone, +they tap Listen on the import screen. It repeats until their phone connects, for up to 30 seconds; Stop sound ends it sooner. +Turn the media volume up, and hold the phones close.

+

On a hotspot of the server's own, the tones also carry its name and password, so the other phone can join it. Anyone close +enough to hear them gets them too, as anyone who sees the Serve screen does. On other Wi-Fi, the tones never carry a password.

+

Allow or Deny

+

The four digits prove you're talking to the phone in front of you, not another on the same network. If they don't match both +screens, tap Deny; nothing is sent.

+

When the copy expires

+

In a week, in a month, on a date you choose, or never. On or after that date, it's deleted from their phone. To give them a +newer version, share again.

+

Back to Share Your Apps Server

"""), + "importing.html": page("Importing a store", """ +

Importing

+
    +
  1. Tap Import a store… in Manage server, or scan the owner's QR code with the camera and open the link.
  2. +
  3. The code is filled in, or type it; letters can be either case. Your phone's name is what the owner sees.
  4. +
  5. Tap Continue.
  6. +
+

Listen

+

Instead of scanning or typing the code, tap Listen, and ask the owner to tap Play sound on their share screen. +The first time, Android asks to let the app use the microphone; it listens only while this screen shows Listening…, for up to +30 seconds, and Android shows its microphone indicator meanwhile. Stop listening ends it sooner.

+

While it listens, the screen counts down the seconds left and shows a Microphone level meter, in dB: it rises with any sound +the microphone hears, voices and noise too, and is empty when it's quiet. The line above it says whether the tones themselves are heard: +Nothing heard yet, Hearing something faint (hold the phones closer), or Hearing the tones. +Turning the phone doesn't stop listening.

+

Once it hears the code, the import starts by itself, with your phone's name as shown. If it hears nothing, hold the phones closer, +ask the owner to turn up the media volume, and try again.

+

If this phone can already reach the owner's phone, the import starts at once. If the owner's phone serves on a hotspot of its own, +the tones carry its name and password: on Android 10 and later, Android asks whether to connect to it; tap Connect within +30 seconds. This phone uses that hotspot only for the import, and leaves it when the import ends. On Android 9, or without the tap, +the screen shows the hotspot's name and password: join it in Wi-Fi settings, then tap Continue.

+

If the owner's phone is on another Wi-Fi network, the tones carry its name, never its password: if the import can't find the +owner's phone, join that network, then tap Continue.

+

The four digits

+

Both screens show the same four digits. The owner checks them before allowing the copy.

+

While it arrives

+

Keep both phones close, with their screens on. You can leave the screen: a notification shows its progress. Cancel stops, +keeping nothing; a copy you already had stays as it was.

+

If it fails

+

Try again repeats the transfer while the owner's share screen stays open, with no new code. Start over begins again, +with a new code.

+

Can't import a store here

+

A phone that's serving a store can't import one, so a copy is never replaced under a running server. Stop serving first, or +import on another phone.

+

When it's imported

+

Serve it now starts serving the copy; Done leaves it for later. If the import happened over the owner's own network, +leave it before serving: join your own Wi-Fi, or turn Wi-Fi off, so the phone starts its own hotspot.

+

Back to Share Your Apps Server

"""), + "copies.html": page("Imported copies", """ +

The copy's panel

+

Manage server shows an imported copy in a panel of its own, with its name and expiry. It's served exactly as published: it can't be +changed, or passed on. A phone holds one copy at a time.

+

Serving it

+

Serve this store serves the copy. On a phone with no store of its own, Start serves it too. Publishing from the +plugin serves your own store instead, keeping the copy.

+

Its PIN

+

Up to 6 digits, which buyers enter before reaching the store, or none. It's yours, not the owner's.

+

Removing it

+

Remove this store asks first, then deletes the copy, stopping the server if it's serving it.

+

When it expires

+

On or after its date, the copy is deleted from the phone, and Manage server says A store has expired until you tap OK. +Downloads under way finish first. To serve it again, ask its owner for a new copy.

+

Back to Share Your Apps Server

"""), + "running.html": page("When to run, and logs", """ +

When to run

+

Run always keeps serving whatever the screen does. Pause when the screen turns off saves battery, and resumes when you +unlock the phone.

+

Logs

+

The log records buyers' requests and what the server does. Log size limit sets how large each file grows; 0 turns logging +off. View logs shows the newest lines first, and Export logs sends every log file off the phone. The log folder is +private to the app, since it records buyers' addresses. See Reading the access log.

+

Back to Share Your Apps Server

"""), + "mcp.html": page("MCP control", """ +

MCP control lets apps on this phone, such as an AI assistant, control Share Your Apps Server through the Model Context Protocol (MCP). +It's off until you turn it on, and only apps on this phone can reach it: other devices on the network can't.

+

Turning it on

+

Turn on MCP control in the Server panel. The app first says what it allows; tap Turn on, then allow the microphone +if Android asks. A notification shows while +it's on, with a Turn off button. The line under the switch says whether it's running.

+

After the phone restarts, it starts again the next time you open the app.

+

What apps can and can't do

+

Apps can start and stop the server, share this store and import a store. They can't change the store or approve a copy: +a person still taps Allow on the sharing phone.

+

When an app shares this store

+

The app gets a code for the other phone, as Share this store… shows. When the other phone asks for a copy, a notification +says so: tap it to open the share screen, check that the four digits match both phones, choose when the copy expires, and tap +Allow or Deny. Nothing is sent until you do.

+

Opening Share this store… while an app's share is under way shows that share, rather than making a new code, so the app's +code keeps working. Leaving the screen leaves the app's share open; Cancel ends it. A share you open yourself still ends +when you leave the screen.

+

If Pause when the screen turns off is chosen, the server pauses when the screen turns off, which ends any share.

+

When an app imports a store

+

The app gives the code or link from the other phone, and the import starts as if you'd typed it on the import screen. The other +phone's owner still checks the four digits and taps Allow. An app can't import while this phone is serving, starting or paused: +it must stop the server first, and it can't start the server while an import is running.

+

An app's import replaces an imported copy of a different store without asking. Replacing a newer copy of the same store with an +older one still needs you: a notification asks Import an older copy?. Tap it and answer within 2 minutes, or the copy on +this phone is kept. This phone's own store is never touched.

+

While any import runs, its notification has a Cancel button. If a transfer fails partway, tap Try again on the +import screen; apps can't retry it.

+

Sound

+

An app can also use sound instead of a code. On the sharing phone, it plays the share's code as tones, as Play sound does, +for up to 30 seconds. On the importing phone, it listens for them, as Listen does, for up to 30 seconds, and starts the import +once it hears the code. Android shows its microphone indicator while it listens. If the sharing phone serves on its own hotspot, +Android asks to join it: tap Connect. Apps are never told the hotspot's password.

+

The line under the switch says if the microphone isn't allowed, or works only once the app is opened, as after the phone +restarts. Without it, a person uses Listen on the import screen instead.

+

The token

+

An app must send the token with every request. Copy token copies it without showing it; paste it into the app's settings. +New token replaces it, and apps using the old one are refused until they get the new one. Keep it as private as a password.

+

Connecting an app

+

The address is http://127.0.0.1:6176/mcp, using MCP's Streamable HTTP transport. The app sends the token in the +header Authorization: Bearer, followed by the token.

+

If it doesn't start

+

If the line under the switch says Failed, another app may be using port 6176. Close that app, then turn MCP control off and +on again. The store's own port can't be 6176, as that's kept for MCP control.

+

Back to Share Your Apps Server

"""), + # A fixed page for checking that Tier 3 works end to end. + "x.html": page("Help test page", "

If you can read this, in-app help pages load from the help database.

"), +} + +TOOLTIPS = [ # tag, summary (Tier 1), detail (Tier 2), [(button text, page)] + ("server.overview", "Share Your Apps Server
Serves the store you publish from Code On The Go.", + "

Publish from the Share Your Apps tab in Code On The Go, and this app serves the result to phones on the same network.

", + [("About Share Your Apps Server", "index.html")]), + ("server.status", "Whether the server is running, and what it's serving.", + "

While it's serving, the store's address appears below, with a button beside it that copies it.

", []), + ("server.hotspot", "The hotspot buyers join when this phone isn't on Wi-Fi.", + "

When the phone isn't on a Wi-Fi network, the server starts a hotspot of its own. It tries a Wi-Fi Direct group first, " + "which keeps the same name and password every time, so phones that joined before rejoin by themselves. That needs " + "Android 10 or later and Wi-Fi switched on. Otherwise Android's own hotspot is used, and Android picks a new name and password each time.

" + "

Buyers join it like any Wi-Fi network, using the name and password shown here, then open the store's address. " + "The hotspot turns off when the server stops.

" + "

If you've turned on your phone's own Mobile hotspot in Settings, the server uses that instead, and this line says so. " + "Its name and password are in Settings; type them on the QR code screen to show buyers a join code. Buyers on it can use your " + "phone's mobile data too. Turning it off stops the server.

", []), + ("server.serve", "Show buyers the QR codes for joining the network and opening the store.", + "

Opens a full-screen page to hold up for buyers: one code joins the network, the other opens the store in their browser. " + "The screen stays on while it's showing.

" + "

On a hotspot, the first code is made for you. On Wi-Fi, type the network's password on that page to show the first code; " + "it's never saved. Without it, buyers join the Wi-Fi themselves and scan only the second code.

", []), + ("server.serve_wifi", "Optional: your Wi-Fi password, to make a code buyers scan to join.", + "

Android doesn't let apps read the password of a network the phone has joined, so type it here if you want a join code. " + "It's kept only while this screen is open, and is never saved. The code contains the password, so anyone who scans it can join the network.

", []), + ("server.copies", "Give another seller a copy of this store, to serve from their phone.", + "

Someone nearby can serve a copy of this store from their own phone, so it reaches buyers where you aren't. " + "The copy is served exactly as you published it, with their own PIN: they can't change it, or pass it on to anyone else.

" + "

You choose when each copy expires; on that date it's deleted from their phone. To give them a newer version, share again.

", []), + ("server.share", "Show a code for the other phone, then allow or deny its request.", + "

Shows a QR code, and the same as a code to type. The other phone scans or types it in Share Your Apps Server; then you see " + "its name and a four-digit check code, and choose when the copy expires. Nothing is sent until you tap Allow.

" + "

Only works while the server is serving. Both phones must be on the same Wi-Fi network or hotspot.

", []), + ("share.code", "The other phone scans this, or types the code.", + "

The code works for one phone, for 10 minutes. After five wrong codes it stops working, so it can't be guessed. " + "Keep this screen open: sharing stops when you leave it.

", []), + ("share.app", "Gives the other phone the app itself, if it doesn't have it.", + "

The other phone's camera opens this in its browser, which downloads Share Your Apps Server from this phone: the same app, " + "signed the same way. Android then asks to install it, and the first time, whether to let the browser install apps. " + "Both phones must be on the same network. It's only offered while this screen is open.

", []), + ("share.allow", "Check the four digits match the other screen, then choose.", + "

The digits prove you're talking to the phone in front of you, not another on the same network. " + "If they don't match, tap Deny.

", []), + ("share.expiry", "When the copy is deleted from their phone.", + "

In a week, in a month, on a date you choose, or never. Until then they can serve it as you published it. " + "To extend it, share again: a newer copy replaces the old one, with its new date.

", []), + ("share.sound", "Play the code as tones, for the other phone to hear.", + "

On the other phone, they tap Listen on the import screen. The tones repeat until that phone connects, for up to " + "30 seconds; Stop sound ends them sooner. Turn the media volume up and hold the phones close.

" + "

On this phone's own hotspot, the tones also carry its name and password, so anyone close enough to hear them gets them. " + "On other Wi-Fi, they never carry a password.

", []), + ("import.listen", "Hear the code from the owner's phone, instead of scanning or typing it.", + "

Ask the owner to tap Play sound on their share screen. The first time, Android asks to let the app use the microphone. " + "It listens for up to 30 seconds, only while this screen shows Listening…; Stop listening ends it sooner. " + "Once it hears the code, the import starts by itself.

", []), + ("server.import", "Serve a copy of someone else's store, from this phone.", + "

With the owner's permission, this phone gets a copy of their store, and can serve it to buyers nearby with its own PIN. " + "It's served as the owner published it: it can't be changed, or passed on. It's deleted on the date the owner chose.

" + "

A phone serving its own store can't import one: stop serving it first, or import on another phone.

", []), + ("import.code", "The code the owner's phone shows, or scan its QR code instead.", + "

Scan the QR code with this phone's camera app, and open the link it offers: the code is filled in for you. Or type the code: " + "LS, then two groups of four letters and digits. Letters can be upper or lower case, and O and 0 are the same.

", []), + ("import.name", "What the owner sees when you ask.", + "

It starts as this phone's own name, from Android's settings. Change it to something the owner will recognise.

", []), + ("import.check", "Tell the owner these four digits, or check they match theirs.", + "

The same four digits show on both phones. If they match, the owner knows the request really comes from this phone.

", []), + ("server.copy", "A copy of someone else's store, imported to this phone.", + "

It's served exactly as its owner published it: it can't be changed, or passed on to anyone else. " + "On its expiry date it's deleted from this phone. To serve it longer, or to get a newer version, import a new copy from its owner.

", []), + ("server.copy_serve", "Serve the copy to buyers nearby, from this phone.", + "

Buyers use it exactly as they would any store: Show QR codes for buyers works the same way. " + "Publishing your own store from Code On The Go serves that instead, and keeps the copy for later.

", []), + ("server.copy_pin", "Optional: a PIN buyers enter before reaching the store.", + "

Up to six digits, or leave it blank for no PIN. It's yours, not the owner's: it's never part of the copy. " + "A change applies the next time you serve the store.

", []), + ("server.copy_remove", "Delete the copy from this phone.", + "

Stops serving it, if it's being served, and deletes it. To serve it again, ask its owner for a new copy.

", []), + ("server.copy_expired", "An imported copy expired, and was deleted.", + "

Its owner chose when it would expire. To serve the store again, ask its owner for a new copy. Tap OK to dismiss this.

", []), + ("server.hotspot_name", "The name buyers see for this phone's hotspot, after DIRECT-LS-.", + "

Android puts DIRECT-LS- in front, and allows 22 more: letters, digits, spaces and punctuation count 1 each, " + "accented letters 2, and emoji 4. Buyers who joined before won't reconnect by themselves if you change it: they join again, " + "with the new details on the Serve screen.

", []), + ("server.hotspot_password", "The hotspot's password: 8 to 63 characters.", + "

Letters, digits, spaces and ordinary punctuation, with no accented letters or emoji, which some phones can't type. " + "If you change it, buyers who joined before must join again.

", []), + ("server.hotspot_save", "Keep this name and password. They take effect the next time the hotspot starts.", + "

The hotspot already running keeps its old details until the server stops and starts again.

", []), + ("server.hotspot_suggest", "Fill in a strong, random password.", + "

Sixteen random letters and digits. Tap Save name & password to keep it.

", []), + ("share.cancel", "End the share: the code stops working.", + "

A phone that hasn't finished importing can't. Leaving this screen does the same for a share you opened here; rotating the phone doesn't. " + "A share an app started through MCP control stays open when you leave the screen: Cancel ends it.

", []), + ("share.deny", "Refuse this request: nothing is sent.", + "

The other phone is told you denied it. To share with a phone after all, tap Share again for a new code.

", []), + ("share.again", "Make a new code, for another phone, or to try again.", + "

Each code serves one phone, so every share needs its own.

", []), + ("share.done", "Close this screen. The share has ended.", "

Nothing more is sent.

", []), + ("import.cant", "Close this screen.", + "

A phone that's serving a store can't import one, so a copy is never replaced under a running server. " + "Stop serving first, in Manage server, or import on another phone.

", []), + ("import.continue", "Ask the owner's phone for a copy, with this code.", + "

The owner's phone then shows your phone's name and four digits, and asks whether to allow it. After a failed transfer, " + "Start over begins again, with a new code from the owner.

", []), + ("import.retry", "Try the transfer again, while the owner's share screen is still open.", + "

It uses the same request, so the owner needn't make a new code or allow it again.

", []), + ("import.cancel", "Stop importing. Nothing is kept.", + "

A copy you already had, if any, stays as it was.

", []), + ("import.serve_now", "Start serving the copy now.", + "

It's served with the PIN set for it in Manage server, in the store's panel, or with none if there isn't one. " + "You can change the PIN there at any time.

", []), + ("import.done", "Close this screen, without serving yet.", + "

The copy stays on this phone. Serve it whenever you like, from Manage server.

", []), + ("serve.close", "Close this screen.", "

Start the server, or publish from the Share Your Apps plugin, and the codes appear here.

", []), + ("serve.done", "Close this screen. The store keeps serving.", "

Open it again any time with Show QR codes for buyers.

", []), + ("serve.show_join", "Show the QR code that joins buyers to this network.", + "

Buyers scan it with their camera to join, then scan the store's own code, which appears after it.

", []), + ("server.view_logs", "See every log file, with search and filters.", + "

Opens the full log. Choose a file — Current, or an older one by age — search it, or show only requests or only the " + "server's own status lines. Pinch to zoom, and swipe to move around. Share sends the file you're looking at.

", []), + ("server.export_logs", "Send all the log files off the phone.", + "

Opens Android's share sheet with every log file attached, so you can save them to Drive, email them, or send them in a chat.

", []), + ("server.log_folder", "Where the logs are kept on this phone.", + "

Tap the path to select it. The folder is private to this app, because the logs record buyers' addresses, so other apps and " + "file managers can't open it. Use Export logs to send the logs elsewhere.

", []), + ("server.p2p_settings", "The name and password of the Wi-Fi Direct hotspot.", + "

When this phone isn't on Wi-Fi, the server starts a Wi-Fi Direct hotspot with this name and password. The name always begins " + "with DIRECT-LS-, which Android requires; choose the rest, up to 22 plain letters. The password needs 8 to 63 ordinary characters.

" + "

Changes take effect the next time the hotspot starts: tap Stop, then Start. Phones that joined under the old name or password " + "won't rejoin by themselves. If Wi-Fi Direct can't start, Android's own hotspot is used instead, and Android chooses its name and password.

", []), + ("server.grant", "Lets the server read your published store.", + "

The store's files are in shared storage, so the server needs permission to read them. It only needs granting once.

", []), + ("server.last_published", "What Start will serve.", + "

Start always serves the last store you published from the plugin. To change it, publish again.

", []), + ("server.port", "The port the store is served on. The default is 6175.", + "

A number from 1024 to 65535. Change it only if another app already uses 6175. It takes effect the next time the server starts.

", []), + ("server.start", "Start serving the last store you published.", + "

If the server is already running, it restarts. The notification shows while it's serving.

", []), + ("server.stop", "Stop serving.", + "

Phones can't reach the store until you start the server again or publish from the plugin.

", []), + ("server.run_mode", "Keep serving always, or pause while the screen is off.", + "

Pause when the screen turns off saves battery. While the screen is off, the server and its hotspot pause; " + "they resume by themselves when you unlock the phone. The choice applies immediately.

" + "

If the server is using Android's own hotspot, rather than a Wi-Fi Direct one, Android picks a new network name and " + "password each time it resumes, so buyers need to scan the join code again.

", []), + ("server.log_size", "How big the access log can grow, in MB. 0 turns logging off.", + "

From 0 to 100. The server keeps at most five log files. A new limit takes effect the next time the server starts.

", []), + ("server.log", "What the server has done, newest first.", + "

It updates every 2 seconds. Long lines scroll sideways.

", [("Reading the access log", "log.html")]), + ("server.mcp", "Lets apps on this phone control the server, through MCP. Off until you turn it on.", + "

Apps on this phone, such as an AI assistant, can start and stop the server, share this store and import a store. " + "They can't change the store or approve a copy: you still tap Allow. Other devices on the network can't reach it.

" + "

Apps can also play the share code as sound, and use the microphone to hear another phone's, only while they ask it to.

" + "

The line below says whether it's running. After the phone restarts, it starts again when you next open the app.

", []), + ("server.mcp_token", "The password apps send to use MCP control.", + "

Copy token copies it without showing it, to paste into the app's settings. New token replaces it; " + "apps using the old one are refused until they get the new one. Keep it as private as a password.

", []), +] + +# Tier 3 for every entry: the page, and section, each tag's button opens. +TIER3 = [ + (("server.status", "server.last_published"), "Serving the store", "serving.html#status"), + (("server.port", "server.start", "server.stop"), "Serving the store", "serving.html#start"), + (("server.grant",), "Serving the store", "serving.html#grant"), + (("server.serve", "server.serve_wifi", "serve.close", "serve.done", "serve.show_join"), "The codes buyers scan", "serving.html#serve"), + (("server.hotspot",), "Hotspots", "hotspot.html#kinds"), + (("server.p2p_settings", "server.hotspot_name", "server.hotspot_password", "server.hotspot_save", "server.hotspot_suggest"), "The hotspot's name and password", "hotspot.html#wifi-direct"), + (("server.copies", "server.share", "share.code", "share.cancel", "share.again", "share.done"), "Sharing your store", "sharing.html#share"), + (("share.app",), "A phone without Share Your Apps Server", "sharing.html#app"), + (("share.sound",), "Play sound", "sharing.html#sound"), + (("import.listen",), "Listen", "importing.html#listen"), + (("share.allow", "share.deny"), "Allow or Deny", "sharing.html#allow"), + (("share.expiry",), "When the copy expires", "sharing.html#expiry"), + (("server.import", "import.code", "import.name", "import.continue"), "Importing a store", "importing.html#import"), + (("import.check",), "The four digits", "importing.html#check"), + (("import.cancel",), "While it arrives", "importing.html#progress"), + (("import.retry",), "If it fails", "importing.html#failed"), + (("import.cant",), "Can't import a store here", "importing.html#cant"), + (("import.serve_now", "import.done"), "When it's imported", "importing.html#done"), + (("server.copy",), "Imported copies", "copies.html#panel"), + (("server.copy_serve",), "Serving a copy", "copies.html#serve"), + (("server.copy_pin",), "A copy's PIN", "copies.html#pin"), + (("server.copy_remove",), "Removing a copy", "copies.html#remove"), + (("server.copy_expired",), "When a copy expires", "copies.html#expiry"), + (("server.run_mode",), "When to run", "running.html#modes"), + (("server.log_size", "server.view_logs", "server.export_logs", "server.log_folder"), "Logs", "running.html#logs"), + (("server.mcp",), "MCP control", "mcp.html#on"), + (("server.mcp_token",), "The token", "mcp.html#token"), +] +def tier3(tag): + for tags, label, uri in TIER3: + if tag in tags: return [(label, uri)] + return [] + +def build(out): + if os.path.exists(out): os.remove(out) + db = sqlite3.connect(out) + # 1 KB pages: of every page size, this gives the smallest database once compressed in the APK, and + # keeps it at 55 KB on the phone, against 98 KB with SQLite's default 4 KB pages. + db.execute("PRAGMA page_size = 1024") + db.executescript(""" +CREATE TABLE DocumentationDatabaseVersion (version INTEGER NOT NULL); +CREATE TABLE Languages (id INTEGER PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE ContentTypes (id INTEGER PRIMARY KEY, value TEXT NOT NULL, compression TEXT NOT NULL DEFAULT 'none'); +CREATE TABLE Templates (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, content BLOB NOT NULL); +CREATE TABLE CompressionDictionary (id INTEGER PRIMARY KEY, dictionary BLOB NOT NULL); +CREATE TABLE Content (path TEXT NOT NULL, content BLOB NOT NULL, + contentTypeID INTEGER NOT NULL REFERENCES ContentTypes(id), + languageId INTEGER NOT NULL REFERENCES Languages(id), + templateId INTEGER NOT NULL DEFAULT 0); +CREATE UNIQUE INDEX ContentPath ON Content(path, languageId); +CREATE TABLE TooltipCategories (id INTEGER PRIMARY KEY, category TEXT NOT NULL UNIQUE); +CREATE TABLE Tooltips (id INTEGER PRIMARY KEY, categoryId INTEGER NOT NULL REFERENCES TooltipCategories(id), + tag TEXT NOT NULL, summary TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', UNIQUE(categoryId, tag)); +CREATE TABLE TooltipButtonNumbers (id INTEGER PRIMARY KEY, value INTEGER NOT NULL); +CREATE TABLE TooltipButtons (tooltipId INTEGER NOT NULL REFERENCES Tooltips(id), description TEXT NOT NULL, + uri TEXT NOT NULL, buttonNumberId INTEGER NOT NULL REFERENCES TooltipButtonNumbers(id)); +""") + db.execute("INSERT INTO DocumentationDatabaseVersion VALUES (1)") + db.execute("INSERT INTO Languages VALUES (1, 'en')") + db.execute("INSERT INTO ContentTypes VALUES (1, 'text/html', 'none')") + db.executemany("INSERT INTO TooltipButtonNumbers VALUES (?, ?)", [(i, i) for i in range(10)]) + for path, html in PAGES.items(): + data = html.encode("utf-8") + parts = [data[i:i + CHUNK] for i in range(0, len(data), CHUNK)] or [b""] + for n, part in enumerate(parts): + db.execute("INSERT INTO Content (path, content, contentTypeID, languageId) VALUES (?, ?, 1, 1)", + (path if n == 0 else f"{path}-{n}", part)) + cat = db.execute("INSERT INTO TooltipCategories (category) VALUES (?)", (CATEGORY,)).lastrowid + for tag, summary, detail, buttons in TOOLTIPS: + buttons = buttons or tier3(tag) + tid = db.execute("INSERT INTO Tooltips (categoryId, tag, summary, detail) VALUES (?, ?, ?, ?)", + (cat, tag, summary, detail)).lastrowid + for i, (text, uri) in enumerate(buttons): + db.execute("INSERT INTO TooltipButtons VALUES (?, ?, ?, ?)", (tid, text, uri, i)) + db.commit() + db.execute("VACUUM") + db.close() + +if __name__ == "__main__": + build(sys.argv[1] if len(sys.argv) > 1 else "web_server_documentation.db") diff --git a/plugins/Share-Your-Apps/server/help/build_help_db.sh b/plugins/Share-Your-Apps/server/help/build_help_db.sh new file mode 100644 index 000000000..e4206c8c8 --- /dev/null +++ b/plugins/Share-Your-Apps/server/help/build_help_db.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Rebuilds the app's help database from build_help_db.py, then checks the MCP help is in it. +# Run from anywhere: +# sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server MCP/help/build_help_db.sh" +# Then do a Standard Run, so the app picks up the new database. +set -e + +# This script's own folder, so the paths below work wherever it's run from. +HERE=$(cd "$(dirname "$0")" && pwd) +DB="$HERE/../app/src/main/assets/web_server_documentation.db" + +# python3 if there is one, else python. +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +else echo "Neither python3 nor python was found." >&2; exit 1 +fi + +echo "Building $DB with $PY ..." +"$PY" "$HERE/build_help_db.py" "$DB" + +# A quick check: the new page and both new help entries are in the database. +"$PY" - "$DB" <<'EOF' +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +tags = [r[0] for r in db.execute("SELECT tag FROM Tooltips WHERE tag LIKE 'server.mcp%' ORDER BY tag")] +page = db.execute("SELECT length(content) FROM Content WHERE path = 'mcp.html'").fetchone() +link = db.execute("SELECT instr(content, 'href=\"mcp.html\"') FROM Content WHERE path = 'index.html'").fetchone() +total = db.execute("SELECT count(*) FROM Tooltips").fetchone()[0] +print("Help entries:", total) +print("MCP entries:", tags) +print("mcp.html:", f"{page[0]} bytes" if page else "MISSING") +print("index.html links to mcp.html:", "yes" if link and link[0] else "NO") +ok = tags == ["server.mcp", "server.mcp_token"] and page and link and link[0] +print("OK" if ok else "SOMETHING IS MISSING") +sys.exit(0 if ok else 1) +EOF diff --git a/plugins/Share-Your-Apps/server/mcp-call.sh b/plugins/Share-Your-Apps/server/mcp-call.sh new file mode 100644 index 000000000..405cfd018 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-call.sh @@ -0,0 +1,123 @@ +#!/bin/sh +# Calls one tool of Share Your Apps Server's MCP control, for testing by hand: you play the MCP client. +# +# Usage: +# sh mcp-call.sh TOOL [ARGUMENTS] +# Examples: +# sh mcp-call.sh tools lists the tools +# sh mcp-call.sh server_status +# sh mcp-call.sh share_start opens a share; prints its code +# sh mcp-call.sh share_status what the share is doing now +# sh mcp-call.sh share_status '{"wait_seconds":20}' waits up to 20 s for a change +# sh mcp-call.sh share_stop closes the share +# +# Before running: MCP control on (the line under the switch says "On, at http://127.0.0.1:6176/mcp"). +# It asks for the token (from Copy token) without showing it. To skip the question, set MCP_TOKEN. +# Each run starts its own MCP session and ends it afterwards. A share stays open between runs: +# the app keeps it, not the session. +# MCP_URL changes the address (default http://127.0.0.1:6176/mcp). + +set -u +URL="${MCP_URL:-http://127.0.0.1:6176/mcp}" +TOOL="${1:-}" +ARGS="${2:-}" +[ -n "$ARGS" ] || ARGS='{}' + +if [ -z "$TOOL" ]; then + echo "Usage: sh mcp-call.sh TOOL [ARGUMENTS]" + echo " e.g. sh mcp-call.sh share_start" + echo " sh mcp-call.sh share_status '{\"wait_seconds\":20}'" + echo " sh mcp-call.sh tools (lists the tools)" + exit 2 +fi +command -v curl >/dev/null || { echo "curl isn't installed. In Termux: pkg install curl"; exit 2; } + +# The token: asked on the terminal itself, not hidden in the output, and not shown as it's pasted. +if [ -z "${MCP_TOKEN:-}" ] && [ -r /dev/tty ] && [ -w /dev/tty ]; then + printf 'Paste the MCP token (from Copy token), then press Enter: ' > /dev/tty + stty -echo < /dev/tty 2>/dev/null + read -r MCP_TOKEN < /dev/tty + stty echo < /dev/tty 2>/dev/null + echo > /dev/tty +fi +[ -n "${MCP_TOKEN:-}" ] || { echo "No token given."; exit 2; } + +# The token goes to curl from a private temporary file, never on its command line. +umask 077 +WORK="$(mktemp -d "${TMPDIR:-/tmp}/mcp-call.XXXXXX")" || { + echo "Couldn't make a temporary folder. Try: TMPDIR=\$HOME sh mcp-call.sh $TOOL"; exit 2; } +trap 'rm -rf "$WORK"' EXIT +printf 'Authorization: Bearer %s\n' "$MCP_TOKEN" > "$WORK/auth" + +# post BODY [more curl arguments]: sends one request. The reply's body goes to $WORK/body and its +# headers to $WORK/head; prints the HTTP status. 40 s allows for wait_seconds up to 25. +post() { + p_body="$1"; shift + printf '%s' "$p_body" > "$WORK/req" + : > "$WORK/body"; : > "$WORK/head"; : > "$WORK/err" + curl -sS -X POST -o "$WORK/body" -D "$WORK/head" -w '%{http_code}' --max-time 40 \ + -H "@$WORK/auth" -H "Content-Type: application/json" "$@" --data-binary "@$WORK/req" "$URL" 2>"$WORK/err" +} + +# 1. Start a session. +status="$(post '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-call","version":"1"}}}')" +if [ "$status" != 200 ]; then + echo "Couldn't start an MCP session (HTTP ${status:-000})." + if [ -s "$WORK/err" ]; then cat "$WORK/err"; fi + if [ -s "$WORK/body" ]; then cat "$WORK/body"; echo; fi + echo "Is MCP control on? Is the token the one from Copy token?" + exit 1 +fi +SESSION="$(grep -i '^mcp-session-id:' "$WORK/head" | head -n 1 | cut -d: -f2- | tr -d ' \r')" +[ -n "$SESSION" ] || { echo "The server didn't give a session id."; exit 1; } +printf 'Mcp-Session-Id: %s\nMCP-Protocol-Version: 2025-06-18\n' "$SESSION" > "$WORK/session" +post '{"jsonrpc":"2.0","method":"notifications/initialized"}' -H "@$WORK/session" > /dev/null + +# 2. Call the tool, or list the tools. +if [ "$TOOL" = tools ]; then + REQ='{"jsonrpc":"2.0","id":2,"method":"tools/list"}' +else + REQ="$(printf '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"%s","arguments":%s}}' "$TOOL" "$ARGS")" +fi +status="$(post "$REQ" -H "@$WORK/session")" +cp "$WORK/body" "$WORK/reply" + +# 3. End the session. The share, if any, stays open. +curl -sS -X DELETE -o /dev/null --max-time 10 -H "@$WORK/auth" -H "@$WORK/session" "$URL" 2>/dev/null + +if [ "$status" != 200 ]; then + echo "The request failed (HTTP ${status:-000})." + if [ -s "$WORK/err" ]; then cat "$WORK/err"; fi + if [ -s "$WORK/reply" ]; then cat "$WORK/reply"; echo; fi + exit 1 +fi + +# 4. Show the answer: readably with Python, if it's installed; otherwise the raw reply. +if command -v python3 > /dev/null 2>&1; then + python3 - "$WORK/reply" "$TOOL" <<'EOF' +import json, sys +path, tool = sys.argv[1], sys.argv[2] +raw = open(path, encoding="utf-8", errors="replace").read() +try: + reply = json.loads(raw) +except Exception: + print(raw) + sys.exit(0) +if "error" in reply: + print("Refused:", reply["error"].get("message")) + sys.exit(0) +result = reply.get("result", {}) +if tool == "tools": + for t in result.get("tools", []): + print(f"{t['name']:15} {t.get('title', '')}") + sys.exit(0) +if result.get("isError"): + print("The tool reported a problem:") +for c in result.get("content", []): + if c.get("type") == "text": + print(c["text"]) +EOF +else + cat "$WORK/reply"; echo +fi +exit 0 diff --git a/plugins/Share-Your-Apps/server/mcp-curl-tests.sh b/plugins/Share-Your-Apps/server/mcp-curl-tests.sh new file mode 100644 index 000000000..83495bfe1 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-curl-tests.sh @@ -0,0 +1,347 @@ +#!/usr/bin/env bash +# Tests MCP control (project A, step 2) with curl, on the phone running Share Your Apps Server. +# +# Before running: +# 1. Do a Standard Run of "Share Your Apps Server MCP", open the app, turn on MCP control, +# and wait until the line under the switch says "On, at http://127.0.0.1:6176/mcp". +# 2. Tap Copy token. +# +# Run it from a terminal on the same phone (Code on the Go's terminal, or Termux): +# bash mcp-curl-tests.sh +# It asks for the token: paste it and press Enter (it isn't shown). Or set MCP_TOKEN first. +# +# From a computer instead: run adb forward tcp:6176 tcp:6176 and then this script there. +# MCP_URL changes the address (default http://127.0.0.1:6176/mcp). +# Optional: set MCP_WIFI_IP to this phone's Wi-Fi address, to check MCP can't be reached on it. +# +# Each check prints PASS or FAIL with the HTTP status. A FAIL also prints the reply. +# The token is never printed and never put on curl's command line (it's read from a private +# temporary file, deleted at the end). +# +# Checks to do by hand, on the phone (not covered here): +# - Turning the switch on shows "Turn on MCP control?" first; Cancel leaves it off. +# - The "MCP control is on" notification's Turn off button turns the switch off; after that +# this script's requests fail with HTTP 000 (connection refused). +# - Typing 6176 in the server's Port field and tapping Start says the port is kept for MCP control. +# - Long-press the switch: the new help shows (after running help/build_help_db.sh and a Standard Run). + +set -u +URL="${MCP_URL:-http://127.0.0.1:6176/mcp}" +BASE="${URL%/mcp}" +command -v curl >/dev/null || { echo "curl isn't installed. In Termux: pkg install curl"; exit 2; } + +if [ -z "${MCP_TOKEN:-}" ]; then + # The prompt and the typing use the terminal itself (/dev/tty), so sending the output to a file + # (> result.txt, or | tee result.txt) can't hide the prompt. With no terminal, stop rather than wait. + # The check runs in a subshell, so a failed open can't end the script itself. + if ! (exec < /dev/tty) 2>/dev/null; then + echo "No token given, and no terminal to type it on. Run this in a terminal, or set MCP_TOKEN first." + exit 2 + fi + printf 'Paste the MCP token (from Copy token), then press Enter: ' > /dev/tty + # Plain sh has no read -s: stty hides the typing instead. + stty -echo < /dev/tty 2>/dev/null + read -r MCP_TOKEN < /dev/tty + stty echo < /dev/tty 2>/dev/null; echo > /dev/tty +fi +[ -n "$MCP_TOKEN" ] || { echo "No token given."; exit 2; } + +umask 077 +WORK="$(mktemp -d "${TMPDIR:-/tmp}/mcp-test.XXXXXX")" || { echo "Couldn't make a temporary folder."; exit 2; } +trap 'rm -rf "$WORK"' EXIT +printf 'Authorization: Bearer %s\n' "$MCP_TOKEN" > "$WORK/auth" +printf 'Authorization: Bearer %s\n' "not-the-token" > "$WORK/badauth" + +PASS=0 +FAIL=0 + +show() { + echo " reply: $(head -c 3000 "$WORK/body")" + if [ -s "$WORK/err" ]; then echo " curl: $(cat "$WORK/err")"; fi +} + +# check NAME WANT_STATUS WANT_TEXT METHOD BODY [more curl arguments] +# WANT_TEXT: text the reply (body or headers) must contain, any case; "" for none. +# BODY: JSON to send, @file to send a file, or "" for none. +# Settings for one call: AUTH=good|bad|none, CTYPE=, TARGET=, SHOW=1. +# Plain sh, no arrays: the extra curl arguments stay in "$@", and this puts its own in front. +# The settings are read, then cleared, so they never carry over to the next check, whichever +# way the shell treats VAR=value before a function call. +check() { + c_name="$1"; c_want="$2"; c_text="$3"; c_method="$4"; c_body="$5"; shift 5 + c_auth="${AUTH:-good}"; c_ctype="${CTYPE:-application/json}"; c_target="${TARGET:-$URL}"; c_show="${SHOW:-0}" + AUTH=; CTYPE=; TARGET=; SHOW= + if [ -n "$c_body" ]; then set -- -H "Content-Type: $c_ctype" --data-binary "$c_body" "$@"; fi + case "$c_auth" in + good) set -- -H "@$WORK/auth" "$@" ;; + bad) set -- -H "@$WORK/badauth" "$@" ;; + esac + : > "$WORK/body"; : > "$WORK/head"; : > "$WORK/err" + c_got="$(curl -sS -X "$c_method" -o "$WORK/body" -D "$WORK/head" -w '%{http_code}' --max-time 30 "$@" "$c_target" 2>"$WORK/err")" + [ -n "$c_got" ] || c_got=000 + c_ok=1 + [ "$c_got" = "$c_want" ] || c_ok=0 + if [ -n "$c_text" ] && ! grep -qiF -- "$c_text" "$WORK/body" "$WORK/head"; then c_ok=0; fi + if [ $c_ok = 1 ]; then + PASS=$((PASS + 1)); echo "PASS $c_name (HTTP $c_got)" + if [ "$c_show" = 1 ]; then show; fi + else + FAIL=$((FAIL + 1)); echo "FAIL $c_name: wanted HTTP $c_want${c_text:+ containing $c_text}, got HTTP $c_got"; show + fi + return 0 +} + +# has NAME TEXT: the last reply contains TEXT. hasnt NAME TEXT: it doesn't. +has() { + if grep -qiF -- "$2" "$WORK/body" "$WORK/head"; then PASS=$((PASS + 1)); echo "PASS $1" + else FAIL=$((FAIL + 1)); echo "FAIL $1: the reply doesn't contain $2"; show; fi +} +hasnt() { + if grep -qiF -- "$2" "$WORK/body" "$WORK/head"; then FAIL=$((FAIL + 1)); echo "FAIL $1: the reply contains $2"; show + else PASS=$((PASS + 1)); echo "PASS $1"; fi +} + +PING='{"jsonrpc":"2.0","id":1,"method":"ping"}' +INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl-test","version":"1"}}}' + +echo "Testing $URL" +echo +echo "== Who may ask" +AUTH=none check "no token is refused" 401 "Missing or wrong token" POST "$PING" +has "…and the refusal names the Bearer scheme" "WWW-Authenticate" +AUTH=bad check "a wrong token is refused" 401 "Missing or wrong token" POST "$PING" +check "a Host other than 127.0.0.1 or localhost is refused" 403 "Host header" POST "$PING" -H 'Host: example.com' +check "a request from a web page (Origin) is refused" 403 "web pages" POST "$PING" -H 'Origin: https://example.com' +TARGET="$BASE/other" check "another path is not found" 404 "/mcp" POST "$PING" +check "GET is refused: no event stream" 405 "event stream" GET "" +CTYPE=text/plain check "a body that isn't JSON's content type is refused" 415 "application/json" POST "$PING" +check "broken JSON is a parse error" 400 "-32700" POST '{"jsonrpc":' +check "a request before initialize is refused" 400 "initialize first" POST "$PING" +check "an unknown session is refused" 404 "initialize again" POST "$PING" -H 'Mcp-Session-Id: no-such-session' +head -c 1100000 /dev/zero | tr '\0' a > "$WORK/big" +check "a request over 1 MB is refused" 413 "" POST "@$WORK/big" + +echo +echo "== Starting a session" +check "initialize answers with the version asked for" 200 '"protocolVersion":"2025-06-18"' POST "$INIT" +SESSION="$(grep -i '^mcp-session-id:' "$WORK/head" | head -n 1 | cut -d: -f2- | tr -d ' \r')" +has "…with a session id" "Mcp-Session-Id" +has "…the server's name" '"name":"share-your-apps-server"' +has "…and the tools capability" '"tools":{' +check "initialize with an unknown version offers the newest" 200 '"protocolVersion":"2025-06-18"' POST \ + '{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"1999-01-01","capabilities":{}}}' +if [ -z "$SESSION" ]; then + echo + echo "No session id came back, so the rest can't run." + echo "$PASS passed, $((FAIL + 1)) failed. Paste the FAIL lines into the chat." + exit 1 +fi +# The session's headers, in a file curl reads with -H @file (plain sh has no arrays). +printf 'Mcp-Session-Id: %s\nMCP-Protocol-Version: 2025-06-18\n' "$SESSION" > "$WORK/session" + +echo +echo "== In the session" +check "notifications/initialized needs no answer" 202 "" POST '{"jsonrpc":"2.0","method":"notifications/initialized"}' -H "@$WORK/session" +check "ping" 200 '"result":{}' POST "$PING" -H "@$WORK/session" +check "tools/list lists server_status" 200 '"name":"server_status"' POST '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' -H "@$WORK/session" +has "…and store_info" '"name":"store_info"' +has "…marked read-only" '"readOnlyHint":true' +SHOW=1 check "server_status" 200 '"isError":false' POST \ + '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"server_status"}}' -H "@$WORK/session" +has "…reports a state" '"state":' +hasnt "…and no password" 'password' +SHOW=1 check "store_info" 200 '"own_store"' POST \ + '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"store_info","arguments":{}}}' -H "@$WORK/session" +has "…and the imported copy" '"imported_copy"' +check "an unknown tool is an invalid-params error" 200 '-32602' POST \ + '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"delete_store"}}' -H "@$WORK/session" +check "arguments that aren't an object are refused" 200 '-32602' POST \ + '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"server_status","arguments":[1]}}' -H "@$WORK/session" +check "an unknown method is method-not-found" 200 '-32601' POST '{"jsonrpc":"2.0","id":8,"method":"resources/list"}' -H "@$WORK/session" +check "a batch of two pings gets two answers" 200 '"id":21' POST \ + '[{"jsonrpc":"2.0","id":21,"method":"ping"},{"jsonrpc":"2.0","id":22,"method":"ping"}]' -H "@$WORK/session" +has "…the second one too" '"id":22' +check "a batch of only notifications needs no answer" 202 "" POST \ + '[{"jsonrpc":"2.0","method":"notifications/initialized"}]' -H "@$WORK/session" +check "Origin http://localhost is accepted" 200 '"result":{}' POST "$PING" -H "@$WORK/session" -H 'Origin: http://localhost' +check "Host localhost is accepted" 200 '"result":{}' POST "$PING" -H "@$WORK/session" -H 'Host: localhost' +check "an unknown MCP-Protocol-Version is refused" 400 "Unsupported" POST "$PING" \ + -H "Mcp-Session-Id: $SESSION" -H 'MCP-Protocol-Version: 1999-01-01' +AUTH=bad check "a wrong token is refused, even with a session" 401 "" POST "$PING" -H "@$WORK/session" + +echo +echo "== Share and server tools (step 3)" +check "tools/list lists share_start" 200 '"name":"share_start"' POST '{"jsonrpc":"2.0","id":30,"method":"tools/list"}' -H "@$WORK/session" +has "…share_status" '"name":"share_status"' +has "…share_stop" '"name":"share_stop"' +has "…server_start" '"name":"server_start"' +has "…server_stop" '"name":"server_stop"' +hasnt "…and no tool to allow a copy" '"name":"share_allow"' +SHOW=1 check "share_status answers, whatever is being served" 200 '"state":' POST \ + '{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"share_status"}}' -H "@$WORK/session" +check "share_status refuses wait_seconds that isn't a number" 200 '"isError":true' POST \ + '{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"share_status","arguments":{"wait_seconds":"5"}}}' -H "@$WORK/session" +check "server_start refuses a store other than own or copy" 200 'store must be' POST \ + '{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"server_start","arguments":{"store":"both"}}}' -H "@$WORK/session" +has "…as a tool error" '"isError":true' + +# Helpers for the optional sections below. +# call ID TOOL [ARGS]: one tools/call; its reply is left in $WORK/body for has/hasnt, but isn't counted as a check. +call() { + c_args="${3:-}"; [ -n "$c_args" ] || c_args='{}' + printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}' "$1" "$2" "$c_args" > "$WORK/call" + : > "$WORK/body"; : > "$WORK/head"; : > "$WORK/err" + curl -sS -X POST -o "$WORK/body" -D "$WORK/head" --max-time 40 -H "@$WORK/auth" -H "@$WORK/session" \ + -H "Content-Type: application/json" --data-binary "@$WORK/call" "$URL" 2>"$WORK/err" || true +} +# serving_own ID: whether the server is serving this phone's own store (an imported copy can't be shared). +serving_own() { call "$1" server_status; grep -qF '"serving":"own"' "$WORK/body"; } +# wait_for_code ID: a share opened just after a start or a publish is "preparing" while the store's files +# are compressed. Waits for its code with share_status, up to 3 × 20 seconds. +wait_for_code() { + w_n=0 + while grep -qF '"state":"preparing"' "$WORK/body" && [ "$w_n" -lt 3 ]; do + echo " the store is being prepared; waiting for the code…" + call "$1" share_status '{"wait_seconds":20}' + w_n=$((w_n + 1)) + done +} + +echo +echo "== Import tools (step 4)" +# Every refusal here comes before an import would start, so nothing is imported or searched for. +check "tools/list lists import_start" 200 '"name":"import_start"' POST '{"jsonrpc":"2.0","id":70,"method":"tools/list"}' -H "@$WORK/session" +has "…import_status" '"name":"import_status"' +has "…import_cancel" '"name":"import_cancel"' +SHOW=1 check "import_status answers" 200 '"phase":' POST \ + '{"jsonrpc":"2.0","id":71,"method":"tools/call","params":{"name":"import_status"}}' -H "@$WORK/session" +check "import_cancel with no import running cancels nothing" 200 '"cancelled":false' POST \ + '{"jsonrpc":"2.0","id":72,"method":"tools/call","params":{"name":"import_cancel"}}' -H "@$WORK/session" +check "import_start refuses both code and link" 200 'exactly one' POST \ + '{"jsonrpc":"2.0","id":73,"method":"tools/call","params":{"name":"import_start","arguments":{"code":"LS-AB12-CD34","link":"shareyourapps-share://192.168.1.5:6175/AB12CD34"}}}' -H "@$WORK/session" +has "…as a tool error" '"isError":true' +check "import_start refuses neither code nor link" 200 'exactly one' POST \ + '{"jsonrpc":"2.0","id":74,"method":"tools/call","params":{"name":"import_start","arguments":{}}}' -H "@$WORK/session" +check "import_start refuses a code that isn't a share code" 200 'a share code: LS' POST \ + '{"jsonrpc":"2.0","id":75,"method":"tools/call","params":{"name":"import_start","arguments":{"code":"hello"}}}' -H "@$WORK/session" +check "import_start refuses a link that isn't a share link" 200 'a share link: it looks' POST \ + '{"jsonrpc":"2.0","id":76,"method":"tools/call","params":{"name":"import_start","arguments":{"link":"https://example.com/"}}}' -H "@$WORK/session" +check "import_start refuses a phone_name over 40 characters" 200 'at most 40' POST \ + '{"jsonrpc":"2.0","id":77,"method":"tools/call","params":{"name":"import_start","arguments":{"code":"LS-AB12-CD34","phone_name":"abcdefghijabcdefghijabcdefghijabcdefghijk"}}}' -H "@$WORK/session" +check "import_start refuses an empty phone_name" 200 'be empty' POST \ + '{"jsonrpc":"2.0","id":78,"method":"tools/call","params":{"name":"import_start","arguments":{"code":"LS-AB12-CD34","phone_name":" "}}}' -H "@$WORK/session" +# Only while serving: on a stopped server, a valid code would really start an import. +call 79 server_status +if grep -qF '"state":"serving"' "$WORK/body"; then + SHOW=1 check "import_start is refused while serving" 200 'Stop the server first' POST \ + '{"jsonrpc":"2.0","id":80,"method":"tools/call","params":{"name":"import_start","arguments":{"code":"LS-AB12-CD34"}}}' -H "@$WORK/session" + has "…as a tool error" '"isError":true' +else + echo "SKIP import_start while serving: the server isn't serving, and a valid code would start a real import." +fi + +# Optional: really opens and closes a share. Needs the server serving this phone's own store; skipped otherwise. +# MCP_SHARE=1 sh mcp-curl-tests.sh +# Run with the server serving, this section also connects the share tools to the server process, so that +# MCP_SERVER=1 below then checks they reach the new one after server_stop and server_start. +if [ "${MCP_SHARE:-0}" = 1 ]; then + echo + echo "== A real share (MCP_SHARE=1)" + if ! serving_own 39; then + echo "SKIP the server isn't serving this phone's own store, so there's nothing to share here." + echo " Tap Start in the app first, then run this again." + [ "${MCP_SERVER:-0}" = 1 ] && echo " (The server section below starts it and shares there, but can't check reconnecting.)" + else + SHOW=1 check "share_start opens a share" 200 '"isError":false' POST \ + '{"jsonrpc":"2.0","id":40,"method":"tools/call","params":{"name":"share_start"}}' -H "@$WORK/session" + wait_for_code 45 + has "…with a code" '"code":' + # JSON may write / as \/, so only the part before the slashes is checked. + has "…and a link" '"link":"shareyourapps-share:' + check "share_start again returns the same share, not a new one" 200 '"already_open":true' POST \ + '{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"share_start"}}' -H "@$WORK/session" + SHOW=1 check "share_status waits up to 3 seconds" 200 '"changed":false' POST \ + '{"jsonrpc":"2.0","id":42,"method":"tools/call","params":{"name":"share_status","arguments":{"wait_seconds":3}}}' -H "@$WORK/session" + check "share_stop closes it" 200 '"stopped":true' POST \ + '{"jsonrpc":"2.0","id":43,"method":"tools/call","params":{"name":"share_stop"}}' -H "@$WORK/session" + check "…after which share_status says closed" 200 '"state":"closed"' POST \ + '{"jsonrpc":"2.0","id":44,"method":"tools/call","params":{"name":"share_status"}}' -H "@$WORK/session" + fi +fi + +# Optional: really stops the server, then starts it again. Buyers connected now are cut off. +# MCP_SERVER=1 sh mcp-curl-tests.sh +if [ "${MCP_SERVER:-0}" = 1 ]; then + echo + echo "== Stopping and starting the server (MCP_SERVER=1)" + call 49 server_status + if grep -qF '"state":"serving"' "$WORK/body"; then WAS_SERVING=1; else WAS_SERVING=0; fi + SHOW=1 check "server_stop stops it" 200 '"state":"stopped"' POST \ + '{"jsonrpc":"2.0","id":50,"method":"tools/call","params":{"name":"server_stop","arguments":{"wait_seconds":15}}}' -H "@$WORK/session" + # server_start restarts a server that's still serving; one that has stopped is simply started. + if grep -qF '"state":"serving"' "$WORK/body"; then RESTART=1; else RESTART=0; fi + SHOW=1 check "server_start starts it again" 200 '"state":"serving"' POST \ + '{"jsonrpc":"2.0","id":51,"method":"tools/call","params":{"name":"server_start","arguments":{"wait_seconds":20}}}' -H "@$WORK/session" + # The new server process is a new connection for the share tools: they must reach it without + # MCP control being turned off and on (result4.txt: "Couldn't reach the server process"). + SHOW=1 check "share_status reaches the new server process" 200 '"isError":false' POST \ + '{"jsonrpc":"2.0","id":52,"method":"tools/call","params":{"name":"share_status"}}' -H "@$WORK/session" + hasnt "…without \"Couldn't reach the server process\"" "reach the server process" + if [ "${MCP_SHARE:-0}" = 1 ]; then + check "share_start opens a share on the new server process" 200 '"isError":false' POST \ + '{"jsonrpc":"2.0","id":53,"method":"tools/call","params":{"name":"share_start"}}' -H "@$WORK/session" + wait_for_code 55 + has "…with a code" '"code":' + check "…and share_stop closes it" 200 '"stopped":true' POST \ + '{"jsonrpc":"2.0","id":54,"method":"tools/call","params":{"name":"share_stop"}}' -H "@$WORK/session" + fi + if [ "$WAS_SERVING" = 1 ]; then + echo " In View logs, the stop should read: stopped serving …: stopped by an MCP client" + else + echo " The server wasn't serving before server_stop, so no stop line was logged." + fi + if [ "$RESTART" = 1 ]; then + echo " …and the start should read: restarted by an MCP client" + else + echo " server_start started a stopped server, so no \"restarted by an MCP client\" line is logged." + echo " That line appears only when server_start is called while the server is serving: see MCP_RESTART=1." + fi +fi + +# Optional: calls server_start while the server is serving, so it restarts and the log names MCP control. +# Also checks the share tools reach the new server process. Buyers connected now are cut off. +# MCP_RESTART=1 sh mcp-curl-tests.sh +if [ "${MCP_RESTART:-0}" = 1 ]; then + echo + echo "== Restarting a serving server (MCP_RESTART=1)" + call 60 server_status + if ! grep -qF '"state":"serving"' "$WORK/body"; then + echo "SKIP the server isn't serving, so server_start would start it, not restart it." + echo " Tap Start in the app first, then run this again." + else + SHOW=1 check "server_start restarts a serving server" 200 '"state":"serving"' POST \ + '{"jsonrpc":"2.0","id":61,"method":"tools/call","params":{"name":"server_start","arguments":{"wait_seconds":20}}}' -H "@$WORK/session" + check "…and share_status reaches the new server process" 200 '"isError":false' POST \ + '{"jsonrpc":"2.0","id":62,"method":"tools/call","params":{"name":"share_status"}}' -H "@$WORK/session" + hasnt "…without \"Couldn't reach the server process\"" "reach the server process" + echo " In View logs, the restart should read: stopped serving Store_…: restarted by an MCP client (Store_…)" + fi +fi + +echo +echo "== Ending the session" +check "DELETE ends the session" 204 "" DELETE "" -H "@$WORK/session" +check "…after which it's refused" 404 "" POST "$PING" -H "@$WORK/session" +check "…and can't be ended twice" 404 "" DELETE "" -H "@$WORK/session" + +if [ -n "${MCP_WIFI_IP:-}" ]; then + echo + echo "== Not reachable from other devices" + TARGET="http://$MCP_WIFI_IP:6176/mcp" check "nothing answers on the Wi-Fi address" 000 "" POST "$PING" +fi + +echo +echo "$PASS passed, $FAIL failed." +if [ "$FAIL" = 0 ]; then echo "All checks passed."; exit 0; fi +echo "Paste the FAIL lines into the chat." +exit 1 diff --git a/plugins/Share-Your-Apps/server/mcp-import-side.sh b/plugins/Share-Your-Apps/server/mcp-import-side.sh new file mode 100644 index 000000000..de94b9328 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-import-side.sh @@ -0,0 +1,209 @@ +#!/bin/sh +# Project A second-phone tests on the IMPORTING phone (phone 2). Tests from mcp-session-state.md: +# sh mcp-import-side.sh 6 a real MCP import; the check code is compared with phone 1 +# sh mcp-import-side.sh 9mcp Cancel in the import notification, for an import MCP started +# sh mcp-import-side.sh 9person the same, for an import a person started on the import screen +# sh mcp-import-side.sh 11 server_start and import_start with the app off screen +# Keep the results: sh mcp-import-side.sh 6 2>&1 | tee result-t6.txt +# Needs MCP_TOKEN (this phone's token). Optional: MCP_PHONE_NAME, the name phone 1's owner sees. +# Phone 1 runs mcp-share-side.sh, which opens a share and shows its code. +set -u +TEST="${1:-}" +case "$TEST" in 6|9mcp|9person|11) ;; *) echo "Say which test: sh mcp-import-side.sh 6 | 9mcp | 9person | 11"; exit 2 ;; esac +. "$(dirname "$0")/mcp-lib.sh" +echo "Test $TEST on the importing phone, $(date)" + +# The imported copy on this phone, to check a cancelled import leaves it as it was. +copy_sig() { + call store_info + if has '"imported_copy":null'; then echo "none"; else echo "$(field store_id) $(field created) $(num bytes)"; fi +} + +# An import needs the server stopped and no import running. +ensure_stopped() { + call server_status + st="$(field state)" + case "$st" in + serving|starting|paused) + info "The server is $st on this phone; stopping it (an import needs it stopped)." + call server_stop '{"wait_seconds":20}' + st="$(field state)" + if [ "$st" = stopped ] || [ "$st" = failed ]; then pass "server_stop stopped the server" + else fail "server_stop: the server is $st"; show; return 1; fi ;; + esac + call import_status + if has '"busy":true'; then + echo "An import is already running on this phone ($(field phase)). End it on the import screen, then run this again." + return 1 + fi + return 0 +} + +read_code() { + CODE_ARGS= + while [ -z "$CODE_ARGS" ]; do + ask "Type the code shown on phone 1 (LS-XXXX-XXXX), or its link, then press Enter:" + r="$(printf '%s' "$a_ans" | tr -d ' \r')" + case "$r" in + shareyourapps-share://*) CODE_ARGS="\"link\":\"$(printf '%s' "$r" | tr -cd 'A-Za-z0-9:/.-')\"" ;; + ?*) CODE_ARGS="\"code\":\"$(printf '%s' "$r" | tr -cd 'A-Za-z0-9-')\"" ;; + esac + done +} + +start_import() { + s_args="{$CODE_ARGS" + if [ -n "${MCP_PHONE_NAME:-}" ]; then + s_args="$s_args,\"phone_name\":\"$(printf '%s' "$MCP_PHONE_NAME" | tr -d '"\\')\"" + fi + call import_start "$s_args}" +} + +# follow_import STOP_PHASES MAX_SECONDS: follows import_status, printing each change, until the phase +# is one of STOP_PHASES or MAX_SECONDS pass. Sets PHASE and CHECK. +follow_import() { + f_stop=" $1 "; f_end=$(( $(date +%s) + $2 )); f_last=; f_wait=0 + while :; do + call import_status "{\"wait_seconds\":$f_wait}" + f_wait=20 + if is_error; then info "import_status failed:"; show; PHASE=; return 1; fi + PHASE="$(field phase)"; CHECK="$(field check_code)" + if needs_person; then f_q=yes; else f_q=; fi + f_now="$PHASE|$CHECK|$f_q" + if [ "$f_now" != "$f_last" ]; then + info "import: $PHASE, started by $(field started_by): $(field message)" + if [ -n "$f_q" ]; then info "person needed: $(field person_needed)"; fi + f_last="$f_now" + fi + case "$f_stop" in *" $PHASE "*) return 0 ;; esac + if [ "$(date +%s)" -ge "$f_end" ]; then info "still $PHASE after $2 seconds"; return 1; fi + done +} + +show_check() { + echo + echo " ==========================================" + echo " Check code on this phone: ${CHECK:-(none yet)}" + echo " ==========================================" +} + +# After the import reaches waiting: a person taps Cancel in this phone's import notification. +cancel_step() { + echo ">>> Don't tap Allow on phone 1." + echo ">>> On THIS phone, pull down the notifications and tap Cancel in the import notification." + follow_import "cancelled failed denied done idle" 300 + if [ "$PHASE" = cancelled ]; then pass "Cancel in the notification cancelled $1 import" + else fail "Cancel in the notification ($1 import): it ended as ${PHASE:-unknown}"; fi + by_eye "the import notification went away after Cancel" "Has the import notification gone from this phone?" + after="$(copy_sig)" + if [ "$after" = "$BEFORE" ]; then pass "the copy already on this phone is unchanged ($after)" + else fail "the copy on this phone changed: before $BEFORE, after $after"; fi + echo ">>> On phone 1, answer the share script's question to close the share." +} + +if [ "$TEST" = 11 ]; then + echo ">>> Test 11: Share Your Apps Server must stay off screen. You're in the terminal, so it is." + echo ">>> Don't open the app until this script ends." + wait_enter "Ready? The script waits 15 seconds, then starts." + sleep 15 +fi + +if ! start_session; then + if [ "$TEST" = 11 ]; then fail "MCP control answered with the app off screen"; summary; fi + exit 1 +fi + +case "$TEST" in +6) + ensure_stopped || exit 1 + read_code + start_import + if is_error; then fail "import_start started the import"; show; summary; fi + pass "import_start started the import" + if [ "$(field started_by)" = mcp ]; then pass "import_status says MCP started it" + else fail "started_by is \"$(field started_by)\", not mcp"; fi + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + if [ -n "$CHECK" ]; then + by_eye "the check code matches phone 1" "Does phone 1 show the same check code, $CHECK?" + else + fail "import_status gave a check code while waiting" + fi + echo ">>> Now on phone 1: choose an expiry and tap Allow." + follow_import "done failed denied cancelled" 600 + if [ "$PHASE" = done ]; then pass "the import finished"; else fail "the import ended as ${PHASE:-unknown}"; summary; fi + STORE="$(field store)" + if [ -n "$(field note)" ]; then info "note: $(field note)"; fi + call store_info + if has '"imported_copy":null'; then fail "store_info shows the imported copy" + elif [ -n "$STORE" ] && has "\"name\":\"$STORE\""; then pass "store_info shows the imported copy of $STORE" + else fail "store_info's imported copy is $STORE"; show; fi + ;; +9mcp) + ensure_stopped || exit 1 + BEFORE="$(copy_sig)" + info "imported copy before: $BEFORE" + read_code + start_import + if is_error; then fail "import_start started the import"; show; summary; fi + pass "import_start started the import" + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + cancel_step "an MCP" + ;; +9person) + ensure_stopped || exit 1 + BEFORE="$(copy_sig)" + info "imported copy before: $BEFORE" + echo ">>> On this phone: open Share Your Apps Server, tap Import a store…, type phone 1's code and tap Continue." + echo ">>> When it says it's waiting for phone 1's owner, come back to this terminal." + wait_enter "Back here?" + call import_status + if ! has '"busy":true'; then fail "a person's import is running (phase $(field phase))"; show; summary; fi + if [ "$(field started_by)" = person ]; then pass "import_status says a person started it" + else fail "started_by is \"$(field started_by)\", not person"; fi + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + cancel_step "a person's" + ;; +11) + pass "MCP control answered with the app off screen" + call server_status + case "$(field state)" in + serving|starting|paused) call server_stop '{"wait_seconds":20}'; info "stopped the server first: $(field state)" ;; + esac + call server_start '{"wait_seconds":25}' + st="$(field state)" + if ! is_error && [ "$st" = starting ]; then sleep 10; call server_status; st="$(field state)"; fi + if needs_person; then + pass "server_start off screen: reports person needed"; info "$(field person_needed)" + elif ! is_error && [ "$st" = serving ]; then + pass "server_start off screen: serving" + call server_stop '{"wait_seconds":20}' + if [ "$(field state)" = stopped ]; then pass "server_stop off screen"; else fail "server_stop off screen: $(field state)"; show; fi + else + fail "server_start off screen: neither serving nor person needed"; show + fi + ensure_stopped || summary + echo ">>> On phone 1, open a new share and read its code." + read_code + start_import + if needs_person; then + pass "import_start off screen: reports person needed"; info "$(field person_needed)" + elif is_error; then + fail "import_start off screen: neither started nor person needed"; show + else + pass "import_start off screen: the import started" + follow_import "waiting done failed denied cancelled" 180 + show_check + echo ">>> On phone 1: check the code is $CHECK, choose an expiry and tap Allow." + follow_import "done failed denied cancelled" 600 + if [ "$PHASE" = done ]; then pass "the import finished with the app off screen" + else fail "the import with the app off screen ended as ${PHASE:-unknown}"; fi + fi + ;; +esac +summary diff --git a/plugins/Share-Your-Apps/server/mcp-lib.sh b/plugins/Share-Your-Apps/server/mcp-lib.sh new file mode 100644 index 000000000..f38448996 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-lib.sh @@ -0,0 +1,90 @@ +# Shared parts of the MCP second-phone tests. Read by mcp-import-side.sh and mcp-share-side.sh; +# not run on its own. Plain sh: no bash, no jq. +URL="${MCP_URL:-http://127.0.0.1:6176/mcp}" +command -v curl >/dev/null 2>&1 || { echo "curl isn't installed."; exit 2; } +if [ -z "${MCP_TOKEN:-}" ]; then + echo "MCP_TOKEN isn't set. In the app, tap Copy token, then run: export MCP_TOKEN=''" + echo "and run this again. Each phone has its own token." + exit 2 +fi +if ! (exec < /dev/tty) 2>/dev/null; then echo "These tests ask questions, so they need a terminal."; exit 2; fi +umask 077 +WORK="$(mktemp -d "${TMPDIR:-/tmp}/mcp-2p.XXXXXX")" || { echo "Couldn't make a temporary folder."; exit 2; } +trap 'end_session; rm -rf "$WORK"' EXIT +trap 'exit 130' INT TERM +# The token goes to curl from a private file: never on its command line, never printed. +printf 'Authorization: Bearer %s\n' "$MCP_TOKEN" > "$WORK/auth" +PASS=0; FAIL=0; CALL_ID=10; HTTP=000; SESSION=; PHASE=; CHECK=; a_ans= + +pass() { PASS=$((PASS + 1)); echo "PASS $1"; } +fail() { FAIL=$((FAIL + 1)); echo "FAIL $1"; } +info() { echo " $1"; } +show() { + echo " reply (HTTP $HTTP): $(head -c 1500 "$WORK/body")" + if [ -s "$WORK/err" ]; then echo " curl: $(cat "$WORK/err")"; fi +} + +# Questions use the terminal itself, so | tee result.txt can't hide them. The answers are +# recorded as PASS or FAIL lines, which do go to the result file. +confirm() { + while :; do + printf '\n>>> %s [y/n] ' "$1" > /dev/tty + read -r c_ans < /dev/tty || return 1 + case "$c_ans" in y|Y|yes|Yes|YES) return 0 ;; n|N|no|No|NO) return 1 ;; esac + done +} +by_eye() { if confirm "$2"; then pass "$1"; else fail "$1"; fi; } +ask() { printf '\n>>> %s ' "$1" > /dev/tty; read -r a_ans < /dev/tty || a_ans=; } +wait_enter() { printf '\n>>> %s (press Enter) ' "$1" > /dev/tty; read -r w_ans < /dev/tty || true; } + +# post BODY: one request in the session; the reply is left in $WORK/body, its status in $HTTP. +post() { + printf '%s' "$1" > "$WORK/call" + : > "$WORK/body"; : > "$WORK/head"; : > "$WORK/err" + HTTP="$(curl -sS -X POST -o "$WORK/body" -D "$WORK/head" -w '%{http_code}' --max-time 45 \ + -H "@$WORK/auth" -H "@$WORK/session" -H 'Content-Type: application/json' \ + --data-binary "@$WORK/call" "$URL" 2>"$WORK/err")" + [ -n "$HTTP" ] || HTTP=000 +} +# call TOOL [ARGS-JSON] +call() { + CALL_ID=$((CALL_ID + 1)) + c_args="${2:-}"; [ -n "$c_args" ] || c_args='{}' + post "$(printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}' "$CALL_ID" "$1" "$c_args")" +} + +start_session() { + : > "$WORK/session" + post '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"two-phone-test","version":"1"}}}' + SESSION="$(grep -i '^mcp-session-id:' "$WORK/head" | head -n 1 | cut -d: -f2- | tr -d ' \r')" + if [ "$HTTP" != 200 ] || [ -z "$SESSION" ]; then + echo "MCP control didn't answer at $URL." + echo "Check that MCP control is on in Share Your Apps Server, and that MCP_TOKEN is this phone's token." + show + return 1 + fi + printf 'Mcp-Session-Id: %s\nMCP-Protocol-Version: 2025-06-18\n' "$SESSION" > "$WORK/session" + post '{"jsonrpc":"2.0","method":"notifications/initialized"}' + return 0 +} +end_session() { + if [ -n "$SESSION" ] && [ -d "$WORK" ]; then + curl -sS -X DELETE -o /dev/null --max-time 5 -H "@$WORK/auth" -H "@$WORK/session" "$URL" 2>/dev/null || true + SESSION= + fi +} + +# Reading the last reply. field NAME: a string value (empty for null). num NAME: a number. +field() { sed -n 's/.*"'"$1"'":"\([^"]*\)".*/\1/p' "$WORK/body" | head -n 1 | sed 's#\\/#/#g'; } +num() { sed -n 's/.*"'"$1"'":\([0-9][0-9]*\).*/\1/p' "$WORK/body" | head -n 1; } +has() { grep -qF -- "$1" "$WORK/body"; } +is_error() { [ "$HTTP" != 200 ] || has '"isError":true' || has '"error":{'; } +needs_person() { has 'person_needed' || has 'A person is needed'; } + +summary() { + echo + echo "$PASS passed, $FAIL failed." + if [ "$FAIL" = 0 ]; then echo "All checks passed."; exit 0; fi + echo "Paste the FAIL lines into the chat." + exit 1 +} diff --git a/plugins/Share-Your-Apps/server/mcp-session-state.md b/plugins/Share-Your-Apps/server/mcp-session-state.md new file mode 100644 index 000000000..f58f0b09e --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-session-state.md @@ -0,0 +1,251 @@ +# Session state: Share Your Apps Server (Combined: MCP control + sound handshake) + +Current state only. No history: the older versions were deleted on purpose. + +## 1. How to resume (instructions for the agent) +- **Work folder:** /storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined (project A, the MCP server, merged + with project B, the sound handshake, in step C). Source: app/src/main/java/org/appdevforall/shareyourapps/server. + Unit tests: app/src/test/java. Help: help/build_help_db.py, built by help/build_help_db.sh. +- **Other folders in CodeOnTheGoProjects:** "Share Your Apps Server" = the original, the only fallback (Git isn't used). + "Share Your Apps Server MCP" (A) and "Share Your Apps Server Sound" (B) = the pre-merge projects, to be deleted by the user. + Every copy has the same app ID: installing one replaces another on the phone. +- **The user's standing rule: plan first.** Change nothing until the user approves. "Proceed" or "Continue" after a + plan approves it and the agent's suggested decisions. +- **Reply style:** plain words, short sections, bold headings; say exactly what was written, read back, built or + tested; never call something tested unless the user reported it; end with numbered "Please do this next" steps. +- **The agent can't:** run shell commands or Gradle; switch, open, copy or delete folders; play sounds; flash the + screen; choose Standard Run or Quick Build. +- **The user runs:** Standard Run; `:app:testDebugUnitTest` from the terminal; help/build_help_db.sh; the shell + scripts (plain `sh`, no bash; python3 and curl are installed). +- **Writes:** + - Every write needs the user's approval in Code on the Go, which times out after 5 minutes. So write only as + the first step after a user message, and start that reply with "⚠ APPROVAL PROMPT NOW". + - One file per turn. Change existing files with edit_file, reading the exact file first. + - Larger changes go in self-checking sh scripts: an END line checked first; every patch found exactly once before + anything is written; backups and `undo`; read back with SHA-256. A 29,274-character script was written whole. +- **Traps:** + - search_project also matches build/ files: ignore them, and always use full paths. + - Quick Build fails at :app:generateDebugQuickBuildSources because ServerService uses android:process=":server". + Use Standard Run. This is not a code error. + - read_build_output shows the last Gradle run, including testDebugUnitTest from the terminal. + - McpProtocolTest prints nothing: BUILD SUCCESSFUL is its pass signal. + - help/build_help_db.sh fails unless there are exactly two `server.mcp…` tooltips (server.mcp, server.mcp_token). + - McpProtocolTest checks that ShareControl sends only SHARE_OPEN, SHARE_POLL and SHARE_CLOSE. Never add others. + +## 2. Current state +- **Step C (A + B merged) is done.** Verified by the user on one phone (a Galaxy Note 20): + - Standard Run builds; `:app:testDebugUnitTest` passes, including the 4 sound tests. + - The share screen's Play sound / Stop sound works, and View logs shows "[sound] played …". + - The MCP switch message has the microphone paragraph; Android asks for the microphone; the line under the switch + is right. + - mcp-sound-tests-1phone.sh: 15 of 15 passed. The microphone works with the app off screen (it ended + nothing_heard, not "heard only silence"). + - The help database rebuilds with OK (53 entries); the help shows on the phone. +- **Earlier, before the merge:** project A's MCP tests 67/67 (mcp-curl-tests.sh, one phone); project B's manual sound + tests on one phone; project B's stale import result fix confirmed in B. +- **Last change:** SoundLog.played says "part of the first round" instead of "0 rounds" when stopped early with no + error. Unit tests pass; the new line hasn't been seen on the phone yet. +- **Step C scripts:** step-c-1-copy.sh … step-c-6-tools.sh, backups in step-c-backup/1–6, checksums in + step-c-checksums.txt. `sh step-c-N.sh undo` undoes one script; undo in reverse order (6 first). The SoundLog + wording change was a direct edit, not in any backup. Delete the scripts, backups and checksums together once a + two-phone sound import has worked. + +## 3. Untested and open +1. A two-phone import by sound: import_listen hears a real code (listen part: checking, then import_started), and the + import completes. Also the import screen's Listen in this combined build. +2. Android's Connect prompt when SoundImport joins the sharing phone's own hotspot for MCP. +3. The microphone right after a reboot, before the app is opened: the line under the switch should say + "Microphone: works once the app is opened". +4. D5: the share screen's Play sound and share_play_sound playing at once. +5. The stale import result fix in this combined build (import, stop serving, Wi-Fi off, delete the copy, reopen + Import a store: it should show the empty form). +6. Project A's second-phone tests 6–11 (section 8). Tests 7 and 8 need a third phone. +7. Project B's second-phone tests 1–5 (section 8). Which were done was never reported. +8. "On the owner's network" was once shown though both phones were on the same Wi-Fi. Re-read onOwnersNetwork / + onOwnersNetworkNow (true when this phone's default route's gateway is the owner's address). Not investigated. +9. Reading QR codes from a picture on the import screen: the plan is in qr-from-picture-plan.md (probably still in the + Sound folder: move it here before deleting that folder). Not approved; no code. Scope: every QR code the app + shows; codes from other apps shown as text with Copy. +- **Optional, not asked for:** + - a dark mode change while listening stops listening; + - the import.listen tooltip doesn't mention the countdown or the meter; + - it's not proven that McpService starts only once per resume. +- **Open questions from the code:** where the local store folder is; which store is served after an import. + +## 4. Requirements and decisions +1. An MCP client may **control** the store but **not change** it. +2. A client can take the sharer or importer role with the least human effort. +3. **Only a person taps Allow** on the sharing phone. MCP can never approve a copy. +4. An MCP import runs by itself: a newer copy of the same store replaces it; a different store is replaced without + asking; an older copy still asks a person (notification); every import notification has Cancel. +5. An import replaces the whole imported copy atomically. The local store is never replaced. +6. **Sound is for the handshake only;** data goes over Wi-Fi. BLE is a possible later option. No Nearby Connections. +7. The tones carry: on its own hotspot, SSID + password + code + address; on other Wi-Fi, the SSID if readable, + **never the password**. +8. SSID + password ≈ 30 characters typically; length fields, no hard limit beyond SSID ≤ 32, password ≤ 63. +9. MCP is on-device only (127.0.0.1). +10. The MCP switch is on the server screen near Start / Stop / Help. Off by default. +11. MCP may start and stop the server. +12. People use Play sound (share screen) and Listen (import screen). +13. Turning the MCP switch on also asks for the microphone, after a message. The microphone stays tied to MCP control + (the user chose this in step C). +14. MCP is on TCP 6176. The store's port can't be 6176. MCP reports a taken port; it doesn't move. +- **Step C decisions:** + - D2: import_listen returns at once; import_status follows it. + - D3: MCP is never told the hotspot password (the tones still carry it on the phone's own hotspot). + - D4: the MCP sound flow is in its own file, SoundImport.kt; ImportActivity is unchanged from B. + - D5: the share screen and share_play_sound have separate players. Playing both at once is an accepted risk. + - D6 a: share_play_sound's "played" line reaches the server's log over its own short binding. +- **Kept from A on purpose:** Compressor.duration takes milliseconds (B's took nanoseconds), and A's AuthTest. + +## 5. Design: where each part came from +- **From B unchanged:** + - SoundPayload, SoundDsp, SoundModem, SoundDecoder, SoundIo, WifiJoin, ImportActivity; + - SoundLog (plus the wording change); + - the tests SoundPayloadTest, SoundModemTest, SoundLogTest, SoundLevelTest; + - help/build_help_db.py (it had all of A's MCP help). +- **From A:** + - ImportService, MainActivity, HostService, ServerService, Compressor, ShareControl; + - StoreLog: status lines are timestamped; `statusLine` for `[tag] …` lines sent over MSG_LOG; + - LogFilter: a status line = a timestamp, then a tag; + - McpProtocol, McpHttp, McpTools, McpService; + - the tests AuthTest, CoreTest, LogFilterTest, McpProtocolTest. +- **Merged:** + - ImportJob: + - `start(context, code, phoneName, address, network = null, byMcp = false): String?` is @Synchronized and + returns null, or why it didn't start; + - run() uses `joined ?: wifiNetwork`; + - the stale result fix: Snapshot.storeId, clearFinished() (@Synchronized) and onOwnersNetworkNow(). + - ImportActivity: B's file, plus a public companion `defaultPhoneName(context)` (cut to 40) used by MCP. + - ShareActivity: A's file (joins a share under way; ownShare; Cancel ends a joined share) plus B's Play sound. + - Manifest: RECORD_AUDIO, FOREGROUND_SERVICE_MICROPHONE, ImportActivity configChanges; McpService type + specialUse|microphone. +- **New:** SoundImport.kt, McpSoundTools.kt. + +## 6. Design: sound (from B) +- **SoundPayload:** a version/flags byte, a 5-byte packed code, optional IPv4 + port, optional SSID and password with + a length byte each, CRC-16/CCITT-FALSE. decode returns null unless the data is exactly a payload. toString hides + the password. +- **Modem:** + - 32 tones from 2400 to 4725 Hz, 75 Hz apart; even and odd symbols use interleaved sets; + - a sweep from 2400 to 4800 Hz starts each burst; 3 repeats, each scrambled with its own XOR key; + - 30 ms tones with 3 ms soft edges, 44.1 kHz, volume 0.7. No return channel. +- **SoundDecoder:** FFT correlation finds the sweep (THRESHOLD 0.35); Goertzel reads the symbols; it combines up to 3 + bursts; the CRC check decides. +- **SoundIo:** + - Player: media sound on the speaker, repeats until stop() or 30 s. + - Listener: 44.1 kHz, UNPROCESSED if supported, else VOICE_RECOGNITION; ends on a valid payload, stop() or 30 s; + reports Level(signal, db, msLeft). + - canListen(), volumeLow(). METER_FLOOR_DB = -60. +- **Import screen Listen:** + - Three quick taps run a self-test. The microphone is asked on first use. + - While listening it shows a countdown and a level meter. + - Once a code is heard: WifiJoin.reachable → ImportJob.start; else on Android 10+ WifiJoin.join (a person taps + Connect within 30 s); else the hotspot's name and password are shown for joining by hand. +- **WifiJoin:** reachable() (about 2 s); join() via WifiNetworkSpecifier with no INTERNET capability; + holdUntilImportEnds(); release(). +- **SoundLog:** "[sound] …" lines, never a password. On the sharing phone they go to the server's log via MSG_LOG; on + the importing phone the main process writes them (nothing while serving); all go to logcat too (ShareYourAppsSound). + +## 7. Design: MCP (A + step C) +- **Endpoint:** + - 127.0.0.1:6176, POST /mcp, JSON-RPC 2.0, Streamable HTTP with plain JSON; GET → 405; DELETE ends a session. + - It checks Host and Origin. A bearer token (Copy token / New token) is never logged. + - Long operations return at once; status tools take wait_seconds ≤ 25. McpService runs in the main process. +- **McpService:** + - A silent notification (channel "mcp_quiet") with Turn off. Started from MainActivity.onResume if the switch is on + (nothing starts it at boot). + - Foreground type specialUse, plus microphone when the microphone is allowed (Android 11+). If Android refuses the + microphone type, it runs without it. + - The line under the switch: "On, at http://127.0.0.1:6176/mcp", plus "Microphone not allowed: …" or + "Microphone: works once the app is opened" when those apply. + - Turning it off ends an MCP share and stops MCP tones and listening. +- **MainActivity:** + - The switch message adds the microphone paragraph; Turn on then asks for RECORD_AUDIO; the answer restarts + McpService. + - Start refuses port 6176. POST_NOTIFICATIONS is asked only when missing. +- **Tools (12):** + - server_status, store_info, server_start, server_stop; + - share_start, share_status, share_stop; + - import_start ({code | link}, phone_name), import_status, import_cancel; + - share_play_sound, import_listen. +- **share_play_sound {stop}:** + - Only while a share is waiting_for_phone. It plays the share's code (plus the hotspot name and password on the + phone's own hotspot) for up to 30 s. + - A watcher stops it when the share moves on or the server stops; already_playing if called again. + - The answer never has the password. It logs "played …, for an MCP client". +- **import_listen {phone_name, stop}:** + - Refused while serving, starting or paused. Returns at once. + - import_status gets a "listen" part: listening (seconds_left, hearing), checking, joining, import_started, + nothing_heard, person_needed, failed or stopped. + - import_start is refused while listening or joining; import_cancel also stops listening. +- **SoundImport:** + - Needs the microphone, else "person needed". Listens 30 s. + - Once heard: reachable, or no password → ImportJob.start(byMcp = true). Android 9 → person_needed. Else + WifiJoin.join (a person taps Connect) → an import on that network, let go when it ends; no tap → person_needed + (the person uses Listen on the import screen). + - Only silence (≤ -60 dB) for 30 s → person_needed (the microphone may be blocked off screen). +- **import_status:** on_owners_network is checked now, not at import end; copy_on_phone; wait_seconds also ends when + the listen phase changes. +- **Share for MCP:** + - ShareControl binds ServerService (flag 0) and sends only open/poll/close. + - A heads-up notification, " asks for a copy of ", opens ShareActivity, which joins the share. + - Leaving the screen doesn't close an MCP share; Cancel does. +- **Import for MCP:** + - The older-copy question waits 2 minutes, via notification channel "import_question". + - The notification title is "Importing ". Retry is only by a person (Try again). +- **Help:** mcp.html (sections on, limits, share, import, sound, token, connect, problems), tooltips server.mcp + (mentions sound) and server.mcp_token; sharing.html#sound, importing.html#listen; share.sound, import.listen; + "[sound]" in log.html. + +## 8. Tests and scripts +- **Unit tests** (`:app:testDebugUnitTest`): AuthTest, CoreTest, LogFilterTest, McpProtocolTest and the 4 sound tests. +- **Token in a terminal** (each phone has its own), pasted after the first line, which hides it: + `stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN` +- **The scripts:** + - mcp-call.sh TOOL [JSON]: a curl MCP client, one tool per run (`tools` lists them). + - mcp-sound-tests-1phone.sh: step C's one-phone tests (15). It leaves the server stopped. + - mcp-curl-tests.sh: project A's one-phone tests (67). + - mcp-tests-bundle.sh unpacks mcp-lib.sh, mcp-import-side.sh (tests 6, 9mcp, 9person, 11) and mcp-share-side.sh + (test 10), for project A's second-phone tests. +- **Project A second-phone tests:** + 6. A real MCP import: the check code matches the other phone. + 7. A different store's copy is replaced without asking. + 8. The older-copy notification: answered, and no answer in 2 minutes keeps the copy. + 9. Cancel in the import notification, for a person's import and an MCP import. + 10. The Allow notification for an MCP share. + 11. server_start and import_start with the app off screen: works, or reports "person needed". +- **Project B second-phone tests:** + 1. Sound in a quiet and a noisy room, at several distances. + 2. Joins: already on the owner's Wi-Fi; the owner's hotspot with Connect tapped; no tap within 30 s; Android 9 + by hand; Try again on a joined hotspot; letting go after the import. + 3. Dark mode during "Connect?" with no tap: the screen shows the hotspot's name and password, with the code filled in. + 4. Phones without dual Wi-Fi lose their own Wi-Fi while joined. + 5. Cancel in the import notification. + +## 9. Findings from the code +- minSdk 28, targetSdk/compileSdk 36, Java 17. Only ZXing as a dependency; org.json is used for tests only. +- Store HttpServer on TCP 6175 (127.0.0.1 and the external address). Share discovery on UDP 6176: "LSD1 " + a hash + of the code to every broadcast address; the server replies "LSH1 ". +- Sharing runs in the server process. ShareActivity binds ServerService (flag 0) and polls every 500 ms. A person's + share closes when the screen is left; the screen stays on. +- Share codes: LS-XXXX-XXXX, 8 Crockford base32 characters = 5 bytes; normalize() forgives case, spaces, dashes, the + LS prefix, O→0, I/L→1. Link `shareyourapps-share://:/`; it carries no Wi-Fi details. +- Imported copies: files/imported// + .json, at most one per phone; swapped atomically with + rollback (SharePackage). A copy is never replaced under a running server. The local store is never touched. +- Hotspot: Wi-Fi Direct keeps a fixed name and password (Android 10+); the local-only fallback gets new ones each + time and needs Location on Android 9–12. Hotspot.info is non-null only on the app's own hotspot. + +## 10. Android requirements, and when a person is needed +- Permissions: RECORD_AUDIO, FOREGROUND_SERVICE_MICROPHONE, FOREGROUND_SERVICE_SPECIAL_USE, + FOREGROUND_SERVICE_DATA_SYNC, CHANGE_NETWORK_STATE, CHANGE_WIFI_STATE, POST_NOTIFICATIONS. No activity starts from + the background: notifications open the screens. +- A person is needed for: + - turning the MCP switch on, and the first microphone permission; + - Allow (always); + - Connect when joining the sharing phone's hotspot; + - a network not joined (the password is never given to MCP); + - an older copy replacing a newer one; + - a background start Android refuses. + + diff --git a/plugins/Share-Your-Apps/server/mcp-share-side.sh b/plugins/Share-Your-Apps/server/mcp-share-side.sh new file mode 100644 index 000000000..e297c7994 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-share-side.sh @@ -0,0 +1,85 @@ +#!/bin/sh +# Project A second-phone tests on the SHARING phone (phone 1). Opens shares with MCP for the importing +# phone's tests (6, 9, 11) and checks test 10: the "asks for a copy" notification for a share MCP opened. +# sh mcp-share-side.sh 2>&1 | tee share-result.txt +# Needs MCP_TOKEN (this phone's token), and this phone's own store published. +set -u +. "$(dirname "$0")/mcp-lib.sh" +echo "Sharing phone, $(date)" +start_session || exit 1 + +call server_status +if has '"serving":"copy"'; then + echo "This phone is serving an imported copy, which can't be shared." + echo "Tap Stop in the app, then run this again: it starts this phone's own store." + exit 1 +fi +if [ "$(field state)" != serving ]; then + info "The server isn't serving; starting it with this phone's own store." + call server_start '{"store":"own","wait_seconds":25}' + if [ "$(field state)" = serving ]; then pass "server_start serves this phone's own store" + else fail "server_start: $(field state)"; show; summary; fi +fi + +T10=0 +while :; do + call share_start + if is_error; then fail "share_start opened a share"; show; break; fi + n=0 + while [ "$(field state)" = preparing ] && [ "$n" -lt 4 ]; do + info "the store is being prepared; waiting for the code…" + call share_status '{"wait_seconds":20}' + n=$((n + 1)) + done + CODE="$(field code)"; LINK="$(field link)" + if [ -z "$CODE" ]; then fail "share_start gave a code"; show; break; fi + pass "share_start gave a code" + if has '"already_open":true'; then info "a share was already open; this is that share"; fi + if [ -n "$(field warning)" ]; then info "warning: $(field warning)"; fi + echo + echo " ==========================================" + echo " Code: $CODE" + echo " ==========================================" + echo " Link: $LINK" + echo " Type the code into mcp-import-side.sh on phone 2. It works once, for 10 minutes." + + LAST=; S=; ENTERED=0; END=$(( $(date +%s) + 720 )) + while :; do + call share_status '{"wait_seconds":20}' + if is_error; then info "share_status failed:"; show; S=; break; fi + S="$(field state)" + if [ "$S" != "$LAST" ]; then + info "share: $S $(field phone)" + LAST="$S" + if [ "$S" = waiting_for_allow ]; then + CHECK="$(field check_code)"; PHONE="$(field phone)"; STORE="$(field store)" + echo + echo " ==========================================" + echo " Check code: $CHECK (compare with phone 2)" + echo " ==========================================" + if has 'Notifications are off'; then info "notifications are off for this app on this phone"; fi + if [ "$T10" = 0 ]; then + T10=1 + by_eye "test 10: the \"asks for a copy\" notification appeared" \ + "Did a notification \"${PHONE:-A phone} asks for a copy of ${STORE:-your store}\" appear on this phone?" + by_eye "test 10: tapping it opened the share screen with Allow" \ + "Tap it. Did the share screen open with Allow and the check code $CHECK?" + fi + echo ">>> Tap Allow (or Deny) on this phone. For test 9, tap nothing and let phone 2 cancel." + wait_enter "When you've tapped, or phone 2 has cancelled," + ENTERED=1 + fi + fi + case "$S" in done|denied|expired|closed|not_serving|cant_share) break ;; esac + if [ "$ENTERED" = 1 ] && { [ "$S" = waiting_for_allow ] || [ "$S" = phone_connecting ]; }; then + if confirm "The share is still $S. Close it now?"; then + call share_stop; info "share_stop: $(field reason)"; S=closed; break + fi + fi + if [ "$(date +%s)" -ge "$END" ]; then info "still $S after 12 minutes"; break; fi + done + info "the share ended: ${S:-unknown} $(field reason)" + case "$S" in done|denied|expired|closed|not_serving|cant_share) ;; *) call share_stop ;; esac + confirm "Open a new share for the next test?" || break +done +summary diff --git a/plugins/Share-Your-Apps/server/mcp-sound-tests-1phone.sh b/plugins/Share-Your-Apps/server/mcp-sound-tests-1phone.sh new file mode 100644 index 000000000..6d7b6b3ca --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-sound-tests-1phone.sh @@ -0,0 +1,204 @@ +#!/bin/sh +# mcp-sound-tests-1phone.sh: step C's MCP sound tools on one phone, through mcp-call.sh (a curl MCP client). +# +# Run it with this phone's token exported first (Copy token, under the MCP control switch). Paste the token after +# the first line; it isn't shown: +# stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN +# sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/mcp-sound-tests-1phone.sh" +# +# It starts the server, opens a share, then stops the server; at the end the server is left stopped. +# It asks a few questions (do you hear tones?), and asks you to talk or tap near the phone for 30 s. +# While it runs, Share Your Apps Server is off screen: so the listening tests are also the off-screen tests. +# Everything goes to the screen and to mcp-sound-tests-1phone-result.txt in this folder: paste that to the agent. +# +# 1 tools lists share_play_sound and import_listen 9 server_stop +# 2 server_start serves 10 import_listen listens +# 3 share_start: a share waiting for a phone 11 import_start refused while listening +# 4 share_play_sound plays (you hear tones) 12 import_status follows listening to its end: +# 5 share_play_sound again: already playing nothing_heard = the microphone works off screen +# 6 share_play_sound stop (the tones stop) 13 import_cancel stops listening +# 7 import_listen refused while serving 14 import_listen stop, nothing listening +# 8 share_stop; share_play_sound then refused 15 View logs has the [sound] lines (you check) +# Plain sh, no bash. + +set -u +NAME="mcp-sound-tests-1phone.sh" + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\". Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder."; exit 2; } +cd "$HERE" || exit 2 +[ -f mcp-call.sh ] || { echo "STOPPED: mcp-call.sh isn't in $HERE."; exit 2; } +command -v curl >/dev/null 2>&1 || { echo "STOPPED: curl isn't installed. In Termux: pkg install curl"; exit 2; } +if [ -z "${MCP_TOKEN:-}" ]; then + echo "STOPPED: MCP_TOKEN isn't set, or isn't exported. Run these, pasting the token after the first line:" + echo " stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN" + exit 2 +fi +[ -r /dev/tty ] || { echo "STOPPED: this needs a terminal, for its questions."; exit 2; } + +RES="mcp-sound-tests-1phone-result.txt" +P=0; F=0; S=0; OUT="" + +line() { printf '%s\n' "$1" | tee -a "$RES"; } +pass() { P=$((P+1)); line "PASS $1"; } +fail() { F=$((F+1)); line "FAIL $1"; } +skip() { S=$((S+1)); line "SKIP $1"; } +# call TOOL [ARGUMENTS]: one tool call; its answer is shown, logged, and kept in $OUT. +call() { + line "" + line "\$ sh mcp-call.sh $*" + OUT="$(sh ./mcp-call.sh "$@" 2>&1)" + printf '%s\n' "$OUT" | tee -a "$RES" +} +# has REGEX: whether the last answer matches (extended regex; spaces after : allowed). +has() { printf '%s\n' "$OUT" | grep -Eq "$1"; } +# ask QUESTION: yes or no, from the terminal; the answer is logged. +ask() { + printf '\n>>> %s [y/n] ' "$1" > /dev/tty + read -r a < /dev/tty + printf '%s\n' "QUESTION: $1 -> ${a:-}" >> "$RES" + case "$a" in y|Y|yes|Yes|YES) return 0 ;; *) return 1 ;; esac +} +note() { printf '\n>>> %s\n' "$1" > /dev/tty; printf '%s\n' "NOTE: $1" >> "$RES"; } + +: > "$RES" +line "mcp-sound-tests-1phone.sh, $(date)" +if ! ask "This starts the server, opens a share, then stops the server and leaves it stopped. Go on?"; then + line "Not run: the answer was no."; exit 0 +fi + +# ---- 0. MCP control answers. +call server_status +if has "Couldn't start an MCP session|The request failed"; then + line "STOPPED: MCP control didn't answer. Is it on? Is MCP_TOKEN this phone's token, from Copy token?" + exit 1 +fi + +# ---- 1. The tool list. +call tools +if has 'share_play_sound' && has 'import_listen'; then pass "1 tools lists share_play_sound and import_listen" +else fail "1 tools doesn't list share_play_sound and import_listen: is this the step C build?"; fi + +# ---- 2. Serving. +SERVING=no +call server_start '{"wait_seconds":25}' +if has '"state": *"serving"'; then pass "2 server_start serves"; SERVING=yes +else fail "2 server_start didn't serve (see above): tests 3 to 8 are skipped"; fi + +if [ "$SERVING" = yes ]; then + # ---- 3. A share waiting for a phone (it may first be preparing, after a publish). + call share_start + n=0 + while ! has '"state": *"waiting_for_phone"' && has '"state": *"preparing"' && [ $n -lt 2 ]; do + n=$((n+1)); call share_status '{"wait_seconds":25}' + done + if has '"state": *"waiting_for_phone"'; then + pass "3 share_start: a share waiting for a phone" + + # ---- 4. Tones. + call share_play_sound + if has '"playing": *true'; then + if ask "Do you hear tones from this phone? (Media volume up.)"; then pass "4 share_play_sound plays, and the tones are heard" + else fail "4 share_play_sound says it plays, but no tones were heard"; fi + else fail "4 share_play_sound didn't play (see above)"; fi + + # ---- 5. Again, while playing. + call share_play_sound + if has '"already_playing": *true'; then pass "5 share_play_sound while playing: already_playing" + else fail "5 share_play_sound while playing didn't say already_playing"; fi + + # ---- 6. Stop. + call share_play_sound '{"stop":true}' + if has '"stopped": *true'; then + if ask "Have the tones stopped?"; then pass "6 share_play_sound stop: stopped" + else fail "6 share_play_sound stop said stopped, but the tones carried on"; fi + else fail "6 share_play_sound stop didn't stop (were the tones already over? see above)"; fi + + # ---- 7. Listening is refused while serving. + call import_listen + if has 'serving a store'; then pass "7 import_listen refused while serving" + else fail "7 import_listen wasn't refused while serving"; import_cancel_needed=yes; fi + [ "${import_cancel_needed:-no}" = yes ] && call import_cancel + + # ---- 8. No share, no sound. + call share_stop + call share_play_sound + if has 'only works while a share is waiting|no_share_waiting'; then pass "8 share_play_sound refused with no share waiting" + else fail "8 share_play_sound wasn't refused with no share waiting"; fi + else + fail "3 share_start: no share waiting for a phone (see above): tests 4 to 8 are skipped" + for t in 4 5 6 7 8; do skip "$t (no share)"; done + call share_stop + fi +else + for t in 3 4 5 6 7 8; do skip "$t (not serving)"; done +fi + +# ---- 9. Stop serving: an import, or listening, needs a stopped server. +call server_stop '{"wait_seconds":25}' +if has '"state": *"(stopped|failed)"'; then pass "9 server_stop: not serving" +else fail "9 server_stop: still serving or stopping (see above)"; fi + +# ---- 10 to 12. Listening, with the app off screen. +note "Next, the phone listens for 30 s. TALK OR TAP NEAR THE PHONE the whole time, so the microphone hears something. Don't play any share code." +printf '>>> Press Enter to start listening. ' > /dev/tty; read -r _ < /dev/tty +call import_listen +if has '"phase": *"listening"'; then + pass "10 import_listen listens" + + call import_start '{"code":"LS-0000-0000"}' + if has 'import_listen is still listening'; then pass "11 import_start refused while listening" + else fail "11 import_start wasn't refused while listening"; fi + + n=0 + while [ $n -lt 3 ]; do + n=$((n+1)); call import_status '{"wait_seconds":25}' + has '"phase": *"listening"' || break + done + if has '"phase": *"nothing_heard"'; then + pass "12 listening ended nothing_heard: the microphone works with the app off screen" + elif has 'heard only silence'; then + if ask "Were you talking or tapping near the phone during the 30 s?"; then + fail "12 only silence while you made sounds: Android blocked the microphone with the app off screen" + else + fail "12 only silence, but no sounds were made: run it again, making sounds" + fi + elif has '"phase": *"listening"'; then fail "12 still listening after 3 calls of 25 s" + elif has '"phase": *"(checking|joining|import_started)"'; then fail "12 heard a share code: was another phone playing one? (see above)" + else fail "12 listening ended some other way (see above)"; fi +else + fail "10 import_listen didn't listen (see above): tests 11 and 12 are skipped" + skip "11 (not listening)"; skip "12 (not listening)" +fi + +# ---- 13. import_cancel stops listening. +call import_listen +if has '"phase": *"listening"'; then + call import_cancel + if has 'Stopped listening'; then + call import_status + if has '"phase": *"stopped"'; then pass "13 import_cancel stops listening; import_status shows stopped" + else fail "13 import_cancel said it stopped, but import_status doesn't show stopped"; fi + else fail "13 import_cancel didn't stop listening"; call import_listen '{"stop":true}'; fi +else skip "13 (import_listen didn't listen)"; fi + +# ---- 14. Stop with nothing listening. +call import_listen '{"stop":true}' +if has 'Nothing was listening'; then pass "14 import_listen stop with nothing listening: says so" +else fail "14 import_listen stop with nothing listening didn't say so"; fi + +# ---- 15. The log, which only the app can show (its folder is private). +note "Open Share Your Apps Server, tap View logs, and look for [sound] lines from just now: 'played ... for an MCP client', 'listening for a share code, for an MCP client', 'heard nothing in 30 s', 'stopped listening: by an MCP client'." +if ask "Are those [sound] lines in View logs?"; then pass "15 View logs has the [sound] lines" +else fail "15 some [sound] lines are missing from View logs: tell the agent which"; fi + +line "" +line "Done: $P passed, $F failed, $S skipped. The server is left stopped: tap Start, or sh mcp-call.sh server_start." +line "Results: $HERE/$RES Paste that file, or this screen, to the agent." +exit 0 +# END OF mcp-sound-tests-1phone.sh diff --git a/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone-howto.md b/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone-howto.md new file mode 100644 index 000000000..0925641d0 --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone-howto.md @@ -0,0 +1,89 @@ +# How to run the two-phone MCP sound tests (mcp-sound-tests-2phone.sh) + +The script tests step C's MCP sound tools on two phones: one phone shares its store and plays its code as tones, the +other listens, hears the code and imports the store. It uses mcp-call.sh (a curl MCP client) for every call. + +## How it works +- You run the same script on both phones, with a different role: + - **Sharing phone:** `sh mcp-sound-tests-2phone.sh share` + - **Importing phone:** `sh mcp-sound-tests-2phone.sh import` +- The script tells you when to press Enter on each phone. Start listening on the importing phone first, then press + Enter on the sharing phone straight away to play the tones. +- If nothing is heard, either side offers to try again, up to 3 times. +- Each phone saves its results beside the script, in `mcp-sound-tests-2phone-share-result.txt` or + `mcp-sound-tests-2phone-import-result.txt`. Each run replaces that phone's file. +- At the end, the sharing phone is left **serving**. The importing phone is left **stopped**, with the imported copy + on it. Any copy the importing phone already had may be replaced. +- Instead of running the share side, the sharing phone's person may open **Share this store…** and tap **Play sound**; + then run only the import side. + +## What it tests +**Sharing side (S1–S8):** +1. The server starts. +2. A share opens and waits for a phone. +3. `share_play_sound` plays. +4. A phone connects. +5. The tones stop by themselves once it connects. +6. The "asks for a copy" notification opens the Allow screen. +7. The copy is sent. +8. View logs has the "played" and "allowed" lines. + +**Importing side (I1–I10):** +1. The server stops. +2. `import_listen` listens. +3. The code is heard. +4. The Connect prompt appears (hotspot run only). +5. The import starts by itself. +6. The check code matches the sharing phone's. +7. The import finishes. +8. `copy_on_phone` is true. +9. `on_owners_network` matches what Wi-Fi settings show (this checks open item 8 in mcp-session-state.md). +10. View logs has the "listening" and "heard" lines. + +## Run it twice +- **a.** Both phones on the same ordinary Wi-Fi. +- **b.** The sharing phone on its own hotspot: Wi-Fi on but not joined to any network. The importing phone on another + network. Android should ask the importing phone to **Connect**; tap it within 30 s (Android 10 and later). + +## Limits +- **S5 can pass for the wrong reason:** if the tones had already run their full 30 s before the phone connected, it + still passes. +- **I4 depends on your answer:** the script can see that the app tried to join the hotspot, but only you can confirm + the Connect prompt appeared. +- **Long waits are normal:** I6 and I7 can wait up to about 12 minutes, and S7 up to about 10 minutes, while someone + taps Allow. + +## Steps +1. **Get the combined build onto the second phone.** A Standard Run only installs on the phone running Code on the + Go. One way: on that phone's share screen, use the small "No Share Your Apps Server on the other phone?" QR code, + which downloads the build from it. Android may refuse to install over an older build signed differently. If so, + uninstall the old app on the second phone first. That deletes its data, including its MCP token and any imported + copy. +2. **On the second phone:** turn MCP control on and allow the microphone (the line under the switch should have no + "Microphone" warning). Install curl and python3 in Termux: `pkg install curl python`. Copy both `mcp-call.sh` and + `mcp-sound-tests-2phone.sh` into one folder. +3. **On each phone:** export that phone's own token (from Copy token, under its MCP control switch), pasted after the + first line, which hides it: + ``` + stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN + ``` +4. Run the share side first and the import side second, and follow the prompts. Turn the media volume up and hold + the phones close. +5. Paste both result files to the agent, for run a, and for run b if you can. + +## Housekeeping (from the same session) +- Swap in the new state file, if not done yet, from the Combined folder: + ``` + cp mcp-session-state.md mcp-session-state.prev.md + mv mcp-session-state.new.md mcp-session-state.md + ``` +- Then delete what's no longer needed (`rm -rf` can't be undone: check the names first): + ``` + rm -rf ProjectA project-b-reference + rm -f HANDOFF.md mcp-session-state.md.old make-combined.sh mcp-sound-tests-1phone-result.txt + ``` +- Move `qr-from-picture-plan.md` out of the "Share Your Apps Server Sound" folder before deleting that folder. +- Keep `step-c-backup/`, the step C scripts and the original "Share Your Apps Server" folder until a two-phone import by + sound has worked. + + diff --git a/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone.sh b/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone.sh new file mode 100644 index 000000000..b4d04300f --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-sound-tests-2phone.sh @@ -0,0 +1,292 @@ +#!/bin/sh +# mcp-sound-tests-2phone.sh: step C's MCP sound tools on two phones, through mcp-call.sh (a curl MCP client). +# One phone shares, the other imports: run this script on each, with its role. +# +# Before running, on BOTH phones: +# - the combined build installed; MCP control on; the microphone allowed (the line under the switch has no +# "Microphone" warning); +# - this script and mcp-call.sh in the same folder (copy both to the other phone; any folder works); +# - curl and python3 installed (in Termux: pkg install curl python); +# - that phone's OWN token exported (Copy token, under its MCP control switch), pasted after the first line: +# stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN +# +# Then, in this order: +# 1. Sharing phone: sh mcp-sound-tests-2phone.sh share (runs until it says to start the import side) +# 2. Importing phone: sh mcp-sound-tests-2phone.sh import (press Enter there to listen) +# 3. Sharing phone: press Enter at once, to play the tones. Hold the phones close, media volume up. +# Then follow both screens: a person taps the notification and Allow on the sharing phone. +# +# Run it twice to cover both ways of joining: +# a. both phones on the same ordinary Wi-Fi (the import reaches the sharing phone directly); +# b. the sharing phone on its own hotspot (Wi-Fi on but not joined to a network), the importing phone on another +# network: Android should ask the importing phone to Connect to the hotspot (Android 10 and later). +# Instead of the share side, the sharing phone's person may open Share this store... and tap Play sound; then run +# only the import side. +# +# The share side leaves its server serving; the import side leaves its server stopped, with the imported copy. +# An imported copy already on the importing phone may be replaced. +# Results go to the screen and to mcp-sound-tests-2phone--result.txt beside this script: paste both. +# +# Share side: S1 server_start S2 share_start S3 share_play_sound S4 a phone connects S5 the tones stop by +# themselves S6 the "asks for a copy" notification S7 the copy is sent S8 View logs +# Import side: I1 server_stop I2 import_listen I3 the code is heard I4 the Connect prompt (hotspot only) +# I5 the import starts I6 the check code matches I7 the import is done I8 copy_on_phone +# I9 on_owners_network is right I10 View logs +# Plain sh, no bash. + +set -u +NAME="mcp-sound-tests-2phone.sh" + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\". Ask the agent to write it again." + exit 2 +fi + +ROLE="${1:-}" +case "$ROLE" in + share|import) ;; + *) echo "Usage: sh $NAME share (on the sharing phone, first)" + echo " sh $NAME import (on the importing phone)" + exit 2 ;; +esac + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder."; exit 2; } +cd "$HERE" || exit 2 +[ -f mcp-call.sh ] || { echo "STOPPED: mcp-call.sh isn't in $HERE. Copy it beside this script."; exit 2; } +command -v curl >/dev/null 2>&1 || { echo "STOPPED: curl isn't installed. In Termux: pkg install curl"; exit 2; } +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || { echo "STOPPED: python3 isn't installed. In Termux: pkg install python"; exit 2; } +if [ -z "${MCP_TOKEN:-}" ]; then + echo "STOPPED: MCP_TOKEN isn't set, or isn't exported. Run these, pasting this phone's token after the first line:" + echo " stty -echo; read -r MCP_TOKEN; stty echo; export MCP_TOKEN" + exit 2 +fi +[ -r /dev/tty ] || { echo "STOPPED: this needs a terminal, for its questions."; exit 2; } + +RES="mcp-sound-tests-2phone-$ROLE-result.txt" +PASSN=0; FAILN=0; SKIPN=0; OUT="" + +line() { printf '%s\n' "$1" | tee -a "$RES"; } +pass() { PASSN=$((PASSN+1)); line "PASS $1"; } +fail() { FAILN=$((FAILN+1)); line "FAIL $1"; } +skip() { SKIPN=$((SKIPN+1)); line "SKIP $1"; } +# call TOOL [ARGUMENTS]: one tool call; its answer is shown, logged, and kept in $OUT. +call() { + line "" + line "\$ sh mcp-call.sh $*" + OUT="$(sh ./mcp-call.sh "$@" 2>&1)" + printf '%s\n' "$OUT" | tee -a "$RES" +} +has() { printf '%s\n' "$OUT" | grep -Eq "$1"; } +# jget a.b: a field of the last answer, if it was JSON; empty otherwise. true/false for booleans. +jget() { + printf '%s' "$OUT" | "$PY" -c ' +import json, sys +try: + d = json.loads(sys.stdin.read()) +except Exception: + sys.exit(0) +for k in sys.argv[1].split("."): + if isinstance(d, dict) and k in d: d = d[k] + else: sys.exit(0) +if isinstance(d, bool): print("true" if d else "false") +elif d is not None: print(d) +' "$1" +} +ask() { + printf '\n>>> %s [y/n] ' "$1" > /dev/tty + read -r a < /dev/tty + printf '%s\n' "QUESTION: $1 -> ${a:-}" >> "$RES" + case "$a" in y|Y|yes|Yes|YES) return 0 ;; *) return 1 ;; esac +} +note() { printf '\n>>> %s\n' "$1" > /dev/tty; printf '%s\n' "NOTE: $1" >> "$RES"; } +enter() { + printf '\n>>> %s\n>>> Press Enter when ready. ' "$1" > /dev/tty + read -r _ < /dev/tty + printf '%s\n' "WAITED: $1" >> "$RES" +} +finish() { + line "" + line "Done ($ROLE side): $PASSN passed, $FAILN failed, $SKIPN skipped." + line "$1" + line "Results: $HERE/$RES Paste that file, and the other phone's, to the agent." + exit 0 +} +mcp_ok() { + call server_status + if has "Couldn't start an MCP session|The request failed|No token given"; then + line "STOPPED: MCP control didn't answer. Is it on? Is MCP_TOKEN this phone's own token, from Copy token?" + exit 1 + fi +} + +# ======================================================================== the sharing phone +share_side() { + ask "This phone SHARES: it starts its server, opens a share and plays its code. The server is left serving. Go on?" \ + || { line "Not run: the answer was no."; exit 0; } + mcp_ok + + call server_start '{"wait_seconds":25}' + [ "$(jget state)" = serving ] || { fail "S1 server_start didn't serve (see above)"; finish "Stopped early."; } + pass "S1 server_start serves, on network kind $(jget network.kind)" + + call share_start + n=0 + while [ "$(jget state)" = preparing ] && [ $n -lt 3 ]; do n=$((n+1)); call share_status '{"wait_seconds":25}'; done + [ "$(jget state)" = waiting_for_phone ] || { fail "S2 no share waiting for a phone (see above)"; finish "Stopped early."; } + pass "S2 share_start: share $(jget code) waiting for a phone" + + OWN=unknown; MOVED=no; try=0 + while [ $try -lt 3 ] && [ "$MOVED" = no ]; do + try=$((try+1)) + enter "On the importing phone, run: sh $NAME import, and press Enter there to start listening. Then press Enter here AT ONCE to play. Hold the phones close; media volume up." + call share_play_sound + [ "$(jget playing)" = true ] || { fail "S3 share_play_sound didn't play (see above)"; finish "Stopped early."; } + if [ $try = 1 ]; then OWN="$(jget own_hotspot)"; pass "S3 share_play_sound plays (own_hotspot $OWN)"; fi + n=0 + while [ $n -lt 3 ]; do + n=$((n+1)); call share_status '{"wait_seconds":25}' + [ "$(jget state)" = waiting_for_phone ] || { MOVED=yes; break; } + done + if [ "$MOVED" = no ]; then + call share_play_sound '{"stop":true}' + ask "No phone has connected yet. Try again? (Start listening on the importing phone again first.)" || break + fi + done + [ "$MOVED" = yes ] || { fail "S4 no phone connected"; call share_stop; finish "The share was closed; the server is still serving."; } + pass "S4 a phone connected (share state $(jget state))" + + # The watcher looks once a second: give it a moment, then ask to stop. Nothing should be playing any more. + sleep 3 + call share_play_sound '{"stop":true}' + if [ "$(jget stopped)" = false ]; then pass "S5 the tones stopped by themselves once the phone connected" + else fail "S5 the tones were still playing after the phone connected (stopped now)"; fi + + call share_status + n=0 + while [ "$(jget state)" = phone_connecting ] && [ $n -lt 4 ]; do n=$((n+1)); call share_status '{"wait_seconds":25}'; done + if [ "$(jget state)" = waiting_for_allow ]; then + note "A notification should say \"$(jget phone) asks for a copy of $(jget store)\". Tap it, check the four digits match the importing phone's, choose an expiry, and tap Allow." + if ask "Did the notification appear, and open the Allow screen?"; then pass "S6 the \"asks for a copy\" notification opened the Allow screen" + else fail "S6 the \"asks for a copy\" notification didn't appear, or didn't open the Allow screen"; fi + else + fail "S6 the share didn't reach waiting_for_allow (state $(jget state))" + fi + + n=0; ST="" + while [ $n -lt 24 ]; do + n=$((n+1)); call share_status '{"wait_seconds":25}' + ST="$(jget state)" + case "$ST" in done|denied|expired|closed|transfer_failed|not_serving) break ;; esac + done + if [ "$ST" = done ]; then pass "S7 the copy was sent: done" + else fail "S7 the share ended $ST, not done (see above)"; fi + + note "Open Share Your Apps Server, tap View logs, and look for: \"[sound] played the code ..., for an MCP client\" and \"[share] allowed ... a copy\"." + if ask "Are both lines in View logs?"; then pass "S8 View logs has the played and allowed lines" + else fail "S8 a line is missing from View logs: tell the agent which"; fi + finish "The server is left serving." +} + +# ======================================================================== the importing phone +import_side() { + ask "This phone IMPORTS: it stops its server, listens for the sharing phone's tones and imports its store. A copy already on this phone may be replaced. Go on?" \ + || { line "Not run: the answer was no."; exit 0; } + mcp_ok + + call server_stop '{"wait_seconds":25}' + case "$(jget state)" in + stopped|failed) pass "I1 server_stop: not serving" ;; + *) fail "I1 server_stop: still serving or stopping (see above)"; finish "Stopped early." ;; + esac + + HEARD=no; JOINED=no; LP=""; try=0 + while [ $try -lt 3 ] && [ "$HEARD" = no ]; do + try=$((try+1)) + enter "Get the sharing phone to its \"Press Enter\" to play. Press Enter HERE to start listening, then press Enter THERE at once." + call import_listen + [ "$(jget phase)" = listening ] || { fail "I2 import_listen didn't listen (see above)"; finish "Stopped early."; } + [ $try = 1 ] && pass "I2 import_listen listens" + n=0 + while [ $n -lt 8 ]; do + n=$((n+1)); call import_status '{"wait_seconds":25}' + LP="$(jget listen.phase)" + case "$LP" in + listening|checking) ;; + joining) + if [ "$JOINED" = no ]; then + JOINED=yes + note "Android should now ask to connect to the sharing phone's hotspot, $(jget listen.owner_network). Tap Connect within 30 s." + fi ;; + *) break ;; + esac + done + case "$LP" in + import_started) HEARD=yes ;; + nothing_heard) line "Nothing heard this time."; ask "Try listening again?" || break ;; + *) break ;; + esac + done + if [ "$HEARD" = no ]; then + fail "I3 the code wasn't heard, or the import didn't start: listen phase $LP: $(jget listen.message)" + finish "Stopped early. The server is left stopped." + fi + pass "I3 heard the code $(jget listen.code)" + if [ "$JOINED" = yes ]; then + if ask "Did Android's Connect prompt appear, and did you tap Connect?"; then pass "I4 joined the sharing phone's hotspot after Connect" + else fail "I4 the import started, but the Connect prompt wasn't seen: tell the agent what you saw"; fi + else + skip "I4 (no hotspot to join: this phone reached the sharing phone on its own network)" + fi + pass "I5 the import started by itself" + + # Follow the import: the person checks the digits and taps Allow on the sharing phone. + ASKED=no; QSHOWN=""; PH=""; n=0 + while [ $n -lt 30 ]; do + n=$((n+1)) + PH="$(jget phase)" + case "$PH" in done|failed|denied|cancelled) break ;; esac + CHECK="$(jget check_code)" + if [ "$ASKED" = no ] && [ -n "$CHECK" ]; then + ASKED=yes + note "This phone's check code is $CHECK. On the sharing phone, tap the \"asks for a copy\" notification." + if ask "Does the sharing phone's Allow screen show the same digits, $CHECK?"; then pass "I6 the check code matches the sharing phone's" + else fail "I6 the check codes don't match: tap Deny on the sharing phone"; fi + note "Now tap Allow on the sharing phone, if the digits matched." + fi + if [ "$(jget state)" = person_needed ] && [ "$QSHOWN" != "$(jget question.title)" ]; then + QSHOWN="$(jget question.title)" + note "A person is needed on THIS phone: $(jget person_needed)" + fi + call import_status '{"wait_seconds":25}' + done + [ "$ASKED" = yes ] || skip "I6 (no check code was seen)" + if [ "$PH" != done ]; then + fail "I7 the import ended $PH, not done: $(jget message)" + finish "The server is left stopped." + fi + pass "I7 imported $(jget store): $(jget files) files, $(jget total) bytes" + + if [ "$(jget copy_on_phone)" = true ]; then pass "I8 copy_on_phone: true" + else fail "I8 copy_on_phone isn't true right after the import"; fi + + OWNERS="$(jget on_owners_network)" + if ask "Is this phone connected to the sharing phone's OWN hotspot right now? (Look in Wi-Fi settings.)"; then EXP=true; else EXP=false; fi + if [ "$OWNERS" = "$EXP" ]; then pass "I9 on_owners_network is $OWNERS, which matches Wi-Fi settings" + else fail "I9 on_owners_network is $OWNERS, but Wi-Fi settings say $EXP (open item 8: tell the agent both phones' networks)"; fi + + note "Open Share Your Apps Server, tap View logs, and look for: \"[sound] listening for a share code, for an MCP client\" and \"[sound] heard code $(jget listen.code) ...\"." + if ask "Are both lines in View logs?"; then pass "I10 View logs has the listening and heard lines" + else fail "I10 a line is missing from View logs: tell the agent which"; fi + finish "The server is left stopped. To serve the copy: Serve this store, or sh mcp-call.sh server_start '{\"store\":\"copy\"}'." +} + +: > "$RES" +line "$NAME $ROLE, $(date)" +if [ "$ROLE" = share ]; then share_side; else import_side; fi +exit 0 +# END OF mcp-sound-tests-2phone.sh diff --git a/plugins/Share-Your-Apps/server/mcp-tests-bundle.sh b/plugins/Share-Your-Apps/server/mcp-tests-bundle.sh new file mode 100644 index 000000000..691f2acdc --- /dev/null +++ b/plugins/Share-Your-Apps/server/mcp-tests-bundle.sh @@ -0,0 +1,413 @@ +#!/bin/sh +# Unpacks the project A second-phone test scripts (tests 6, 9, 10 and 11) next to this file: +# mcp-lib.sh shared parts, read by the other two +# mcp-import-side.sh for the importing phone (phone 2): tests 6, 9 and 11 +# mcp-share-side.sh for the sharing phone (phone 1): opens shares, and test 10 +# Run once on each phone: sh mcp-tests-bundle.sh +# It never overwrites: if one of the three files is already here, it stops and unpacks nothing. +set -u +cd "$(dirname "$0")" || exit 2 +for f in mcp-lib.sh mcp-import-side.sh mcp-share-side.sh; do + if [ -e "$f" ]; then + echo "$f is already here, so nothing was unpacked. Move or delete it, then run this again." + exit 2 + fi +done + +cat > mcp-lib.sh <<'MCP_LIB_EOF' +# Shared parts of the MCP second-phone tests. Read by mcp-import-side.sh and mcp-share-side.sh; +# not run on its own. Plain sh: no bash, no jq. +URL="${MCP_URL:-http://127.0.0.1:6176/mcp}" +command -v curl >/dev/null 2>&1 || { echo "curl isn't installed."; exit 2; } +if [ -z "${MCP_TOKEN:-}" ]; then + echo "MCP_TOKEN isn't set. In the app, tap Copy token, then run: export MCP_TOKEN=''" + echo "and run this again. Each phone has its own token." + exit 2 +fi +if ! (exec < /dev/tty) 2>/dev/null; then echo "These tests ask questions, so they need a terminal."; exit 2; fi +umask 077 +WORK="$(mktemp -d "${TMPDIR:-/tmp}/mcp-2p.XXXXXX")" || { echo "Couldn't make a temporary folder."; exit 2; } +trap 'end_session; rm -rf "$WORK"' EXIT +trap 'exit 130' INT TERM +# The token goes to curl from a private file: never on its command line, never printed. +printf 'Authorization: Bearer %s\n' "$MCP_TOKEN" > "$WORK/auth" +PASS=0; FAIL=0; CALL_ID=10; HTTP=000; SESSION=; PHASE=; CHECK=; a_ans= + +pass() { PASS=$((PASS + 1)); echo "PASS $1"; } +fail() { FAIL=$((FAIL + 1)); echo "FAIL $1"; } +info() { echo " $1"; } +show() { + echo " reply (HTTP $HTTP): $(head -c 1500 "$WORK/body")" + if [ -s "$WORK/err" ]; then echo " curl: $(cat "$WORK/err")"; fi +} + +# Questions use the terminal itself, so | tee result.txt can't hide them. The answers are +# recorded as PASS or FAIL lines, which do go to the result file. +confirm() { + while :; do + printf '\n>>> %s [y/n] ' "$1" > /dev/tty + read -r c_ans < /dev/tty || return 1 + case "$c_ans" in y|Y|yes|Yes|YES) return 0 ;; n|N|no|No|NO) return 1 ;; esac + done +} +by_eye() { if confirm "$2"; then pass "$1"; else fail "$1"; fi; } +ask() { printf '\n>>> %s ' "$1" > /dev/tty; read -r a_ans < /dev/tty || a_ans=; } +wait_enter() { printf '\n>>> %s (press Enter) ' "$1" > /dev/tty; read -r w_ans < /dev/tty || true; } + +# post BODY: one request in the session; the reply is left in $WORK/body, its status in $HTTP. +post() { + printf '%s' "$1" > "$WORK/call" + : > "$WORK/body"; : > "$WORK/head"; : > "$WORK/err" + HTTP="$(curl -sS -X POST -o "$WORK/body" -D "$WORK/head" -w '%{http_code}' --max-time 45 \ + -H "@$WORK/auth" -H "@$WORK/session" -H 'Content-Type: application/json' \ + --data-binary "@$WORK/call" "$URL" 2>"$WORK/err")" + [ -n "$HTTP" ] || HTTP=000 +} +# call TOOL [ARGS-JSON] +call() { + CALL_ID=$((CALL_ID + 1)) + c_args="${2:-}"; [ -n "$c_args" ] || c_args='{}' + post "$(printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}' "$CALL_ID" "$1" "$c_args")" +} + +start_session() { + : > "$WORK/session" + post '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"two-phone-test","version":"1"}}}' + SESSION="$(grep -i '^mcp-session-id:' "$WORK/head" | head -n 1 | cut -d: -f2- | tr -d ' \r')" + if [ "$HTTP" != 200 ] || [ -z "$SESSION" ]; then + echo "MCP control didn't answer at $URL." + echo "Check that MCP control is on in Share Your Apps Server, and that MCP_TOKEN is this phone's token." + show + return 1 + fi + printf 'Mcp-Session-Id: %s\nMCP-Protocol-Version: 2025-06-18\n' "$SESSION" > "$WORK/session" + post '{"jsonrpc":"2.0","method":"notifications/initialized"}' + return 0 +} +end_session() { + if [ -n "$SESSION" ] && [ -d "$WORK" ]; then + curl -sS -X DELETE -o /dev/null --max-time 5 -H "@$WORK/auth" -H "@$WORK/session" "$URL" 2>/dev/null || true + SESSION= + fi +} + +# Reading the last reply. field NAME: a string value (empty for null). num NAME: a number. +field() { sed -n 's/.*"'"$1"'":"\([^"]*\)".*/\1/p' "$WORK/body" | head -n 1 | sed 's#\\/#/#g'; } +num() { sed -n 's/.*"'"$1"'":\([0-9][0-9]*\).*/\1/p' "$WORK/body" | head -n 1; } +has() { grep -qF -- "$1" "$WORK/body"; } +is_error() { [ "$HTTP" != 200 ] || has '"isError":true' || has '"error":{'; } +needs_person() { has 'person_needed' || has 'A person is needed'; } + +summary() { + echo + echo "$PASS passed, $FAIL failed." + if [ "$FAIL" = 0 ]; then echo "All checks passed."; exit 0; fi + echo "Paste the FAIL lines into the chat." + exit 1 +} +MCP_LIB_EOF + +cat > mcp-import-side.sh <<'MCP_IMPORT_EOF' +#!/bin/sh +# Project A second-phone tests on the IMPORTING phone (phone 2). Tests from mcp-session-state.md: +# sh mcp-import-side.sh 6 a real MCP import; the check code is compared with phone 1 +# sh mcp-import-side.sh 9mcp Cancel in the import notification, for an import MCP started +# sh mcp-import-side.sh 9person the same, for an import a person started on the import screen +# sh mcp-import-side.sh 11 server_start and import_start with the app off screen +# Keep the results: sh mcp-import-side.sh 6 2>&1 | tee result-t6.txt +# Needs MCP_TOKEN (this phone's token). Optional: MCP_PHONE_NAME, the name phone 1's owner sees. +# Phone 1 runs mcp-share-side.sh, which opens a share and shows its code. +set -u +TEST="${1:-}" +case "$TEST" in 6|9mcp|9person|11) ;; *) echo "Say which test: sh mcp-import-side.sh 6 | 9mcp | 9person | 11"; exit 2 ;; esac +. "$(dirname "$0")/mcp-lib.sh" +echo "Test $TEST on the importing phone, $(date)" + +# The imported copy on this phone, to check a cancelled import leaves it as it was. +copy_sig() { + call store_info + if has '"imported_copy":null'; then echo "none"; else echo "$(field store_id) $(field created) $(num bytes)"; fi +} + +# An import needs the server stopped and no import running. +ensure_stopped() { + call server_status + st="$(field state)" + case "$st" in + serving|starting|paused) + info "The server is $st on this phone; stopping it (an import needs it stopped)." + call server_stop '{"wait_seconds":20}' + st="$(field state)" + if [ "$st" = stopped ] || [ "$st" = failed ]; then pass "server_stop stopped the server" + else fail "server_stop: the server is $st"; show; return 1; fi ;; + esac + call import_status + if has '"busy":true'; then + echo "An import is already running on this phone ($(field phase)). End it on the import screen, then run this again." + return 1 + fi + return 0 +} + +read_code() { + CODE_ARGS= + while [ -z "$CODE_ARGS" ]; do + ask "Type the code shown on phone 1 (LS-XXXX-XXXX), or its link, then press Enter:" + r="$(printf '%s' "$a_ans" | tr -d ' \r')" + case "$r" in + shareyourapps-share://*) CODE_ARGS="\"link\":\"$(printf '%s' "$r" | tr -cd 'A-Za-z0-9:/.-')\"" ;; + ?*) CODE_ARGS="\"code\":\"$(printf '%s' "$r" | tr -cd 'A-Za-z0-9-')\"" ;; + esac + done +} + +start_import() { + s_args="{$CODE_ARGS" + if [ -n "${MCP_PHONE_NAME:-}" ]; then + s_args="$s_args,\"phone_name\":\"$(printf '%s' "$MCP_PHONE_NAME" | tr -d '"\\')\"" + fi + call import_start "$s_args}" +} + +# follow_import STOP_PHASES MAX_SECONDS: follows import_status, printing each change, until the phase +# is one of STOP_PHASES or MAX_SECONDS pass. Sets PHASE and CHECK. +follow_import() { + f_stop=" $1 "; f_end=$(( $(date +%s) + $2 )); f_last=; f_wait=0 + while :; do + call import_status "{\"wait_seconds\":$f_wait}" + f_wait=20 + if is_error; then info "import_status failed:"; show; PHASE=; return 1; fi + PHASE="$(field phase)"; CHECK="$(field check_code)" + if needs_person; then f_q=yes; else f_q=; fi + f_now="$PHASE|$CHECK|$f_q" + if [ "$f_now" != "$f_last" ]; then + info "import: $PHASE, started by $(field started_by): $(field message)" + if [ -n "$f_q" ]; then info "person needed: $(field person_needed)"; fi + f_last="$f_now" + fi + case "$f_stop" in *" $PHASE "*) return 0 ;; esac + if [ "$(date +%s)" -ge "$f_end" ]; then info "still $PHASE after $2 seconds"; return 1; fi + done +} + +show_check() { + echo + echo " ==========================================" + echo " Check code on this phone: ${CHECK:-(none yet)}" + echo " ==========================================" +} + +# After the import reaches waiting: a person taps Cancel in this phone's import notification. +cancel_step() { + echo ">>> Don't tap Allow on phone 1." + echo ">>> On THIS phone, pull down the notifications and tap Cancel in the import notification." + follow_import "cancelled failed denied done idle" 300 + if [ "$PHASE" = cancelled ]; then pass "Cancel in the notification cancelled $1 import" + else fail "Cancel in the notification ($1 import): it ended as ${PHASE:-unknown}"; fi + by_eye "the import notification went away after Cancel" "Has the import notification gone from this phone?" + after="$(copy_sig)" + if [ "$after" = "$BEFORE" ]; then pass "the copy already on this phone is unchanged ($after)" + else fail "the copy on this phone changed: before $BEFORE, after $after"; fi + echo ">>> On phone 1, answer the share script's question to close the share." +} + +if [ "$TEST" = 11 ]; then + echo ">>> Test 11: Share Your Apps Server must stay off screen. You're in the terminal, so it is." + echo ">>> Don't open the app until this script ends." + wait_enter "Ready? The script waits 15 seconds, then starts." + sleep 15 +fi + +if ! start_session; then + if [ "$TEST" = 11 ]; then fail "MCP control answered with the app off screen"; summary; fi + exit 1 +fi + +case "$TEST" in +6) + ensure_stopped || exit 1 + read_code + start_import + if is_error; then fail "import_start started the import"; show; summary; fi + pass "import_start started the import" + if [ "$(field started_by)" = mcp ]; then pass "import_status says MCP started it" + else fail "started_by is \"$(field started_by)\", not mcp"; fi + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + if [ -n "$CHECK" ]; then + by_eye "the check code matches phone 1" "Does phone 1 show the same check code, $CHECK?" + else + fail "import_status gave a check code while waiting" + fi + echo ">>> Now on phone 1: choose an expiry and tap Allow." + follow_import "done failed denied cancelled" 600 + if [ "$PHASE" = done ]; then pass "the import finished"; else fail "the import ended as ${PHASE:-unknown}"; summary; fi + STORE="$(field store)" + if [ -n "$(field note)" ]; then info "note: $(field note)"; fi + call store_info + if has '"imported_copy":null'; then fail "store_info shows the imported copy" + elif [ -n "$STORE" ] && has "\"name\":\"$STORE\""; then pass "store_info shows the imported copy of $STORE" + else fail "store_info's imported copy is $STORE"; show; fi + ;; +9mcp) + ensure_stopped || exit 1 + BEFORE="$(copy_sig)" + info "imported copy before: $BEFORE" + read_code + start_import + if is_error; then fail "import_start started the import"; show; summary; fi + pass "import_start started the import" + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + cancel_step "an MCP" + ;; +9person) + ensure_stopped || exit 1 + BEFORE="$(copy_sig)" + info "imported copy before: $BEFORE" + echo ">>> On this phone: open Share Your Apps Server, tap Import a store…, type phone 1's code and tap Continue." + echo ">>> When it says it's waiting for phone 1's owner, come back to this terminal." + wait_enter "Back here?" + call import_status + if ! has '"busy":true'; then fail "a person's import is running (phase $(field phase))"; show; summary; fi + if [ "$(field started_by)" = person ]; then pass "import_status says a person started it" + else fail "started_by is \"$(field started_by)\", not person"; fi + follow_import "waiting done failed denied cancelled" 180 + if [ "$PHASE" != waiting ]; then fail "the import reached waiting (it is ${PHASE:-unknown})"; summary; fi + show_check + cancel_step "a person's" + ;; +11) + pass "MCP control answered with the app off screen" + call server_status + case "$(field state)" in + serving|starting|paused) call server_stop '{"wait_seconds":20}'; info "stopped the server first: $(field state)" ;; + esac + call server_start '{"wait_seconds":25}' + st="$(field state)" + if ! is_error && [ "$st" = starting ]; then sleep 10; call server_status; st="$(field state)"; fi + if needs_person; then + pass "server_start off screen: reports person needed"; info "$(field person_needed)" + elif ! is_error && [ "$st" = serving ]; then + pass "server_start off screen: serving" + call server_stop '{"wait_seconds":20}' + if [ "$(field state)" = stopped ]; then pass "server_stop off screen"; else fail "server_stop off screen: $(field state)"; show; fi + else + fail "server_start off screen: neither serving nor person needed"; show + fi + ensure_stopped || summary + echo ">>> On phone 1, open a new share and read its code." + read_code + start_import + if needs_person; then + pass "import_start off screen: reports person needed"; info "$(field person_needed)" + elif is_error; then + fail "import_start off screen: neither started nor person needed"; show + else + pass "import_start off screen: the import started" + follow_import "waiting done failed denied cancelled" 180 + show_check + echo ">>> On phone 1: check the code is $CHECK, choose an expiry and tap Allow." + follow_import "done failed denied cancelled" 600 + if [ "$PHASE" = done ]; then pass "the import finished with the app off screen" + else fail "the import with the app off screen ended as ${PHASE:-unknown}"; fi + fi + ;; +esac +summary +MCP_IMPORT_EOF + +cat > mcp-share-side.sh <<'MCP_SHARE_EOF' +#!/bin/sh +# Project A second-phone tests on the SHARING phone (phone 1). Opens shares with MCP for the importing +# phone's tests (6, 9, 11) and checks test 10: the "asks for a copy" notification for a share MCP opened. +# sh mcp-share-side.sh 2>&1 | tee share-result.txt +# Needs MCP_TOKEN (this phone's token), and this phone's own store published. +set -u +. "$(dirname "$0")/mcp-lib.sh" +echo "Sharing phone, $(date)" +start_session || exit 1 + +call server_status +if has '"serving":"copy"'; then + echo "This phone is serving an imported copy, which can't be shared." + echo "Tap Stop in the app, then run this again: it starts this phone's own store." + exit 1 +fi +if [ "$(field state)" != serving ]; then + info "The server isn't serving; starting it with this phone's own store." + call server_start '{"store":"own","wait_seconds":25}' + if [ "$(field state)" = serving ]; then pass "server_start serves this phone's own store" + else fail "server_start: $(field state)"; show; summary; fi +fi + +T10=0 +while :; do + call share_start + if is_error; then fail "share_start opened a share"; show; break; fi + n=0 + while [ "$(field state)" = preparing ] && [ "$n" -lt 4 ]; do + info "the store is being prepared; waiting for the code…" + call share_status '{"wait_seconds":20}' + n=$((n + 1)) + done + CODE="$(field code)"; LINK="$(field link)" + if [ -z "$CODE" ]; then fail "share_start gave a code"; show; break; fi + pass "share_start gave a code" + if has '"already_open":true'; then info "a share was already open; this is that share"; fi + if [ -n "$(field warning)" ]; then info "warning: $(field warning)"; fi + echo + echo " ==========================================" + echo " Code: $CODE" + echo " ==========================================" + echo " Link: $LINK" + echo " Type the code into mcp-import-side.sh on phone 2. It works once, for 10 minutes." + + LAST=; S=; ENTERED=0; END=$(( $(date +%s) + 720 )) + while :; do + call share_status '{"wait_seconds":20}' + if is_error; then info "share_status failed:"; show; S=; break; fi + S="$(field state)" + if [ "$S" != "$LAST" ]; then + info "share: $S $(field phone)" + LAST="$S" + if [ "$S" = waiting_for_allow ]; then + CHECK="$(field check_code)"; PHONE="$(field phone)"; STORE="$(field store)" + echo + echo " ==========================================" + echo " Check code: $CHECK (compare with phone 2)" + echo " ==========================================" + if has 'Notifications are off'; then info "notifications are off for this app on this phone"; fi + if [ "$T10" = 0 ]; then + T10=1 + by_eye "test 10: the \"asks for a copy\" notification appeared" \ + "Did a notification \"${PHONE:-A phone} asks for a copy of ${STORE:-your store}\" appear on this phone?" + by_eye "test 10: tapping it opened the share screen with Allow" \ + "Tap it. Did the share screen open with Allow and the check code $CHECK?" + fi + echo ">>> Tap Allow (or Deny) on this phone. For test 9, tap nothing and let phone 2 cancel." + wait_enter "When you've tapped, or phone 2 has cancelled," + ENTERED=1 + fi + fi + case "$S" in done|denied|expired|closed|not_serving|cant_share) break ;; esac + if [ "$ENTERED" = 1 ] && { [ "$S" = waiting_for_allow ] || [ "$S" = phone_connecting ]; }; then + if confirm "The share is still $S. Close it now?"; then + call share_stop; info "share_stop: $(field reason)"; S=closed; break + fi + fi + if [ "$(date +%s)" -ge "$END" ]; then info "still $S after 12 minutes"; break; fi + done + info "the share ended: ${S:-unknown} $(field reason)" + case "$S" in done|denied|expired|closed|not_serving|cant_share) ;; *) call share_stop ;; esac + confirm "Open a new share for the next test?" || break +done +summary +MCP_SHARE_EOF + +chmod 700 mcp-lib.sh mcp-import-side.sh mcp-share-side.sh 2>/dev/null +echo "Unpacked mcp-lib.sh, mcp-import-side.sh and mcp-share-side.sh." +echo "Phone 1: sh mcp-share-side.sh 2>&1 | tee share-result.txt" +echo "Phone 2: sh mcp-import-side.sh 6 2>&1 | tee result-t6.txt (or 9mcp, 9person, 11)" diff --git a/plugins/Share-Your-Apps/server/qr-from-picture-plan.md b/plugins/Share-Your-Apps/server/qr-from-picture-plan.md new file mode 100644 index 000000000..06673a252 --- /dev/null +++ b/plugins/Share-Your-Apps/server/qr-from-picture-plan.md @@ -0,0 +1,69 @@ +# Plan: read QR codes from a picture on the import screen (project B) + +Status: PLANNED, NOT approved, no code written. Saved for later (user: "We will take it later"). +The user's standing rule applies: plan first; build nothing until the user approves. + +## Request +"On the import screen, support QR recognition from an image already on the phone", for all QR codes +the app shows, on all screens (user: "All qr codes means all codes on all screens"). + +## What was found (read-only) +- ImportActivity.kt (read in full, 522 lines): the only way a share QR reaches the import screen today is + the camera app opening the shareyourapps-share://… link (onCreate parses intent.data with ShareLink.parse + and fills linkAddress / linkCode). Nothing reads a picture. +- QR codes the app shows: + | Screen | Code | Content | + |---|---|---| + | Share screen (ShareActivity.kt:366) | Share code | shareyourapps-share://
:/ | + | Serve screen, "1. Join this Wi-Fi network" (ServeActivity.kt:149) | Wi-Fi code | QrCodes.wifi(ssid, password): the app's own hotspot, the phone's Mobile hotspot, or a home Wi-Fi network (the last two typed by the owner) | + | Serve screen, "2. Open the store" | Store code | NOT read yet; drawn by the qr(content) helper (ServeActivity.kt:256); content set in lines 1–119; probably the store's web address | +- Gaps to close before writing: + 1. The QR search stopped at 100 matches (mostly build/ files); search app/src only to confirm no other codes. + 2. Read ServeActivity.kt lines 1–119 for the store code's content. + +## Plan +- Button "Read QR code from a picture" below Listen on the import screen. Opens Android's own image + chooser (no new permission, no manifest change). +- Reading, off the main thread: scale the picture to about 1600 px on the longest side; find every QR code + (ZXing multiple-code reader); try harder if needed; also read light-on-dark codes. +- What each code does: + - Share link: fill in the code and the owner's address; the person taps Continue. + - A bare share code (LS-XXXX-XXXX): fill in the code; the person taps Continue. + - Wi-Fi code (any of the three networks, or another app's Wi-Fi code): join that network. + - Android 10+: the system "Connect?" prompt; the network is kept for the import started with Continue + and let go when the import ends or the screen is left. + - Android 9, WEP, hidden networks, or no tap within 30 s: show the name and password to join by hand. + - A Wi-Fi code holds no share code: "Joined. Now scan or type the share code." + - Store code: explain that it opens the store in a browser and can't import it; ask the owner to tap + "Share this store…". Final wording after reading what the code holds. + - Several codes in one picture (e.g. a whole Serve screenshot): join Wi-Fi first, then fill in the code; + list the rest. + - Codes from other apps: shown as text with Copy, never acted on. + - No code found: "No QR code found in that picture." + - Log: a "[qr]" line in the app's log; never a password, never the full text of other apps' codes. +- Files: + - New QrImage.kt: finds the codes in a picture. + - New QrContent.kt: plain Kotlin; sorts each text into share link, share code, Wi-Fi (escapes, type, + hidden flag), store code, other. + - Changed ImportActivity.kt: button, chooser, handling, list of other codes. + - Probably changed WifiJoin.kt: join any WPA or open network, not only the owner's hotspot; keep a network + joined BEFORE Continue (today it lets go whenever no import is running). + - Changed help/build_help_db.py: importing.html section and an import.qr_image tooltip. + - New app/src/test/java/QrContentTest.kt: draw each app code with QrCodes, read it back, check the sorting; + Wi-Fi codes with odd characters, open and hidden networks; other apps' codes never acted on. +- Read first: ServeActivity.kt lines 1–119; app/build.gradle (does the ZXing library include decoding?); + WifiJoin.kt; QrCodes.kt; QrTest.kt; a QR search limited to app/src. + +## Decisions (agent's suggestions, waiting for the user) +1. Scope: every code the app shows on any screen; other apps' codes shown as text. Suggest: yes. +2. Wi-Fi codes for a home network or Mobile hotspot are joined like the app's hotspot (used only by this + app for the import, then let go). Suggest: yes. +3. A share code from a picture fills in the form; the person taps Continue (as with the camera). Suggest: yes. +4. Other apps' codes: Copy only, no Open. Suggest: yes. +5. QR codes only, no other barcode types. Suggest: yes. +6. The store code is explained, not used for importing (confirm after reading its content). Suggest: yes. + +## Testing (when built) +Screenshots on the phone: the share screen; the Serve screen with each kind of Wi-Fi code (app hotspot, +Mobile hotspot, home Wi-Fi); the "Open the store" code; a QR code from another app; one picture with +several codes. diff --git a/plugins/Share-Your-Apps/server/r5 b/plugins/Share-Your-Apps/server/r5 new file mode 100644 index 000000000..f0f1b6052 --- /dev/null +++ b/plugins/Share-Your-Apps/server/r5 @@ -0,0 +1,8 @@ +Every function SoundImport.kt calls is in the project (20 checked). +Checks passed: SoundImport.kt, 193 lines, 11142 bytes. + added app/src/main/java/org/appdevforall/shareyourapps/server/SoundImport.kt: 11142 bytes, sha256 92f82f3c72d1... +It reads back as written. + +Record: step-c-backup/5 Checksums: step-c-checksums.txt +Next: a Standard Run (nothing uses SoundImport yet: this checks it compiles). Script 6 adds import_listen. +Paste all of this output, and the build result, to the agent. diff --git a/plugins/Share-Your-Apps/server/settings.gradle.kts b/plugins/Share-Your-Apps/server/settings.gradle.kts new file mode 100644 index 000000000..aeb111d18 --- /dev/null +++ b/plugins/Share-Your-Apps/server/settings.gradle.kts @@ -0,0 +1,34 @@ +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} + +// AGP 9 compiles Kotlin itself and refuses the `org.jetbrains.kotlin.android` plugin. +// It takes the compiler from the kotlin-gradle-plugin jar on this classpath, so this +// is where the Kotlin version is pinned, beside AGP: the two must share a class loader. +// Code On The Go injects the on-device Maven repo here so it resolves offline. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath("com.android.tools.build:gradle:9.3.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.21") + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "Share Your Apps Server" + +include(":app") diff --git a/plugins/Share-Your-Apps/server/step-c-1-copy.sh b/plugins/Share-Your-Apps/server/step-c-1-copy.sh new file mode 100644 index 000000000..3eac6bef9 --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-1-copy.sh @@ -0,0 +1,178 @@ +#!/bin/sh +# step-c-1-copy.sh: step C, script 1 of 6. Copies project B's sound files into this project, unchanged. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-1-copy.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-1-copy.sh" undo +# (puts back the files it replaced, deletes the files it added) +# +# Copied from project-b-reference (only read, never changed) to the same place here: +# app/src/main/java/org/appdevforall/shareyourapps/server/ +# SoundPayload.kt SoundDsp.kt SoundModem.kt SoundDecoder.kt SoundIo.kt SoundLog.kt WifiJoin.kt (new here) +# ImportActivity.kt (replaces A's) +# SoundPayloadTest.kt SoundModemTest.kt SoundLogTest.kt SoundLevelTest.kt (found by name under app/src/test) +# help/build_help_db.py (replaces A's: B's copy has all of A's MCP help, plus the sound help) +# +# Before changing anything it checks: this file ends with its END line (it wasn't cut off); this is the +# Combined folder; it hasn't run before; every source file exists, exactly once. +# Then it backs up what it replaces (step-c-backup/1), copies, and checks that every copy's SHA-256 equals +# its source's. If a check fails once copying has started, it undoes itself. Checksums: step-c-checksums.txt. +# At the end it lists the files that still differ from project B, for the agent. +# +# The project won't build after this script alone: run step-c-2-import.sh too first. +# Plain sh, no bash. + +set -u +NAME="step-c-1-copy.sh" +STEP=1 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +REF="project-b-reference" +SRC="app/src/main/java/org/appdevforall/shareyourapps/server" +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +# ---- Undo: put back what was replaced, delete what was added, forget this step's checksums. +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + UNDO_OK=yes + if [ -f "$BK/replaced.txt" ]; then + while IFS= read -r f; do + [ -n "$f" ] || continue + if cp "$BK/files/$f" "$f"; then echo " put back: $f" + else echo " COULDN'T PUT BACK: $f (its copy is in $BK/files)"; UNDO_OK=no; fi + done < "$BK/replaced.txt" + fi + if [ -f "$BK/added.txt" ]; then + while IFS= read -r f; do + [ -n "$f" ] || continue + if [ -e "$f" ]; then rm -f "$f" && echo " removed: $f"; fi + done < "$BK/added.txt" + fi + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + if [ "$UNDO_OK" = yes ]; then + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 + fi + echo "NOT fully undone: see the lines above. The backup stays in $BK." + return 1 +} + +case "${1:-}" in + "") ;; + undo) + for n in 2 3 4 5 6; do + if [ -d "step-c-backup/$n" ]; then + echo "STOPPED: step C script $n has run since this one. Undo it first (its script, with undo). Nothing was changed." + exit 1 + fi + done + echo "Undoing $NAME..." + undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +# ---- Checks. Nothing is changed until all of them pass. +[ -d "$REF/app/src" ] || fail "$REF/app/src isn't here. Is this the Combined folder made by make-combined.sh?" +[ -f "$SRC/McpService.kt" ] || fail "$SRC/McpService.kt isn't here, so this isn't project A's code." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +if command -v sha256sum >/dev/null 2>&1; then SHA=sha256sum +elif command -v toybox >/dev/null 2>&1 && toybox sha256sum "$0" >/dev/null 2>&1; then SHA="toybox sha256sum" +elif [ -n "$PY" ]; then SHA=py +else SHA="" +fi +[ -n "$SHA" ] || fail "can't work out SHA-256 checksums here: no sha256sum, toybox or Python." +sha() { + if [ "$SHA" = py ]; then + "$PY" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$1" + else + $SHA "$1" | cut -d ' ' -f 1 + fi +} + +PLAN="" +for f in SoundPayload.kt SoundDsp.kt SoundModem.kt SoundDecoder.kt SoundIo.kt SoundLog.kt WifiJoin.kt ImportActivity.kt; do + PLAN="$PLAN $SRC/$f" +done +for t in SoundPayloadTest.kt SoundModemTest.kt SoundLogTest.kt SoundLevelTest.kt; do + found="$(find "$REF/app/src/test" -type f -name "$t" 2>/dev/null)" + n="$(printf '%s\n' "$found" | grep -c .)" + [ "$n" = "1" ] || fail "expected 1 file named $t under $REF/app/src/test, found $n." + case "$found" in *" "*) fail "the path of $t has a space in it: $found" ;; esac + PLAN="$PLAN ${found#"$REF"/}" +done +PLAN="$PLAN help/build_help_db.py" +for p in $PLAN; do + [ -f "$REF/$p" ] || fail "$REF/$p is missing." +done +echo "Checks passed: $(echo $PLAN | wc -w | tr -d ' ') files to copy." + +# ---- Back up everything it will replace, and check each backup. +mkdir -p "$BK/files" || fail "couldn't make $BK." +: > "$BK/replaced.txt"; : > "$BK/added.txt"; : > "$BK/sums.txt" +for p in $PLAN; do + if [ -f "$p" ]; then + { mkdir -p "$BK/files/$(dirname "$p")" && cp "$p" "$BK/files/$p"; } || { rm -rf "$BK"; fail "couldn't back up $p."; } + [ "$(sha "$p")" = "$(sha "$BK/files/$p")" ] || { rm -rf "$BK"; fail "the backup of $p doesn't match it."; } + echo "$p" >> "$BK/replaced.txt" + else + echo "$p" >> "$BK/added.txt" + fi +done +echo "Backed up to $BK." + +# ---- Copy, and check every copy against its source. +echo "Copying from $REF..." +BAD="" +for p in $PLAN; do + { mkdir -p "$(dirname "$p")" && cp "$REF/$p" "$p"; } || { BAD="$p (the copy failed)"; break; } + a="$(sha "$REF/$p")"; b="$(sha "$p")" + if [ -z "$a" ] || [ "$a" != "$b" ]; then BAD="$p (its SHA-256 doesn't match the source's)"; break; fi + if grep -Fqx "$p" "$BK/replaced.txt"; then what="replaced"; else what="added "; fi + echo " $what $p ($(wc -c < "$p" | tr -d ' ') bytes, sha256 $(printf '%s' "$a" | cut -c1-12)...)" + echo "step$STEP $a $p" >> "$BK/sums.txt" +done +if [ -n "$BAD" ]; then + echo "FAILED: $BAD. Undoing what this script did..." + undo + exit 1 +fi +cat "$BK/sums.txt" >> "$SUMS" + +# ---- For the agent: what still differs from project B. "known" = merged by hand, or A's kept on purpose. +echo +echo "Files that still differ from project B:" +KNOWN=" ImportJob.kt ShareActivity.kt ImportService.kt MainActivity.kt AndroidManifest.xml HostService.kt StoreLog.kt Compressor.kt AuthTest.kt build_help_db.sh " +find "$REF/app/src" "$REF/help" -type f | sort | while IFS= read -r f; do + rel="${f#"$REF"/}" + if [ ! -f "$rel" ]; then echo " CHECK only in B: $rel"; continue; fi + [ "$(sha "$f")" = "$(sha "$rel")" ] && continue + case "$KNOWN" in + *" $(basename "$rel") "*) echo " known differs: $rel" ;; + *) echo " CHECK differs: $rel" ;; + esac +done + +echo +echo "Done: $(grep -c . "$BK/replaced.txt") replaced, $(grep -c . "$BK/added.txt") added. Every copy matches its source." +echo "Backup: $BK Checksums: $SUMS" +echo "Python for scripts 2 to 6: ${PY:-NOT FOUND}" +echo "Don't build yet: the project compiles only after step-c-2-import.sh. Paste all of this output to the agent." +exit 0 +# END OF step-c-1-copy.sh diff --git a/plugins/Share-Your-Apps/server/step-c-2-import.sh b/plugins/Share-Your-Apps/server/step-c-2-import.sh new file mode 100644 index 000000000..9ff74327d --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-2-import.sh @@ -0,0 +1,242 @@ +#!/bin/sh +# step-c-2-import.sh: step C, script 2 of 6. Merges ImportJob.kt (A + B) and gives B's ImportActivity.kt A's +# public defaultPhoneName(context), which McpTools uses. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-2-import.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-2-import.sh" undo +# +# ImportJob.kt (A's file, patched): +# 1. Snapshot gets storeId (B's stale import result fix). +# 2. start() doc: the owner's tones; the network parameter. +# 3. start() takes network (B) before byMcp (A), so both projects' calls still work. +# 4. start() passes network to run(). +# 5. run() uses the joined network first: joined ?: wifiNetwork(context). +# 6. DONE carries storeId; adds clearFinished() (synchronized with start) and onOwnersNetworkNow(). +# ImportActivity.kt (B's file, from script 1, patched): +# 7. The private defaultPhoneName() calls the companion's. +# 8. The companion gets A's public defaultPhoneName(context), cut to 40 characters. +# +# Before changing anything it checks: this file ends with its END line; script 1 has run; this one hasn't; +# every text to replace is in its file exactly once; every patch keeps { } and ( ) balanced. Then it backs up +# (step-c-backup/2), writes each file through a temporary file, reads it back and compares SHA-256. On any +# failure it puts every file back. Checksums: step-c-checksums.txt. +# After this script the project should compile: do a Standard Run. Plain sh, no bash; needs Python. + +set -u +NAME="step-c-2-import.sh" +STEP=2 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + UNDO_OK=yes + while IFS= read -r f; do + [ -n "$f" ] || continue + if cp "$BK/files/$f" "$f"; then echo " put back: $f" + else echo " COULDN'T PUT BACK: $f (its copy is in $BK/files)"; UNDO_OK=no; fi + done < "$BK/replaced.txt" + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + if [ "$UNDO_OK" = yes ]; then + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 + fi + echo "NOT fully undone: see the lines above. The backup stays in $BK." + return 1 +} + +case "${1:-}" in + "") ;; + undo) + for n in 3 4 5 6; do + if [ -d "step-c-backup/$n" ]; then + echo "STOPPED: step C script $n has run since this one. Undo it first (its script, with undo). Nothing was changed." + exit 1 + fi + done + echo "Undoing $NAME..." + undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +[ -d "step-c-backup/1" ] || fail "step-c-1-copy.sh hasn't run yet (step-c-backup/1 isn't here). Run it first." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || fail "neither python3 nor python was found." + +"$PY" - "$STEP" "$BK" "$SUMS" <<'PYEOF' +import hashlib, os, shutil, sys +step, bk, sums_path = sys.argv[1], sys.argv[2], sys.argv[3] +SRC = "app/src/main/java/org/appdevforall/shareyourapps/server/" +P = [] +def patch(f, what, old, new): P.append((SRC + f, what, old, new)) + +patch("ImportJob.kt", "Snapshot gets storeId", r''' /** Imported over the owner's own network: serving it there would depend on the owner's phone. */ + val onOwnersNetwork: Boolean = false, + ) {''', r''' /** Imported over the owner's own network: serving it there would depend on the owner's phone. */ + val onOwnersNetwork: Boolean = false, + /** Once DONE: the imported copy's store ID, so the screen can check the copy is still on this phone. */ + val storeId: String? = null, + ) {''') + +patch("ImportJob.kt", "start() doc", r''' * Starts importing, from [address] if known — from a QR link — or by searching for the code.''', +r''' * Starts importing, from [address] if known — from a QR link or the owner's tones — or by searching for the code. + * [network]: the network to use, such as the owner's hotspot that WifiJoin joined; null uses the phone's Wi-Fi.''') + +patch("ImportJob.kt", "start() takes network", r''' fun start(context: Context, code: String, phoneName: String, address: InetSocketAddress?, byMcp: Boolean = false): String? {''', +r''' fun start(context: Context, code: String, phoneName: String, address: InetSocketAddress?, + network: android.net.Network? = null, byMcp: Boolean = false): String? {''') + +patch("ImportJob.kt", "start() passes network to run()", r''' try { run(app, code, phoneName, address) }''', +r''' try { run(app, code, phoneName, address, network) }''') + +patch("ImportJob.kt", "run() uses the joined network first", r''' private fun run(context: Context, code: String, phoneName: String, known: InetSocketAddress?) { + // Everything goes over Wi-Fi explicitly: a network without internet, such as the owner's hotspot, + // isn't Android's default, and requests would otherwise go to mobile data, and fail. + val wifi = wifiNetwork(context) ?: throw IOException(''', r''' private fun run(context: Context, code: String, phoneName: String, known: InetSocketAddress?, joined: android.net.Network?) { + // Everything goes over Wi-Fi explicitly: a network without internet, such as the owner's hotspot, + // isn't Android's default, and requests would otherwise go to mobile data, and fail. A network WifiJoin + // joined (the owner's hotspot) comes first: it may not be the first Wi-Fi network Android lists. + val wifi = joined ?: wifiNetwork(context) ?: throw IOException(''') + +patch("ImportJob.kt", "DONE carries storeId; clearFinished(), onOwnersNetworkNow()", r''' set(Snapshot(Phase.DONE, "Imported", check, desc.storeName, desc.totalBytes, desc.totalBytes, desc.files.size, desc.expires, onOwnersNetwork = owners)) + }''', r''' set(Snapshot(Phase.DONE, "Imported", check, desc.storeName, desc.totalBytes, desc.totalBytes, desc.files.size, desc.expires, + onOwnersNetwork = owners, storeId = desc.storeId)) + } + + /** + * Forgets a finished import (done, denied, cancelled, or failed with no Try again), so the next visit to the import + * screen shows the empty form, not an old result. A failed transfer that can be tried again is kept, as is a busy one. + * Synchronized with [start], so an import an MCP client starts at the same moment is never wiped. + */ + @Synchronized + fun clearFinished() { + val s = snapshot + if (s.busy || s.phase == Phase.IDLE || s.canRetry) return + set(Snapshot(Phase.IDLE)) + } + + /** + * Whether this phone is on the owner's network now, not when the import ended: Wi-Fi may have been turned off or + * changed since. False with no Wi-Fi, or if no owner is known. + */ + fun onOwnersNetworkNow(context: Context): Boolean = + wifiNetwork(context.applicationContext)?.let { onOwnersNetwork(context.applicationContext, it) } == true''') + +patch("ImportActivity.kt", "private defaultPhoneName() calls the companion's", r''' private fun defaultPhoneName(): String = + (if (Build.VERSION.SDK_INT >= 25) Settings.Global.getString(contentResolver, Settings.Global.DEVICE_NAME) else null) + ?.takeIf { it.isNotBlank() } ?: Build.MODEL''', +r''' /** The phone's own name, at most 40 characters: the companion's [defaultPhoneName], which import_start uses too. */ + private fun defaultPhoneName(): String = defaultPhoneName(this)''') + +patch("ImportActivity.kt", "public defaultPhoneName(context) in the companion", r''' private var pendingByHand: ByHand? = null + } +}''', r''' private var pendingByHand: ByHand? = null + + /** + * The name the owner sees when this phone asks for a copy: the phone's own name, or its model. At most 40 + * characters, as the import screen's field allows. Public so an MCP import (import_start) uses the same default. + */ + fun defaultPhoneName(context: android.content.Context): String = + ((if (Build.VERSION.SDK_INT >= 25) Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME) else null) + ?.takeIf { it.isNotBlank() } ?: Build.MODEL).take(40) + } +}''') + +def stop(msg): + print("STOPPED: " + msg) + print("Nothing was changed.") + sys.exit(1) +def sha(b): return hashlib.sha256(b).hexdigest() +def bal(t): return (t.count("{") - t.count("}"), t.count("(") - t.count(")")) + +files = [] +for p in P: + if p[0] not in files: files.append(p[0]) +raw, out = {}, {} +for f in files: + if not os.path.isfile(f): stop(f + " isn't here.") + with open(f, "rb") as h: raw[f] = h.read() + t = raw[f].decode("utf-8") + for i, (g, what, old, new) in enumerate(P, 1): + if g != f: continue + if old == new: stop("patch %d (%s) changes nothing: the script is wrong." % (i, what)) + n = t.count(old) + if n != 1: stop("patch %d (%s): its text to replace is in %s %d times, not once. Has the file changed?" % (i, what, f, n)) + if bal(old) != bal(new): stop("patch %d (%s) would unbalance { } or ( ): the script is wrong." % (i, what)) + t = t.replace(old, new) + out[f] = t.encode("utf-8") +for i, (f, what, old, new) in enumerate(P, 1): + c = out[f].decode("utf-8").count(new) + if c != 1: stop("patch %d (%s): after patching, its new text is in %s %d times, not once." % (i, what, f, c)) +for f in files: + if bal(raw[f].decode("utf-8")) != bal(out[f].decode("utf-8")): stop(f + ": { } or ( ) would no longer balance as before.") +print("Checks passed: %d patches to %d files." % (len(P), len(files))) + +try: + os.makedirs(os.path.join(bk, "files")) + with open(os.path.join(bk, "replaced.txt"), "w") as h: + for f in files: + dst = os.path.join(bk, "files", f) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as o: o.write(raw[f]) + with open(dst, "rb") as o: + if sha(o.read()) != sha(raw[f]): raise IOError("the backup of %s doesn't match it" % f) + h.write(f + "\n") +except Exception as e: + shutil.rmtree(bk, ignore_errors=True) + stop("couldn't back up: %s." % e) +print("Backed up to %s." % bk) + +try: + for f in files: + tmp = f + ".step-c.tmp" + with open(tmp, "wb") as o: o.write(out[f]) + os.replace(tmp, f) + with open(f, "rb") as o: + if sha(o.read()) != sha(out[f]): raise IOError("%s doesn't read back as written" % f) +except Exception as e: + for f in files: + try: + with open(f, "wb") as o: o.write(raw[f]) + except Exception: print(" COULDN'T PUT BACK %s: its copy is in %s/files" % (f, bk)) + shutil.rmtree(bk, ignore_errors=True) + print("FAILED: %s. Every file was put back as it was." % e) + sys.exit(1) + +with open(sums_path, "a") as h: + for f in files: h.write("step%s %s %s\n" % (step, sha(out[f]), f)) +for f in files: + n = sum(1 for p in P if p[0] == f) + print(" patched %s: %d changes, %d -> %d bytes, sha256 %s..." % (f, n, len(raw[f]), len(out[f]), sha(out[f])[:12])) +for i, (f, what, _, _) in enumerate(P, 1): + print(" %d. %s: %s" % (i, os.path.basename(f), what)) +print("Every file reads back as written.") +PYEOF +RC=$? +[ "$RC" = 0 ] || exit "$RC" + +echo +echo "Backup: $BK Checksums: $SUMS" +echo "Next: a Standard Run (the project should compile now), then :app:testDebugUnitTest." +echo "Paste all of this output, and the build result, to the agent." +exit 0 +# END OF step-c-2-import.sh diff --git a/plugins/Share-Your-Apps/server/step-c-3-share.sh b/plugins/Share-Your-Apps/server/step-c-3-share.sh new file mode 100644 index 000000000..b50a682a1 --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-3-share.sh @@ -0,0 +1,287 @@ +#!/bin/sh +# step-c-3-share.sh: step C, script 3 of 6. Adds project B's Play sound / Stop sound to project A's ShareActivity.kt. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-3-share.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-3-share.sh" undo +# +# ShareActivity.kt (A's file, patched with B's sound code, copied from project B unchanged): +# 1. The class description mentions Play sound. +# 2. Fields: player and playButton. +# 3. onDestroy stops the tones and sends the "played" line first, while still connected to the server. +# 4. show(): the tones stop once the share leaves OPEN (a phone connected, or the share ended). +# 5. showCode(): the Play sound button under the code. +# 6. The sound functions: soundButton, playSound, logSound, stopSound, soundPayload, toast. +# A's joining of a share under way, ownShare and Cancel are unchanged. +# +# Same checks as script 2: not cut off; script 2 has run, this one hasn't; every text to replace is there exactly +# once; { } and ( ) stay balanced. Backup in step-c-backup/3; written through a temporary file, read back, SHA-256 +# compared; on any failure the file is put back. Checksums: step-c-checksums.txt. Plain sh, no bash; needs Python. + +set -u +NAME="step-c-3-share.sh" +STEP=3 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + UNDO_OK=yes + while IFS= read -r f; do + [ -n "$f" ] || continue + if cp "$BK/files/$f" "$f"; then echo " put back: $f" + else echo " COULDN'T PUT BACK: $f (its copy is in $BK/files)"; UNDO_OK=no; fi + done < "$BK/replaced.txt" + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + if [ "$UNDO_OK" = yes ]; then + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 + fi + echo "NOT fully undone: see the lines above. The backup stays in $BK." + return 1 +} + +case "${1:-}" in + "") ;; + undo) + for n in 4 5 6; do + if [ -d "step-c-backup/$n" ]; then + echo "STOPPED: step C script $n has run since this one. Undo it first (its script, with undo). Nothing was changed." + exit 1 + fi + done + echo "Undoing $NAME..." + undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +[ -d "step-c-backup/2" ] || fail "step-c-2-import.sh hasn't run yet (step-c-backup/2 isn't here). Run it first." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || fail "neither python3 nor python was found." + +"$PY" - "$STEP" "$BK" "$SUMS" <<'PYEOF' +import hashlib, os, shutil, sys +step, bk, sums_path = sys.argv[1], sys.argv[2], sys.argv[3] +SRC = "app/src/main/java/org/appdevforall/shareyourapps/server/" +P = [] +def patch(f, what, old, new): P.append((SRC + f, what, old, new)) + +patch("ShareActivity.kt", "class description mentions Play sound", r''' * share it opened itself; Cancel closes either kind. Allow and Deny are only ever sent from here, by a person. + * The screen stays on while it's open, since a server paused for a dark screen can't share. + */''', r''' * share it opened itself; Cancel closes either kind. Allow and Deny are only ever sent from here, by a person. + * The screen stays on while it's open, since a server paused for a dark screen can't share. Play sound plays the + * code as tones, for a phone that taps Listen; they stop when the share moves on or the screen closes. + */''') + +patch("ShareActivity.kt", "fields: player and playButton", r''' private var ownShare = false + private var lastState = "" +''', r''' private var ownShare = false + private var lastState = "" + /** Play sound: the player while the code plays, and its button, which reads Stop sound meanwhile. */ + private var player: SoundIo.Player? = null + private var playButton: Button? = null +''') + +patch("ShareActivity.kt", "onDestroy stops the tones and logs first", r''' override fun onDestroy() { + main.removeCallbacksAndMessages(null) +''', r''' override fun onDestroy() { + // Nothing plays off the screen: leaving it, or rotating, stops the tones. The "played" line is sent now, + // while the connection to the server is still open, rather than when the player thread ends. + val wasPlaying = player != null + stopSound() + if (wasPlaying) logPlayedNow?.invoke() + logPlayedNow = null + main.removeCallbacksAndMessages(null) +''') + +patch("ShareActivity.kt", "show(): tones stop once the share leaves OPEN", r''' if (key == lastState) return + lastState = key + val store = b.getString(Ipc.KEY_SHARE_STORE).orEmpty()''', r''' if (key == lastState) return + lastState = key + // The other phone has connected, or the share ended: the tones have done their job. + if (state != "OPEN") stopSound() + val store = b.getString(Ipc.KEY_SHARE_STORE).orEmpty()''') + +patch("ShareActivity.kt", "showCode(): Play sound button", r''' codeRow(code), + text("Both phones must be on the same Wi-Fi network or hotspot.''', r''' codeRow(code), + soundButton(code, link), + text("Both phones must be on the same Wi-Fi network or hotspot.''') + +patch("ShareActivity.kt", "the sound functions (from project B)", r''' private fun codeRow(code: String) = copyRow(code, 30f, clipLabel = "Share code", description = "Copy the code", + copied = "Code copied", sensitive = true) +''', r''' private fun codeRow(code: String) = copyRow(code, 30f, clipLabel = "Share code", description = "Copy the code", + copied = "Code copied", sensitive = true) + + // ---- Play sound ---- + /** Counts players started and stopped, so a finished player's callback can't reset a newer one's button. */ + private var soundRun = 0 + + /** Play sound, or Stop sound while the tones play. */ + private fun soundButton(code: String, link: String): Button = + button(if (player != null) "Stop sound" else "Play sound") { if (player != null) stopSound() else playSound(code, link) } + .help("share.sound").also { playButton = it } + + /** + * Logs the playing player's "played" line at once, as stopped early. onDestroy calls it while the connection to + * the server is still open; the player's own callback, coming later, then logs nothing. + */ + private var logPlayedNow: (() -> Unit)? = null + + private fun playSound(code: String, link: String) { + val payload = soundPayload(code, link) ?: return toast("Couldn't turn this code into sound.") + val low = SoundIo.volumeLow(this) + if (low) toast("The media volume is low: turn it up so the other phone hears the tones.") + val run = ++soundRun + var logged = false + lateinit var p: SoundIo.Player + p = SoundIo.Player(payload.encode()) { error -> + if (run == soundRun) { player = null; playButton?.text = "Play sound" } + if (error != null) toast(error) + if (!logged) { logged = true; logSound(SoundLog.played(p.rounds, p.stoppedEarly, low, payload.ownHotspot, error)) } + } + logPlayedNow = { if (!logged) { logged = true; logSound(SoundLog.played(p.rounds, true, low, payload.ownHotspot, null)) } } + player = p.start() + playButton?.text = "Stop sound" + } + + /** The server process owns the log file while it serves, so the line goes to it, over the share's connection. */ + private fun logSound(message: String) { + val line = SoundLog.line(message) + android.util.Log.i("ShareYourAppsSound", line) + send(Ipc.MSG_LOG, Bundle().apply { putString(Ipc.KEY_LINE, line) }) + } + + private fun stopSound() { + soundRun++ + player?.stop(); player = null + playButton?.text = "Play sound" + } + + /** + * What the tones carry: the code and the server's address from the share link; on this phone's own hotspot, + * also its name and password. On other Wi-Fi, neither name nor password (Hotspot.info is null there). + */ + private fun soundPayload(code: String, link: String): SoundPayload? { + val normalized = ShareCodes.normalize(code) ?: return null + val parsed = ShareLink.parse(link) + val address = parsed?.let { try { java.net.InetAddress.getByName(it.first) as? java.net.Inet4Address } catch (e: Exception) { null } } + val port = if (address != null && parsed != null) parsed.second else 0 + val hotspot = Hotspot.info + fun fits(s: String) = s.isNotEmpty() && s.toByteArray(Charsets.UTF_8).size <= SoundPayload.MAX_FIELD + val ssid = hotspot?.ssid?.takeIf { it != "?" && fits(it) } + val password = hotspot?.password?.takeIf { ssid != null && fits(it) } + return try { SoundPayload(normalized, if (port > 0) address else null, port, hotspot != null, ssid, password) } + catch (e: IllegalArgumentException) { null } + } + + private fun toast(t: String) { android.widget.Toast.makeText(this, t, android.widget.Toast.LENGTH_LONG).show() } +''') + +def stop(msg): + print("STOPPED: " + msg) + print("Nothing was changed.") + sys.exit(1) +def sha(b): return hashlib.sha256(b).hexdigest() +def bal(t): return (t.count("{") - t.count("}"), t.count("(") - t.count(")")) + +files = [] +for p in P: + if p[0] not in files: files.append(p[0]) +raw, out = {}, {} +for f in files: + if not os.path.isfile(f): stop(f + " isn't here.") + with open(f, "rb") as h: raw[f] = h.read() + t = raw[f].decode("utf-8") + if "SoundIo.Player" in t: stop(f + " already has sound code in it. Has this script, or a hand edit, been applied already?") + for i, (g, what, old, new) in enumerate(P, 1): + if g != f: continue + if old == new: stop("patch %d (%s) changes nothing: the script is wrong." % (i, what)) + n = t.count(old) + if n != 1: stop("patch %d (%s): its text to replace is in %s %d times, not once. Has the file changed?" % (i, what, f, n)) + if bal(old) != bal(new): stop("patch %d (%s) would unbalance { } or ( ): the script is wrong." % (i, what)) + t = t.replace(old, new) + out[f] = t.encode("utf-8") +for i, (f, what, old, new) in enumerate(P, 1): + c = out[f].decode("utf-8").count(new) + if c != 1: stop("patch %d (%s): after patching, its new text is in %s %d times, not once." % (i, what, f, c)) +for f in files: + if bal(raw[f].decode("utf-8")) != bal(out[f].decode("utf-8")): stop(f + ": { } or ( ) would no longer balance as before.") +# The sound code must match project B's word for word: compare each function body with B's file. +ref = "project-b-reference/" + SRC + "ShareActivity.kt" +if os.path.isfile(ref): + with open(ref, "rb") as h: b_text = h.read().decode("utf-8") + for marker in (" private fun playSound(", " private fun logSound(", " private fun stopSound(", " private fun soundPayload("): + mine = out[files[0]].decode("utf-8"); i, j = mine.find(marker), b_text.find(marker) + if i < 0 or j < 0: stop("couldn't find %s in both files." % marker.strip()) + end_m, end_b = mine.find("\n }\n", i), b_text.find("\n }\n", j) + if mine[i:end_m] != b_text[j:end_b]: stop("%s doesn't match project B's word for word: the script is wrong." % marker.strip()) + print("The sound functions match project B's word for word.") +print("Checks passed: %d patches to %d file." % (len(P), len(files))) + +try: + os.makedirs(os.path.join(bk, "files")) + with open(os.path.join(bk, "replaced.txt"), "w") as h: + for f in files: + dst = os.path.join(bk, "files", f) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as o: o.write(raw[f]) + with open(dst, "rb") as o: + if sha(o.read()) != sha(raw[f]): raise IOError("the backup of %s doesn't match it" % f) + h.write(f + "\n") +except Exception as e: + shutil.rmtree(bk, ignore_errors=True) + stop("couldn't back up: %s." % e) +print("Backed up to %s." % bk) + +try: + for f in files: + tmp = f + ".step-c.tmp" + with open(tmp, "wb") as o: o.write(out[f]) + os.replace(tmp, f) + with open(f, "rb") as o: + if sha(o.read()) != sha(out[f]): raise IOError("%s doesn't read back as written" % f) +except Exception as e: + for f in files: + try: + with open(f, "wb") as o: o.write(raw[f]) + except Exception: print(" COULDN'T PUT BACK %s: its copy is in %s/files" % (f, bk)) + shutil.rmtree(bk, ignore_errors=True) + print("FAILED: %s. Every file was put back as it was." % e) + sys.exit(1) + +with open(sums_path, "a") as h: + for f in files: h.write("step%s %s %s\n" % (step, sha(out[f]), f)) +for f in files: + n = sum(1 for p in P if p[0] == f) + print(" patched %s: %d changes, %d -> %d bytes, sha256 %s..." % (f, n, len(raw[f]), len(out[f]), sha(out[f])[:12])) +for i, (f, what, _, _) in enumerate(P, 1): + print(" %d. %s: %s" % (i, os.path.basename(f), what)) +print("Every file reads back as written.") +PYEOF +RC=$? +[ "$RC" = 0 ] || exit "$RC" + +echo +echo "Backup: $BK Checksums: $SUMS" +echo "Next: a Standard Run. Then, if you like, a quick check on the phone: start the server, tap Share this store...," +echo "then Play sound / Stop sound. Paste all of this output, and the build result, to the agent." +exit 0 +# END OF step-c-3-share.sh diff --git a/plugins/Share-Your-Apps/server/step-c-4-mic.sh b/plugins/Share-Your-Apps/server/step-c-4-mic.sh new file mode 100644 index 000000000..462025907 --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-4-mic.sh @@ -0,0 +1,291 @@ +#!/bin/sh +# step-c-4-mic.sh: step C, script 4 of 6. The microphone for MCP control: manifest, McpService, the MCP switch. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-4-mic.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-4-mic.sh" undo +# +# AndroidManifest.xml: +# 1. RECORD_AUDIO and FOREGROUND_SERVICE_MICROPHONE. +# 2. ImportActivity gets project B's configChanges (turning the phone doesn't stop Listen). +# 3. McpService's type becomes specialUse|microphone. +# McpService.kt: +# 4. A micType field: whether the service runs with the microphone type. +# 5. Started again while running (the app opened, the microphone allowed): the line under the switch is updated. +# 6. The line under the switch says whether import_listen can use the microphone. +# 7. goForeground: the microphone type when the microphone is allowed; if Android refuses it (the app not on +# screen), it runs as before, without it. The old code is kept for that case, unchanged. +# MainActivity.kt: +# 8. A request code for the microphone. +# 9. The "Turn on MCP control?" message gets the microphone paragraph; Turn on then asks for the microphone. +# 10. The microphone answered: MCP control starts again, with or without the microphone type. +# +# Same checks as scripts 2 and 3, plus: the manifest must still parse as XML. Backup in step-c-backup/4. +# Plain sh, no bash; needs Python. + +set -u +NAME="step-c-4-mic.sh" +STEP=4 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + UNDO_OK=yes + while IFS= read -r f; do + [ -n "$f" ] || continue + if cp "$BK/files/$f" "$f"; then echo " put back: $f" + else echo " COULDN'T PUT BACK: $f (its copy is in $BK/files)"; UNDO_OK=no; fi + done < "$BK/replaced.txt" + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + if [ "$UNDO_OK" = yes ]; then + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 + fi + echo "NOT fully undone: see the lines above. The backup stays in $BK." + return 1 +} + +case "${1:-}" in + "") ;; + undo) + for n in 5 6; do + if [ -d "step-c-backup/$n" ]; then + echo "STOPPED: step C script $n has run since this one. Undo it first (its script, with undo). Nothing was changed." + exit 1 + fi + done + echo "Undoing $NAME..." + undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +[ -d "step-c-backup/3" ] || fail "step-c-3-share.sh hasn't run yet (step-c-backup/3 isn't here). Run it first." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || fail "neither python3 nor python was found." + +"$PY" - "$STEP" "$BK" "$SUMS" <<'PYEOF' +import hashlib, os, shutil, sys +step, bk, sums_path = sys.argv[1], sys.argv[2], sys.argv[3] +SRC = "app/src/main/java/org/appdevforall/shareyourapps/server/" +MANIFEST = "app/src/main/AndroidManifest.xml" +P = [] +def patch(f, what, old, new): P.append((f, what, old, new)) + +patch(MANIFEST, "RECORD_AUDIO and FOREGROUND_SERVICE_MICROPHONE", r''' + +''', r''' + + + + + +''') + +patch(MANIFEST, "ImportActivity configChanges (project B)", r''' + ''', r''' + ''') + +patch(MANIFEST, "McpService type specialUse|microphone", r''' android:name=".McpService" + android:exported="false" + android:foregroundServiceType="specialUse">''', r''' android:name=".McpService" + android:exported="false" + android:foregroundServiceType="specialUse|microphone">''') + +patch(SRC + "McpService.kt", "micType field", r''' @Volatile private var http: McpHttp? = null +''', r''' @Volatile private var http: McpHttp? = null + /** Whether the service runs with the microphone type, so import_listen can hear tones with the app off screen. */ + @Volatile private var micType = false +''') + +patch(SRC + "McpService.kt", "started again while running: update the line", r''' if (http != null || starting) return START_NOT_STICKY''', +r''' if (http != null || starting) { + // Already running: the microphone type may have changed (the app opened, the microphone allowed or refused). + http?.let { McpStatus.set(McpStatus.State.ON, onText(it.boundPort)) } + return START_NOT_STICKY + }''') + +patch(SRC + "McpService.kt", "the line under the switch", r''' McpStatus.set(McpStatus.State.ON, "On, at http://127.0.0.1:${h.boundPort}${McpHttp.PATH}")''', +r''' McpStatus.set(McpStatus.State.ON, onText(h.boundPort))''') + +patch(SRC + "McpService.kt", "goForeground: the microphone type when allowed", r''' if (Build.VERSION.SDK_INT >= 34) { + startForeground(NOTIFICATION, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + } else { + startForeground(NOTIFICATION, n) + } + }''', r''' // The microphone type too, when the app may use the microphone, so import_listen hears tones with the app off + // screen. Android refuses that type unless the app is on screen (it isn't after a reboot, or from the + // background): then MCP runs as before, without it, and the next opening of the app adds it (onResume). + // Android 9 and 10 have no microphone type: any foreground service may use the microphone there. + val mic = SoundIo.canListen(this) + if (Build.VERSION.SDK_INT >= 30 && mic) { + val special = if (Build.VERSION.SDK_INT >= 34) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0 + try { + startForeground(NOTIFICATION, n, special or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + micType = true + return + } catch (e: Exception) { + Log.w(TAG, "the microphone type was refused (${e.javaClass.simpleName}); running without it until the app is opened") + } + } + micType = mic && Build.VERSION.SDK_INT < 30 + if (Build.VERSION.SDK_INT >= 34) { + startForeground(NOTIFICATION, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + } else { + startForeground(NOTIFICATION, n) + } + } + + /** The line under the switch while it's on: the address, and whether import_listen can use the microphone. */ + private fun onText(port: Int): String = "On, at http://127.0.0.1:$port${McpHttp.PATH}" + when { + !SoundIo.canListen(this) -> "\nMicrophone not allowed: hearing a sharing phone's tones needs a person." + !micType -> "\nMicrophone: works once the app is opened." + else -> "" + }''') + +patch(SRC + "MainActivity.kt", "request code for the microphone", r''' private const val IMPORT_CAPTION = "Serve a copy of someone else's store, with their permission. You'll need to be near their phone, on the same network." + }''', r''' private const val IMPORT_CAPTION = "Serve a copy of someone else's store, with their permission. You'll need to be near their phone, on the same network." + /** Asking for the microphone after MCP control is turned on, for import_listen. */ + private const val REQUEST_MCP_MIC = 4 + }''') + +patch(SRC + "MainActivity.kt", "switch message: microphone paragraph, then ask", r''' .setMessage("Apps on this phone will be able to start and stop the server, share this store and import a store.\n\n" + + "They can't change the store or approve a copy. You still tap Allow.\n\n" + + "Each app needs the token: use Copy token, below the switch.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Turn on") { _, _ -> McpService.setEnabled(this@MainActivity, true); showMcp() }''', +r''' .setMessage("Apps on this phone will be able to start and stop the server, share this store and import a store.\n\n" + + "They can't change the store or approve a copy. You still tap Allow.\n\n" + + "This also lets the app use the microphone to hear the sound a sharing phone plays. It only listens while " + + "it's receiving a handshake, and Android shows its microphone indicator while it does.\n\n" + + "Each app needs the token: use Copy token, below the switch.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Turn on") { _, _ -> + McpService.setEnabled(this@MainActivity, true); showMcp() + // The microphone, for import_listen: asked now, while the person is here. Refused: MCP is on anyway. + if (!SoundIo.canListen(this@MainActivity)) + this@MainActivity.requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_MCP_MIC) + }''') + +patch(SRC + "MainActivity.kt", "microphone answered: start MCP again", r''' else status.text = "Without that permission, the server can't start a hotspot. Connect to Wi-Fi instead, or tap Start to be asked again." + } + }''', r''' else status.text = "Without that permission, the server can't start a hotspot. Connect to Wi-Fi instead, or tap Start to be asked again." + } + // Allowed or refused: MCP control starts again, with or without the microphone type, and its line says which. + if (requestCode == REQUEST_MCP_MIC) McpService.start(this) + }''') + +def stop(msg): + print("STOPPED: " + msg) + print("Nothing was changed.") + sys.exit(1) +def sha(b): return hashlib.sha256(b).hexdigest() +def bal(t): return (t.count("{") - t.count("}"), t.count("(") - t.count(")")) + +GUARDS = {MANIFEST: "FOREGROUND_SERVICE_MICROPHONE", SRC + "McpService.kt": "micType", SRC + "MainActivity.kt": "REQUEST_MCP_MIC"} +files = [] +for p in P: + if p[0] not in files: files.append(p[0]) +raw, out = {}, {} +for f in files: + if not os.path.isfile(f): stop(f + " isn't here.") + with open(f, "rb") as h: raw[f] = h.read() + t = raw[f].decode("utf-8") + if GUARDS[f] in t: stop(f + " already has %s in it. Has this script, or a hand edit, been applied already?" % GUARDS[f]) + for i, (g, what, old, new) in enumerate(P, 1): + if g != f: continue + if old == new: stop("patch %d (%s) changes nothing: the script is wrong." % (i, what)) + n = t.count(old) + if n != 1: stop("patch %d (%s): its text to replace is in %s %d times, not once. Has the file changed?" % (i, what, f, n)) + if bal(old) != bal(new): stop("patch %d (%s) would unbalance { } or ( ): the script is wrong." % (i, what)) + t = t.replace(old, new) + out[f] = t.encode("utf-8") +for i, (f, what, old, new) in enumerate(P, 1): + c = out[f].decode("utf-8").count(new) + if c != 1: stop("patch %d (%s): after patching, its new text is in %s %d times, not once." % (i, what, f, c)) +for f in files: + if bal(raw[f].decode("utf-8")) != bal(out[f].decode("utf-8")): stop(f + ": { } or ( ) would no longer balance as before.") +try: + import xml.etree.ElementTree as ET + ET.fromstring(out[MANIFEST]) +except Exception as e: + stop("the patched manifest isn't valid XML (%s): the script is wrong." % e) +print("The patched manifest is valid XML.") +print("Checks passed: %d patches to %d files." % (len(P), len(files))) + +try: + os.makedirs(os.path.join(bk, "files")) + with open(os.path.join(bk, "replaced.txt"), "w") as h: + for f in files: + dst = os.path.join(bk, "files", f) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as o: o.write(raw[f]) + with open(dst, "rb") as o: + if sha(o.read()) != sha(raw[f]): raise IOError("the backup of %s doesn't match it" % f) + h.write(f + "\n") +except Exception as e: + shutil.rmtree(bk, ignore_errors=True) + stop("couldn't back up: %s." % e) +print("Backed up to %s." % bk) + +try: + for f in files: + tmp = f + ".step-c.tmp" + with open(tmp, "wb") as o: o.write(out[f]) + os.replace(tmp, f) + with open(f, "rb") as o: + if sha(o.read()) != sha(out[f]): raise IOError("%s doesn't read back as written" % f) +except Exception as e: + for f in files: + try: + with open(f, "wb") as o: o.write(raw[f]) + except Exception: print(" COULDN'T PUT BACK %s: its copy is in %s/files" % (f, bk)) + shutil.rmtree(bk, ignore_errors=True) + print("FAILED: %s. Every file was put back as it was." % e) + sys.exit(1) + +with open(sums_path, "a") as h: + for f in files: h.write("step%s %s %s\n" % (step, sha(out[f]), f)) +for f in files: + n = sum(1 for p in P if p[0] == f) + print(" patched %s: %d changes, %d -> %d bytes, sha256 %s..." % (f, n, len(raw[f]), len(out[f]), sha(out[f])[:12])) +for i, (f, what, _, _) in enumerate(P, 1): + print(" %d. %s: %s" % (i, os.path.basename(f), what)) +print("Every file reads back as written.") +PYEOF +RC=$? +[ "$RC" = 0 ] || exit "$RC" + +echo +echo "Backup: $BK Checksums: $SUMS" +echo "Next: a Standard Run, then :app:testDebugUnitTest. Then on the phone: turn MCP control off and on again," +echo "read the message, answer the microphone question, and note the line under the switch." +echo "Paste all of this output, and what you saw, to the agent." +exit 0 +# END OF step-c-4-mic.sh diff --git a/plugins/Share-Your-Apps/server/step-c-5-soundimport.sh b/plugins/Share-Your-Apps/server/step-c-5-soundimport.sh new file mode 100644 index 000000000..cc1f31481 --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-5-soundimport.sh @@ -0,0 +1,338 @@ +#!/bin/sh +# step-c-5-soundimport.sh: step C, script 5 of 6. Adds the new file SoundImport.kt: hearing a share code for an MCP +# client (import_listen), with no screen. Script 6 adds the import_listen tool that uses it. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-5-soundimport.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-5-soundimport.sh" undo +# (deletes SoundImport.kt) +# +# SoundImport.kt follows the import screen's Listen (project B), which stays unchanged: +# listen up to 30 s -> heard: is the owner's phone reachable? -> yes, or no hotspot password: the import starts +# (ImportJob, byMcp) -> else on Android 10+ WifiJoin asks to join the owner's hotspot (a person taps Connect) +# -> Android 9, or no tap: "person needed" (a person uses Listen on the import screen). Never the password. +# +# Before writing it checks: this file ends with its END line; script 4 has run; this one hasn't; SoundImport.kt +# doesn't exist yet; every function it calls is in the project's files; its { } and ( ) balance; it ends with its +# own END line. Then it writes through a temporary file, reads it back and compares SHA-256. Backup record in +# step-c-backup/5; checksums in step-c-checksums.txt. Plain sh, no bash; needs Python. + +set -u +NAME="step-c-5-soundimport.sh" +STEP=5 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + while IFS= read -r f; do + [ -n "$f" ] || continue + if [ -e "$f" ]; then rm -f "$f" && echo " removed: $f"; fi + done < "$BK/added.txt" + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 +} + +case "${1:-}" in + "") ;; + undo) + if [ -d "step-c-backup/6" ]; then + echo "STOPPED: step C script 6 has run since this one. Undo it first (its script, with undo). Nothing was changed." + exit 1 + fi + echo "Undoing $NAME..." + undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +[ -d "step-c-backup/4" ] || fail "step-c-4-mic.sh hasn't run yet (step-c-backup/4 isn't here). Run it first." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || fail "neither python3 nor python was found." + +"$PY" - "$STEP" "$BK" "$SUMS" <<'PYEOF' +import hashlib, os, shutil, sys +step, bk, sums_path = sys.argv[1], sys.argv[2], sys.argv[3] +SRC = "app/src/main/java/org/appdevforall/shareyourapps/server/" +TARGET = SRC + "SoundImport.kt" + +KT = r'''package org.appdevforall.shareyourapps.server + +import android.content.Context +import android.os.Handler +import android.os.Looper +import java.net.InetSocketAddress +import kotlin.concurrent.thread +import org.json.JSONObject + +/** + * Hearing a share code for an MCP client (import_listen), with no screen: the same steps as the import screen's + * Listen (project B), which this leaves unchanged. Main process only; the listener's and WifiJoin's answers run on + * the main thread. + * + * 1. Listens for up to 30 s (SoundIo.MAX_MS), while McpService runs with the microphone type. + * 2. Heard: can this phone reach the owner's phone on its Wi-Fi (WifiJoin.reachable, about 2 s)? + * 3. Reachable, or the tones carry no hotspot password: the import starts, as import_start would (byMcp). + * 4. Otherwise, on Android 10 and later, WifiJoin asks Android to join the owner's own hotspot: a person taps + * Connect within 30 s. Joined: the import starts on that network, which is let go once the import ends. + * 5. Android 9, or no tap: a person is needed, who uses Listen on the import screen; it shows the hotspot's name + * and password for joining by hand. + * + * The hotspot's password is never put in the state, the client's answers or the log. + */ +object SoundImport { + enum class Phase { IDLE, LISTENING, CHECKING, JOINING, IMPORT_STARTED, NOTHING_HEARD, PERSON_NEEDED, FAILED, STOPPED } + + /** What import_listen reports. [ssid]: the owner's network name, from the tones; never its password. */ + class State(val phase: Phase, val message: String, val secondsLeft: Long = 0, val signal: Double = 0.0, + val code: String? = null, val ssid: String? = null) + + private val main = Handler(Looper.getMainLooper()) + @Volatile var state = State(Phase.IDLE, "Not listening."); private set + @Volatile private var listener: SoundIo.Listener? = null + /** Counts listens started and stopped, so a late answer about an older one is ignored. */ + @Volatile private var run = 0 + + /** Listening, checking the network, or waiting for a person's Connect tap. */ + val busy: Boolean get() = state.phase in setOf(Phase.LISTENING, Phase.CHECKING, Phase.JOINING) + + /** + * Starts listening. Returns null once started, or why not: "person needed: ..." when only a person can fix it. + * The caller checks first that this phone isn't serving, as import_start does. + */ + @Synchronized + fun start(context: Context, phoneName: String): String? { + val app = context.applicationContext + if (!SoundIo.canListen(app)) { + SoundLog.write(app, SoundLog.microphoneRefused()) + return "person needed: the app isn't allowed to use the microphone. Ask a person to open Share Your Apps Server, " + + "turn MCP control off and on again, and allow the microphone." + } + if (busy) return "Already listening: follow it with import_status, or stop it with import_cancel." + if (ImportJob.snapshot.busy) return "An import is already running. Follow it with import_status, or end it with import_cancel." + val r = ++run + var strongest = 0.0 + var loudest = SoundDsp.METER_FLOOR_DB + state = State(Phase.LISTENING, "Listening. Ask the owner to tap Play sound on their share screen.", SoundIo.MAX_MS / 1000) + SoundLog.write(app, "listening for a share code, for an MCP client") + listener = SoundIo.Listener(app, + level = { v -> + if (r == run) { + strongest = maxOf(strongest, v.signal) + loudest = maxOf(loudest, v.db) + state = State(Phase.LISTENING, hearing(v.signal), (v.msLeft + 999) / 1000, v.signal) + } + }, + heard = { p, how -> if (r == run) { listener = null; onHeard(app, r, p, how, phoneName) } }, + ended = { end, why -> + if (r == run) { + listener = null + val seconds = SoundIo.MAX_MS / 1000 + when (end) { + SoundIo.End.NOTHING_HEARD -> { + SoundLog.write(app, SoundLog.nothingHeard(seconds, strongest)) + // Only silence: Android may be blocking the microphone while the app is off screen. + state = if (loudest <= SoundDsp.METER_FLOOR_DB) + State(Phase.PERSON_NEEDED, "The microphone heard only silence for $seconds s. Android may block it while the app " + + "is off screen: ask a person to open Share Your Apps Server, then call import_listen again.") + else State(Phase.NOTHING_HEARD, "Didn't hear the code in $seconds s. The phones may need to be closer, or the owner's " + + "media volume higher. Call import_listen again while the owner's phone plays its sound.") + } + SoundIo.End.NO_MICROPHONE -> { + SoundLog.write(app, SoundLog.listenFailed(why)) + state = State(Phase.PERSON_NEEDED, "$why Ask a person to open Share Your Apps Server, then call import_listen again.") + } + else -> { + SoundLog.write(app, SoundLog.listenFailed(why)) + state = State(Phase.FAILED, why) + } + } + } + }, + ).start() + return null + } + + private fun hearing(signal: Double) = "Listening. " + when { + signal < 0.15 -> "Nothing heard yet." + signal < SoundDecoder.THRESHOLD -> "Hearing something faint: the phones may need to be closer." + else -> "Hearing the tones." + } + + /** A code was heard: first, whether this phone can already reach the owner's phone, off the main thread. */ + private fun onHeard(app: Context, r: Int, p: SoundPayload, how: String, name: String) { + SoundLog.write(app, SoundLog.heard(p, how)) // never the password + val address = p.address?.let { InetSocketAddress(it, p.port) } + state = State(Phase.CHECKING, "Heard the code ${ShareCodes.display(p.code)}. Checking whether this phone can reach the owner's phone.", + code = p.code, ssid = p.ssid) + thread(name = "sound-reach-mcp") { + val ok = WifiJoin.reachable(app, p.code, address) + main.post { if (r == run) afterReach(app, r, p, name, address, ok) } + } + } + + /** As the import screen does: import at once; or join the owner's own hotspot first; or a person is needed. */ + private fun afterReach(app: Context, r: Int, p: SoundPayload, name: String, address: InetSocketAddress?, reachable: Boolean) { + val ssid = p.ssid + val password = p.password + if (reachable || ssid == null || password == null) { + val hint = if (!reachable && ssid != null) " The owner's phone is on the Wi-Fi network $ssid: if the import can't find it, " + + "a person must join that network, then call import_start with the code." else "" + startImport(app, p, name, address, null, hint) + return + } + if (!WifiJoin.canJoin) { + SoundLog.write(app, "the owner's hotspot $ssid must be joined by hand (Android 9)") + state = byHand(p, "This phone runs Android 9, which can't join the owner's hotspot $ssid by itself.") + return + } + val tapSeconds = WifiJoin.CONNECT_TAP_MS / 1000 + SoundLog.write(app, "joining the owner's hotspot $ssid, for an MCP client") + state = State(Phase.JOINING, "Joining the owner's hotspot $ssid. A person must tap Connect when Android asks, within $tapSeconds s.", + code = p.code, ssid = ssid) + WifiJoin.join(app, ssid, password) { network -> + if (r != run) return@join + if (network != null) { + SoundLog.write(app, "joined the owner's hotspot $ssid") + startImport(app, p, name, address, network, "") + // After start: the import is busy by now, so the hotspot is let go once it ends; at once if it didn't start. + if (ImportJob.snapshot.busy) WifiJoin.holdUntilImportEnds() else WifiJoin.release() + } else { + SoundLog.write(app, "didn't join the owner's hotspot $ssid: no Connect tap within $tapSeconds s, or refused") + state = byHand(p, "Nobody tapped Connect within $tapSeconds s, so this phone didn't join the owner's hotspot $ssid.") + } + } + } + + /** A person must join the owner's hotspot. The client never gets its password: the import screen shows it. */ + private fun byHand(p: SoundPayload, why: String) = State(Phase.PERSON_NEEDED, "$why A person must open Share Your Apps Server, " + + "tap Import a store, then Listen while the owner's phone plays its sound again, and follow the screen: it joins the " + + "hotspot, or shows its name and password.", code = p.code, ssid = p.ssid) + + private fun startImport(app: Context, p: SoundPayload, name: String, address: InetSocketAddress?, network: android.net.Network?, hint: String) { + val why = ImportJob.start(app, p.code, name, address, network = network, byMcp = true) + state = when { + why == null -> State(Phase.IMPORT_STARTED, "Heard the code ${ShareCodes.display(p.code)}, and the import has started: " + + "follow it with import_status.$hint", code = p.code, ssid = p.ssid) + why.startsWith("person needed: ") -> State(Phase.PERSON_NEEDED, why.removePrefix("person needed: "), code = p.code, ssid = p.ssid) + else -> State(Phase.FAILED, why, code = p.code, ssid = p.ssid) + } + } + + /** Stops listening, checking or joining; an import already started carries on (import_cancel ends that). */ + @Synchronized + fun stop(context: Context): Boolean { + if (!busy) return false + val joining = state.phase == Phase.JOINING + run++ + listener?.stop(); listener = null + // A join still being asked for is let go, on the main thread, where WifiJoin runs. + if (joining) main.post { WifiJoin.release() } + SoundLog.write(context.applicationContext, SoundLog.stopped() + ": by an MCP client") + state = State(Phase.STOPPED, "Stopped.") + return true + } + + /** import_listen's and import_status's report. Never the hotspot's password. */ + fun status(): JSONObject { + val s = state + val out = JSONObject().put("phase", s.phase.name.lowercase()).put("message", s.message) + if (s.phase == Phase.LISTENING) out.put("seconds_left", s.secondsLeft).put("hearing", when { + s.signal < 0.15 -> "nothing" + s.signal < SoundDecoder.THRESHOLD -> "faint" + else -> "tones" + }) + s.code?.let { out.put("code", ShareCodes.display(it)) } + s.ssid?.let { out.put("owner_network", it) } + if (s.phase == Phase.PERSON_NEEDED) out.put("person_needed", s.message) + return out + } +} +// END OF SoundImport.kt +''' + +# What SoundImport.kt calls, which must be in the project as it is now: (file, text), "*" = any file in SRC. +NEEDS = [ + ("SoundIo.kt", "fun canListen("), ("SoundIo.kt", "class Listener("), ("SoundIo.kt", "const val MAX_MS"), + ("SoundIo.kt", "enum class End { STOPPED, NOTHING_HEARD, NO_MICROPHONE, FAILED }"), + ("WifiJoin.kt", "fun reachable(context: Context, code: String, address: InetSocketAddress?)"), + ("WifiJoin.kt", "fun join(context: Context, ssid: String, password: String, done: (Network?) -> Unit)"), + ("WifiJoin.kt", "fun holdUntilImportEnds()"), ("WifiJoin.kt", "fun release()"), + ("WifiJoin.kt", "val canJoin"), ("WifiJoin.kt", "const val CONNECT_TAP_MS"), + ("ImportJob.kt", "network: android.net.Network? = null, byMcp: Boolean = false): String?"), + ("SoundLog.kt", "fun heard("), ("SoundLog.kt", "fun nothingHeard("), ("SoundLog.kt", "fun microphoneRefused("), + ("SoundLog.kt", "fun listenFailed("), ("SoundLog.kt", "fun stopped("), ("SoundLog.kt", "fun write(context: Context, message: String)"), + ("SoundDsp.kt", "METER_FLOOR_DB"), ("SoundDecoder.kt", "THRESHOLD"), + ("*", "fun display("), +] + +def stop(msg): + print("STOPPED: " + msg) + print("Nothing was changed.") + sys.exit(1) +def sha(b): return hashlib.sha256(b).hexdigest() +def bal(t): return (t.count("{") - t.count("}"), t.count("(") - t.count(")")) +def read(p): + with open(p, encoding="utf-8") as h: return h.read() + +if os.path.exists(TARGET): stop(TARGET + " already exists. Has this script, or a hand edit, been applied already?") +for f, needle in NEEDS: + if f == "*": + found = any(needle in read(SRC + n) for n in os.listdir(SRC) if n.endswith(".kt")) + else: + found = os.path.isfile(SRC + f) and needle in read(SRC + f) + if not found: stop("%s doesn't have \"%s\", which SoundImport.kt calls: the script is wrong, or the file changed." % (f, needle)) +print("Every function SoundImport.kt calls is in the project (%d checked)." % len(NEEDS)) +if not KT.startswith("package org.appdevforall.shareyourapps.server\n"): stop("SoundImport.kt's text doesn't start with its package line.") +if not KT.endswith("}\n// END OF SoundImport.kt\n"): stop("SoundImport.kt's text is cut off: it doesn't end with its END line.") +if bal(KT) != (0, 0): stop("SoundImport.kt's { } or ( ) don't balance %s: the script is wrong." % (bal(KT),)) +data = KT.encode("utf-8") +print("Checks passed: SoundImport.kt, %d lines, %d bytes." % (KT.count("\n"), len(data))) + +try: + os.makedirs(bk) + with open(os.path.join(bk, "added.txt"), "w") as h: h.write(TARGET + "\n") + tmp = TARGET + ".step-c.tmp" + with open(tmp, "wb") as o: o.write(data) + os.replace(tmp, TARGET) + with open(TARGET, "rb") as o: + if sha(o.read()) != sha(data): raise IOError("%s doesn't read back as written" % TARGET) +except Exception as e: + for p in (TARGET, TARGET + ".step-c.tmp"): + try: os.remove(p) + except Exception: pass + shutil.rmtree(bk, ignore_errors=True) + print("FAILED: %s. Nothing was left behind." % e) + sys.exit(1) + +with open(sums_path, "a") as h: h.write("step%s %s %s\n" % (step, sha(data), TARGET)) +print(" added %s: %d bytes, sha256 %s..." % (TARGET, len(data), sha(data)[:12])) +print("It reads back as written.") +PYEOF +RC=$? +[ "$RC" = 0 ] || exit "$RC" + +echo +echo "Record: $BK Checksums: $SUMS" +echo "Next: a Standard Run (nothing uses SoundImport yet: this checks it compiles). Script 6 adds import_listen." +echo "Paste all of this output, and the build result, to the agent." +exit 0 +# END OF step-c-5-soundimport.sh diff --git a/plugins/Share-Your-Apps/server/step-c-6-tools.sh b/plugins/Share-Your-Apps/server/step-c-6-tools.sh new file mode 100644 index 000000000..120504a25 --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-6-tools.sh @@ -0,0 +1,515 @@ +#!/bin/sh +# step-c-6-tools.sh: step C, script 6 of 6. The MCP sound tools, share_play_sound and import_listen, and the help. +# +# Run: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-6-tools.sh" +# Undo: sh "/storage/emulated/0/CodeOnTheGoProjects/Share Your Apps Server Combined/step-c-6-tools.sh" undo +# +# New file McpSoundTools.kt: +# share_play_sound: plays the open share's code as tones, as the share screen's Play sound does; stops by itself +# after 30 s or once the share moves on; stop true stops it sooner. Its "played" line goes to the server's log +# over a connection of its own (decision D6 a): ShareControl still only opens, polls and closes a share. +# import_listen: listens through SoundImport (script 5); returns at once; stop true stops it. +# McpTools.kt: +# 1. The tool list gets both tools; the app's context is kept for import_status. +# 2. import_start is refused while import_listen is listening or joining. +# 3. import_status: on_owners_network checked now (the stale import result fix), and copy_on_phone. +# 4. Its note uses the network as it is now. +# 5. import_status gets a listen part once import_listen has been used. +# 6. import_status's wait_seconds also ends when the listen part's phase changes. +# 7. import_cancel stops listening too. +# McpService.kt: +# 8. Turning MCP control off stops its tones and its listening. +# help/build_help_db.py (still exactly two server.mcp tooltips, as build_help_db.sh checks): +# 9. mcp.html: allow the microphone when turning MCP control on. 10. mcp.html: a Sound section. +# 11. The server.mcp tooltip mentions sound. +# +# Same checks as scripts 2 to 5, plus: build_help_db.py must still compile as Python. Backup in step-c-backup/6. +# Plain sh, no bash; needs Python. + +set -u +NAME="step-c-6-tools.sh" +STEP=6 + +# ---- Not cut off: the last line of this file must be its END line. +if [ "$(tail -n 1 "$0" 2>/dev/null)" != "# END OF $NAME" ]; then + echo "STOPPED: $0 is incomplete: its last line isn't \"# END OF $NAME\"." + echo "Nothing was changed. Ask the agent to write it again." + exit 2 +fi + +HERE="$(cd "$(dirname "$0")" && pwd)" || { echo "STOPPED: couldn't find this script's folder. Nothing was changed."; exit 2; } +cd "$HERE" || exit 2 + +fail() { echo "STOPPED: $*"; echo "Nothing was changed."; exit 1; } + +BK="step-c-backup/$STEP" +SUMS="step-c-checksums.txt" + +undo() { + [ -d "$BK" ] || { echo "Nothing to undo: $BK doesn't exist."; return 1; } + UNDO_OK=yes + while IFS= read -r f; do + [ -n "$f" ] || continue + if cp "$BK/files/$f" "$f"; then echo " put back: $f" + else echo " COULDN'T PUT BACK: $f (its copy is in $BK/files)"; UNDO_OK=no; fi + done < "$BK/replaced.txt" + while IFS= read -r f; do + [ -n "$f" ] || continue + if [ -e "$f" ]; then rm -f "$f" && echo " removed: $f"; fi + done < "$BK/added.txt" + if [ -f "$SUMS" ]; then grep -v "^step$STEP " "$SUMS" > "$SUMS.tmp"; mv "$SUMS.tmp" "$SUMS"; fi + if [ "$UNDO_OK" = yes ]; then + mv "$BK" "$BK.undone-$(date +%Y%m%d-%H%M%S)" + echo "Undone." + return 0 + fi + echo "NOT fully undone: see the lines above. The backup stays in $BK." + return 1 +} + +case "${1:-}" in + "") ;; + undo) echo "Undoing $NAME..."; undo; exit $? ;; + *) fail "unknown option \"$1\". Run it with nothing, or with undo." ;; +esac + +[ -d "step-c-backup/5" ] || fail "step-c-5-soundimport.sh hasn't run yet (step-c-backup/5 isn't here). Run it first." +[ -e "$BK" ] && fail "this script has already run ($BK exists). To run it again, undo it first: sh $NAME undo" + +PY="" +if command -v python3 >/dev/null 2>&1; then PY=python3 +elif command -v python >/dev/null 2>&1; then PY=python +fi +[ -n "$PY" ] || fail "neither python3 nor python was found." + +"$PY" - "$STEP" "$BK" "$SUMS" <<'PYEOF' +import hashlib, os, shutil, sys +step, bk, sums_path = sys.argv[1], sys.argv[2], sys.argv[3] +SRC = "app/src/main/java/org/appdevforall/shareyourapps/server/" +TOOLS = SRC + "McpTools.kt" +SERVICE = SRC + "McpService.kt" +HELP = "help/build_help_db.py" +NEWF = SRC + "McpSoundTools.kt" +P = [] +def patch(f, what, old, new): P.append((f, what, old, new)) + +patch(TOOLS, "tool list gets both tools; the app's context kept", r''' private const val DEFAULT_START_WAIT_S = 10 + + fun all(context: Context): List { + val app = context.applicationContext + return listOf(serverStatus(app), storeInfo(app), serverStart(app), serverStop(app), + shareStart(app), shareStatus(app), shareStop(app), + importStartTool(app), importStatusTool(app), importCancelTool(app)) + }''', r''' private const val DEFAULT_START_WAIT_S = 10 + /** The app's context, kept by [all], so import_status can check the network now, not when the import ended. */ + @Volatile private var appCtx: Context? = null + + fun all(context: Context): List { + val app = context.applicationContext + appCtx = app + // Step C's sound tools, share_play_sound and import_listen, are in McpSoundTools. + return listOf(serverStatus(app), storeInfo(app), serverStart(app), serverStop(app), + shareStart(app), shareStatus(app), shareStop(app), + importStartTool(app), importStatusTool(app), importCancelTool(app)) + McpSoundTools.all(app) + }''') + +patch(TOOLS, "import_start refused while listening", r''' val why = ImportJob.start(ctx, code, name, address, byMcp = true)''', +r''' if (SoundImport.busy) throw McpToolError("import_listen is still listening or joining. Wait for it, or stop it with import_cancel.", + JSONObject().put("state", "listening").put("listen", SoundImport.status())) + val why = ImportJob.start(ctx, code, name, address, byMcp = true)''') + +patch(TOOLS, "import_status: owner's network now, copy_on_phone", r''' out.put("expires", s.expires?.toString() ?: JSONObject.NULL).put("on_owners_network", s.onOwnersNetwork)''', +r''' // Checked now, not when the import ended: Wi-Fi may have been turned off or changed since. And whether the + // copy is still on this phone: it may have been removed, expired or replaced since. + val owners = appCtx?.let { ImportJob.onOwnersNetworkNow(it) } ?: s.onOwnersNetwork + val still = appCtx?.let { c -> runCatching { ImportJob.currentCopy(c)?.storeId == s.storeId }.getOrDefault(true) } ?: true + out.put("expires", s.expires?.toString() ?: JSONObject.NULL).put("on_owners_network", owners).put("copy_on_phone", still)''') + +patch(TOOLS, "import_status note uses the network now", r''' if (s.onOwnersNetwork) out.put("note", ''', r''' if (owners) out.put("note", ''') + +patch(TOOLS, "import_status listen part", r''' .put("question", JSONObject().put("title", q.title).put("message", q.message)) + } + return out''', r''' .put("question", JSONObject().put("title", q.title).put("message", q.message)) + } + // import_listen's part, once it has been used: listening, checking, joining, import_started, nothing_heard ... + if (SoundImport.state.phase != SoundImport.Phase.IDLE) out.put("listen", SoundImport.status()) + return out''') + +patch(TOOLS, "wait_seconds also ends on a listen change", r''' val key = { ImportJob.snapshot.phase to ImportJob.question }''', +r''' // import_listen's phase counts too: the loop below looks every 250 ms. + val key = { Triple(ImportJob.snapshot.phase, ImportJob.question, SoundImport.state.phase) }''') + +patch(TOOLS, "import_cancel stops listening too", r''' ) { _ -> + if (!ImportJob.snapshot.busy) { + importStatus().put("cancelled", false).put("note", "No import is running.") + } else {''', r''' ) { _ -> + // Listening, checking or joining for import_listen stops too; an import it already started is cancelled below. + val stoppedListening = SoundImport.stop(ctx) + if (!ImportJob.snapshot.busy) { + if (stoppedListening) importStatus().put("cancelled", true).put("note", "Stopped listening. No import had started.") + else importStatus().put("cancelled", false).put("note", "No import is running.") + } else {''') + +patch(SERVICE, "turning MCP off stops its tones and listening", r''' thread(name = "mcp-share-shutdown") { ShareControl.shutdown() }''', +r''' thread(name = "mcp-share-shutdown") { ShareControl.shutdown() } + // Tones an MCP client started, and listening for one, end with MCP control. + McpSoundTools.stopPlaying() + SoundImport.stop(this)''') + +patch(HELP, "mcp.html: allow the microphone", r'''

Turn on MCP control in the Server panel. The app first says what it allows; tap Turn on. A notification shows while''', +r'''

Turn on MCP control in the Server panel. The app first says what it allows; tap Turn on, then allow the microphone +if Android asks. A notification shows while''') + +patch(HELP, "mcp.html: Sound section", r'''

The token

''', r'''

Sound

+

An app can also use sound instead of a code. On the sharing phone, it plays the share's code as tones, as Play sound does, +for up to 30 seconds. On the importing phone, it listens for them, as Listen does, for up to 30 seconds, and starts the import +once it hears the code. Android shows its microphone indicator while it listens. If the sharing phone serves on its own hotspot, +Android asks to join it: tap Connect. Apps are never told the hotspot's password.

+

The line under the switch says if the microphone isn't allowed, or works only once the app is opened, as after the phone +restarts. Without it, a person uses Listen on the import screen instead.

+

The token

''') + +patch(HELP, "server.mcp tooltip mentions sound", r''' "They can't change the store or approve a copy: you still tap Allow. Other devices on the network can't reach it.

"''', +r''' "They can't change the store or approve a copy: you still tap Allow. Other devices on the network can't reach it.

" + "

Apps can also play the share code as sound, and use the microphone to hear another phone's, only while they ask it to.

"''') + +KT = r'''package org.appdevforall.shareyourapps.server + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Message +import android.os.Messenger +import kotlin.concurrent.thread +import org.json.JSONObject + +/** + * Step C's sound tools for MCP clients. share_play_sound: the sharing phone plays the open share's code as tones, as + * the share screen's Play sound does. import_listen: the importing phone listens for them, through [SoundImport]. + * Kept apart from [McpTools] and [ShareControl]: ShareControl may only open, poll and close a share, so the "played" + * line goes to the server's log over a short connection of its own here. The hotspot's password is never reported. + */ +object McpSoundTools { + private val lock = Any() + @Volatile private var player: SoundIo.Player? = null + /** Counts players started and stopped, so a finished player's callback, or its watcher, can't touch a newer one. */ + @Volatile private var soundRun = 0 + @Volatile private var playingCode: String? = null + + fun all(context: Context): List { + val app = context.applicationContext + return listOf(sharePlaySound(app), importListen(app)) + } + + private fun boolArg(args: JSONObject, key: String): Boolean = when (val v = args.opt(key)) { + null, JSONObject.NULL -> false + is Boolean -> v + else -> throw McpToolError("$key must be true or false.") + } + + private fun personNeeded(what: String) = + McpToolError("A person is needed: $what", JSONObject().put("state", "person_needed").put("person_needed", what)) + + // ---------------------------------------------------------------- share_play_sound + + private fun sharePlaySound(ctx: Context) = McpTool( + name = "share_play_sound", + title = "Play the share code as sound", + description = "Plays the open share's code as a short run of tones through this phone's speaker, as the share screen's Play sound " + + "does, so a phone nearby can hear it instead of scanning or typing it: import_listen there, or Listen on its import screen. " + + "Needs a share waiting for a phone: call share_start first. Repeats for up to 30 seconds, and stops by itself once a phone " + + "connects or the share ends; stop true stops it sooner. On this phone's own hotspot the tones also carry the hotspot's " + + "name and password, so anyone close enough to hear them gets them. The password is never in this tool's answer.", + inputSchema = JSONObject().put("type", "object").put("properties", JSONObject() + .put("stop", JSONObject().put("type", "boolean").put("description", "true: stop the tones now."))) + .put("additionalProperties", false), + readOnly = false, + ) { args -> if (boolArg(args, "stop")) stopTool() else play(ctx) } + + private fun play(ctx: Context): JSONObject { + if (ServerStatus.url == null) throw McpToolError("The server isn't serving, so there's no share to play. Call server_start, then share_start.", + JSONObject().put("state", "not_serving")) + val share = ShareControl.status(ctx, 0) + val code = share.optString("code", "") + val link = share.optString("link", "") + if (share.optString("state") != "waiting_for_phone" || code.isEmpty()) + throw McpToolError("Sound only works while a share is waiting for a phone. Call share_start first.", + JSONObject().put("state", "no_share_waiting").put("share", share)) + synchronized(lock) { + if (player != null && playingCode == code) return JSONObject().put("playing", true).put("already_playing", true).put("code", code) + } + val payload = payload(code, link) ?: throw McpToolError("Couldn't turn this share's code into sound.") + val low = SoundIo.volumeLow(ctx) + val r = synchronized(lock) { + player?.stop() + val n = ++soundRun + playingCode = code + lateinit var p: SoundIo.Player + p = SoundIo.Player(payload.encode()) { error -> + synchronized(lock) { if (n == soundRun) { player = null; playingCode = null } } + log(ctx, SoundLog.played(p.rounds, p.stoppedEarly, low, payload.ownHotspot, error) + ", for an MCP client") + } + player = p.start() + n + } + watch(ctx, r, code) + val withHotspot = payload.ssid != null && payload.password != null + val out = JSONObject().put("playing", true).put("already_playing", false).put("code", code) + .put("seconds", SoundIo.MAX_MS / 1000).put("own_hotspot", payload.ownHotspot) + .put("carries", if (withHotspot) "the code, the server's address, and this phone's hotspot name and password" else "the code and the server's address") + .put("next", "On the other phone, call import_listen, or tap Listen on its import screen. Follow this share with share_status.") + if (low) out.put("warning", "The media volume is low: the other phone may not hear the tones. A person can turn it up.") + return out + } + + private fun stopTool(): JSONObject { + val was = stopPlaying() + val out = JSONObject().put("playing", false).put("stopped", was) + if (!was) out.put("note", "No sound was playing.") + return out + } + + /** Stops the tones, if any are playing; their "played" line is still logged. Also called when MCP control is turned off. */ + fun stopPlaying(): Boolean { + synchronized(lock) { + val p = player ?: return false + soundRun++ + p.stop(); player = null; playingCode = null + return true + } + } + + /** Once a second: the tones stop when the share leaves waiting_for_phone, the code changes, or the server stops. */ + private fun watch(ctx: Context, r: Int, code: String) { + thread(name = "sound-share-watch", isDaemon = true) { + while (true) { + try { Thread.sleep(1000) } catch (e: InterruptedException) { return@thread } + if (r != soundRun || player == null) return@thread + val s = try { ShareControl.status(ctx, 0) } catch (e: Exception) { null } + val movedOn = s != null && (s.optString("state") != "waiting_for_phone" || s.optString("code") != code) + if (movedOn || ServerStatus.url == null) { + synchronized(lock) { if (r == soundRun) { soundRun++; player?.stop(); player = null; playingCode = null } } + return@thread + } + } + } + } + + /** + * What the tones carry, as on the share screen: the code and the server's address from the share link; on this + * phone's own hotspot, also its name and password. On other Wi-Fi, neither (Hotspot.info is null there). + */ + private fun payload(code: String, link: String): SoundPayload? { + val normalized = ShareCodes.normalize(code) ?: return null + val parsed = ShareLink.parse(link) + val address = parsed?.let { try { java.net.InetAddress.getByName(it.first) as? java.net.Inet4Address } catch (e: Exception) { null } } + val port = if (address != null && parsed != null) parsed.second else 0 + val hotspot = Hotspot.info + fun fits(s: String) = s.isNotEmpty() && s.toByteArray(Charsets.UTF_8).size <= SoundPayload.MAX_FIELD + val ssid = hotspot?.ssid?.takeIf { it != "?" && fits(it) } + val password = hotspot?.password?.takeIf { ssid != null && fits(it) } + return try { SoundPayload(normalized, if (port > 0) address else null, port, hotspot != null, ssid, password) } + catch (e: IllegalArgumentException) { null } + } + + /** The "played" line: to the server's log while it serves (its process owns the file), else here. */ + private fun log(ctx: Context, message: String) { + val app = ctx.applicationContext + if (ServerStatus.url == null) { SoundLog.write(app, message); return } + val line = SoundLog.line(message) + android.util.Log.i("ShareYourAppsSound", line) + Handler(Looper.getMainLooper()).post { LogOnce(app, line).send() } + } + + /** Binds the server process without starting it, sends one log line, and lets go; gives up after 3 s. */ + private class LogOnce(private val app: Context, private val line: String) : ServiceConnection { + private var done = false + fun send() { + val bound = try { app.bindService(Intent(app, ServerService::class.java), this, 0) } catch (e: Exception) { false } + if (!bound) finish() else Handler(Looper.getMainLooper()).postDelayed({ finish() }, 3000) + } + override fun onServiceConnected(name: ComponentName, service: IBinder) { + try { Messenger(service).send(Message.obtain(null, Ipc.MSG_LOG).apply { data = Bundle().apply { putString(Ipc.KEY_LINE, line) } }) } + catch (e: Exception) { } + finish() + } + override fun onServiceDisconnected(name: ComponentName) { } + private fun finish() { + if (done) return + done = true + try { app.unbindService(this) } catch (e: Exception) { } + } + } + + // ---------------------------------------------------------------- import_listen + + private fun importListen(ctx: Context) = McpTool( + name = "import_listen", + title = "Listen for a share code", + description = "Listens with this phone's microphone, for up to 30 seconds, for the share code another phone plays as sound: " + + "share_play_sound there, or Play sound on its share screen. Once it hears the code, the import starts, as import_start would. " + + "Returns at once: follow it with import_status, whose listen part is one of listening, checking, joining, import_started, " + + "nothing_heard, person_needed, failed or stopped. If the other phone serves on its own hotspot, Android asks a person here " + + "to tap Connect to join it. The hotspot's password is never reported. stop true stops listening; import_cancel does too. " + + "Refused while this phone is serving, starting or paused: call server_stop first. Refused while an import is running.", + inputSchema = JSONObject().put("type", "object").put("properties", JSONObject() + .put("phone_name", JSONObject().put("type", "string").put("maxLength", 40) + .put("description", "The name the other phone's owner sees, at most 40 characters. Default: this phone's name.")) + .put("stop", JSONObject().put("type", "boolean").put("description", "true: stop listening now."))) + .put("additionalProperties", false), + readOnly = false, + ) { args -> if (boolArg(args, "stop")) stopListening(ctx) else listen(ctx, args) } + + private fun stopListening(ctx: Context): JSONObject { + val was = SoundImport.stop(ctx) + val out = SoundImport.status().put("stopped", was) + if (!was) out.put("note", "Nothing was listening.") + return out + } + + private fun listen(ctx: Context, args: JSONObject): JSONObject { + val name = McpTools.phoneNameArg(args) ?: ImportActivity.defaultPhoneName(ctx) + // As import_start: a phone serving its own store can't import one. Starting and paused count too. + val server = McpTools.stateOf(ServerStatus.text, ServerStatus.url) + if (server == "serving" || server == "starting" || server == "paused") + throw McpToolError("This phone is serving a store, or about to, and can't import one while it does. Stop the server first, with server_stop.", + JSONObject().put("state", "server_running").put("server", McpTools.status(ctx))) + val why = SoundImport.start(ctx, name) + if (why != null) { + if (why.startsWith("person needed: ")) throw personNeeded(why.removePrefix("person needed: ")) + throw McpToolError(why, JSONObject().put("state", if (SoundImport.busy) "listening" else "importing").put("listen", SoundImport.status())) + } + return SoundImport.status().put("phone_name", name) + .put("next", "Ask the owner to play the code: Play sound on their share screen, or share_play_sound on their phone. " + + "Follow with import_status, wait_seconds up to 25: its listen part says what was heard, and the import's own fields follow once it starts.") + } +} +// END OF McpSoundTools.kt +''' + +# What McpSoundTools.kt and the patches call, which must be in the project as it is now. "*" = any .kt file in SRC. +NEEDS = [ + ("*", "class McpTool("), ("*", "class McpToolError("), + ("McpTools.kt", "fun stateOf(text: String, url: String?)"), ("McpTools.kt", "fun status(ctx: Context): JSONObject"), + ("McpTools.kt", "internal fun phoneNameArg(args: JSONObject)"), + ("ShareControl.kt", "fun status(ctx: Context, waitSeconds: Int)"), + ("SoundImport.kt", "fun start(context: Context, phoneName: String)"), ("SoundImport.kt", "fun stop(context: Context): Boolean"), + ("SoundImport.kt", "fun status(): JSONObject"), ("SoundImport.kt", "val busy"), ("SoundImport.kt", "enum class Phase { IDLE"), + ("SoundIo.kt", "class Player("), ("SoundIo.kt", "fun volumeLow("), ("SoundIo.kt", "const val MAX_MS"), + ("SoundPayload.kt", "MAX_FIELD"), ("SoundPayload.kt", "fun encode("), + ("ImportJob.kt", "fun onOwnersNetworkNow("), ("ImportJob.kt", "val storeId: String?"), + ("ImportActivity.kt", "fun defaultPhoneName(context: android.content.Context)"), + ("SoundLog.kt", "fun played("), ("SoundLog.kt", "fun line("), + ("*", "MSG_LOG"), ("*", "KEY_LINE"), ("*", "fun parse("), ("*", "fun normalize("), +] +GUARDS = {TOOLS: "McpSoundTools", SERVICE: "McpSoundTools", HELP: "id=sound>Sound"} + +def stop(msg): + print("STOPPED: " + msg) + print("Nothing was changed.") + sys.exit(1) +def sha(b): return hashlib.sha256(b).hexdigest() +def bal(t): return (t.count("{") - t.count("}"), t.count("(") - t.count(")")) +def read(p): + with open(p, encoding="utf-8") as h: return h.read() + +if os.path.exists(NEWF): stop(NEWF + " already exists. Has this script, or a hand edit, been applied already?") +for f, needle in NEEDS: + if f == "*": found = any(needle in read(SRC + n) for n in os.listdir(SRC) if n.endswith(".kt")) + else: found = os.path.isfile(SRC + f) and needle in read(SRC + f) + if not found: stop("%s doesn't have \"%s\", which this script's code calls: the script is wrong, or the file changed." % (f, needle)) +print("Every function the new code calls is in the project (%d checked)." % len(NEEDS)) + +files = [] +for p in P: + if p[0] not in files: files.append(p[0]) +raw, out = {}, {} +for f in files: + if not os.path.isfile(f): stop(f + " isn't here.") + with open(f, "rb") as h: raw[f] = h.read() + t = raw[f].decode("utf-8") + if GUARDS[f] in t: stop(f + " already has %s in it. Has this script, or a hand edit, been applied already?" % GUARDS[f]) + for i, (g, what, old, new) in enumerate(P, 1): + if g != f: continue + if old == new: stop("patch %d (%s) changes nothing: the script is wrong." % (i, what)) + n = t.count(old) + if n != 1: stop("patch %d (%s): its text to replace is in %s %d times, not once. Has the file changed?" % (i, what, f, n)) + if bal(old) != bal(new): stop("patch %d (%s) would unbalance { } or ( ): the script is wrong." % (i, what)) + t = t.replace(old, new) + out[f] = t.encode("utf-8") +for i, (f, what, old, new) in enumerate(P, 1): + c = out[f].decode("utf-8").count(new) + if c != 1: stop("patch %d (%s): after patching, its new text is in %s %d times, not once." % (i, what, f, c)) +for f in files: + if bal(raw[f].decode("utf-8")) != bal(out[f].decode("utf-8")): stop(f + ": { } or ( ) would no longer balance as before.") +try: + compile(out[HELP].decode("utf-8"), HELP, "exec") +except SyntaxError as e: + stop("the patched %s isn't valid Python (%s): the script is wrong." % (HELP, e)) +print("The patched build_help_db.py compiles as Python.") +if not KT.startswith("package org.appdevforall.shareyourapps.server\n"): stop("McpSoundTools.kt's text doesn't start with its package line.") +if not KT.endswith("}\n// END OF McpSoundTools.kt\n"): stop("McpSoundTools.kt's text is cut off: it doesn't end with its END line.") +if bal(KT) != (0, 0): stop("McpSoundTools.kt's { } or ( ) don't balance %s: the script is wrong." % (bal(KT),)) +data = KT.encode("utf-8") +print("Checks passed: %d patches to %d files, and McpSoundTools.kt (%d lines, %d bytes)." % (len(P), len(files), KT.count("\n"), len(data))) + +try: + os.makedirs(os.path.join(bk, "files")) + with open(os.path.join(bk, "added.txt"), "w") as h: h.write(NEWF + "\n") + with open(os.path.join(bk, "replaced.txt"), "w") as h: + for f in files: + dst = os.path.join(bk, "files", f) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as o: o.write(raw[f]) + with open(dst, "rb") as o: + if sha(o.read()) != sha(raw[f]): raise IOError("the backup of %s doesn't match it" % f) + h.write(f + "\n") +except Exception as e: + shutil.rmtree(bk, ignore_errors=True) + stop("couldn't back up: %s." % e) +print("Backed up to %s." % bk) + +writes = [(f, out[f]) for f in files] + [(NEWF, data)] +try: + for f, b in writes: + tmp = f + ".step-c.tmp" + with open(tmp, "wb") as o: o.write(b) + os.replace(tmp, f) + with open(f, "rb") as o: + if sha(o.read()) != sha(b): raise IOError("%s doesn't read back as written" % f) +except Exception as e: + for f in files: + try: + with open(f, "wb") as o: o.write(raw[f]) + except Exception: print(" COULDN'T PUT BACK %s: its copy is in %s/files" % (f, bk)) + for p in (NEWF, NEWF + ".step-c.tmp"): + try: os.remove(p) + except Exception: pass + shutil.rmtree(bk, ignore_errors=True) + print("FAILED: %s. Every file was put back as it was." % e) + sys.exit(1) + +with open(sums_path, "a") as h: + for f, b in writes: h.write("step%s %s %s\n" % (step, sha(b), f)) +for f in files: + n = sum(1 for p in P if p[0] == f) + print(" patched %s: %d changes, %d -> %d bytes, sha256 %s..." % (f, n, len(raw[f]), len(out[f]), sha(out[f])[:12])) +print(" added %s: %d bytes, sha256 %s..." % (NEWF, len(data), sha(data)[:12])) +for i, (f, what, _, _) in enumerate(P, 1): + print(" %d. %s: %s" % (i, os.path.basename(f), what)) +print("Every file reads back as written.") +PYEOF +RC=$? +[ "$RC" = 0 ] || exit "$RC" + +echo +echo "Backup: $BK Checksums: $SUMS" +echo "Next: sh help/build_help_db.sh (rebuilds the help; it should end with OK), then a Standard Run," +echo "then :app:testDebugUnitTest. Paste all of this output, and the results, to the agent." +exit 0 +# END OF step-c-6-tools.sh diff --git a/plugins/Share-Your-Apps/server/step-c-checksums.txt b/plugins/Share-Your-Apps/server/step-c-checksums.txt new file mode 100644 index 000000000..ea83c57bb --- /dev/null +++ b/plugins/Share-Your-Apps/server/step-c-checksums.txt @@ -0,0 +1,24 @@ +step1 f25cfde7a53a64e08dc62643aff836385a5471e136b64e61e6d21f88263ab33c app/src/main/java/org/appdevforall/shareyourapps/server/SoundPayload.kt +step1 c8abe0be3ab07639b4e9b6b792b85349bddf0cd1faf4b19d814bbb2659183f12 app/src/main/java/org/appdevforall/shareyourapps/server/SoundDsp.kt +step1 14d8dc88a1d5cb2d2510f56ad1dfeb7c5e9556d9e9a2beb600953c2a01c029f6 app/src/main/java/org/appdevforall/shareyourapps/server/SoundModem.kt +step1 5601255ff2e751f0310a24eb150eb70dfb714554c097efed40847ded981772f1 app/src/main/java/org/appdevforall/shareyourapps/server/SoundDecoder.kt +step1 fcaac88f6b5faeec67663eeff9574bc7c87133841a1db6bc9d123307a4c11727 app/src/main/java/org/appdevforall/shareyourapps/server/SoundIo.kt +step1 079c93d685c6460f5a73751c39767afebf61a03a12991574646da083fbd800d6 app/src/main/java/org/appdevforall/shareyourapps/server/SoundLog.kt +step1 c6e7bce0927c4c929e79297fd034f2cee8e272971f9ab518c89ffd4bb57e2014 app/src/main/java/org/appdevforall/shareyourapps/server/WifiJoin.kt +step1 9f8e4fdeaf1ae413f14fb56a064fc04b6e0d0b306749732e774d680f71cbe5ff app/src/main/java/org/appdevforall/shareyourapps/server/ImportActivity.kt +step1 bf0718d9d04a579b09abd6a78c64f48d64f5f24d1751d20f44ce2ca2201abae6 app/src/test/java/SoundPayloadTest.kt +step1 f7f616960f963e799e2786942862551be0dfacc303dfa9f50eea727a2173ddb7 app/src/test/java/SoundModemTest.kt +step1 7fc8c84ada1ea1f42e898cefb406f53229332e937226a72410ebb1ecba95aec3 app/src/test/java/SoundLogTest.kt +step1 bbd1a1df8a92b0f208ec3c46d8f06b3c2f6294d717642543053988e586c87e67 app/src/test/java/SoundLevelTest.kt +step1 149321b2c0601e3db1f0dfc45b7a0a1a31116bac34ae97e34b6aca97320abf51 help/build_help_db.py +step2 fc605dd92c395853d45f79a87156794a72e3ca1332d608ff275c646ef31fc25f app/src/main/java/org/appdevforall/shareyourapps/server/ImportJob.kt +step2 d13757c83728d067e2128265cae7a2e858081aa6b13e6959746bd710c5fd16cb app/src/main/java/org/appdevforall/shareyourapps/server/ImportActivity.kt +step3 ad5347c0dffb5f7ec00201668ebcb1885ce1e9784444470403220f29c1f0cfd9 app/src/main/java/org/appdevforall/shareyourapps/server/ShareActivity.kt +step4 5acaedea5e08eef3e90a131f8cec7869759caaceeff48540eda1de761df07b07 app/src/main/AndroidManifest.xml +step4 3b66991a5a86e451aefe10f873eeccf891e1f3e229ad565e43e1f11cf3cf7b27 app/src/main/java/org/appdevforall/shareyourapps/server/McpService.kt +step4 8dc3a86ce03030381f8ae8fa6c8c96a479e4b95be5bd888c8cc39286f593effe app/src/main/java/org/appdevforall/shareyourapps/server/MainActivity.kt +step5 92f82f3c72d1a34f41f1fd38ef91099b454ad36ba16d90f459c6006b5007ee72 app/src/main/java/org/appdevforall/shareyourapps/server/SoundImport.kt +step6 69ab79cdb4613a3023969f781f3f5d70b1f713c483d3d2f2805e6bd66aee560f app/src/main/java/org/appdevforall/shareyourapps/server/McpTools.kt +step6 59d31d8d7f009e062f59f7549ace417eb29c7397ac218bc865d68994f3aeebd8 app/src/main/java/org/appdevforall/shareyourapps/server/McpService.kt +step6 aa83e018335a64968df9429449e3742b56db22c2e99b0d87975b9f1edb5a4c2b help/build_help_db.py +step6 a41b672a8021815658237936b19c532c158bee649e3a2f37a98cafb3198d5989 app/src/main/java/org/appdevforall/shareyourapps/server/McpSoundTools.kt diff --git a/plugins/Share-Your-Apps/settings.gradle.kts b/plugins/Share-Your-Apps/settings.gradle.kts new file mode 100644 index 000000000..e39e9d555 --- /dev/null +++ b/plugins/Share-Your-Apps/settings.gradle.kts @@ -0,0 +1,30 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath(files("../../libs/plugin-api.jar")) + classpath(files("../../libs/gradle-plugin.jar")) + classpath("com.android.tools.build:gradle:9.3.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.21") + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "share-your-apps" \ No newline at end of file diff --git a/plugins/Share-Your-Apps/share-your-apps.html b/plugins/Share-Your-Apps/share-your-apps.html new file mode 100644 index 000000000..b65edb5a6 --- /dev/null +++ b/plugins/Share-Your-Apps/share-your-apps.html @@ -0,0 +1,124 @@ + + + + + +Share Your Apps + + + + +
+

Share Your Apps

+

Publish your apps and their source to a store on your local network — no internet, no accounts

+
Version 1.0.2 · Author: App Dev For All · Package: org.appdevforall.shareyourapps
+
+ +
+

Executive overview

+

+ Share Your Apps turns the apps you build in Code on the Go into a small web store. + People on the same Wi-Fi network or hotspot open it in their phone's browser and + download each app's APK, its source, or both. Nothing goes through the internet. +

+

+ The store is served by the companion Share Your Apps Server app, + which the plugin carries, installs and starts. +

+
+ +
+

Core functionality

+
    +
  • Manage the catalog in the Share Your Apps tab: the store's name, + description, header image and optional PIN, and products with their project, APK, + pictures, videos and description. Everything is saved as you edit it.
  • +
  • Publish builds a complete new store beside the current one, starts the + server on it, checks every file is served correctly, and only then removes the old one. + If anything fails, the store keeps serving the previous version.
  • +
  • Templates. The store page is rendered with Pebble. Pick one of the + built-in looks, or write your own.
  • +
  • Copy a store to another phone by QR code, a typed code, or sound — + useful when a phone's camera is broken.
  • +
  • Help everywhere. Long-press any heading or button for a tooltip.
  • +
+
+ +
+

Technical architecture

+

Share Your Apps is two parts:

+
    +
  • The plugin runs inside Code on the Go as a tab in the bottom sheet. It keeps the catalog in + the plugin's private folder, renders the store page with Pebble templates, and on Publish writes a + complete new Store_* folder to shared storage: each product's APK and its source as a zip, without + build output, IDE settings or signing files.
  • +
  • Share Your Apps Server is a small Android app the plugin carries and installs. It serves the + store folder over HTTP on Wi-Fi or a hotspot, as a foreground service, with an optional PIN. It also copies a + store to another phone, encrypted, after the owner allows it, and can be controlled by other apps on the phone + through an MCP endpoint on 127.0.0.1 that needs a token.
  • +
+

The plugin starts the server on the new folder, then downloads every file back from it over + 127.0.0.1 and compares sizes and checksums before removing the old folder.

+
+ +
+

Usage

+
    +
  1. Install the plugin and open the Share Your Apps tab.
  2. +
  3. Name your store and add a product for each app you want to share.
  4. +
  5. Tap Publish. The first time, the plugin installs Share Your Apps Server.
  6. +
  7. Share the address the server shows. Anyone on the same network can open it.
  8. +
+
+ +
+

Key benefits

+
    +
  • Works offline. No internet, app store account or computer is needed to hand out an app.
  • +
  • Source and app together. Learners can download what a classmate built and how they built it.
  • +
  • Safe to update. Buyers keep the current store until the new one is checked and serving.
  • +
  • Passes on. A store can be copied to another phone, so it reaches people beyond one Wi-Fi network.
  • +
+
+ +
+ Share Your Apps is free software, licensed under the GNU Affero General Public License v3.0 or later. +
+ + + diff --git a/plugins/Share-Your-Apps/src/main/AndroidManifest.xml b/plugins/Share-Your-Apps/src/main/AndroidManifest.xml new file mode 100644 index 000000000..f5ef9e606 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/index.html b/plugins/Share-Your-Apps/src/main/assets/docs/index.html new file mode 100644 index 000000000..25ce65589 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/index.html @@ -0,0 +1,16 @@ +Share Your Apps

Share Your Apps

+

Share Your Apps shares the apps you build in Code On The Go with people nearby — no internet, and no accounts. You describe your apps +in the Share Your Apps tab, and tap Publish. The plugin builds a small website of them, and the Share Your Apps Server +app serves it over Wi-Fi or a hotspot, where buyers open it in their phone's browser.

+

Topics

+
    +
  • The store: its name, description, header picture and PIN
  • +
  • Products: each app, its project, APK and source, and what buyers read
  • +
  • Pictures and videos, with descriptions and captions
  • +
  • Templates: the store page's look, and Extra JSON
  • +
  • Publishing: what happens, and what its messages mean
  • +
+

Share Your Apps Server has its own help: long-press anything in it.

diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/media.html b/plugins/Share-Your-Apps/src/main/assets/docs/media.html new file mode 100644 index 000000000..4277dc20f --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/media.html @@ -0,0 +1,8 @@ +Pictures and videos

Pictures and videos

+

Adding them

+ Add media adds pictures, videos or sounds. Buyers swipe through them on the product's card. Publishing copies them into the store, and makes a still frame for each video.

+

Describing them

Describe says what an item shows, for visually-impaired people, whose screen readers read it aloud in its place. Say what matters for choosing the app — The chat screen, with two messages — not what kind of item it is. Without one, the page says only which it is: Termux, picture 1 of 3.

+

Captions for a video

In a video's Describe, Choose captions file picks a WebVTT file, ending .vtt: text with the time each line appears. Buyers turn captions on in the video's menu, or its CC button. No captions removes them.

+

Removing one

Remove takes an item out of the product at your next publish, with its description and captions. The file itself stays on your phone.

diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/products.html b/plugins/Share-Your-Apps/src/main/assets/docs/products.html new file mode 100644 index 000000000..abb0b6a22 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/products.html @@ -0,0 +1,11 @@ +Products

Products

+

The list

+ Add product adds one at the end. Move up and Move down set the order buyers see. Remove takes a product out of the store at your next publish.

+

Name

The product's name, as buyers see it. It also names its download files, such as todo-app.apk; a second product of the same name gets todo-app-2.

+

Project

The Code On The Go project the product comes from. Its source can be published as a zip.

+

APK

The installable app buyers download, chosen from the project's builds. The picker marks unsigned builds, which buyers can't install; publishing still goes ahead, and its message notes each one.

+

What to publish

Publish the APK and Publish the source choose what buyers can download. A product with neither, or with no APK chosen, is left out, and the publish message says why.

+

Description

What buyers read about the product, in HTML.

+

Extra JSON

Optional details, as JSON: whatsNew, license, author and website appear on the product's card in the built-in templates. Other keys reach your own template as {{ p.extra.yourKey }}. Text from them is not checked, so use the ready-made p.websiteHref for a link, not a raw value.

diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/publishing.html b/plugins/Share-Your-Apps/src/main/assets/docs/publishing.html new file mode 100644 index 000000000..c2471244a --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/publishing.html @@ -0,0 +1,7 @@ +Publishing

Publishing

+

What Publish does

First it asks you to confirm, saying how many products the store will have, and which are left out. Cancel changes nothing.

  1. Checks that every file it needs exists.
  2. Builds a new copy of the store, beside the old one.
  3. Installs or updates Share Your Apps Server, if needed; Android may ask you to allow it.
  4. Starts the server on the new copy, and checks every file it serves.
+

Until the new store is ready, buyers keep the old one — unless Share Your Apps Server is being updated, which stops it briefly.

+

Its messages

Published … files verified means buyers can use it now. Left out lists products with nothing to download. Notes list things to fix that don't stop the publish, such as unsigned APKs. Couldn't publish means nothing changed: the store still serves its previous version.

diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/store.html b/plugins/Share-Your-Apps/src/main/assets/docs/store.html new file mode 100644 index 000000000..bb570c73d --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/store.html @@ -0,0 +1,8 @@ +The store

The store

+

Store name

The name at the top of the store page, and in its browser tab.

+

Store description

Optional text under the name, in HTML. A tag opened but never closed, or similar, shows a red warning under the field; it doesn't stop you publishing.

+

An optional picture or short video across the top. A video shows a still frame, its poster, and plays when a buyer taps it, so buyers don't each download it on every visit.

+

PIN

Up to 6 digits, which buyers enter before reaching the store; leave it empty for none. It keeps casual visitors out, but isn't real security: the store doesn't use encryption.

diff --git a/plugins/Share-Your-Apps/src/main/assets/docs/templates.html b/plugins/Share-Your-Apps/src/main/assets/docs/templates.html new file mode 100644 index 000000000..b3a8614f4 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/assets/docs/templates.html @@ -0,0 +1,8 @@ +Templates

Templates

+

The store page's template

The store page is made from a Pebble template. Leave Template override empty for the built-in design, or Choose a template file — such as one of the alternatives in the plugin's templates folder. Load the default template fills in the built-in one, to start from.

+

A template can {% extends "default" %} and replace only the parts it wants: styles, header, announcement, card, downloads or footer. Pieces and macros shared between templates go in the folder CodeOnTheGoProjects/ShareYourAppsTemplates, for {% include %} and {% import %}.

+

Built-in functions and filters: t("key") for text in the store's language; plural(n, "# app", "# apps"); markdown; qr("text"); bytes; and slugify.

+

Extra JSON

Optional settings for the whole store, as JSON, passed to the template as extra. The built-in templates use announcement, a line above the products; accent, a colour; contact, your name, email, phone and web address, shown at the foot of the page so buyers can reach you; and lang, the page's language. strings holds text for t(), by language.

diff --git a/plugins/Share-Your-Apps/src/main/assets/icon_day.png b/plugins/Share-Your-Apps/src/main/assets/icon_day.png new file mode 100644 index 000000000..b3742a825 Binary files /dev/null and b/plugins/Share-Your-Apps/src/main/assets/icon_day.png differ diff --git a/plugins/Share-Your-Apps/src/main/assets/icon_night.png b/plugins/Share-Your-Apps/src/main/assets/icon_night.png new file mode 100644 index 000000000..a6367920b Binary files /dev/null and b/plugins/Share-Your-Apps/src/main/assets/icon_night.png differ diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/ApkReader.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/ApkReader.kt new file mode 100644 index 000000000..b8acb7d59 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/ApkReader.kt @@ -0,0 +1,18 @@ +package org.appdevforall.shareyourapps + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import java.io.File + +/** Reads an APK's version, package name and minimum Android version, with Android's own PackageManager. */ +object ApkReader { + fun read(ctx: Context, apk: File): ApkFacts? = try { + val pm = ctx.packageManager + val info = if (Build.VERSION.SDK_INT >= 33) pm.getPackageArchiveInfo(apk.path, PackageManager.PackageInfoFlags.of(0)) + else @Suppress("DEPRECATION") pm.getPackageArchiveInfo(apk.path, 0) + info?.let { ApkFacts(it.versionName, it.longVersionCode, it.packageName, it.applicationInfo?.minSdkVersion) } + } catch (e: Exception) { + null // not a readable APK, such as the demo's placeholders: the page simply leaves those facts out + } +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Catalog.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Catalog.kt new file mode 100644 index 000000000..6e8f3c6a5 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Catalog.kt @@ -0,0 +1,194 @@ +package org.appdevforall.shareyourapps + +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject +import org.json.JSONTokener + +/** + * A JSON object with nothing after it. org.json's own `JSONObject(text)` — on Android and the + * JVM alike — stops at the closing brace and silently ignores anything after it, so `{}ffg` + * would pass as `{}`. + */ +fun strictJsonObject(text: String): JSONObject { + val t = JSONTokener(text) + val v = t.nextValue() + if (v !is JSONObject) throw JSONException("it must be a JSON object, in { }") + if (t.nextClean() != 0.toChar()) throw JSONException("there's unexpected text after the closing }") + return v +} + +class CatalogException(message: String) : Exception(message) + +/** What loading `catalog.json` found: the catalog, and a problem to show the owner, if any. */ +class CatalogLoad(val catalog: Catalog?, val problem: String?) + +/** + * Loads [file]. A file that can't be read is renamed `catalog.json.bad`, replacing any earlier + * one, before the owner starts again with an empty catalog — so the next save can't overwrite + * it, and it can still be recovered by hand. [catalog] null means "start empty". + */ +fun loadCatalogFile(file: java.io.File): CatalogLoad { + if (!file.exists()) return CatalogLoad(null, null) + val why = try { + return CatalogLoad(Catalog.parse(file.readText()), null) + } catch (e: Exception) { e.message ?: e.toString() } + val bad = java.io.File(file.parentFile, file.name + ".bad") + bad.delete() + val kept = file.renameTo(bad) + return CatalogLoad(null, + if (kept) "catalog.json couldn't be read, so this is a new, empty catalog. The unreadable file is kept as catalog.json.bad, beside it, in case it can be fixed: $why" + else "catalog.json couldn't be read, so this is a new, empty catalog: $why") +} + +data class Product( + val name: String, + val project: String?, // relative to shared storage, e.g. CodeOnTheGoProjects/MyApp + val apk: String?, + val apkPublished: Boolean, + val sourceZipPublished: Boolean, + val carousel: List, + val descriptionHtml: String?, + val dateAdded: String?, + val ordinal: Int, + /** The product's own Extra JSON: owner-defined, with documented keys whatsNew, license, author and website. */ + val extra: JSONObject = JSONObject(), + /** For each picture or video in [carousel], by its path: what it shows, and a video's captions. */ + val mediaText: Map = emptyMap(), +) { + val published: Boolean get() = (apkPublished && apk != null) || sourceZipPublished + + /** Why publishing leaves this product out — it has nothing to download — or null if it's included. */ + val leftOutReason: String? get() = when { + published -> null + apk == null -> "has no APK chosen, and Publish the source isn't ticked" + else -> "has Publish the APK and Publish the source both unticked" + } +} + +/** + * What a picture or video shows, for buyers who can't see it, and a video's captions: a WebVTT + * file, relative to shared storage. Either may be missing. + */ +data class MediaText(val description: String? = null, val captions: String? = null) { + val isEmpty: Boolean get() = description.isNullOrBlank() && captions == null +} + +/** catalog.json: the whole catalog, in the plugin's private storage. */ +data class Catalog( + val storeDir: String?, // the Store directory currently being served, or null + val storeName: String, + val storeDescriptionHtml: String?, + val headerImage: String?, + val pin: String?, + val templateOverride: String?, + val extra: JSONObject, + val products: List, + /** + * A Store directory handed to the server whose publish hasn't finished. If Code On The Go's + * process dies between the server switching and [storeDir] being saved, this is the one the + * server may really be serving, so it's never removed as a leftover. + */ + val pendingDir: String? = null, +) { + fun toJson(): JSONObject = JSONObject().apply { + put("storeDir", storeDir ?: JSONObject.NULL) + put("pendingDir", pendingDir ?: JSONObject.NULL) + put("storeName", storeName) + put("storeDescriptionHtml", storeDescriptionHtml ?: JSONObject.NULL) + put("headerImage", headerImage ?: JSONObject.NULL) + put("pin", pin ?: JSONObject.NULL) + put("templateOverride", templateOverride ?: JSONObject.NULL) + put("extra", extra) + put("products", JSONArray().apply { + for (p in products) put(JSONObject().apply { + put("name", p.name) + put("project", p.project ?: JSONObject.NULL) + put("apk", p.apk ?: JSONObject.NULL) + put("apkPublished", p.apkPublished) + put("sourceZipPublished", p.sourceZipPublished) + put("carousel", JSONArray(p.carousel)) + put("descriptionHtml", p.descriptionHtml ?: JSONObject.NULL) + put("dateAdded", p.dateAdded ?: JSONObject.NULL) + put("ordinal", p.ordinal) + put("extra", p.extra) + if (p.mediaText.isNotEmpty()) put("mediaText", JSONObject().apply { + p.mediaText.forEach { (path, t) -> put(path, JSONObject().apply { + t.description?.let { put("description", it) }; t.captions?.let { put("captions", it) } }) } }) + }) + }) + } + + companion object { + private val PIN = Regex("[0-9]{1,6}") + + fun parse(text: String): Catalog { + val o = try { strictJsonObject(text) } catch (e: Exception) { + throw CatalogException("catalog.json isn't valid JSON: ${e.message}") + } + val extra = when { + !o.has("extra") || o.isNull("extra") -> JSONObject() + o.get("extra") is JSONObject -> o.getJSONObject("extra") + else -> throw CatalogException("\"extra\" must be a JSON object") + } + val pin = str(o, "pin")?.takeIf { it.isNotEmpty() } + if (pin != null && !PIN.matches(pin)) throw CatalogException("\"pin\" must be up to 6 digits") + val arr = if (o.has("products") && !o.isNull("products")) o.getJSONArray("products") else JSONArray() + val products = (0 until arr.length()).map { i -> + val p = arr.getJSONObject(i) + val carousel = if (p.has("carousel") && !p.isNull("carousel")) p.getJSONArray("carousel") else JSONArray() + Product( + name = str(p, "name") ?: throw CatalogException("product ${i + 1} has no \"name\""), + project = str(p, "project"), + apk = str(p, "apk"), + apkPublished = p.optBoolean("apkPublished", false), + sourceZipPublished = p.optBoolean("sourceZipPublished", false), + carousel = (0 until carousel.length()).map { carousel.getString(it) }, + descriptionHtml = str(p, "descriptionHtml"), + dateAdded = str(p, "dateAdded"), + ordinal = p.optInt("ordinal", i + 1), + extra = p.optJSONObject("extra") ?: JSONObject(), + mediaText = p.optJSONObject("mediaText")?.let { m -> m.keys().asSequence().associateWith { k -> + val t = m.optJSONObject(k) ?: JSONObject() + MediaText(str(t, "description"), str(t, "captions")) } } ?: emptyMap(), + ) + } + return Catalog( + storeDir = str(o, "storeDir"), + pendingDir = str(o, "pendingDir"), + storeName = str(o, "storeName") ?: "Share Your Apps", + storeDescriptionHtml = str(o, "storeDescriptionHtml"), + headerImage = str(o, "headerImage"), + pin = pin, + templateOverride = str(o, "templateOverride"), + extra = extra, + products = products, + ) + } + + /** A string field, or null when missing or JSON null (org.json differs between Android and the JVM here). */ + private fun str(o: JSONObject, key: String): String? = + if (!o.has(key) || o.isNull(key)) null else o.get(key).toString() + } +} + +/** A file's modification time and size, to notice when something else has changed it. */ +data class FileStamp(val modified: Long, val length: Long) { + companion object { + fun of(f: java.io.File): FileStamp? = if (f.isFile) FileStamp(f.lastModified(), f.length()) else null + } +} + +enum class Reload { NONE, RELOAD, CONFLICT } + +/** + * Whether the catalog should be reloaded from catalog.json: [loaded] is the file as it was at the + * last load or save, [current] as it is now, and [unsaved] whether there are edits not yet saved. + * An unchanged file needs nothing; a changed one is reloaded — unless there are unsaved edits, + * which are kept rather than lost, and reported as a conflict. + */ +fun reloadDecision(loaded: FileStamp?, current: FileStamp?, unsaved: Boolean): Reload = when { + loaded == current -> Reload.NONE + unsaved -> Reload.CONFLICT + else -> Reload.RELOAD +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/CatalogState.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/CatalogState.kt new file mode 100644 index 000000000..23a4e507f --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/CatalogState.kt @@ -0,0 +1,158 @@ +package org.appdevforall.shareyourapps + +import android.os.Handler +import android.os.Looper +import org.json.JSONObject +import java.io.File +import java.util.concurrent.Executors + +/** + * The catalog being edited, process-wide, so it survives the tab being rebuilt. Every change + * is saved to catalog.json shortly afterward. Main thread only, apart from the file writes. + */ +object CatalogState { + + private val main = Handler(Looper.getMainLooper()) + private var writer = Executors.newSingleThreadExecutor() + private val saveSoon = Runnable { saveNow() } + private var dataDir: File? = null + + var catalog = empty() + private set + + /** The extra-JSON field as typed; it only reaches [catalog] while it's a valid object. */ + var extraText = "{}" + private set + var extraError: String? = null + private set + + /** Which product's editor is open (-1 for none): UI state, kept here so it survives rebuilds. */ + var expanded = -1 + + var loadError: String? = null + private set + + fun empty() = Catalog(null, "Share Your Apps", null, null, null, null, JSONObject(), emptyList()) + + /** + * The catalog's text as last loaded or successfully written. A save with the same text is + * skipped, so leaving the tab without changing anything never touches catalog.json — a file + * replaced by hand isn't overwritten — and an edit that's undone doesn't count as a change. + */ + @Volatile private var lastWritten: String? = null + + /** catalog.json as it was at the last load or save, to notice when something else changes it. */ + @Volatile private var loadedStamp: FileStamp? = null + /** Set while a save is being written, when the file may briefly differ from [loadedStamp]. */ + @Volatile private var writing = false + + fun load(dir: File) { + if (dataDir == dir) return + dataDir = dir + // An unreadable file is set aside as catalog.json.bad first, so the next save can't overwrite it. + val loaded = loadCatalogFile(File(dir, "catalog.json")) + loadError = loaded.problem + catalog = loaded.catalog ?: empty() + extraText = catalog.extra.toString(2) + extraError = null + lastWritten = snapshot().toJson().toString(2) + loadedStamp = FileStamp.of(File(dir, "catalog.json")) + } + + fun hasUnsavedEdits(): Boolean = snapshot().toJson().toString(2) != lastWritten + + /** + * Called when the tab returns to the screen, and before publishing: if something else has + * changed catalog.json since it was loaded or saved — say, a catalog installed by hand — it's + * reloaded. With unsaved edits, those are kept instead, and the owner is told. + */ + fun reloadIfChanged(): Reload { + val dir = dataDir ?: return Reload.NONE + if (writing) return Reload.NONE + val f = File(dir, "catalog.json") + val decision = reloadDecision(loadedStamp, FileStamp.of(f), hasUnsavedEdits()) + when (decision) { + Reload.RELOAD -> { + main.removeCallbacks(saveSoon) + val loaded = loadCatalogFile(f) + loadError = loaded.problem + catalog = loaded.catalog ?: empty() + extraText = catalog.extra.toString(2) + extraError = null + expanded = -1 + lastWritten = snapshot().toJson().toString(2) + loadedStamp = FileStamp.of(f) + } + Reload.CONFLICT -> { + loadError = "catalog.json was changed outside Share Your Apps while you had unsaved changes here. " + + "Your changes are kept, and saving them will replace the other version." + loadedStamp = FileStamp.of(f) // say it once + } + Reload.NONE -> {} + } + return decision + } + + fun update(change: (Catalog) -> Catalog) { + catalog = change(catalog) + main.removeCallbacks(saveSoon) + main.postDelayed(saveSoon, 400) + } + + fun updateProduct(index: Int, change: (Product) -> Product) = update { c -> + c.copy(products = c.products.mapIndexed { i, p -> if (i == index) change(p) else p }) + } + + fun setExtra(text: String) { + extraText = text + val result = runCatching { strictJsonObject(text.ifBlank { "{}" }) } + val parsed = result.getOrNull() + extraError = if (parsed == null) "Not valid yet (${result.exceptionOrNull()?.message}). The last valid value is kept." else null + if (parsed != null) update { it.copy(extra = parsed) } + } + + /** Called when a publish has switched the server to [dir]; that publish is no longer pending. */ + fun setStoreDir(dir: String) { + catalog = catalog.copy(storeDir = dir, pendingDir = null) + saveNow() + } + + /** Records [dir] as handed to the server, before it's launched, or clears it; saved at once. */ + fun setPendingDir(dir: String?) { + catalog = catalog.copy(pendingDir = dir) + saveNow() + } + + /** The catalog as it stands, with products numbered in list order. */ + fun snapshot(): Catalog = catalog.copy( + products = catalog.products.mapIndexed { i, p -> p.copy(ordinal = i + 1) } + ) + + /** The plugin is being unloaded: saves any edit still waiting, lets that write finish, and stops the writer's thread. */ + fun dispose() { + saveNow() + writer.shutdown() + dataDir = null + } + + fun saveNow() { + main.removeCallbacks(saveSoon) + val dir = dataDir ?: return + val json = snapshot().toJson().toString(2) + if (json == lastWritten) return + if (writer.isShutdown) writer = Executors.newSingleThreadExecutor() + writer.execute { + writing = true + runCatching { + dir.mkdirs() + val tmp = File(dir, "catalog.json.tmp") + tmp.writeText(json) + // Recorded only once written, so a failed write is tried again at the next save. + val target = File(dir, "catalog.json") + // The stamp first: until lastWritten catches up, the edits still count as unsaved. + if (tmp.renameTo(target)) { loadedStamp = FileStamp.of(target); lastWritten = json } + } + writing = false + } + } +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Help.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Help.kt new file mode 100644 index 000000000..96cba4c55 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Help.kt @@ -0,0 +1,129 @@ +package org.appdevforall.shareyourapps + +import com.itsaky.androidide.plugins.extensions.PluginTooltipEntry + +/** + * Tooltips for Manage Catalog. CodeOnTheGo stores these under the category + * `plugin_org.appdevforall.shareyourapps`, derived from the plugin ID, and resolves the category + * itself when one is shown, so tags only need to be unique within this plugin. + * Summary is the one-line tooltip; detail is what "See more" shows. + */ +object Help { + const val OVERVIEW = "shareyourapps.overview" + const val STORE_NAME = "shareyourapps.store_name" + const val STORE_DESCRIPTION = "shareyourapps.store_description" + const val HEADER_IMAGE = "shareyourapps.header_image" + const val PIN = "shareyourapps.pin" + const val PRODUCTS = "shareyourapps.products" + const val PRODUCT_PROJECT = "shareyourapps.product_project" + const val PRODUCT_APK = "shareyourapps.product_apk" + const val PUBLISH_APK = "shareyourapps.publish_apk" + const val PUBLISH_SOURCE = "shareyourapps.publish_source" + const val PRODUCT_MEDIA = "shareyourapps.product_media" + const val MEDIA_DESCRIBE = "shareyourapps.media_describe" + const val MEDIA_REMOVE = "shareyourapps.media_remove" + const val PRODUCT_NAME = "shareyourapps.product_name" + const val CAPTIONS = "shareyourapps.captions" + const val PRODUCT_DESCRIPTION = "shareyourapps.product_description" + const val PRODUCT_ORDER = "shareyourapps.product_order" + const val TEMPLATE = "shareyourapps.template" + const val EXTRA = "shareyourapps.extra" + const val PRODUCT_EXTRA = "shareyourapps.product_extra" + const val PUBLISH = "shareyourapps.publish" + + val entries = listOf( + e(OVERVIEW, "Share Your Apps
Share your apps and their source with people nearby.", + "

Share Your Apps turns your projects into a small web store that people on the same Wi-Fi network " + + "or hotspot can open in their phone's browser, to download your APKs and source code. " + + "No internet or accounts are needed.

" + + "

Fill in the store's details and products here, then tap Publish. The Share Your Apps " + + "Server app serves what you publish; its Serve screen shows the codes people scan to reach it.

" + + "

Changes are saved as you make them, but buyers only see them after you publish.

"), + e(STORE_NAME, "The name at the top of your store, and on its PIN page.", + "

Shown as the heading of the store page, and on the PIN page if you set a PIN.

"), + e(STORE_DESCRIPTION, "Optional HTML shown under the store name.", + "

Write it as HTML, for example <p>Everything here is free.</p>. " + + "It's placed on the page exactly as written, so it can include links and formatting.

" + + "

Tag mistakes — a tag opened but never closed, closed but never opened, or closed in the wrong order — " + + "are shown under the field as you type. They don't stop a publish.

"), + e(HEADER_IMAGE, "The picture at the top of your store.", + "

Choose an image or video from your phone, or tap Default to use the built-in icon. " + + "Publishing copies it into the store, so you can change or delete the original afterward.

"), + e(PIN, "Optional: a PIN buyers must enter before they can see the store.", + "

Up to 6 digits. Leave it empty for an open store.

" + + "

After entering the PIN, a buyer's browser stays signed in for 24 hours. Changing the PIN " + + "doesn't sign anyone out.

" + + "

After 5 wrong PINs, a phone must wait 30 seconds before trying again, and twice as long after " + + "each further wrong PIN.

" + + "

The store doesn't use encryption, so treat the PIN as a way to keep casual visitors out, not " + + "as real security.

"), + e(PRODUCTS, "The apps in your store, in the order buyers see them.", + "

Tap + Add product to add one, and tap a product's name to open or close its details. " + + "A product marked draft has nothing to download yet — no APK chosen with Publish the APK ticked, and " + + "Publish the source unticked — so it's left out of the store. The message after publishing names any product left out, and why.

"), + e(PRODUCT_PROJECT, "The CodeOnTheGo project this product comes from.", + "

Needed for publishing the source, and for finding the project's APKs.

"), + e(PRODUCT_APK, "The APK buyers download and install.", + "

The list shows the APKs this project has built, newest first. Build the project in " + + "CodeOnTheGo if it's empty.

"), + e(PUBLISH_APK, "Include the APK in the store.", + "

When this is off, the product has no Download APK button.

"), + e(PUBLISH_SOURCE, "Include the project's source code in the store, as a zip.", + "

The zip leaves out build output, caches, IDE settings, and signing files such as keystores and " + + "release.properties, along with anything your .gitignore excludes.

" + + "

Check that the project doesn't contain passwords or keys in other files before you publish it.

"), + e(PRODUCT_MEDIA, "Pictures and videos shown for this product.", + "

They appear in a row that buyers can swipe through. Publishing copies them into the store.

"), + e(PRODUCT_NAME, "The product's name, as buyers see it.", + "

It heads the product's card on the store page, and names the product's download files, " + + "such as todo-app.apk. Two products can share a name: the second's files get a number, such as todo-app-2.

"), + e(MEDIA_REMOVE, "Take this picture or video out of the product.", + "

It leaves the store at your next publish, and its description and captions go with it. The file itself stays on your phone.

"), + e(CAPTIONS, "Add captions to this video, for buyers who can't hear it, or remove them.", + "

Choose captions file picks a WebVTT file, ending .vtt: text with the time each line appears. " + + "Publishing copies it beside the video, and buyers can turn the captions on in the video's menu or its CC button. " + + "No captions removes them. Either takes effect when you tap Save.

"), + e(MEDIA_DESCRIBE, "Say what a picture or video shows, for buyers who can't see it.", + "

Screen readers read the description aloud, in place of the picture. Say what matters about it for choosing the app — " + + "The chat screen, with two messages — not what kind of item it is. Without one, the page says only which picture it is: " + + "Termux, picture 1 of 3.

For a video, you can also add captions: a WebVTT file, ending .vtt, " + + "which the store shows under the video for buyers who can't hear it.

"), + e(PRODUCT_DESCRIPTION, "Optional HTML describing this product.", + "

Written as HTML and placed on the page exactly as written. Tag mistakes, such as a tag opened but never " + + "closed, are shown under the field as you type, and on the product's card when it's closed. They don't stop a publish.

"), + e(PRODUCT_ORDER, "Move this product up or down the list, or remove it.", + "

Removing a product takes it out of the store at your next publish.

"), + e(TEMPLATE, "Optional: your own Pebble template for the store page.", + "

Leave it empty to use the built-in design. Tap Load the default template to start from " + + "the built-in one and change it, or Choose a template file to load a Pebble template " + + "(a .peb file) from your phone, starting in Download. Either replaces what's in the field.

" + + "

A template that can't be rendered stops the publish and shows the error, so a mistake here " + + "never reaches buyers.

"), + e(EXTRA, "Optional JSON your template can use, as extra.", + "

It must be a JSON object, in { }. A template can then use, for example, " + + "{{ extra.motto }}. You can't publish while it isn't valid.

" + + "

Every template understands these keys:

    " + + "
  • \"lang\": the store's language, such as \"sw\". Without it, the phone's is used.
  • " + + "
  • \"contact\": {\"name\": …, \"email\": …, \"phone\": …, \"url\": …}, shown at the foot of the page, " + + "so buyers can reach you. Any part may be left out.
  • " + + "
  • \"announcement\": a short line of news, shown above the products.
  • " + + "
  • \"accent\": a colour such as \"#1E88E5\", for the download buttons. " + + "Text on it is black or white, whichever reads better. The accessible version keeps its own colours.
"), + e(PRODUCT_EXTRA, "Optional JSON about this product, for your template.", + "

It must be a JSON object, in { }. Every template shows these keys:

    " + + "
  • \"whatsNew\": what's changed in this version.
  • " + + "
  • \"license\": the licence, such as \"GPL-3.0-or-later\" — worth giving " + + "when you publish the source.
  • " + + "
  • \"author\": who made it.
  • " + + "
  • \"website\": an https:// address.
" + + "

Other keys reach your own template as {{ p.extra.yourKey }}.

"), + e(PUBLISH, "Send your catalog to the store.", + "

Builds a new copy of the store, starts the Share Your Apps Server on it, checks that everything is " + + "being served correctly, and then deletes the previous copy.

" + + "

If anything goes wrong, nothing changes: the store keeps showing what you published last.

"), + ) + + /** Each entry's tier-3 button, to its section of the plugin's offline pages (HelpPages). */ + private fun e(tag: String, summary: String, detail: String) = PluginTooltipEntry(tag, summary, detail, + listOfNotNull(HelpPages.buttons[tag]?.let { (label, uri) -> com.itsaky.androidide.plugins.extensions.PluginTooltipButton(label, uri, 0, false) })) +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HelpPages.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HelpPages.kt new file mode 100644 index 000000000..2ddadbcca --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HelpPages.kt @@ -0,0 +1,32 @@ +package org.appdevforall.shareyourapps + +/** + * Tier 3 of the plugin's help: for each tooltip tag, the button to its section of the offline pages in + * src/main/assets/docs/, which CodeOnTheGo serves (DocumentationExtension.getTier3DocsAssetPath). + * Uris are relative, so CodeOnTheGo scopes them to this plugin's own pages. + */ +object HelpPages { + val buttons: Map> = mapOf( + "shareyourapps.overview" to ("Share Your Apps help" to "index.html"), + "shareyourapps.store_name" to ("The store" to "store.html#name"), + "shareyourapps.store_description" to ("The store" to "store.html#description"), + "shareyourapps.header_image" to ("The store" to "store.html#header"), + "shareyourapps.pin" to ("The store's PIN" to "store.html#pin"), + "shareyourapps.products" to ("Products" to "products.html#list"), + "shareyourapps.product_order" to ("Products" to "products.html#list"), + "shareyourapps.product_name" to ("A product's name" to "products.html#name"), + "shareyourapps.product_project" to ("Products" to "products.html#project"), + "shareyourapps.product_apk" to ("A product's APK" to "products.html#apk"), + "shareyourapps.publish_apk" to ("What to publish" to "products.html#publish"), + "shareyourapps.publish_source" to ("What to publish" to "products.html#publish"), + "shareyourapps.product_description" to ("Products" to "products.html#description"), + "shareyourapps.product_extra" to ("A product's Extra JSON" to "products.html#extra"), + "shareyourapps.product_media" to ("Pictures and videos" to "media.html#pictures"), + "shareyourapps.media_describe" to ("Describing pictures and videos" to "media.html#describe"), + "shareyourapps.captions" to ("Captions" to "media.html#captions"), + "shareyourapps.media_remove" to ("Pictures and videos" to "media.html#remove"), + "shareyourapps.template" to ("Templates" to "templates.html#template"), + "shareyourapps.extra" to ("Extra JSON" to "templates.html#extra"), + "shareyourapps.publish" to ("Publishing" to "publishing.html#publish"), + ) +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HtmlCheck.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HtmlCheck.kt new file mode 100644 index 000000000..cfdd88119 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/HtmlCheck.kt @@ -0,0 +1,110 @@ +package org.appdevforall.shareyourapps + +/** + * Checks owner-written HTML — the store and product descriptions, which go into the page as-is — + * for the mistakes an owner can make and fix: a tag opened but never closed, a tag closed that was + * never opened, and tags closed in the wrong order. It knows HTML's own rules, so it doesn't + * complain about what's legal: tags that never close (`
`, ``), end tags that are optional + * (`
  • `, `

    `, ``), and the raw text inside `""" + + /** + * Clear Access, for buyers who use a screen reader or have low vision. Every publish also + * renders it as accessible.html, which the other templates link to as "Accessible version" — + * unless the store's own template is this one, recognised by [ACCESSIBLE_MARKER]. + */ + const val ACCESSIBLE = """{# share-your-apps:accessible — marks this as the accessible template, so the plugin makes no second copy of it. #} +{{storeName}} + +

    +{% if standardHref is not empty %}{% endif %} +
    {% if headerImage.type=='video' %}{% else %}{% endif %}

    {{storeName}}

    {% if storeDescriptionHtml is not empty %}
    {{storeDescriptionHtml|raw}}
    {% endif %}
    +{% if announcement is not empty %}

    {{announcement}}

    {% endif %}{% if products is not empty %}{% endif %} +
    {% for p in products %}

    {{p.name}}

    Added {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}

    {% if p.descriptionHtml is not empty %}
    {{p.descriptionHtml|raw}}
    {% endif %}{% if p.whatsNew is not empty %}

    What's new: {{p.whatsNew}}

    {% endif %}
    {% if p.apk is not empty %}Download {{p.name}} APK, {{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download {{p.name}} source code, {{p.sourceZip.sizeLabel}}{% endif %}
    {% if p.apk is not empty %}

    {% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

    {% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

    {% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

    {% endif %}{% if p.carousel is not empty %}
      {% for m in p.carousel %}
    • {% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}
    • {% endfor %}
    {% endif %}Back to the list of apps
    {% endfor %}
    +

    {{storeName}} · Updated

    {% if contact is not empty %}

    Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

    {% endif %}

    Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

    +
    +""" + + /** In a template, marks it as the accessible one, so no second copy is made. */ + const val ACCESSIBLE_MARKER = "share-your-apps:accessible" + + /** Written to the root of every Store directory. */ + const val README = """SHARE YOUR APPS - DATA FOLDER + +This folder holds the published contents of your Share Your Apps, the Code On +The Go plugin for sharing apps and source code with people on the same +Wi-Fi network or hotspot. + +- It is managed automatically. Each time you publish, a new folder like + this one is written and the previous one is deleted. Don't put your own + files here. + +- Anything you publish can be downloaded by anyone who can reach your store, + and everything in this folder can be read by other apps on this device. + Don't publish anything you want to keep private. + +- To change what's published, use the Share Your Apps plugin in Code On The Go. + Don't edit these files by hand. + +- If you no longer use Share Your Apps, you can delete this folder. The store + stops working until you publish again. + +- The number in this folder's name is random. It keeps the folder from + clashing with the name of one of your projects. +""" + + /** The header image when the owner hasn't chosen one: a phone with a cart. Under 10 KB, so always inlined. */ + const val DEFAULT_ICON_SVG = """""" +} diff --git a/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Verifier.kt b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Verifier.kt new file mode 100644 index 000000000..78687908b --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/kotlin/org/appdevforall/shareyourapps/Verifier.kt @@ -0,0 +1,71 @@ +package org.appdevforall.shareyourapps + +import java.io.File +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URI +import java.net.URLEncoder +import java.security.MessageDigest + +/** + * Checks the running server serves exactly what the publish wrote: fetches index.html and + * every other file over localhost and compares length and SHA-256. The token gets past the PIN. + */ +class Verifier(private val port: Int, private val token: String) { + + /** Problems found, one line each; empty means everything matched. */ + fun verify(root: File, files: List): List { + val problems = mutableListOf() + check("/", File(root, "index.html"), "index.html", problems) + for (rel in files) check(link(rel), File(root, rel), rel, problems) + return problems + } + + private fun check(path: String, file: File, label: String, problems: MutableList) { + try { + val url = URI("http://127.0.0.1:$port$path?token=" + URLEncoder.encode(token, "UTF-8")).toURL() + val c = url.openConnection() as HttpURLConnection + c.connectTimeout = 5_000 + c.readTimeout = 30_000 + c.instanceFollowRedirects = false + // Set explicitly: HttpURLConnection otherwise asks for gzip itself and silently decompresses. + c.setRequestProperty("Accept-Encoding", "identity") + try { + if (c.responseCode != 200) { problems += "$label: server answered ${c.responseCode}"; return } + val (length, digest) = c.inputStream.use { digest(it) } + val (expectedLength, expected) = expected(file).use { digest(it) } + if (length != expectedLength) problems += "$label: served $length bytes, expected $expectedLength" + else if (!digest.contentEquals(expected)) problems += "$label: contents differ" + } finally { + c.disconnect() + } + } catch (e: Exception) { + problems += "$label: ${e.message ?: e.toString()}" + } + } + + /** + * The file's contents, as published. The server replaces a source zip by its .gz copy once that's made — perhaps + * mid-check — so a zip that's gone is read from its copy, decompressed: the same bytes. Opened once, so its length + * and contents can't come from different copies. + */ + private fun expected(file: File): InputStream = try { + file.inputStream() + } catch (e: java.io.FileNotFoundException) { + val gz = File(file.path + ".gz") + if (file.name.endsWith(".zip") && gz.isFile) java.util.zip.GZIPInputStream(gz.inputStream(), 64 * 1024) else throw e + } + + private fun digest(input: InputStream): Pair { + val md = MessageDigest.getInstance("SHA-256") + val buf = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buf) + if (n < 0) break + md.update(buf, 0, n) + total += n + } + return total to md.digest() + } +} diff --git a/plugins/Share-Your-Apps/src/main/res/drawable/ic_plugin.xml b/plugins/Share-Your-Apps/src/main/res/drawable/ic_plugin.xml new file mode 100644 index 000000000..1f437decf --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/res/drawable/ic_plugin.xml @@ -0,0 +1,10 @@ + + + diff --git a/plugins/Share-Your-Apps/src/main/res/values-night/colors.xml b/plugins/Share-Your-Apps/src/main/res/values-night/colors.xml new file mode 100644 index 000000000..35516a83d --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/res/values-night/colors.xml @@ -0,0 +1,20 @@ + + + #88D6B8 + #00382A + #00513D + #A4F2D3 + #B3CCBF + #1F352C + #191C1A + #E1E3DF + #BFC9C1 + #89938C + #404943 + #E1E3DF + #2E3230 + #88D6B8 + #0D2E22 + #FFB4AB + #690005 + diff --git a/plugins/Share-Your-Apps/src/main/res/values/colors.xml b/plugins/Share-Your-Apps/src/main/res/values/colors.xml new file mode 100644 index 000000000..d6b2fcf1f --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/res/values/colors.xml @@ -0,0 +1,20 @@ + + + #1A6B52 + #FFFFFF + #A4F2D3 + #002117 + #4C6359 + #FFFFFF + #FBFDF9 + #191C1A + #404943 + #707973 + #BFC9C1 + #191C1A + #E1E7E2 + #1A6B52 + #D4F5E6 + #BA1A1A + #FFDAD6 + diff --git a/plugins/Share-Your-Apps/src/main/res/values/strings.xml b/plugins/Share-Your-Apps/src/main/res/values/strings.xml new file mode 100644 index 000000000..17867ddb1 --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + Share Your Apps + A Code on the Go plugin + Ready + Perform Action + diff --git a/plugins/Share-Your-Apps/src/main/res/values/styles.xml b/plugins/Share-Your-Apps/src/main/res/values/styles.xml new file mode 100644 index 000000000..0ce3a804e --- /dev/null +++ b/plugins/Share-Your-Apps/src/main/res/values/styles.xml @@ -0,0 +1,6 @@ + + + +

    {{x}}

    " + val readable = "{# note #}\n

    {{x}}

    " + org.junit.Assert.assertNull(firstDifference(normalizeTemplate(compact), normalizeTemplate(readable))) + org.junit.Assert.assertNotNull(firstDifference(normalizeTemplate(compact), normalizeTemplate(readable.replace("red", "blue")))) + org.junit.Assert.assertNotNull(firstDifference(normalizeTemplate(compact), normalizeTemplate(readable.replace("{{x}}", "{{y}}")))) + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/HtmlCheckTest.kt b/plugins/Share-Your-Apps/src/test/kotlin/HtmlCheckTest.kt new file mode 100644 index 000000000..3228bc60e --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/HtmlCheckTest.kt @@ -0,0 +1,62 @@ +package htmltest +import org.appdevforall.shareyourapps.HtmlCheck +import org.appdevforall.shareyourapps.Product + +var failures = 0 +val failedNames = mutableListOf() +fun check(name: String, cond: Boolean) { + if (!cond) failedNames += name + println((if (cond) "PASS " else "FAIL ") + name); if (!cond) failures++ } +fun p(h: String) = HtmlCheck.problems(h) + +/** Runs every check; returns the names of those that failed. */ +fun runChecks(): List { + failures = 0; failedNames.clear() + // Fine as written. + check("plain text", p("frammis gloopy gloop").isEmpty()) + check("balanced tags", p("

    Hi there, link

    ").isEmpty()) + check("tags that never close", p("a
    b
    c
    ").isEmpty()) + check("optional end tags left out", p("
    • one
    • two

    a

    b
    12
    ").isEmpty()) + check("a block tag ends an open

    ", p("

    intro

    • x
    ").isEmpty()) + check("script and style contents are text", p("").isEmpty()) + check("comments are skipped", p("x").isEmpty()) + check("'>' inside a quoted attribute", p(" b\" href='x'>y").isEmpty()) + check("'<' as plain text", p("if a < b and 3 <4").isEmpty()) + check("upper-case tags match", p("bold").isEmpty()) + check("self-closing SVG shapes", p("").isEmpty()) + check("the owner's store description", p("Hi, mom!").isEmpty()) + + // Mistakes. + val gs = p("frammis gloopy gloop
    1. zippy
    2. zoppy\n
    3. zoppy\n
    4. zoppy\n
      1. ") + check("the Great Scott! description: two unclosed lists", gs == listOf("
          is opened 2 times but never closed")) + check("opened but never closed", p("bold") == listOf(" is opened but never closed")) + check("closed but never opened", p("text") == listOf(" closes a tag that was never opened")) + check("closed in the wrong order", p("
            x
          ") == listOf("
        closes before the inside it", " closes a tag that was never opened")) + check("a closing tag for a tag that never closes", p("a

        ") == listOf("
        isn't needed:
        never takes a closing tag")) + check("a tag never finished", p("")) + check("an unclosed comment", p("")) + check("an unclosed script", p(" [x](javascript:alert(1)) [y](https://e.org\"onmouseover=alert(1))'|markdown }}") + val hrefs = Regex("href=\"([^\"]*)\"").findAll(evil).map { it.groupValues[1] }.toList() + check("…and no HTML, script or javascript: link survives, nor a quote in any link ($evil)", + " pr.carousel.any { it.endsWith("demo.mp4") } && pr.carousel.any { it.endsWith("large shot.png") } } + check("the test catalog has a product with a picture and a video", withMedia >= 0) + val mp = catalog.products[withMedia] + val shot = mp.carousel.first { it.endsWith("large shot.png") }; val vid = mp.carousel.first { it.endsWith("demo.mp4") } + File(sd, "Movies").mkdirs(); File(sd, "Movies/demo.vtt").writeText("WEBVTT\n\n00:00.000 --> 00:02.000\nHello\n") + val described = catalog.copy(products = catalog.products.mapIndexed { k, pr -> if (k != withMedia) pr else pr.copy(mediaText = mapOf( + shot to MediaText("The chat screen, with two messages"), vid to MediaText(null, "Movies/demo.vtt"))) }) + val dBuild = Publisher(sd).build(described) + val dHtml = File(sd, "CodeOnTheGoProjects/${dBuild.storeDir}/index.html").readText() + check("a description becomes the picture's alt text, escaped", "alt=\"The chat screen, with <b>two</b> messages\"" in dHtml) + val others = mp.carousel.withIndex().filter { it.value != shot && !it.value.endsWith(".mp4") && Media.kind(File(it.value).name) == "image" } + val mpName = mp.name.replace("&", "&").replace("<", "<").replace(">", ">") + check("…while an undescribed picture keeps its place: \"${mp.name}, picture n of ${mp.carousel.size}\"", + others.all { (i, _) -> "alt=\"$mpName, picture ${i + 1} of ${mp.carousel.size}\"" in dHtml }) + val track = Regex("""""").find(dHtml) + check("a video's captions become a captions track", track != null) + val trackFile = track?.groupValues?.get(1)?.removePrefix("/f/").orEmpty() + check("…with the captions file copied beside the video, and listed for verifying", File(sd, "CodeOnTheGoProjects/${dBuild.storeDir}/$trackFile").readText().startsWith("WEBVTT") && trackFile in dBuild.files) + val rt = Catalog.parse(described.toJson().toString()).products[withMedia].mediaText + check("descriptions and captions survive saving and loading", rt[shot]?.description == "The chat screen, with two messages" && rt[vid]?.captions == "Movies/demo.vtt") + val noVtt = runCatching { Publisher(sd).build(described.copy(products = described.products.mapIndexed { k, pr -> if (k != withMedia) pr else pr.copy(mediaText = mapOf(vid to MediaText(null, "Movies/nope.vtt"))) })) }.exceptionOrNull() + check("a missing captions file stops the publish", noVtt is PublishException && "captions file not found" in noVtt.message.orEmpty()) + File(sd, "Movies/demo.srt").writeText("1\n") + val srt = runCatching { Publisher(sd).build(described.copy(products = described.products.mapIndexed { k, pr -> if (k != withMedia) pr else pr.copy(mediaText = mapOf(vid to MediaText(null, "Movies/demo.srt"))) })) }.exceptionOrNull() + check("…and so does one that isn't WebVTT", srt is PublishException && "WebVTT" in srt.message.orEmpty()) + + // --- tier-3 help: every button's page and section exist, offline --- + val docs = listOf(File("src/main/assets/docs"), File("../../lsp/assets/docs")).firstOrNull { it.isDirectory } + check("the plugin's tier-3 pages are there (${docs?.path})", docs != null && File(docs, "index.html").isFile) + if (docs != null) { + val broken = HelpPages.buttons.values.map { it.second }.distinct().filter { uri -> + val f = File(docs, uri.substringBefore('#')); val frag = uri.substringAfter('#', "") + !f.isFile || (frag.isNotEmpty() && "id=\"$frag\"" !in f.readText()) } + check("every help button's page and section exist (broken: $broken)", broken.isEmpty() && HelpPages.buttons.size >= 21) + val remote = docs.listFiles()!!.filter { Regex("""(src|href)="(https?:)?//""").containsMatchIn(it.readText()) }.map { it.name } + check("…and the pages work offline, loading nothing from the internet (loading: $remote)", remote.isEmpty()) + } + + // --- slugs (design, Files): two products can never share a folder --- + check("slugs: the design's example", uniqueSlugs(listOf("Great Scott 2", "Great Scott", "Great Scott")) == listOf("great-scott-2", "great-scott", "great-scott-3")) + check("…and the review's, where only earlier products count", uniqueSlugs(listOf("Great Scott", "Great Scott", "Great Scott 2")) == listOf("great-scott", "great-scott-2", "great-scott-2-2")) + check("…never two the same, however many clash", uniqueSlugs(List(12) { i -> if (i % 3 == 0) "App" else "App ${i / 3 + 1}" }).let { it.toSet().size == it.size }) + + // --- unsigned APKs: buyers can't install them --- + val signedDir = Files.createTempDirectory("sig").toFile() + fun zipOf(vararg entries: String) = java.io.ByteArrayOutputStream().also { b -> java.util.zip.ZipOutputStream(b).use { z -> + entries.forEach { z.putNextEntry(java.util.zip.ZipEntry(it)); z.write(ByteArray(100) { 7 }); z.closeEntry() } } }.toByteArray() + val unsignedApk = File(signedDir, "app-release-unsigned.apk").apply { writeBytes(zipOf("classes.dex", "AndroidManifest.xml")) } + val v1Apk = File(signedDir, "v1.apk").apply { writeBytes(zipOf("classes.dex", "META-INF/MANIFEST.MF", "META-INF/CERT.RSA")) } + // v2 or later: the APK Signing Block's marker ends just before the central directory. + val plainZip = zipOf("classes.dex", "AndroidManifest.xml") + val eocd = plainZip.size - 22 + val cdOffset = java.nio.ByteBuffer.wrap(plainZip, eocd + 16, 4).order(java.nio.ByteOrder.LITTLE_ENDIAN).int + val magic = "APK Sig Block 42".toByteArray() + val v2Bytes = plainZip.copyOfRange(0, cdOffset) + magic + plainZip.copyOfRange(cdOffset, plainZip.size) + java.nio.ByteBuffer.wrap(v2Bytes, v2Bytes.size - 22 + 16, 4).order(java.nio.ByteOrder.LITTLE_ENDIAN).putInt(cdOffset + 16) + val v2Apk = File(signedDir, "v2.apk").apply { writeBytes(v2Bytes) } + check("an APK with no signature is unsigned", !apkSigned(unsignedApk)) + check("…one signed the v1 way is signed", apkSigned(v1Apk)) + check("…and one signed the v2 way, by its signing block", apkSigned(v2Apk)) + check("…and a file that isn't a zip at all isn't", !apkSigned(File(signedDir, "junk.apk").apply { writeBytes(ByteArray(500) { 3 }) })) + val projUnsigned = File(sd, "CodeOnTheGoProjects/Unsigned/app/build/outputs/apk/release").apply { mkdirs() } + unsignedApk.copyTo(File(projUnsigned, "app-release-unsigned.apk"), overwrite = true) + val withUnsigned = catalog.copy(products = catalog.products.map { if (it.apk != null) it.copy(apk = "CodeOnTheGoProjects/Unsigned/app/build/outputs/apk/release/app-release-unsigned.apk") else it }) + val unsignedBuild = runCatching { Publisher(sd).build(withUnsigned) } + check("an unsigned APK still publishes — as the demo's placeholders must — with a warning (${unsignedBuild.getOrNull()?.warnings?.firstOrNull()?.take(70)})", + unsignedBuild.isSuccess && unsignedBuild.getOrNull()!!.warnings.any { "isn't signed" in it }) + check("…and a signed one publishes without", Publisher(sd).build(catalog).warnings.isEmpty()) + signedDir.deleteRecursively() + + // --- a source-only product with "Publish the APK" left ticked, and no APK chosen --- + val srcOnly = catalog.products.first { it.apk == null && it.sourceZipPublished } + val ticked = catalog.copy(products = catalog.products.map { if (it === srcOnly) it.copy(apkPublished = true) else it }) + val tickedBuild = runCatching { Publisher(sd).build(ticked) } + check("a source-only product with Publish the APK left ticked still publishes (${tickedBuild.exceptionOrNull()?.message ?: "ok"})", tickedBuild.isSuccess) + + // --- an unreadable catalog.json is kept, not overwritten --- + val dataDir = Files.createTempDirectory("data").toFile() + val cf = File(dataDir, "catalog.json") + check("no catalog.json: start empty, no problem", loadCatalogFile(cf).let { it.catalog == null && it.problem == null }) + cf.writeText(catalog.toJson().toString()) + check("a good catalog.json loads", loadCatalogFile(cf).catalog?.storeName == catalog.storeName) + File(dataDir, "catalog.json.bad").writeText("an older bad file") + cf.writeText("{ this isn't json") + val badLoad = loadCatalogFile(cf) + check("an unreadable one starts empty, and says where the file went", + badLoad.catalog == null && badLoad.problem?.contains("catalog.json.bad") == true) + check("…it's kept as catalog.json.bad, replacing an older one, and catalog.json is gone", + File(dataDir, "catalog.json.bad").readText() == "{ this isn't json" && !cf.exists()) + dataDir.deleteRecursively() + + // --- noticing a catalog.json changed by something else --- + val watched = File(Files.createTempDirectory("watch").toFile(), "catalog.json") + watched.writeText(catalog.toJson().toString()) + val atLoad = FileStamp.of(watched) + check("an unchanged file needs nothing, even with unsaved edits", + reloadDecision(atLoad, FileStamp.of(watched), unsaved = false) == Reload.NONE && reloadDecision(atLoad, FileStamp.of(watched), unsaved = true) == Reload.NONE) + watched.writeText(catalog.copy(storeName = "Replaced by hand").toJson().toString()) + check("a replaced file is noticed", FileStamp.of(watched) != atLoad) + check("…and reloaded", reloadDecision(atLoad, FileStamp.of(watched), unsaved = false) == Reload.RELOAD) + check("…unless there are unsaved edits, which are kept", reloadDecision(atLoad, FileStamp.of(watched), unsaved = true) == Reload.CONFLICT) + watched.delete() + check("a deleted file counts as changed", FileStamp.of(watched) == null && reloadDecision(atLoad, null, unsaved = false) == Reload.RELOAD) + watched.parentFile?.deleteRecursively() + + // --- a publish that never finished: its directory is spared, not deleted as a leftover --- + val projectsDir = File(sd, "CodeOnTheGoProjects") + projectsDir.listFiles()!!.filter { it.name.startsWith("Store_") }.forEach { deleteTree(it) } + for (n in listOf("Store_11111111", "Store_22222222", "Store_33333333")) File(projectsDir, "$n/index.html").apply { parentFile?.mkdirs(); writeText("x") } + val interrupted = catalog.copy(storeDir = "Store_11111111", pendingDir = "Store_22222222") + val rebuilt = Publisher(sd).build(interrupted) + check("the directory being served survives the next publish", File(projectsDir, "Store_11111111").isDirectory) + check("so does one a publish handed to the server but never finished", File(projectsDir, "Store_22222222").isDirectory) + check("a true leftover is still removed", !File(projectsDir, "Store_33333333").exists()) + Publisher(sd).removeOthers(setOf(rebuilt.storeDir)) + check("once a publish succeeds, every other store directory is removed", + projectsDir.listFiles()!!.filter { it.name.startsWith("Store_") }.map { it.name } == listOf(rebuilt.storeDir)) + check("catalog.json keeps pendingDir", Catalog.parse(interrupted.toJson().toString()).pendingDir == "Store_22222222") + check("and it's null when absent", Catalog.parse(catalog.toJson().toString()).pendingDir == null) + + sd.deleteRecursively() + println(if (failures == 0) "\nALL PASSED" else "\n$failures FAILED") + return failedNames.toList() +} + +/** The JUnit test: runs the checks above, and fails naming them if any fail. */ +class PublishChecks { + @org.junit.Test + fun everyCheckPasses() { + val failed = runChecks() + org.junit.Assert.assertTrue("Failed checks: " + failed.joinToString("; "), failed.isEmpty()) + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Brand.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Brand.kt new file mode 100644 index 000000000..f8b54093f --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Brand.kt @@ -0,0 +1,47 @@ +package org.appdevforall.shareyourapps.server + +import java.util.Base64 + +/** + * The store's look, from the Eight-Armed Merchant icon: its awning across the top, a cream + * ground, and outlined "sticker" cards and buttons. Shared by every page the server itself sends + * buyers — the PIN page and the short message pages. The catalog page's template uses the same + * palette. No web fonts: stores run offline. + */ +object Brand { + + /** The icon, animated, as a self-contained image. Kept in an , so its styles can't touch the page. */ + const val OCTOPUS_SVG = """""" + + val octopusDataUri: String = "data:image/svg+xml;base64," + Base64.getEncoder().encodeToString(OCTOPUS_SVG.toByteArray(Charsets.UTF_8)) + + const val INK = "#2B1B3D" + + private const val CSS = + "*{box-sizing:border-box;margin:0}" + + "body{background:#FFF3D6;color:#2B1B3D;font-family:ui-rounded,\"SF Pro Rounded\",system-ui,sans-serif}" + + // The awning: red and cream stripes with scalloped edges, over the teal of the icon. + ".aw{height:26px;background:radial-gradient(circle at 12px 14px,#FF4F3A 11.5px,transparent 12px) 0 0/48px 26px repeat-x," + + "radial-gradient(circle at 36px 14px,#FFF3D6 11.5px,transparent 12px) 0 0/48px 26px repeat-x," + + "repeating-linear-gradient(90deg,#FF4F3A 0 24px,#FFF3D6 24px 48px) 0 0/100% 14px no-repeat,#0B6E6E}" + + "main{max-width:22em;margin:0 auto;padding:28px 16px}" + + ".k{background:#fff;border:3px solid #2B1B3D;border-radius:16px;box-shadow:5px 5px 0 #2B1B3D;padding:22px 20px;text-align:center}" + + ".k img{width:96px;height:96px;border-radius:22px;border:3px solid #2B1B3D;display:block;margin:0 auto 14px}" + + "h1{font-size:22px;font-weight:800;margin-bottom:14px;overflow-wrap:anywhere}" + + "p{font-size:17px;line-height:1.45}" + + "label{display:block;font-weight:700;text-align:left}" + + "input{font:inherit;font-size:1.4em;width:100%;padding:.45em .6em;margin:.4em 0 .9em;border:3px solid #2B1B3D;" + + "border-radius:12px;letter-spacing:.3em;text-align:center;background:#fff;color:#2B1B3D}" + + "input:focus,button:focus-visible{outline:3px solid #8E5BFF;outline-offset:2px}" + + "button{font:inherit;font-size:1.15em;font-weight:800;width:100%;padding:.6em;background:#FF9E2C;color:#2B1B3D;" + + "border:3px solid #2B1B3D;border-radius:12px;box-shadow:3px 3px 0 #2B1B3D;cursor:pointer}" + + "button:active{transform:translate(3px,3px);box-shadow:none}" + + ".er{color:#C2261A;font-weight:700;margin-bottom:12px}" + + /** A complete page: the awning, then a card holding the octopus and [body]. [title] must already be escaped. */ + fun page(title: String, body: String): String = + "" + + "$title" + + "
        " + + "\"\"$body
        " +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Compressor.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Compressor.kt new file mode 100644 index 000000000..df4025140 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/Compressor.kt @@ -0,0 +1,106 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.nio.file.Files +import java.nio.file.LinkOption +import java.util.stream.Collectors +import java.util.zip.Deflater +import java.util.zip.GZIPOutputStream +import kotlin.concurrent.thread + +/** + * Gzips the pages at the Store directory's top and every source zip, in the background, so + * publishing doesn't wait for it. Each copy is written to `.gz.tmp` and renamed to + * `.gz` only when finished, so a partial copy is never served. A copy that isn't smaller + * than the original is deleted instead of renamed. On any error the temporary file is deleted + * and that file is skipped, and the uncompressed file keeps being served. Once a source zip's + * copy is complete, the zip itself is deleted, and HttpServer serves it from the copy. + * + * Nothing coordinates with this thread: a relaunch kills the whole server process. + */ +class Compressor(root: File, private val log: StoreLog) { + + private val rootDir = root.canonicalFile + + /** The files to compress, relative to the Store directory: the pages at its top — index.html and accessible.html — and every .zip, without a .gz. */ + fun pending(): List { + val base = rootDir.toPath() + return Files.walk(base).use { paths -> // doesn't follow symlinks, so it stays inside + paths.filter { Files.isRegularFile(it, LinkOption.NOFOLLOW_LINKS) } + .map { base.relativize(it).toString().replace(File.separatorChar, '/') } + .filter { (it.endsWith(".html") && '/' !in it) || it.endsWith(".zip") } + .filter { !File(rootDir, "$it.gz").exists() } + .sorted() + .collect(Collectors.toList()) // not Stream.toList(): that's API 34+ on Android + } + } + + fun start(): Thread = thread(name = "gzip", isDaemon = true, priority = Thread.MIN_PRIORITY) { run() } + + fun run() { + val todo = try { pending() } catch (e: Exception) { + log.status("gzip", "failed: couldn't list files: ${e.message}") + return + } + log.status("gzip", "started: ${todo.size} files") + var ok = 0 + var skipped = 0 + var failed = 0 + for (rel in todo) { + when (compress(rel)) { + Outcome.COMPRESSED -> ok++ + Outcome.NOT_SMALLER -> skipped++ + Outcome.FAILED -> failed++ + } + } + log.status("gzip", "finished: $ok compressed, $skipped not smaller, $failed failed") + } + + private enum class Outcome { COMPRESSED, NOT_SMALLER, FAILED } + + private fun compress(rel: String): Outcome { + val src = File(rootDir, rel) + val tmp = File(rootDir, "$rel.gz.tmp") + val dst = File(rootDir, "$rel.gz") + val started = System.currentTimeMillis() + return try { + FileInputStream(src).use { input -> + BestGzip(FileOutputStream(tmp)).use { out -> input.copyTo(out, 64 * 1024) } + } + val secs = (System.currentTimeMillis() - started) / 1000 + if (tmp.length() >= src.length()) { + // Serving it would save nothing, so it never becomes a .gz. + log.status("gzip", "not smaller: $rel ${src.length()} -> ${tmp.length()} bytes; deleted") + tmp.delete() + return Outcome.NOT_SMALLER + } + if (!tmp.renameTo(dst)) throw IOException("couldn't rename ${tmp.name}") + log.status("gzip", "done: $rel ${src.length()} -> ${dst.length()} bytes in $secs s") + // A source zip keeps only its copy, to save space: the server decompresses it for the rare client that + // doesn't take gzip, and for ranges. The copy takes the zip's date, so its ETag and Last-Modified don't + // change. Pages keep both, being tiny; so does a zip of 4 GB or more, since gzip records sizes modulo 4 GB. + if (rel.endsWith(".zip") && src.length() < GZ_SIZE_LIMIT) { + dst.setLastModified(src.lastModified()) + if (src.delete()) log.status("gzip", "kept only the copy: $rel") else log.status("gzip", "couldn't delete $rel; serving both") + } + Outcome.COMPRESSED + } catch (e: Exception) { + tmp.delete() + log.status("gzip", "failed: $rel: ${e.message ?: e.toString()}") + Outcome.FAILED + } + } + + companion object { + /** gzip records the original size modulo 2^32, so a larger zip keeps its original. */ + const val GZ_SIZE_LIMIT = 1L shl 32 + } + + private class BestGzip(out: OutputStream) : GZIPOutputStream(out, 64 * 1024) { + init { def.setLevel(Deflater.BEST_COMPRESSION) } + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/HttpServer.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/HttpServer.kt new file mode 100644 index 000000000..5a436152b --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/HttpServer.kt @@ -0,0 +1,780 @@ +package org.appdevforall.shareyourapps.server + +import java.util.Base64 + +import org.json.JSONObject + +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.net.URLDecoder +import java.io.FilterOutputStream +import java.security.MessageDigest +import java.time.Instant +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec +import kotlin.concurrent.thread + +/** + * Who may see the store. [pin] null means no PIN. A request is authenticated by a valid `ls_auth` + * cookie, or by a `?token=` equal to [token] (the plugin's verify step). + * + * The cookie is the time it was issued and an HMAC of that time made with [cookieSecret], so the + * server itself rejects it after 24 hours — whatever a browser keeps — without a session list. It + * still survives restarts and PIN changes, since the secret doesn't change. + */ +class Auth( + val pin: String?, val cookieSecret: String, val token: String?, + private val now: () -> Long = { System.currentTimeMillis() / 1000 }, +) { + companion object { + val NONE = Auth(null, "", null) + const val LIFETIME_S = 86_400L + } + + /** A fresh cookie value: `.`. */ + fun issueCookie(): String { val t = now(); return "$t.${sign(t)}" } + + fun cookieValid(value: String): Boolean { + if (cookieSecret.isEmpty()) return false + val t = value.substringBefore('.', "").toLongOrNull() ?: return false + val age = now() - t + if (age < -60 || age >= LIFETIME_S) return false // a minute's grace for clock steps + return MessageDigest.isEqual(value.substringAfter('.', "").toByteArray(), sign(t).toByteArray()) + } + + private fun sign(t: Long): String { + val mac = Mac.getInstance("HmacSHA256") + mac.init(SecretKeySpec(cookieSecret.toByteArray(), "HmacSHA256")) + return mac.doFinal(t.toString().toByteArray()).joinToString("") { "%02x".format(it) } + } +} + +/** + * Serves one Store directory. **One main thread decides every response** — it reads the request, + * checks the PIN, cookie and token, routes, and chooses the file — so none of that ever runs + * concurrently. **Sending is left to a sender thread per response,** which writes the response, + * streams any file, writes the log line and closes the connection, so a buyer who stops + * receiving — a paused video, or a phone gone out of range — holds up nobody else. + * + * A sender shares only its last-progress time, which it writes and the main thread reads, and + * the log, whose writes are synchronized. The main thread alone owns the list of senders: it + * forgets finished ones and closes the connection of any that has sent nothing for [stallMs], + * and it also runs [stop]'s shutdown. At [MAX_SENDERS], new requests get a small "busy" page. + * Every response closes its connection, and each request's line and headers must arrive within + * [READ_TIMEOUT_MS], so an idle browser preconnect can't hold the main thread. + */ +class HttpServer( + private val root: File, + private val addresses: List, + private val port: Int, + private val log: StoreLog, + private val auth: Auth = Auth.NONE, + private val storeName: String = "Share Your Apps", + private val stallMs: Long = STALL_MS, + private val clock: () -> Long = System::currentTimeMillis, +) { + companion object { + const val READ_TIMEOUT_MS = 2000 + /** A whole request must arrive within this long of the main thread taking it. */ + const val REQUEST_DEADLINE_MS = 5000L + /** A stalled sender is closed after this long: it holds up nobody, so this only frees resources. */ + const val STALL_MS = 120_000L + /** At most this many responses being sent at once; beyond it, buyers get a "busy" page. */ + const val MAX_SENDERS = 16 + private const val MAX_HEADER_BYTES = 16 * 1024 + private const val MAX_FORM_BYTES = 1024 + /** Wrong PINs a client may enter before it must wait; each wrong PIN after that doubles the wait. */ + const val PIN_FREE_TRIES = 5 + const val PIN_LOCKOUT_MS = 30_000L + private const val PIN_LOCKOUT_MAX_MS = 3_600_000L + const val COOKIE = "ls_auth" + const val COOKIE_MAX_AGE = Auth.LIFETIME_S + private val STATUS = mapOf( + 200 to "OK", 206 to "Partial Content", 302 to "Found", 304 to "Not Modified", 400 to "Bad Request", 403 to "Forbidden", + 404 to "Not Found", 405 to "Method Not Allowed", 409 to "Conflict", 410 to "Gone", 426 to "Upgrade Required", 416 to "Range Not Satisfiable", 429 to "Too Many Requests", 503 to "Service Unavailable", + ) + } + + private val files = StoreFiles(root) + private val sockets = mutableListOf() + /** New connections, and [Stop], for the main thread. */ + private val queue = LinkedBlockingQueue() + private object Stop + private val threads = mutableListOf() + @Volatile private var running = false + /** False once [stopAccepting] has run: the main thread then closes any connection it's handed. */ + @Volatile private var accepting = true + /** The share the owner is showing, if any (design, Appendix E): set by the owner's screen, read by the main thread. */ + @Volatile var share: ShareHost? = null + + /** The responses being sent. The main thread's alone: nothing else reads or changes it. */ + private val senders = mutableListOf() + /** How many responses are being sent, as of the main thread's last tidy-up; for [stopAccepting]'s caller. */ + @Volatile var sending = 0 + private set + + /** The port actually bound (useful when [port] is 0). */ + var boundPort: Int = port + private set + + /** Binds every address. Throws IOException with a readable message if any bind fails. */ + fun start() { + var p = port + try { + for (a in addresses) { + val s = ServerSocket() + sockets += s + s.reuseAddress = true + s.bind(InetSocketAddress(a, p), 50) + if (p == 0) p = s.localPort + } + } catch (e: IOException) { + stop() + throw IOException("Can't listen on port $port: ${e.message}", e) + } + boundPort = p + running = true + for (s in sockets) { + threads += thread(name = "accept-${s.inetAddress.hostAddress}", isDaemon = true) { acceptLoop(s) } + } + threads += thread(name = "main", isDaemon = true) { mainLoop() } + } + + /** + * Stops taking new connections, but lets responses already being sent finish (design, Appendix + * E.5: a copy that expires lets downloads under way finish). Watch [sending] fall to 0, then [stop]. + */ + fun stopAccepting() { + accepting = false + running = false + for (s in sockets) try { s.close() } catch (e: IOException) { } + } + + /** + * Stops listening, and asks the main thread to close every response being sent — it owns the + * senders, so it does that itself — then waits, so the port is truly free when this returns: + * on some platforms, Android's among them, a socket a thread is blocked in accept() on isn't + * released until that thread returns. + */ + fun stop() { + running = false + for (s in sockets) try { s.close() } catch (e: IOException) { } + sockets.clear() + queue.put(Stop) + threads.forEach { try { it.join(3_000) } catch (e: InterruptedException) { } } + threads.clear() + while (true) { + val c = queue.poll() ?: break + if (c is Socket) try { c.close() } catch (e: IOException) { } + } + } + + private fun acceptLoop(s: ServerSocket) { + while (running) { + try { + val c = s.accept() + // On Android, a closed socket keeps listening until a blocked accept() returns, so one + // more connection can arrive after stopAccepting: close it, and end, releasing the port. + if (!running) { try { c.close() } catch (e: IOException) { }; return } + queue.put(c) + } catch (e: IOException) { + if (!running || s.isClosed) return + } catch (e: InterruptedException) { + return + } + } + } + + /** Takes each connection and decides its response, then hands it to a sender; tidies up at least once a second. */ + private fun mainLoop() { + val tick = (stallMs / 4).coerceIn(50, 1000) + while (true) { + val item = try { queue.poll(tick, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { Stop } + reap() + if (item === Stop) break + if (item is Socket) take(item) + } + // Stopping: close every response still being sent, and wait for its sender. + for (s in senders) try { s.x.socket.close() } catch (e: IOException) { } + for (s in senders) try { s.join(1_000) } catch (e: InterruptedException) { } + senders.clear() + } + + private fun take(c: Socket) { + // However a connection got here after stopAccepting — queued just before, or accepted at the + // last moment while Android was still closing the socket — it isn't served. + if (!accepting) { try { c.close() } catch (e: IOException) { }; return } + val x = Exchange(c, c.inetAddress?.hostAddress ?: "-") + try { handle(x) } catch (e: Exception) { x.status = 0 } // one bad request must never stop the server + if (x.status == 0) { try { c.close() } catch (e: IOException) { }; return } + if (senders.size >= MAX_SENDERS) return busy(x) + val sender = Sender(x) + senders += sender + sender.start() + } + + /** + * At [MAX_SENDERS]: a small "busy" page instead, written here — it's small enough that + * writing it can't block — so the main thread never waits for a sender to finish. + */ + private fun busy(x: Exchange) { + val req = x.req ?: return + val reply = Exchange(x.socket, x.client).also { it.req = req } + respondText(reply, req, 503, "The store is busy. Try again in a moment.", mapOf("Retry-After" to "5")) + try { + x.socket.getOutputStream().apply { write(reply.out.toByteArray()); flush() } + log.access(x.client, req.line, 503, reply.inlineBytes, req.headers["referer"], req.headers["user-agent"], 0) + } catch (e: IOException) { + } finally { + try { x.socket.close() } catch (e: IOException) { } + } + } + + /** Forgets finished senders, and closes the connection of any that has sent nothing for [stallMs]. */ + private fun reap() { + senders.removeAll { !it.isAlive } + sending = senders.size + val now = System.currentTimeMillis() + for (s in senders) { + if (s.closing || now - s.lastProgress <= stallMs) continue + s.closing = true + log.status("server", "closed a connection from ${s.x.client} that received nothing for ${stallMs / 1000} s") + try { s.x.socket.close() } catch (e: IOException) { } // its blocked write then fails, and the sender ends + } + } + + /** A socket's input, for reading a request: each read waits no longer than what's left of [deadline]. */ + private class Deadline(private val socket: Socket, private val deadline: Long) : InputStream() { + private val input = socket.getInputStream() + private fun arm() { + val left = deadline - System.currentTimeMillis() + if (left <= 0) throw SocketTimeoutException("the request took too long to arrive") + socket.soTimeout = minOf(READ_TIMEOUT_MS.toLong(), left).toInt().coerceAtLeast(1) + } + override fun read(): Int { arm(); return input.read() } + override fun read(b: ByteArray, off: Int, len: Int): Int { arm(); return input.read(b, off, len) } + } + + /** One request's response, as the main thread decided it, for a sender to send. */ + private class Exchange(val socket: Socket, val client: String) { + var req: Request? = null + /** The head, and any small body. */ + val out = ByteArrayOutputStream() + /** Content made as it's sent, such as an encrypted copy of the store; it writes to what it's given, which it mustn't close. */ + var producer: ((OutputStream) -> Unit)? = null + /** A file to stream after [out], for a GET of a file: [fileCount] bytes from [fileOffset]. */ + var file: File? = null + var fileOffset = 0L + var fileCount = 0L + /** For the log line; 0 means there's no response to send. */ + var status = 0 + var inlineBytes = 0L + } + + /** Sends one response, streams its file, writes its log line and closes its connection. */ + private inner class Sender(val x: Exchange) : Thread("sender") { + /** When it last handed anything to the network; the only thing it shares, read by the main thread. */ + @Volatile var lastProgress = System.currentTimeMillis() + /** Set by the main thread only, once it has closed this sender's connection. */ + var closing = false + /** Bytes handed to the network, headers included: the sender's own, for its log line. */ + var handedOver = 0L + + init { isDaemon = true } + + override fun run() { + val started = System.currentTimeMillis() + try { + val out = BufferedOutputStream(Progress(x.socket.getOutputStream(), this), 64 * 1024) + out.write(x.out.toByteArray()) + x.producer?.let { produce -> produce(object : FilterOutputStream(out) { + override fun write(b: ByteArray, off: Int, len: Int) { out.write(b, off, len) } + override fun close() { flush() } // the sender closes the connection itself + }) } + x.file?.let { f -> + FileInputStream(f).use { input -> + input.channel.position(x.fileOffset) // a range starts partway through + val buf = ByteArray(64 * 1024) + var left = x.fileCount + while (left > 0) { + val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()) + if (n < 0) break + out.write(buf, 0, n); left -= n + } + } + } + out.flush() + } catch (e: Exception) { + // The buyer went away, or the main thread closed a stalled connection. + } finally { + // Logged even when the send failed partway, with the body bytes actually handed to + // the network — so the log shows a download a buyer stopped, as a size smaller than the file's. + val req = x.req + val headLength = x.out.size() - x.inlineBytes + val body = (handedOver - headLength).coerceAtLeast(0) + if (req != null) log.access(x.client, req.line, x.status, body, req.headers["referer"], + req.headers["user-agent"], if (x.file != null || x.producer != null) System.currentTimeMillis() - started else 0) + try { x.socket.close() } catch (e: IOException) { } + } + } + } + + /** + * Notes each chunk actually handed to the network: its time, for the main thread's check on + * stalled senders, and its size, for the log. Writes go out in 8 KB slices, so a send that + * fails partway is counted to within 8 KB. + */ + private class Progress(out: OutputStream, private val sender: Sender) : FilterOutputStream(out) { + override fun write(b: ByteArray, off: Int, len: Int) { + var i = off + while (i < off + len) { + val n = minOf(8 * 1024, off + len - i) + out.write(b, i, n); i += n + sender.handedOver += n + sender.lastProgress = System.currentTimeMillis() + } + } + override fun write(b: Int) { out.write(b); sender.handedOver++; sender.lastProgress = System.currentTimeMillis() } + } + + private class Request( + val method: String, val target: String, val line: String, + val headers: Map, + ) { + val path: String get() = target.substringBefore('?') + fun query(name: String): String? = target.substringAfter('?', "").split('&') + .firstOrNull { it.substringBefore('=') == name }?.substringAfter('=', "") + ?.let { runCatching { URLDecoder.decode(it, "UTF-8") }.getOrNull() } + fun cookie(name: String): String? = headers["cookie"]?.split(';')?.map { it.trim() } + ?.firstOrNull { it.substringBefore('=') == name }?.substringAfter('=', "") + } + + /** Reads the request and decides its response, into [x]; leaves x.status at 0 when there's nothing to send. */ + private fun handle(x: Exchange) { + x.socket.soTimeout = READ_TIMEOUT_MS + // The whole request — headers, and any body — must arrive within REQUEST_DEADLINE_MS, not just + // each read within READ_TIMEOUT_MS: a client sending a byte a second can't hold the main thread. + val input = BufferedInputStream(Deadline(x.socket, System.currentTimeMillis() + REQUEST_DEADLINE_MS)) + + val req = try { + readRequest(input) + } catch (e: SocketTimeoutException) { + return // an idle connection, such as a browser preconnect: close quietly + } ?: return + x.req = req + + if (!files.hasIndex()) { + return respondText(x, req, 503, "This store hasn't been set up yet.") + } + + val path = req.path + // Sellers aren't buyers, so the sharing address comes before the PIN. + if (path.startsWith("/share/")) return shareRoute(input, x, req) + if (path == "/pin") return pinRoute(input, x, req) + if (req.method != "GET" && req.method != "HEAD") { + return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET, HEAD")) + } + if (auth.pin != null && !authenticated(req)) return redirect(x, req, "/pin") + + val relative = when { + path == "/" || path == "/index.html" -> "index.html" + path.startsWith("/f/") -> percentDecode(path.removePrefix("/f/")) + ?: return respondText(x, req, 400, "Bad request.") + else -> return respondText(x, req, 404, "Not found.") + } + val file = files.resolve(relative) + if (file != null) return serveFile(x, req, file, relative) + // A source zip the compressor has replaced by its .gz copy, to save space. + val gzOnly = if (relative.endsWith(".zip")) files.resolve("$relative.gz") else null + if (gzOnly != null) return serveFile(x, req, null, relative, gzOnly) + respondText(x, req, 404, "Not found.") + } + + /** + * The sharing address (design, Appendix E.3): request, reveal, status and copy. Only while the + * owner's screen has a share; otherwise every path answers not found, as if it didn't exist. + */ + private fun shareRoute(input: InputStream, x: Exchange, req: Request) { + // While the owner's screen has a share, open or not, so a seller can still hear "denied" or + // "expired"; each route refuses what it should. Leaving the sharing screen removes the share. + val host = share ?: return respondText(x, req, 404, "Not found.") + val route = req.path.removePrefix("/share/") + // A phone that doesn't have the app yet gets it here: the genuine APK, signed with the server's key. + if (route == "app") return shareApp(x, req, host) + val post = route == "request" || route == "reveal" + if (post && req.method != "POST") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "POST")) + if (!post && req.method != "GET") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET")) + try { + when (route) { + "request" -> { + val body = readJson(input, req) ?: return respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + val (id, ownerKey) = host.request(body.optString("code"), body.optString("name"), + Base64.getDecoder().decode(body.optString("commitment")), body.optInt("protocol", 1)) + log.status("share", "${host.phoneName()} asked for a copy of ${host.storeName}") + respondJson(x, req, 200, JSONObject().put("request", id).put("ownerKey", Base64.getEncoder().encodeToString(ownerKey)) + .put("protocol", ShareHost.PROTOCOL)) + } + "reveal" -> { + val body = readJson(input, req) ?: return respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + host.reveal(body.optString("request"), Base64.getDecoder().decode(body.optString("sellerKey"))) + respondJson(x, req, 200, JSONObject().put("ok", true)) + } + "status" -> { + val state = host.status(req.query("request").orEmpty()) + val reply = JSONObject().put("state", state).put("storeName", host.storeName) + if (state == "allowed") reply.put("expires", host.copyExpiry()?.toString() ?: JSONObject.NULL) + respondJson(x, req, 200, reply) + } + "copy" -> { + val copy = host.copyFor(req.query("request").orEmpty()) + writeHead(x.out, 200, linkedMapOf("Content-Type" to "application/octet-stream", "Cache-Control" to "no-store")) + x.status = 200 + // Encrypted as it's written, so the copy is never stored on this phone. + x.producer = { out -> + try { + SealedOutputStream(out, copy.key).use { SharePackage.write(it, copy.storeDir, copy.description, copy.storeKey) } + } catch (e: Exception) { host.transferFailed(); throw e } + host.sent() + log.status("share", "sent a copy of ${host.storeName} to ${host.phoneName()}") + } + } + else -> respondText(x, req, 404, "Not found.") + } + } catch (e: ShareHost.Refused) { + respondJson(x, req, e.refusal.status, JSONObject().put("error", e.refusal.message)) + } catch (e: IllegalArgumentException) { // bad base64 + respondJson(x, req, 400, JSONObject().put("error", "Bad request.")) + } + } + + private fun shareApp(x: Exchange, req: Request, host: ShareHost) { + if (req.method != "GET" && req.method != "HEAD") return respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET")) + val apk = host.appApk?.takeIf { it.isFile } ?: return respondText(x, req, 404, "Not found.") + writeHead(x.out, 200, linkedMapOf( + "Content-Type" to "application/vnd.android.package-archive", + "Content-Length" to apk.length().toString(), + "Content-Disposition" to "attachment; filename=\"share-your-apps-server.apk\"", + "Cache-Control" to "no-store", + )) + if (req.method == "GET") { x.file = apk; x.fileOffset = 0; x.fileCount = apk.length() } + x.status = 200 + } + + private fun readJson(input: InputStream, req: Request): JSONObject? { + val length = req.headers["content-length"]?.toIntOrNull() ?: return null + if (length < 0 || length > MAX_FORM_BYTES) return null + val body = ByteArray(length); var read = 0 + while (read < length) { val n = input.read(body, read, length - read); if (n < 0) return null; read += n } + return try { JSONObject(String(body, Charsets.UTF_8)) } catch (e: Exception) { null } + } + + private fun respondJson(x: Exchange, req: Request, status: Int, json: JSONObject) { + val bytes = json.toString().toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf("Content-Type" to "application/json", "Content-Length" to bytes.size.toString(), "Cache-Control" to "no-store")) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = if (req.method == "HEAD") 0 else bytes.size.toLong() + } + + private fun authenticated(req: Request): Boolean { + val cookie = req.cookie(COOKIE) + if (cookie != null && auth.cookieValid(cookie)) return true + val token = req.query("token") + return token != null && auth.token != null && same(token, auth.token) + } + + private fun same(a: String, b: String) = MessageDigest.isEqual(a.toByteArray(), b.toByteArray()) + + /** A client's wrong PINs, and until when it must wait. Main thread only, like everything [pinRoute] touches. */ + private class PinFails(var count: Int = 0, var lockedUntil: Long = 0) + private val pinFails = HashMap() + + /** + * GET shows the PIN page (or redirects home if there's nothing to enter); POST checks the PIN. + * After [PIN_FREE_TRIES] wrong PINs a client waits [PIN_LOCKOUT_MS], doubling with each further + * wrong one, so a short PIN can't simply be tried in full. A waiting client is answered at once. + */ + private fun pinRoute(input: InputStream, x: Exchange, req: Request) { + val pin = auth.pin + if (pin == null || authenticated(req)) return redirect(x, req, "/") + when (req.method) { + "GET", "HEAD" -> respondHtml(x, req, pinPage(null)) + "POST" -> { + val entered = readForm(input, req)?.get("pin") + ?: return respondText(x, req, 400, "Bad request.") + val now = clock() + val fails = pinFails[x.client] + if (fails != null && now < fails.lockedUntil) { + val seconds = (fails.lockedUntil - now + 999) / 1000 + return respondHtml(x, req, pinPage("Too many wrong PINs. Try again in $seconds seconds."), 429) + } + if (entered.isNotEmpty() && same(entered, pin)) { + pinFails.remove(x.client) + redirect(x, req, "/", mapOf("Set-Cookie" to + "$COOKIE=${auth.issueCookie()}; Max-Age=$COOKIE_MAX_AGE; Path=/; HttpOnly; SameSite=Lax")) + } else { + // ponytail: per-client only; many addresses guessing together aren't slowed. Add a store-wide budget if that's seen. + if (pinFails.size > 1000) pinFails.clear() + val f = pinFails.getOrPut(x.client) { PinFails() } + f.count++ + if (f.count >= PIN_FREE_TRIES) { + f.lockedUntil = now + minOf(PIN_LOCKOUT_MS shl minOf(f.count - PIN_FREE_TRIES, 20), PIN_LOCKOUT_MAX_MS) + } + respondHtml(x, req, pinPage("That PIN isn't right.")) + } + } + else -> respondText(x, req, 405, "Method not allowed.", mapOf("Allow" to "GET, POST")) + } + } + + private fun readForm(input: InputStream, req: Request): Map? { + val length = req.headers["content-length"]?.toIntOrNull() ?: return null + if (length < 0 || length > MAX_FORM_BYTES) return null + val body = ByteArray(length) + var read = 0 + while (read < length) { + val n = input.read(body, read, length - read) + if (n < 0) return null + read += n + } + return String(body, Charsets.UTF_8).split('&').filter { it.isNotEmpty() }.associate { + val k = it.substringBefore('=') + val v = it.substringAfter('=', "") + k to (runCatching { URLDecoder.decode(v, "UTF-8") }.getOrNull() ?: "") + } + } + + private fun pinPage(error: String?): String { + val name = htmlEscape(storeName) + val err = if (error != null) "

        ${htmlEscape(error)}

        " else "" + return Brand.page(name, "

        $name

        $err" + + "
        " + + "
        ") + } + + private fun redirect(x: Exchange, req: Request, to: String, extra: Map = emptyMap()) { + writeHead(x.out, 302, linkedMapOf("Location" to to, "Content-Length" to "0", "Cache-Control" to "no-store") + extra) + x.status = 302 + } + + private fun respondHtml(x: Exchange, req: Request, html: String, status: Int = 200) { + val bytes = html.toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf( + "Content-Type" to "text/html; charset=utf-8", + "Content-Length" to bytes.size.toString(), + "Cache-Control" to "no-store", + )) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = bytes.size.toLong() + } + + /** + * Sends [file], or its `.gz` copy if the client accepts gzip and one exists. Or, with [file] null, a source zip + * kept only as its copy, [gzOnly]: the copy as-is to a client that accepts gzip, and otherwise the zip's own bytes, + * decompressed on the fly — whole, or a range, skipped to. Its size, date and ETag are the zip's, exactly as they + * were before it was deleted, since the copy has its date, and gzip records its size. + */ + private fun serveFile(x: Exchange, req: Request, file: File?, relative: String, gzOnly: File? = null) { + val name = relative.substringAfterLast('/') + val length = file?.length() ?: StoreFiles.gzipSize(gzOnly!!) + // Each publish copies its files afresh, so a file's time changes whenever its content can have. + val modified = (file ?: gzOnly!!).lastModified() / 1000 * 1000 + // 304 only for this very file of this very store. On Wi-Fi Direct every store is at the same + // address, so a browser's cached page may be another store's: an exact date match, or an + // ETag naming the store, rather than "not modified since", keeps one from confirming another. + val etag = "W/\"${root.name}-$modified-$length\"" + val inm = req.headers["if-none-match"] + val since = req.headers["if-modified-since"]?.let(::parseHttpDate) + val unchanged = if (inm != null) inm.split(',').map { it.trim().removePrefix("W/") }.any { it == "*" || it == etag.removePrefix("W/") } + else since != null && modified == since + if (unchanged) { + writeHead(x.out, 304, linkedMapOf("ETag" to etag, "Last-Modified" to httpDate(modified), "Vary" to "Accept-Encoding", "Cache-Control" to "no-cache")) + x.status = 304 + return + } + // A range request — skipping in a video, or resuming a download — gets just that slice of + // the plain file, never of its gzip copy, whose byte positions differ. If-Range with an old + // date means the browser's copy is stale, so it gets the whole, new file instead. + val range = req.headers["range"]?.takeIf { ifRangeHolds(req.headers["if-range"], modified) }?.let { parseRange(it, length) } + if (range == ByteRange.UNSATISFIABLE) { + writeHead(x.out, 416, linkedMapOf("Content-Range" to "bytes */$length", "Content-Length" to "0", "Accept-Ranges" to "bytes")) + x.status = 416 + return + } + val gz = if (range == null && acceptsGzip(req.headers["accept-encoding"])) (gzOnly ?: files.resolve("$relative.gz")) else null + val body = gz ?: file // null: decompressed from gzOnly, below + val offset = range?.start ?: 0L + val count = range?.let { it.end - it.start + 1 } ?: (body?.length() ?: length) + val headers = linkedMapOf( + "Content-Type" to StoreFiles.contentType(name), + "Content-Length" to count.toString(), + "Accept-Ranges" to "bytes", + "Vary" to "Accept-Encoding", + // Every publish reuses the same addresses — "/" and each product's files — for new + // content, so browsers must check back each time rather than reuse an old copy. + "Cache-Control" to "no-cache", + "Last-Modified" to httpDate(modified), + "ETag" to etag, + ) + if (range != null) headers["Content-Range"] = "bytes ${range.start}-${range.end}/$length" + if (gz != null) headers["Content-Encoding"] = "gzip" + StoreFiles.disposition(name)?.let { headers["Content-Disposition"] = it } + + val status = if (range != null) 206 else 200 + writeHead(x.out, status, headers) + if (req.method == "GET") { + if (body != null) { x.file = body; x.fileOffset = offset; x.fileCount = count } // the sender streams it + else x.producer = { out -> StoreFiles.gunzipSlice(gzOnly!!, offset, count, out) } // the zip, decompressed + } + x.status = status + } + + private fun respondText( + x: Exchange, req: Request, status: Int, message: String, + extra: Map = emptyMap(), + ) { + // The same look as the PIN page: every page a buyer can reach is themed. + val bytes = Brand.page(htmlEscape(storeName).ifEmpty { "Share Your Apps" }, "

        $message

        ").toByteArray(Charsets.UTF_8) + writeHead(x.out, status, linkedMapOf( + "Content-Type" to "text/html; charset=utf-8", + "Content-Length" to bytes.size.toString(), + "Cache-Control" to "no-store", + ) + extra) + if (req.method != "HEAD") x.out.write(bytes) + x.status = status + x.inlineBytes = if (req.method == "HEAD") 0 else bytes.size.toLong() + } + + private fun writeHead(out: OutputStream, status: Int, headers: Map) { + val sb = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: ""}\r\n") + for ((k, v) in headers) sb.append(k).append(": ").append(v).append("\r\n") + sb.append("Connection: close\r\n\r\n") + out.write(sb.toString().toByteArray(Charsets.ISO_8859_1)) + } + + /** Reads the request line and headers. Returns null if the request is malformed or too big. */ + private fun readRequest(input: InputStream): Request? { + val buf = ByteArrayOutputStream() + var last4 = 0 + while (true) { + val b = input.read() + if (b < 0) return null + buf.write(b) + last4 = (last4 shl 8) or b + if (last4 == 0x0d0a0d0a || (last4 and 0xffff) == 0x0a0a) break + if (buf.size() > MAX_HEADER_BYTES) return null + } + val lines = buf.toString("ISO-8859-1").split("\n").map { it.trimEnd('\r') } + val requestLine = lines.firstOrNull() ?: return null + val parts = requestLine.split(' ') + if (parts.size != 3 || !parts[2].startsWith("HTTP/")) return null + val headers = HashMap() + for (l in lines.drop(1)) { + val i = l.indexOf(':') + if (i > 0) headers[l.substring(0, i).trim().lowercase()] = l.substring(i + 1).trim() + } + // The verify token is never written to disk, so it's blanked in the line that gets logged. + val logged = requestLine.replace(Regex("""([?&]token=)[^&\s]*"""), "\$1-") + return Request(parts[0], parts[1], logged, headers) + } +} + +/** An HTTP date, such as "Thu, 24 Sep 2026 10:00:00 GMT". */ +/** A single byte range, inclusive; or [UNSATISFIABLE], for a range that starts past the end. */ +data class ByteRange(val start: Long, val end: Long) { + companion object { val UNSATISFIABLE = ByteRange(-1, -1) } +} + +/** + * A Range header, for a file of [length] bytes, following RFC 9110: a single `bytes=a-b`, `bytes=a-` + * or `bytes=-n`. Several ranges, another unit, or anything malformed returns null, meaning the + * header is ignored and the whole file sent, which the standard allows. A range that starts at or + * past the end is [ByteRange.UNSATISFIABLE]; one that runs past the end is cut short. + */ +fun parseRange(header: String, length: Long): ByteRange? { + val h = header.trim() + if (!h.startsWith("bytes=", ignoreCase = true)) return null + val spec = h.substring(6).trim() + if (',' in spec) return null + val dash = spec.indexOf('-').takeIf { it >= 0 } ?: return null + val a = spec.substring(0, dash).trim(); val b = spec.substring(dash + 1).trim() + if (!a.all(Char::isDigit) || !b.all(Char::isDigit)) return null + return when { + a.isEmpty() && b.isEmpty() -> null + a.isEmpty() -> { // the last n bytes + val n = b.toLongOrNull() ?: return null + if (n == 0L || length == 0L) ByteRange.UNSATISFIABLE else ByteRange(maxOf(0, length - n), length - 1) + } + else -> { + val start = a.toLongOrNull() ?: return null + val end = if (b.isEmpty()) length - 1 else (b.toLongOrNull() ?: return null) + when { + b.isNotEmpty() && end < start -> null + start >= length -> ByteRange.UNSATISFIABLE + else -> ByteRange(start, minOf(end, length - 1)) + } + } + } +} + +/** Whether a range request's If-Range still matches the file: absent, or the file's own date. We send no ETags. */ +fun ifRangeHolds(ifRange: String?, modified: Long): Boolean = ifRange == null || parseHttpDate(ifRange.trim()) == modified + +fun httpDate(millis: Long): String = + DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(millis).atOffset(ZoneOffset.UTC)) + +/** The time an HTTP date names, in milliseconds, or null if it isn't one. */ +fun parseHttpDate(s: String): Long? = + try { ZonedDateTime.parse(s.trim(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() } catch (e: Exception) { null } + +/** True if an Accept-Encoding header accepts gzip (q=0 means refused). */ +fun acceptsGzip(header: String?): Boolean { + if (header == null) return false + return header.split(',').any { part -> + val bits = part.split(';').map { it.trim() } + val coding = bits[0].lowercase() + val q = bits.drop(1).firstOrNull { it.startsWith("q=") }?.substring(2)?.toDoubleOrNull() ?: 1.0 + (coding == "gzip" || coding == "x-gzip") && q > 0.0 + } +} + +/** Decodes %XX escapes in a URL path as UTF-8. Returns null on a malformed escape or a NUL. */ +fun percentDecode(s: String): String? { + val out = ByteArrayOutputStream() + var i = 0 + while (i < s.length) { + val ch = s[i] + if (ch == '%') { + if (i + 2 >= s.length) return null + val v = s.substring(i + 1, i + 3).toIntOrNull(16) ?: return null + out.write(v) + i += 3 + } else { + out.write(ch.toString().toByteArray(Charsets.UTF_8)) + i++ + } + } + val r = out.toString("UTF-8") + return if (r.contains('\u0000')) null else r +} + +fun htmlEscape(s: String): String = + s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/README.md b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/README.md new file mode 100644 index 000000000..5ee749eed --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/README.md @@ -0,0 +1,8 @@ +# Copied from Share Your Apps Server + +These nine files are copies of Share Your Apps Server's own code — its HTTP server and the files it depends on, including the four for sharing a store — from its +`app/src/main/java/org/appdevforall/shareyourapps/server/`. The plugin's end-to-end test uses them to +serve a published store and verify it, exactly as the real server would. + +They're used only by the tests and never ship in the plugin. When the server's versions change, +copy them here again, keeping the two comment lines at the top of each. diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareCrypto.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareCrypto.kt new file mode 100644 index 000000000..d9e21a980 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareCrypto.kt @@ -0,0 +1,194 @@ +package org.appdevforall.shareyourapps.server + +import java.io.DataInputStream +import java.io.EOFException +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.nio.ByteBuffer +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.MessageDigest +import java.security.PrivateKey +import java.security.PublicKey +import java.security.SecureRandom +import java.security.Signature +import java.security.spec.ECGenParameterSpec +import java.security.spec.PKCS8EncodedKeySpec +import java.security.spec.X509EncodedKeySpec +import javax.crypto.Cipher +import javax.crypto.KeyAgreement +import javax.crypto.Mac +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * The cryptography for sharing a store with another seller (design, Appendix E.3), kept in this + * one file so it can be reviewed on its own. P-256 throughout, since Android has it built in back + * to Android 9: ECDSA signs a copy's description with the store's key; ECDH, then HKDF-SHA256, + * derives a key only one pair of phones can know; AES-256-GCM, in numbered chunks, encrypts the + * copy with it. + * + * The exchange, whose check code the owner compares by eye (screen 3 with screens 5 and 6): + * 1. seller → owner: the share code, and a commitment — the hash of the seller's public key; + * 2. owner → seller: the owner's one-time public key; + * 3. seller → owner: the seller's public key, which the owner checks against the commitment. + * Each side's key is fixed before it sees the other's, so someone in the middle can't try keys + * until the four digits match: their chance stays 1 in 10,000. + */ +object ShareCrypto { + private val random = SecureRandom() + + fun newKeyPair(): KeyPair = + KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1"), random) }.generateKeyPair() + + fun publicKey(encoded: ByteArray): PublicKey = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(encoded)) + fun privateKey(encoded: ByteArray): PrivateKey = KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(encoded)) + + fun sign(key: PrivateKey, data: ByteArray): ByteArray = + Signature.getInstance("SHA256withECDSA").run { initSign(key); update(data); sign() } + + fun verify(key: PublicKey, data: ByteArray, signature: ByteArray): Boolean = try { + Signature.getInstance("SHA256withECDSA").run { initVerify(key); update(data); verify(signature) } + } catch (e: Exception) { false } + + fun sha256(vararg parts: ByteArray): ByteArray = + MessageDigest.getInstance("SHA-256").run { parts.forEach { update(it) }; digest() } + + /** A store's identity: its public key's SHA-256, first 10 bytes, in base32 — 16 characters. */ + fun storeId(key: PublicKey): String = Base32.encode(sha256(key.encoded).copyOf(10)) + + /** Step 1's commitment to the seller's public key. */ + fun commitment(sellerPublic: ByteArray): ByteArray = sha256("shareyourapps-commit v1".toByteArray(), sellerPublic) + + fun commitmentHolds(commitment: ByteArray, sellerPublic: ByteArray): Boolean = + MessageDigest.isEqual(commitment, commitment(sellerPublic)) + + /** The four digits both phones show. They match only if both hold the same two public keys and code. */ + fun checkCode(ownerPublic: ByteArray, sellerPublic: ByteArray, code: String): String { + val h = sha256("shareyourapps-check v1".toByteArray(), ownerPublic, sellerPublic, code.toByteArray()) + val n = ByteBuffer.wrap(h, 0, 4).int.toLong() and 0xffffffffL + return "%04d".format(n % 10_000) + } + + /** The key for one pair of phones: ECDH, then HKDF bound to the share code and both public keys. */ + fun sessionKey(own: PrivateKey, theirs: PublicKey, code: String, ownerPublic: ByteArray, sellerPublic: ByteArray): ByteArray { + val secret = KeyAgreement.getInstance("ECDH").run { init(own); doPhase(theirs, true); generateSecret() } + return hkdf(secret, code.toByteArray(), "shareyourapps-share v1".toByteArray() + ownerPublic + sellerPublic, 32) + } + + /** HKDF-SHA256, RFC 5869. */ + fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray { + val prk = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(if (salt.isEmpty()) ByteArray(32) else salt, "HmacSHA256")); doFinal(ikm) } + val out = java.io.ByteArrayOutputStream(); var t = ByteArray(0); var i = 1 + while (out.size() < length) { + t = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(prk, "HmacSHA256")); update(t); update(info); update(i.toByte()); doFinal() } + out.write(t); i++ + } + return out.toByteArray().copyOf(length) + } + + fun randomBytes(n: Int): ByteArray = ByteArray(n).also { random.nextBytes(it) } +} + +/** + * AES-256-GCM over a stream, in chunks of up to 64 KB, so a copy of any size is encrypted without + * holding it in memory. A header of magic bytes and an 8-byte random nonce prefix; then each chunk + * as its length and ciphertext, with nonce = prefix + chunk number, and the number and a "last" + * flag authenticated with it. So altering, reordering, or cutting off the stream all fail. + */ +class SealedOutputStream(private val out: OutputStream, key: ByteArray) : OutputStream() { + private val cipherKey = SecretKeySpec(key, "AES") + private val prefix = ShareCrypto.randomBytes(8) + private val buf = ByteArray(CHUNK); private var n = 0; private var counter = 0; private var closed = false + + init { out.write(MAGIC); out.write(prefix) } + + override fun write(b: Int) { if (n == CHUNK) flushChunk(false); buf[n++] = b.toByte() } + override fun write(b: ByteArray, off: Int, len: Int) { + var i = off; val end = off + len + while (i < end) { + if (n == CHUNK) flushChunk(false) + val k = minOf(CHUNK - n, end - i); System.arraycopy(b, i, buf, n, k); n += k; i += k + } + } + + private fun flushChunk(last: Boolean) { + val c = Cipher.getInstance("AES/GCM/NoPadding") + c.init(Cipher.ENCRYPT_MODE, cipherKey, GCMParameterSpec(128, nonce(prefix, counter))) + c.updateAAD(aad(counter, last)) + val sealed = c.doFinal(buf, 0, n) + out.write(ByteBuffer.allocate(4).putInt(sealed.size).array()); out.write(sealed) + counter++; n = 0 + } + + /** Writes the last chunk — possibly empty — so the reader knows the stream really ended. */ + override fun close() { if (closed) return; closed = true; flushChunk(true); out.flush(); out.close() } + + companion object { + const val CHUNK = 64 * 1024 + val MAGIC = "LSC1".toByteArray() + fun nonce(prefix: ByteArray, counter: Int): ByteArray = prefix + ByteBuffer.allocate(4).putInt(counter).array() + fun aad(counter: Int, last: Boolean): ByteArray = ByteBuffer.allocate(5).putInt(counter).put(if (last) 1 else 0).array() + } +} + +/** Reads a [SealedOutputStream]'s stream; any altered, reordered or missing chunk throws IOException. */ +class SealedInputStream(input: InputStream, key: ByteArray) : InputStream() { + private val src = DataInputStream(input) + private val cipherKey = SecretKeySpec(key, "AES") + private val prefix: ByteArray + private var plain = ByteArray(0); private var pos = 0; private var counter = 0; private var ended = false + + init { + val magic = ByteArray(4); src.readFully(magic) + if (!magic.contentEquals(SealedOutputStream.MAGIC)) throw IOException("not a sealed Share Your Apps copy") + prefix = ByteArray(8); src.readFully(prefix) + } + + private fun nextChunk(): Boolean { + if (ended) return false + val len = try { src.readInt() } catch (e: EOFException) { throw IOException("the copy was cut off") } + if (len < 16 || len > SealedOutputStream.CHUNK + 16) throw IOException("a chunk of the copy is damaged") + val sealed = ByteArray(len); try { src.readFully(sealed) } catch (e: EOFException) { throw IOException("the copy was cut off") } + // A chunk authenticates as the last, or not; try the ordinary case first. + plain = open(sealed, false) ?: open(sealed, true)?.also { ended = true } ?: throw IOException("a chunk of the copy failed its check") + pos = 0; counter++ + if (ended && src.read() != -1) throw IOException("the copy has data after its end") + return true + } + + private fun open(sealed: ByteArray, last: Boolean): ByteArray? = try { + Cipher.getInstance("AES/GCM/NoPadding").run { + init(Cipher.DECRYPT_MODE, cipherKey, GCMParameterSpec(128, SealedOutputStream.nonce(prefix, counter))) + updateAAD(SealedOutputStream.aad(counter, last)); doFinal(sealed) + } + } catch (e: javax.crypto.AEADBadTagException) { null } + + override fun read(): Int { + while (pos >= plain.size) if (!nextChunk()) return -1 + return plain[pos++].toInt() and 0xff + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (len == 0) return 0 + while (pos >= plain.size) if (!nextChunk()) return -1 + val k = minOf(len, plain.size - pos); System.arraycopy(plain, pos, b, off, k); pos += k; return k + } + + /** True once the last chunk has been read and fully consumed: the copy arrived whole. */ + val complete: Boolean get() = ended && pos >= plain.size +} + +/** RFC 4648 base32, upper case, without padding. */ +object Base32 { + private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + fun encode(b: ByteArray): String { + val sb = StringBuilder(); var buffer = 0; var bits = 0 + for (x in b) { buffer = (buffer shl 8) or (x.toInt() and 0xff); bits += 8 + while (bits >= 5) { sb.append(ALPHABET[(buffer shr (bits - 5)) and 31]); bits -= 5 } } + if (bits > 0) sb.append(ALPHABET[(buffer shl (5 - bits)) and 31]) + return sb.toString() + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareHost.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareHost.kt new file mode 100644 index 000000000..12f78cccb --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareHost.kt @@ -0,0 +1,145 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.security.KeyPair +import java.time.Instant + +/** + * The owner's side of sharing a store (design, Appendix E.2–E.3): one share at a time, for one + * phone. The server's main thread answers the seller's requests through it, and the owner's screen + * reads and decides through it, so its methods are synchronized — the only lock besides the log's, + * held only for a moment each time. + * + * A share opens with a new code, good for [CODE_LIFETIME_MS]. The seller's server asks with the + * code, its phone's name and a commitment to its key; then reveals the key. The owner sees the name + * and the check code, and allows — choosing the copy's expiry — or denies. An allowed copy can be + * downloaded until one download completes; then the share is done. + */ +class ShareHost( + val storeDir: File, + val storeName: String, + private val storeKey: KeyPair, + private val now: () -> Long = System::currentTimeMillis, +) { + enum class State { OPEN, ASKED, REVEALED, ALLOWED, DENIED, DONE, CLOSED } + + /** Why a request was refused; the sharing address turns each into an HTTP status. */ + enum class Refusal(val status: Int, val message: String) { + WRONG_CODE(404, "That code isn't being shown here."), + EXPIRED(410, "That code has expired. Ask the owner for a new one."), + TAKEN(409, "Another phone is already using that code."), + BAD_KEY(403, "This phone's key didn't match what it promised."), + NOT_ALLOWED(403, "The owner hasn't allowed this copy."), + SELLER_OLDER(426, "This phone's Share Your Apps Server is older than the owner's. Get the newer one from the owner's share screen — the small QR code — then try again."), + SELLER_NEWER(426, "The owner's Share Your Apps Server is older than this phone's. The owner needs to update it first."), + UNKNOWN(404, "That request isn't known here."), + } + + class Refused(val refusal: Refusal) : Exception(refusal.message) + + /** What the owner's screen shows while deciding: the phone's name and the check code. */ + class Pending(val phoneName: String, val checkCode: String) + + /** An allowed copy, ready to stream: its session key and signed description. */ + class Copy(val key: ByteArray, val description: SharePackage.Description, val storeKey: KeyPair, val storeDir: File) + + /** The server's own installed APK, offered at /share/app to a phone that doesn't have the app yet; null offers nothing. */ + @Volatile var appApk: File? = null + + val code: String = ShareCodes.normalize(ShareCodes.newCode())!! + val displayCode: String get() = ShareCodes.display(code) + private val openedAt = now() + val expiresAt: Long = openedAt + CODE_LIFETIME_MS + + private var state = State.OPEN + private var wrongGuesses = 0 + private var requestId: String? = null + private var phoneName = "" + private var commitment = ByteArray(0) + private var ownerKey: KeyPair? = null + private var checkCode: String? = null + private var sessionKey: ByteArray? = null + private var copyExpires: Instant? = null + + @Synchronized fun state(): State = if (state in LIVE && now() >= expiresAt) State.CLOSED.also { state = it } else state + + /** Whether the sharing address should answer at all. */ + @Synchronized fun isOpen(): Boolean = state() in LIVE || state == State.ALLOWED + + /** Step 1: the code, the phone's name and a commitment. Returns the request's id and the owner's one-time public key. */ + @Synchronized fun request(codeInput: String, name: String, commitment: ByteArray, protocol: Int = PROTOCOL): Pair { + if (state() == State.CLOSED && now() >= expiresAt) throw Refused(Refusal.EXPIRED) + if (!isOpen()) throw Refused(Refusal.WRONG_CODE) + if (ShareCodes.normalize(codeInput) != code) { + if (++wrongGuesses >= MAX_WRONG_GUESSES) state = State.CLOSED // guessing can't go on + throw Refused(Refusal.WRONG_CODE) + } + // After the code, so strangers can't probe which version a phone runs. + if (protocol < PROTOCOL) throw Refused(Refusal.SELLER_OLDER) + if (protocol > PROTOCOL) throw Refused(Refusal.SELLER_NEWER) + if (state != State.OPEN) throw Refused(Refusal.TAKEN) + val id = Base32.encode(ShareCrypto.randomBytes(15)) + val key = ShareCrypto.newKeyPair() + requestId = id; phoneName = name.trim().take(40).ifEmpty { "A phone" }; this.commitment = commitment; ownerKey = key + state = State.ASKED + return id to key.public.encoded + } + + /** Step 3: the seller's key, checked against its commitment. Returns the check code. */ + @Synchronized fun reveal(id: String, sellerPublic: ByteArray): String { + if (id != requestId || state() != State.ASKED) throw Refused(Refusal.UNKNOWN) + if (!ShareCrypto.commitmentHolds(commitment, sellerPublic)) { state = State.CLOSED; throw Refused(Refusal.BAD_KEY) } + val owner = ownerKey!! + val seller = try { ShareCrypto.publicKey(sellerPublic) } catch (e: Exception) { state = State.CLOSED; throw Refused(Refusal.BAD_KEY) } + checkCode = ShareCrypto.checkCode(owner.public.encoded, sellerPublic, code) + sessionKey = ShareCrypto.sessionKey(owner.private, seller, code, owner.public.encoded, sellerPublic) + state = State.REVEALED + return checkCode!! + } + + /** For the owner's screen: who's asking, once their key is revealed. */ + @Synchronized fun pending(): Pending? = if (state() == State.REVEALED) Pending(phoneName, checkCode!!) else null + + @Synchronized fun allow(expires: Instant?) { if (state() == State.REVEALED) { copyExpires = expires; state = State.ALLOWED } } + @Synchronized fun deny() { if (state() in LIVE) state = State.DENIED } + @Synchronized fun close() { if (state != State.DONE) state = State.CLOSED } + + /** What the seller's server hears when it asks: waiting, allowed, denied or expired. */ + @Synchronized fun status(id: String): String { + if (id != requestId) throw Refused(Refusal.UNKNOWN) + return when (state()) { + State.ASKED, State.REVEALED -> "waiting" + State.ALLOWED, State.DONE -> "allowed" + State.DENIED -> "denied" + else -> "expired" + } + } + + @Synchronized fun copyExpiry(): Instant? = copyExpires + + /** The copy to stream, only once allowed. */ + @Synchronized fun copyFor(id: String): Copy { + if (id != requestId) throw Refused(Refusal.UNKNOWN) + if (state() != State.ALLOWED) throw Refused(Refusal.NOT_ALLOWED) + val description = SharePackage.describe(storeDir, storeName, storeKey, Instant.ofEpochMilli(now()), copyExpires) + return Copy(sessionKey!!, description, storeKey, storeDir) + } + + private var failures = 0 + /** A transfer of the allowed copy failed partway; the seller may try again while the share is open. */ + @Synchronized fun transferFailed() { failures++ } + @Synchronized fun failures(): Int = failures + + /** One download finished: the share is done, and the code can't be used again. */ + @Synchronized fun sent() { if (state == State.ALLOWED) state = State.DONE } + + @Synchronized fun phoneName(): String = phoneName + + companion object { + const val CODE_LIFETIME_MS = 10 * 60 * 1000L + const val MAX_WRONG_GUESSES = 5 + /** The sharing protocol's version; both phones must match. Raise it with any change to the exchange or the copy's format. */ + const val PROTOCOL = 1 + private val LIVE = setOf(State.OPEN, State.ASKED, State.REVEALED) + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/SharePackage.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/SharePackage.kt new file mode 100644 index 000000000..52b39fd00 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/SharePackage.kt @@ -0,0 +1,135 @@ +package org.appdevforall.shareyourapps.server + +import org.json.JSONArray +import org.json.JSONObject +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.security.KeyPair +import java.time.Instant +import java.util.Base64 + +/** + * A copy of a published store (design, Appendix E): its signed description, then its files. The + * whole copy travels inside a [SealedOutputStream], so this layer only has to describe and order + * the files, and refuse anything unsafe when importing. + * + * The description is JSON: format, storeId, storeName, storeKey (the store's public key, X.509, + * base64), created, expires (null for never), and files, each with its path and size. + */ +object SharePackage { + const val FORMAT = 1 + const val MAX_DESCRIPTION = 4 * 1024 * 1024 + + class Description(val json: JSONObject) { + val storeId: String get() = json.getString("storeId") + val storeName: String get() = json.getString("storeName") + val storeKey: ByteArray get() = Base64.getDecoder().decode(json.getString("storeKey")) + val created: Instant get() = Instant.parse(json.getString("created")) + val expires: Instant? get() = if (json.isNull("expires")) null else Instant.parse(json.getString("expires")) + val files: List> get() = json.getJSONArray("files").let { a -> (0 until a.length()).map { a.getJSONObject(it).let { f -> f.getString("path") to f.getLong("size") } } } + val totalBytes: Long get() = files.sumOf { it.second } + } + + /** Every file of a published store, by path under it, in a fixed order. */ + fun filesOf(storeDir: File): List> = + // Never a temporary file, such as the compressor's .gz.tmp, which may vanish while it's being shared. + storeDir.walkTopDown().filter { it.isFile && !it.name.endsWith(".tmp") }.map { it.relativeTo(storeDir).invariantSeparatorsPath to it }.sortedBy { it.first }.toList() + + fun describe(storeDir: File, storeName: String, storeKey: KeyPair, created: Instant, expires: Instant?): Description { + val files = JSONArray(); filesOf(storeDir).forEach { (p, f) -> files.put(JSONObject().put("path", p).put("size", f.length())) } + return Description(JSONObject() + .put("format", FORMAT).put("storeId", ShareCrypto.storeId(storeKey.public)).put("storeName", storeName) + .put("storeKey", Base64.getEncoder().encodeToString(storeKey.public.encoded)) + .put("created", created.toString()).put("expires", expires?.toString() ?: JSONObject.NULL).put("files", files)) + } + + /** Writes the signed description, then every file it lists, to [out] — normally a SealedOutputStream. */ + fun write(out: OutputStream, storeDir: File, description: Description, storeKey: KeyPair) { + val d = DataOutputStream(out) + val bytes = description.json.toString().toByteArray(Charsets.UTF_8) + val signature = ShareCrypto.sign(storeKey.private, bytes) + d.writeInt(bytes.size); d.write(bytes); d.writeInt(signature.size); d.write(signature) + val buf = ByteArray(64 * 1024) + for ((path, size) in description.files) { + // A source zip the compressor replaced by its .gz copy after the listing: the same bytes, decompressed. + val f = File(storeDir, path); val gz = File(storeDir, "$path.gz") + val source: InputStream = if (!f.exists() && path.endsWith(".zip") && gz.isFile) java.util.zip.GZIPInputStream(FileInputStream(gz), 64 * 1024) else FileInputStream(f) + source.use { input -> + var left = size + while (left > 0) { val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) throw IOException("$path shrank while being shared"); d.write(buf, 0, n); left -= n } + } + } + d.flush() + } + + /** Reads just the signed description, checking its signature; throws IOException if it's wrong. */ + fun readDescription(input: InputStream): Description { + val d = DataInputStream(input) + val len = d.readInt(); if (len <= 0 || len > MAX_DESCRIPTION) throw IOException("the copy's description is damaged") + val bytes = ByteArray(len).also { d.readFully(it) } + val sigLen = d.readInt(); if (sigLen <= 0 || sigLen > 256) throw IOException("the copy's signature is damaged") + val signature = ByteArray(sigLen).also { d.readFully(it) } + val desc = try { Description(JSONObject(String(bytes, Charsets.UTF_8))) } catch (e: Exception) { throw IOException("the copy's description can't be read") } + if (desc.json.optInt("format") != FORMAT) throw IOException("this copy was made by a newer Share Your Apps Server") + val key = try { ShareCrypto.publicKey(desc.storeKey) } catch (e: Exception) { throw IOException("the copy's store key can't be read") } + if (ShareCrypto.storeId(key) != desc.storeId) throw IOException("the copy's store identity doesn't match its key") + if (!ShareCrypto.verify(key, bytes, signature)) throw IOException("the copy's signature doesn't match") + desc.files.forEach { (p, s) -> if (!safePath(p) || s < 0) throw IOException("the copy lists an unsafe file: $p") } + if (desc.files.map { it.first }.toSet().size != desc.files.size) throw IOException("the copy lists a file twice") + return desc + } + + /** A path that stays inside the store: relative, with no empty, "." or ".." parts, and no backslashes. */ + fun safePath(p: String): Boolean = + p.isNotEmpty() && !p.startsWith("/") && '\\' !in p && '\u0000' !in p && p.split('/').none { it.isEmpty() || it == "." || it == ".." } + + /** + * Imports a copy from [input], already decrypted, into [destParent]/. Everything goes + * into a temporary folder first, renamed into place only once the last file is saved, so a store + * is either complete or absent. The free space — [usableSpace], if given, else the phone's — is + * checked against the description's total first. + * [accept] sees the description before any file is written, and can refuse it by throwing. + */ + fun import(input: InputStream, destParent: File, usableSpace: Long? = null, accept: (Description) -> Unit = {}, + progress: (written: Long, total: Long) -> Unit = { _, _ -> }): Pair { + val desc = readDescription(input) + accept(desc) + // A folder that doesn't exist yet reports no space, so measure the nearest one that does. + val space = usableSpace ?: generateSequence(destParent.absoluteFile) { it.parentFile }.first { it.exists() }.usableSpace + if (desc.totalBytes + 1024 * 1024 > space) throw IOException("there isn't enough space on this phone for the copy") + destParent.mkdirs() + val tmp = File(destParent, ".incoming-" + Base32.encode(ShareCrypto.randomBytes(5))) + try { + val buf = ByteArray(64 * 1024) + var written = 0L + progress(0, desc.totalBytes) + for ((path, size) in desc.files) { + val f = File(tmp, path); f.parentFile?.mkdirs() + if (!f.canonicalPath.startsWith(tmp.canonicalPath + File.separator)) throw IOException("the copy lists an unsafe file: $path") + FileOutputStream(f).use { out -> + var left = size + while (left > 0) { + val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) throw IOException("the copy was cut off") + out.write(buf, 0, n); left -= n; written += n; progress(written, desc.totalBytes) + } + } + } + if (input.read() != -1) throw IOException("the copy has more data than it lists") + if (input is SealedInputStream && !input.complete) throw IOException("the copy was cut off") + val dest = File(destParent, desc.storeId) + val old = File(destParent, ".replaced-" + desc.storeId) + if (dest.exists()) { old.deleteRecursively(); if (!dest.renameTo(old)) throw IOException("the previous copy couldn't be moved aside") } + if (!tmp.renameTo(dest)) { old.renameTo(dest); throw IOException("the copy couldn't be put in place") } + old.deleteRecursively() + return desc to dest + } catch (e: Exception) { + tmp.deleteRecursively(); throw e + } + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareRules.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareRules.kt new file mode 100644 index 000000000..5233ecd73 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/ShareRules.kt @@ -0,0 +1,167 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import org.json.JSONObject +import java.time.Instant +import java.security.KeyPair + +/** + * Share codes, as the owner's screen shows them and a seller types them: LS-XXXX-XXXX, from + * Crockford's base32, which leaves out I, L, O and U. Reading one forgives case, spaces, dashes, + * the LS prefix, and the look-alikes O for 0 and I or L for 1. + */ +object ShareCodes { + private const val ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + + fun newCode(): String { + val b = ShareCrypto.randomBytes(8) + val chars = b.map { ALPHABET[(it.toInt() and 0xff) % 32] }.joinToString("") + return "LS-${chars.take(4)}-${chars.drop(4)}" + } + + /** The code's 8 characters, or null if the input isn't one. */ + fun normalize(input: String): String? { + var s = input.uppercase().filter { it.isLetterOrDigit() } + if (s.startsWith("LS") && s.length == 10) s = s.drop(2) + s = s.map { when (it) { 'O' -> '0'; 'I', 'L' -> '1'; else -> it } }.joinToString("") + return s.takeIf { it.length == 8 && it.all { c -> c in ALPHABET } } + } + + fun display(normalized: String): String = "LS-${normalized.take(4)}-${normalized.drop(4)}" +} + +/** + * A copy's expiry, against a phone clock that can be set back (design, Appendix E.5). The latest + * time ever seen is kept in [stateFile]. A clock up to five minutes behind it is an ordinary + * correction; further behind, the copy expires at once, and the caller deletes it. + */ +class ExpiryClock(private val stateFile: File) { + enum class Status { OK, EXPIRED, CLOCK_SET_BACK } + + /** The latest time this phone's clock has shown, in epoch milliseconds, or 0. */ + fun latestSeen(): Long = try { stateFile.readText().trim().toLong() } catch (e: Exception) { 0L } + + fun check(nowMs: Long, expiresMs: Long?): Status { + val latest = latestSeen() + if (latest > 0 && nowMs < latest - ALLOWED_BACK_MS) return Status.CLOCK_SET_BACK + if (nowMs > latest) { + stateFile.parentFile?.mkdirs() + val tmp = File(stateFile.path + ".tmp"); tmp.writeText(nowMs.toString()); tmp.renameTo(stateFile) + } + return if (expiresMs != null && nowMs >= expiresMs) Status.EXPIRED else Status.OK + } + + /** + * Starts again from [nowMs], for a fresh copy: the rule stops a seller extending a copy they + * already have, and a clock once set too far ahead mustn't condemn every copy imported later. + */ + fun restart(nowMs: Long) { + stateFile.parentFile?.mkdirs() + val tmp = File(stateFile.path + ".tmp"); tmp.writeText(nowMs.toString()); tmp.renameTo(stateFile) + } + + companion object { const val ALLOWED_BACK_MS = 5 * 60 * 1000L } +} + +/** + * The store's key pair (design, Appendix E.3): made once, and kept in the app's private storage. + * Each file is written to a temporary name, then renamed, so a crash can't leave half a key. + * Losing it needs no recovery: a new key simply makes a new store identity. + */ +object StoreKeyFile { + fun loadOrCreate(dir: File): KeyPair { + val pub = File(dir, "store-key.pub"); val priv = File(dir, "store-key.p8") + if (pub.isFile && priv.isFile) try { + return KeyPair(ShareCrypto.publicKey(pub.readBytes()), ShareCrypto.privateKey(priv.readBytes())) + } catch (e: Exception) { } + val k = ShareCrypto.newKeyPair() + dir.mkdirs() + write(priv, k.private.encoded); write(pub, k.public.encoded) + return k + } + + private fun write(f: File, bytes: ByteArray) { + val tmp = File(f.path + ".tmp"); tmp.writeBytes(bytes) + if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) } + } +} + +/** + * The link a share's QR code holds: shareyourapps-share://
        :/. A phone's own camera + * app recognises it, and opening it takes the seller straight to importing, with the code filled in. + */ +object ShareLink { + const val SCHEME = "shareyourapps-share" + + fun make(address: String, port: Int, code: String): String = "$SCHEME://$address:$port/${ShareCodes.display(code)}" + + /** The address, port and code, or null if the text isn't a share link. */ + fun parse(link: String): Triple? { + val m = Regex("^$SCHEME://([0-9.]{7,15}):(\\d{1,5})/([A-Za-z0-9-]+)/?$").matchEntire(link.trim()) ?: return null + val (address, port, code) = m.destructured + val p = port.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null + val c = ShareCodes.normalize(code) ?: return null + if (address.split('.').let { it.size != 4 || it.any { o -> (o.toIntOrNull() ?: 256) > 255 } }) return null + return Triple(address, p, c) + } +} + +/** + * A copy's expiry, applied (design, Appendix E.5). A copy is due on its date, or at once if the + * phone's clock has been set back more than five minutes. Then it's deleted, and a notice left for + * the seller — screen 8, "A store has expired" — until they dismiss it. The two cases look the same + * to the seller and in the log: nothing says which it was, so nothing teaches how the rule works. + * + * Copies live in the imported folder as /, with their description beside them as + * .json. The notice is [NOTICE], in the same folder. + */ +object CopyExpiry { + const val NOTICE = "expired-notice.json" + + class Expired(val storeName: String, val expires: Instant?, val clockSetBack: Boolean) + + /** Every copy's description in [importedDir]: every .json except the notice. */ + fun copies(importedDir: File): List = + importedDir.listFiles { f -> f.isFile && f.name.endsWith(".json") && f.name != NOTICE }.orEmpty().mapNotNull { f -> + try { SharePackage.Description(JSONObject(f.readText())).also { it.storeId; it.storeName } } catch (e: Exception) { null } + } + + /** Whether [copy] is still fine, due, or on a phone whose clock was set back. Updates the clock's latest time. */ + fun status(copy: SharePackage.Description, clock: ExpiryClock, nowMs: Long = System.currentTimeMillis()): ExpiryClock.Status { + val s = clock.check(nowMs, copy.expires?.toEpochMilli()) + // A copy that never expires has no date to extend, so the clock rule spares it. + return if (copy.expires == null && s == ExpiryClock.Status.CLOCK_SET_BACK) ExpiryClock.Status.OK else s + } + + /** Deletes [copy] and leaves the notice. */ + fun delete(importedDir: File, copy: SharePackage.Description, clockSetBack: Boolean): Expired { + File(importedDir, copy.storeId).deleteRecursively() + File(importedDir, "${copy.storeId}.json").delete() + val e = Expired(copy.storeName, copy.expires, clockSetBack) + val tmp = File(importedDir, "$NOTICE.tmp") + tmp.writeText(JSONObject().put("storeName", e.storeName).toString()) // just the name: nothing says why + tmp.renameTo(File(importedDir, NOTICE)) + return e + } + + /** Checks every copy, deleting any that's due; returns the last one deleted, or null. */ + fun enforce(importedDir: File, clock: ExpiryClock, nowMs: Long = System.currentTimeMillis()): Expired? { + var last: Expired? = null + for (c in copies(importedDir)) { + val s = status(c, clock, nowMs) + if (s != ExpiryClock.Status.OK) last = delete(importedDir, c, s == ExpiryClock.Status.CLOCK_SET_BACK) + } + return last + } + + /** The notice left by a deleted copy, until the seller dismisses it. */ + fun notice(importedDir: File): Expired? = try { + val j = JSONObject(File(importedDir, NOTICE).readText()) + Expired(j.getString("storeName"), null, false) + } catch (e: Exception) { null } + + fun dismiss(importedDir: File) { File(importedDir, NOTICE).delete() } + + /** Where the expiry clock keeps the latest time it has seen: outside the imported folder, so it outlives copies. */ + fun clockFile(filesDir: File) = File(filesDir, "share/latest-time") +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreFiles.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreFiles.kt new file mode 100644 index 000000000..5b7df5755 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreFiles.kt @@ -0,0 +1,77 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.IOException + +/** + * The only way the server finds files to serve. Every request path is resolved against the + * Store directory's canonical path — which follows symlinks — and anything that doesn't + * land inside it is refused. + */ +class StoreFiles(root: File) { + + private val rootDir: File = root.canonicalFile + private val rootPrefix: String = rootDir.path + File.separator + + fun hasIndex(): Boolean = resolve("index.html") != null + + /** The regular file at [relative] inside the Store directory, or null. */ + fun resolve(relative: String): File? { + if (relative.isEmpty() || relative.startsWith("/") || relative.contains('\u0000')) return null + if (relative.split('/').any { it == ".." }) return null + val f = try { File(rootDir, relative).canonicalFile } catch (e: IOException) { return null } + if (!f.path.startsWith(rootPrefix)) return null + return if (f.isFile) f else null + } + + companion object { + /** A .gz file's original size, from its last four bytes — modulo 4 GB, so only for smaller files. */ + fun gzipSize(gz: File): Long = java.io.RandomAccessFile(gz, "r").use { f -> + f.seek(f.length() - 4); val b = ByteArray(4); f.readFully(b) + (b[0].toLong() and 0xff) or ((b[1].toLong() and 0xff) shl 8) or ((b[2].toLong() and 0xff) shl 16) or ((b[3].toLong() and 0xff) shl 24) + } + + /** Writes [count] bytes of [gz]'s original contents, from [offset], decompressing it on the way. */ + fun gunzipSlice(gz: File, offset: Long, count: Long, out: java.io.OutputStream) { + java.util.zip.GZIPInputStream(java.io.BufferedInputStream(java.io.FileInputStream(gz), 64 * 1024), 64 * 1024).use { input -> + var skip = offset + while (skip > 0) { val n = input.skip(skip); if (n <= 0) { if (input.read() < 0) return; skip-- } else skip -= n } + val buf = ByteArray(64 * 1024); var left = count + while (left > 0) { val n = input.read(buf, 0, minOf(buf.size.toLong(), left).toInt()); if (n < 0) break; out.write(buf, 0, n); left -= n } + } + } + + private val TYPES = mapOf( + "apk" to "application/vnd.android.package-archive", + "zip" to "application/zip", + "html" to "text/html; charset=utf-8", "htm" to "text/html; charset=utf-8", + "txt" to "text/plain; charset=utf-8", + "css" to "text/css", "js" to "text/javascript", "json" to "application/json", + "png" to "image/png", "jpg" to "image/jpeg", "jpeg" to "image/jpeg", + "gif" to "image/gif", "webp" to "image/webp", "svg" to "image/svg+xml", + "ico" to "image/x-icon", + "mp4" to "video/mp4", "webm" to "video/webm", + "mp3" to "audio/mpeg", "ogg" to "audio/ogg", "wav" to "audio/wav", "m4a" to "audio/mp4", + ) + + fun contentType(name: String): String = + TYPES[name.substringAfterLast('.', "").lowercase()] ?: "application/octet-stream" + + /** APKs and zips download under their real name; everything else displays inline. */ + fun disposition(name: String): String? { + val ext = name.substringAfterLast('.', "").lowercase() + if (ext != "apk" && ext != "zip") return null + val ascii = name.map { if (it.code in 0x20..0x7e && it != '"' && it != '\\') it else '_' } + .joinToString("") + return "attachment; filename=\"$ascii\"; filename*=UTF-8''${pctEncode(name)}" + } + + private fun pctEncode(s: String): String = buildString { + for (b in s.toByteArray(Charsets.UTF_8)) { + val c = b.toInt() and 0xff + if (c.toChar().isLetterOrDigit() && c < 0x80 || c.toChar() in "-._~") append(c.toChar()) + else append('%').append("%02X".format(c)) + } + } + } +} diff --git a/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreLog.kt b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreLog.kt new file mode 100644 index 000000000..a77401db8 --- /dev/null +++ b/plugins/Share-Your-Apps/src/test/kotlin/org/appdevforall/shareyourapps/server/StoreLog.kt @@ -0,0 +1,81 @@ +package org.appdevforall.shareyourapps.server + +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * The access log. Thread-safe: every write and every rotation happen under one lock, + * so no line can land in a file that is being closed or renamed. + * + * Keeps at most five files: access.log plus access.log.1 … access.log.4. + * maxBytes = 0 turns logging off. + */ +class StoreLog(private val dir: File, private val maxBytes: Long) { + + companion object { + const val FILE_NAME = "access.log" + const val KEEP = 5 + } + + private val file = File(dir, FILE_NAME) + private var out: FileOutputStream? = null + private val dateFormat = SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US) + + @Synchronized + fun write(line: String) { + if (maxBytes <= 0) return + try { + val o = out ?: open().also { out = it } + o.write((line + "\n").toByteArray(Charsets.UTF_8)) + o.flush() + if (file.length() >= maxBytes) rotate() + } catch (e: IOException) { + // Logging must never break serving. + } + } + + /** A plain-text status line, e.g. `[server] serving Store_12345678 on 192.168.1.5:6175`. */ + fun status(tag: String, message: String) = write("[$tag] $message") + + /** One Apache combined-format line, plus the transfer rate. */ + @Synchronized + fun access( + client: String, requestLine: String, status: Int, bytes: Long, + referer: String?, userAgent: String?, millis: Long, + ) { + val rate = if (millis > 0) bytes * 1000 / millis else bytes + val size = if (bytes > 0) bytes.toString() else "-" + write( + "$client - - [${dateFormat.format(Date())}] \"${q(requestLine)}\" $status $size " + + "\"${q(referer ?: "-")}\" \"${q(userAgent ?: "-")}\" ${rate}B/s" + ) + } + + @Synchronized + fun close() { + try { out?.close() } catch (e: IOException) { } + out = null + } + + private fun open(): FileOutputStream { + dir.mkdirs() + return FileOutputStream(file, true) + } + + private fun rotate() { + try { out?.close() } catch (e: IOException) { } + out = null + File(dir, "$FILE_NAME.${KEEP - 1}").delete() + for (i in KEEP - 2 downTo 1) { + val f = File(dir, "$FILE_NAME.$i") + if (f.exists()) f.renameTo(File(dir, "$FILE_NAME.${i + 1}")) + } + file.renameTo(File(dir, "$FILE_NAME.1")) + } + + private fun q(s: String) = s.replace("\\", "\\\\").replace("\"", "\\\"") +} diff --git a/plugins/Share-Your-Apps/templates/README.md b/plugins/Share-Your-Apps/templates/README.md new file mode 100644 index 000000000..a653b7767 --- /dev/null +++ b/plugins/Share-Your-Apps/templates/README.md @@ -0,0 +1,60 @@ +# Store page templates + +Pebble templates for the store page. The plugin ships its own default; these are alternatives, and an annotated copy of the default to learn from. + +- `default-annotated.peb` — the default template, laid out and commented to explain how it works. It renders the same page as the default the plugin ships, so it's also a good starting point for your own. +- `theme-neon-arcade.peb` — a dark synthwave arcade: neon lettering, a sunset over a moving grid, glowing cabinets and CRT screens. +- `theme-morning-edition.peb` — a newspaper: a masthead, articles in columns with drop caps, photos that take colour when touched, and coupons for downloads. Dark mode makes it a *Night Edition*. +- `theme-aurora-deck.peb` — frosted glass cards over a moving aurora, in a deck that swipes sideways. +- `theme-clear-access.peb` — for buyers who use a screen reader or have low vision: a clear heading structure, a contents list, large high-contrast text, and descriptive download links. It passes axe-core's WCAG 2.2 AA checks. + +`preview.png` shows the top of the first three alternatives on a phone. + +**To use one:** copy it to your phone's Download folder. In the Share Your Apps tab's Manage Catalog, under **Advanced**, tap **Choose a template file** and pick it, then publish. To go back, tap **Load the default template**, or clear the template field, and publish again. + +Every publish also makes an accessible version of the store page from Clear Access, and each of the others links to it from its top left as *Accessible version*; your own templates can show the same link, from `accessibleHref`. All of them also show what the plugin reads from each APK — its version, the Android it needs, and which phones it's for — and the documented Extra JSON keys: the store's `announcement`, `contact` and `accent`, and each product's `whatsNew`, `license`, `author` and `website`. `default-annotated.peb` lists everything a template receives. All of them pass axe-core's WCAG 2.2 AA checks, work offline, and stop animating for anyone whose phone asks for reduced motion. *Developer notes → Writing a template* lists the Pebble rules to know. + +## Extending the default, and a template library + +You needn't copy a whole template to change one part of it. A template can **extend** the default, and replace only the blocks it wants: `styles`, `header`, `announcement`, `card`, `downloads` or `footer`. For example, to change just each product's download buttons: + +``` +{% extends "default" %} +{% block downloads %}Get it{% endblock %} +``` + +Inside a block, `{{ parent() }}` keeps the original, so you can add to a part rather than replace it — such as extra styles: `{% block styles %}{{ parent() }}{% endblock %}`. + +Templates of your own can also share pieces, kept in the **template library**, the folder `CodeOnTheGoProjects/ShareYourAppsTemplates/`: + +- **`{% include "footer-note" %}`** inserts `footer-note.peb` from the library. Folders work too: `"parts/note"`. +- **`{% import "macros" %}`**, or `{% from "macros" import badge %}`, makes the macros in `macros.peb` available — your own reusable functions, written in Pebble: + ``` + {% macro badge(text) %}{{ text }}{% endmacro %} + ``` + +Names are always relative to the library's top, and can't leave it. A template that names one that isn't there doesn't publish, and the message names it. `default-annotated.peb` shows where each block is. + +## Built-in functions and filters + +Templates can also use these, without any code of your own: + +- **`{{ t("download", "Download") }}`** — text in the store's language, from a table in the store's Extra JSON: `{"strings": {"sw": {"download": "Pakua"}}}`. Without a match in the store's language, it tries English, then the fallback you give, then the key itself. +- **`{{ plural(apps|length, "# app", "# apps") }}`** — *1 app*, *3 apps*: `#` becomes the number. +- **`{{ p.whatsNew|markdown }}`** — a little Markdown, turned into HTML: paragraphs, `- ` lists, `**bold**`, `*italic*`, `` `code` `` and `[links](https://…)`. Any HTML in the text is shown as text, never run. +- **`{{ qr("http://192.168.49.1:6175/", "Scan to open the store") }}`** — a QR code, as an image, with a label for screen readers. +- **`{{ p.apk.sizeBytes|bytes }}`** — a size, such as *5.0 MB*. **`{{ p.name|slugify }}`** — text as a URL-safe name. + +Pebble's own filters work too, such as `abbreviate(40)` to shorten text, `upper`, `date` and `default`. + +## Picture descriptions and captions + +In Manage Catalog, **Describe**, beside each picture or video, lets you say what it shows, for buyers who use a screen reader, and add captions to a video: a WebVTT file, ending `.vtt`. In a template, each item of `p.carousel` has: + +- **`m.alt`** — the description, or, without one, which picture it is: *Termux, picture 1 of 3*. Use it for `alt` on pictures and `aria-label` on videos and sounds. +- **`m.description`** — the description alone, or nothing, if you want to show it as a caption under the picture. +- **`m.captions`** — for a video with captions, the link to its captions file: + `{% if m.captions is not empty %}{% endif %}` + +Every built-in template uses all three. + diff --git a/plugins/Share-Your-Apps/templates/default-annotated.peb b/plugins/Share-Your-Apps/templates/default-annotated.peb new file mode 100644 index 000000000..16ff788c3 --- /dev/null +++ b/plugins/Share-Your-Apps/templates/default-annotated.peb @@ -0,0 +1,478 @@ +{# + BLOCKS: this template is split into blocks — styles, header, announcement, + card, downloads and footer. A template of your own can extend it and replace just one: + + {% extends "default" %} + {% block downloads %}Get it{% endblock %} + + {{ parent() }} inside a block keeps the original too. Other templates, and macros, go in the + template library, CodeOnTheGoProjects/ShareYourAppsTemplates/, for {% include %} and {% import %}. +#} +{# + The default Share Your Apps page, laid out and annotated. It renders the same page as the compact + copy the plugin ships. Comments like this one are Pebble comments: Pebble removes + them while rendering, so none reach buyers. The /* … */ comments in the CSS and script do reach + the page, as ordinary CSS and JavaScript comments. + + What the template receives: + lang the page's language, such as "en-US": Extra JSON's "lang" if set, else the phone's + publishedAt when this publish happened, as an ISO date and time; publishedLabel is "Sep 24, 2026" + shareYourAppsVersion the plugin's version, such as "1.0.0", for a "Made with Share Your Apps" line + contact from Extra JSON, checked: .name, .email, .phone and .url, each with an + .emailHref, .phoneHref or .urlHref only when it's a plausible address + announcement from Extra JSON: a short line of news, as plain text + accent, accentInk from Extra JSON: a colour, only ever #rrggbb, and black or white — whichever + reads better on it, which always reaches WCAG's 4.5 to 1 + storeName the store's name, as text + storeDescriptionHtml the owner's description, as HTML, or null + headerImage .src and .type ("image" or "video") — the octopus when none is chosen + products in Manage Catalog's order, each with: + .name, .ordinal, .slug (a stable ID, such as "termux"), .descriptionHtml (HTML or null) + .dateAddedLabel "Sep 24, 2026"; .dateAddedIso is the same as an ISO date and time + .carousel pictures, videos and sounds: .src, .type, .poster for a video, and + .width and .height where known + .apk .src, .sizeLabel ("6.8 MB") and .sizeBytes, or null; and what the plugin reads + from the APK: .versionName, .versionCode, .packageName, .minSdk and + .androidLabel ("Android 9 or later") — each null when it can't be read — + and .abis, its native-code architectures, with .abiLabel for buyers + ("64-bit phones", "32-bit phones", "32- and 64-bit phones", or "all + phones" when it has no native code) + .sourceZip .src, .sizeLabel and .sizeBytes, or null + .whatsNew, .license, .author + from the product's Extra JSON, checked: plain text, cut to 500, 80 and 80 + characters, or null. They sit on the product itself: p.whatsNew, not + p.extra.whatsNew + .website, .websiteHref + from the product's Extra JSON: the text, cut to 300 characters, and the same + as a link, only when it's an http or https address, else null + .extra the product's whole Extra JSON, exactly as typed and not checked: any key the + owner added is here, but nothing in it is safe to use as a link. Prefer the + checked values above + extra the store's whole Extra JSON, exactly as typed and not checked. Its "strings" + table feeds t("key", "fallback"), which picks the text for the store's + language; the other documented keys have checked values above (lang, + contact, announcement, accent) + accessibleHref the link to the accessible version of the page, accessible.html, which + every publish also makes from the Clear Access template + + Every .src is ready to use: a /f/… link to a file in the store, or, for anything of 10 KB or + less, the file itself as a data: URI. + + Pebble rules that differ from other template languages: a condition needs "is not empty" — + a bare {% if x %} is an error — and the sort filter takes no arguments, which is why products + arrive already in order. {{ … }} escapes HTML; |raw prints the owner's HTML as it is. +#} + + + + + +{{storeName}} +{% block styles %}{% endblock %} +{# The owner's accent colour, if any, for the download button: checked by the plugin, so it's only + ever a #rrggbb colour, with black or white text on it. #} +{% if accent is not empty %}{% endif %} + + +{# The accessible version, first on the page. It's in its own small region, so screen readers + list it among the page's regions. #} +{% if accessibleHref is not empty %}{% endif %} +{# The awning is decoration only, so screen readers skip it. #} + + +{# The header. The octopus arrives as headerImage when the owner hasn't chosen an image. A video + header plays by itself, silently and in a loop, like an animated picture. #} +{% block header %}
        + {% if headerImage.type=='video' %}{% else %}{% endif %} +
        +

        {{storeName}}

        + {% if storeDescriptionHtml is not empty %}
        {{storeDescriptionHtml|raw}}
        {% endif %} +
        +
        {% endblock %} + +{# The owner's announcement, if any, above the products. #} +{% block announcement %}{% if announcement is not empty %}

        {{announcement}}

        {% endif %}{% endblock %} + +{# The products, one card each, in Manage Catalog's order. They're the page's main region, which + screen readers can jump straight to. #} +
        + {% for p in products %}{% block card %}
        + + {# The picture strip, if the product has any pictures, videos or sounds. It can take keyboard + focus, so it can be scrolled with the arrow keys, and screen readers announce its label. #} + {% if p.carousel is not empty %} +
        +
        + {% for m in p.carousel %} +
        + {# Videos show their poster until played, and never preload: preloading would tie up + the server's single thread. Each item is labelled with its product and position, such + as "Termux, picture 1 of 3": the catalog has no descriptions of what pictures show. #} + {% if m.type=='video' %} + {% elseif m.type=='audio' %} + {% else %}{% endif %} +
        + {% endfor %} +
        + {# Arrows only when there's more than one item. The left one starts hidden, at the first + item; the script shows and hides both as the strip moves. #} + {% if p.carousel|length > 1 %} + + + {% endif %} +
        + {% endif %} + + {# The name, as a heading, with the date — in a
        {% endblock %}{% endfor %} +
        + +{# The foot: the owner's contact details, each a link only when it's a real address, and the version. #} +{% block footer %}
        + {% if contact is not empty %}

        Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

        {% endif %} +

        Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

        +
        {% endblock %} + + + + diff --git a/plugins/Share-Your-Apps/templates/preview.png b/plugins/Share-Your-Apps/templates/preview.png new file mode 100644 index 000000000..fb3363b57 Binary files /dev/null and b/plugins/Share-Your-Apps/templates/preview.png differ diff --git a/plugins/Share-Your-Apps/templates/templates-README.md b/plugins/Share-Your-Apps/templates/templates-README.md new file mode 100644 index 000000000..7aabf1230 --- /dev/null +++ b/plugins/Share-Your-Apps/templates/templates-README.md @@ -0,0 +1,15 @@ +# Store page templates + +Pebble templates for the store page. The plugin ships its own default; these are alternatives, and an annotated copy of the default to learn from. + +- `default-annotated.peb` — the default template, laid out and commented to explain how it works. It renders the same page as the default the plugin ships, so it's also a good starting point for your own. +- `theme-neon-arcade.peb` — a dark synthwave arcade: neon lettering, a sunset over a moving grid, glowing cabinets and CRT screens. +- `theme-morning-edition.peb` — a newspaper: a masthead, articles in columns with drop caps, photos that take colour when touched, and coupons for downloads. Dark mode makes it a *Night Edition*. +- `theme-aurora-deck.peb` — frosted glass cards over a moving aurora, in a deck that swipes sideways. +- `theme-clear-access.peb` — for buyers who use a screen reader or have low vision: a clear heading structure, a contents list, large high-contrast text, and descriptive download links. It passes axe-core's WCAG 2.2 AA checks. + +`preview.png` shows the top of the first three alternatives on a phone. + +**To use one:** copy it to your phone's Download folder. In the Share Your Apps tab's Manage Catalog, under **Advanced**, tap **Choose a template file** and pick it, then publish. To go back, tap **Load the default template**, or clear the template field, and publish again. + +All of them work offline, and stop animating for anyone whose phone asks for reduced motion. *Developer notes → Writing a template* lists the Pebble rules to know. diff --git a/plugins/Share-Your-Apps/templates/theme-aurora-deck.peb b/plugins/Share-Your-Apps/templates/theme-aurora-deck.peb new file mode 100644 index 000000000..d15edf59b --- /dev/null +++ b/plugins/Share-Your-Apps/templates/theme-aurora-deck.peb @@ -0,0 +1,47 @@ +{{storeName}}{% if accent is not empty %}{% endif %}{% if accessibleHref is not empty %}{% endif %} +
        {% if headerImage.type=='video' %}{% else %}{% endif %}

        {{storeName}}

        {% if storeDescriptionHtml is not empty %}
        {{storeDescriptionHtml|raw}}
        {% endif %}
        +{% if announcement is not empty %}

        {{announcement}}

        {% endif %}
        {{products|length}} appsSwipe →
        +
        {% for p in products %}
        {% if p.carousel is not empty %}
        {% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
        {% endif %}

        {{p.name}}

        {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}
        {% if p.descriptionHtml is not empty %}
        {{p.descriptionHtml|raw}}
        {% endif %}{% if p.whatsNew is not empty %}

        What's new: {{p.whatsNew}}

        {% endif %}
        {% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Source{{p.sourceZip.sizeLabel}}{% endif %}
        {% if p.apk is not empty %}

        {% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

        {% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

        {% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

        {% endif %}
        {% endfor %}
        diff --git a/plugins/Share-Your-Apps/templates/theme-clear-access.peb b/plugins/Share-Your-Apps/templates/theme-clear-access.peb new file mode 100644 index 000000000..e25a53b81 --- /dev/null +++ b/plugins/Share-Your-Apps/templates/theme-clear-access.peb @@ -0,0 +1,53 @@ +{# share-your-apps:accessible — marks this as the accessible template, so the plugin makes no second copy of it. #} +{{storeName}} + +
        +{% if standardHref is not empty %}{% endif %} +
        {% if headerImage.type=='video' %}{% else %}{% endif %}

        {{storeName}}

        {% if storeDescriptionHtml is not empty %}
        {{storeDescriptionHtml|raw}}
        {% endif %}
        +{% if announcement is not empty %}

        {{announcement}}

        {% endif %}{% if products is not empty %}{% endif %} +
        {% for p in products %}

        {{p.name}}

        Added {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}

        {% if p.descriptionHtml is not empty %}
        {{p.descriptionHtml|raw}}
        {% endif %}{% if p.whatsNew is not empty %}

        What's new: {{p.whatsNew}}

        {% endif %}
        {% if p.apk is not empty %}Download {{p.name}} APK, {{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download {{p.name}} source code, {{p.sourceZip.sizeLabel}}{% endif %}
        {% if p.apk is not empty %}

        {% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

        {% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

        {% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

        {% endif %}{% if p.carousel is not empty %}
          {% for m in p.carousel %}
        • {% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}
        • {% endfor %}
        {% endif %}Back to the list of apps
        {% endfor %}
        +

        {{storeName}} · Updated

        {% if contact is not empty %}

        Questions?{% if contact.name is not empty %} Ask {{contact.name}}{% endif %}{% if contact.emailHref is not empty or contact.phoneHref is not empty or contact.urlHref is not empty %}:{% endif %}{% if contact.emailHref is not empty %} {{contact.email}}{% endif %}{% if contact.phoneHref is not empty %}{% if contact.emailHref is not empty %} ·{% endif %} {{contact.phone}}{% endif %}{% if contact.urlHref is not empty %}{% if contact.emailHref is not empty or contact.phoneHref is not empty %} ·{% endif %} website{% endif %}

        {% endif %}

        Made with Share Your Apps{% if shareYourAppsVersion is not empty %} {{shareYourAppsVersion}}{% endif %}

        +
        diff --git a/plugins/Share-Your-Apps/templates/theme-morning-edition.peb b/plugins/Share-Your-Apps/templates/theme-morning-edition.peb new file mode 100644 index 000000000..919df9dac --- /dev/null +++ b/plugins/Share-Your-Apps/templates/theme-morning-edition.peb @@ -0,0 +1,52 @@ +{{storeName}}{% if accent is not empty %}{% endif %}
        {% if accessibleHref is not empty %}{% endif %} + +
        {% if headerImage.type=='video' %}{% else %}{% endif %}

        {{storeName}}

        All the apps that are fit to install

        + +{% if storeDescriptionHtml is not empty %}
        {{storeDescriptionHtml|raw}}
        {% endif %}
        +{% if announcement is not empty %}

        Stop press {{announcement}}

        {% endif %}
        {% for p in products %}
        No. {{p.ordinal}}

        {{p.name}}

        Filed {% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}
        {% if p.carousel is not empty %}
        {% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
        {% if p.carousel|length > 1 %}{{p.carousel|length}} pictures — swipe for more. {% endif %}Touch a picture for colour.
        {% endif %}{% if p.descriptionHtml is not empty %}
        {{p.descriptionHtml|raw}}
        {% endif %}{% if p.whatsNew is not empty %}

        What's new: {{p.whatsNew}}

        {% endif %}
        {% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download source{{p.sourceZip.sizeLabel}}{% endif %}
        {% if p.apk is not empty %}

        {% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

        {% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

        {% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

        {% endif %}
        {% endfor %}
        + +
        diff --git a/plugins/Share-Your-Apps/templates/theme-neon-arcade.peb b/plugins/Share-Your-Apps/templates/theme-neon-arcade.peb new file mode 100644 index 000000000..98d4424e4 --- /dev/null +++ b/plugins/Share-Your-Apps/templates/theme-neon-arcade.peb @@ -0,0 +1,48 @@ +{{storeName}}{% if accent is not empty %}{% endif %}{% if accessibleHref is not empty %}{% endif %} +
        {% if headerImage.type=='video' %}{% else %}{% endif %}

        {{storeName}}

        {% if storeDescriptionHtml is not empty %}
        {{storeDescriptionHtml|raw}}
        {% endif %}
        +{% if announcement is not empty %}

        {{announcement}}

        {% endif %}
        {% for p in products %}
        No. {{p.ordinal}}{% if p.dateAddedIso is not empty %}{% else %}{{p.dateAddedLabel}}{% endif %}

        {{p.name}}

        {% if p.carousel is not empty %}
        {% for m in p.carousel %}{% if m.type=='video' %}{% elseif m.type=='audio' %}{% else %}{% endif %}{% endfor %}
        {% if p.carousel|length > 1 %}{% endif %}
        {% endif %}{% if p.descriptionHtml is not empty %}
        {{p.descriptionHtml|raw}}
        {% endif %}{% if p.whatsNew is not empty %}

        What's new: {{p.whatsNew}}

        {% endif %}
        {% if p.apk is not empty %}Download APK{{p.apk.sizeLabel}}{% endif %}{% if p.sourceZip is not empty %}Download source{{p.sourceZip.sizeLabel}}{% endif %}
        {% if p.apk is not empty %}

        {% if p.apk.versionName is not empty %}Version {{p.apk.versionName}} · {% endif %}{% if p.apk.androidLabel is not empty %}{{p.apk.androidLabel}} · {% endif %}For {{p.apk.abiLabel}}

        {% endif %}{% if p.author is not empty or p.license is not empty or p.websiteHref is not empty %}

        {% if p.author is not empty %}By {{p.author}}{% endif %}{% if p.license is not empty %}{% if p.author is not empty %} · {% endif %}License: {{p.license}}{% endif %}{% if p.websiteHref is not empty %}{% if p.author is not empty or p.license is not empty %} · {% endif %}Website{% endif %}

        {% endif %}
        {% endfor %}
        + diff --git a/scripts/server-signing-key.sh b/scripts/server-signing-key.sh new file mode 100755 index 000000000..c2bd72f82 --- /dev/null +++ b/scripts/server-signing-key.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# +# Puts Share Your Apps Server's release key where its build finds it, for a CI job. +# Writes the keystore from SERVER_SIGNING_KEYSTORE_BASE64 to $RUNNER_TEMP and exports the four +# SERVER_SIGNING_* variables that plugins/Share-Your-Apps/server/app/build.gradle.kts reads, through +# $GITHUB_ENV. The workflow passes the four repository secrets in as environment variables. +# +# Each workflow's Pre-flight checks step has already failed the run if any of the four is missing. + +set -euo pipefail + +store="$RUNNER_TEMP/share-your-apps-server.p12" +printf '%s' "$SERVER_SIGNING_KEYSTORE_BASE64" | base64 --decode > "$store" +chmod 600 "$store" +{ + echo "SERVER_SIGNING_STORE_FILE=$store" + echo "SERVER_SIGNING_STORE_PASSWORD=$SERVER_SIGNING_STORE_PASSWORD" + echo "SERVER_SIGNING_KEY_ALIAS=$SERVER_SIGNING_KEY_ALIAS" + echo "SERVER_SIGNING_KEY_PASSWORD=$SERVER_SIGNING_KEY_PASSWORD" +} >> "$GITHUB_ENV" +echo "Share Your Apps Server's release key is in place."