diff --git a/.github/ci/ci-members.json b/.github/ci/ci-members.json index 9792f1bb9b0..3375e99fd35 100644 --- a/.github/ci/ci-members.json +++ b/.github/ci/ci-members.json @@ -732,6 +732,7 @@ "scripts/pulse/**", "scripts/slate/**", "scripts/fieldline/**", + "scripts/lingo/**", "scripts/splat/**", "scripts/skirmish/**", "scripts/papercut/**", diff --git a/.github/workflows/samples-ios-nightly.yml b/.github/workflows/samples-ios-nightly.yml index 3cf15fa7198..991dbb94c34 100644 --- a/.github/workflows/samples-ios-nightly.yml +++ b/.github/workflows/samples-ios-nightly.yml @@ -65,7 +65,7 @@ jobs: # Watch-app samples (dash, pulse, splat, slate) are the slow ones; # they are split across the shards. - shard: a - samples: ' parley savor dash pulse bastion fieldline papercut ' + samples: ' parley savor dash pulse bastion fieldline lingo papercut ' - shard: b samples: ' wayline reel splat slate skirmish bazaar ' steps: @@ -188,6 +188,10 @@ jobs: if: ${{ !cancelled() && contains(matrix.samples, ' fieldline ') }} run: scripts/ci/build-sample-ios-simulator.sh scripts/fieldline timeout-minutes: 45 + - name: 'iOS: lingo' + if: ${{ !cancelled() && contains(matrix.samples, ' lingo ') }} + run: scripts/ci/build-sample-ios-simulator.sh scripts/lingo + timeout-minutes: 45 - name: 'iOS: skirmish' if: ${{ !cancelled() && contains(matrix.samples, ' skirmish ') }} run: scripts/ci/build-sample-ios-simulator.sh scripts/skirmish diff --git a/.github/workflows/samples.yml b/.github/workflows/samples.yml index 5f5eb98d379..436f2b856aa 100644 --- a/.github/workflows/samples.yml +++ b/.github/workflows/samples.yml @@ -31,6 +31,7 @@ on: - scripts/ci/start-test-database.sh - scripts/dash/** - scripts/fieldline/** + - scripts/lingo/** - scripts/papercut/** - scripts/parley/** - scripts/pulse/** @@ -85,9 +86,9 @@ jobs: env: EVENT: ${{ github.event_name }} BASE: ${{ github.event.pull_request.base.sha || '' }} - PATHS: '{"bastion": ["scripts/bastion/**", "maven/cn1-app-kit/**"], "bazaar": ["scripts/bazaar/**", "maven/cn1-app-kit/**"], "brickyard": ["scripts/brickyard/**"], "dash": ["scripts/dash/**", "maven/cn1-app-kit/**"], "fieldline": ["scripts/fieldline/**", "maven/cn1-app-kit/**"], "papercut": ["scripts/papercut/**"], "parley": ["scripts/parley/**", "maven/cn1-app-kit/**"], "pulse": ["scripts/pulse/**", "maven/cn1-app-kit/**"], "reel": ["scripts/reel/**", "maven/cn1-app-kit/**"], "savor": ["scripts/savor/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"], "skirmish": ["scripts/skirmish/**", "maven/cn1-app-kit/**"], "slate": ["scripts/slate/**", "maven/cn1-app-kit/**"], "splat": ["scripts/splat/**"], "wayline": ["scripts/wayline/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"]}' - KINDS: '{"android": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "app": ["brickyard"], "backend": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "backend-database": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "chain": ["bastion"], "client-e2e": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "ios": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "rules": ["dash", "skirmish", "splat"], "template-sync": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], - "web": ["bastion", "bazaar", "fieldline", "parley", "pulse", "reel", "savor", "slate", "wayline"]}' + PATHS: '{"bastion": ["scripts/bastion/**", "maven/cn1-app-kit/**"], "bazaar": ["scripts/bazaar/**", "maven/cn1-app-kit/**"], "brickyard": ["scripts/brickyard/**"], "dash": ["scripts/dash/**", "maven/cn1-app-kit/**"], "fieldline": ["scripts/fieldline/**", "maven/cn1-app-kit/**"], "lingo": ["scripts/lingo/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"], "papercut": ["scripts/papercut/**"], "parley": ["scripts/parley/**", "maven/cn1-app-kit/**"], "pulse": ["scripts/pulse/**", "maven/cn1-app-kit/**"], "reel": ["scripts/reel/**", "maven/cn1-app-kit/**"], "savor": ["scripts/savor/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"], "skirmish": ["scripts/skirmish/**", "maven/cn1-app-kit/**"], "slate": ["scripts/slate/**", "maven/cn1-app-kit/**"], "splat": ["scripts/splat/**"], "wayline": ["scripts/wayline/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"]}' + KINDS: '{"android": ["bastion", "bazaar", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "app": ["brickyard"], "backend": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "backend-database": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "chain": ["bastion"], "client-e2e": ["bastion", "bazaar", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "ios": ["bastion", "bazaar", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "rules": ["dash", "skirmish", "splat"], "template-sync": ["bastion", "bazaar", "dash", "fieldline", "lingo", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], + "web": ["bastion", "bazaar", "fieldline", "lingo", "parley", "pulse", "reel", "savor", "slate", "wayline"]}' run: | python3 - <<'EOF' import fnmatch, json, os, subprocess @@ -139,6 +140,9 @@ jobs: - name: 'fieldline: Compare the template with scripts/fieldline' run: python3 scripts/sync-initializr-template.py fieldline if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Compare the template with scripts/lingo' + run: python3 scripts/sync-initializr-template.py lingo + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'papercut: Compare the template with scripts/papercut' run: | python3 scripts/sync-initializr-template.py papercut @@ -347,6 +351,16 @@ jobs: JAVA_HOME: ${{ env.JDK_17_HOME }} JDK_8_HOME: ${{ env.JDK_8_HOME }} if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Run the server tests on the JVM and compiled' + working-directory: scripts/lingo + run: | + mvn -B -Dcodename1.platform=backend -pl shared,backend test \ + -Dcn1.backend.compiledTests=true \ + -Dmaven.repo.local="$GITHUB_WORKSPACE/.m2-repo" + env: + JAVA_HOME: ${{ env.JDK_17_HOME }} + JDK_8_HOME: ${{ env.JDK_8_HOME }} + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'fieldline: Check that both runners reported' working-directory: scripts/fieldline/backend/target/surefire-reports run: | @@ -358,6 +372,17 @@ jobs: exit 1 fi if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Check that both runners reported' + working-directory: scripts/lingo/backend/target/surefire-reports + run: | + jvm=$(find . -maxdepth 1 -name 'TEST-*.xml' ! -name '*-compiled.xml' | wc -l) + compiled=$(find . -maxdepth 1 -name 'TEST-*-compiled.xml' | wc -l) + echo "JVM reports: $jvm, compiled reports: $compiled" + if [ "$jvm" -eq 0 ] || [ "$compiled" -eq 0 ]; then + echo "::error::a runner produced no test reports" + exit 1 + fi + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'fieldline: Upload the test reports' if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') && (!cancelled()) }} uses: actions/upload-artifact@v7 @@ -366,6 +391,14 @@ jobs: path: scripts/fieldline/backend/target/surefire-reports/** if-no-files-found: warn retention-days: 14 + - name: 'lingo: Upload the test reports' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') && (!cancelled()) }} + uses: actions/upload-artifact@v7 + with: + name: lingo-backend-tests + path: scripts/lingo/backend/target/surefire-reports/** + if-no-files-found: warn + retention-days: 14 - name: 'papercut: Run the server tests on the JVM and compiled' working-directory: scripts/papercut run: | @@ -847,6 +880,18 @@ jobs: env: JAVA_HOME: ${{ env.JDK_17_HOME }} if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') }} + - name: 'lingo: Run the server tests on ${{ matrix.database }}' + run: | + if [ "${{ matrix.database }}" = mysql ]; then + export CN1_TEST_DATABASE_URL="mysql://cn1:secret@127.0.0.1:3306/cn1?sslmode=disable" + else + export CN1_TEST_DATABASE_URL="postgres://cn1:secret@localhost:5432/cn1?sslmode=disable" + fi + scripts/ci/sample-server-tests-on-database.sh scripts/lingo \ + -Dmaven.repo.local="$GITHUB_WORKSPACE/.m2-repo" + env: + JAVA_HOME: ${{ env.JDK_17_HOME }} + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') }} - name: 'fieldline: Upload the test reports' if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') && (always()) }} uses: actions/upload-artifact@v7 @@ -855,6 +900,14 @@ jobs: path: scripts/fieldline/backend/target/surefire-reports/** if-no-files-found: warn retention-days: 14 + - name: 'lingo: Upload the test reports' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') && (always()) }} + uses: actions/upload-artifact@v7 + with: + name: lingo-backend-${{ matrix.database }}-tests + path: scripts/lingo/backend/target/surefire-reports/** + if-no-files-found: warn + retention-days: 14 - name: 'papercut: Run the server tests on ${{ matrix.database }}' run: | if [ "${{ matrix.database }}" = mysql ]; then @@ -1181,6 +1234,13 @@ jobs: export PATH="${JAVA_HOME_17}/bin:$PATH" scripts/fieldline/check-template.sh "$RUNNER_TEMP/fieldline-template" if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Build a project generated from the Initializr template' + run: | + export JDK_8_HOME="${JAVA_HOME_8}" + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME_17}/bin:$PATH" + scripts/lingo/check-template.sh "$RUNNER_TEMP/lingo-template" + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'fieldline: Run the application against the server' run: | export JDK_8_HOME="${JAVA_HOME_8}" @@ -1188,6 +1248,13 @@ jobs: export PATH="${JAVA_HOME_17}/bin:$PATH" scripts/fieldline/run-e2e.sh if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Run the application against the server' + run: | + export JDK_8_HOME="${JAVA_HOME_8}" + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME_17}/bin:$PATH" + scripts/lingo/run-e2e.sh + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'fieldline: Upload the captures and the server log' if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') && (!cancelled()) }} uses: actions/upload-artifact@v7 @@ -1198,6 +1265,16 @@ jobs: scripts/fieldline/target/e2e-server.log if-no-files-found: warn retention-days: 14 + - name: 'lingo: Upload the captures and the server log' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') && (!cancelled()) }} + uses: actions/upload-artifact@v7 + with: + name: lingo-e2e + path: | + scripts/lingo/target/e2e-shots/** + scripts/lingo/target/e2e-server.log + if-no-files-found: warn + retention-days: 14 - name: 'papercut: Build a project generated from the Initializr template' run: | export JDK_8_HOME="${JAVA_HOME_8}" @@ -1521,6 +1598,12 @@ jobs: JAVA_HOME: ${{ env.JDK_17_HOME }} JDK_8_HOME: ${{ env.JDK_8_HOME }} if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} + - name: 'lingo: Run the hosted web app in a headless browser' + run: scripts/lingo/run-web-e2e.sh + env: + JAVA_HOME: ${{ env.JDK_17_HOME }} + JDK_8_HOME: ${{ env.JDK_8_HOME }} + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} - name: 'fieldline: Upload the screenshots and the logs' if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') && (!cancelled()) }} uses: actions/upload-artifact@v7 @@ -1529,6 +1612,14 @@ jobs: path: scripts/fieldline/target/web-e2e/** if-no-files-found: warn retention-days: 14 + - name: 'lingo: Upload the screenshots and the logs' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') && (!cancelled()) }} + uses: actions/upload-artifact@v7 + with: + name: lingo-web-e2e + path: scripts/lingo/target/web-e2e/** + if-no-files-found: warn + retention-days: 14 - name: 'parley: Run the hosted web app in a headless browser' run: scripts/parley/run-web-e2e.sh env: @@ -1689,6 +1780,14 @@ jobs: if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} env: CN1_APP_DIR: scripts/fieldline + - name: 'lingo: Build the Android application' + run: | + mkdir -p ~/.codenameone + cp maven/UpdateCodenameOne.jar ~/.codenameone/ + ./scripts/build-android-app.sh -q -DskipTests + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} + env: + CN1_APP_DIR: scripts/lingo - name: 'papercut: Build the Android application' run: | mkdir -p ~/.codenameone @@ -2268,6 +2367,13 @@ jobs: if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} env: CN1_APP_DIR: scripts/fieldline + - name: 'lingo: Generate the Xcode project' + id: build-ios-app-lingo + run: ./scripts/build-ios-app.sh -q -DskipTests + timeout-minutes: 25 + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} + env: + CN1_APP_DIR: scripts/lingo - name: 'fieldline: Build the application for the simulator' run: | set -euo pipefail @@ -2306,6 +2412,44 @@ jobs: if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' fieldline ') }} env: CN1_APP_DIR: scripts/fieldline + - name: 'lingo: Build the application for the simulator' + run: | + set -euo pipefail + WORKSPACE='${{ steps.build-ios-app-lingo.outputs.workspace }}' + SCHEME='${{ steps.build-ios-app-lingo.outputs.scheme }}' + DERIVED_DATA="${{ runner.temp }}/lingo-dd" + rm -rf "$DERIVED_DATA" + # One architecture, the host's: the port's SIMD natives are NEON + # under __aarch64__, and a universal simulator build compiles an + # x86_64 slice that has no use here. + HOST_ARCH="$(uname -m)" + case "$HOST_ARCH" in + arm64|x86_64) BUILD_ARCH="$HOST_ARCH" ;; + *) BUILD_ARCH=arm64 ;; + esac + XCB_CONTAINER_FLAG="-workspace" + if [[ "$WORKSPACE" != *.xcworkspace ]]; then + XCB_CONTAINER_FLAG="-project" + fi + # No -sdk: it forces every target of the scheme onto the iPhone SDK, the + # embedded watch app included, whose watch-only icon then has nothing to + # compile for. The destination picks each target's own SDK. + xcodebuild "$XCB_CONTAINER_FLAG" "$WORKSPACE" -scheme "$SCHEME" \ + -configuration Debug \ + -destination 'generic/platform=iOS Simulator' \ + -derivedDataPath "$DERIVED_DATA" \ + ARCHS="$BUILD_ARCH" ONLY_ACTIVE_ARCH=YES \ + EXCLUDED_ARCHS="armv7 armv7s" \ + CODE_SIGNING_ALLOWED=NO build + APP_BUNDLE="$(find "$DERIVED_DATA/Build/Products" -maxdepth 3 -type d -name "${SCHEME}.app" | head -n 1)" + if [ -z "$APP_BUNDLE" ]; then + echo "::error::no .app bundle under $DERIVED_DATA" + exit 1 + fi + timeout-minutes: 20 + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' lingo ') }} + env: + CN1_APP_DIR: scripts/lingo - name: 'parley: Generate the Xcode project' id: build-ios-app-parley run: ./scripts/build-ios-app.sh -q -DskipTests diff --git a/CodenameOne/src/com/codename1/impl/pdf/PdfCms.java b/CodenameOne/src/com/codename1/impl/pdf/PdfCms.java new file mode 100644 index 00000000000..a7d6a7f0130 --- /dev/null +++ b/CodenameOne/src/com/codename1/impl/pdf/PdfCms.java @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.pdf; + +import com.codename1.security.Hash; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; + +/// The DER half of a PDF signature: builds the CMS `SignedData` a +/// `/adbe.pkcs7.detached` signature carries, and reads one back. +/// +/// Only what a PAdES baseline (B-B) signature needs is produced: SHA-256, +/// the `contentType`, `messageDigest` and `signingCertificateV2` signed +/// attributes, and the signer's certificate chain. The signing time is +/// deliberately not a signed attribute; PAdES puts it in the signature +/// dictionary's `/M` instead. +/// +/// Nothing here signs or verifies. The bytes to sign are handed to the +/// caller, so the same code serves a device (the platform crypto bridge) +/// and a server (the JDK) without depending on either. +@com.codename1.impl.SharedWithBackend +public final class PdfCms { + private static final int SEQUENCE = 0x30; + private static final int SET = 0x31; + private static final int INTEGER = 0x02; + private static final int OCTET_STRING = 0x04; + private static final int NULL = 0x05; + private static final int OID = 0x06; + private static final int CONTEXT_0 = 0xA0; + + static final String OID_DATA = "1.2.840.113549.1.7.1"; + static final String OID_SIGNED_DATA = "1.2.840.113549.1.7.2"; + static final String OID_CONTENT_TYPE = "1.2.840.113549.1.9.3"; + static final String OID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4"; + static final String OID_SIGNING_CERTIFICATE_V2 = "1.2.840.113549.1.9.16.2.47"; + static final String OID_SHA256 = "2.16.840.1.101.3.4.2.1"; + static final String OID_SHA256_WITH_RSA = "1.2.840.113549.1.1.11"; + static final String OID_RSA = "1.2.840.113549.1.1.1"; + static final String OID_ECDSA_WITH_SHA256 = "1.2.840.10045.4.3.2"; + static final String OID_COMMON_NAME = "2.5.4.3"; // NOPMD AvoidUsingHardCodedIP - an OID + + /// `SHA256withRSA`, the value [#signatureAlgorithm(String)] answers for + /// an RSA key. + public static final String SHA256_WITH_RSA = "SHA256withRSA"; + + /// `SHA256withECDSA`, the value [#signatureAlgorithm(String)] answers for + /// an EC key. + public static final String SHA256_WITH_ECDSA = "SHA256withECDSA"; + + private PdfCms() { + } + + /// Maps a key algorithm (`RSA` or `EC`) to the signature algorithm a + /// signature over the signed attributes uses. + public static String signatureAlgorithm(String keyAlgorithm) { + if ("EC".equalsIgnoreCase(keyAlgorithm) || "ECDSA".equalsIgnoreCase(keyAlgorithm)) { + return SHA256_WITH_ECDSA; + } + if ("RSA".equalsIgnoreCase(keyAlgorithm)) { + return SHA256_WITH_RSA; + } + throw new IllegalArgumentException("Unsupported signing key algorithm: " + keyAlgorithm); + } + + /// The DER `SET` of signed attributes for a document whose byte ranges + /// hash to `documentDigest`, signed by `certificate`. These are the + /// exact bytes the signature is computed over. + public static byte[] signedAttributes(byte[] documentDigest, byte[] certificate) { + List attrs = new ArrayList(); + attrs.add(attribute(OID_CONTENT_TYPE, oid(OID_DATA))); + attrs.add(attribute(OID_MESSAGE_DIGEST, tlv(OCTET_STRING, documentDigest))); + // SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF ESSCertIDv2 } + // ESSCertIDv2 ::= SEQUENCE { hashAlgorithm DEFAULT sha256, certHash } + byte[] essCertId = tlv(SEQUENCE, tlv(OCTET_STRING, Hash.sha256(certificate))); + attrs.add(attribute(OID_SIGNING_CERTIFICATE_V2, tlv(SEQUENCE, tlv(SEQUENCE, essCertId)))); + return setOf(attrs); + } + + /// The complete `ContentInfo` holding `SignedData`. + /// + /// @param signedAttributes what [#signedAttributes(byte[], byte[])] returned + /// @param signature the signature over `signedAttributes`; for ECDSA the + /// DER `ECDSA-Sig-Value` the JDK and the platform bridges produce + /// @param signatureAlgorithm [#SHA256_WITH_RSA] or [#SHA256_WITH_ECDSA] + /// @param chain the signer's certificate first, then any intermediates + public static byte[] signedData(byte[] signedAttributes, byte[] signature, String signatureAlgorithm, + byte[][] chain) { + if (chain == null || chain.length == 0) { + throw new IllegalArgumentException("A signature needs the signer's certificate"); + } + byte[][] issuerSerial = issuerAndSerial(chain[0]); + byte[] sigAlg = SHA256_WITH_ECDSA.equals(signatureAlgorithm) + ? tlv(SEQUENCE, oid(OID_ECDSA_WITH_SHA256)) + : tlv(SEQUENCE, concat(oid(OID_SHA256_WITH_RSA), new byte[] {NULL, 0})); + byte[] digestAlg = tlv(SEQUENCE, oid(OID_SHA256)); + // signedAttrs is [0] IMPLICIT: the SET's tag replaced, its body kept. + byte[] implicitAttrs = signedAttributes.clone(); + implicitAttrs[0] = (byte) CONTEXT_0; + byte[] signerInfo = tlv(SEQUENCE, concat( + tlv(INTEGER, new byte[] {1}), + tlv(SEQUENCE, concat(issuerSerial[0], issuerSerial[1])), + digestAlg, + implicitAttrs, + sigAlg, + tlv(OCTET_STRING, signature))); + ByteArrayOutputStream certs = new ByteArrayOutputStream(); + for (byte[] cert : chain) { + certs.write(cert, 0, cert.length); + } + byte[] signedData = tlv(SEQUENCE, concat( + tlv(INTEGER, new byte[] {1}), + tlv(SET, digestAlg), + tlv(SEQUENCE, oid(OID_DATA)), + tlv(CONTEXT_0, certs.toByteArray()), + tlv(SET, signerInfo))); + return tlv(SEQUENCE, concat(oid(OID_SIGNED_DATA), tlv(CONTEXT_0, signedData))); + } + + /// The parts of a `SignedData` a verifier needs, or null when `der` is + /// not a `SignedData` this class can read. Index 0 is the signed + /// attributes re-tagged as a `SET` (the bytes that were signed), 1 the + /// signature value, 2 the signer's certificate, 3 the `messageDigest` + /// attribute, 4 the `signingCertificateV2` hash (empty when absent) and + /// 5 the signature algorithm name as a US-ASCII byte string. + public static byte[][] parse(byte[] der) { + try { + Reader ci = new Reader(der, 0, der.length); + Reader contentInfo = ci.enter(SEQUENCE); + if (!OID_SIGNED_DATA.equals(oidString(contentInfo.read(OID)))) { + return null; + } + Reader sd = contentInfo.enter(CONTEXT_0).enter(SEQUENCE); + sd.read(INTEGER); + sd.skip(); + sd.skip(); + List certificates = new ArrayList(); + if (sd.peek() == CONTEXT_0) { + Reader certs = sd.enter(CONTEXT_0); + while (certs.hasMore()) { + certificates.add(certs.element()); + } + } + while (sd.peek() == 0xA1) { + sd.skip(); + } + Reader si = sd.enter(SET).enter(SEQUENCE); + si.read(INTEGER); + Reader sid = si.enter(SEQUENCE); + byte[] issuer = sid.element(); + byte[] serial = sid.element(); + si.skip(); + if (si.peek() != CONTEXT_0) { + return null; + } + byte[] attrs = si.element(); + byte[] algId = si.element(); + byte[] signature = si.read(OCTET_STRING); + Reader alg = new Reader(algId, 0, algId.length).enter(SEQUENCE); + String algOid = oidString(alg.read(OID)); + String algorithm; + if (OID_ECDSA_WITH_SHA256.equals(algOid)) { + algorithm = SHA256_WITH_ECDSA; + } else if (OID_SHA256_WITH_RSA.equals(algOid) || OID_RSA.equals(algOid)) { + algorithm = SHA256_WITH_RSA; + } else { + return null; + } + byte[] signer = null; + for (byte[] candidate : certificates) { + byte[][] is = issuerAndSerial(candidate); + if (equal(is[0], issuer) && equal(is[1], serial)) { + signer = candidate; + break; + } + } + if (signer == null) { + return null; + } + byte[] signedAttrs = attrs.clone(); + signedAttrs[0] = (byte) SET; + byte[] digest = null; + byte[] certHash = new byte[0]; + Reader as = new Reader(attrs, 0, attrs.length).enter(CONTEXT_0); + while (as.hasMore()) { + Reader a = as.enter(SEQUENCE); + String type = oidString(a.read(OID)); + Reader values = a.enter(SET); + if (OID_MESSAGE_DIGEST.equals(type)) { + digest = values.read(OCTET_STRING); + } else if (OID_SIGNING_CERTIFICATE_V2.equals(type)) { + Reader ess = values.enter(SEQUENCE).enter(SEQUENCE).enter(SEQUENCE); + if (ess.peek() == SEQUENCE) { + ess.skip(); + } + certHash = ess.read(OCTET_STRING); + } + } + if (digest == null) { + return null; + } + return new byte[][] {signedAttrs, signature, signer, digest, certHash, PdfFormat.ascii(algorithm)}; + } catch (IllegalStateException malformed) { + return null; + } + } + + /// The `subjectPublicKeyInfo` of an X.509 certificate. + public static byte[] subjectPublicKeyInfo(byte[] certificate) { + Reader tbs = tbs(certificate); + tbs.skip(); // signature + tbs.skip(); // issuer + tbs.skip(); // validity + tbs.skip(); // subject + return tbs.element(); + } + + /// The common name (CN) of a certificate's subject, or null. + public static String subjectCommonName(byte[] certificate) { + try { + Reader tbs = tbs(certificate); + tbs.skip(); + tbs.skip(); + tbs.skip(); + Reader name = tbs.enter(SEQUENCE); + while (name.hasMore()) { + Reader rdn = name.enter(SET); + while (rdn.hasMore()) { + Reader atv = rdn.enter(SEQUENCE); + if (OID_COMMON_NAME.equals(oidString(atv.read(OID)))) { + byte[] value = atv.element(); + Reader v = new Reader(value, 0, value.length); + int[] hl = v.header(); + return utf8(value, hl[1], hl[2]); + } + } + } + } catch (IllegalStateException malformed) { + return null; + } + return null; + } + + private static Reader tbs(byte[] certificate) { + Reader tbs = new Reader(certificate, 0, certificate.length).enter(SEQUENCE).enter(SEQUENCE); + if (tbs.peek() == CONTEXT_0) { + tbs.skip(); + } + tbs.skip(); // serial + return tbs; + } + + /// Index 0 the issuer Name element, 1 the serialNumber element. + private static byte[][] issuerAndSerial(byte[] certificate) { + Reader tbs = new Reader(certificate, 0, certificate.length).enter(SEQUENCE).enter(SEQUENCE); + if (tbs.peek() == CONTEXT_0) { + tbs.skip(); + } + byte[] serial = tbs.element(); + tbs.skip(); + byte[] issuer = tbs.element(); + return new byte[][] {issuer, serial}; + } + + private static byte[] attribute(String type, byte[] value) { + return tlv(SEQUENCE, concat(oid(type), tlv(SET, value))); + } + + /// A DER `SET OF`: the members sorted by their encodings. + private static byte[] setOf(List members) { + byte[][] sorted = members.toArray(new byte[members.size()][]); + for (int i = 1; i < sorted.length; i++) { + byte[] key = sorted[i]; + int j = i - 1; + while (j >= 0 && compare(sorted[j], key) > 0) { + sorted[j + 1] = sorted[j]; + j--; + } + sorted[j + 1] = key; + } + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + for (byte[] member : sorted) { + bo.write(member, 0, member.length); + } + return tlv(SET, bo.toByteArray()); + } + + private static int compare(byte[] a, byte[] b) { + int n = Math.min(a.length, b.length); + for (int i = 0; i < n; i++) { + int d = (a[i] & 0xff) - (b[i] & 0xff); + if (d != 0) { + return d; + } + } + return a.length - b.length; + } + + static byte[] oid(String dotted) { + String[] parts = split(dotted); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + long first = Long.parseLong(parts[0]) * 40 + Long.parseLong(parts[1]); + base128(bo, first); + for (int i = 2; i < parts.length; i++) { + base128(bo, Long.parseLong(parts[i])); + } + return tlv(OID, bo.toByteArray()); + } + + static String oidString(byte[] body) { + StringBuilder sb = new StringBuilder(); + long value = 0; + boolean first = true; + for (byte b : body) { + value = (value << 7) | (b & 0x7f); + if ((b & 0x80) == 0) { + if (first) { + long a = value < 80 ? value / 40 : 2; + sb.append(a).append('.').append(value - a * 40); + first = false; + } else { + sb.append('.').append(value); + } + value = 0; + } + } + return sb.toString(); + } + + private static String[] split(String dotted) { + List out = new ArrayList(); + int start = 0; + for (int i = 0; i <= dotted.length(); i++) { + if (i == dotted.length() || dotted.charAt(i) == '.') { + out.add(dotted.substring(start, i)); + start = i + 1; + } + } + return out.toArray(new String[out.size()]); + } + + private static void base128(ByteArrayOutputStream bo, long v) { + int groups = 1; + for (long t = v >>> 7; t != 0; t >>>= 7) { + groups++; + } + for (int g = groups - 1; g >= 0; g--) { + int b = (int) ((v >>> (7 * g)) & 0x7f); + bo.write(g == 0 ? b : b | 0x80); + } + } + + static byte[] tlv(int tag, byte[] content) { + int len = content.length; + byte[] lenBytes; + if (len < 0x80) { + lenBytes = new byte[] {(byte) len}; + } else { + int n = 0; + for (int t = len; t != 0; t >>>= 8) { + n++; + } + lenBytes = new byte[n + 1]; + lenBytes[0] = (byte) (0x80 | n); + for (int i = 0; i < n; i++) { + lenBytes[n - i] = (byte) (len >>> (8 * i)); + } + } + byte[] out = new byte[1 + lenBytes.length + len]; + out[0] = (byte) tag; + System.arraycopy(lenBytes, 0, out, 1, lenBytes.length); + System.arraycopy(content, 0, out, 1 + lenBytes.length, len); + return out; + } + + private static byte[] concat(byte[]... parts) { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + for (byte[] part : parts) { + bo.write(part, 0, part.length); + } + return bo.toByteArray(); + } + + static boolean equal(byte[] a, byte[] b) { + if (a.length != b.length) { + return false; + } + int diff = 0; + for (int i = 0; i < a.length; i++) { + diff |= a[i] ^ b[i]; + } + return diff == 0; + } + + private static String utf8(byte[] b, int off, int len) { + try { + return new String(b, off, len, "UTF-8"); + } catch (java.io.UnsupportedEncodingException e) { + return null; + } + } + + /// A cursor over the elements of one DER constructed value. Malformed + /// input throws IllegalStateException, which [#parse(byte[])] turns + /// into "not a signature". + private static final class Reader { + private final byte[] data; + private int pos; + private final int end; + + Reader(byte[] data, int start, int end) { + if (end > data.length || start < 0 || start > end) { + throw new IllegalStateException("truncated"); + } + this.data = data; + this.pos = start; + this.end = end; + } + + boolean hasMore() { + return pos < end; + } + + int peek() { + if (pos >= end) { + return -1; + } + return data[pos] & 0xff; + } + + /// {tag, content start, content length, element end} + int[] header() { + if (pos + 2 > end) { + throw new IllegalStateException("truncated"); + } + int tag = data[pos] & 0xff; + int p = pos + 1; + int len = data[p++] & 0xff; + if (len >= 0x80) { + int n = len & 0x7f; + if (n == 0 || n > 4 || p + n > end) { + throw new IllegalStateException("bad length"); + } + len = 0; + for (int i = 0; i < n; i++) { + len = (len << 8) | (data[p++] & 0xff); + } + if (len < 0) { + throw new IllegalStateException("bad length"); + } + } + if (p + len > end) { + throw new IllegalStateException("truncated"); + } + return new int[] {tag, p, len, p + len}; + } + + Reader enter(int tag) { + int[] h = header(); + if (h[0] != tag) { + throw new IllegalStateException("unexpected tag"); + } + pos = h[3]; + return new Reader(data, h[1], h[3]); + } + + byte[] read(int tag) { + int[] h = header(); + if (h[0] != tag) { + throw new IllegalStateException("unexpected tag"); + } + pos = h[3]; + byte[] out = new byte[h[2]]; + System.arraycopy(data, h[1], out, 0, h[2]); + return out; + } + + byte[] element() { + int[] h = header(); + byte[] out = new byte[h[3] - pos]; + System.arraycopy(data, pos, out, 0, out.length); + pos = h[3]; + return out; + } + + void skip() { + pos = header()[3]; + } + } +} diff --git a/CodenameOne/src/com/codename1/pdf/PdfDocument.java b/CodenameOne/src/com/codename1/pdf/PdfDocument.java index 1789351b1a8..13b615cc713 100644 --- a/CodenameOne/src/com/codename1/pdf/PdfDocument.java +++ b/CodenameOne/src/com/codename1/pdf/PdfDocument.java @@ -67,6 +67,7 @@ public final class PdfDocument { private String creator; private long creationDate = System.currentTimeMillis(); private boolean compress = true; + private PdfSignature signature; /// Adds a page of `size` at the end of the document. public PdfPage addPage(PdfPageSize size) { @@ -142,6 +143,21 @@ public PdfDocument setCreationDate(long millis) { return this; } + /// Signs the document with `signature` when it is saved. Pass null to + /// save unsigned again. Every save signs afresh, so the bytes differ + /// between saves. + /// + /// @throws IllegalArgumentException if a visible signature is placed on + /// a page of another document + public PdfDocument sign(PdfSignature signature) { + if (signature != null && signature.getPage() != null + && signature.getPage().document() != this) { // NOPMD CompareObjectsWithEquals - the same document object is required + throw new IllegalArgumentException("The signature's page belongs to another document"); + } + this.signature = signature; + return this; + } + /// Turns stream compression off, for a file that can be read in a text /// editor while debugging. On by default. public PdfDocument setCompress(boolean compress) { @@ -205,6 +221,20 @@ public void save(OutputStream out) throws IOException { if (pages.isEmpty()) { addPage(PdfPageSize.A4); } + if (signature == null) { + write(out, null); + return; + } + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + PdfPage target = signature.getPage() != null ? signature.getPage() : pages.get(0); + write(bo, target); + byte[] file = bo.toByteArray(); + PdfSignatures.complete(file, signature); + out.write(file); + out.flush(); + } + + private void write(OutputStream out, PdfPage signedPage) throws IOException { PdfWriter w = new PdfWriter(out); int catalog = w.reserve(); int tree = w.reserve(); @@ -217,6 +247,11 @@ public void save(OutputStream out) throws IOException { for (int i = 0; i < imageOrder.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed like the surrounding decoder loops imageObjects.put(imageOrder.get(i), Integer.valueOf(w.reserve())); } + int sigField = 0; + if (signedPage != null) { + sigField = w.reserve(); + signedPage.signatureWidget = sigField; + } extGStateObjects = new int[extGStateOrder.size()]; for (int i = 0; i < extGStateObjects.length; i++) { extGStateObjects[i] = w.reserve(); @@ -244,8 +279,15 @@ public void save(OutputStream out) throws IOException { PdfImage img = imageOrder.get(i); img.write(w, imageObject(img)); } + if (signedPage != null) { + signedPage.signatureWidget = 0; + PdfSignatures.writeField(w, signature, signedPage, sigField); + } int outlines = bookmarks.isEmpty() ? 0 : writeOutlines(w); StringBuilder cat = new StringBuilder("<>"); + } if (outlines > 0) { cat.append(" /Outlines ").append(outlines).append(" 0 R /PageMode /UseOutlines"); } diff --git a/CodenameOne/src/com/codename1/pdf/PdfPage.java b/CodenameOne/src/com/codename1/pdf/PdfPage.java index 805eed1cca7..344f71f86e8 100644 --- a/CodenameOne/src/com/codename1/pdf/PdfPage.java +++ b/CodenameOne/src/com/codename1/pdf/PdfPage.java @@ -41,6 +41,9 @@ public final class PdfPage { private final List images = new ArrayList(); private final List links = new ArrayList(); int objectNumber; + /// The object number of the signature field's widget on this page while + /// a signed document is being saved, otherwise 0. + int signatureWidget; PdfPage(PdfDocument document, float width, float height) { this.document = document; @@ -137,10 +140,13 @@ String resources() { } String annotations() { - if (links.isEmpty()) { + if (links.isEmpty() && signatureWidget == 0) { return ""; } StringBuilder sb = new StringBuilder(" /Annots ["); + if (signatureWidget > 0) { + sb.append(signatureWidget).append(" 0 R "); + } for (int i = 0; i < links.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed like the surrounding decoder loops Object[] link = links.get(i); float[] r = (float[]) link[0]; diff --git a/CodenameOne/src/com/codename1/pdf/PdfSignature.java b/CodenameOne/src/com/codename1/pdf/PdfSignature.java new file mode 100644 index 00000000000..c2bd13cbbf6 --- /dev/null +++ b/CodenameOne/src/com/codename1/pdf/PdfSignature.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +/// Describes the digital signature [PdfDocument#sign(PdfSignature)] embeds +/// when the document is saved. +/// +/// The result is a PAdES baseline (B-B) signature: a detached CMS +/// `SignedData` over the whole file, SHA-256, with the signer's +/// certificate. Acrobat, Preview and `pdfsig` report it as signed; whether +/// they call it *trusted* depends on the certificate, which is the +/// application's choice, not this class's. +/// +/// ```java +/// PrivateKey key = PrivateKey.fromPem(new String(Util.readInputStream( +/// CN.getResourceAsStream("/signer-key.pem")), "UTF-8")); +/// byte[] certificateDer = Util.readInputStream(CN.getResourceAsStream("/signer.der")); +/// PdfDocument doc = new PdfDocument(); +/// doc.addPage(PdfPageSize.A4); +/// // ... draw the certificate of completion ... +/// doc.sign(new PdfSignature(PdfSigner.provider(key, certificateDer)) +/// .setReason("Certificate of completion") +/// .setLocation("Lingo Academy") +/// .setVisible(doc.getPage(0), 380, 40, 180, 50)); +/// byte[] signed = doc.toByteArray(); +/// ``` +@com.codename1.impl.SharedWithBackend +public final class PdfSignature { + private final PdfSignatureProvider provider; + private String name; + private String reason; + private String location; + private String contactInfo; + private long signingTime = System.currentTimeMillis(); + private PdfPage page; + private float x; + private float y; + private float width; + private float height; + private int reservedBytes = 12288; + + /// A signature whose key material comes from `provider`. + public PdfSignature(PdfSignatureProvider provider) { + if (provider == null) { + throw new IllegalArgumentException("A signature needs a provider"); + } + this.provider = provider; + } + + /// The provider given to the constructor. + public PdfSignatureProvider getProvider() { + return provider; + } + + /// The signer's name as shown by viewers; defaults to the certificate's + /// common name. + public PdfSignature setName(String name) { + this.name = name; + return this; + } + + /// The signer's name, or null for the certificate's common name. + public String getName() { + return name; + } + + /// Why the document was signed. + public PdfSignature setReason(String reason) { + this.reason = reason; + return this; + } + + /// Why the document was signed, or null. + public String getReason() { + return reason; + } + + /// Where the document was signed. + public PdfSignature setLocation(String location) { + this.location = location; + return this; + } + + /// Where the document was signed, or null. + public String getLocation() { + return location; + } + + /// How to reach the signer. + public PdfSignature setContactInfo(String contactInfo) { + this.contactInfo = contactInfo; + return this; + } + + /// How to reach the signer, or null. + public String getContactInfo() { + return contactInfo; + } + + /// The claimed signing time, in milliseconds since the epoch; the + /// current time by default. It is the signer's claim, not a timestamp + /// authority's. + public PdfSignature setSigningTime(long millis) { + this.signingTime = millis; + return this; + } + + /// The claimed signing time. + public long getSigningTime() { + return signingTime; + } + + /// Shows the signature as a box at `(x, y, width, height)` on `page`, + /// in the page's top-left based coordinates, with the signer's name, + /// the date and the reason. Without this the signature is invisible + /// and attached to the first page. + public PdfSignature setVisible(PdfPage page, float x, float y, float width, float height) { + this.page = page; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + } + + /// True when [#setVisible] placed the signature on a page. + public boolean isVisible() { + return page != null && width > 0 && height > 0; + } + + PdfPage getPage() { + return page; + } + + float[] getRect() { + return new float[] {x, y, width, height}; + } + + /// The space reserved in the file for the CMS signature, in bytes; + /// 12 KB by default, enough for a signer certificate and two + /// intermediates. Saving fails if the signature does not fit. + public PdfSignature setReservedBytes(int bytes) { + if (bytes < 1024) { + throw new IllegalArgumentException("At least 1024 bytes must be reserved"); + } + this.reservedBytes = bytes; + return this; + } + + /// The space reserved for the CMS signature, in bytes. + public int getReservedBytes() { + return reservedBytes; + } +} diff --git a/CodenameOne/src/com/codename1/pdf/PdfSignatureInfo.java b/CodenameOne/src/com/codename1/pdf/PdfSignatureInfo.java new file mode 100644 index 00000000000..8a6c2d40656 --- /dev/null +++ b/CodenameOne/src/com/codename1/pdf/PdfSignatureInfo.java @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +import com.codename1.impl.pdf.PdfCms; +import com.codename1.security.Hash; +import java.util.ArrayList; +import java.util.List; + +/// One digital signature found in a PDF, as [#find(byte[])] reads it. +/// +/// This class checks everything that needs no public-key cryptography: +/// that the signed byte ranges hash to the digest the signature commits +/// to ([#isDigestValid()]), that the certificate is the one the signature +/// names ([#isCertificateBound()]) and that nothing was appended after +/// signing ([#coversWholeDocument()]). The signature itself is verified by +/// `PdfSigner.verify` on a device, or by the JDK on a +/// server over [#getSignedAttributes()] and [#getSignatureValue()]. +/// +/// Trust is out of scope: a self-signed certificate verifies as well as a +/// CA-issued one. Compare [#getSignerCertificate()] with the certificate +/// you expect, or validate its chain, before believing who signed. +@com.codename1.impl.SharedWithBackend +public final class PdfSignatureInfo { + private final long[] byteRange; + private final boolean wholeDocument; + private final boolean digestValid; + private final boolean certificateBound; + private final byte[] signedAttributes; + private final byte[] signatureValue; + private final byte[] certificate; + private final String algorithm; + + private PdfSignatureInfo(long[] byteRange, boolean wholeDocument, boolean digestValid, byte[][] parts) { + this.byteRange = byteRange; + this.wholeDocument = wholeDocument; + this.digestValid = digestValid; + this.signedAttributes = parts[0]; + this.signatureValue = parts[1]; + this.certificate = parts[2]; + byte[] certHash = parts[4]; + this.certificateBound = certHash.length > 0 && equal(certHash, Hash.sha256(parts[2])); + this.algorithm = ascii(parts[5]); + } + + /// Every `adbe.pkcs7.detached` (or `ETSI.CAdES.detached`) signature in + /// `pdf`, in file order. A signature dictionary whose contents cannot + /// be read as a SHA-256 CMS signature is skipped. + public static List find(byte[] pdf) { + List out = new ArrayList(); + byte[] key = {'/', 'B', 'y', 't', 'e', 'R', 'a', 'n', 'g', 'e'}; + int from = 0; + while (true) { + int at = indexOf(pdf, key, from); + if (at < 0) { + return out; + } + from = at + key.length; + long[] br = parseByteRange(pdf, from); + if (br == null) { + continue; + } + PdfSignatureInfo info = read(pdf, br); + if (info != null) { + out.add(info); + } + } + } + + private static PdfSignatureInfo read(byte[] pdf, long[] br) { + long len = pdf.length; + if (br[0] != 0 || br[1] <= 0 || br[2] <= br[1] || br[3] < 0 || br[2] + br[3] > len) { + return null; + } + int gapStart = (int) br[1]; + int gapEnd = (int) br[2]; + if (pdf[gapStart] != '<' || pdf[gapEnd - 1] != '>') { + return null; + } + byte[] cms = unhex(pdf, gapStart + 1, gapEnd - 1); + if (cms == null) { + return null; + } + byte[][] parts = PdfCms.parse(cms); + if (parts == null) { + return null; + } + Hash h = Hash.create(Hash.SHA256); + h.update(pdf, 0, gapStart); + h.update(pdf, gapEnd, (int) br[3]); + boolean digestValid = equal(h.digest(), parts[3]); + return new PdfSignatureInfo(br, br[2] + br[3] == len, digestValid, parts); + } + + /// The four `/ByteRange` numbers: offset and length of the bytes signed + /// before the signature, then after it. + public long[] getByteRange() { + return byteRange.clone(); + } + + /// True when the signed ranges reach the end of the file, so nothing + /// was added after signing. An incremental update after the signature + /// (a later annotation, a second signature) makes this false while the + /// signature itself stays valid for the bytes it covers. + public boolean coversWholeDocument() { + return wholeDocument; + } + + /// True when the signed bytes hash to the digest the signature commits + /// to. False means the document was changed after it was signed. + public boolean isDigestValid() { + return digestValid; + } + + /// True when the signature's `signingCertificateV2` attribute names the + /// embedded signer certificate, so the certificate cannot have been + /// swapped for another with the same key. + public boolean isCertificateBound() { + return certificateBound; + } + + /// The DER signed attributes, the exact bytes the signature is over. + public byte[] getSignedAttributes() { + return signedAttributes.clone(); + } + + /// The raw signature value (DER for ECDSA). + public byte[] getSignatureValue() { + return signatureValue.clone(); + } + + /// The signer's DER X.509 certificate. + public byte[] getSignerCertificate() { + return certificate.clone(); + } + + /// The certificate's DER `SubjectPublicKeyInfo`, the key to verify with. + public byte[] getSignerPublicKey() { + return PdfCms.subjectPublicKeyInfo(certificate); + } + + /// The common name of the signer's certificate, or null. + public String getSignerName() { + return PdfCms.subjectCommonName(certificate); + } + + /// `SHA256withRSA` or `SHA256withECDSA`. + public String getSignatureAlgorithm() { + return algorithm; + } + + private static long[] parseByteRange(byte[] pdf, int p) { + while (p < pdf.length && isSpace(pdf[p])) { + p++; + } + if (p >= pdf.length || pdf[p] != '[') { + return null; + } + p++; + long[] out = new long[4]; + for (int i = 0; i < 4; i++) { + while (p < pdf.length && isSpace(pdf[p])) { + p++; + } + int start = p; + long v = 0; + while (p < pdf.length && pdf[p] >= '0' && pdf[p] <= '9' && p - start < 15) { + v = v * 10 + (pdf[p] - '0'); + p++; + } + if (p == start) { + return null; + } + out[i] = v; + } + return out; + } + + private static boolean isSpace(byte b) { + return b == ' ' || b == '\n' || b == '\r' || b == '\t' || b == '\f' || b == 0; + } + + private static int indexOf(byte[] data, byte[] key, int from) { + for (int i = from; i <= data.length - key.length; i++) { + if (matchesAt(data, key, i)) { + return i; + } + } + return -1; + } + + private static boolean matchesAt(byte[] data, byte[] key, int at) { + for (int j = 0; j < key.length; j++) { + if (data[at + j] != key[j]) { + return false; + } + } + return true; + } + + /// Hex digits between `start` and `end`, whitespace ignored. Trailing + /// zero padding past the DER element is harmless: the parser reads one + /// element and stops. + private static byte[] unhex(byte[] pdf, int start, int end) { + byte[] out = new byte[(end - start) / 2 + 1]; + int n = 0; + int hi = -1; + for (int i = start; i < end; i++) { + int c = pdf[i]; + int v; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A' + 10; + } else if (isSpace((byte) c)) { + continue; + } else { + return null; + } + if (hi < 0) { + hi = v; + } else { + out[n++] = (byte) ((hi << 4) | v); + hi = -1; + } + } + byte[] r = new byte[n]; + System.arraycopy(out, 0, r, 0, n); + return r; + } + + private static boolean equal(byte[] a, byte[] b) { + if (a.length != b.length) { + return false; + } + int diff = 0; + for (int i = 0; i < a.length; i++) { + diff |= a[i] ^ b[i]; + } + return diff == 0; + } + + private static String ascii(byte[] b) { + StringBuilder sb = new StringBuilder(b.length); + for (byte c : b) { + sb.append((char) (c & 0x7f)); + } + return sb.toString(); + } +} diff --git a/CodenameOne/src/com/codename1/pdf/PdfSignatureProvider.java b/CodenameOne/src/com/codename1/pdf/PdfSignatureProvider.java new file mode 100644 index 00000000000..03f18b4e761 --- /dev/null +++ b/CodenameOne/src/com/codename1/pdf/PdfSignatureProvider.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +import java.io.IOException; + +/// Supplies the key material of a PDF signature without exposing the key. +/// +/// [PdfDocument] computes what has to be signed and calls [#sign(byte[])] +/// exactly once while saving. On a device, `PdfSigner.provider` answers +/// with the platform crypto bridge. On a Codename One server, implement it +/// over `com.codename1.backend.Crypto.sign` (`RS256` or `ES256` with the +/// PKCS#8 key), which runs on the JVM and compiled alike; a hardware +/// security module fits the same shape, so the private key never leaves +/// it. +@com.codename1.impl.SharedWithBackend +public interface PdfSignatureProvider { + /// The key algorithm, `RSA` or `EC`. The signature is SHA-256 with + /// that key (`SHA256withRSA` or `SHA256withECDSA`). + String getKeyAlgorithm(); + + /// The DER X.509 certificates: the signer's first, then any + /// intermediates a verifier needs to build the chain. + byte[][] getCertificateChain(); + + /// Signs `data` with SHA-256 and the private key. ECDSA signatures are + /// returned DER encoded (`ECDSA-Sig-Value`), as every Codename One port and + /// the backend's `Crypto.sign` produce them. + /// + /// @throws IOException when the key cannot sign: a hardware key that is + /// locked, a remote signing service that cannot be reached. The save + /// that asked fails with it. + byte[] sign(byte[] data) throws IOException; +} diff --git a/CodenameOne/src/com/codename1/pdf/PdfSignatures.java b/CodenameOne/src/com/codename1/pdf/PdfSignatures.java new file mode 100644 index 00000000000..10d9e5bd09a --- /dev/null +++ b/CodenameOne/src/com/codename1/pdf/PdfSignatures.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +import com.codename1.impl.pdf.PdfCms; +import com.codename1.impl.pdf.PdfFormat; +import com.codename1.impl.pdf.PdfWriter; +import com.codename1.security.Hash; +import java.io.IOException; + +/// Writes the signature field of a signed [PdfDocument] and, once the file +/// is complete, fills in its byte range and CMS contents. +/// +/// The signature dictionary is written with a fixed-width `/ByteRange` +/// placeholder and a `/Contents` hex string of zeros. Both are patched in +/// place after saving, so no offset in the file moves. +@com.codename1.impl.SharedWithBackend +final class PdfSignatures { + /// Width of each patched `/ByteRange` number; enough for a 9 GB file. + private static final int RANGE_WIDTH = 10; + private static final String RANGE_PLACEHOLDER = "/ByteRange [0 0000000000 0000000000 0000000000]"; + + private PdfSignatures() { + } + + static void writeField(PdfWriter w, PdfSignature sig, PdfPage page, int field) throws IOException { + int sigDict = w.reserve(); + StringBuilder sb = new StringBuilder("<>>"); + w.object(sigDict, sb.toString()); + + StringBuilder f = new StringBuilder("<>>>"); + w.object(field, f.toString()); + writeAppearance(w, sig, ap, r[2], r[3]); + } else { + f.append("0 0 0 0]>>"); + w.object(field, f.toString()); + } + } + + private static void writeAppearance(PdfWriter w, PdfSignature sig, int ap, float width, float height) + throws IOException { + String name = sig.getName(); + if (name == null) { + byte[][] chain = sig.getProvider().getCertificateChain(); + name = chain != null && chain.length > 0 ? PdfCms.subjectCommonName(chain[0]) : null; + } + String date = PdfDocument.pdfDate(sig.getSigningTime()); + String[] lines = { + "Digitally signed by " + (name == null ? "unknown" : name), + "Date: " + date.substring(2, 6) + "-" + date.substring(6, 8) + "-" + date.substring(8, 10), + sig.getReason() + }; + float size = Math.max(5, Math.min(10, height / 4.5f)); + StringBuilder c = new StringBuilder("0.2 0.3 0.6 RG 1 w 0.5 0.5 "); + PdfFormat.number(c, width - 1); + c.append(' '); + PdfFormat.number(c, height - 1); + c.append(" re S BT 0.1 0.1 0.2 rg /Helv "); + PdfFormat.number(c, size); + c.append(" Tf "); + float y = height - size - 3; + for (String line : lines) { + if (line == null) { + continue; + } + c.append("1 0 0 1 4 "); + PdfFormat.number(c, y); + c.append(" Tm "); + PdfFormat.literal(c, latin1(line)); + c.append(" Tj "); + y -= size * 1.3f; + } + c.append("ET"); + StringBuilder dict = new StringBuilder("/Type /XObject /Subtype /Form /BBox [0 0 "); + PdfFormat.number(dict, width); + dict.append(' '); + PdfFormat.number(dict, height); + dict.append("] /Resources <>>>>>"); + w.stream(ap, dict.toString(), PdfFormat.ascii(c.toString()), false); + } + + /// Patches the byte range and the CMS signature into a saved file. + static void complete(byte[] file, PdfSignature sig) throws IOException { + byte[] marker = PdfFormat.ascii(RANGE_PLACEHOLDER); + int rangeAt = indexOf(file, marker, 0); + byte[] contentsKey = PdfFormat.ascii("/Contents <"); + int gapStart = indexOf(file, contentsKey, rangeAt) + contentsKey.length - 1; + int gapEnd = gapStart + 2 + sig.getReservedBytes() * 2; + if (rangeAt < 0 || gapStart < rangeAt || file[gapEnd - 1] != '>') { + throw new IllegalStateException("The signature placeholder was not found"); + } + long[] br = {0, gapStart, gapEnd, file.length - gapEnd}; + StringBuilder range = new StringBuilder("/ByteRange [0"); + for (int i = 1; i < 4; i++) { + String n = Long.toString(br[i]); + if (n.length() > RANGE_WIDTH) { + throw new IllegalStateException("The document is too large to sign"); + } + range.append(' ').append(n); + for (int p = n.length(); p < RANGE_WIDTH; p++) { + range.append(' '); + } + } + range.append(']'); + byte[] patched = PdfFormat.ascii(range.toString()); + System.arraycopy(patched, 0, file, rangeAt, patched.length); + + Hash h = Hash.create(Hash.SHA256); + h.update(file, 0, gapStart); + h.update(file, gapEnd, file.length - gapEnd); + PdfSignatureProvider provider = sig.getProvider(); + byte[][] chain = provider.getCertificateChain(); + if (chain == null || chain.length == 0) { + throw new IllegalStateException("The signature provider returned no certificate"); + } + byte[] attrs = PdfCms.signedAttributes(h.digest(), chain[0]); + String algorithm = PdfCms.signatureAlgorithm(provider.getKeyAlgorithm()); + byte[] cms = PdfCms.signedData(attrs, provider.sign(attrs), algorithm, chain); + if (cms.length > sig.getReservedBytes()) { + throw new IllegalStateException("The signature needs " + cms.length + " bytes but only " + + sig.getReservedBytes() + " were reserved; raise PdfSignature.setReservedBytes"); + } + int p = gapStart + 1; + for (byte b : cms) { + file[p++] = (byte) HEX.charAt((b >> 4) & 0xf); + file[p++] = (byte) HEX.charAt(b & 0xf); + } + } + + private static final String HEX = "0123456789ABCDEF"; + + private static void entry(StringBuilder sb, String key, String value) { + if (value != null) { + sb.append(" /").append(key).append(' '); + PdfFormat.textString(sb, value); + } + } + + /// Characters outside Latin-1 become `?`: the appearance uses a + /// standard font, which has no other glyphs. + private static String latin1(String s) { + StringBuilder sb = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + sb.append(ch < 256 ? ch : '?'); + } + return sb.toString(); + } + + private static int indexOf(byte[] data, byte[] key, int from) { + if (from < 0) { + return -1; + } + for (int i = from; i <= data.length - key.length; i++) { + if (matchesAt(data, key, i)) { + return i; + } + } + return -1; + } + + private static boolean matchesAt(byte[] data, byte[] key, int at) { + for (int j = 0; j < key.length; j++) { + if (data[at + j] != key[j]) { + return false; + } + } + return true; + } +} diff --git a/CodenameOne/src/com/codename1/pdf/PdfSigner.java b/CodenameOne/src/com/codename1/pdf/PdfSigner.java new file mode 100644 index 00000000000..873c29f8123 --- /dev/null +++ b/CodenameOne/src/com/codename1/pdf/PdfSigner.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +import com.codename1.impl.pdf.PdfCms; +import com.codename1.security.PrivateKey; +import com.codename1.security.PublicKey; +import com.codename1.security.Signature; + +/// Device-side helpers for PDF signatures, over the platform crypto bridge +/// in `com.codename1.security`. +/// +/// A server signs with the same [PdfSignature] API but implements +/// [PdfSignatureProvider] over the JDK; this class is the client's +/// shortcut. +public final class PdfSigner { + private PdfSigner() { + } + + /// A provider that signs with `key`, an RSA or EC private key, and + /// presents `chain` (DER certificates, the signer's first). + public static PdfSignatureProvider provider(final PrivateKey key, final byte[]... chain) { + if (key == null || chain == null || chain.length == 0) { + throw new IllegalArgumentException("A key and the signer's certificate are required"); + } + final String keyAlgorithm = key.getAlgorithm(); + final String algorithm = PdfCms.signatureAlgorithm(keyAlgorithm); + return new PdfSignatureProvider() { + @Override + public String getKeyAlgorithm() { + return keyAlgorithm; + } + + @Override + public byte[][] getCertificateChain() { + return chain; + } + + @Override + public byte[] sign(byte[] data) { + return Signature.sign(algorithm, key, data); + } + }; + } + + /// True when `info` is a complete, untouched signature: the digest + /// matches, the certificate is bound to it and the signature verifies + /// against the certificate's key. It says nothing about whether the + /// certificate should be trusted. + public static boolean verify(PdfSignatureInfo info) { + if (!info.isDigestValid() || !info.isCertificateBound()) { + return false; + } + String alg = info.getSignatureAlgorithm(); + String keyAlg = PdfCms.SHA256_WITH_ECDSA.equals(alg) ? PublicKey.EC : PublicKey.RSA; + PublicKey pk = PublicKey.fromX509(keyAlg, info.getSignerPublicKey()); + return Signature.verify(alg, pk, info.getSignedAttributes(), info.getSignatureValue()); + } +} diff --git a/README.md b/README.md index 73d459110b0..96d71db0bcf 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ Choose an Initializr full-stack template or explore Brickyard, a complete game-p | --- | --- | | Brickyard creator studio editing a game world on desktop

A full-stack Java game-platform sample with a Luau runtime, GPU engine, multiplayer server and creator studio. Roblox place-file compatibility is reported per file; run it with your own hosting and configured services. | Bazaar shop on a phone with stores to follow and popular products

Shopper, merchant, register and admin apps with a server-rendered web store and a Java backend: one cart across stores, fulfilment and inventory across locations, a sales pipeline, an AI store assistant and a register that sells offline. | +| [Lingo — Language learning](https://www.codenameone.com/developer-guide/lingo-users-guide/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=lingo) | +| --- | +| Lingo learner home with the streak, the daily goal and the course to continue

An AI language tutor that runs on the phone, pronunciation scored word by word, community courses, video lessons and live WebRTC classes with a 70% creator share, and a Java backend that issues signed PDF certificates anyone can verify. | + [Generate your application](https://www.codenameone.com/initializr/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=template-start) · [Explore the complete templates](https://www.codenameone.com/demos/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=fullstack-samples) | What do you want to build? | Start here | @@ -57,7 +61,7 @@ Choose an Initializr full-stack template or explore Brickyard, a complete game-p | An existing Swing or JavaFX app | [Import desktop Java source](https://www.codenameone.com/developer-guide/desktop-interop/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=desktop-import) and compile supported Swing, SwingX, JavaFX, FXML and CSS for phones, desktop and web | | A Kotlin Multiplatform / Compose app | [Import shared Kotlin and Compose screens](https://www.codenameone.com/developer-guide/kotlin-multiplatform-interop/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=kmp-import) and use Codename One APIs from the same project | | Existing Flutter screens | [Compile supported Dart and Flutter code to Java](https://www.codenameone.com/developer-guide/flutter-interop/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=flutter-import); experimental compatibility, with interaction limits documented in the guide | -| A complete full-stack application | [Choose a template](#start-with-a-complete-full-stack-application): food delivery, messaging, ride hailing, multiplayer games, fitness, appointment booking, field service, virtual banking or streaming and courses | +| A complete full-stack application | [Choose a template](#start-with-a-complete-full-stack-application): food delivery, language learning, messaging, ride hailing, multiplayer games, fitness, appointment booking, field service, virtual banking or streaming and courses | | Bring Python code | [Compile supported Python modules to Java](https://www.codenameone.com/developer-guide/python-interop/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=python-interop) for apps and native Java backends; no Python interpreter ships in the executable | | Evidence before adopting | [Compare performance](#measured-performance) and [inspect platform support](https://www.codenameone.com/port-status/?utm_source=github&utm_medium=oss&utm_campaign=repo-readme&utm_content=platforms) | diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java index 8a8f26bd7b2..2a4ad92ebcb 100644 --- a/docs/demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java @@ -34,9 +34,13 @@ import com.codename1.pdf.PdfPageSize; import com.codename1.pdf.PdfParagraph; import com.codename1.pdf.PdfReader; +import com.codename1.pdf.PdfSignature; +import com.codename1.pdf.PdfSignatureInfo; +import com.codename1.pdf.PdfSigner; import com.codename1.pdf.PdfTable; import com.codename1.pdf.ui.PdfViewer; import com.codename1.printing.Printer; +import com.codename1.security.PrivateKey; import com.codename1.ui.Form; import com.codename1.ui.layouts.BorderLayout; import java.io.IOException; @@ -138,4 +142,37 @@ public void print() { } // end::pdf-print[] } + + byte[] signCertificate() throws IOException { + // tag::pdf-sign[] + // The signer's key and certificate, shipped with the app or fetched + // from your server. + PrivateKey key = PrivateKey.fromPem(new String( + Util.readInputStream(CN.getResourceAsStream("/signer-key.pem")), "UTF-8")); + byte[] certificateDer = Util.readInputStream(CN.getResourceAsStream("/signer.der")); + PdfDocument doc = new PdfDocument().setTitle("Certificate of completion"); + PdfPage page = doc.addPage(PdfPageSize.A4); + doc.sign(new PdfSignature(PdfSigner.provider(key, certificateDer)) + .setReason("Certificate of completion") + .setLocation("Lingo Academy") + .setVisible(page, 380, 760, 180, 50)); + byte[] signed = doc.toByteArray(); + // end::pdf-sign[] + return signed; + } + + boolean checkSignature() throws IOException { + // tag::pdf-verify[] + byte[] pdf = Util.readInputStream(CN.getResourceAsStream("/certificate.pdf")); + byte[] expected = Util.readInputStream(CN.getResourceAsStream("/signer.der")); + boolean trusted = false; + for (PdfSignatureInfo info : PdfSignatureInfo.find(pdf)) { + boolean intact = PdfSigner.verify(info) && info.coversWholeDocument(); + boolean ours = java.util.Arrays.equals(info.getSignerCertificate(), expected); + trusted = trusted || intact && ours; + } + Log.p(trusted ? "Signed by us and unchanged" : "Not our signature, or altered"); + // end::pdf-verify[] + return trusted; + } } diff --git a/docs/demos/common/src/main/snippets/developer-guide/lingo.sh b/docs/demos/common/src/main/snippets/developer-guide/lingo.sh new file mode 100644 index 00000000000..385982de26a --- /dev/null +++ b/docs/demos/common/src/main/snippets/developer-guide/lingo.sh @@ -0,0 +1,32 @@ +// Snippets of the Lingo chapter of the developer guide. Edit them here, not inline. + +// tag::lingo-sh-server[] +cd scripts/lingo +CN1_PROFILE=dev backend/server.sh run +// end::lingo-sh-server[] + +// tag::lingo-sh-simulator[] +cd scripts/lingo +mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase +// end::lingo-sh-simulator[] + +// tag::lingo-sh-production[] +export CN1_PROFILE=prod +export DATABASE_URL=postgres://lingo:secret@db.example.com:5432/lingo +export LINGO_PUBLIC_URL=https://learn.example.com +export LINGO_ADMIN_EMAIL=you@example.com +export LINGO_ADMIN_PASSWORD=change-me +export LINGO_CERTIFICATES_KEY=base64-pkcs8-key +export LINGO_CERTIFICATES_CHAIN=base64-signer-cert,base64-issuer-cert +export LINGO_AI_KEY=sk-ant-your-key +export LINGO_PUSH_APP=your-push-app-id +export LINGO_PUSH_KEY=your-push-server-key +backend/server.sh run --native +// end::lingo-sh-production[] + +// tag::lingo-sh-tests[] +cd scripts/lingo +./run-e2e.sh +./run-web-e2e.sh +./check-template.sh +// end::lingo-sh-tests[] diff --git a/docs/developer-guide/Lingo-Implementors-Guide.asciidoc b/docs/developer-guide/Lingo-Implementors-Guide.asciidoc new file mode 100644 index 00000000000..d8f4264fbd6 --- /dev/null +++ b/docs/developer-guide/Lingo-Implementors-Guide.asciidoc @@ -0,0 +1,155 @@ +[[lingo-implementors-guide]] +== Lingo: Building on the sample + +This chapter is for the developer who starts from Lingo: how the project is laid +out, how each part works, and where to change it. <> shows +the same app from the user's side. + +The sample lives in `scripts/lingo`. The Initializr generates it, under your own +name and package, when you pick the language learning template. Everything in +it's released under MIT No Attribution, so take any part of it into your own +application. + +=== Running it + +The development profile needs nothing installed: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-server,indent=0] +---- + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-simulator,indent=0] +---- + +=== The modules + +`shared` is the contract. It holds the data classes both sides exchange and the +`@RestClient` interfaces, such as `LearnApi`, `CommunityApi`, `StudioApi` and +`AdminApi`, that name every call. The app's build generates a client from them +and the server's build generates the interfaces it implements, so a change one +side didn't follow is a compile error. + +`common` is the app, for every platform. Its packages: + +[cols="1,4"] +|=== +| `learn` | The learner's screens: today, the catalogue, the three kinds of lesson, rewards, badges, the leaderboard, certificates, the wallet and the admin's accounts. +| `studio` | The creator's: the studio, the course and lesson editors and the class scheduler. +| `ai` | Choosing the tutor and running it: `Tutors`, and one `TutorEngine` per kind. +| `speech` | `Voice`, which speaks and listens, and `PronunciationScorer`. +| `live` | The live channel and `LiveRoom`, a class over WebRTC. +| `ui`, `net`, `notify` | The shared kit, the session and the API clients, and reminders. +|=== + +`backend` is the server. `learn` holds progress, XP, badges and the conversation +tutor. `community` holds questions, live classes and payments, `studio` the +creators' side, `cert` the certificates, `live` the WebSocket, and `admin` the +accounts console. The entities are in `domain` with a repository each. The schema +is the migration scripts in `src/main/resources/db/migration`, with a variant for +each database. + +=== The tutor + +`Tutors.choose` picks the conversation partner, best first: + +. the operating system's own model, Apple Intelligence or Gemini Nano, when the + device has one ready; +. a model the app downloads, Qwen2.5 0.5B Instruct, run on the device with + `llama.cpp`; +. the cloud tutor through the server, only when the learner turned it on; +. a scripted partner, which always works. + +`choose` takes four booleans and nothing else, so `TutorLogicTest` covers the +order without a device. Each engine implements `TutorEngine`, which takes the +scene, the level and the turns so far, and answers with a reply and an optional +correction. To use a different on-device model, change `MODEL_URL`, +`MODEL_SHA256` and `MODEL_BYTES` in `Tutors`. The download goes through +`ModelCache`, which needs the digest: iOS refuses an unpinned download, and the +digest makes sure the model is the one the app was tested with. + +The cloud tutor is `backend/.../ai/ClaudeClient`, behind the server's own key +(`lingo.ai.key`), so no key ever ships in the app. Without a key the server +answers from rules. + +=== Pronunciation + +`Voice` speaks the phrase with the device's text to speech and listens with its +speech recognizer, both in the course's language. `PronunciationScorer` aligns +what was heard with the phrase, word by word, using an edit distance in which +swapping one word for another costs how different their letters are. A dropped +word therefore costs one word and doesn't shift the rest. Case, accents and +punctuation are folded away character by character, because recognizers +disagree on all three. The fold never calls `toLowerCase()`, whose result +depends on the device's locale. + +The recognizer writes down words, not sounds, so the score measures whether a +native listener understood each word. A language-specific acoustic model could +replace the scorer behind the same `Result`. + +=== Progress and badges + +The server is the authority on progress. `Learning` records a finished lesson, +awards its XP, extends the streak, and asks `Badges` what the lesson unlocked; +the app only shows what comes back. Badge rules are plain Java in `Badges`. A new +badge is a rule there and a line in the seed. + +=== Certificates + +When the last lesson of a course is done, `Certificates` draws the PDF: the name, +the course, the date, the hours and a QR code of its verification address. It +signs the PDF with the core `PdfDocument.sign` and a `PdfSignature` over +`CertificateKeys`, and stores the bytes exactly as issued. `GET /verify/{id}` +looks a certificate up and checks its signature again; `/verify/{id}` in a +browser is the public page the QR code opens. + +To make PDF readers trust the signature, give the server a key and a +certificate from a CA they trust, in `lingo.certificates.key` and +`lingo.certificates.chain`. Without them, it signs with a self-signed key it keeps +in the database. + +=== Payments and the creator's share + +`Community.purchase` records every sale: a course, a seat in a class, Pro or a +tip. It credits the creator `CREATOR_SHARE`, 70%, of a sale, and the whole of a tip. +Payments are simulated: every one succeeds unless its method is `declined`. +A real deployment puts a payment provider in `purchase`. The rest of the server +reads only the receipts it writes. + +=== Live classes + +`LiveRoom` makes the host the hub. Each learner holds one peer connection, to +the host, and the host holds one to each learner. The signalling goes over the +app's live channel, which the server relays only between people seated in a +class while it's live. A class of more than a handful wants a selective +forwarding unit (SFU) in place of the host; the signalling stays the same. + +=== Settings and deployment + +`backend/application.properties` lists every setting. A production start looks +like this: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-production,indent=0] +---- + +Outside a development profile the only account created is the administrator, +who grants the first creators from the studio's *Accounts* button. The seed +courses are loaded on every profile, from `src/main/resources/seed/courses.json`. + +=== Tests + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-tests,indent=0] +---- + +The server's tests run from `mvn -pl shared,backend -Dcodename1.platform=backend test`, +and `scripts/ci/sample-server-tests-on-database.sh scripts/lingo` runs them again +against PostgreSQL or MySQL. `run-e2e.sh` starts the server and drives the app in +the simulator as a learner and a creator. `run-web-e2e.sh` does the same in a +headless browser, and `check-template.sh` builds a project generated from the +Initializr template. diff --git a/docs/developer-guide/Lingo-Users-Guide.asciidoc b/docs/developer-guide/Lingo-Users-Guide.asciidoc new file mode 100644 index 00000000000..b511bf34512 --- /dev/null +++ b/docs/developer-guide/Lingo-Users-Guide.asciidoc @@ -0,0 +1,178 @@ +[[lingo-users-guide]] +== Lingo: A language learning app from every side + +Lingo is a sample app with a server behind it, for anyone who teaches a language. +Learners practice speaking with an AI tutor that runs on the phone, and every +word they say is scored. Teachers publish courses, hold live classes and earn +from them. A finished course ends with a signed PDF certificate that anyone can +check. The app and the server are one Maven project, written in Java on both +sides. + +This chapter is the user's guide: what each kind of user sees and can do. +<> is the other half. It explains how the project is +built and what to change to make it yours. + +One app serves everyone. The server gives every account a set of roles, and the +app opens on the screens for the role the account holds. + +[cols="1,3"] +|=== +| Role | What it adds + +| Learner +| Practice every day: phrase drills scored word by word, role-play + conversations with the tutor, and video lessons. Earn XP, keep a streak, unlock + badges, buy courses, ask the teacher questions, join live classes and collect + certificates. + +| Creator +| Write courses of phrase, conversation and video lessons, publish them free or + at a price, schedule live classes and hold them, and see what the courses + earn. + +| Administrator +| Grant roles: registering makes a learner, and an administrator makes a + teacher a creator. +|=== + +=== Trying it + +Start the server on the development profile. It needs nothing installed: the +database is in memory, push notifications are printed on the console, and the +cloud tutor answers from rules built into the server: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-server,indent=0] +---- + +Then run the app in the simulator, from another terminal: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/lingo.sh[tag=lingo-sh-simulator,indent=0] +---- + +The demo has five courses in Spanish and French, a teacher with three live +classes coming up, and a learner two lessons into Spanish for Travellers. Every +demo account has the password `lingo-demo`: + +[cols="2,3"] +|=== +| `learner@lingo.example` | a learner with a streak and a course under way +| `learner2@lingo.example` | a second learner +| `creator@lingo.example` | a teacher with published courses +| `admin@lingo.example` | a creator who also grants roles +|=== + +=== The learner + +image::img/lingo-welcome.png["The Lingo welcome screen with buttons to sign in and to create an account",scaledwidth=40%] + +The welcome screen signs in or creates an account. A new account is a learner. +On a phone, the server's address is set here too. + +==== Today + +image::img/lingo-today.png["Today: the streak and XP at the top, the course to continue with the daily goal as a ring, the week's streak, and the learner's courses",scaledwidth=40%] + +The app opens on today. The flame is the streak, the bolt the learner's XP. The +card continues the course under way, with the daily goal as a ring around it; +*Practice now* opens the next lesson. Below are the week's days of practice and +the courses the learner is in. The tabs at the bottom lead to the catalogue, the +live classes and the learner's own page. + +==== A phrase lesson + +image::img/lingo-phrase.png["A phrase lesson: the phrase in Spanish, its translation, buttons to listen at normal and at reduced speed, a hint, and the microphone",scaledwidth=40%] + +The app speaks each phrase first, as a teacher would. *Listen* says it again, and +the button beside it repeats it at a slower pace. The learner taps the microphone and says it. +Where the device has no speech recognizer, such as the simulator, the phrase is +typed instead and scored the same way. + +image::img/lingo-phrase-scored.png["The scored phrase: each word colored by how well it was heard, the verdict, the words to work on and the score",scaledwidth=40%] + +Each word is colored by how well it was heard, and the verdict names the words to +work on. A phrase passes at 50%, and 80% counts as good. *Try again* repeats it; *Continue* moves on. + +==== Conversations and videos + +image::img/lingo-conversation.png["A conversation lesson: the scene, the tutor playing a waiter in Spanish, and the learner's replies",scaledwidth=40%] + +A conversation lesson is a role-play: the tutor plays the waiter, the station +clerk or the new colleague, at the course's level. The learner answers by voice +or by typing, and the tutor corrects mistakes as it goes. The screen shows which tutor +answers: the phone's own model, the model the learner downloaded, the cloud +tutor or the scripted partner. A video lesson plays the teacher's recording. + +image::img/lingo-video-lesson.png["A video lesson: the teacher's recorded slides playing above the lesson title and summary",scaledwidth=40%] + +==== Rewards + +image::img/lingo-reward.png["Lesson complete: a trophy, the XP earned, the score, the streak and the level, the daily goal, and a badge unlocked",scaledwidth=40%] + +A finished lesson shows the XP earned, the score, the streak and the level, and +any badge it unlocked. The last lesson of a course issues its certificate. + +==== The learner's page + +image::img/lingo-me-dark.png["The learner's page in dark mode: their name and level, tiles for streak, XP, lessons and minutes practiced, and links to achievements, the leaderboard and certificates",scaledwidth=40%] + +The learner's page holds their numbers and everything else: badges, the +leaderboard, certificates, the tutor, Pro, purchases, the profile and the +settings. A certificate opens as the PDF itself, with the verification result +beside it, and can be shared. + +image::img/lingo-certificate.png["A certificate of completion shown as the signed PDF, with the verification result and a button to share it",scaledwidth=40%] + +The certificate's QR code opens the server's verification page +for anyone who receives it. + +*Tutor* shows which tutor the phone uses and, on a phone that can run one, +offers to download the on-device model, about 470 MB, on Wi-Fi only unless the +learner says otherwise. + +==== Settings + +image::img/lingo-settings.png["Settings: the profile, the password, the tutor download and cloud tutor switches, and the practice reminder",scaledwidth=40%] + +*Cloud tutor* is off until the learner turns it on: with it on, a phone that +can't run a tutor sends the conversation to the server. The practice reminder +nudges the learner when the day's goal isn't done. The app follows the +device's language and its light or dark mode, or the learner's choice here. + +=== The creator + +image::img/lingo-studio.png["The studio: the earnings, the published courses, drafts and live classes, each course with its learners and price, and the classes coming up",scaledwidth=40%] + +A creator opens on the studio: what the courses have earned, which is 70% of +every sale, and how many learners are in them. *New* starts a course: its +language, level, price and accent color. A course takes three kinds of lessons: + +* phrases, each with its translation and a pronunciation hint; +* a conversation, given as the scene and the tutor's role; +* a video, recorded on the phone or picked from the gallery. + +*Publish* puts the course in the catalogue. A creator can schedule a live class, +start it when it's time, and end it. Learners with a seat are told as it +starts, and join from their Live tab: they see the teacher, and the teacher +sees each of them. + +image::img/lingo-live-room.png["A live class from the teacher's side: the class title, the camera preview, and buttons to mute, turn off the camera, switch cameras and end the class",scaledwidth=40%] + +==== On a desktop + +The same app runs as a desktop application, laid out for a wide window: + +image::img/lingo-desktop-today.png["Lingo in a desktop window: today's goal ring, the course to continue and the week's streak across the full width",scaledwidth=80%] + +image::img/lingo-desktop-studio.png["The studio in a desktop window: earnings, published courses, drafts and live classes",scaledwidth=80%] + +=== The administrator + +The administrator's studio has an extra button at the top, *Accounts*. It lists +everyone who can sign in. Opening an account switches its roles on or off, +including creator, or suspends it. An administrator can't take away their own +admin role or suspend their own account, and the last active administrator +can't be removed. diff --git a/docs/developer-guide/PDF.asciidoc b/docs/developer-guide/PDF.asciidoc index 9caceeff00b..57523098054 100644 --- a/docs/developer-guide/PDF.asciidoc +++ b/docs/developer-guide/PDF.asciidoc @@ -50,6 +50,31 @@ include::../demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSni Nothing in `com.codename1.pdf` touches the UI, so a Codename One backend generates documents with the same classes. A typical use is an endpoint that returns `doc.toByteArray()` with the `application/pdf` content type, or a scheduled job that mails monthly statements. The app and the server can share the code that lays out a document. +=== Signing a PDF + +A certificate of completion, a contract or a statement often has to prove where it came from and that nobody changed it afterward. `PdfDocument.sign` embeds a digital signature when the document is saved. It's a PAdES baseline signature: a detached CMS signature over the whole file, using SHA-256 and carrying the signer's certificate. Acrobat, Preview and Poppler's `pdfsig` show it as signed: + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java[tag=pdf-sign,indent=0] +---- + +`PdfSignature` holds what the reader sees: the reason, the location, the contact details and the signing time, plus an optional visible box on a page. Without `setVisible` the signature is invisible. The key itself stays behind a `PdfSignatureProvider`, which returns the certificate chain and signs one block of bytes when asked. `PdfSigner.provider` builds one over a `PrivateKey` and the platform crypto bridge. On a Codename One server, implement the interface over `com.codename1.backend.Crypto.sign`, or over a hardware security module, and the private key never has to be handed to the PDF code. + +A viewer trusts a signature only when it trusts the certificate. A self-signed certificate produces a valid signature, but an untrusted one. To be trusted by every reader, a document must be signed with a certificate from a CA in the Adobe Approved Trust List. Within your own system, comparing the signer's certificate with the one you expect is enough. + +Reading a signature back doesn't need a viewer. `PdfSignatureInfo.find` returns every signature in a file, and the checks are split by what they need: + +* `isDigestValid()` says whether the signed bytes still hash to the value the signature commits to. +* `coversWholeDocument()` says whether anything was appended after signing. +* `isCertificateBound()` says whether the embedded certificate is the one the signature names. +* `PdfSigner.verify` adds the public-key check. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/pdf/PdfSnippets.java[tag=pdf-verify,indent=0] +---- + === Reading a PDF `PdfReader` opens an existing file to read its page count, page sizes, metadata and text: diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index 5bc5918306f..439160c67d7 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -224,6 +224,10 @@ include::Fieldline-Users-Guide.asciidoc[] include::Fieldline-Implementors-Guide.asciidoc[] +include::Lingo-Users-Guide.asciidoc[] + +include::Lingo-Implementors-Guide.asciidoc[] + = Device and platform services include::Push-Notifications.asciidoc[] diff --git a/docs/developer-guide/img/lingo-certificate.png b/docs/developer-guide/img/lingo-certificate.png new file mode 100644 index 00000000000..da55dc6f983 Binary files /dev/null and b/docs/developer-guide/img/lingo-certificate.png differ diff --git a/docs/developer-guide/img/lingo-conversation.png b/docs/developer-guide/img/lingo-conversation.png new file mode 100644 index 00000000000..b92e8d345d5 Binary files /dev/null and b/docs/developer-guide/img/lingo-conversation.png differ diff --git a/docs/developer-guide/img/lingo-desktop-studio.png b/docs/developer-guide/img/lingo-desktop-studio.png new file mode 100644 index 00000000000..545a401c184 Binary files /dev/null and b/docs/developer-guide/img/lingo-desktop-studio.png differ diff --git a/docs/developer-guide/img/lingo-desktop-today.png b/docs/developer-guide/img/lingo-desktop-today.png new file mode 100644 index 00000000000..756a6927343 Binary files /dev/null and b/docs/developer-guide/img/lingo-desktop-today.png differ diff --git a/docs/developer-guide/img/lingo-live-room.png b/docs/developer-guide/img/lingo-live-room.png new file mode 100644 index 00000000000..99ed1571cee Binary files /dev/null and b/docs/developer-guide/img/lingo-live-room.png differ diff --git a/docs/developer-guide/img/lingo-me-dark.png b/docs/developer-guide/img/lingo-me-dark.png new file mode 100644 index 00000000000..da785eb8be9 Binary files /dev/null and b/docs/developer-guide/img/lingo-me-dark.png differ diff --git a/docs/developer-guide/img/lingo-phrase-scored.png b/docs/developer-guide/img/lingo-phrase-scored.png new file mode 100644 index 00000000000..c5380fc0f65 Binary files /dev/null and b/docs/developer-guide/img/lingo-phrase-scored.png differ diff --git a/docs/developer-guide/img/lingo-phrase.png b/docs/developer-guide/img/lingo-phrase.png new file mode 100644 index 00000000000..362237ac9ab Binary files /dev/null and b/docs/developer-guide/img/lingo-phrase.png differ diff --git a/docs/developer-guide/img/lingo-reward.png b/docs/developer-guide/img/lingo-reward.png new file mode 100644 index 00000000000..5e4c04b4673 Binary files /dev/null and b/docs/developer-guide/img/lingo-reward.png differ diff --git a/docs/developer-guide/img/lingo-settings.png b/docs/developer-guide/img/lingo-settings.png new file mode 100644 index 00000000000..dd19bf35970 Binary files /dev/null and b/docs/developer-guide/img/lingo-settings.png differ diff --git a/docs/developer-guide/img/lingo-studio.png b/docs/developer-guide/img/lingo-studio.png new file mode 100644 index 00000000000..036ea6b956d Binary files /dev/null and b/docs/developer-guide/img/lingo-studio.png differ diff --git a/docs/developer-guide/img/lingo-today.png b/docs/developer-guide/img/lingo-today.png new file mode 100644 index 00000000000..02666dffafc Binary files /dev/null and b/docs/developer-guide/img/lingo-today.png differ diff --git a/docs/developer-guide/img/lingo-video-lesson.png b/docs/developer-guide/img/lingo-video-lesson.png new file mode 100644 index 00000000000..a675adce14e Binary files /dev/null and b/docs/developer-guide/img/lingo-video-lesson.png differ diff --git a/docs/developer-guide/img/lingo-welcome.png b/docs/developer-guide/img/lingo-welcome.png new file mode 100644 index 00000000000..4ee83c0a015 Binary files /dev/null and b/docs/developer-guide/img/lingo-welcome.png differ diff --git a/docs/developer-guide/languagetool-accept.txt b/docs/developer-guide/languagetool-accept.txt index 5e4a9c4aa2e..97577118812 100644 --- a/docs/developer-guide/languagetool-accept.txt +++ b/docs/developer-guide/languagetool-accept.txt @@ -966,4 +966,6 @@ EdXposed Shamiko callees supertypes +Travellers +Poppler Laza diff --git a/maven/build-engine/src/main/java/com/codename1/maven/annotations/ProcessorContext.java b/maven/build-engine/src/main/java/com/codename1/maven/annotations/ProcessorContext.java index 86395b77387..75e7e3c4c3b 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/annotations/ProcessorContext.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/annotations/ProcessorContext.java @@ -269,6 +269,16 @@ public Map getEmittedResources() { private final Map attributes = new LinkedHashMap(); + private final Map backingSources = new java.util.HashMap(); + + /// Whether a source still backs each class, by binary name, as answered + /// once in this run. The sources do not change during a run, and the + /// question is asked again for every class each time the bean graph is + /// planned -- once per test context -- which walked the source tree some + /// hundred million times for a module of a thousand classes and a hundred + /// test classes. + public Map getBackingSources() { return backingSources; } + /// Shares a result between processors of one run -- the backend's bean graph /// is computed once and read by the processor that writes the entry point. public void setAttribute(String key, Object value) { attributes.put(key, value); } diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java index 8adee67f4d5..74eb504e1b0 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java @@ -982,8 +982,14 @@ private boolean concerns(AnnotatedClass cls) { if (cls.isSynthetic() || cls.getClassAnnotation(GENERATED) != null) { return false; } - return BuildHintAnnotationProcessor.hasBackingSource(cls, ctx.getCompileSourceRoots(), - ctx.getSourceEncoding()); + Map known = ctx.getBackingSources(); + Boolean answer = known.get(cls.getBinaryName()); + if (answer == null) { + answer = Boolean.valueOf(BuildHintAnnotationProcessor.hasBackingSource(cls, + ctx.getCompileSourceRoots(), ctx.getSourceEncoding())); + known.put(cls.getBinaryName(), answer); + } + return answer.booleanValue(); } private static boolean isStereotyped(AnnotatedClass cls) { diff --git a/maven/core-unittests/src/test/java/com/codename1/pdf/PdfSignatureTest.java b/maven/core-unittests/src/test/java/com/codename1/pdf/PdfSignatureTest.java new file mode 100644 index 00000000000..08355d9bd0c --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/pdf/PdfSignatureTest.java @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pdf; + +import com.codename1.junit.UITestBase; +import com.codename1.security.PrivateKey; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/// Signs generated documents and reads the signatures back, through the +/// device API ([PdfSigner]) and, when `openssl` is installed, through an +/// independent CMS verifier. +class PdfSignatureTest extends UITestBase { + + @Test + void rsaSignatureRoundTrips() throws Exception { + KeyPair kp = jdkKeys("RSA", 2048); + byte[] cert = selfSignedCertificate(kp, "SHA256withRSA", "Lingo Test Academy"); + byte[] pdf = signedCertificate(PrivateKey.fromPkcs8("RSA", kp.getPrivate().getEncoded()), cert, true); + + List sigs = PdfSignatureInfo.find(pdf); + assertEquals(1, sigs.size()); + PdfSignatureInfo info = sigs.get(0); + assertTrue(info.isDigestValid()); + assertTrue(info.isCertificateBound()); + assertTrue(info.coversWholeDocument()); + assertEquals("SHA256withRSA", info.getSignatureAlgorithm()); + assertEquals("Lingo Test Academy", info.getSignerName()); + assertArrayEquals(cert, info.getSignerCertificate()); + assertTrue(PdfSigner.verify(info)); + // Still a readable PDF with its text intact. + assertTrue(PdfReader.open(pdf).extractText(0).contains("Certificate of Completion")); + opensslVerify(pdf, info, cert); + pdfsigVerify(pdf); + } + + @Test + void ecSignatureRoundTrips() throws Exception { + KeyPair kp = jdkKeys("EC", 256); + byte[] cert = selfSignedCertificate(kp, "SHA256withECDSA", "EC Signer"); + byte[] pdf = signedCertificate(PrivateKey.fromPkcs8("EC", kp.getPrivate().getEncoded()), cert, false); + PdfSignatureInfo info = PdfSignatureInfo.find(pdf).get(0); + assertEquals("SHA256withECDSA", info.getSignatureAlgorithm()); + assertTrue(PdfSigner.verify(info)); + } + + @Test + void tamperingIsDetected() throws Exception { + KeyPair kp = jdkKeys("RSA", 2048); + byte[] cert = selfSignedCertificate(kp, "SHA256withRSA", "Tamper"); + byte[] pdf = signedCertificate(PrivateKey.fromPkcs8("RSA", kp.getPrivate().getEncoded()), cert, true); + int at = indexOf(pdf, "/Producer (Codename One)"); + assertTrue(at > 0); + pdf[at + 11] = 'X'; + PdfSignatureInfo info = PdfSignatureInfo.find(pdf).get(0); + assertFalse(info.isDigestValid()); + assertFalse(PdfSigner.verify(info)); + } + + @Test + void appendedBytesAreReported() throws Exception { + KeyPair kp = jdkKeys("EC", 256); + byte[] cert = selfSignedCertificate(kp, "SHA256withECDSA", "Append"); + byte[] pdf = signedCertificate(PrivateKey.fromPkcs8("EC", kp.getPrivate().getEncoded()), cert, false); + byte[] longer = new byte[pdf.length + 8]; + System.arraycopy(pdf, 0, longer, 0, pdf.length); + PdfSignatureInfo info = PdfSignatureInfo.find(longer).get(0); + assertTrue(info.isDigestValid()); + assertFalse(info.coversWholeDocument()); + } + + @Test + void unsignedDocumentHasNoSignatures() throws Exception { + PdfDocument doc = new PdfDocument(); + doc.addPage(PdfPageSize.A4); + assertTrue(PdfSignatureInfo.find(doc.toByteArray()).isEmpty()); + } + + @Test + void tooSmallReservationFails() throws Exception { + KeyPair kp = jdkKeys("RSA", 2048); + byte[] cert = selfSignedCertificate(kp, "SHA256withRSA", "Small"); + PdfDocument doc = new PdfDocument(); + doc.addPage(PdfPageSize.A4); + doc.sign(new PdfSignature(PdfSigner.provider(PrivateKey.fromPkcs8("RSA", kp.getPrivate().getEncoded()), + cert)).setReservedBytes(1024)); + assertThrows(IllegalStateException.class, doc::toByteArray); + } + + private static byte[] signedCertificate(PrivateKey key, byte[] cert, boolean visible) throws Exception { + PdfDocument doc = new PdfDocument().setTitle("Certificate"); + PdfPage page = doc.addPage(PdfPageSize.A4); + PdfCanvas c = page.getCanvas(); + c.setFont(PdfFont.HELVETICA_BOLD, 28); + c.drawText("Certificate of Completion", 72, 120); + PdfSignature sig = new PdfSignature(PdfSigner.provider(key, cert)) + .setReason("Completed Spanish A1") + .setLocation("Lingo"); + if (visible) { + sig.setVisible(page, 360, 720, 180, 50); + } + doc.sign(sig); + return doc.toByteArray(); + } + + private static KeyPair jdkKeys(String alg, int bits) throws Exception { + KeyPairGenerator g = KeyPairGenerator.getInstance(alg); + g.initialize(bits); + return g.generateKeyPair(); + } + + /// A minimal v3 self-signed certificate, encoded by hand so the test + /// needs no JDK-internal X.509 classes. + static byte[] selfSignedCertificate(KeyPair kp, String alg, String cn) throws Exception { + byte[] algId = "SHA256withRSA".equals(alg) + ? seq(cat(oid("1.2.840.113549.1.1.11"), new byte[] {5, 0})) + : seq(oid("1.2.840.10045.4.3.2")); + byte[] name = seq(tlv(0x31, seq(cat(oid("2.5.4.3"), tlv(0x0C, cn.getBytes("UTF-8")))))); + byte[] validity = seq(cat(tlv(0x17, "260101000000Z".getBytes("US-ASCII")), + tlv(0x17, "360101000000Z".getBytes("US-ASCII")))); + byte[] tbs = seq(cat( + tlv(0xA0, tlv(0x02, new byte[] {2})), + tlv(0x02, BigInteger.valueOf(System.nanoTime() & 0x7fffffffL).toByteArray()), + algId, name, validity, name, + kp.getPublic().getEncoded())); + java.security.Signature s = java.security.Signature.getInstance(alg); + s.initSign(kp.getPrivate()); + s.update(tbs); + byte[] sig = s.sign(); + return seq(cat(tbs, algId, tlv(0x03, cat(new byte[] {0}, sig)))); + } + + /// Hands the embedded CMS to `openssl cms -verify` over the signed byte + /// ranges, when openssl is on the path. + private static void opensslVerify(byte[] pdf, PdfSignatureInfo info, byte[] cert) throws Exception { + if (!onPath("openssl")) { + return; + } + long[] br = info.getByteRange(); + ByteArrayOutputStream content = new ByteArrayOutputStream(); + content.write(pdf, 0, (int) br[1]); + content.write(pdf, (int) br[2], (int) br[3]); + String hex = new String(pdf, (int) br[1] + 1, (int) (br[2] - br[1] - 2), "US-ASCII"); + File dir = java.nio.file.Files.createTempDirectory("pdfsig").toFile(); + File data = write(new File(dir, "data.bin"), content.toByteArray()); + File cms = write(new File(dir, "sig.der"), trimHex(hex)); + File ca = write(new File(dir, "ca.der"), cert); + Process conv = new ProcessBuilder("openssl", "x509", "-inform", "DER", "-in", ca.getPath(), + "-out", new File(dir, "ca.pem").getPath()).redirectErrorStream(true).start(); + assertEquals(0, conv.waitFor()); + Process p = new ProcessBuilder("openssl", "cms", "-verify", "-binary", "-inform", "DER", + "-in", cms.getPath(), "-content", data.getPath(), "-CAfile", + new File(dir, "ca.pem").getPath(), "-purpose", "any", "-out", "/dev/null") + .redirectErrorStream(true).start(); + ByteArrayOutputStream log = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = p.getInputStream().read(buf)) > 0) { + log.write(buf, 0, n); + } + String out = new String(log.toByteArray(), "UTF-8"); + assertEquals(0, p.waitFor(), out); + } + + /// Poppler's `pdfsig`, when installed, reads the file the way a viewer + /// does: the signature field, the byte range and the CMS together. + private static void pdfsigVerify(byte[] pdf) throws Exception { + if (!onPath("pdfsig")) { + return; + } + File f = write(File.createTempFile("signed", ".pdf"), pdf); + Process p = new ProcessBuilder("pdfsig", f.getPath()).redirectErrorStream(true).start(); + ByteArrayOutputStream log = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = p.getInputStream().read(buf)) > 0) { + log.write(buf, 0, n); + } + p.waitFor(); + String out = new String(log.toByteArray(), "UTF-8"); + assertTrue(out.contains("Signature Validation: Signature is Valid."), out); + assertTrue(out.contains("Total document signed"), out); + } + + private static byte[] trimHex(String hex) { + byte[] all = new byte[hex.length() / 2]; + for (int i = 0; i < all.length; i++) { + all[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); + } + // One DER element; the zero padding after it is not part of the CMS. + int len = all[1] & 0xff; + int header = 2; + if (len >= 0x80) { + int n = len & 0x7f; + len = 0; + for (int i = 0; i < n; i++) { + len = (len << 8) | (all[2 + i] & 0xff); + } + header += n; + } + byte[] out = new byte[header + len]; + System.arraycopy(all, 0, out, 0, out.length); + return out; + } + + private static boolean onPath(String tool) { + try { + return new ProcessBuilder(tool, "pdfsig".equals(tool) ? "-v" : "version").redirectErrorStream(true).start().waitFor() == 0; + } catch (Exception e) { + return false; + } + } + + private static File write(File f, byte[] b) throws Exception { + FileOutputStream o = new FileOutputStream(f); + try { + o.write(b); + } finally { + o.close(); + } + return f; + } + + private static int indexOf(byte[] data, String s) throws Exception { + byte[] key = s.getBytes("US-ASCII"); + outer: + for (int i = 0; i <= data.length - key.length; i++) { + for (int j = 0; j < key.length; j++) { + if (data[i + j] != key[j]) { + continue outer; + } + } + return i; + } + return -1; + } + + private static byte[] oid(String dotted) { + String[] parts = dotted.split("\\."); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + bo.write(Integer.parseInt(parts[0]) * 40 + Integer.parseInt(parts[1])); + for (int i = 2; i < parts.length; i++) { + long v = Long.parseLong(parts[i]); + int groups = 1; + for (long t = v >>> 7; t != 0; t >>>= 7) { + groups++; + } + for (int g = groups - 1; g >= 0; g--) { + int b = (int) ((v >>> (7 * g)) & 0x7f); + bo.write(g == 0 ? b : b | 0x80); + } + } + return tlv(0x06, bo.toByteArray()); + } + + private static byte[] seq(byte[] c) { + return tlv(0x30, c); + } + + private static byte[] tlv(int tag, byte[] c) { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + bo.write(tag); + if (c.length < 0x80) { + bo.write(c.length); + } else if (c.length < 0x100) { + bo.write(0x81); + bo.write(c.length); + } else { + bo.write(0x82); + bo.write(c.length >> 8); + bo.write(c.length); + } + bo.write(c, 0, c.length); + return bo.toByteArray(); + } + + private static byte[] cat(byte[]... parts) { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + for (byte[] p : parts) { + bo.write(p, 0, p.length); + } + return bo.toByteArray(); + } +} diff --git a/scripts/check-copyright-headers.sh b/scripts/check-copyright-headers.sh index be32b90b0bf..6c1eaf443f4 100755 --- a/scripts/check-copyright-headers.sh +++ b/scripts/check-copyright-headers.sh @@ -38,11 +38,11 @@ is_excluded() { local candidate="$1" # What Initializr puts into a generated project is the developer's, not # Codename One's GPLv2 + Classpath Exception source: these trees are released - # under MIT No Attribution (scripts/wayline/LICENSE, scripts/savor/LICENSE, scripts/bazaar/LICENSE, scripts/skirmish/LICENSE, scripts/dash/LICENSE, scripts/parley/LICENSE, scripts/pulse/LICENSE, scripts/slate/LICENSE, scripts/splat/LICENSE, scripts/papercut/LICENSE, scripts/fieldline/LICENSE, scripts/brickyard/LICENSE, + # under MIT No Attribution (scripts/wayline/LICENSE, scripts/savor/LICENSE, scripts/bazaar/LICENSE, scripts/skirmish/LICENSE, scripts/dash/LICENSE, scripts/parley/LICENSE, scripts/pulse/LICENSE, scripts/slate/LICENSE, scripts/splat/LICENSE, scripts/papercut/LICENSE, scripts/fieldline/LICENSE, scripts/lingo/LICENSE, scripts/brickyard/LICENSE, # scripts/bastion/LICENSE, scripts/reel/LICENSE), and carry that header # or none. case "$candidate" in - scripts/wayline/*|scripts/savor/*|scripts/bazaar/*|scripts/skirmish/*|scripts/dash/*|scripts/parley/*|scripts/bastion/*|scripts/reel/*|scripts/pulse/*|scripts/slate/*|scripts/splat/*|scripts/papercut/*|scripts/fieldline/*|scripts/brickyard/*|maven/cn1app-archetype/src/main/resources/archetype-resources/*|scripts/initializr/common/src/main/resources/skill/*) return 0 ;; + scripts/wayline/*|scripts/savor/*|scripts/bazaar/*|scripts/skirmish/*|scripts/dash/*|scripts/parley/*|scripts/bastion/*|scripts/reel/*|scripts/pulse/*|scripts/slate/*|scripts/splat/*|scripts/papercut/*|scripts/fieldline/*|scripts/lingo/*|scripts/brickyard/*|maven/cn1app-archetype/src/main/resources/archetype-resources/*|scripts/initializr/common/src/main/resources/skill/*) return 0 ;; esac # Design Import's gallery is the tool's own output, regenerated by ExamplesTest: a form, # a stylesheet and a test written for whoever runs the tool, which carry no header by diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java index e6bf43d9d3d..017ed6536fd 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java @@ -469,7 +469,7 @@ private Container createLanguageSelector(Template[] selectedTemplate, Runnable o } Template[] apps = {Template.WAYLINE, Template.SAVOR, Template.BAZAAR, Template.SKIRMISH, Template.DASH, Template.SPLAT, Template.PAPERCUT, Template.PARLEY, Template.BASTION, Template.REEL, Template.PULSE, - Template.SLATE, Template.FIELDLINE}; + Template.SLATE, Template.FIELDLINE, Template.LINGO}; int offered = 0; for (Template app : apps) { if (GeneratorModel.isTemplateOffered(app)) { @@ -520,6 +520,7 @@ static String templateTitle(Template template) { : template == Template.PULSE ? "Fitness studio" : template == Template.SLATE ? "Appointment booking" : template == Template.FIELDLINE ? "Field service" + : template == Template.LINGO ? "Language learning" : template == Template.BAZAAR ? "Commerce platform" : template.IS_KOTLIN ? "Empty app, Kotlin" : "Empty app, Java"; } diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java index f45a7215cec..b3d5006c546 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java @@ -128,6 +128,12 @@ public static boolean isMavenLayoutChoiceOffered() { /// template is neither offered nor generated. static final String BAZAAR_SINCE = "7.0.284"; + /// The first release the language learning template is offered from. It + /// signs its certificates with the core PDF signing API, and the releases + /// before it lack that API, so the template is neither offered nor + /// generated before then. + static final String LINGO_SINCE = BAZAAR_SINCE; + /// The first release a template can be generated against. static String templateSince(Template template) { return template == Template.BASTION ? BASTION_SINCE @@ -136,6 +142,7 @@ static String templateSince(Template template) { : template == Template.PAPERCUT ? PAPERCUT_SINCE : template == Template.SLATE ? SLATE_SINCE : template == Template.FIELDLINE ? FIELDLINE_SINCE + : template == Template.LINGO ? LINGO_SINCE : template == Template.BAZAAR ? BAZAAR_SINCE : JAVA_TIME_ENTITIES_SINCE; } @@ -177,6 +184,9 @@ static String templateSince(Template template) { /// The field service template's `--brand`, held to its theme.css the same way. public static final int FIELDLINE_BRAND = 0x4f46e5; + /// The language learning template's `--brand`, held to its theme.css the same way. + public static final int LINGO_BRAND = 0x4f46e5; + /// The commerce template's `--brand`, held to its theme.css the same way. public static final int BAZAAR_BRAND = 0x4f46e5; @@ -198,6 +208,9 @@ public static int brandOf(Template template) { if (template == Template.FIELDLINE) { return FIELDLINE_BRAND; } + if (template == Template.LINGO) { + return LINGO_BRAND; + } if (template == Template.BAZAAR) { return BAZAAR_BRAND; } @@ -2199,6 +2212,8 @@ private String buildReadmeMarkdown() { appendBankSection(out, toLowerCaseInvariant(appName)); } else if (template == Template.FIELDLINE) { appendFieldSection(out, toLowerCaseInvariant(appName)); + } else if (template == Template.LINGO) { + appendLingoSection(out, toLowerCaseInvariant(appName)); } else if (template.isFullStack()) { boolean food = template == Template.SAVOR; boolean shop = template == Template.BAZAAR; @@ -2410,6 +2425,38 @@ private static void appendFieldSection(StringBuilder out, String lower) { .append("engine's and the server's tests.\n\n"); } + /// The README section of the language learning template: what the project is, + /// how to run it and the accounts its development profile creates. + private static void appendLingoSection(StringBuilder out, String lower) { + out.append("## The app and its server\n\n") + .append("This project is a working language learning app: learners, creators and an admin mode ") + .append("in one app, chosen by the role of whoever signs in, and the server they talk to.\n\n") + .append("- `shared/` is the contract: the REST interfaces and the objects they carry. The app's ") + .append("client and the server's dispatcher are both generated from it, so the two cannot drift.\n") + .append("- `backend/` is the server: accounts and roles, courses and lessons, progress, XP, ") + .append("streaks and badges, the leaderboard, simulated payments with a 70% creator share, live ") + .append("classes, signed PDF certificates (`/verify/{id}` checks one), the cloud tutor and the ") + .append("database migrations.\n") + .append("- `common/` is the app: pronunciation practice scored word by word (speech recognition ") + .append("and text to speech) and conversation with an AI tutor that runs on the device, then a ") + .append("downloadable model, then an opt-in cloud tutor, then a scripted partner. ") + .append("`src/main/css/theme.css` opens with the colours and corner radius every screen takes ") + .append("its look from.\n\n") + .append("Start the server, then, in a second terminal, the app:\n\n```\n") + .append("./run-server.sh\n") + .append("./run.sh\n```\n\n") + .append("On Windows: `run-server.bat`, then `run.bat`. Your IDE's run menu has both: ") + .append("\"Run Server\" and the simulator.\n\n") + .append("On the `dev` profile the server creates demonstration accounts, all with the ") + .append("password `").append(lower).append("-demo`: `learner@").append(lower) + .append(".example` and `learner2@").append(lower).append(".example`, learners with some ") + .append("progress, `creator@").append(lower).append(".example`, who publishes courses and runs ") + .append("live classes, and `admin@").append(lower).append(".example`.\n\n") + .append("Payments are simulated; the passwords, the certificate signatures and the live-class ") + .append("connections are real.\n\n") + .append("`./mvnw -pl backend -am -Dcodename1.platform=backend test` runs the server's tests.\n\n"); + } + private static void appendBankSection(StringBuilder out, String lower) { out.append("## The app and its server\n\n") .append("This project is a working bank: a customer and an admin mode in one app, chosen by the ") diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java index e393a777625..5fb0ae6fae2 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java @@ -165,7 +165,17 @@ public enum Template { "com.codenameone.examples.fieldline", "Fieldline", "/fieldline-preview.jpg", "The field service template is an app, a server and the module they share, " + "which holds the contract and the scheduling engine; an Initializr Gradle project is a single project.", - new String[0], "/fieldline-modules.zip", "/fieldline-settings.properties"); + new String[0], "/fieldline-modules.zip", "/fieldline-settings.properties"), + // The same kind of template as WAYLINE: language learning (learners and + // the creators who publish courses and run live classes) and its server, + // with the contract in the `shared` module both halves depend on. It is the + // project in scripts/lingo, and its resources come from + // `scripts/sync-initializr-template.py lingo`. + LINGO(false, "/lingo-src.zip", "/lingo-css.zip", "/lingo-pom.xml", + "com.codenameone.examples.lingo", "Lingo", "/lingo-preview.jpg", + "The language learning template is an app, a server and the contract module they share; " + + "an Initializr Gradle project is a single project.", + new String[0], "/lingo-modules.zip", "/lingo-settings.properties"); /// The resource holding the picture shown for a template that has no live /// preview, or null for one that has. diff --git a/scripts/initializr/common/src/main/resources/lingo-css.zip b/scripts/initializr/common/src/main/resources/lingo-css.zip new file mode 100644 index 00000000000..f88c7ad503e Binary files /dev/null and b/scripts/initializr/common/src/main/resources/lingo-css.zip differ diff --git a/scripts/initializr/common/src/main/resources/lingo-modules.zip b/scripts/initializr/common/src/main/resources/lingo-modules.zip new file mode 100644 index 00000000000..10c72a134b3 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/lingo-modules.zip differ diff --git a/scripts/initializr/common/src/main/resources/lingo-pom.xml b/scripts/initializr/common/src/main/resources/lingo-pom.xml new file mode 100644 index 00000000000..aef41e0be1f --- /dev/null +++ b/scripts/initializr/common/src/main/resources/lingo-pom.xml @@ -0,0 +1,422 @@ + + + 4.0.0 + + com.example.myapp + myappname + 1.0-SNAPSHOT + + com.example.myapp + myappname-common + 1.0-SNAPSHOT + jar + + + + + + ${project.groupId} + myappname-shared + ${project.version} + + + + com.codenameone + cn1-app-kit-lib + ${cn1.version} + pom + + + com.codenameone + codenameone-core + + + com.codenameone + codenameone-javase + test + + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + + + + + install-codenameone + ${user.home}/.codenameone/guibuilder.jar + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + kotlin + + + + ${basedir}/src/main/kotlin + + + + 2.2.10 + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + + org.jetbrains + annotations + 13.0 + + + com.codenameone + java-runtime + provided + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + + -no-reflect + -no-jdk + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + -no-reflect + -no-jdk + + + + + + + + + + + + + javase + + + codename1.platform + javase + + + + javase + + + + + org.codehaus.mojo + exec-maven-plugin + + java + true + + -Xmx1024M + + -classpath + + ${exec.mainClass} + ${cn1.mainClass} + + + + + + + + + + simulator + + javase + + + + + + ios-debug + + + iphone + + + ios + + + + + ios-release + + + iphone + true + + + ios + true + + + + + javascript + + javascript + javascript + + + + + android + + android + android + + + + + windows + + desktop_windows + javase + + + + + mac + + desktop_macosx + javase + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + + com.codenameone + codenameone-maven-plugin + + + xalan + serializer + 2.7.3 + + + + + + generate-gui-sources + process-sources + + generate-gui-sources + + + + cn1-process-classes + process-classes + + bytecode-compliance + css + + process-annotations + + + + + attach-test-artifact + test + + attach-test-artifact + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + + + diff --git a/scripts/initializr/common/src/main/resources/lingo-preview.jpg b/scripts/initializr/common/src/main/resources/lingo-preview.jpg new file mode 100644 index 00000000000..559e02c3a57 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/lingo-preview.jpg differ diff --git a/scripts/initializr/common/src/main/resources/lingo-settings.properties b/scripts/initializr/common/src/main/resources/lingo-settings.properties new file mode 100644 index 00000000000..5010adb9d74 --- /dev/null +++ b/scripts/initializr/common/src/main/resources/lingo-settings.properties @@ -0,0 +1,21 @@ +# A server started on this machine is reached over plain HTTP, which Android +# refuses by default. Remove this once the app talks to a server with a +# certificate. +codename1.arg.android.xapplication_attr=android\:usesCleartextTraffic\="true" +# What iOS shows before a creator records a video lesson or holds a live class. +codename1.arg.ios.NSCameraUsageDescription=The camera records your video lessons and shows you in live classes. +# What iOS shows when a creator picks a video they already recorded. +codename1.arg.ios.NSPhotoLibraryUsageDescription=Your library is where you pick a video lesson you already recorded. +# The microphone hears a learner say each phrase, and carries their voice in a live class. +codename1.arg.ios.NSMicrophoneUsageDescription=Lingo listens as you say each phrase, to score your pronunciation, and carries your voice in live classes. +# What iOS shows before speech recognition turns what was said into words to score. +codename1.arg.ios.NSSpeechRecognitionUsageDescription=Speech recognition writes down what you said, so Lingo can score each word. +# What iOS shows before Face ID unlocks the sign-in kept in secure storage. +codename1.arg.ios.NSFaceIDUsageDescription=Authenticate to securely access your account +# Push notifications. With push included the build adds the +# remote-notification background mode and the push entitlement itself. +codename1.arg.ios.includePush=true +# Android push is off until the app has its Firebase file: a build that +# uses PushClient without google-services.json stops with an error. Once +# native/android/google-services.json is in place, delete this line. +codename1.arg.android.messagingService=none diff --git a/scripts/initializr/common/src/main/resources/lingo-src.zip b/scripts/initializr/common/src/main/resources/lingo-src.zip new file mode 100644 index 00000000000..972487053e0 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/lingo-src.zip differ diff --git a/scripts/initializr/common/src/main/resources/skill/references/demos.md b/scripts/initializr/common/src/main/resources/skill/references/demos.md index 99a393eae38..a004059d7ec 100644 --- a/scripts/initializr/common/src/main/resources/skill/references/demos.md +++ b/scripts/initializr/common/src/main/resources/skill/references/demos.md @@ -48,6 +48,7 @@ README of each lists the demo accounts. | `scripts/pulse` | Gym and studio: member, trainer, front desk, owner | Health and workouts (`com.codename1.health`), a watch companion (`wearable`), rotating QR and NFC door passes (`codescan`, `nfc`), class booking with waitlists and device calendar, households and kids' bookings, an owner dashboard with charts and a desktop master-detail layout, server-side billing with dunning and engagement nudges over push | | `scripts/slate` | Generic appointment booking for salons, tutors, trainers and consultants: client, provider, front desk, owner | Multi-party availability, slot rules (buffers, gaps, travel time), day, week and agenda views, device and Google, Microsoft and ICS calendar sync, simulated deposits | | `scripts/fieldline` | Field service and inspections: technician, dispatcher | A scheduling engine in `shared` (`scheduler`) (regret insertion, adaptive large neighbourhood search, repair on time off), the resource timeline and Gantt views of `com.codename1.ui.scheduler` (`dispatch/BoardForm.java`), a route of numbered map markers and background location (`field/TodayForm.java`, `field/Tracker.java`), checklists, camera photos and an AI diagnosis behind the server's key (`field/JobForm.java`, server `ai/`), a `SignatureComponent` sign-off sealed with a hash (`field/SignOffForm.java`), and write-only device calendar sync (`field/CalendarSync.java`) | +| `scripts/lingo` | Language learning: learner, creator, admin | On-device pronunciation scoring word by word (speech recognition and text to speech) and conversation with an AI tutor that falls back from the device to a downloadable model, an opt-in cloud tutor and a scripted partner (`learn/TutorForm.java`, `ai/`), community courses with video, phrase and conversation lessons, live classes over WebRTC (`live/`), simulated payments with a 70% creator share, signed PDF certificates the server signs with the core PDF signing API and `/verify/{id}` checks, XP, streaks, badges and a leaderboard | | `scripts/skirmish` | Real-time 3D card battler | Games: `GameView`/3D rendering (`battle/`), a deterministic simulation in `shared` run by app, server and tests, replays, in-app purchases and rewarded ads (`engage/`), matchmaking over sockets, in-app editors (`forge/`) | | `scripts/splat` | Team paintball first-person shooter: player, admin console | Games: 3D first-person rendering with `GameView` (`play/`), a deterministic simulation in `shared` that the server runs as the authority while the app predicts and reconciles (`play/OnlineDriver`), lag-compensated hits, bots inside the rules, parties with voice, crews and replays over sockets (`net/`, `game/`), in-app purchases and rewarded ads (`engage/`) | | `scripts/papercut` | Twin-stick arena shooter on a sheet of paper: player, admin console | Games: 2D `GameView` with twin sticks, keys and gamepad (`play/`), the whole simulation in one class with no UI (`play/Arena`), score plausibility checked on the server with no rules module (`ScoreBounds`), daily seeded sheet, boards, in-app purchases and rewarded ads (`engage/`) | diff --git a/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java b/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java index bd32254ca52..748fc958e09 100644 --- a/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java +++ b/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java @@ -133,6 +133,7 @@ public boolean runTest() throws Exception { validateSplatGate(); validateSlateGate(); validateFieldlineGate(); + validateLingoGate(); validateBazaarGate(); validateCommandLineProject(); for (Template template : Template.values()) { @@ -430,6 +431,7 @@ private void assertFullStackProject(Template template, Map entri boolean studio = template == Template.PULSE; boolean booking = template == Template.SLATE; boolean field = template == Template.FIELDLINE; + boolean lingo = template == Template.LINGO; boolean shop = template == Template.BAZAAR; String name = template.SOURCE_MAIN_CLASS; String upper = template.name(); @@ -445,12 +447,12 @@ private void assertFullStackProject(Template template, Map entri // project once got the ride-hailing accounts and chapters. String readme = getText(entries, "README.md"); boolean chat = template == Template.PARLEY; - assertContains(readme, game ? (runner ? "endless runner" : paintball ? "paintball shooter" : arena ? "arena shooter" : "card battler") : rides ? "ride-hailing app" : chat ? "messaging app" : bank ? "working bank" : studio ? "fitness studio app" : field ? "field service app" : shop ? "commerce platform" : booking ? "appointment booking app" : video ? "video streaming service" : "food-delivery app", + assertContains(readme, game ? (runner ? "endless runner" : paintball ? "paintball shooter" : arena ? "arena shooter" : "card battler") : rides ? "ride-hailing app" : chat ? "messaging app" : bank ? "working bank" : studio ? "fitness studio app" : field ? "field service app" : lingo ? "language learning app" : shop ? "commerce platform" : booking ? "appointment booking app" : video ? "video streaming service" : "food-delivery app", label + "README names the app"); if (!game) { - assertContains(readme, (rides ? "`rider@" : chat ? "`alice@" : bank ? "`customer2@" : studio ? "`member@" : field ? "`tech@" : shop ? "`shopper@" : booking ? "`client@" : video ? "`viewer@" : "`customer@") + artifact + ".example`", + assertContains(readme, (rides ? "`rider@" : chat ? "`alice@" : bank ? "`customer2@" : studio ? "`member@" : field ? "`tech@" : lingo ? "`learner@" : shop ? "`shopper@" : booking ? "`client@" : video ? "`viewer@" : "`customer@") + artifact + ".example`", label + "README lists the template's own demo accounts"); - assertFalse(readme.indexOf(rides || chat || bank || video || studio || booking || field || shop ? "courier@" : "rider@") >= 0, + assertFalse(readme.indexOf(rides || chat || bank || video || studio || booking || field || lingo || shop ? "courier@" : "rider@") >= 0, label + "README carries no other template's accounts"); assertFalse(chat && readme.indexOf("rider@") >= 0, label + "README carries no ride-hailing accounts"); } @@ -467,15 +469,15 @@ private void assertFullStackProject(Template template, Map entri assertContains(getText(entries, "backend/pom.xml"), "generate-annotation-stubs", label + "the server generates its half of the contract"); - assertContains(getText(entries, "shared/src/main/java/" + packagePath + (game ? "/api/AccountApi.java" : rides ? "/api/RiderApi.java" : chat ? "/api/MessageApi.java" : bank ? "/api/BankingApi.java" : video ? "/api/CatalogApi.java" : studio ? "/api/BookingApi.java" : field ? "/api/FieldApi.java" : booking ? "/api/AppointmentApi.java" : "/api/OrderApi.java")), + assertContains(getText(entries, "shared/src/main/java/" + packagePath + (game ? "/api/AccountApi.java" : rides ? "/api/RiderApi.java" : chat ? "/api/MessageApi.java" : bank ? "/api/BankingApi.java" : video ? "/api/CatalogApi.java" : studio ? "/api/BookingApi.java" : field ? "/api/FieldApi.java" : lingo ? "/api/LearnApi.java" : booking ? "/api/AppointmentApi.java" : "/api/OrderApi.java")), "package " + packageName + ".api;", label + "the contract moves to the project's package"); assertContains(getText(entries, "backend/src/main/java/" + packagePath + "/SecurityConfig.java"), "package " + packageName + ";", label + "the server moves to the project's package"); assertNotNull(entries.get("backend/src/main/resources/db/migration/" + (game ? "V1__game.sql" : bank ? "V4__accounts.sql" : studio || booking ? "V2__accounts.sql" : "V1__accounts.sql")), label + "the server keeps its migrations"); - assertNotNull(entries.get("backend/src/test/java/" + packagePath + (arena ? "/RunTest.java" : game ? "/GameSocketTest.java" : rides ? "/RideFlowTest.java" : chat ? "/MessagingTest.java" : bank ? "/LedgerTest.java" : video ? "/PlaybackTest.java" : studio ? "/StudioTest.java" : field ? "/FieldTest.java" : shop ? "/AccountTest.java" : booking ? "/booking/BookingFlowTest.java" : "/OrderFlowTest.java")), + assertNotNull(entries.get("backend/src/test/java/" + packagePath + (arena ? "/RunTest.java" : game ? "/GameSocketTest.java" : rides ? "/RideFlowTest.java" : chat ? "/MessagingTest.java" : bank ? "/LedgerTest.java" : video ? "/PlaybackTest.java" : studio ? "/StudioTest.java" : field ? "/FieldTest.java" : lingo ? "/LearningTest.java" : shop ? "/AccountTest.java" : booking ? "/booking/BookingFlowTest.java" : "/OrderFlowTest.java")), label + "the server keeps its tests"); - assertNotNull(entries.get("common/src/main/java/" + packagePath + (game ? "/ui/HomeForm.java" : rides ? "/rider/RiderForm.java" : chat ? "/ui/ChatForm.java" : bank ? "/ui/HomeForm.java" : video ? "/ui/WelcomeForm.java" : studio ? "/member/MemberForm.java" : field ? "/field/TodayForm.java" : shop ? "/shop/CheckoutForm.java" : booking ? "/client/ClientForm.java" : "/customer/CustomerForm.java")), + assertNotNull(entries.get("common/src/main/java/" + packagePath + (game ? "/ui/HomeForm.java" : rides ? "/rider/RiderForm.java" : chat ? "/ui/ChatForm.java" : bank ? "/ui/HomeForm.java" : video ? "/ui/WelcomeForm.java" : studio ? "/member/MemberForm.java" : field ? "/field/TodayForm.java" : lingo ? "/learn/LearnHome.java" : shop ? "/shop/CheckoutForm.java" : booking ? "/client/ClientForm.java" : "/customer/CustomerForm.java")), label + "the app's screens move to the project's package"); if (!game) { assertNotNull(entries.get("common/src/main/l10n/Bundle.properties"), label + "the app keeps its bundle"); @@ -700,6 +702,19 @@ private void validateFieldlineGate() throws Exception { "The page offers Fieldline from its gate on"); } + /// The language learning template signs its certificates with the core PDF + /// signing API: below its gate it is refused, and the page does not list it. + private void validateLingoGate() throws Exception { + assertFalse(GeneratorModel.isVersionAtLeast(FULL_STACK_VERSION, GeneratorModel.LINGO_SINCE), + "Lingo's gate is past the other complete apps'"); + assertRefused(GeneratorModel.createForPluginVersion(IDE.INTELLIJ, Template.LINGO, "OldLingo", + "com.acme.oldlingo", ProjectOptions.defaults().forFullStack(), FULL_STACK_VERSION), + GeneratorModel.LINGO_SINCE, "Lingo is not generated before its gate"); + assertEqual(Boolean.valueOf(GeneratorModel.isVersionAtLeast(GeneratorModel.cn1PluginVersion(), + GeneratorModel.LINGO_SINCE)), Boolean.valueOf(GeneratorModel.isTemplateOffered(Template.LINGO)), + "The page offers Lingo from its gate on"); + } + /// The commerce template ships from its own gate: below it it is refused, /// and the page does not list it. private void validateBazaarGate() throws Exception { diff --git a/scripts/initializr/e2e-shipped.sh b/scripts/initializr/e2e-shipped.sh index 5de311aad36..b29affe42e6 100755 --- a/scripts/initializr/e2e-shipped.sh +++ b/scripts/initializr/e2e-shipped.sh @@ -12,7 +12,7 @@ # # e2e-shipped.sh [--require-latest] [--no-ui] [TEMPLATE ...] # -# TEMPLATE is BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE or BAZAAR; all of them +# TEMPLATE is BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE, LINGO or BAZAAR; all of them # by default. Every other check of the templates builds them against this # checkout's 8.0-SNAPSHOT, which no developer has: the generated pom names the # release the Initializr pins, and that is the only thing this script builds @@ -69,7 +69,7 @@ for arg in "$@"; do *) TEMPLATES+=("$arg") ;; esac done -[ ${#TEMPLATES[@]} -gt 0 ] || TEMPLATES=(BAREBONES KOTLIN WAYLINE SAVOR SKIRMISH DASH SPLAT PAPERCUT PARLEY BASTION REEL PULSE SLATE FIELDLINE BAZAAR) +[ ${#TEMPLATES[@]} -gt 0 ] || TEMPLATES=(BAREBONES KOTLIN WAYLINE SAVOR SKIRMISH DASH SPLAT PAPERCUT PARLEY BASTION REEL PULSE SLATE FIELDLINE LINGO BAZAAR) log() { echo "[e2e-shipped] $*" >&2; } fail() { echo "[e2e-shipped] FAIL: $*" >&2; exit 1; } @@ -104,6 +104,8 @@ template_since() { PAPERCUT) echo "$PAPERCUT_SINCE" ;; SLATE) echo "$SLATE_SINCE" ;; FIELDLINE) echo "$FIELDLINE_SINCE" ;; + # LINGO_SINCE is defined as BAZAAR_SINCE, so it has no literal to read. + LINGO) echo "$BAZAAR_SINCE" ;; BAZAAR) echo "$BAZAAR_SINCE" ;; *) echo "$FULL_STACK_SINCE" ;; esac diff --git a/scripts/lingo/LICENSE b/scripts/lingo/LICENSE new file mode 100644 index 00000000000..af5d69aaeb3 --- /dev/null +++ b/scripts/lingo/LICENSE @@ -0,0 +1,22 @@ +MIT No Attribution + +Copyright (c) 2026, Codename One and/or its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +This applies to the Skirmish sample and to everything Codename One Initializr +writes into a generated project: the application templates under +maven/cn1app-archetype/src/main/resources/archetype-resources, the agent skill +under scripts/initializr/common/src/main/resources/skill, and the Initializr +template archives built from them. diff --git a/scripts/lingo/README.adoc b/scripts/lingo/README.adoc new file mode 100644 index 00000000000..f230d920325 --- /dev/null +++ b/scripts/lingo/README.adoc @@ -0,0 +1,217 @@ += Lingo + +A language learning application and its server, in one Maven project and one +language. Learners practise speaking with an AI tutor that runs on the phone, +are scored word by word on their pronunciation, and keep a streak going with +XP, levels and badges. Teachers publish courses of phrase drills, role-play +conversations and video lessons, hold live classes over WebRTC, and keep 70% of +what their paid courses earn. Every completed course ends with a PDF +certificate the server signs, which anyone can check. Which screens a person +sees is decided by the roles the server gives their account. + +It is a sample of how a Codename One application and a Codename One Backend fit +together, and the project the Initializr generates when you start from the +language learning template. + +== Start here + +https://www.codenameone.com/developer-guide/lingo-users-guide/[The user's guide] +(link:../../docs/developer-guide/Lingo-Users-Guide.asciidoc[source]) shows the +application as a learner and a creator see it, with the demo accounts. +https://www.codenameone.com/developer-guide/lingo-implementors-guide/[The implementor's guide] +(link:../../docs/developer-guide/Lingo-Implementors-Guide.asciidoc[source]) +explains how it is built and where to change it. + +To see it running first, the two commands under <> are all it takes. + +== The modules + +[cols="1,4"] +|=== +| `shared` +| The contract: the data classes both sides exchange and the `@RestClient` + interfaces that name every call. The app's build generates a client from them + and the server's build generates the interfaces it implements, so a change the + other side did not follow is a compile error. + +| `common` +| The application. `learn` is the learner's side: today's practice, the + catalogue, the three kinds of lesson, rewards, badges, the leaderboard, + certificates and the wallet. `studio` is the creator's. `ai` chooses and runs + the tutor, `speech` speaks phrases and scores what it hears, and `live` is the + live channel and the WebRTC class room. Styled in `src/main/css/theme.css`, + whose first block of variables holds the colors and the corner radius + everything else is drawn with. The text is in `src/main/l10n`, in English, + Spanish, French, German and Hebrew. What it reports to Codename One analytics + about how it is used, once the user has agreed, is all in `Telemetry`. + +| `backend` +| The server: accounts and roles, the course catalogue and its seed, progress, + XP, streaks and badges, the leaderboard, questions and answers, purchases and + the creator's share, live classes and their seats, uploaded video, the signed + certificates and the public page that verifies them, the cloud tutor behind + the server's own key, push notifications, and a WebSocket that carries live + updates and the class rooms' signalling. + The data is entity classes in `domain`, read and written by the repository + beside each service. The schema is the migration scripts in + `src/main/resources/db/migration`, and the same server runs on SQLite, + PostgreSQL, MySQL and MariaDB. + +|=== + +There are no platform modules: `common` builds the application for the +simulator, the desktop, Android, iOS and the browser itself. + +== Running it + +Start the server on the development profile. It needs nothing installed: the +database is in memory, push notifications are printed on the console, and the +cloud tutor answers from rules built into the server. + +[source,bash] +---- +CN1_PROFILE=dev backend/server.sh run +---- + +Then run the application in the simulator, from another terminal: + +[source,bash] +---- +mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase +---- + +The development profile loads five courses in Spanish and French, two short +video lessons and a live class, and these accounts, all with the password +`lingo-demo`: + +[cols="2,3"] +|=== +| `learner@lingo.example` | a learner two lessons into Spanish for Travellers, with a streak +| `learner2@lingo.example` | a second learner, for the leaderboard and live classes +| `creator@lingo.example` | a teacher with published courses and a class to hold +| `admin@lingo.example` | also grants roles and sees every creator's numbers +|=== + +Sign in as the creator in one simulator and as a learner in another, start the +live class from the studio, and join it from the learner's Live tab. On a +phone, set the server's address on the welcome screen: `localhost` on a phone +is the phone. + +=== In a browser, with nothing installed + +The server can host the application itself. Build the browser version once, and +again when the application changes; it takes about a minute: + +[source,bash] +---- +backend/server.sh web +CN1_PROFILE=dev backend/server.sh run +---- + +Then open `http://localhost:8080/`. `server.sh run --web` does both in one step. + +`server.sh web` runs `cn1:backend-webapp`, which builds the application for the +browser and stages it in `backend/target/webapp`; a server that finds it there +serves it at `/`, after its own routes. In the browser the application takes the +page's address as the server's and opens its live channel to the same origin. To +deploy it, put `backend/target/webapp` beside the server binary as `webapp`. + +== What each role does + +A learner opens on today: their streak, the XP they still need for the daily +goal, and the next lesson of the course they are in. A phrase lesson speaks +each phrase, listens, and colors every word by how well it was heard. A +conversation lesson is a role-play with the tutor -- ordering a coffee, asking +the way -- spoken or typed, with corrections as it goes. A video lesson plays +the teacher's recording. Lessons earn XP, keep the streak, raise the level and +unlock badges; finishing a course issues its certificate, which they can open, +share and have checked by anyone at its address. They browse and buy courses, +ask the teacher questions, take a seat in a live class, and practise freely +with the tutor. + +A creator opens on the studio: what their courses have earned, the learners in +them, their courses and drafts, and their classes. They write a course, add +phrase, conversation and video lessons, publish it at a price or free, answer +questions, schedule a live class and hold it. + +An administrator can also grant roles, and sees the studio for every creator. + +== What is real and what is simulated + +The tutor runs on the phone when it can: the operating system's own model where +there is one (Apple Intelligence, Gemini Nano), otherwise a 470 MB model the +learner may download, run with llama.cpp. Only a learner who turns on the cloud +tutor sends anything to the server, which passes it to Claude when +`LINGO_AI_KEY` holds a key and otherwise answers from rules. Where none of +those is available -- the simulator, the tests -- a scripted partner plays the +scene, so every screen works without a model. + +Speech recognition and text to speech are the device's own. The simulator has +neither, so there a phrase lesson asks for the phrase to be typed and is scored +the same way. + +Payments are simulated: a purchase is recorded, the creator's 70% share is +credited and nothing is charged. Live classes are real WebRTC between the +devices, signalled through the server's WebSocket; the media goes peer to +peer. + +Certificates are real PAdES signatures made with the server's key, so any PDF +reader can check them. With no key configured the server makes a self-signed +one, and a reader then shows the signature intact but its signer unknown. + +Push notifications go through the Codename One push service +(`lingo.push.app`, `lingo.push.key`). On a development profile they are +printed on the console instead. A server whose settings are missing still starts +and logs a configuration error naming each one. + +`backend/application.properties` lists every setting a deployment supplies. The +database is the one named by `DATABASE_URL`: a `postgres://` or `mysql://` +address, or the path of a SQLite file. Every setting is also read from the +environment in upper case with `_` for every dot (`LINGO_AI_KEY`). Outside a +development profile the only account created is the administrator named by +`lingo.admin.email` and `lingo.admin.password`, who grants the first roles. + +== Tests + +[source,bash] +---- +mvn -pl shared,backend -Dcodename1.platform=backend test # <1> +mvn -pl shared,backend -Dcodename1.platform=backend test -Dcn1.backend.compiledTests=true # <2> +./run-e2e.sh # <3> +./check-template.sh # <4> +./run-web-e2e.sh # <5> +---- +<1> The server's tests, on the JVM. +<2> The same tests again, translated to a native binary, which is how the server + ships. +<3> Starts the server on the `test` profile and runs the application's tests + against it in the simulator: they sign in as a learner and a creator, + register, finish a phrase lesson and see their XP rise, and change the + settings while a second user acts through the API. The screens they reach + are captured in `target/e2e-shots`. Pass `--native` to run them against + the compiled server. +<4> Generates a project from the Initializr template, under another name and + package, and builds it. +<5> Builds the browser version of the application, starts the server hosting + it, and drives it in a headless browser: the application loads from the + server, signs in as the demo learner and opens its live channel, then signs + in as the demo creator and reaches the studio. Needs Node with Playwright and its Chromium (`npm ci` and + `npx playwright install chromium` in `scripts/`). Screenshots and logs go + to `target/web-e2e`. + +`.github/workflows/samples.yml` runs all five, and builds the application for +Android and iOS through `scripts/build-android-app.sh` and +`scripts/build-ios-app.sh` with `CN1_APP_DIR=scripts/lingo`. + +== The Initializr template + +`scripts/sync-initializr-template.py lingo --write` copies this project into the +Initializr's resources; without `--write` it fails when they differ, which is what +CI runs. Change the project here, never the copies. + +== Licence + +Lingo is released under MIT No Attribution (see `LICENSE`), not under the +GPLv2 with Classpath Exception that covers Codename One itself. Take any of it +into your own application, under any licence, with no notice to keep. The same +holds for everything Initializr writes into a generated project. diff --git a/scripts/lingo/backend/application-dev.properties b/scripts/lingo/backend/application-dev.properties new file mode 100644 index 00000000000..23eefe8fcaa --- /dev/null +++ b/scripts/lingo/backend/application-dev.properties @@ -0,0 +1,25 @@ +# The development profile, chosen with CN1_PROFILE=dev. +# +# An in-memory SQLite database, so the server starts with nothing installed: the +# migrations create the tables at start-up, and the demo accounts are added to +# them. Point this at a file to keep the data between runs: +# +# cn1.datasource.url=./target/app.db +# +# Production points cn1.datasource.url at the real database instead -- a +# postgres:// or mysql:// URL -- and the same code runs against it. +cn1.datasource.url=:memory: + +# On this profile the server also serves, without a token: +# +# /manage/health, /manage/metrics, /manage/prometheus, /manage/jobs +# /mcp -- the development MCP tools, for an agent working on this backend +# +# Neither is served outside a development profile unless it is turned on and +# given a token (cn1.management.token, cn1.mcp.token). + +# Push notifications are printed on the console; the assistant answers from its +# rules unless LINGO_AI_KEY is set. +# tag::lingo-properties-dev-providers[] +lingo.push.provider=console +# end::lingo-properties-dev-providers[] diff --git a/scripts/lingo/backend/application-test.properties b/scripts/lingo/backend/application-test.properties new file mode 100644 index 00000000000..d9d2d31dfd6 --- /dev/null +++ b/scripts/lingo/backend/application-test.properties @@ -0,0 +1,19 @@ +# The test profile, chosen with CN1_PROFILE=test. It is what run-e2e.sh starts the +# server on for the app's end-to-end tests, and what @BackendTest runs the +# server's own tests on. +# +# Like `dev` -- an in-memory database, the demo accounts, the demo crew -- and one thing more: places are looked up in a list of +# ten the server carries, so a test run asks no public geocoder for anything. +cn1.datasource.url=:memory: + +# The tests sign several accounts in from one address, one after another, which +# is exactly what the sign-in rate limit is there to stop. +lingo.signin.per-minute=1000 + +# A test never reaches a model: the assistant answers from its rules, and the +# scheduler takes fewer steps so a test run stays quick. +lingo.ai.provider=demo +lingo.scheduler.iterations=400 + +# Push notifications are kept for the tests to read, not sent. +lingo.push.provider=recording diff --git a/scripts/lingo/backend/application.properties b/scripts/lingo/backend/application.properties new file mode 100644 index 00000000000..d3abd864dae --- /dev/null +++ b/scripts/lingo/backend/application.properties @@ -0,0 +1,62 @@ +# The settings this server reads at start-up, and the layer with the lowest +# precedence. A system property of the same name wins over anything here, then +# the environment variable the key maps to (cn1.datasource.url is read from +# CN1_DATASOURCE_URL, and also from DATABASE_URL, which is what a platform sets +# for you), then application-.properties, then this file. +# +# It sits in the module root on purpose. This runtime has no classpath to load a +# resource from, so Config opens application*.properties as FILES relative to the +# working directory: the module directory under `cn1:backend`, and wherever the +# binary is started once it is packaged. +# +# Choose a profile with CN1_PROFILE. The one beside this file is `dev`: +# +# CN1_PROFILE=dev mvn -pl backend -Dcodename1.platform=backend cn1:backend +# +# A development profile (dev, test, local) needs nothing else: an in-memory +# database, a signing key made at start-up, push notifications printed on the +# console, the cloud tutor answering from its built-in rules, the seed courses +# and the demo learners, creator and admin. A real deployment sets, here or in +# its environment: +# +# cn1.datasource.url the database +# cn1.security.authorizationserver.issuer the public address of this server +# cn1.security.authorizationserver.jwk.keys the key tokens are signed with +# lingo.public.url the address printed on certificates +# lingo.admin.email, lingo.admin.password the first admin, who grants the rest +# lingo.certificates.key, .chain the certificate signing key, below +# lingo.push.app, lingo.push.key push notifications, below +# lingo.ai.key the cloud tutor, below +# +# The cloud tutor. The app runs its tutor on the phone; a learner who turns on +# "Cloud tutor" in the settings, on a phone that cannot run one, asks this server +# instead. With lingo.ai.key set (LINGO_AI_KEY in the environment; never in this +# file) those turns go to the Claude API, model lingo.ai.model +# (claude-opus-5-5). Without it they answer from rules built into the server. +# lingo.ai.provider forces one: anthropic or demo. +# +# Certificates. lingo.certificates.key (a PKCS#8 EC or RSA key) and +# lingo.certificates.chain (the signer's certificate first, then its issuers, +# comma separated), each base 64 DER. Without them the server makes a key and a +# self-signed certificate the first time it signs and keeps both in the +# database, so a PDF reader shows the signature intact and its signer unknown. +# +# Push notifications. lingo.push.provider is cloud, console or recording; +# unset, it is recording on the test profile, console on the other development +# profiles and cloud on any other. cloud sends through the Codename One push +# service and needs lingo.push.app and lingo.push.key (the latter in the +# environment as LINGO_PUSH_KEY). Learners are reminded of their daily goal and +# told when a live class they hold a seat in starts. + +# ${DATABASE_URL} is resolved when the value is READ, so this line is fine in a +# checkout where that variable is unset: the dev profile overrides the key, and +# nothing reads this one. SQLite (a file path), postgres:// and mysql:// all work. +cn1.datasource.url=${DATABASE_URL} + +# The port. A platform that sets PORT wins over this, which is what lets the same +# build deploy anywhere. +cn1.server.port=8080 + +# Creates the tables the accounts, the registered app and the tokens are kept in. +# Read by the build, so it has to be here and not in a profile's file. +cn1.security.schema.enabled=true diff --git a/scripts/lingo/backend/pom.xml b/scripts/lingo/backend/pom.xml new file mode 100644 index 00000000000..8a248f7070b --- /dev/null +++ b/scripts/lingo/backend/pom.xml @@ -0,0 +1,167 @@ + + + 4.0.0 + + com.codenameone.examples.lingo + lingo + 1.0-SNAPSHOT + + com.codenameone.examples.lingo + lingo-backend + 1.0-SNAPSHOT + jar + + lingo-backend + + + + + + com.codenameone + codenameone-backend + ${cn1.version} + + + + com.codenameone + cn1-app-kit-backend + ${cn1.version} + + + + ${project.groupId} + lingo-shared + ${project.version} + + + + org.xerial + sqlite-jdbc + 3.46.1.0 + runtime + + + + com.codenameone + codenameone-backend-test + ${cn1.version} + test + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + cn1-generate-annotation-stubs + generate-sources + + + generate-annotation-stubs + + + + cn1-process-annotations + process-classes + + + process-annotations + + + + cn1-process-test-annotations + process-test-classes + + + process-test-annotations + + + + cn1-compiled-tests + test + + + backend-test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + false + + + + + diff --git a/scripts/lingo/backend/server.sh b/scripts/lingo/backend/server.sh new file mode 100755 index 00000000000..d1f82e9b984 --- /dev/null +++ b/scripts/lingo/backend/server.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# +# Builds and runs the Lingo server. +# +# server.sh build [--jvm|--native] [--web] +# server.sh run [--jvm|--native] [--web] [--prebuilt] [--port N] +# server.sh web +# +# --jvm (the default) runs the server on this JDK, which is how you work on it. +# --native compiles it to a native binary, which is how it ships. +# +# The profile comes from CN1_PROFILE. `test` and `dev` need nothing else: an +# in-memory database, four demo accounts, a geocoder that knows ten places +# (`test`) and text messages that are printed, not sent. Anything else is a +# deployment and reads its settings from the environment -- see +# application.properties. +# +# `web` builds the app for the browser and stages it in target/webapp, which +# takes about a minute; `--web` does that as part of a build or a run. A server +# that finds the app there serves it at /, so http://localhost:8080/ is Lingo +# with nothing installed. It stays staged until the next `mvn clean`: build it +# once, and again when the app changed. +# +# The server prints "listening on http port N" when it accepts connections. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +APP="$(cd "$HERE/.." && pwd)" +# The project's own Maven wrapper where it has one. +if [ -z "${MVN:-}" ]; then + if [ -x "$APP/mvnw" ]; then MVN="$APP/mvnw"; else MVN="mvn"; fi +fi + +log() { echo "[lingo-server] $*" >&2; } + +build_jvm() { + log "building the server for the JVM" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl shared,backend \ + -Dmaven.test.skip=true package dependency:copy-dependencies \ + -DincludeScope=runtime -DoutputDirectory="$APP/backend/target/server-lib" >&2 +} + +build_native() { + log "translating the server to a native binary" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl shared,backend \ + -Dmaven.test.skip=true package cn1:backend-package \ + -Dcn1.backend.output="$APP/backend/target/lingo-server" >&2 +} + +build_web() { + log "building the app for the browser" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl backend \ + cn1:backend-webapp >&2 +} + +# The server looks for the app in `webapp` beside its settings; here it is build +# output, so it is under target and the server is told. An address set by the +# caller is left alone. +serve_web() { + if [ -z "${CN1_WEBAPP_ROOT:-}" ] && [ -f "$APP/backend/target/webapp/index.html" ]; then + export CN1_WEBAPP_ROOT="target/webapp" + log "serving the web app in backend/target/webapp" + fi +} + +command="${1:-run}" +shift || true +mode="jvm" +port="${PORT:-8080}" +prebuilt=0 +web=0 +while [ $# -gt 0 ]; do + case "$1" in + --jvm) mode="jvm" ;; + --native) mode="native" ;; + --prebuilt) prebuilt=1 ;; + --web) web=1 ;; + --port) port="$2"; shift ;; + *) log "unknown argument $1"; exit 2 ;; + esac + shift +done + +case "$command" in + build) + if [ "$mode" = "native" ]; then build_native; else build_jvm; fi + [ "$web" = 0 ] || build_web + ;; + web) + build_web + ;; + run) + # application.properties is read from the working directory. + cd "$APP/backend" + if [ "$mode" = "native" ]; then + [ "$prebuilt" = 1 ] || build_native + [ "$web" = 0 ] || [ "$prebuilt" = 1 ] || build_web + serve_web + PORT="$port" exec "$APP/backend/target/lingo-server" + fi + [ "$prebuilt" = 1 ] || build_jvm + [ "$web" = 0 ] || [ "$prebuilt" = 1 ] || build_web + serve_web + main="$(tr -d '\r\n' < "$APP/backend/target/classes/META-INF/cn1-backend-main")" + log "running $main on port $port" + PORT="$port" exec java -cp "$APP/backend/target/classes:$APP/backend/target/server-lib/*" "$main" + ;; + *) + log "unknown command $command (build, run, web)" + exit 2 + ;; +esac diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Ids.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Ids.java new file mode 100644 index 00000000000..8b06c04cbc8 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Ids.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Crypto; + +import java.io.IOException; + +/// Identifiers and secrets made of random bytes. +public final class Ids { + private static final char[] HEX = "0123456789abcdef".toCharArray(); + + private Ids() { + } + + /// A new identifier: 32 hex digits from 16 random bytes. Random and not a + /// counter, so the id of one course says nothing about the id of another, and + /// so no table needs a generated key, which every database spells its own way. + public static String next() throws IOException { + return hex(Crypto.randomBytes(16)); + } + + public static String hex(byte[] bytes) { + char[] out = new char[bytes.length * 2]; + for (int iter = 0; iter < bytes.length; iter++) { + out[iter * 2] = HEX[(bytes[iter] >> 4) & 0xf]; + out[iter * 2 + 1] = HEX[bytes[iter] & 0xf]; + } + return new String(out); + } + + /// The SHA-256 of `text`, in hex. What is stored in place of a secret that + /// only ever needs to be compared. + public static String sha256(String text) throws IOException { + return hex(Crypto.sha256(text.getBytes("UTF-8"))); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Roles.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Roles.java new file mode 100644 index 00000000000..40d17f4ba15 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Roles.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +/// The roles an account can hold. A learner takes courses and classes; +/// a creator makes and sells them; an admin manages accounts. The +/// app opens on the mode of the strongest role the account holds and offers +/// the others from its menu. +public final class Roles { + public static final String LEARNER = "LEARNER"; + public static final String CREATOR = "CREATOR"; + public static final String ADMIN = "ADMIN"; + + private Roles() { + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SecurityConfig.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SecurityConfig.java new file mode 100644 index 00000000000..5ae4d18b18c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SecurityConfig.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + + +import com.codename1.appkit.server.Grants; +import com.codename1.appkit.server.security.AccountSecurity; +import com.codename1.backend.Config; +import com.codename1.backend.DataSource; +import com.codename1.backend.annotations.Bean; +import com.codename1.backend.annotations.Configuration; +import com.codename1.backend.annotations.Order; +import com.codename1.backend.annotations.Value; +import com.codename1.backend.security.AntPathRequestMatcher; +import com.codename1.backend.security.HttpSecurity; +import com.codename1.backend.security.SecurityFilterChain; +import com.codename1.backend.security.SessionCreationPolicy; +import com.codename1.backend.security.core.userdetails.JdbcUserDetailsManager; +import com.codename1.backend.security.crypto.JwkSource; +import com.codename1.backend.security.crypto.PasswordEncoder; +import com.codename1.backend.security.oauth2.server.authorization.OAuth2AuthorizationService; +import com.codename1.backend.security.oauth2.server.authorization.RegisteredClientRepository; +import com.codename1.backend.security.ratelimit.InMemoryRateLimiter; +import com.codename1.backend.security.ratelimit.RateLimitKeys; + +import java.io.IOException; + +/// Who may call what. +/// +/// This server is two things at once, and has a filter chain for each: +/// +/// - **An authorization server.** The app signs a user in here -- e-mail and +/// password, then the authorization-code flow with PKCE -- and gets a +/// short-lived access token and a refresh token. Nothing but this server ever +/// sees the password. +/// - **An API.** Everything under `/api` takes that access token as a bearer +/// token, keeps no session, and decides from the account's roles what the +/// caller may do. +/// +/// The roles are LEARNER, CREATOR and ADMIN ([Roles]). `/api/studio` +/// is the creators' console and `/api/admin` the admins'; the rest is for +/// anyone signed in and acts on the caller's own account and progress. +@Configuration +public class SecurityConfig { + public static final String CLIENT_ID = "lingo-app"; + public static final String AUDIENCE = "urn:lingo:api"; + + @Bean + public PasswordEncoder passwordEncoder() { + return AccountSecurity.passwordEncoder(); + } + + @Bean + public JdbcUserDetailsManager users(DataSource db) { + return AccountSecurity.users(db); + } + + @Bean + public RegisteredClientRepository clients(DataSource db, + @Value("${" + AccountSecurity.ISSUER_KEY + ":}") String issuer) throws IOException { + return AccountSecurity.clients(db, "lingo", CLIENT_ID, "Lingo", issuer); + } + + @Bean + public OAuth2AuthorizationService authorizations(DataSource db) { + return AccountSecurity.authorizations(db); + } + + /// The sign-ins an account has open. The kit declares no beans of its + /// own, so the server that runs the authorization server declares it here. + @Bean + public Grants grants(DataSource db, OAuth2AuthorizationService authorizations) { + return new Grants(db, authorizations); + } + + @Bean + public JwkSource signingKeys(Config config) throws IOException { + return AccountSecurity.signingKeys(config); + } + + /// Signing in. Ten tries a minute from one address, unless + /// `lingo.signin.per-minute` says otherwise: the end-to-end tests are many + /// people signing in from one address, and their profile raises it. + @Bean + @Order(1) + public SecurityFilterChain signIn(HttpSecurity http, + @Value("${" + AccountSecurity.ISSUER_KEY + ":}") String issuer, + @Value("${lingo.signin.per-minute:10}") int signInsPerMinute) throws IOException { + return AccountSecurity.signIn(http, issuer, signInsPerMinute, AUDIENCE); + } + + @Bean + @Order(2) + public SecurityFilterChain api(HttpSecurity http, JwkSource signingKeys, + @Value("${" + AccountSecurity.ISSUER_KEY + ":}") String issuer, + JdbcUserDetailsManager users) throws IOException { + http.securityMatcher("/api/**") + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // Opening accounts costs something each time and a stranger can + // ask for it. One limiter per rule: a shared one would share its count. + .rateLimit("/api/account/register", RateLimitKeys.clientAddress(), + new InMemoryRateLimiter(20, 3600)) + // Guessing the current password with a token in hand, and filling + // the database with pictures: an hour's allowance of each is more + // than anyone honest needs. + .rateLimit("/api/account/password", + RateLimitKeys.firstOf(RateLimitKeys.principal(), RateLimitKeys.clientAddress()), + new InMemoryRateLimiter(10, 3600)) + // Each turn with the cloud tutor is a request paid for per token, + // and a recording is megabytes stored. An hour's allowance of + // each is more than a lesson or a studio session needs. + .rateLimit("/api/tutor/reply", + RateLimitKeys.firstOf(RateLimitKeys.principal(), RateLimitKeys.clientAddress()), + new InMemoryRateLimiter(240, 3600)) + .rateLimit("/api/studio/uploads", + RateLimitKeys.firstOf(RateLimitKeys.principal(), RateLimitKeys.clientAddress()), + new InMemoryRateLimiter(30, 3600)) + // Anyone may check a certificate, and a QR code invites it; a + // script walking ids would be refused. + .rateLimit("/api/verify/*", RateLimitKeys.clientAddress(), + new InMemoryRateLimiter(60, 60)) + // tag::lingo-api-rules[] + .authorizeHttpRequests(auth -> auth + .requestMatchers(AntPathRequestMatcher.antMatcher("POST", + "/api/account/register")).permitAll() + .requestMatchers(AntPathRequestMatcher.antMatcher("GET", + "/api/verify/*")).permitAll() + .requestMatchers("/api/studio/**").hasRole(Roles.CREATOR) + .requestMatchers("/api/admin/**").hasRole(Roles.ADMIN) + .anyRequest().authenticated()) + // end::lingo-api-rules[] + .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder( + AccountSecurity.tokenDecoder(signingKeys, issuer, AUDIENCE)) + .jwtAuthenticationConverter(AccountSecurity.accountRoles(users)))); + return http.build(); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Services.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Services.java new file mode 100644 index 00000000000..adad6004146 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/Services.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Config; +import com.codename1.backend.annotations.Bean; +import com.codename1.backend.annotations.Configuration; +import com.codename1.backend.annotations.Value; +import com.codename1.backend.push.CloudPush; +import com.codenameone.examples.lingo.ai.ClaudeClient; +import com.codename1.appkit.server.push.CloudPushSender; +import com.codename1.appkit.server.push.ConsolePushSender; +import com.codename1.appkit.server.push.MisconfiguredPushSender; +import com.codename1.appkit.server.push.PushSender; +import com.codename1.appkit.server.push.RecordingPushSender; + +import java.io.IOException; + +/// The services this server reaches outside itself for, each behind an +/// interface and each chosen here from the settings. +/// +/// Each is named by one setting -- `lingo.push.provider` and +/// `lingo.ai.provider` -- and, when that is not +/// set, a development profile (dev, test, local) gets the one that needs no +/// account. Any other profile gets the real provider, and when its settings +/// are missing the server still starts and logs a configuration error naming +/// each missing setting. +/// +/// Every setting is also read from the environment, in upper case with `_` +/// for each `.` (`LINGO_AI_KEY`), which is where secrets belong. +@Configuration +public class Services { + /// The model behind the assistant: photo diagnosis, report drafting, + /// manual lookups and the creator's natural-language re-planning. + /// + /// `lingo.ai.provider` is `anthropic` or `demo`. Unset, it is + /// `anthropic` when `lingo.ai.key` (`LINGO_AI_KEY`) holds a key and + /// `demo` otherwise. `demo` answers from rules written into this server -- + /// a fixed diagnosis per kind of asset, a report assembled from the + /// checklist, an assistant that understands a handful of phrasings -- so + /// the template is whole without an account, and the tests are + /// repeatable. Every answer says which of the two produced it. + /// + /// `lingo.ai.model` overrides the model, `claude-opus-5-5` by default. + @Bean + public ClaudeClient claude( + @Value("${lingo.ai.provider:}") String chosen, + @Value("${lingo.ai.key:}") String key, + @Value("${lingo.ai.model:claude-opus-5-5}") String model, + @Value("${lingo.ai.url:https://api.anthropic.com}") String url) { + String kind = chosen.trim().length() > 0 ? chosen.trim() + : key.trim().length() > 0 ? "anthropic" : "demo"; + if ("anthropic".equalsIgnoreCase(kind)) { + if (key.trim().length() == 0) { + System.err.println("Configuration error: " + unset("AI", "anthropic", + "lingo.ai.key") + "; answering from the demo rules"); + return ClaudeClient.demo(); + } + return new ClaudeClient(url.trim(), key.trim(), model.trim()); + } + if (!"demo".equalsIgnoreCase(kind)) { + System.err.println("Configuration error: lingo.ai.provider is '" + kind + + "', which is neither anthropic nor demo; answering from the demo rules"); + } + return ClaudeClient.demo(); + } + + /// Photon, at `lingo.geocoder.url`. `lingo.geocoder=stub` selects the + /// one that knows ten places and asks nobody, and it is what the `test` + /// profile gets unless told otherwise. + // tag::lingo-push-choice[] + /// `lingo.push.provider` is one of: + /// + /// - `cloud`: the Codename One push service. It needs `lingo.push.app`, + /// the app's push id, and `lingo.push.key`, a server key with the push + /// scope; both are in the Push section of the Codename One console. + /// - `console`: prints each notification, on a development profile only. + /// - `recording`: keeps each notification for the tests to read, on a + /// development profile only. + /// + /// Unset, it is `recording` on the `test` profile, `console` on the other + /// development profiles and `cloud` otherwise. A server whose push settings + /// are missing still starts and still serves lessons: it logs a configuration + /// error at start-up and again for every notification it could not send. + @Bean + public PushSender pushSender(Config config, + @Value("${lingo.push.provider:}") String chosen, + @Value("${lingo.push.app:}") String app, + @Value("${lingo.push.key:}") String key, + @Value("${lingo.push.url:}") String url) { + String kind = chosen.trim().length() > 0 ? chosen.trim() + : "test".equals(config.getProfile()) ? "recording" + : config.isDevelopmentProfile() ? "console" : "cloud"; + if ("console".equalsIgnoreCase(kind) || "recording".equalsIgnoreCase(kind)) { + if (!config.isDevelopmentProfile()) { + return new MisconfiguredPushSender("lingo.push.provider=" + kind + + " sends nothing and is refused on the '" + config.getProfile() + + "' profile; set it to cloud"); + } + return "console".equalsIgnoreCase(kind) ? new ConsolePushSender() + : new RecordingPushSender(); + } + if (!"cloud".equalsIgnoreCase(kind)) { + return new MisconfiguredPushSender("lingo.push.provider is '" + kind + + "', which is none of cloud, console or recording"); + } + String missing = missing("lingo.push.", new String[] {"app", app, "key", key}); + if (missing.length() > 0) { + return new MisconfiguredPushSender(unset("push", "cloud", missing)); + } + try { + CloudPush push = new CloudPush(app.trim(), key.trim()); + return new CloudPushSender(url.trim().length() > 0 ? push.withEndpoint(url.trim()) + : push); + } catch (IllegalArgumentException err) { + return new MisconfiguredPushSender("push provider 'cloud' is misconfigured: " + + err.getMessage()); + } + } + // end::lingo-push-choice[] + + /// The names, after `prefix`, of the settings in `namesAndValues` whose + /// value is empty, separated by commas. + private static String missing(String prefix, String[] namesAndValues) { + StringBuilder out = new StringBuilder(); + for (int iter = 0; iter + 1 < namesAndValues.length; iter += 2) { + if (namesAndValues[iter + 1] == null || namesAndValues[iter + 1].trim().length() == 0) { + if (out.length() > 0) { + out.append(", "); + } + out.append(prefix).append(namesAndValues[iter]); + } + } + return out.toString(); + } + + private static String unset(String service, String provider, String missing) { + return service + " provider '" + provider + "' is not configured; set " + missing; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SignInCodePage.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SignInCodePage.java new file mode 100644 index 00000000000..b04bf16fb93 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/SignInCodePage.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.appkit.server.security.AccountSecurity; + +import com.codename1.backend.HttpServer; +import com.codename1.backend.Json; +import com.codename1.backend.annotations.GetMapping; +import com.codename1.backend.annotations.RequestParam; +import com.codename1.backend.annotations.RestController; + +import java.util.LinkedHashMap; +import java.util.Map; + +/// Where a sign-in from a browser ends: the authorization code, handed back. +/// +/// The installed app asks for its code to be sent to a loopback address and +/// reads it off the redirect without following it. A page in a browser cannot +/// do that -- the browser follows the redirect itself and shows the page only +/// what it found at the end -- so the app running in one asks for the code to +/// be sent here, and what is at the end is the code. +/// +/// Nothing is decided here and nothing is trusted: the code arrived in the +/// address, so repeating it tells the caller nothing it did not have, and it +/// is worth nothing without the PKCE verifier only the app that started the +/// sign-in holds. That is why this needs no sign-in of its own. +@RestController +public class SignInCodePage { + @GetMapping(AccountSecurity.WEB_REDIRECT_PATH) + public HttpServer.Response code( + @RequestParam(value = "code", required = false) String code, + @RequestParam(value = "state", required = false) String state, + @RequestParam(value = "error", required = false) String error) throws Exception { + Map answer = new LinkedHashMap(); + if (code != null) { + answer.put("code", code); + } + if (state != null) { + answer.put("state", state); + } + if (error != null) { + answer.put("error", error); + } + return new HttpServer.Response(code == null ? 400 : 200, "application/json", + Json.write(answer).getBytes("UTF-8")) + // A code is good once, for a few minutes; nothing should keep it. + .header("Cache-Control", "no-store") + // And nothing should read it as anything but data: the values + // come from the address, which anyone can write a link to. + .header("X-Content-Type-Options", "nosniff"); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountCleanup.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountCleanup.java new file mode 100644 index 00000000000..45bb6e83a63 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountCleanup.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.account; + +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.repository.EnrollmentRepository; +import com.codenameone.examples.lingo.repository.LessonResultRepository; +import com.codenameone.examples.lingo.repository.XpEventRepository; +import com.codenameone.examples.lingo.repository.LearnerStatsRepository; +import com.codenameone.examples.lingo.repository.EarnedBadgeRepository; +import com.codenameone.examples.lingo.repository.SeatRepository; +import com.codenameone.examples.lingo.repository.CertificateRepository; +import com.codenameone.examples.lingo.repository.CommentRepository; +import com.codenameone.examples.lingo.repository.LiveTicketRepository; +import com.codenameone.examples.lingo.repository.PreferenceRepository; +import com.codenameone.examples.lingo.repository.PushDeviceRepository; + +/// What closing an account does to the rows other parts of the server keep +/// under its name. It has no transaction of its own: [Accounts] calls it +/// inside one. +@Component +public class AccountCleanup { + private final PreferenceRepository preferences; + private final LiveTicketRepository tickets; + private final PushDeviceRepository pushDevices; + private final EnrollmentRepository enrollments; + private final LessonResultRepository results; + private final XpEventRepository events; + private final LearnerStatsRepository stats; + private final EarnedBadgeRepository badges; + private final SeatRepository seats; + private final CertificateRepository certificates; + private final CommentRepository comments; + + public AccountCleanup(PreferenceRepository preferences, LiveTicketRepository tickets, + PushDeviceRepository pushDevices, EnrollmentRepository enrollments, LessonResultRepository results, XpEventRepository events, LearnerStatsRepository stats, EarnedBadgeRepository badges, SeatRepository seats, CertificateRepository certificates, CommentRepository comments) { + this.preferences = preferences; + this.tickets = tickets; + this.pushDevices = pushDevices; + this.enrollments = enrollments; + this.results = results; + this.events = events; + this.stats = stats; + this.badges = badges; + this.seats = seats; + this.certificates = certificates; + this.comments = comments; + } + + /// Deletes what an account leaves in the tables keyed by it. + public void removeEverythingOf(String username) { + preferences.deleteByUsername(username); + tickets.deleteByUsername(username); + pushDevices.deleteByUsername(username); + enrollments.deleteByUsername(username); + results.deleteByUsername(username); + events.deleteByUsername(username); + stats.deleteByUsername(username); + badges.deleteByUsername(username); + seats.deleteByUsername(username); + // A certificate names its holder, so it goes with the account: its + // verification page then answers "not found", which is the truth. + certificates.deleteByUsername(username); + comments.deleteByAuthor(username); + // Receipts stay: they are the record of money paid to a creator, + // which a business must keep for its accounts. + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountEndpoint.java new file mode 100644 index 00000000000..33785750bd4 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/AccountEndpoint.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.account; + +import com.codename1.backend.annotations.Component; +import com.codename1.appkit.server.Caller; +import com.codenameone.examples.lingo.api.AccountApiServer; +import com.codenameone.examples.lingo.api.AccountClosureDto; +import com.codenameone.examples.lingo.api.PasswordChangeDto; +import com.codenameone.examples.lingo.api.PreferencesDto; +import com.codenameone.examples.lingo.api.ProfileDto; +import com.codenameone.examples.lingo.api.PushDeviceDto; +import com.codenameone.examples.lingo.api.RegisterDto; +import com.codenameone.examples.lingo.api.TicketDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.live.LiveTickets; +import com.codenameone.examples.lingo.push.PushDevices; + +/// The server's half of `AccountApi`. +/// +/// `AccountApiServer` is generated from the contract the app calls through, and +/// the build routes each of the contract's paths to this class. Change a path or +/// a type in the contract and both sides stop compiling until they agree. +@Component +public class AccountEndpoint implements AccountApiServer { + private final Accounts accounts; + private final LiveTickets tickets; + private final Preferences preferences; + private final PushDevices devices; + + public AccountEndpoint(Accounts accounts, LiveTickets tickets, + Preferences preferences, PushDevices devices) { + this.accounts = accounts; + this.tickets = tickets; + this.preferences = preferences; + this.devices = devices; + } + + @Override + public UserDto register(RegisterDto request) throws Exception { + return accounts.register(request); + } + + @Override + public UserDto me() throws Exception { + return accounts.describe(Caller.name()); + } + + @Override + public TicketDto liveTicket() throws Exception { + return tickets.issue(Caller.name()); + } + + @Override + public PreferencesDto preferences() throws Exception { + return preferences.get(Caller.name()); + } + + @Override + public PreferencesDto savePreferences(PreferencesDto wanted) throws Exception { + return preferences.save(Caller.name(), wanted); + } + + @Override + public ProfileDto profile() throws Exception { + return accounts.profile(Caller.name()); + } + + @Override + public UserDto saveProfile(ProfileDto profile) throws Exception { + return accounts.saveProfile(Caller.name(), profile); + } + + @Override + public UserDto changePassword(PasswordChangeDto change) throws Exception { + return accounts.changePassword(Caller.name(), change == null ? null : change.current(), + change == null ? null : change.replacement()); + } + + @Override + public UserDto deleteAccount(AccountClosureDto closure) throws Exception { + return accounts.close(Caller.name(), closure == null ? null : closure.password()); + } + + @Override + public PushDeviceDto registerPush(PushDeviceDto device) throws Exception { + return devices.register(Caller.name(), device); + } + + @Override + public PushDeviceDto unregisterPush(PushDeviceDto device) throws Exception { + return devices.unregister(Caller.name(), device); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Accounts.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Accounts.java new file mode 100644 index 00000000000..a47ca26fd5b --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Accounts.java @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.account; + +import com.codename1.appkit.server.Grants; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.backend.security.GrantedAuthority; +import com.codename1.backend.security.core.userdetails.JdbcUserDetailsManager; +import com.codename1.backend.security.core.userdetails.User; +import com.codename1.backend.security.core.userdetails.UserDetails; +import com.codename1.backend.security.crypto.PasswordEncoder; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.Roles; +import com.codenameone.examples.lingo.api.AccountChangeDto; +import com.codenameone.examples.lingo.api.ProfileDto; +import com.codenameone.examples.lingo.api.RegisterDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.domain.ClosedAccount; +import com.codenameone.examples.lingo.domain.Profile; +import com.codenameone.examples.lingo.live.LiveHub; +import com.codenameone.examples.lingo.repository.ClosedAccountRepository; +import com.codenameone.examples.lingo.repository.ProfileRepository; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/// Accounts: opening one, describing one, and what its owner may change. +/// +/// An account is two things kept under one name. Its sign-in -- password hash, +/// roles, whether it is enabled -- is the backend's own user store. Its profile +/// -- display name, phone, language -- is this application's table. The name +/// is the e-mail address, in lower case. +/// +/// Someone who signs up is a learner: they can enrol in any free course at +/// once. The +/// CREATOR and ADMIN roles are granted, never asked for. +@Component +public class Accounts { + private final ProfileRepository profiles; + private final AccountCleanup cleanup; + private final JdbcUserDetailsManager users; + private final PasswordEncoder encoder; + private final LiveHub live; + private final ClosedAccountRepository closed; + private final Grants grants; + + public Accounts(ProfileRepository profiles, AccountCleanup cleanup, + JdbcUserDetailsManager users, PasswordEncoder encoder, LiveHub live, + ClosedAccountRepository closed, Grants grants) { + this.profiles = profiles; + this.cleanup = cleanup; + this.users = users; + this.encoder = encoder; + this.live = live; + this.closed = closed; + this.grants = grants; + } + + /// Opens an account. Answers 400 for a request that cannot be an account + /// and 409 when the e-mail already has one. + /// + /// Not a transaction itself, so that it can look again after one failed. + /// Two requests for the same e-mail can both find it free; the name's + /// unique key then refuses the second, and what the database says about + /// that differs with the database. So nothing here reads the error: if the + /// account exists once the transaction is over, that is why it failed, and + /// the answer is the same 409 the check gives. + public UserDto register(RegisterDto request) throws IOException { + try { + return open(request); + } catch (ResponseStatusException answered) { + throw answered; + } catch (IOException failed) { + throw taken(request, failed); + } catch (RuntimeException failed) { + throw taken(request, failed); + } + } + + /// The 409 for a registration that failed because the account was opened + /// meanwhile, or the failure itself when it was something else. + private T taken(RegisterDto request, T failed) { + if (request != null && request.email() != null + && users.userExists(email(request.email()))) { + throw new ResponseStatusException(409, "That e-mail already has an account"); + } + return failed; + } + + @Transactional(rollbackFor = IOException.class) + private UserDto open(RegisterDto request) throws IOException { + if (request == null) { + throw new ResponseStatusException(400, "Nothing to register"); + } + String username = email(request.email()); + password(request.password()); + String displayName = required(request.displayName(), 120, "your name"); + String raw = request.phone() == null ? "" : request.phone().trim(); + String phone = raw.length() == 0 ? "" : phone(raw); + if (users.userExists(username)) { + throw new ResponseStatusException(409, "That e-mail already has an account"); + } + // An address whose account was closed is not given to anyone again: + // the certificates that account earned are still filed under it. See [#retire]. + if (closed.existsById(Ids.sha256(username))) { + throw new ResponseStatusException(409, + "That e-mail belonged to an account that was closed. Use another"); + } + create(username, request.password(), displayName, phone, true, false, false, + System.currentTimeMillis()); + return describe(username); + } + + /// Creates the sign-in and the profile. The caller has checked the name is + /// free, and makes the learner row itself when there is to be one. + @Transactional(rollbackFor = IOException.class) + public void create(String username, String password, String displayName, String phone, + boolean learner, boolean creator, boolean admin, long openedAt) + throws IOException { + users.createUser(User.withUsername(username).password(encoder.encode(password)) + .roles(roles(learner, creator, admin)).build()); + Profile profile = new Profile(); + profile.setUsername(username); + profile.setDisplayName(displayName); + profile.setPhone(phone); + profile.setLanguage("en"); + profile.setCreatedAt(openedAt); + profiles.insert(profile); + } + + public boolean exists(String username) { + return users.userExists(username); + } + + /// The account as the app sees it. Answers 404 for a name with no account. + @Transactional(readOnly = true) + public UserDto describe(String username) throws IOException { + Profile profile = profiles.findById(username); + if (profile == null || !users.userExists(username)) { + throw new ResponseStatusException(404, "No such account"); + } + UserDetails signIn = users.loadUserByUsername(username); + return toDto(profile, authorities(signIn), signIn.isEnabled()); + } + + @Transactional(readOnly = true) + public ProfileDto profile(String username) throws IOException { + Profile row = profiles.findById(username); + if (row == null) { + throw new ResponseStatusException(404, "No such account"); + } + return new ProfileDto(row.getDisplayName(), row.getPhone()); + } + + /// Saves the name and phone. A learner's name on the board follows. + @Transactional(rollbackFor = IOException.class) + public UserDto saveProfile(String username, ProfileDto profile) throws IOException { + if (profile == null) { + throw new ResponseStatusException(400, "Nothing to save"); + } + // Everything is checked before anything is assigned: the row is written + // from what it holds when the transaction commits. + String name = required(profile.name(), 120, "your name"); + String raw = profile.phone() == null ? "" : profile.phone().trim(); + String phone = raw.length() == 0 ? "" : phone(raw); + Profile row = profiles.findById(username); + if (row == null) { + throw new ResponseStatusException(404, "No such account"); + } + row.setDisplayName(name); + row.setPhone(phone); + return describe(username); + } + + /// Changes a password, for someone who knows the one it replaces. A token + /// in hand is not enough: it is what a borrowed phone has. The account's + /// other sign-ins end with the old password. + @Transactional(rollbackFor = IOException.class) + public UserDto changePassword(String username, String current, String replacement) + throws IOException { + // Before the password is read. Two changes at once would otherwise + // both check the same old password and both succeed, the last one + // winning: whoever else knows the old password could race the owner's + // change and keep the account. Behind the hold the second change + // checks against the password the first one set. + profiles.hold(username); + UserDetails signIn = load(username); + if (current == null || !encoder.matches(current, signIn.getPassword())) { + throw new ResponseStatusException(403, "That is not your current password"); + } + password(replacement); + users.updatePassword(signIn, encoder.encode(replacement)); + // A password is changed, as often as not, because someone else may + // have the old one or a device that was signed in with it. A refresh + // token asks for no password, so every sign-in but this one ends here. + grants.endOthers(username); + return describe(username); + } + + /// Closes an account, for good: the sign-in, the profile and the settings + /// are deleted, not hidden. The certificates it earned stay + /// verifiable, under a learner no longer linked to anyone. Refused for an + /// admin, so that a service is not left with none. + /// + /// `password` is the account's own, asked for again: a token alone is not + /// enough for something that cannot be undone. + public UserDto close(String username, String password) throws IOException { + UserDto was = erase(username, password); + // After the commit and not inside it: what is said over a live + // connection is acted on at once, and must not be said about a change + // that could still be rolled back. + live.drop(username); + return new UserDto(was.username(), was.displayName(), was.phone(), was.learner(), + was.creator(), was.admin(), true, was.targetLanguage(), was.language()); + } + + /// Everything closing an account deletes, as one transaction. + @Transactional(rollbackFor = IOException.class) + UserDto erase(String username, String password) throws IOException { + profiles.hold(username); + UserDetails signIn = load(username); + if (password == null || !encoder.matches(password, signIn.getPassword())) { + throw new ResponseStatusException(403, "That is not your current password"); + } + UserDto was = describe(username); + if (was.admin()) { + throw new ResponseStatusException(409, "Hand the admin role on before closing"); + } + cleanup.removeEverythingOf(username); + // Read again: the statements above each cleared what the session had + // loaded. + if (profiles.findById(username) != null) { + profiles.deleteById(username); + } + retire(username); + // Last: the tokens in hand stop working when the sign-in is gone. + users.deleteUser(username); + grants.endAll(username); + return was; + } + + /// Retires an e-mail for good, as only a hash of it. + /// + /// A certificate outlives the account that earned it, under the e-mail that account + /// signed in with, and so does a token until it expires. Were the address + /// free to register again, whoever took it would be handed the history of the + /// person who left, and that person's old + /// token would sign in to the new account. Only a hash is kept: enough to + /// refuse it, and not a list of who has left. + private void retire(String username) throws IOException { + String hash = Ids.sha256(username); + if (!closed.existsById(hash)) { + ClosedAccount row = new ClosedAccount(); + row.setUsernameHash(hash); + row.setClosedAt(Instant.now()); + closed.insert(row); + } + } + + /// Every account, newest first, for the admin's list. + @Transactional(readOnly = true) + public List all() throws IOException { + List everyone = new ArrayList(profiles.findAll()); + Collections.sort(everyone, (a, b) -> Long.compare(b.getCreatedAt(), a.getCreatedAt())); + List out = new ArrayList(); + for (Profile profile : everyone) { + // One sign-in read per account: the user store answers for one + // name at a time. A profile whose sign-in is gone is skipped + // rather than failing the whole list. + if (!users.userExists(profile.getUsername())) { + continue; + } + UserDetails signIn = users.loadUserByUsername(profile.getUsername()); + out.add(toDto(profile, authorities(signIn), signIn.isEnabled())); + } + return out; + } + + /// Sets an account's roles and suspension, as an admin. An admin cannot + /// take their own admin role away or suspend themselves: the console would + /// be gone with nobody left to give it back. A suspended account cannot + /// sign in, and the token it holds stops working on its next request, + /// because the API reads the account every time. + /// + /// @return whether the learner role changed, so the caller re-plans + @Transactional(rollbackFor = IOException.class) + public boolean change(String by, AccountChangeDto change) throws IOException { + if (change == null || change.username() == null) { + throw new ResponseStatusException(400, "Name the account to change"); + } + String username = email(change.username()); + UserDetails signIn = load(username); + if (username.equals(by) && !change.admin()) { + throw new ResponseStatusException(400, "You cannot withdraw your own admin role"); + } + if (username.equals(by) && change.suspended()) { + throw new ResponseStatusException(400, "You cannot suspend your own account"); + } + if ((!change.admin() || change.suspended()) + && authorities(signIn).contains("ROLE_" + Roles.ADMIN) && signIn.isEnabled()) { + // Another admin may be demoted only while someone is left to + // run the console afterwards. + int others = 0; + for (UserDto u : all()) { + if (u.admin() && !u.suspended() && !username.equals(u.username())) { + others++; + } + } + if (others == 0) { + throw new ResponseStatusException(400, "Keep at least one active admin"); + } + } + boolean wasLearner = authorities(signIn).contains("ROLE_" + Roles.LEARNER); + users.updateUser(User.withUserDetails(signIn) + .roles(roles(change.learner(), change.creator(), change.admin())) + .disabled(change.suspended()).build()); + return wasLearner != change.learner(); + } + + /// Makes the rest of the caller's transaction take its turn with any other + /// that holds the same account. See [ProfileRepository#hold]. Answers 404 + /// when the account is gone: it was closed while the request was under + /// way, its clean-up has run, and a row the caller went on to insert would + /// never be deleted. + public void hold(String username) { + if (profiles.hold(username) == 0) { + throw new ResponseStatusException(404, "No such account"); + } + } + + private UserDetails load(String username) { + if (username == null || !users.userExists(username)) { + throw new ResponseStatusException(404, "No such account"); + } + return users.loadUserByUsername(username); + } + + private static void password(String value) { + if (value == null || value.length() < 8) { + throw new ResponseStatusException(400, "Choose a password of at least 8 characters"); + } + if (value.length() > 200) { + throw new ResponseStatusException(400, "That password is too long"); + } + } + + private static List authorities(UserDetails signIn) { + List held = new ArrayList(); + Iterator it = signIn.getAuthorities().iterator(); + while (it.hasNext()) { + held.add(it.next().getAuthority()); + } + return held; + } + + private static String[] roles(boolean learner, boolean creator, boolean admin) { + List roles = new ArrayList(); + if (learner) { + roles.add(Roles.LEARNER); + } + if (creator) { + roles.add(Roles.CREATOR); + } + if (admin) { + roles.add(Roles.ADMIN); + } + return roles.toArray(new String[roles.size()]); + } + + private static UserDto toDto(Profile profile, List authorities, boolean enabled) { + return new UserDto(profile.getUsername(), profile.getDisplayName(), profile.getPhone(), + authorities.contains("ROLE_" + Roles.LEARNER), + authorities.contains("ROLE_" + Roles.CREATOR), + authorities.contains("ROLE_" + Roles.ADMIN), !enabled, profile.getTargetLanguage(), + profile.getLanguage()); + } + + /// An e-mail address as an account name: trimmed, and its ASCII letters in + /// lower case. Folded by hand, because `toLowerCase()` follows the server's + /// locale and a key must not: under a Turkish locale the `I` of `INFO@` would + /// fold to a dotless i and name a different account. + public static String email(String value) { + String text = value == null ? "" : value.trim(); + int at = text.indexOf('@'); + if (at < 1 || at != text.lastIndexOf('@') || at > text.length() - 4 + || text.indexOf('.', at) < 0 || text.length() > 190) { + throw new ResponseStatusException(400, "That is not an e-mail address"); + } + char[] chars = text.toCharArray(); + for (int iter = 0; iter < chars.length; iter++) { + char c = chars[iter]; + if (c <= ' ' || c > '~') { + throw new ResponseStatusException(400, "That is not an e-mail address"); + } + if (c >= 'A' && c <= 'Z') { + chars[iter] = (char) (c + ('a' - 'A')); + } + } + return new String(chars); + } + + /// A phone number in the form it is sent to and stored in: a `+` and its + /// digits, with the spaces, dashes and brackets people type taken out. + static String phone(String value) { + String text = value == null ? "" : value.trim(); + StringBuilder digits = new StringBuilder(); + for (int iter = 0; iter < text.length(); iter++) { + char c = text.charAt(iter); + if (c >= '0' && c <= '9') { + digits.append(c); + } else if (c != ' ' && c != '-' && c != '(' && c != ')' && c != '.' + && !(c == '+' && iter == 0)) { + throw new ResponseStatusException(400, "That is not a phone number"); + } + } + if (digits.length() < 7 || digits.length() > 15) { + throw new ResponseStatusException(400, "That is not a phone number"); + } + return "+" + digits; + } + + private static String required(String value, int max, String what) { + String text = value == null ? "" : value.trim(); + if (text.length() == 0) { + throw new ResponseStatusException(400, "Tell us " + what); + } + if (text.length() > max) { + throw new ResponseStatusException(400, "That is too long for " + what); + } + return text; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/DemoAccounts.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/DemoAccounts.java new file mode 100644 index 00000000000..952e787e3b9 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/DemoAccounts.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.account; + +import com.codename1.backend.Config; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.PostConstruct; +import com.codename1.backend.annotations.Value; +import com.codenameone.examples.lingo.learn.Catalogue; + +import java.io.IOException; + +/// The accounts a server starts with. +/// +/// On a development profile: a course creator, two learners who can sign +/// in, an admin, and a handful of classmates for the leaderboard; the +/// community courses and live tutorials ([Catalogue]); and some progress. +/// +/// Anywhere else, at most one: the admin named by `lingo.admin.email` and +/// `lingo.admin.password` (or the same two names in the environment, in +/// upper case with `_` for each `.`), because a new deployment needs somebody +/// able to grant the first roles. It is created once; changing the setting +/// later does not change the password of an account that exists. +@Component +public class DemoAccounts { + public static final String CREATOR = "creator@lingo.example"; + public static final String LEARNER = "learner@lingo.example"; + public static final String SECOND_LEARNER = "learner2@lingo.example"; + public static final String ADMIN = "admin@lingo.example"; + /// The password of every demo account. Not a secret: these accounts exist + /// only where the profile says the server is not a real one. + public static final String PASSWORD = "lingo-demo"; + /// Learners nobody signs in as, there so the weekly board has a field. + static final String[] CLASSMATES = {"Priya Nair", "Tom\u00e1s Ruiz", "Mei Chen", "Jonas Berg"}; + + private final Accounts accounts; + private final Catalogue catalogue; + private final Config config; + private final String adminEmail; + private final String adminPassword; + + public DemoAccounts(Accounts accounts, Catalogue catalogue, Config config, + @Value("${lingo.admin.email:}") String adminEmail, + @Value("${lingo.admin.password:}") String adminPassword) { + this.accounts = accounts; + this.catalogue = catalogue; + this.config = config; + this.adminEmail = adminEmail; + this.adminPassword = adminPassword; + } + + /// Runs once, when the server starts. Each account is made by a + /// transactional method, so a server stopped half way through start-up + /// is left with whole accounts and the next start adds the missing ones. + @PostConstruct + public void seed() throws IOException { + if (!config.isDevelopmentProfile()) { + catalogue.seed(null); + if (adminEmail.length() > 0 && adminPassword.length() >= 8 + && !accounts.exists(Accounts.email(adminEmail))) { + accounts.create(Accounts.email(adminEmail), adminPassword, "Administrator", "", + false, true, true, System.currentTimeMillis()); + } + return; + } + boolean first = !accounts.exists(CREATOR); + long now = System.currentTimeMillis(); + if (first) { + accounts.create(CREATOR, PASSWORD, "Lucia Moreno", "+15550200", false, true, false, + now); + } + if (!accounts.exists(ADMIN)) { + accounts.create(ADMIN, PASSWORD, "Alex Admin", "+15550203", false, true, true, now); + } + if (!accounts.exists(LEARNER)) { + accounts.create(LEARNER, PASSWORD, "Dana Okafor", "+15550201", true, false, false, + now); + } + if (!accounts.exists(SECOND_LEARNER)) { + accounts.create(SECOND_LEARNER, PASSWORD, "Sam Whitaker", "+15550202", true, false, + false, now); + } + for (int iter = 0; iter < CLASSMATES.length; iter++) { + String email = "classmate" + (iter + 1) + "@lingo.example"; + if (!accounts.exists(email)) { + accounts.create(email, PASSWORD, CLASSMATES[iter], "", true, false, false, now); + } + } + catalogue.seed(CREATOR); + catalogue.seedLive(CREATOR); + catalogue.seedProgress(LEARNER, 2, 180, 4); + catalogue.seedProgress(SECOND_LEARNER, 3, 260, 6); + for (int iter = 0; iter < CLASSMATES.length; iter++) { + catalogue.seedProgress("classmate" + (iter + 1) + "@lingo.example", 1 + iter % 3, + 90 + iter * 55, 1 + iter); + } + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Preferences.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Preferences.java new file mode 100644 index 00000000000..2f4a6f2e2cf --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/account/Preferences.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.account; + +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.appkit.server.Text; +import com.codenameone.examples.lingo.api.PreferencesDto; +import com.codenameone.examples.lingo.domain.Preference; +import com.codenameone.examples.lingo.domain.Profile; +import com.codenameone.examples.lingo.repository.PreferenceRepository; +import com.codenameone.examples.lingo.repository.ProfileRepository; + +import java.io.IOException; + +/// How one person wants the app: language, theme, what they are told about, +/// whether the offline tutor waits for Wi-Fi, and whether the cloud +/// tutor may be used. +/// +/// Kept on the server so that they follow the account from one phone to the +/// next. The language lives in the profile, where a creator sees it. +@Component +public class Preferences { + private static final String[] LANGUAGES = {"en", "es", "fr", "de", "he"}; + private static final String[] THEMES = {"system", "light", "dark"}; + + private final ProfileRepository profiles; + private final PreferenceRepository preferences; + + public Preferences(ProfileRepository profiles, PreferenceRepository preferences) { + this.profiles = profiles; + this.preferences = preferences; + } + + @Transactional(readOnly = true) + public PreferencesDto get(String username) throws IOException { + Profile profile = profiles.findById(username); + if (profile == null) { + throw new ResponseStatusException(404, "No such account"); + } + Preference row = preferences.findById(username); + if (row == null) { + // What someone who never opened the settings gets. + return new PreferencesDto(profile.getLanguage(), THEMES[0], true, true, false, true); + } + return new PreferencesDto(profile.getLanguage(), row.getTheme(), row.isNotifyReminders(), + row.isNotifyLive(), row.isWifiOnlyModel(), row.isCloudTutor()); + } + + /// Saves all of them. The theme and language are checked against the + /// values they can take: they are words the server and app act on, not + /// text to show back. + @Transactional + public PreferencesDto save(String username, PreferencesDto wanted) throws IOException { + if (wanted == null) { + throw new ResponseStatusException(400, "Nothing to save"); + } + // First, before anything is read: two saves sent together for an + // account with no row yet would each find none and each insert one. + profiles.hold(username); + String theme = Text.oneOf(wanted.theme(), THEMES, THEMES[0], "the theme"); + String language = Text.oneOf(wanted.language(), LANGUAGES, LANGUAGES[0], "the language"); + Profile profile = profiles.findById(username); + if (profile == null) { + throw new ResponseStatusException(404, "No such account"); + } + profile.setLanguage(language); + Preference row = preferences.findById(username); + boolean unsaved = row == null; + if (unsaved) { + row = new Preference(); + row.setUsername(username); + } + row.setTheme(theme); + row.setNotifyReminders(wanted.notifyReminders()); + row.setNotifyLive(wanted.notifyLive()); + row.setWifiOnlyModel(wanted.wifiOnlyModel()); + row.setCloudTutor(wanted.cloudTutor()); + if (unsaved) { + preferences.insert(row); + } + return get(username); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/AdminEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/AdminEndpoint.java new file mode 100644 index 00000000000..fc2f4e058fb --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/AdminEndpoint.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.admin; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.api.AccountChangeDto; +import com.codenameone.examples.lingo.api.AdminApiServer; +import com.codenameone.examples.lingo.api.UserDto; +import java.util.List; + +/// [com.codenameone.examples.lingo.api.AdminApi], served. The security +/// configuration lets only admins reach it; [Accounts#change] keeps an admin +/// from locking everyone out. +@Component +public class AdminEndpoint implements AdminApiServer { + private final Accounts accounts; + + public AdminEndpoint(Accounts accounts) { + this.accounts = accounts; + } + + @Override + public List accounts() throws Exception { + return accounts.all(); + } + + @Override + public UserDto changeAccount(AccountChangeDto change) throws Exception { + accounts.change(Caller.name(), change); + return accounts.describe(change.username()); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/package-info.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/package-info.java new file mode 100644 index 00000000000..324edde1b6c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/admin/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +/// The admin's console: accounts and their roles. +package com.codenameone.examples.lingo.admin; diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/ai/ClaudeClient.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/ai/ClaudeClient.java new file mode 100644 index 00000000000..87c351876bb --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/ai/ClaudeClient.java @@ -0,0 +1,103 @@ +package com.codenameone.examples.lingo.ai; + +import com.codename1.backend.Json; +import com.codename1.backend.Web; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/// The Claude Messages API, over plain HTTP. +/// +/// The key stays on this server: the app talks to Lingo's own endpoints, +/// and only this class talks to Anthropic. Requests are built by the callers as +/// maps in the shape of the API's JSON and sent as they are, so what is sent is +/// readable in one place, [FieldAssistant]. +/// +/// A client made by [#demo] has no key and [#isLive] answers false; callers +/// then answer from their own rules. [com.codenameone.examples.lingo.Services] +/// chooses which. +public final class ClaudeClient { + static final String VERSION = "2026-10-21"; + + private final String url; + private final String key; + private final String model; + + public ClaudeClient(String url, String key, String model) { + String base = url == null ? "" : url; + while (base.endsWith("/")) { + base = base.substring(0, base.length() - 1); + } + this.url = base; + this.key = key; + this.model = model; + } + + /// A client that never calls out. + public static ClaudeClient demo() { + return new ClaudeClient(null, null, null); + } + + public boolean isLive() { + return key != null && key.length() > 0; + } + + public String model() { + return model; + } + + /// Sends one request to `/v1/messages` and answers the parsed response. + /// `request` gets the model filled in. Throws for anything but a 2xx, with + /// the API's own error message, so the caller can fall back and log why. + public Map message(Map request) throws IOException { + if (!isLive()) { + throw new IOException("No model is configured"); + } + request.put("model", model); + List headers = new ArrayList(); + headers.add("x-api-key: " + key); + headers.add("anthropic-version: " + VERSION); + headers.add("content-type: application/json"); + byte[] body = Json.write(request).getBytes("UTF-8"); + Web.Result answer = Web.request("POST", url + "/v1/messages", headers, body); + String text = answer.getBodyAsString(); + if (!answer.isSuccess()) { + String why = text; + try { + Object error = Json.parseObject(text).get("error"); + if (error instanceof Map) { + Object message = ((Map) error).get("message"); + why = message == null ? text : String.valueOf(message); + } + } catch (IOException notJson) { + why = text; + } + throw new IOException("Claude answered " + answer.getStatus() + ": " + why); + } + return Json.parseObject(text); + } + + /// The text of every text block of a response, joined. + public static String text(Map response) { + StringBuilder out = new StringBuilder(); + Object content = response.get("content"); + if (content instanceof List) { + for (Object block : (List) content) { + if (block instanceof Map && "text".equals(((Map) block).get("type"))) { + Object t = ((Map) block).get("text"); + if (t != null) { + out.append(t); + } + } + } + } + return out.toString(); + } + + public static String stopReason(Map response) { + Object reason = response.get("stop_reason"); + return reason == null ? "" : String.valueOf(reason); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/CertificateKeys.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/CertificateKeys.java new file mode 100644 index 00000000000..1673a3e4534 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/CertificateKeys.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.cert; + +import com.codename1.backend.Base64; +import com.codename1.backend.Crypto; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Value; +import com.codename1.backend.security.pki.Certificate; +import com.codename1.backend.security.pki.DistinguishedName; +import com.codename1.pdf.PdfSignatureProvider; +import com.codenameone.examples.lingo.domain.SigningKey; +import com.codenameone.examples.lingo.repository.SigningKeyRepository; +import java.io.IOException; + +/// The key certificates are signed with, as a [PdfSignatureProvider]. +/// +/// A deployment names its own with `lingo.certificates.key` (a PKCS#8 EC or +/// RSA key) and `lingo.certificates.chain` (the signer's certificate first, +/// then its issuers, comma separated), each base 64 DER -- a certificate +/// from a CA that PDF readers trust, so they show the signature as valid. +/// Without them the server makes a P-256 key and a self-signed certificate +/// the first time it signs, and keeps both in the database: every +/// certificate it has issued then verifies against the same key, here and +/// after a restart, and a PDF reader shows the signature intact but its +/// signer unknown. +@Component +public class CertificateKeys implements PdfSignatureProvider { + static final String ID = "certificates"; + + private final SigningKeyRepository keys; + private final String configuredKey; + private final String configuredChain; + private byte[] privateKey; + private byte[][] chain; + private String algorithm; + + public CertificateKeys(SigningKeyRepository keys, + @Value("${lingo.certificates.key:}") String configuredKey, + @Value("${lingo.certificates.chain:}") String configuredChain) { + this.keys = keys; + this.configuredKey = configuredKey.trim(); + this.configuredChain = configuredChain.trim(); + } + + private synchronized void load() throws IOException { + if (privateKey != null) { + return; + } + if (configuredKey.length() > 0 && configuredChain.length() > 0) { + // Split by hand: the backend's class library has no String.split. + java.util.List chain = new java.util.ArrayList(); + int from = 0; + while (from <= configuredChain.length()) { + int comma = configuredChain.indexOf(',', from); + int to = comma < 0 ? configuredChain.length() : comma; + String part = configuredChain.substring(from, to).trim(); + if (part.length() > 0) { + chain.add(Base64.decode(part)); + } + from = to + 1; + } + byte[][] certs = chain.toArray(new byte[chain.size()][]); + use(Base64.decode(configuredKey), certs); + return; + } + SigningKey row = keys.findById(ID); + if (row == null) { + byte[] key = Crypto.generateEcKey(Crypto.P256); + Certificate cert = Certificate.selfSigned( + DistinguishedName.parse("CN=Lingo Certificates,O=Lingo"), key, 3650); + row = new SigningKey(); + row.setId(ID); + row.setPrivateKey(key); + row.setCertificate(cert.getEncoded()); + row.setCreatedAt(System.currentTimeMillis()); + keys.save(row); + } + use(row.getPrivateKey(), new byte[][] {row.getCertificate()}); + } + + private void use(byte[] key, byte[][] certs) throws IOException { + // Signed once to learn which algorithm the key takes. + byte[] probe = {1, 2, 3}; + try { + Crypto.sign(Crypto.ES256, key, probe); + algorithm = "EC"; + } catch (IOException notEc) { + Crypto.sign(Crypto.RS256, key, probe); + algorithm = "RSA"; + } + chain = certs; + privateKey = key; + } + + /// The signer's certificate, DER: what a certificate must have been + /// signed by for this server to call it genuine. + public byte[] certificate() throws IOException { + load(); + return chain[0]; + } + + @Override + public String getKeyAlgorithm() { + try { + load(); + } catch (IOException err) { + throw new IllegalStateException("No signing key: " + err.getMessage(), err); + } + return algorithm; + } + + @Override + public byte[][] getCertificateChain() { + try { + load(); + } catch (IOException err) { + throw new IllegalStateException("No signing key: " + err.getMessage(), err); + } + return chain; + } + + @Override + public byte[] sign(byte[] data) throws IOException { + load(); + return Crypto.sign("EC".equals(algorithm) ? Crypto.ES256 : Crypto.RS256, privateKey, + data); + } + + /// Checks `signature` over `data` against the public key `publicKey` + /// (SubjectPublicKeyInfo DER) with the algorithm a PDF named. + static boolean verify(String pdfAlgorithm, byte[] publicKey, byte[] data, byte[] signature) { + try { + String algorithm = pdfAlgorithm != null && pdfAlgorithm.endsWith("ECDSA") + ? Crypto.ES256 : Crypto.RS256; + return Crypto.verify(algorithm, publicKey, data, signature); + } catch (IOException unreadable) { + return false; + } + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/Certificates.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/Certificates.java new file mode 100644 index 00000000000..77caa386d84 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/cert/Certificates.java @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.cert; + +import com.codename1.backend.Base64; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.backend.annotations.Value; +import com.codename1.pdf.PdfCanvas; +import com.codename1.pdf.PdfDocument; +import com.codename1.pdf.PdfFont; +import com.codename1.pdf.PdfPage; +import com.codename1.pdf.PdfPageSize; +import com.codename1.pdf.PdfSignature; +import com.codename1.pdf.PdfSignatureInfo; +import com.codename1.qrcode.QrCode; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.CertificateDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.api.CertificatePdfDto; +import com.codenameone.examples.lingo.api.VerificationDto; +import com.codenameone.examples.lingo.domain.Certificate; +import com.codenameone.examples.lingo.domain.Course; +import com.codenameone.examples.lingo.domain.Profile; +import com.codenameone.examples.lingo.repository.CertificateRepository; +import com.codenameone.examples.lingo.repository.ProfileRepository; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/// Certificates of completion: drawn as a PDF, signed with the server's key +/// (PAdES, through `PdfDocument.sign`), and kept exactly as issued, so the +/// copy a learner shares and the copy the server checks are the same bytes. +/// +/// Anyone can check one: the QR code on it opens `/verify/{id}`, which looks +/// the certificate up and verifies its signature again. +@Component +public class Certificates { + private static final String[] MONTHS = {"January", "February", "March", "April", "May", + "June", "July", "August", "September", "October", "November", "December"}; + private static final int INK = 0x1d2433; + private static final int MUTED = 0x667085; + private static final int BRAND = 0x4f46e5; + private static final int GOLD = 0xc9a227; + private static final int PAPER = 0xfdfbf6; + + private final CertificateRepository certificates; + private final ProfileRepository profiles; + private final CertificateKeys keys; + private final String publicUrl; + + public Certificates(CertificateRepository certificates, ProfileRepository profiles, + CertificateKeys keys, @Value("${lingo.public.url:http://localhost:8080}") + String publicUrl) { + this.certificates = certificates; + this.profiles = profiles; + this.keys = keys; + String base = publicUrl.trim(); + while (base.endsWith("/")) { + base = base.substring(0, base.length() - 1); + } + this.publicUrl = base; + } + + /// Issues the certificate for `username` finishing `course`, or answers + /// the one already issued: finishing a course twice is one certificate. + @Transactional + public Certificate issue(String username, Course course, int minutes) throws IOException { + Certificate existing = certificates.findFirstByUsernameAndCourseId(username, + course.getId()); + if (existing != null) { + return existing; + } + Profile profile = profiles.findById(username); + Certificate row = new Certificate(); + row.setId(Ids.next()); + row.setUsername(username); + row.setCourseId(course.getId()); + row.setLearnerName(profile == null ? username : profile.getDisplayName()); + row.setCourseTitle(course.getTitle()); + row.setLanguage(course.getLanguage()); + row.setIssuedAt(System.currentTimeMillis()); + row.setMinutes(minutes); + row.setPdf(render(row, course.getLevel())); + certificates.save(row); + return row; + } + + @Transactional(readOnly = true) + public List list(String username) { + List out = new ArrayList(); + for (Certificate row : certificates.findByUsernameOrderByIssuedAtDesc(username)) { + out.add(dto(row)); + } + return out; + } + + @Transactional(readOnly = true) + public CertificatePdfDto pdf(String username, String id) { + Certificate row = id == null ? null : certificates.findById(id); + if (row == null || !row.getUsername().equals(username)) { + throw new ResponseStatusException(404, "No such certificate"); + } + return new CertificatePdfDto(row.getId(), Base64.encode(row.getPdf())); + } + + /// Checks the certificate `id` from scratch: the PDF is found, its + /// signature covers every byte, the bytes hash to what was signed, the + /// signature is this server's key's, and that key's certificate is the + /// one in the PDF. + @Transactional(readOnly = true) + public VerificationDto verify(String id) throws IOException { + Certificate row = id == null || id.length() > 64 ? null : certificates.findById(id); + if (row == null) { + return new VerificationDto(id == null ? "" : id, false, false, false, "", "", 0, + "", ""); + } + return check(row.getId(), row.getPdf(), row.getLearnerName(), row.getCourseTitle(), + row.getIssuedAt()); + } + + VerificationDto check(String id, byte[] pdf, String learner, String course, long issued) + throws IOException { + List found = PdfSignatureInfo.find(pdf); + if (found.isEmpty()) { + return new VerificationDto(id, true, false, false, learner, course, issued, "", ""); + } + PdfSignatureInfo info = found.get(0); + boolean ours = Arrays.equals(info.getSignerCertificate(), keys.certificate()); + boolean valid = ours && info.isDigestValid() && info.isCertificateBound() + && info.coversWholeDocument() + && CertificateKeys.verify(info.getSignatureAlgorithm(), + info.getSignerPublicKey(), info.getSignedAttributes(), + info.getSignatureValue()); + String signer = info.getSignerName(); + return new VerificationDto(id, true, valid, info.coversWholeDocument(), learner, course, + issued, signer == null ? "" : signer, info.getSignatureAlgorithm()); + } + + public CertificateDto dto(Certificate row) { + return new CertificateDto(row.getId(), row.getCourseId(), row.getCourseTitle(), + row.getLearnerName(), row.getLanguage(), row.getIssuedAt(), row.getMinutes(), + verifyUrl(row.getId())); + } + + public String verifyUrl(String id) { + return publicUrl + "/verify/" + id; + } + + // ------------------------------------------------------------------ + // The drawing + + byte[] render(Certificate row, String level) throws IOException { + PdfDocument doc = new PdfDocument(); + doc.setTitle("Certificate of completion: " + row.getCourseTitle()) + .setAuthor("Lingo").setCreator("Lingo").setSubject(row.getLearnerName()) + .setCreationDate(row.getIssuedAt()); + PdfPage page = doc.addPage(PdfPageSize.A4.landscape()); + float w = page.getWidth(); + float h = page.getHeight(); + PdfCanvas c = page.getCanvas(); + + c.setFillColor(PAPER); + c.fillRect(0, 0, w, h); + // A wash of the brand colour down the left, and two frames. + c.setFillColor(BRAND); + c.fillRect(0, 0, 14, h); + c.setStrokeColor(GOLD); + c.setLineWidth(2.5f); + c.strokeRect(34, 28, w - 62, h - 56); + c.setLineWidth(0.6f); + c.strokeRect(42, 36, w - 78, h - 72); + + // The mark: a speech bubble, the app's icon. + float mx = w / 2 - 15; + c.setFillColor(BRAND); + c.roundRect(mx, 62, 30, 24, 7); + c.fill(); + c.moveTo(mx + 7, 84).lineTo(mx + 7, 93).lineTo(mx + 15, 84).closePath().fill(); + c.setFillColor(0xffffff); + c.fillRect(mx + 7, 70, 16, 2.4f); + c.fillRect(mx + 7, 76, 11, 2.4f); + + centre(c, "L I N G O", PdfFont.HELVETICA_BOLD, 11, BRAND, w, 112); + centre(c, "Certificate of Completion", PdfFont.TIMES_BOLD, 34, INK, w, 158); + c.setStrokeColor(GOLD); + c.setLineWidth(1); + c.drawLine(w / 2 - 60, 174, w / 2 + 60, 174); + centre(c, "This certifies that", PdfFont.TIMES_ITALIC, 15, MUTED, w, 210); + centre(c, row.getLearnerName(), PdfFont.TIMES_BOLD_ITALIC, 40, INK, w, 262); + centre(c, "has completed the course", PdfFont.TIMES_ITALIC, 15, MUTED, w, 298); + centre(c, row.getCourseTitle(), PdfFont.HELVETICA_BOLD, 22, BRAND, w, 334); + String hours = row.getMinutes() >= 60 + ? (row.getMinutes() / 60) + " h " + (row.getMinutes() % 60) + " min" + : row.getMinutes() + " minutes"; + centre(c, Languages.name(row.getLanguage()) + " | Level " + level + " | " + + hours + " of guided practice", PdfFont.HELVETICA, 11, MUTED, w, 360); + + // Bottom row: the date, the signature, the QR code. + float base = h - 80; + c.setStrokeColor(MUTED); + c.setLineWidth(0.6f); + c.drawLine(80, base, 250, base); + text(c, date(row.getIssuedAt()), PdfFont.HELVETICA_BOLD, 12, INK, 80, base - 8); + text(c, "Date of issue", PdfFont.HELVETICA, 9, MUTED, 80, base + 14); + + float sx = w / 2 - 110; + c.setFillColor(0xf2f1fd); + c.roundRect(sx, base - 52, 220, 62, 6); + c.fill(); + c.setStrokeColor(BRAND); + c.roundRect(sx, base - 52, 220, 62, 6); + c.stroke(); + text(c, "Digitally signed", PdfFont.HELVETICA_BOLD, 11, BRAND, sx + 12, base - 32); + text(c, "Lingo Certificates | PAdES", PdfFont.HELVETICA, 9, MUTED, sx + 12, base - 17); + text(c, "Certificate " + row.getId().substring(0, 12), + PdfFont.COURIER, 8, MUTED, sx + 12, base - 3); + + String url = verifyUrl(row.getId()); + QrCode qr = QrCode.encode(url, QrCode.ECC_MEDIUM); + float size = 76; + float qx = w - 80 - size; + float qy = base - size + 6; + float cell = size / qr.getSize(); + c.setFillColor(INK); + for (int y = 0; y < qr.getSize(); y++) { + for (int x = 0; x < qr.getSize(); x++) { + if (qr.isDark(x, y)) { + c.fillRect(qx + x * cell, qy + y * cell, cell + 0.05f, cell + 0.05f); + } + } + } + text(c, "Scan to verify", PdfFont.HELVETICA, 9, MUTED, qx + 6, base + 20); + page.addLink(qx, qy, size, size, url); + + doc.sign(new PdfSignature(keys).setName("Lingo Certificates") + .setReason("Certificate of completion: " + row.getCourseTitle()) + .setLocation(publicUrl).setSigningTime(row.getIssuedAt()) + .setVisible(page, sx, base - 52, 220, 62)); + return doc.toByteArray(); + } + + /// `14 March 2027`, in UTC: the day is the server's, not the reader's. + public static String date(long millis) { + long days = millis / (24L * 60 * 60 * 1000); + java.time.LocalDate day = java.time.LocalDate.ofEpochDay(days); + return day.getDayOfMonth() + " " + MONTHS[day.getMonthValue() - 1] + " " + day.getYear(); + } + + private static void centre(PdfCanvas c, String text, PdfFont font, float size, int color, + float width, float y) { + String shown = printable(font, text); + float fit = size; + while (fit > 10 && font.getStringWidth(shown, fit) > width - 140) { + fit -= 1; + } + text(c, shown, font, fit, color, (width - font.getStringWidth(shown, fit)) / 2, y); + } + + private static void text(PdfCanvas c, String text, PdfFont font, float size, int color, + float x, float y) { + c.setFillColor(color); + c.setFont(font, size); + c.drawText(printable(font, text), x, y); + } + + /// `text` with what the standard font cannot draw replaced, so a name in + /// another script prints as something rather than nothing. + static String printable(PdfFont font, String text) { + StringBuilder out = new StringBuilder(text.length()); + for (int iter = 0; iter < text.length(); iter++) { + char ch = text.charAt(iter); + out.append(font.canDisplay(ch) ? ch : '?'); + } + return out.toString(); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/Community.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/Community.java new file mode 100644 index 00000000000..70757f65927 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/Community.java @@ -0,0 +1,329 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.community; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.CommentDraftDto; +import com.codenameone.examples.lingo.api.CommentDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.PurchaseDto; +import com.codenameone.examples.lingo.api.ReceiptDto; +import com.codenameone.examples.lingo.api.WalletDto; +import com.codenameone.examples.lingo.domain.Comment; +import com.codenameone.examples.lingo.domain.Course; +import com.codenameone.examples.lingo.domain.LearnerStats; +import com.codenameone.examples.lingo.domain.LiveSession; +import com.codenameone.examples.lingo.domain.Profile; +import com.codenameone.examples.lingo.domain.Receipt; +import com.codenameone.examples.lingo.domain.Seat; +import com.codenameone.examples.lingo.learn.Learning; +import com.codenameone.examples.lingo.repository.CommentRepository; +import com.codenameone.examples.lingo.repository.CourseRepository; +import com.codenameone.examples.lingo.repository.LearnerStatsRepository; +import com.codenameone.examples.lingo.repository.LiveSessionRepository; +import com.codenameone.examples.lingo.repository.ProfileRepository; +import com.codenameone.examples.lingo.repository.ReceiptRepository; +import com.codenameone.examples.lingo.repository.SeatRepository; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/// The community side: questions under a course, live tutorials, and the +/// money -- courses, seats, Pro and tips -- with the creator's share of each. +/// +/// Payments are simulated: every one succeeds unless its method is +/// `declined`, which is how the tests and the demo show a refusal. A real +/// deployment puts a payment provider behind [#purchase]; the rest of the +/// server only ever reads the receipts it writes. +@Component +public class Community { + /// What a creator keeps of each sale, in percent. + public static final int CREATOR_SHARE = 70; + /// Lingo Pro, a month. + public static final int PRO_CENTS = 999; + static final long WEEK = 7L * 24 * 60 * 60 * 1000; + + private final CommentRepository comments; + private final CourseRepository courses; + private final LiveSessionRepository sessions; + private final SeatRepository seats; + private final ReceiptRepository receipts; + private final ProfileRepository profiles; + private final LearnerStatsRepository stats; + private final Learning learning; + + public Community(CommentRepository comments, CourseRepository courses, + LiveSessionRepository sessions, SeatRepository seats, ReceiptRepository receipts, + ProfileRepository profiles, LearnerStatsRepository stats, Learning learning) { + this.comments = comments; + this.courses = courses; + this.sessions = sessions; + this.seats = seats; + this.receipts = receipts; + this.profiles = profiles; + this.stats = stats; + this.learning = learning; + } + + // ------------------------------------------------------------------ + // Questions and answers + + @Transactional(readOnly = true) + public List comments(String courseId) { + Course course = published(courseId); + List out = new ArrayList(); + for (Comment comment : comments.findByCourseIdOrderByCreatedAtAsc(course.getId())) { + out.add(dto(comment, course)); + } + return out; + } + + @Transactional + public CommentDto comment(String username, String courseId, CommentDraftDto draft) + throws IOException { + Course course = published(courseId); + String text = Text.required(draft == null ? null : draft.text(), 2000, "A comment"); + String parent = draft.parentId() == null ? "" : draft.parentId(); + if (parent.length() > 0) { + Comment above = comments.findById(parent); + if (above == null || !above.getCourseId().equals(course.getId())) { + throw new ResponseStatusException(404, "No such question"); + } + // Answers hang off the question, one level deep. + if (above.getParentId().length() > 0) { + parent = above.getParentId(); + } + } + Comment comment = new Comment(); + comment.setId(Ids.next()); + comment.setCourseId(course.getId()); + comment.setParentId(parent); + comment.setAuthor(username); + comment.setText(text); + comment.setCreatedAt(System.currentTimeMillis()); + comments.save(comment); + return dto(comment, course); + } + + private CommentDto dto(Comment comment, Course course) { + return new CommentDto(comment.getId(), comment.getCourseId(), comment.getParentId(), + comment.getAuthor(), name(comment.getAuthor()), comment.getText(), + comment.getCreatedAt(), comment.getAuthor().equals(course.getCreator())); + } + + private Course published(String id) { + Course course = id == null ? null : courses.findById(id); + if (course == null || !course.isPublished()) { + throw new ResponseStatusException(404, "No such course"); + } + return course; + } + + // ------------------------------------------------------------------ + // Live tutorials + + @Transactional(readOnly = true) + public List sessions(String username) { + List out = new ArrayList(); + for (LiveSession session : sessions.findByStateNotOrderByStartsAtAsc("ended")) { + out.add(dto(session, username)); + } + return out; + } + + @Transactional + public LiveSessionDto join(String username, String id) throws IOException { + LiveSession session = session(id); + if ("ended".equals(session.getState())) { + throw new ResponseStatusException(409, "That session has ended"); + } + if (session.getHost().equals(username) || seated(id, username)) { + return dto(session, username); + } + if (session.getPriceCents() > 0 + && !receipts.existsByUsernameAndKindAndTargetId(username, "live", id)) { + throw new ResponseStatusException(402, "Buy a seat to join"); + } + if (seats.countBySessionId(id) >= session.getSeats()) { + throw new ResponseStatusException(409, "That session is full"); + } + Seat seat = new Seat(); + seat.setId(Ids.sha256(id + "|" + username)); + seat.setSessionId(id); + seat.setUsername(username); + seat.setJoinedAt(System.currentTimeMillis()); + seats.save(seat); + return dto(session, username); + } + + public LiveSession session(String id) { + LiveSession session = id == null ? null : sessions.findById(id); + if (session == null) { + throw new ResponseStatusException(404, "No such session"); + } + return session; + } + + /// Whether `username` holds a seat in the session `id`. + public boolean seated(String id, String username) { + for (Seat seat : seats.findBySessionId(id)) { + if (seat.getUsername().equals(username)) { + return true; + } + } + return false; + } + + /// Everybody in the session `id`: its host, then its seats. + @Transactional(readOnly = true) + public List members(String id) { + List out = new ArrayList(); + LiveSession session = sessions.findById(id); + if (session == null) { + return out; + } + out.add(session.getHost()); + for (Seat seat : seats.findBySessionId(id)) { + out.add(seat.getUsername()); + } + return out; + } + + public LiveSessionDto dto(LiveSession session, String username) { + return new LiveSessionDto(session.getId(), session.getTitle(), session.getLanguage(), + session.getLevel(), session.getHost(), name(session.getHost()), + session.getStartsAt(), session.getMinutes(), session.getPriceCents(), + session.getSeats(), (int) seats.countBySessionId(session.getId()), + session.getState(), seated(session.getId(), username), + session.getHost().equals(username)); + } + + // ------------------------------------------------------------------ + // Money + + @Transactional + public ReceiptDto purchase(String username, PurchaseDto purchase) throws IOException { + if (purchase == null || purchase.kind() == null) { + throw new ResponseStatusException(400, "Say what to buy"); + } + if ("declined".equals(purchase.method())) { + throw new ResponseStatusException(402, "The card was declined"); + } + String kind = purchase.kind(); + String target = purchase.targetId() == null ? "" : purchase.targetId(); + int amount; + String creator; + String description; + if ("course".equals(kind)) { + Course course = published(target); + if (learning.owns(username, course)) { + throw new ResponseStatusException(409, "You already have this course"); + } + amount = course.getPriceCents(); + creator = course.getCreator(); + description = course.getTitle(); + } else if ("live".equals(kind)) { + LiveSession session = session(target); + if (session.getHost().equals(username) + || receipts.existsByUsernameAndKindAndTargetId(username, kind, target)) { + throw new ResponseStatusException(409, "You already have a seat"); + } + amount = session.getPriceCents(); + creator = session.getHost(); + description = "Live: " + session.getTitle(); + } else if ("pro".equals(kind)) { + LearnerStats mine = learning.stats(username, true); + if (mine.isPro()) { + throw new ResponseStatusException(409, "You already have Pro"); + } + mine.setPro(true); + stats.save(mine); + amount = PRO_CENTS; + creator = ""; + description = "Lingo Pro"; + } else if ("tip".equals(kind)) { + Course course = published(target); + if (course.getCreator().length() == 0 || course.getCreator().equals(username)) { + throw new ResponseStatusException(400, "This course takes no tips"); + } + amount = purchase.amountCents(); + if (amount < 100 || amount > 10000) { + throw new ResponseStatusException(400, "A tip is between 1 and 100"); + } + creator = course.getCreator(); + description = "Tip for " + name(creator); + } else { + throw new ResponseStatusException(400, "Nothing to buy called " + kind); + } + if (amount <= 0) { + throw new ResponseStatusException(400, "That is free"); + } + Receipt receipt = new Receipt(); + receipt.setId(Ids.next()); + receipt.setUsername(username); + receipt.setKind(kind); + receipt.setTargetId(target); + receipt.setDescription(description); + receipt.setAmountCents(amount); + receipt.setCreator(creator); + // A tip goes to the creator whole; a sale is shared. + receipt.setCreatorShareCents(creator.length() == 0 ? 0 + : "tip".equals(kind) ? amount : amount * CREATOR_SHARE / 100); + receipt.setCreatedAt(System.currentTimeMillis()); + receipts.save(receipt); + learning.unlock(username, learning.stats(username, true)); + return dto(receipt); + } + + @Transactional(readOnly = true) + public WalletDto wallet(String username) { + List bought = new ArrayList(); + for (Receipt receipt : receipts.findByUsernameOrderByCreatedAtDesc(username)) { + bought.add(dto(receipt)); + } + List sold = new ArrayList(); + int earned = 0; + int pending = 0; + long weekAgo = System.currentTimeMillis() - WEEK; + for (Receipt receipt : receipts.findByCreatorOrderByCreatedAtDesc(username)) { + sold.add(dto(receipt)); + earned += receipt.getCreatorShareCents(); + // A week to clear, as a card network would hold it. + if (receipt.getCreatedAt() > weekAgo) { + pending += receipt.getCreatorShareCents(); + } + } + return new WalletDto(learning.stats(username, false).isPro(), earned, pending, bought, + sold); + } + + static ReceiptDto dto(Receipt receipt) { + return new ReceiptDto(receipt.getId(), receipt.getKind(), receipt.getDescription(), + receipt.getAmountCents(), receipt.getCreatorShareCents(), receipt.getCreatedAt()); + } + + private String name(String username) { + Profile profile = username == null ? null : profiles.findById(username); + return profile == null ? "Lingo" : profile.getDisplayName(); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/CommunityEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/CommunityEndpoint.java new file mode 100644 index 00000000000..e026b254ba9 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/community/CommunityEndpoint.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.community; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.api.CommentDraftDto; +import com.codenameone.examples.lingo.api.CommentDto; +import com.codenameone.examples.lingo.api.CommunityApiServer; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.PurchaseDto; +import com.codenameone.examples.lingo.api.ReceiptDto; +import com.codenameone.examples.lingo.api.WalletDto; +import java.util.List; + +/// [com.codenameone.examples.lingo.api.CommunityApi], served. +@Component +public class CommunityEndpoint implements CommunityApiServer { + private final Community community; + + public CommunityEndpoint(Community community) { + this.community = community; + } + + @Override + public List comments(String id) throws Exception { + return community.comments(id); + } + + @Override + public CommentDto comment(String id, CommentDraftDto draft) throws Exception { + return community.comment(Caller.name(), id, draft); + } + + @Override + public List sessions() throws Exception { + return community.sessions(Caller.name()); + } + + @Override + public LiveSessionDto join(String id) throws Exception { + return community.join(Caller.name(), id); + } + + @Override + public ReceiptDto purchase(PurchaseDto purchase) throws Exception { + return community.purchase(Caller.name(), purchase); + } + + @Override + public WalletDto wallet() throws Exception { + return community.wallet(Caller.name()); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Certificate.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Certificate.java new file mode 100644 index 00000000000..7241ffad35c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Certificate.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A certificate of completion, kept as the signed PDF that was issued. +@Entity +public class Certificate { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String courseId = ""; + + @Column(nullable = false, type = "VARCHAR(120)") + private String learnerName = ""; + + @Column(nullable = false, type = "VARCHAR(160)") + private String courseTitle = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String language = ""; + + @Column(nullable = false) + private long issuedAt; + + @Column(nullable = false) + private int minutes; + + @Column(nullable = false) + private byte[] pdf = new byte[0]; + + public Certificate() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public String getLearnerName() { + return learnerName; + } + + public void setLearnerName(String learnerName) { + this.learnerName = learnerName; + } + + public String getCourseTitle() { + return courseTitle; + } + + public void setCourseTitle(String courseTitle) { + this.courseTitle = courseTitle; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public long getIssuedAt() { + return issuedAt; + } + + public void setIssuedAt(long issuedAt) { + this.issuedAt = issuedAt; + } + + public int getMinutes() { + return minutes; + } + + public void setMinutes(int minutes) { + this.minutes = minutes; + } + + public byte[] getPdf() { + return pdf; + } + + public void setPdf(byte[] pdf) { + this.pdf = pdf; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/ClosedAccount.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/ClosedAccount.java new file mode 100644 index 00000000000..795180a04b6 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/ClosedAccount.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// What is left of an account that was closed: the hash of its e-mail, kept so +/// that the address cannot be registered again. +@Entity +public class ClosedAccount { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String usernameHash = ""; + + @Column(nullable = false) + private Instant closedAt = Instant.EPOCH; + + public ClosedAccount() { + } + + public String getUsernameHash() { + return usernameHash; + } + + public void setUsernameHash(String usernameHash) { + this.usernameHash = usernameHash; + } + + public Instant getClosedAt() { + return closedAt; + } + + public void setClosedAt(Instant closedAt) { + this.closedAt = closedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Comment.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Comment.java new file mode 100644 index 00000000000..fd4eaa3d5f4 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Comment.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A question, or an answer to one, under a course. +@Entity +public class Comment { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String courseId = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String parentId = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String author = ""; + + @Column(nullable = false, type = "VARCHAR(2000)") + private String text = ""; + + @Column(nullable = false) + private long createdAt; + + public Comment() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public String getParentId() { + return parentId; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Course.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Course.java new file mode 100644 index 00000000000..bbe1ecd00de --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Course.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A course: an AI-generated path or a creator's own. +@Entity +public class Course { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(160)") + private String title = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String language = ""; + + @Column(nullable = false, type = "VARCHAR(8)") + private String level = ""; + + @Column(nullable = false, type = "VARCHAR(1000)") + private String summary = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String kind = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String creator = ""; + + @Column(nullable = false) + private int priceCents; + + @Column(nullable = false, type = "VARCHAR(16)") + private String accent = ""; + + @Column(nullable = false) + private boolean published; + + @Column(nullable = false) + private long createdAt; + + public Course() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getKind() { + return kind; + } + + public void setKind(String kind) { + this.kind = kind; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public int getPriceCents() { + return priceCents; + } + + public void setPriceCents(int priceCents) { + this.priceCents = priceCents; + } + + public String getAccent() { + return accent; + } + + public void setAccent(String accent) { + this.accent = accent; + } + + public boolean isPublished() { + return published; + } + + public void setPublished(boolean published) { + this.published = published; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/EarnedBadge.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/EarnedBadge.java new file mode 100644 index 00000000000..3f5d755d118 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/EarnedBadge.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A badge a learner has earned. +@Entity +public class EarnedBadge { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(32)") + private String achievementId = ""; + + @Column(nullable = false) + private long unlockedAt; + + public EarnedBadge() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getAchievementId() { + return achievementId; + } + + public void setAchievementId(String achievementId) { + this.achievementId = achievementId; + } + + public long getUnlockedAt() { + return unlockedAt; + } + + public void setUnlockedAt(long unlockedAt) { + this.unlockedAt = unlockedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Enrollment.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Enrollment.java new file mode 100644 index 00000000000..024e1dd669c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Enrollment.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A learner taking a course. `completedAt` is 0 until every lesson is done. +@Entity +public class Enrollment { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String courseId = ""; + + @Column(nullable = false) + private long enrolledAt; + + @Column(nullable = false) + private long completedAt; + + public Enrollment() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public long getEnrolledAt() { + return enrolledAt; + } + + public void setEnrolledAt(long enrolledAt) { + this.enrolledAt = enrolledAt; + } + + public long getCompletedAt() { + return completedAt; + } + + public void setCompletedAt(long completedAt) { + this.completedAt = completedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LearnerStats.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LearnerStats.java new file mode 100644 index 00000000000..75673426c3c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LearnerStats.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A learner's running totals, kept so a screen never sums history. +@Entity +public class LearnerStats { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false) + private int xp; + + @Column(nullable = false) + private int streak; + + @Column(nullable = false) + private int bestStreak; + + @Column(nullable = false) + private int lastDay; + + @Column(nullable = false) + private int freezes; + + @Column(nullable = false) + private int lessonsDone; + + @Column(nullable = false) + private int seconds; + + @Column(nullable = false) + private int spoken; + + @Column(nullable = false) + private int perfect; + + @Column(nullable = false) + private boolean pro; + + public LearnerStats() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getXp() { + return xp; + } + + public void setXp(int xp) { + this.xp = xp; + } + + public int getStreak() { + return streak; + } + + public void setStreak(int streak) { + this.streak = streak; + } + + public int getBestStreak() { + return bestStreak; + } + + public void setBestStreak(int bestStreak) { + this.bestStreak = bestStreak; + } + + public int getLastDay() { + return lastDay; + } + + public void setLastDay(int lastDay) { + this.lastDay = lastDay; + } + + public int getFreezes() { + return freezes; + } + + public void setFreezes(int freezes) { + this.freezes = freezes; + } + + public int getLessonsDone() { + return lessonsDone; + } + + public void setLessonsDone(int lessonsDone) { + this.lessonsDone = lessonsDone; + } + + public int getSeconds() { + return seconds; + } + + public void setSeconds(int seconds) { + this.seconds = seconds; + } + + public int getSpoken() { + return spoken; + } + + public void setSpoken(int spoken) { + this.spoken = spoken; + } + + public int getPerfect() { + return perfect; + } + + public void setPerfect(int perfect) { + this.perfect = perfect; + } + + public boolean isPro() { + return pro; + } + + public void setPro(boolean pro) { + this.pro = pro; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Lesson.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Lesson.java new file mode 100644 index 00000000000..36a072f2a44 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Lesson.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A lesson of a course, in `position` order. `phrases` is a JSON array. +@Entity +public class Lesson { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String courseId = ""; + + @Column(nullable = false) + private int position; + + @Column(nullable = false, type = "VARCHAR(160)") + private String title = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String kind = ""; + + @Column(nullable = false, type = "VARCHAR(1000)") + private String summary = ""; + + @Column(nullable = false, type = "TEXT") + private String phrases = ""; + + @Column(nullable = false, type = "VARCHAR(1000)") + private String scenario = ""; + + @Column(nullable = false, type = "VARCHAR(500)") + private String videoUrl = ""; + + @Column(nullable = false) + private int minutes; + + @Column(nullable = false) + private int xp; + + public Lesson() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getKind() { + return kind; + } + + public void setKind(String kind) { + this.kind = kind; + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getPhrases() { + return phrases; + } + + public void setPhrases(String phrases) { + this.phrases = phrases; + } + + public String getScenario() { + return scenario; + } + + public void setScenario(String scenario) { + this.scenario = scenario; + } + + public String getVideoUrl() { + return videoUrl; + } + + public void setVideoUrl(String videoUrl) { + this.videoUrl = videoUrl; + } + + public int getMinutes() { + return minutes; + } + + public void setMinutes(int minutes) { + this.minutes = minutes; + } + + public int getXp() { + return xp; + } + + public void setXp(int xp) { + this.xp = xp; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LessonResult.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LessonResult.java new file mode 100644 index 00000000000..17cda2b786f --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LessonResult.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// The best a learner has done in a lesson. +@Entity +public class LessonResult { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String lessonId = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String courseId = ""; + + @Column(nullable = false) + private int bestScore; + + @Column(nullable = false) + private int attempts; + + @Column(nullable = false) + private long completedAt; + + public LessonResult() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLessonId() { + return lessonId; + } + + public void setLessonId(String lessonId) { + this.lessonId = lessonId; + } + + public String getCourseId() { + return courseId; + } + + public void setCourseId(String courseId) { + this.courseId = courseId; + } + + public int getBestScore() { + return bestScore; + } + + public void setBestScore(int bestScore) { + this.bestScore = bestScore; + } + + public int getAttempts() { + return attempts; + } + + public void setAttempts(int attempts) { + this.attempts = attempts; + } + + public long getCompletedAt() { + return completedAt; + } + + public void setCompletedAt(long completedAt) { + this.completedAt = completedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveSession.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveSession.java new file mode 100644 index 00000000000..92953e78bbf --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveSession.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A live tutorial. `state` is `scheduled`, `live` or `ended`. +@Entity +public class LiveSession { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(160)") + private String title = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String language = ""; + + @Column(nullable = false, type = "VARCHAR(8)") + private String level = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String host = ""; + + @Column(nullable = false) + private long startsAt; + + @Column(nullable = false) + private int minutes; + + @Column(nullable = false) + private int priceCents; + + @Column(nullable = false) + private int seats; + + @Column(nullable = false, type = "VARCHAR(16)") + private String state = ""; + + public LiveSession() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public long getStartsAt() { + return startsAt; + } + + public void setStartsAt(long startsAt) { + this.startsAt = startsAt; + } + + public int getMinutes() { + return minutes; + } + + public void setMinutes(int minutes) { + this.minutes = minutes; + } + + public int getPriceCents() { + return priceCents; + } + + public void setPriceCents(int priceCents) { + this.priceCents = priceCents; + } + + public int getSeats() { + return seats; + } + + public void setSeats(int seats) { + this.seats = seats; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveTicket.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveTicket.java new file mode 100644 index 00000000000..6e03f41767e --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/LiveTicket.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A ticket for one connection to the live channel, as its hash. +@Entity +public class LiveTicket { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String ticketHash = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false) + private Instant expiresAt = Instant.EPOCH; + + public LiveTicket() { + } + + public String getTicketHash() { + return ticketHash; + } + + public void setTicketHash(String ticketHash) { + this.ticketHash = ticketHash; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Preference.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Preference.java new file mode 100644 index 00000000000..b26f083fcc4 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Preference.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// What an account chose in Settings. A missing row reads as the defaults. +@Entity +public class Preference { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(8)") + private String theme = ""; + + @Column(nullable = false) + private boolean notifyReminders; + + @Column(nullable = false) + private boolean notifyLive; + + @Column(nullable = false) + private boolean wifiOnlyModel; + + @Column(nullable = false) + private boolean cloudTutor; + + public Preference() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getTheme() { + return theme; + } + + public void setTheme(String theme) { + this.theme = theme; + } + + public boolean isNotifyReminders() { + return notifyReminders; + } + + public void setNotifyReminders(boolean notifyReminders) { + this.notifyReminders = notifyReminders; + } + + public boolean isNotifyLive() { + return notifyLive; + } + + public void setNotifyLive(boolean notifyLive) { + this.notifyLive = notifyLive; + } + + public boolean isWifiOnlyModel() { + return wifiOnlyModel; + } + + public void setWifiOnlyModel(boolean wifiOnlyModel) { + this.wifiOnlyModel = wifiOnlyModel; + } + + public boolean isCloudTutor() { + return cloudTutor; + } + + public void setCloudTutor(boolean cloudTutor) { + this.cloudTutor = cloudTutor; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Profile.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Profile.java new file mode 100644 index 00000000000..5f292d39a00 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Profile.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// An account's profile: who it is to the people it works with. +/// +/// The sign-in -- password hash, roles, whether it is enabled -- is the backend's +/// own user store, under the same name. +@Entity +public class Profile { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(120)") + private String displayName = ""; + + @Column(nullable = false, type = "VARCHAR(32)") + private String phone = ""; + + @Column(nullable = false, type = "VARCHAR(8)") + private String language = ""; + + /// The language the learner is studying, a BCP 47 tag such as `es-ES`. + @Column(nullable = false, type = "VARCHAR(16)") + private String targetLanguage = ""; + + @Column(nullable = false) + private long createdAt; + + public Profile() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getTargetLanguage() { + return targetLanguage; + } + + public void setTargetLanguage(String targetLanguage) { + this.targetLanguage = targetLanguage; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/PushDevice.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/PushDevice.java new file mode 100644 index 00000000000..7b85528bc3e --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/PushDevice.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A device an account is sent push notifications on. +/// +/// Keyed by the hash of its provider and token, so a token is on one account at +/// a time: the phone belongs to whoever signed in on it last. +@Entity +public class PushDevice { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + /// `fcm`, `apns`, `huawei`, `wns` or `web`. + @Column(nullable = false, type = "VARCHAR(16)") + private String provider = ""; + + @Column(nullable = false, type = "VARCHAR(1024)") + private String token = ""; + + @Column(nullable = false, type = "VARCHAR(32)") + private String platform = ""; + + @Column(nullable = false) + private Instant updatedAt = Instant.EPOCH; + + public PushDevice() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Receipt.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Receipt.java new file mode 100644 index 00000000000..7cb351ffeb3 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Receipt.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A payment, with the creator's share of it. +@Entity +public class Receipt { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String kind = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String targetId = ""; + + @Column(nullable = false, type = "VARCHAR(200)") + private String description = ""; + + @Column(nullable = false) + private int amountCents; + + @Column(nullable = false, type = "VARCHAR(190)") + private String creator = ""; + + @Column(nullable = false) + private int creatorShareCents; + + @Column(nullable = false) + private long createdAt; + + public Receipt() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getKind() { + return kind; + } + + public void setKind(String kind) { + this.kind = kind; + } + + public String getTargetId() { + return targetId; + } + + public void setTargetId(String targetId) { + this.targetId = targetId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getAmountCents() { + return amountCents; + } + + public void setAmountCents(int amountCents) { + this.amountCents = amountCents; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public int getCreatorShareCents() { + return creatorShareCents; + } + + public void setCreatorShareCents(int creatorShareCents) { + this.creatorShareCents = creatorShareCents; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Seat.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Seat.java new file mode 100644 index 00000000000..7afa0f1b548 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Seat.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A learner booked into a live tutorial. +@Entity +public class Seat { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String sessionId = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false) + private long joinedAt; + + public Seat() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public long getJoinedAt() { + return joinedAt; + } + + public void setJoinedAt(long joinedAt) { + this.joinedAt = joinedAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/SigningKey.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/SigningKey.java new file mode 100644 index 00000000000..137be59a078 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/SigningKey.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// The key and certificate the server signs certificates with, made on first use. +@Entity +public class SigningKey { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false) + private byte[] privateKey = new byte[0]; + + @Column(nullable = false) + private byte[] certificate = new byte[0]; + + @Column(nullable = false) + private long createdAt; + + public SigningKey() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public byte[] getPrivateKey() { + return privateKey; + } + + public void setPrivateKey(byte[] privateKey) { + this.privateKey = privateKey; + } + + public byte[] getCertificate() { + return certificate; + } + + public void setCertificate(byte[] certificate) { + this.certificate = certificate; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Upload.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Upload.java new file mode 100644 index 00000000000..06c18a426c3 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/Upload.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// A recorded lesson a creator uploaded. +@Entity +public class Upload { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String mime = ""; + + @Column(nullable = false) + private byte[] data = new byte[0]; + + @Column(nullable = false) + private long createdAt; + + public Upload() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getMime() { + return mime; + } + + public void setMime(String mime) { + this.mime = mime; + } + + public byte[] getData() { + return data; + } + + public void setData(byte[] data) { + this.data = data; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/XpEvent.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/XpEvent.java new file mode 100644 index 00000000000..a82121d45ff --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/domain/XpEvent.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; + +/// Experience earned, by day: what the streak and the weekly board are made of. +@Entity +public class XpEvent { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String lessonId = ""; + + @Column(nullable = false) + private int xp; + + @Column(nullable = false) + private int day; + + @Column(nullable = false) + private int seconds; + + @Column(nullable = false) + private long createdAt; + + public XpEvent() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLessonId() { + return lessonId; + } + + public void setLessonId(String lessonId) { + this.lessonId = lessonId; + } + + public int getXp() { + return xp; + } + + public void setXp(int xp) { + this.xp = xp; + } + + public int getDay() { + return day; + } + + public void setDay(int day) { + this.day = day; + } + + public int getSeconds() { + return seconds; + } + + public void setSeconds(int seconds) { + this.seconds = seconds; + } + + public long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(long createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Badges.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Badges.java new file mode 100644 index 00000000000..575c6990da8 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Badges.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codenameone.examples.lingo.api.AchievementDto; +import com.codenameone.examples.lingo.domain.LearnerStats; +import java.util.ArrayList; +import java.util.List; + +/// The badges, and the rule that earns each. The server alone decides: the +/// app shows what it is told, so a modified app cannot unlock anything. +public final class Badges { + static final String LESSONS = "lessons"; + static final String STREAK = "streak"; + static final String XP = "xp"; + static final String SPOKEN = "spoken"; + static final String PERFECT = "perfect"; + static final String CERTIFICATES = "certificates"; + static final String LANGUAGES = "languages"; + static final String TIPS = "tips"; + + /// One badge: what it measures, and how much of it earns the badge. + public static final class Badge { + final String id; + final String title; + final String description; + final String icon; + final int xp; + final String metric; + final int goal; + + Badge(String id, String title, String description, String icon, int xp, String metric, + int goal) { + this.id = id; + this.title = title; + this.description = description; + this.icon = icon; + this.xp = xp; + this.metric = metric; + this.goal = goal; + } + + AchievementDto dto(int value, long unlockedAt) { + return new AchievementDto(id, title, description, icon, xp, unlockedAt > 0, + unlockedAt, Math.min(value, goal), goal); + } + } + + /// What a learner has done, counted for the rules. + public static final class Counts { + final LearnerStats stats; + final int certificates; + final int languages; + final int tips; + + public Counts(LearnerStats stats, int certificates, int languages, int tips) { + this.stats = stats; + this.certificates = certificates; + this.languages = languages; + this.tips = tips; + } + + int value(String metric) { + if (LESSONS.equals(metric)) { + return stats.getLessonsDone(); + } + if (STREAK.equals(metric)) { + return Math.max(stats.getStreak(), stats.getBestStreak()); + } + if (XP.equals(metric)) { + return stats.getXp(); + } + if (SPOKEN.equals(metric)) { + return stats.getSpoken(); + } + if (PERFECT.equals(metric)) { + return stats.getPerfect(); + } + if (CERTIFICATES.equals(metric)) { + return certificates; + } + if (LANGUAGES.equals(metric)) { + return languages; + } + return TIPS.equals(metric) ? tips : 0; + } + } + + static final Badge[] ALL = { + new Badge("first-words", "First words", "Finish your first lesson", "record_voice_over", + 10, LESSONS, 1), + new Badge("on-fire", "On fire", "Practise three days in a row", "local_fire_department", + 20, STREAK, 3), + new Badge("perfect-pitch", "Perfect pitch", "Score 100 on a lesson", "graphic_eq", 25, + PERFECT, 1), + new Badge("chatterbox", "Chatterbox", "Say 50 phrases out loud", "forum", 30, SPOKEN, 50), + new Badge("scholar", "Scholar", "Finish ten lessons", "menu_book", 40, LESSONS, 10), + new Badge("week-strong", "Seven days strong", "Keep a seven-day streak", "bolt", 50, + STREAK, 7), + new Badge("rising-star", "Rising star", "Earn 500 experience", "star", 50, XP, 500), + new Badge("graduate", "Graduate", "Earn a certificate", "workspace_premium", 100, + CERTIFICATES, 1), + new Badge("polyglot", "Polyglot", "Study two languages", "translate", 60, LANGUAGES, 2), + new Badge("patron", "Patron", "Support a creator with a tip", "volunteer_activism", 20, + TIPS, 1), + }; + + private Badges() { + } + + /// The badges `counts` has earned that are not in `held`. + static List earned(Counts counts, List held) { + List out = new ArrayList(); + for (Badge badge : ALL) { + if (!held.contains(badge.id) && counts.value(badge.metric) >= badge.goal) { + out.add(badge); + } + } + return out; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Catalogue.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Catalogue.java new file mode 100644 index 00000000000..122f89c1954 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Catalogue.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.backend.Json; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.domain.Course; +import com.codenameone.examples.lingo.domain.Enrollment; +import com.codenameone.examples.lingo.domain.LearnerStats; +import com.codenameone.examples.lingo.domain.Lesson; +import com.codenameone.examples.lingo.domain.LessonResult; +import com.codenameone.examples.lingo.domain.LiveSession; +import com.codenameone.examples.lingo.domain.Upload; +import com.codenameone.examples.lingo.domain.XpEvent; +import com.codenameone.examples.lingo.repository.CourseRepository; +import com.codenameone.examples.lingo.repository.EnrollmentRepository; +import com.codenameone.examples.lingo.repository.LearnerStatsRepository; +import com.codenameone.examples.lingo.repository.LessonRepository; +import com.codenameone.examples.lingo.repository.LessonResultRepository; +import com.codenameone.examples.lingo.repository.LiveSessionRepository; +import com.codenameone.examples.lingo.repository.UploadRepository; +import com.codenameone.examples.lingo.repository.XpEventRepository; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/// The courses a new server starts with, from `seed/courses.json`. +/// +/// The AI-guided courses are seeded everywhere: they are the product, and a +/// deployment without a catalogue has nothing to teach. The community +/// courses, their recorded lessons and the live tutorials belong to the demo +/// creator, so they are seeded only on a development profile, with some +/// progress for the demo learners so the screens have something to show. +@Component +public class Catalogue { + static final String RESOURCE = "/seed/courses.json"; + + private final CourseRepository courses; + private final LessonRepository lessons; + private final UploadRepository uploads; + private final LiveSessionRepository sessions; + private final EnrollmentRepository enrollments; + private final LessonResultRepository results; + private final XpEventRepository events; + private final LearnerStatsRepository stats; + + public Catalogue(CourseRepository courses, LessonRepository lessons, UploadRepository uploads, + LiveSessionRepository sessions, EnrollmentRepository enrollments, + LessonResultRepository results, XpEventRepository events, + LearnerStatsRepository stats) { + this.courses = courses; + this.lessons = lessons; + this.uploads = uploads; + this.sessions = sessions; + this.enrollments = enrollments; + this.results = results; + this.events = events; + this.stats = stats; + } + + /// Adds every course not yet in the database. `creator` owns the + /// community courses; null leaves them out. + @Transactional + public void seed(String creator) throws IOException { + Map root = Json.parseObject(read(RESOURCE, "UTF-8")); + long now = System.currentTimeMillis(); + int order = 0; + for (Object item : (List) root.get("courses")) { + Map c = (Map) item; + boolean community = Boolean.TRUE.equals(c.get("community")); + String id = (String) c.get("id"); + order++; + if ((community && creator == null) || courses.findById(id) != null) { + continue; + } + Course course = new Course(); + course.setId(id); + course.setTitle((String) c.get("title")); + course.setLanguage((String) c.get("language")); + course.setLevel((String) c.get("level")); + course.setSummary((String) c.get("summary")); + course.setAccent((String) c.get("accent")); + course.setKind(community ? "community" : "ai"); + course.setCreator(community ? creator : ""); + course.setPriceCents(((Number) c.get("price")).intValue()); + course.setPublished(true); + // Seconds apart, in file order: the catalogue lists by creation. + course.setCreatedAt(now - 100000L + order * 1000L); + courses.save(course); + int position = 0; + for (Object l : (List) c.get("lessons")) { + lessons.save(lesson(course, (Map) l, ++position, creator)); + } + } + } + + private Lesson lesson(Course course, Map l, int position, String creator) throws IOException { + Lesson lesson = new Lesson(); + lesson.setId(course.getId() + "-" + position); + lesson.setCourseId(course.getId()); + lesson.setPosition(position); + lesson.setTitle((String) l.get("title")); + lesson.setKind((String) l.get("kind")); + lesson.setSummary((String) l.get("summary")); + List phrases = new ArrayList(); + Object rows = l.get("phrases"); + if (rows instanceof List) { + for (Object row : (List) rows) { + List p = (List) row; + phrases.add(new PhraseDto((String) p.get(0), (String) p.get(1), (String) p.get(2))); + } + } + lesson.setPhrases(Learning.phrasesJson(phrases)); + Object scenario = l.get("scenario"); + lesson.setScenario(scenario instanceof String ? (String) scenario : ""); + Object video = l.get("video"); + if (video instanceof String) { + Upload upload = new Upload(); + upload.setId(Ids.next()); + upload.setUsername(creator == null ? "" : creator); + upload.setMime("video/mp4"); + upload.setData(bytes("/seed/" + video)); + upload.setCreatedAt(System.currentTimeMillis()); + uploads.save(upload); + lesson.setVideoUrl("/media/" + upload.getId()); + } + int minutes = ((Number) l.get("minutes")).intValue(); + lesson.setMinutes(minutes); + lesson.setXp(10 + minutes * 2); + return lesson; + } + + /// The demo creator's live tutorials: one on now-ish and free, one paid + /// tomorrow. + @Transactional + public void seedLive(String host) throws IOException { + if (!sessions.findByHostOrderByStartsAtAsc(host).isEmpty()) { + return; + } + long hour = 60L * 60 * 1000; + long now = System.currentTimeMillis(); + sessions.save(live(host, "Pronunciation clinic: the Spanish R", "A2", now + hour / 4, 30, + 0, 8)); + sessions.save(live(host, "Mock DELE speaking exam", "B1", now + 26 * hour, 45, 1200, 4)); + sessions.save(live(host, "Tapas vocabulary night", "A1", now + 50 * hour, 40, 500, 10)); + } + + private static LiveSession live(String host, String title, String level, long at, int minutes, + int price, int seats) throws IOException { + LiveSession session = new LiveSession(); + session.setId(Ids.next()); + session.setTitle(title); + session.setLanguage("es-ES"); + session.setLevel(level); + session.setHost(host); + session.setStartsAt(at); + session.setMinutes(minutes); + session.setPriceCents(price); + session.setSeats(seats); + session.setState("scheduled"); + return session; + } + + /// Progress for a demo learner: enrolled in the travel course with its + /// first `done` lessons passed, `xp` spread over the last `days` days. + @Transactional + public void seedProgress(String username, int done, int xp, int days) throws IOException { + if (stats.findById(username) != null) { + return; + } + long now = System.currentTimeMillis(); + int today = Learning.today(); + Enrollment enrollment = new Enrollment(); + enrollment.setId(Ids.sha256(username + "|spanish-travel")); + enrollment.setUsername(username); + enrollment.setCourseId("spanish-travel"); + enrollment.setEnrolledAt(now - days * Learning.DAY); + enrollments.save(enrollment); + for (int iter = 1; iter <= done; iter++) { + LessonResult result = new LessonResult(); + result.setId(Ids.sha256(username + "|spanish-travel-" + iter)); + result.setUsername(username); + result.setLessonId("spanish-travel-" + iter); + result.setCourseId("spanish-travel"); + result.setBestScore(78 + iter * 4); + result.setAttempts(1); + result.setCompletedAt(now - (done - iter) * Learning.DAY); + results.save(result); + } + for (int day = 0; day < days; day++) { + XpEvent event = new XpEvent(); + event.setId(Ids.next()); + event.setUsername(username); + event.setLessonId(""); + event.setXp(xp / days); + event.setDay(today - day); + event.setSeconds(300); + event.setCreatedAt(now - day * Learning.DAY); + events.save(event); + } + LearnerStats row = new LearnerStats(); + row.setUsername(username); + row.setXp(xp / days * days); + row.setStreak(days); + row.setBestStreak(days); + row.setLastDay(today); + row.setLessonsDone(done); + row.setSeconds(days * 300); + row.setSpoken(done * 5); + stats.save(row); + } + + static String read(String resource, String charset) throws IOException { + return new String(bytes(resource), charset); + } + + static byte[] bytes(String resource) throws IOException { + try (InputStream in = Catalogue.class.getResourceAsStream(resource)) { + if (in == null) { + throw new IOException("Missing resource " + resource); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/LearnEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/LearnEndpoint.java new file mode 100644 index 00000000000..a1c2812f464 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/LearnEndpoint.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.api.AchievementDto; +import com.codenameone.examples.lingo.api.AttemptDto; +import com.codenameone.examples.lingo.api.CertificateDto; +import com.codenameone.examples.lingo.api.CertificatePdfDto; +import com.codenameone.examples.lingo.api.CourseDetailDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LeaderEntryDto; +import com.codenameone.examples.lingo.api.LearnApiServer; +import com.codenameone.examples.lingo.api.ProgressDto; +import com.codenameone.examples.lingo.api.StatsDto; +import com.codenameone.examples.lingo.api.TutorReplyDto; +import com.codenameone.examples.lingo.api.TutorRequestDto; +import com.codenameone.examples.lingo.api.VerificationDto; +import com.codenameone.examples.lingo.cert.Certificates; +import java.util.List; + +/// [com.codenameone.examples.lingo.api.LearnApi], served. +@Component +public class LearnEndpoint implements LearnApiServer { + private final Learning learning; + private final Certificates certificates; + private final Tutor tutor; + + public LearnEndpoint(Learning learning, Certificates certificates, Tutor tutor) { + this.learning = learning; + this.certificates = certificates; + this.tutor = tutor; + } + + @Override + public List courses() throws Exception { + return learning.courses(Caller.name()); + } + + @Override + public CourseDetailDto course(String id) throws Exception { + return learning.course(Caller.name(), id); + } + + @Override + public CourseDto enroll(String id) throws Exception { + return learning.enroll(Caller.name(), id); + } + + @Override + public ProgressDto attempt(String id, AttemptDto attempt) throws Exception { + return learning.attempt(Caller.name(), id, attempt); + } + + @Override + public StatsDto stats() throws Exception { + return learning.stats(Caller.name()); + } + + @Override + public List achievements() throws Exception { + return learning.achievements(Caller.name()); + } + + @Override + public List leaderboard() throws Exception { + return learning.leaderboard(Caller.name()); + } + + @Override + public List certificates() throws Exception { + return certificates.list(Caller.name()); + } + + @Override + public CertificatePdfDto certificatePdf(String id) throws Exception { + return certificates.pdf(Caller.name(), id); + } + + @Override + public VerificationDto verify(String id) throws Exception { + return certificates.verify(id); + } + + @Override + public TutorReplyDto tutor(TutorRequestDto request) throws Exception { + return tutor.reply(request); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Learning.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Learning.java new file mode 100644 index 00000000000..b6a3634578c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Learning.java @@ -0,0 +1,594 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.backend.Json; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.AchievementDto; +import com.codenameone.examples.lingo.api.AttemptDto; +import com.codenameone.examples.lingo.api.CourseDetailDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LeaderEntryDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.api.ProgressDto; +import com.codenameone.examples.lingo.api.StatsDto; +import com.codenameone.examples.lingo.cert.Certificates; +import com.codenameone.examples.lingo.domain.Course; +import com.codenameone.examples.lingo.domain.EarnedBadge; +import com.codenameone.examples.lingo.domain.Enrollment; +import com.codenameone.examples.lingo.domain.LearnerStats; +import com.codenameone.examples.lingo.domain.Lesson; +import com.codenameone.examples.lingo.domain.LessonResult; +import com.codenameone.examples.lingo.domain.Profile; +import com.codenameone.examples.lingo.domain.Receipt; +import com.codenameone.examples.lingo.domain.XpEvent; +import com.codenameone.examples.lingo.repository.CertificateRepository; +import com.codenameone.examples.lingo.repository.CourseRepository; +import com.codenameone.examples.lingo.repository.EarnedBadgeRepository; +import com.codenameone.examples.lingo.repository.EnrollmentRepository; +import com.codenameone.examples.lingo.repository.LearnerStatsRepository; +import com.codenameone.examples.lingo.repository.LessonRepository; +import com.codenameone.examples.lingo.repository.LessonResultRepository; +import com.codenameone.examples.lingo.repository.ProfileRepository; +import com.codenameone.examples.lingo.repository.ReceiptRepository; +import com.codenameone.examples.lingo.repository.XpEventRepository; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Progress through courses: experience, levels, streaks, badges and the +/// moment a course is finished and its certificate issued. +/// +/// Every number is the server's. The app reports a score and how long a +/// lesson took; what that earns is worked out here, from the lesson's own +/// value, so the leaderboard means something. +@Component +public class Learning { + /// The experience a day's goal asks for. + public static final int DAILY_GOAL = 50; + /// The score a lesson needs to count as done. + public static final int PASS = 60; + static final long DAY = 24L * 60 * 60 * 1000; + /// A freeze is earned every seven days of streak, and at most this many + /// are kept: a missed day spends one instead of the streak. + static final int MAX_FREEZES = 2; + + private final CourseRepository courses; + private final LessonRepository lessons; + private final EnrollmentRepository enrollments; + private final LessonResultRepository results; + private final XpEventRepository events; + private final LearnerStatsRepository statsRepository; + private final EarnedBadgeRepository badges; + private final ReceiptRepository receipts; + private final CertificateRepository certificateRows; + private final ProfileRepository profiles; + private final Certificates certificates; + + public Learning(CourseRepository courses, LessonRepository lessons, + EnrollmentRepository enrollments, LessonResultRepository results, + XpEventRepository events, LearnerStatsRepository statsRepository, + EarnedBadgeRepository badges, ReceiptRepository receipts, + CertificateRepository certificateRows, ProfileRepository profiles, + Certificates certificates) { + this.courses = courses; + this.lessons = lessons; + this.enrollments = enrollments; + this.results = results; + this.events = events; + this.statsRepository = statsRepository; + this.badges = badges; + this.receipts = receipts; + this.certificateRows = certificateRows; + this.profiles = profiles; + this.certificates = certificates; + } + + static int today() { + return (int) (System.currentTimeMillis() / DAY); + } + + // ------------------------------------------------------------------ + // The catalogue + + @Transactional(readOnly = true) + public List courses(String username) { + Map mine = enrollmentsOf(username); + List out = new ArrayList(); + for (Course course : courses.findByPublishedTrueOrderByCreatedAtAsc()) { + out.add(dto(course, username, mine.get(course.getId()))); + } + return out; + } + + @Transactional(readOnly = true) + public CourseDetailDto course(String username, String id) { + Course course = visible(username, id); + Enrollment enrollment = enrollmentsOf(username).get(id); + return new CourseDetailDto(dto(course, username, enrollment), + lessonsOf(course, username)); + } + + @Transactional + public CourseDto enroll(String username, String id) throws IOException { + Course course = visible(username, id); + if (!owns(username, course)) { + throw new ResponseStatusException(402, "Buy this course to join it"); + } + Enrollment enrollment = enrollmentsOf(username).get(id); + if (enrollment == null) { + enrollment = new Enrollment(); + enrollment.setId(Ids.sha256(username + "|" + id)); + enrollment.setUsername(username); + enrollment.setCourseId(id); + enrollment.setEnrolledAt(System.currentTimeMillis()); + enrollments.save(enrollment); + unlock(username, stats(username, true)); + } + return dto(course, username, enrollment); + } + + /// A course anybody may see: published, or the caller's own draft. + Course visible(String username, String id) { + Course course = id == null ? null : courses.findById(id); + if (course == null || (!course.isPublished() && !course.getCreator().equals(username))) { + throw new ResponseStatusException(404, "No such course"); + } + return course; + } + + /// Whether `username` may take `course`: it is free, theirs, or bought. + public boolean owns(String username, Course course) { + return course.getPriceCents() == 0 || course.getCreator().equals(username) + || receipts.existsByUsernameAndKindAndTargetId(username, "course", course.getId()); + } + + public CourseDto dto(Course course, String username, Enrollment enrollment) { + List all = lessons.findByCourseIdOrderByPositionAsc(course.getId()); + int minutes = 0; + for (Lesson lesson : all) { + minutes += lesson.getMinutes(); + } + int done = 0; + if (enrollment != null) { + for (LessonResult result : results.findByUsernameAndCourseId(username, + course.getId())) { + if (result.getCompletedAt() > 0) { + done++; + } + } + } + return new CourseDto(course.getId(), course.getTitle(), course.getLanguage(), + course.getLevel(), course.getSummary(), course.getKind(), course.getCreator(), + nameOf(course.getCreator()), course.getPriceCents(), all.size(), minutes, + enrollment != null, owns(username, course), done, course.getAccent(), + course.isPublished(), (int) enrollments.countByCourseId(course.getId())); + } + + List lessonsOf(Course course, String username) { + Map mine = new HashMap(); + for (LessonResult result : results.findByUsernameAndCourseId(username, course.getId())) { + mine.put(result.getLessonId(), result); + } + List out = new ArrayList(); + boolean open = true; + for (Lesson lesson : lessons.findByCourseIdOrderByPositionAsc(course.getId())) { + LessonResult result = mine.get(lesson.getId()); + boolean completed = result != null && result.getCompletedAt() > 0; + out.add(dto(lesson, completed, result == null ? 0 : result.getBestScore(), !open)); + // Each lesson opens when the one before it is done. + open = completed; + } + return out; + } + + public static LessonDto dto(Lesson lesson, boolean completed, int best, boolean locked) { + return new LessonDto(lesson.getId(), lesson.getCourseId(), lesson.getPosition(), + lesson.getTitle(), lesson.getKind(), lesson.getSummary(), + phrases(lesson.getPhrases()), lesson.getScenario(), lesson.getVideoUrl(), + lesson.getMinutes(), lesson.getXp(), completed, best, locked); + } + + /// The phrases of a lesson, kept as a JSON array of objects. + public static List phrases(String json) { + List out = new ArrayList(); + if (json == null || json.length() == 0) { + return out; + } + try { + Object tree = Json.parse(json); + if (tree instanceof List) { + for (Object item : (List) tree) { + if (item instanceof Map) { + Map row = (Map) item; + out.add(new PhraseDto(text(row.get("text")), + text(row.get("translation")), text(row.get("hint")))); + } + } + } + } catch (IOException malformed) { + return out; + } + return out; + } + + public static String phrasesJson(List phrases) { + List> rows = new ArrayList>(); + for (int iter = 0; phrases != null && iter < phrases.size(); iter++) { + PhraseDto phrase = phrases.get(iter); + Map row = new LinkedHashMap(); + row.put("text", phrase.text() == null ? "" : phrase.text()); + row.put("translation", phrase.translation() == null ? "" : phrase.translation()); + row.put("hint", phrase.hint() == null ? "" : phrase.hint()); + rows.add(row); + } + return Json.write(rows); + } + + private static String text(Object value) { + return value instanceof String ? (String) value : ""; + } + + // ------------------------------------------------------------------ + // A finished lesson + + @Transactional + public ProgressDto attempt(String username, String lessonId, AttemptDto attempt) + throws IOException { + Lesson lesson = lessonId == null ? null : lessons.findById(lessonId); + if (lesson == null || attempt == null) { + throw new ResponseStatusException(404, "No such lesson"); + } + Course course = visible(username, lesson.getCourseId()); + Enrollment enrollment = enrollmentsOf(username).get(course.getId()); + if (enrollment == null) { + throw new ResponseStatusException(409, "Join the course first"); + } + List path = lessonsOf(course, username); + for (LessonDto step : path) { + if (step.id().equals(lessonId) && step.locked()) { + throw new ResponseStatusException(409, "Finish the lesson before this one first"); + } + } + int score = Math.max(0, Math.min(100, attempt.score())); + int seconds = Math.max(0, Math.min(3600, attempt.seconds())); + int spoken = Math.max(0, Math.min(100, attempt.spoken())); + long now = System.currentTimeMillis(); + + LessonResult result = null; + for (LessonResult r : results.findByUsernameAndCourseId(username, course.getId())) { + if (r.getLessonId().equals(lessonId)) { + result = r; + } + } + boolean first = result == null || result.getCompletedAt() == 0; + if (result == null) { + result = new LessonResult(); + result.setId(Ids.sha256(username + "|" + lessonId)); + result.setUsername(username); + result.setLessonId(lessonId); + result.setCourseId(course.getId()); + } + result.setAttempts(result.getAttempts() + 1); + result.setBestScore(Math.max(result.getBestScore(), score)); + boolean passed = score >= PASS; + if (passed && result.getCompletedAt() == 0) { + result.setCompletedAt(now); + } + results.save(result); + + // Full value the first time a lesson is passed, a fifth of it for + // practising one again, and a little for trying. + int xp; + if (!passed) { + xp = 2; + } else if (first) { + xp = lesson.getXp() * score / 100 + (score == 100 ? 5 : 0); + } else { + xp = Math.max(1, lesson.getXp() / 5); + } + LearnerStats stats = stats(username, true); + int day = today(); + practised(stats, day); + stats.setXp(stats.getXp() + xp); + stats.setSeconds(stats.getSeconds() + seconds); + stats.setSpoken(stats.getSpoken() + spoken); + if (passed && first) { + stats.setLessonsDone(stats.getLessonsDone() + 1); + } + if (score == 100) { + stats.setPerfect(stats.getPerfect() + 1); + } + statsRepository.save(stats); + record(username, lessonId, xp, seconds, day, now); + + boolean completed = false; + String certificateId = ""; + if (passed && enrollment.getCompletedAt() == 0 && allDone(username, course)) { + enrollment.setCompletedAt(now); + enrollments.save(enrollment); + completed = true; + certificateId = certificates.issue(username, course, lessonMinutes(course)).getId(); + } else if (enrollment.getCompletedAt() != 0) { + // Practising a finished course: the app still links to the one + // certificate issued for it. + certificateId = certificates.issue(username, course, lessonMinutes(course)).getId(); + } + List unlocked = unlock(username, stats); + int earned = xp; + for (AchievementDto badge : unlocked) { + earned += badge.xp(); + } + return new ProgressDto(earned, describe(username, stats), unlocked, completed, + certificateId); + } + + /// Moves the streak to `day`: on from yesterday, kept by a freeze over + /// one missed day, or started again. + static void practised(LearnerStats stats, int day) { + int last = stats.getLastDay(); + if (last == day) { + return; + } + if (last == day - 1) { + stats.setStreak(stats.getStreak() + 1); + } else if (last == day - 2 && stats.getFreezes() > 0 && stats.getStreak() > 0) { + stats.setFreezes(stats.getFreezes() - 1); + stats.setStreak(stats.getStreak() + 1); + } else { + stats.setStreak(1); + } + if (stats.getStreak() % 7 == 0 && stats.getFreezes() < MAX_FREEZES) { + stats.setFreezes(stats.getFreezes() + 1); + } + stats.setBestStreak(Math.max(stats.getBestStreak(), stats.getStreak())); + stats.setLastDay(day); + } + + private void record(String username, String lessonId, int xp, int seconds, int day, long now) + throws IOException { + XpEvent event = new XpEvent(); + event.setId(Ids.next()); + event.setUsername(username); + event.setLessonId(lessonId == null ? "" : lessonId); + event.setXp(xp); + event.setDay(day); + event.setSeconds(seconds); + event.setCreatedAt(now); + events.save(event); + } + + private boolean allDone(String username, Course course) { + List all = lessons.findByCourseIdOrderByPositionAsc(course.getId()); + if (all.isEmpty()) { + return false; + } + int done = 0; + for (LessonResult result : results.findByUsernameAndCourseId(username, course.getId())) { + if (result.getCompletedAt() > 0) { + done++; + } + } + return done >= all.size(); + } + + private int lessonMinutes(Course course) { + int minutes = 0; + for (Lesson lesson : lessons.findByCourseIdOrderByPositionAsc(course.getId())) { + minutes += lesson.getMinutes(); + } + return minutes; + } + + // ------------------------------------------------------------------ + // Standing + + /// The running totals of `username`, made when `create` and missing. + public LearnerStats stats(String username, boolean create) { + LearnerStats stats = statsRepository.findById(username); + if (stats == null) { + stats = new LearnerStats(); + stats.setUsername(username); + if (create) { + statsRepository.save(stats); + } + } + return stats; + } + + @Transactional(readOnly = true) + public StatsDto stats(String username) { + return describe(username, stats(username, false)); + } + + StatsDto describe(String username, LearnerStats stats) { + int day = today(); + int[] week = new int[7]; + for (XpEvent event : events.findByUsernameAndDayGreaterThanEqual(username, day - 6)) { + int at = event.getDay() - (day - 6); + if (at >= 0 && at < 7) { + week[at] += event.getXp(); + } + } + List days = new ArrayList(); + for (int value : week) { + days.add(Integer.valueOf(value)); + } + int level = level(stats.getXp()); + // A streak that missed yesterday (and has no freeze to cover it) + // reads as gone, though the row keeps it until the next lesson. + int streak = stats.getStreak(); + if (stats.getLastDay() < day - 1 + && !(stats.getLastDay() == day - 2 && stats.getFreezes() > 0)) { + streak = 0; + } + return new StatsDto(stats.getXp(), level, stats.getXp() - levelStart(level), + levelStart(level + 1) - levelStart(level), streak, stats.getBestStreak(), + week[6], DAILY_GOAL, stats.getLessonsDone(), stats.getSeconds() / 60, + stats.getFreezes(), stats.isPro(), days); + } + + /// Level n starts at 50 n (n - 1) experience: 0, 100, 300, 600 ... + static int levelStart(int level) { + return 50 * level * (level - 1); + } + + static int level(int xp) { + int level = 1; + while (levelStart(level + 1) <= xp) { + level++; + } + return level; + } + + @Transactional(readOnly = true) + public List achievements(String username) { + Map held = new HashMap(); + for (EarnedBadge badge : badges.findByUsername(username)) { + held.put(badge.getAchievementId(), Long.valueOf(badge.getUnlockedAt())); + } + Badges.Counts counts = counts(username, stats(username, false)); + List out = new ArrayList(); + for (Badges.Badge badge : Badges.ALL) { + Long at = held.get(badge.id); + out.add(badge.dto(counts.value(badge.metric), at == null ? 0 : at.longValue())); + } + return out; + } + + /// Awards whatever `stats` now earns and answers what was new. Called + /// after anything that moves a count: a lesson, a tip, a course joined. + @Transactional + public List unlock(String username, LearnerStats stats) throws IOException { + List held = new ArrayList(); + for (EarnedBadge badge : badges.findByUsername(username)) { + held.add(badge.getAchievementId()); + } + List out = new ArrayList(); + long now = System.currentTimeMillis(); + Badges.Counts counts = counts(username, stats); + for (Badges.Badge badge : Badges.earned(counts, held)) { + EarnedBadge row = new EarnedBadge(); + row.setId(Ids.sha256(username + "|" + badge.id)); + row.setUsername(username); + row.setAchievementId(badge.id); + row.setUnlockedAt(now); + badges.save(row); + stats.setXp(stats.getXp() + badge.xp); + out.add(badge.dto(counts.value(badge.metric), now)); + } + if (!out.isEmpty()) { + statsRepository.save(stats); + int total = 0; + for (AchievementDto badge : out) { + total += badge.xp(); + } + record(username, "", total, 0, today(), now); + } + return out; + } + + private Badges.Counts counts(String username, LearnerStats stats) { + List languages = new ArrayList(); + for (Enrollment enrollment : enrollments.findByUsername(username)) { + Course course = courses.findById(enrollment.getCourseId()); + if (course != null && !languages.contains(prefix(course.getLanguage()))) { + languages.add(prefix(course.getLanguage())); + } + } + int tips = 0; + for (Receipt receipt : receipts.findByUsernameOrderByCreatedAtDesc(username)) { + if ("tip".equals(receipt.getKind())) { + tips++; + } + } + return new Badges.Counts(stats, + certificateRows.findByUsernameOrderByIssuedAtDesc(username).size(), + languages.size(), tips); + } + + /// `es` of `es-ES`: two courses in one language and two regions are + /// still one language. + static String prefix(String tag) { + int dash = tag.indexOf('-'); + return dash < 0 ? tag : tag.substring(0, dash); + } + + /// This week's experience, Monday to now, highest first, with the + /// caller's own row marked. + @Transactional(readOnly = true) + public List leaderboard(String username) { + int day = today(); + // Day 0 of the epoch was a Thursday; Monday is three days later. + int monday = day - ((day + 3) % 7); + final Map totals = new HashMap(); + for (XpEvent event : events.findByDayGreaterThanEqual(monday)) { + Integer sum = totals.get(event.getUsername()); + totals.put(event.getUsername(), + Integer.valueOf((sum == null ? 0 : sum.intValue()) + event.getXp())); + } + if (!totals.containsKey(username)) { + totals.put(username, Integer.valueOf(0)); + } + List names = new ArrayList(totals.keySet()); + Collections.sort(names, (a, b) -> { + int diff = totals.get(b).intValue() - totals.get(a).intValue(); + return diff != 0 ? diff : a.compareTo(b); + }); + List out = new ArrayList(); + for (int iter = 0; iter < names.size(); iter++) { + String name = names.get(iter); + if (iter >= 20 && !name.equals(username)) { + continue; + } + Profile profile = profiles.findById(name); + if (profile == null) { + continue; + } + LearnerStats stats = stats(name, false); + out.add(new LeaderEntryDto(iter + 1, profile.getDisplayName(), + totals.get(name).intValue(), stats.getStreak(), name.equals(username))); + } + return out; + } + + private Map enrollmentsOf(String username) { + Map out = new HashMap(); + for (Enrollment enrollment : enrollments.findByUsername(username)) { + out.put(enrollment.getCourseId(), enrollment); + } + return out; + } + + String nameOf(String username) { + if (username == null || username.length() == 0) { + return "Lingo"; + } + Profile profile = profiles.findById(username); + return profile == null ? "" : profile.getDisplayName(); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Tutor.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Tutor.java new file mode 100644 index 00000000000..3d02615a975 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/learn/Tutor.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.ai.ClaudeClient; +import com.codenameone.examples.lingo.api.TutorReplyDto; +import com.codenameone.examples.lingo.api.TutorRequestDto; +import com.codenameone.examples.lingo.api.TutorTurnDto; +import com.codenameone.examples.lingo.api.TutorPrompt; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The cloud tutor: a conversation partner for a phone that can run no +/// model of its own, and only for a learner who said yes to it in Settings. +/// +/// The app tries the phone's own model first, then a downloaded one; this +/// is the last resort, and answers `available == false` when the server has +/// no key, so the app falls back to its scripted partner. +@Component +public class Tutor { + static final int MAX_TURNS = 24; + static final int MAX_TEXT = 600; + + private final ClaudeClient claude; + + public Tutor(ClaudeClient claude) { + this.claude = claude; + } + + public TutorReplyDto reply(TutorRequestDto request) { + if (!claude.isLive() || request == null) { + return new TutorReplyDto("", "", false); + } + Map body = new LinkedHashMap(); + body.put("max_tokens", Integer.valueOf(300)); + body.put("system", TutorPrompt.system(request.language(), request.level(), + request.scenario())); + List> messages = new ArrayList>(); + List turns = request.turns() == null ? new ArrayList() + : request.turns(); + int from = Math.max(0, turns.size() - MAX_TURNS); + for (int iter = from; iter < turns.size(); iter++) { + TutorTurnDto turn = turns.get(iter); + Map message = new LinkedHashMap(); + message.put("role", "assistant".equals(turn.role()) ? "assistant" : "user"); + String text = turn.text() == null ? "" : turn.text(); + message.put("content", text.length() > MAX_TEXT ? text.substring(0, MAX_TEXT) : text); + messages.add(message); + } + if (messages.isEmpty()) { + Map start = new LinkedHashMap(); + start.put("role", "user"); + start.put("content", TutorPrompt.OPENING); + messages.add(start); + } + body.put("messages", messages); + try { + String text = ClaudeClient.text(claude.message(body)).trim(); + return split(text); + } catch (IOException failed) { + System.err.println("Cloud tutor: " + failed.getMessage()); + return new TutorReplyDto("", "", false); + } + } + + /// The model is asked to put a correction, when there is one, on a last + /// line of its own that starts `FIX:`. + static TutorReplyDto split(String text) { + String[] parts = TutorPrompt.split(text); + return new TutorReplyDto(parts[0], parts[1], true); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveEndpoint.java new file mode 100644 index 00000000000..fdb5aa20194 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveEndpoint.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.live; + +import com.codename1.backend.WebSocket; +import com.codename1.backend.WebSocketSession; +import com.codename1.backend.annotations.WebSocketMapping; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.community.Community; +import com.codenameone.examples.lingo.domain.LiveSession; +import com.codename1.backend.Json; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The live channel: one WebSocket per signed-in app, down which the server +/// says what changed ([LiveHub]). +/// +/// No filter chain covers this path, deliberately: the handshake cannot carry +/// the bearer token on every platform. The connection is let in by the ticket +/// in its address instead ([LiveTickets]), and one that presents none, or one +/// already used, is closed before it is told anything. +@WebSocketMapping("/ws/live") +public class LiveEndpoint implements WebSocket { + private final LiveTickets tickets; + private final Accounts accounts; + private final LiveHub hub; + private final Community community; + + public LiveEndpoint(LiveTickets tickets, Accounts accounts, LiveHub hub, + Community community) { + this.tickets = tickets; + this.accounts = accounts; + this.hub = hub; + this.community = community; + } + + @Override + public void onOpen(WebSocketSession session) throws Exception { + String username = tickets.redeem(ticket(session.getQuery())); + UserDto user = username == null ? null : accounts.describe(username); + if (user == null || user.suspended()) { + session.close(4401, "ticket"); + return; + } + // Who this connection is, kept on the connection: the one piece of + // state a WebSocket has that a request does not. + session.setAttachment(username); + hub.add(username, user.creator() || user.admin(), session); + // Read again now that the connection is in the hub. A block or a + // withdrawn admin role commits and then drops the account's + // connections; one that committed after the read above and dropped + // before the add found nothing to drop, and this connection would + // carry what was read before -- for an admin, every learner's position. + // Either the change is seen here, or its drop comes after the add and + // closes this connection. + UserDto now = accounts.describe(username); + if (now == null || now.suspended() || (now.creator() || now.admin()) != (user.creator() || user.admin())) { + hub.remove(username, session); + session.close(4403, "changed"); + return; + } + session.sendText("{\"type\":\"ready\"}"); + } + + @Override + public void onText(WebSocketSession session, String message) throws Exception { + Object who = session.getAttachment(); + if (!(who instanceof String) || message == null) { + return; + } + // The app says one thing to learn the connection is still alive on a + // network that drops idle ones without telling either end, and the + // other is WebRTC signaling for a live session. + if (message.indexOf("\"ping\"") >= 0 && message.length() < 32) { + session.sendText("{\"type\":\"pong\"}"); + return; + } + if (message.length() <= MAX_SIGNAL) { + signal((String) who, message); + } + } + + /// The largest signaling frame relayed: an SDP offer with every codec is + /// a few kilobytes. + static final int MAX_SIGNAL = 32 * 1024; + + /// Relays an offer, answer, ICE candidate, hello or goodbye between two + /// people in the same live session -- host and learner -- and only while + /// it is live. The server reads none of it: the media flows between the + /// phones, and this is how they find each other. + void signal(String from, String message) throws IOException { + Map frame; + try { + frame = Json.parseObject(message); + } catch (IOException malformed) { + return; + } + if (frame == null || !"signal".equals(frame.get("type"))) { + return; + } + String room = text(frame.get("room")); + String to = text(frame.get("to")); + LiveSession live; + try { + live = community.session(room); + } catch (RuntimeException gone) { + return; + } + List members = community.members(room); + if (!"live".equals(live.getState()) || !members.contains(from) + || (to.length() > 0 && !members.contains(to))) { + return; + } + UserDto sender = accounts.describe(from); + Map out = new LinkedHashMap(); + out.put("type", "signal"); + out.put("room", room); + out.put("from", from); + out.put("fromName", sender == null ? "" : sender.displayName()); + out.put("host", Boolean.valueOf(live.getHost().equals(from))); + out.put("kind", text(frame.get("kind"))); + out.put("data", text(frame.get("data"))); + List recipients = new ArrayList(); + if (to.length() > 0) { + recipients.add(to); + } else { + for (String member : members) { + if (!member.equals(from)) { + recipients.add(member); + } + } + } + hub.sendTo(recipients, Json.write(out)); + } + + private static String text(Object value) { + return value instanceof String ? (String) value : ""; + } + + @Override + public void onBinary(WebSocketSession session, byte[] message, int offset, int length) + throws Exception { + session.close(1003, "text only"); + } + + @Override + public void onClose(WebSocketSession session, int code, String reason) { + Object username = session.getAttachment(); + if (username instanceof String) { + hub.remove((String) username, session); + } + } + + /// The `ticket` parameter of a query string, or null. A ticket is hex, so + /// there is nothing in it to decode. + static String ticket(String query) { + if (query == null) { + return null; + } + int at = 0; + while (at < query.length()) { + int end = query.indexOf('&', at); + if (end < 0) { + end = query.length(); + } + if (query.startsWith("ticket=", at)) { + return query.substring(at + 7, end); + } + at = end + 1; + } + return null; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveHub.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveHub.java new file mode 100644 index 00000000000..79b65d24e3a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveHub.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.live; + +import com.codename1.backend.Json; +import com.codename1.backend.WebSocketSession; +import com.codename1.backend.annotations.Component; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The open live connections, and what is pushed down them. +/// +/// Two frames, each a small JSON object: +/// +/// - `{"type":"session","id":...,"state":...}` -- a live tutorial opened +/// (`live`) or closed (`ended`). Sent to its host and everybody holding a +/// seat, who then read it from the API. +/// - `{"type":"signal","room":...,"from":...,"kind":...,"data":...}` -- WebRTC +/// signaling between two people in a live session, relayed by +/// [LiveEndpoint]: an offer, an answer, an ICE candidate, a hello or a +/// goodbye. +/// +/// The connections are those of this process; running more than one +/// instance needs a channel between them (a database LISTEN/NOTIFY, a +/// message broker) feeding [#sendTo]. +@Component +public class LiveHub { + private final Map> byUser = + new HashMap>(); + private final List admins = new ArrayList(); + + synchronized void add(String username, boolean creator, WebSocketSession session) { + List open = byUser.get(username); + if (open == null) { + open = new ArrayList(); + byUser.put(username, open); + } + open.add(session); + if (creator) { + admins.add(session); + } + } + + synchronized void remove(String username, WebSocketSession session) { + List open = byUser.get(username); + if (open != null) { + open.remove(session); + if (open.isEmpty()) { + byUser.remove(username); + } + } + admins.remove(session); + } + + /// How many connections are open, for the tests. + public synchronized int connections() { + int total = 0; + for (List open : byUser.values()) { + total += open.size(); + } + return total; + } + + /// Closes every connection an account has open. + public void drop(String username) { + List open; + synchronized (this) { + open = byUser.remove(username); + if (open != null) { + admins.removeAll(open); + } + } + for (int iter = 0; open != null && iter < open.size(); iter++) { + open.get(iter).close(4403, "suspended"); + } + } + + /// Tells everybody in a live session that it opened or closed. + public void sessionChanged(String sessionId, String state, List members) { + Map frame = new LinkedHashMap(); + frame.put("type", "session"); + frame.put("id", sessionId); + frame.put("state", state); + sendTo(members, Json.write(frame)); + } + + /// Sends `text` to every connection of each of `usernames`. + public void sendTo(List usernames, String text) { + List to = new ArrayList(); + synchronized (this) { + for (int iter = 0; iter < usernames.size(); iter++) { + collect(to, usernames.get(iter)); + } + } + send(to, text); + } + + private static void addAll(List to, List from) { + for (int iter = 0; iter < from.size(); iter++) { + if (!to.contains(from.get(iter))) { + to.add(from.get(iter)); + } + } + } + + /// Must be called holding the lock. + private void collect(List to, String username) { + List open = username == null ? null : byUser.get(username); + for (int iter = 0; open != null && iter < open.size(); iter++) { + if (!to.contains(open.get(iter))) { + to.add(open.get(iter)); + } + } + } + + /// Sends outside the lock: a slow client holds up its own frame, not + /// everyone's. One that cannot be written to is dropped; its close callback + /// takes it out of the maps. + private static void send(List to, String text) { + for (int iter = 0; iter < to.size(); iter++) { + WebSocketSession session = to.get(iter); + try { + session.sendText(text); + } catch (IOException gone) { + session.abort(); + } + } + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveTickets.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveTickets.java new file mode 100644 index 00000000000..3fa3eae668a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/live/LiveTickets.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.live; + +import com.codename1.backend.Crypto; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Scheduled; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.TicketDto; +import com.codenameone.examples.lingo.domain.LiveTicket; +import com.codenameone.examples.lingo.repository.LiveTicketRepository; + +import java.io.IOException; +import java.time.Instant; + +/// Tickets for the live channel. +/// +/// A WebSocket handshake is one request the app cannot attach its bearer token +/// to on every platform -- a browser's WebSocket takes no headers at all -- and a +/// token in the address would end up in every access log on the way. So the app +/// asks for a ticket over the authenticated API and presents that instead: it +/// is random, it names nothing, it is good for one connection, and it is stale +/// in half a minute. +@Component +public class LiveTickets { + static final int TICKET_SECONDS = 30; + + private final LiveTicketRepository tickets; + + public LiveTickets(LiveTicketRepository tickets) { + this.tickets = tickets; + } + + /// Not held against the account being closed, as the rows that last are. + /// A ticket issued in the instant an account is erased outlives it by at + /// most [#TICKET_SECONDS] plus one [#sweep], and opens nothing meanwhile: + /// `LiveEndpoint` checks the account again when the ticket is redeemed. + /// A row lock on every socket connect is not worth that minute. + @Transactional + public TicketDto issue(String username) throws IOException { + String ticket = Ids.hex(Crypto.randomBytes(24)); + LiveTicket row = new LiveTicket(); + row.setTicketHash(Ids.sha256(ticket)); + row.setUsername(username); + row.setExpiresAt(Instant.now().plusSeconds(TICKET_SECONDS)); + tickets.insert(row); + return new TicketDto(ticket, TICKET_SECONDS); + } + + /// The account a ticket was issued to, or null when it is unknown, used or + /// stale. Redeeming it uses it up: the row is deleted, and only the + /// connection whose delete removed it is let in, so a ticket presented twice + /// at the same moment still opens one connection. + @Transactional + public String redeem(String ticket) throws IOException { + if (ticket == null || ticket.length() == 0 || ticket.length() > 128) { + return null; + } + String hash = Ids.sha256(ticket); + LiveTicket row = tickets.findById(hash); + if (row == null) { + return null; + } + String username = row.getUsername(); + Instant expiresAt = row.getExpiresAt(); + // One delete statement: the count it answers is what says this + // connection, and not another presenting the same ticket, used it. + int removed = tickets.deleteByTicketHash(hash); + if (removed != 1 || expiresAt.isBefore(Instant.now())) { + return null; + } + return username; + } + + /// Clears the tickets nobody came back for. + @Scheduled(fixedDelay = 60000, initialDelay = 60000) + @Transactional + public void sweep() throws IOException { + tickets.deleteByExpiresAtLessThan(Instant.now()); + } + + /// Forgets the tickets of an account that is being closed. + @Transactional + public void forget(String username) { + tickets.deleteByUsername(username); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/push/PushDevices.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/push/PushDevices.java new file mode 100644 index 00000000000..3a8b5231413 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/push/PushDevices.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.push; + +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.backend.push.PushTarget; +import com.codenameone.examples.lingo.Ids; +import com.codename1.appkit.server.Text; +import com.codenameone.examples.lingo.api.PushDeviceDto; +import com.codenameone.examples.lingo.domain.PushDevice; +import com.codenameone.examples.lingo.repository.ProfileRepository; +import com.codenameone.examples.lingo.repository.PushDeviceRepository; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +// tag::lingo-push-devices[] +/// The devices each account is sent notifications on. +/// +/// The app registers its token when somebody signs in and removes it when they +/// sign out. A token registered by a second account moves to it: the phone +/// belongs to whoever signed in on it last, and the one before is not to be +/// told about the new owner's classes. +@Component +public class PushDevices { + /// How many devices one account keeps. A new one past this replaces the + /// one heard from longest ago: a token the platform has replaced is never + /// removed by its app, and would otherwise be sent to for good. + static final int MAX_PER_ACCOUNT = 8; + + private final PushDeviceRepository devices; + private final ProfileRepository profiles; + + public PushDevices(PushDeviceRepository devices, ProfileRepository profiles) { + this.devices = devices; + this.profiles = profiles; + } + + @Transactional + public PushDeviceDto register(String username, PushDeviceDto device) throws IOException { + PushTarget target = target(device); + String id = key(target); + Instant now = Instant.now(); + // Before anything is read, the account's profile row is held: a no-op + // update that answers 0 when the profile is gone and otherwise keeps + // the row locked until this commits. It settles two races. + // + // Against closing the account: Accounts.erase holds the same row + // first and deletes it before it commits, so a registration either + // runs first (and erase's cleanup then deletes the device with the + // rest) or waits, finds no profile and is refused. Without it, a + // registration authorized just before the closure could insert its + // device after erase removed the account's, leaving a device of an + // account that no longer exists and that nobody can unregister. + // + // Against itself: two devices registering at once for an account one + // short of the cap would both count the same rows in makeRoom(), both + // skip the eviction and both insert, one past the cap. Behind the hold + // the second counts after the first committed, and evicts. + if (profiles.hold(username) == 0) { + throw new ResponseStatusException(404, "No such account"); + } + // The device row itself is not locked. Two accounts registering one + // token at the same moment -- a registration of the account that + // signed out still in flight as the next one signs in -- can leave it + // with the earlier account, but not for long: the app registers again + // each time it comes to the foreground, for whoever is signed in then. + PushDevice row = devices.findById(id); + if (row == null || !username.equals(row.getUsername())) { + // A device new to this account, whether its token is new or moves + // here from another account, takes a place under the cap. + makeRoom(username); + } + if (row == null) { + row = new PushDevice(); + row.setId(id); + row.setProvider(target.getProvider()); + row.setToken(target.getToken()); + fill(row, username, device, now); + devices.insert(row); + } else { + fill(row, username, device, now); + } + return new PushDeviceDto(target.getProvider(), target.getToken(), row.getPlatform()); + } + + /// Removes `username`'s devices heard from longest ago until one more fits + /// under [#MAX_PER_ACCOUNT]. + private void makeRoom(String username) { + List held = new ArrayList(devices.findByUsername(username)); + while (held.size() >= MAX_PER_ACCOUNT) { + PushDevice oldest = held.get(0); + for (PushDevice each : held) { + if (each.getUpdatedAt().isBefore(oldest.getUpdatedAt())) { + oldest = each; + } + } + devices.deleteById(oldest.getId()); + held.remove(oldest); + } + } + + /// Forgets a device, if it is this account's. Somebody else's is left alone. + @Transactional + public PushDeviceDto unregister(String username, PushDeviceDto device) throws IOException { + PushTarget target = target(device); + devices.deleteByIdAndUsername(key(target), username); + return new PushDeviceDto(target.getProvider(), target.getToken(), ""); + } + + /// Where to reach `username`: every device they registered. + @Transactional(readOnly = true) + public List targets(String username) { + return targetsOf(username); + } + + /// [#targets] for a caller already inside a transaction. + List targetsOf(String username) { + List out = new ArrayList(); + if (username == null || username.length() == 0) { + return out; + } + for (PushDevice each : devices.findByUsername(username)) { + out.add(PushTarget.of(each.getProvider(), each.getToken())); + } + return out; + } + // end::lingo-push-devices[] + + private static void fill(PushDevice row, String username, PushDeviceDto device, Instant now) { + row.setUsername(username); + row.setPlatform(Text.optional(device.platform(), 32, "the platform")); + row.setUpdatedAt(now); + } + + /// The device as a target of the push service, which also spells its + /// provider the one way: `gcm` and `fcm` are one device. + private static PushTarget target(PushDeviceDto device) { + if (device == null) { + throw new ResponseStatusException(400, "Tell us the device"); + } + String token = Text.required(device.token(), 1024, "the device's token"); + try { + return PushTarget.of(Text.required(device.provider(), 16, "the push provider"), token); + } catch (IllegalArgumentException err) { + throw new ResponseStatusException(400, err.getMessage()); + } + } + + private static String key(PushTarget target) throws IOException { + return Ids.sha256(target.getProvider() + ":" + target.getToken()); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CertificateRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CertificateRepository.java new file mode 100644 index 00000000000..36f32163a6a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CertificateRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Certificate; +import java.util.List; + +@Repository(entity = Certificate.class, key = String.class) +public interface CertificateRepository extends CrudRepository { + List findByUsernameOrderByIssuedAtDesc(String username); + Certificate findFirstByUsernameAndCourseId(String username, String courseId); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ClosedAccountRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ClosedAccountRepository.java new file mode 100644 index 00000000000..615c01096a9 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ClosedAccountRepository.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.ClosedAccount; + +/// The hashes of the e-mails that had an account once and may not have another. +@Repository(entity = ClosedAccount.class, key = String.class) +public interface ClosedAccountRepository extends CrudRepository { + +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CommentRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CommentRepository.java new file mode 100644 index 00000000000..5ebad817dc8 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CommentRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Comment; +import java.util.List; + +@Repository(entity = Comment.class, key = String.class) +public interface CommentRepository extends CrudRepository { + List findByCourseIdOrderByCreatedAtAsc(String courseId); + int deleteByAuthor(String author); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CourseRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CourseRepository.java new file mode 100644 index 00000000000..0b5fac55b2a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/CourseRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Course; +import java.util.List; + +@Repository(entity = Course.class, key = String.class) +public interface CourseRepository extends CrudRepository { + List findByPublishedTrueOrderByCreatedAtAsc(); + List findByCreatorOrderByCreatedAtAsc(String creator); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EarnedBadgeRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EarnedBadgeRepository.java new file mode 100644 index 00000000000..8ed976f5d6c --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EarnedBadgeRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.EarnedBadge; +import java.util.List; + +@Repository(entity = EarnedBadge.class, key = String.class) +public interface EarnedBadgeRepository extends CrudRepository { + List findByUsername(String username); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EnrollmentRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EnrollmentRepository.java new file mode 100644 index 00000000000..e6472a402d5 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/EnrollmentRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Enrollment; +import java.util.List; + +@Repository(entity = Enrollment.class, key = String.class) +public interface EnrollmentRepository extends CrudRepository { + List findByUsername(String username); + long countByCourseId(String courseId); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LearnerStatsRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LearnerStatsRepository.java new file mode 100644 index 00000000000..b339bbb2db0 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LearnerStatsRepository.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.LearnerStats; + +@Repository(entity = LearnerStats.class, key = String.class) +public interface LearnerStatsRepository extends CrudRepository { + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonRepository.java new file mode 100644 index 00000000000..224fe2d1b78 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Lesson; +import java.util.List; + +@Repository(entity = Lesson.class, key = String.class) +public interface LessonRepository extends CrudRepository { + List findByCourseIdOrderByPositionAsc(String courseId); + long countByCourseId(String courseId); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonResultRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonResultRepository.java new file mode 100644 index 00000000000..557679be136 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LessonResultRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.LessonResult; +import java.util.List; + +@Repository(entity = LessonResult.class, key = String.class) +public interface LessonResultRepository extends CrudRepository { + List findByUsernameAndCourseId(String username, String courseId); + List findByUsername(String username); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveSessionRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveSessionRepository.java new file mode 100644 index 00000000000..9535b7ee64f --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveSessionRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.LiveSession; +import java.util.List; + +@Repository(entity = LiveSession.class, key = String.class) +public interface LiveSessionRepository extends CrudRepository { + List findByStateNotOrderByStartsAtAsc(String state); + List findByHostOrderByStartsAtAsc(String host); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveTicketRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveTicketRepository.java new file mode 100644 index 00000000000..493a898bb9a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/LiveTicketRepository.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.LiveTicket; +import java.time.Instant; + +/// The tickets that open a live connection. Only the hash of a ticket is +/// stored, and it is the row's key. +@Repository(entity = LiveTicket.class, key = String.class) +public interface LiveTicketRepository extends CrudRepository { + /// Deletes a ticket and answers how many rows that removed: 1 for the one + /// caller that used it, 0 for anyone presenting it after. A statement and + /// not a read followed by a removal, because that count is the whole + /// point. + int deleteByTicketHash(String ticketHash); + + /// Deletes the tickets that went stale before `now`. + int deleteByExpiresAtLessThan(Instant now); + + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PreferenceRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PreferenceRepository.java new file mode 100644 index 00000000000..5afcfc46d2b --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PreferenceRepository.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Preference; + +/// An account's preferences, keyed by its name. An account that never saved any +/// has no row. +@Repository(entity = Preference.class, key = String.class) +public interface PreferenceRepository extends CrudRepository { + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ProfileRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ProfileRepository.java new file mode 100644 index 00000000000..99b89859319 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ProfileRepository.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Profile; + +import java.util.List; + +/// Profiles, keyed by the e-mail an account signs in with. +/// +/// A repository holds the queries of one kind of entity and nothing else: no +/// rule about who may do what, and no transaction of its own. The build writes +/// its implementation, and every call runs on the session of the transaction +/// its caller opened, so a service method marked `@Transactional` is what +/// makes several of these calls one unit of work. Called outside one, it is +/// refused. +@Repository(entity = Profile.class, key = String.class) +public interface ProfileRepository extends CrudRepository { + /// Makes the rest of the transaction wait its turn behind any other that + /// holds the same account: the row is written, to the value it has, and a + /// written row is kept by its writer until it commits. For a check and an + /// insert that must not be interleaved with the same pair made for the + /// same account. Call it before anything is read: what is read after it is + /// what the transaction before this one left, while a row read before it + /// was read before the wait. + /// + /// @return 1, or 0 when the account has no profile + @Modifying + @Query("update Profile p set p.createdAt = p.createdAt where p.username = :username") + int hold(@Param("username") String username); + + /// The profiles of these accounts; none for a name that has none. + List findByUsernameIn(List usernames); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PushDeviceRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PushDeviceRepository.java new file mode 100644 index 00000000000..684a8321e99 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/PushDeviceRepository.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.PushDevice; + +import java.util.List; + +/// The devices each account is sent notifications on. +@Repository(entity = PushDevice.class, key = String.class) +public interface PushDeviceRepository extends CrudRepository { + List findByUsername(String username); + + int deleteByUsername(String username); + + int deleteByIdAndUsername(String id, String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ReceiptRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ReceiptRepository.java new file mode 100644 index 00000000000..ff388a9af11 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/ReceiptRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Receipt; +import java.util.List; + +@Repository(entity = Receipt.class, key = String.class) +public interface ReceiptRepository extends CrudRepository { + List findByUsernameOrderByCreatedAtDesc(String username); + List findByCreatorOrderByCreatedAtDesc(String creator); + boolean existsByUsernameAndKindAndTargetId(String username, String kind, String targetId); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SeatRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SeatRepository.java new file mode 100644 index 00000000000..981e6daaf92 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SeatRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Seat; +import java.util.List; + +@Repository(entity = Seat.class, key = String.class) +public interface SeatRepository extends CrudRepository { + List findBySessionId(String sessionId); + long countBySessionId(String sessionId); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SigningKeyRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SigningKeyRepository.java new file mode 100644 index 00000000000..06574215c8a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/SigningKeyRepository.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.SigningKey; + +@Repository(entity = SigningKey.class, key = String.class) +public interface SigningKeyRepository extends CrudRepository { +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/UploadRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/UploadRepository.java new file mode 100644 index 00000000000..9941b872f94 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/UploadRepository.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.Upload; + +@Repository(entity = Upload.class, key = String.class) +public interface UploadRepository extends CrudRepository { +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/XpEventRepository.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/XpEventRepository.java new file mode 100644 index 00000000000..ec882bc93e2 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/repository/XpEventRepository.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.lingo.domain.XpEvent; +import java.util.List; + +@Repository(entity = XpEvent.class, key = String.class) +public interface XpEventRepository extends CrudRepository { + List findByDayGreaterThanEqual(int day); + List findByUsernameAndDayGreaterThanEqual(String username, int day); + int deleteByUsername(String username); +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/Studio.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/Studio.java new file mode 100644 index 00000000000..4ef2d89ff43 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/Studio.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.Base64; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.Ids; +import com.codenameone.examples.lingo.api.CourseDraftDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDraftDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.LiveDraftDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.api.StudioDto; +import com.codenameone.examples.lingo.api.UploadDto; +import com.codenameone.examples.lingo.api.UploadedDto; +import com.codenameone.examples.lingo.community.Community; +import com.codenameone.examples.lingo.domain.Course; +import com.codenameone.examples.lingo.domain.Lesson; +import com.codenameone.examples.lingo.domain.LiveSession; +import com.codenameone.examples.lingo.domain.Receipt; +import com.codenameone.examples.lingo.domain.Upload; +import com.codenameone.examples.lingo.learn.Learning; +import com.codenameone.examples.lingo.live.LiveHub; +import com.codenameone.examples.lingo.repository.CourseRepository; +import com.codenameone.examples.lingo.repository.EnrollmentRepository; +import com.codenameone.examples.lingo.repository.LessonRepository; +import com.codenameone.examples.lingo.repository.LiveSessionRepository; +import com.codenameone.examples.lingo.repository.ReceiptRepository; +import com.codenameone.examples.lingo.repository.UploadRepository; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/// A creator's studio: courses written lesson by lesson, recorded lessons +/// uploaded, live tutorials scheduled and hosted. +@Component +public class Studio { + static final String[] LEVELS = {"A1", "A2", "B1", "B2", "C1", "C2"}; + static final String[] KINDS = {"phrases", "conversation", "video"}; + static final String[] LANGUAGES = {"es-ES", "fr-FR", "de-DE", "it-IT", "pt-BR", "ja-JP"}; + static final String[] ACCENTS = {"indigo", "coral", "teal", "amber", "rose", "sky"}; + /// The largest recorded lesson, before base 64. + static final int MAX_UPLOAD = 8 * 1024 * 1024; + + private final CourseRepository courses; + private final LessonRepository lessons; + private final LiveSessionRepository sessions; + private final UploadRepository uploads; + private final ReceiptRepository receipts; + private final EnrollmentRepository enrollments; + private final Learning learning; + private final Community community; + private final LiveHub hub; + + public Studio(CourseRepository courses, LessonRepository lessons, + LiveSessionRepository sessions, UploadRepository uploads, ReceiptRepository receipts, + EnrollmentRepository enrollments, Learning learning, Community community, + LiveHub hub) { + this.courses = courses; + this.lessons = lessons; + this.sessions = sessions; + this.uploads = uploads; + this.receipts = receipts; + this.enrollments = enrollments; + this.learning = learning; + this.community = community; + this.hub = hub; + } + + @Transactional(readOnly = true) + public StudioDto studio(String username) { + List mine = new ArrayList(); + int learners = 0; + for (Course course : courses.findByCreatorOrderByCreatedAtAsc(username)) { + mine.add(learning.dto(course, username, null)); + learners += (int) enrollments.countByCourseId(course.getId()); + } + List hosted = new ArrayList(); + for (LiveSession session : sessions.findByHostOrderByStartsAtAsc(username)) { + hosted.add(community.dto(session, username)); + } + int earned = 0; + for (Receipt receipt : receipts.findByCreatorOrderByCreatedAtDesc(username)) { + earned += receipt.getCreatorShareCents(); + } + return new StudioDto(mine, hosted, earned, learners); + } + + @Transactional + public CourseDto createCourse(String username, CourseDraftDto draft) throws IOException { + if (draft == null) { + throw new ResponseStatusException(400, "A course needs a title"); + } + Course course = new Course(); + course.setId(Ids.next()); + course.setTitle(Text.required(draft.title(), 160, "A title")); + course.setLanguage(Text.oneOf(draft.language(), LANGUAGES, "es-ES", "A language")); + course.setLevel(Text.oneOf(draft.level(), LEVELS, "A1", "A level")); + course.setSummary(Text.optional(draft.summary(), 1000, "A summary")); + course.setKind("community"); + course.setCreator(username); + if (draft.priceCents() < 0 || draft.priceCents() > 20000) { + throw new ResponseStatusException(400, "A price is between 0 and 200"); + } + course.setPriceCents(draft.priceCents()); + course.setAccent(Text.oneOf(draft.accent(), ACCENTS, "indigo", "A colour")); + course.setCreatedAt(System.currentTimeMillis()); + courses.save(course); + return learning.dto(course, username, null); + } + + @Transactional + public LessonDto addLesson(String username, String courseId, LessonDraftDto draft) + throws IOException { + Course course = own(username, courseId); + if (draft == null) { + throw new ResponseStatusException(400, "A lesson needs a title"); + } + Lesson lesson = new Lesson(); + lesson.setId(Ids.next()); + lesson.setCourseId(course.getId()); + lesson.setPosition((int) lessons.countByCourseId(course.getId()) + 1); + lesson.setTitle(Text.required(draft.title(), 160, "A title")); + lesson.setKind(Text.oneOf(draft.kind(), KINDS, "phrases", "A kind of lesson")); + lesson.setSummary(Text.optional(draft.summary(), 1000, "A summary")); + List phrases = draft.phrases() == null ? new ArrayList() + : draft.phrases(); + if (phrases.size() > 30) { + throw new ResponseStatusException(400, "A lesson has at most 30 phrases"); + } + for (PhraseDto phrase : phrases) { + Text.required(phrase.text(), 200, "A phrase"); + } + if ("phrases".equals(lesson.getKind()) && phrases.isEmpty()) { + throw new ResponseStatusException(400, "Add a phrase to say"); + } + lesson.setPhrases(Learning.phrasesJson(phrases)); + lesson.setScenario(Text.optional(draft.scenario(), 1000, "A scenario")); + String video = Text.optional(draft.videoUrl(), 500, "A video"); + if ("video".equals(lesson.getKind()) && video.length() == 0) { + throw new ResponseStatusException(400, "Record or link the video first"); + } + lesson.setVideoUrl(video); + lesson.setMinutes(Math.max(1, Math.min(60, draft.minutes()))); + lesson.setXp(10 + lesson.getMinutes() * 2); + lessons.save(lesson); + return Learning.dto(lesson, false, 0, false); + } + + @Transactional + public CourseDto publish(String username, String courseId) { + Course course = own(username, courseId); + if (lessons.countByCourseId(course.getId()) == 0) { + throw new ResponseStatusException(409, "Add a lesson before publishing"); + } + course.setPublished(true); + courses.save(course); + return learning.dto(course, username, null); + } + + @Transactional + public UploadedDto upload(String username, UploadDto upload) throws IOException { + if (upload == null || upload.data() == null) { + throw new ResponseStatusException(400, "Nothing to upload"); + } + String mime = upload.mime() == null ? "" : upload.mime(); + if (!mime.startsWith("video/") && !mime.startsWith("audio/")) { + throw new ResponseStatusException(415, "Upload a video or a recording"); + } + if (upload.data().length() > MAX_UPLOAD / 3 * 4 + 4) { + throw new ResponseStatusException(413, "A recording is at most 8 MB"); + } + byte[] data; + try { + data = Base64.decode(upload.data()); + } catch (RuntimeException malformed) { + throw new ResponseStatusException(400, "That is not base 64"); + } + Upload row = new Upload(); + row.setId(Ids.next()); + row.setUsername(username); + row.setMime(Text.required(mime, 64, "A type")); + row.setData(data); + row.setCreatedAt(System.currentTimeMillis()); + uploads.save(row); + return new UploadedDto("/media/" + row.getId(), data.length); + } + + @Transactional + public LiveSessionDto schedule(String username, LiveDraftDto draft) throws IOException { + if (draft == null) { + throw new ResponseStatusException(400, "A session needs a title"); + } + LiveSession session = new LiveSession(); + session.setId(Ids.next()); + session.setTitle(Text.required(draft.title(), 160, "A title")); + session.setLanguage(Text.oneOf(draft.language(), LANGUAGES, "es-ES", "A language")); + session.setLevel(Text.oneOf(draft.level(), LEVELS, "A1", "A level")); + session.setHost(username); + long now = System.currentTimeMillis(); + session.setStartsAt(draft.startsAt() < now ? now : draft.startsAt()); + session.setMinutes(Math.max(15, Math.min(180, draft.minutes()))); + if (draft.priceCents() < 0 || draft.priceCents() > 20000) { + throw new ResponseStatusException(400, "A price is between 0 and 200"); + } + session.setPriceCents(draft.priceCents()); + session.setSeats(Math.max(1, Math.min(12, draft.seats()))); + session.setState("scheduled"); + sessions.save(session); + return community.dto(session, username); + } + + @Transactional + public LiveSessionDto start(String username, String id) { + return move(username, id, "live"); + } + + @Transactional + public LiveSessionDto end(String username, String id) { + return move(username, id, "ended"); + } + + private LiveSessionDto move(String username, String id, String state) { + LiveSession session = community.session(id); + if (!session.getHost().equals(username)) { + throw new ResponseStatusException(404, "No such session"); + } + if ("ended".equals(session.getState())) { + throw new ResponseStatusException(409, "That session has ended"); + } + session.setState(state); + sessions.save(session); + hub.sessionChanged(session.getId(), state, community.members(session.getId())); + return community.dto(session, username); + } + + private Course own(String username, String courseId) { + Course course = courseId == null ? null : courses.findById(courseId); + if (course == null || !course.getCreator().equals(username)) { + throw new ResponseStatusException(404, "No such course"); + } + return course; + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/StudioEndpoint.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/StudioEndpoint.java new file mode 100644 index 00000000000..7b8f18b61b5 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/studio/StudioEndpoint.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.lingo.api.CourseDraftDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDraftDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.LiveDraftDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.StudioApiServer; +import com.codenameone.examples.lingo.api.StudioDto; +import com.codenameone.examples.lingo.api.UploadDto; +import com.codenameone.examples.lingo.api.UploadedDto; + +/// [com.codenameone.examples.lingo.api.StudioApi], served. The security +/// configuration lets only creators reach it. +@Component +public class StudioEndpoint implements StudioApiServer { + private final Studio studio; + + public StudioEndpoint(Studio studio) { + this.studio = studio; + } + + @Override + public StudioDto studio() throws Exception { + return studio.studio(Caller.name()); + } + + @Override + public CourseDto createCourse(CourseDraftDto draft) throws Exception { + return studio.createCourse(Caller.name(), draft); + } + + @Override + public LessonDto addLesson(String id, LessonDraftDto draft) throws Exception { + return studio.addLesson(Caller.name(), id, draft); + } + + @Override + public CourseDto publish(String id) throws Exception { + return studio.publish(Caller.name(), id); + } + + @Override + public UploadedDto upload(UploadDto upload) throws Exception { + return studio.upload(Caller.name(), upload); + } + + @Override + public LiveSessionDto schedule(LiveDraftDto draft) throws Exception { + return studio.schedule(Caller.name(), draft); + } + + @Override + public LiveSessionDto start(String id) throws Exception { + return studio.start(Caller.name(), id); + } + + @Override + public LiveSessionDto end(String id) throws Exception { + return studio.end(Caller.name(), id); + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/MediaFiles.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/MediaFiles.java new file mode 100644 index 00000000000..c04f412c9f2 --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/MediaFiles.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.web; + +import com.codename1.backend.HttpServer; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.GetMapping; +import com.codename1.backend.annotations.PathVariable; +import com.codename1.backend.annotations.RestController; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.lingo.domain.Upload; +import com.codenameone.examples.lingo.repository.UploadRepository; + +/// Recorded lessons, played straight from their address. +/// +/// Open to anyone who has the address, as a lesson's video must be: a media +/// player sends no bearer token. The address is a random 128-bit id, so it +/// is as hard to guess as a token; and it answers byte ranges, which a +/// player asks for to seek. +@RestController +public class MediaFiles { + private final UploadRepository uploads; + + public MediaFiles(UploadRepository uploads) { + this.uploads = uploads; + } + + @GetMapping("/media/{id}") + @Transactional(readOnly = true) + public HttpServer.Response media(@PathVariable("id") String id, HttpServer.Request request) { + Upload upload = id == null || id.length() > 64 ? null : uploads.findById(id); + if (upload == null) { + throw new ResponseStatusException(404, "No such recording"); + } + String tag = "\"" + id + "\""; + if (tag.equals(request.getHeader("If-None-Match"))) { + return new HttpServer.Response(304, upload.getMime(), new byte[0]).header("ETag", tag); + } + byte[] data = upload.getData(); + long[] range = range(request.getHeader("Range"), data.length); + HttpServer.Response response; + if (range == null) { + response = new HttpServer.Response(200, upload.getMime(), data); + } else if (range.length == 0) { + return new HttpServer.Response(416, "text/plain", new byte[0]) + .header("Content-Range", "bytes */" + data.length); + } else { + int from = (int) range[0]; + int to = (int) range[1]; + byte[] part = new byte[to - from + 1]; + System.arraycopy(data, from, part, 0, part.length); + response = new HttpServer.Response(206, upload.getMime(), part) + .header("Content-Range", "bytes " + from + "-" + to + "/" + data.length); + } + return response.header("ETag", tag).header("Accept-Ranges", "bytes") + .header("Cache-Control", "public, max-age=31536000, immutable") + .header("X-Content-Type-Options", "nosniff"); + } + + /// The one range of `bytes=a-b`, `bytes=a-` or `bytes=-n`: null for none + /// (or one this does not serve, such as several), and an empty array for + /// one past the end. + static long[] range(String header, int length) { + if (header == null || !header.startsWith("bytes=") || header.indexOf(',') >= 0) { + return null; + } + String spec = header.substring(6).trim(); + int dash = spec.indexOf('-'); + if (dash < 0) { + return null; + } + try { + long from; + long to; + if (dash == 0) { + long tail = Long.parseLong(spec.substring(1)); + from = Math.max(0, length - tail); + to = length - 1; + } else { + from = Long.parseLong(spec.substring(0, dash)); + to = dash == spec.length() - 1 ? length - 1 + : Math.min(length - 1, Long.parseLong(spec.substring(dash + 1))); + } + if (from >= length || from > to) { + return new long[0]; + } + return new long[] {from, to}; + } catch (NumberFormatException malformed) { + return null; + } + } +} diff --git a/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/VerifyPage.java b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/VerifyPage.java new file mode 100644 index 00000000000..f93abbac33a --- /dev/null +++ b/scripts/lingo/backend/src/main/java/com/codenameone/examples/lingo/web/VerifyPage.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.web; + +import com.codename1.backend.HttpServer; +import com.codename1.backend.annotations.GetMapping; +import com.codename1.backend.annotations.PathVariable; +import com.codename1.backend.annotations.RestController; +import com.codenameone.examples.lingo.api.VerificationDto; +import com.codenameone.examples.lingo.cert.Certificates; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/// The page the QR code on a certificate opens: who earned it, for what, +/// and whether the signature on the PDF the server holds is intact. +/// +/// It is a page and not the app because whoever checks a certificate -- an +/// employer, a school -- has no account and no app. +@RestController +public class VerifyPage { + private final Certificates certificates; + + public VerifyPage(Certificates certificates) { + this.certificates = certificates; + } + + @GetMapping("/verify/{id}") + public HttpServer.Response verify(@PathVariable("id") String id) throws IOException { + VerificationDto result = certificates.verify(id); + return new HttpServer.Response(result.found() ? 200 : 404, "text/html; charset=utf-8", + page(result).getBytes(StandardCharsets.UTF_8)) + .header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'") + .header("X-Content-Type-Options", "nosniff") + .header("Cache-Control", "no-store"); + } + + static String page(VerificationDto r) { + String state; + String detail; + String color; + if (!r.found()) { + state = "Not found"; + detail = "No certificate has this number. Check the address you were given."; + color = "#c5292a"; + } else if (r.valid()) { + state = "Genuine"; + detail = "The signature is intact and was made by " + escape(r.signer()) + + ". Nothing in the certificate has changed since it was issued."; + color = "#12805c"; + } else { + state = "Not valid"; + detail = "The certificate exists, but its signature does not check out."; + color = "#c5292a"; + } + StringBuilder out = new StringBuilder(); + out.append("") + .append("") + .append("Lingo certificate check
") + .append("
LINGO
") + .append("
").append(state).append("
"); + if (r.found()) { + out.append("

").append(escape(r.learnerName())).append("

") + .append("

completed ").append(escape(r.courseTitle())).append("

"); + } + out.append("

").append(detail).append("

"); + if (r.found()) { + out.append("
Issued
").append(Certificates.date(r.issuedAt())) + .append("
Number
").append(escape(r.id())) + .append("
Signature
").append(escape(r.algorithm())) + .append(r.wholeDocument() ? ", whole document" : ", partial").append("
"); + } + out.append("
"); + return out.toString(); + } + + static String escape(String text) { + if (text == null) { + return ""; + } + StringBuilder out = new StringBuilder(text.length()); + for (int iter = 0; iter < text.length(); iter++) { + char ch = text.charAt(iter); + switch (ch) { + case '<': + out.append("<"); + break; + case '>': + out.append(">"); + break; + case '&': + out.append("&"); + break; + case '"': + out.append("""); + break; + case '\'': + out.append("'"); + break; + default: + out.append(ch); + } + } + return out.toString(); + } +} diff --git a/scripts/lingo/backend/src/main/resources/db/migration/V1__accounts.sql b/scripts/lingo/backend/src/main/resources/db/migration/V1__accounts.sql new file mode 100644 index 00000000000..449a48f75e7 --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/V1__accounts.sql @@ -0,0 +1,31 @@ +-- Accounts: who someone is and what they chose. The sign-in itself (password +-- hash, roles) is the backend's own user store and makes its own tables. + +CREATE TABLE profile ( + username VARCHAR(190) NOT NULL PRIMARY KEY, + display_name VARCHAR(120) NOT NULL, + phone VARCHAR(32) NOT NULL, + language VARCHAR(8) NOT NULL, + target_language VARCHAR(16) NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE preference ( + username VARCHAR(190) NOT NULL PRIMARY KEY, + theme VARCHAR(8) NOT NULL, + notify_reminders SMALLINT NOT NULL, + notify_live SMALLINT NOT NULL, + wifi_only_model SMALLINT NOT NULL, + cloud_tutor SMALLINT NOT NULL +); + +CREATE TABLE closed_account ( + username_hash VARCHAR(64) NOT NULL PRIMARY KEY, + closed_at BIGINT NOT NULL +); + +CREATE TABLE live_ticket ( + ticket_hash VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + expires_at BIGINT NOT NULL +); diff --git a/scripts/lingo/backend/src/main/resources/db/migration/V2__push.sql b/scripts/lingo/backend/src/main/resources/db/migration/V2__push.sql new file mode 100644 index 00000000000..c0bb8242479 --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/V2__push.sql @@ -0,0 +1,12 @@ +-- The devices each account receives notifications on. + +CREATE TABLE push_device ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + provider VARCHAR(16) NOT NULL, + token VARCHAR(1024) NOT NULL, + platform VARCHAR(32) NOT NULL, + updated_at BIGINT NOT NULL +); + +CREATE INDEX push_device_username ON push_device (username); diff --git a/scripts/lingo/backend/src/main/resources/db/migration/V4__learning.sql b/scripts/lingo/backend/src/main/resources/db/migration/V4__learning.sql new file mode 100644 index 00000000000..a7e3b363a2e --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/V4__learning.sql @@ -0,0 +1,141 @@ +-- Courses, lessons, progress, badges, community and payments. + +CREATE TABLE course ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + title VARCHAR(160) NOT NULL, + language VARCHAR(16) NOT NULL, + level VARCHAR(8) NOT NULL, + summary VARCHAR(1000) NOT NULL, + kind VARCHAR(16) NOT NULL, + creator VARCHAR(190) NOT NULL, + price_cents INTEGER NOT NULL, + accent VARCHAR(16) NOT NULL, + published SMALLINT NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX course_creator ON course (creator); + +CREATE TABLE lesson ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + course_id VARCHAR(64) NOT NULL, + position INTEGER NOT NULL, + title VARCHAR(160) NOT NULL, + kind VARCHAR(16) NOT NULL, + summary VARCHAR(1000) NOT NULL, + phrases TEXT NOT NULL, + scenario VARCHAR(1000) NOT NULL, + video_url VARCHAR(500) NOT NULL, + minutes INTEGER NOT NULL, + xp INTEGER NOT NULL +); + +CREATE INDEX lesson_course ON lesson (course_id); + +CREATE TABLE enrollment ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + course_id VARCHAR(64) NOT NULL, + enrolled_at BIGINT NOT NULL, + completed_at BIGINT NOT NULL +); + +CREATE INDEX enrollment_username ON enrollment (username); + +CREATE TABLE lesson_result ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + lesson_id VARCHAR(64) NOT NULL, + course_id VARCHAR(64) NOT NULL, + best_score INTEGER NOT NULL, + attempts INTEGER NOT NULL, + completed_at BIGINT NOT NULL +); + +CREATE INDEX lesson_result_user ON lesson_result (username); + +CREATE TABLE xp_event ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + lesson_id VARCHAR(64) NOT NULL, + xp INTEGER NOT NULL, + day INTEGER NOT NULL, + seconds INTEGER NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX xp_event_day ON xp_event (day); + +CREATE INDEX xp_event_user ON xp_event (username); + +CREATE TABLE learner_stats ( + username VARCHAR(190) NOT NULL PRIMARY KEY, + xp INTEGER NOT NULL, + streak INTEGER NOT NULL, + best_streak INTEGER NOT NULL, + last_day INTEGER NOT NULL, + freezes INTEGER NOT NULL, + lessons_done INTEGER NOT NULL, + seconds INTEGER NOT NULL, + spoken INTEGER NOT NULL, + perfect INTEGER NOT NULL, + pro SMALLINT NOT NULL +); + +CREATE TABLE earned_badge ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + achievement_id VARCHAR(32) NOT NULL, + unlocked_at BIGINT NOT NULL +); + +CREATE INDEX earned_badge_username ON earned_badge (username); + +CREATE TABLE comment ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + course_id VARCHAR(64) NOT NULL, + parent_id VARCHAR(64) NOT NULL, + author VARCHAR(190) NOT NULL, + text VARCHAR(2000) NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX comment_course ON comment (course_id); + +CREATE TABLE live_session ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + title VARCHAR(160) NOT NULL, + language VARCHAR(16) NOT NULL, + level VARCHAR(8) NOT NULL, + host VARCHAR(190) NOT NULL, + starts_at BIGINT NOT NULL, + minutes INTEGER NOT NULL, + price_cents INTEGER NOT NULL, + seats INTEGER NOT NULL, + state VARCHAR(16) NOT NULL +); + +CREATE TABLE seat ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + session_id VARCHAR(64) NOT NULL, + username VARCHAR(190) NOT NULL, + joined_at BIGINT NOT NULL +); + +CREATE INDEX seat_session ON seat (session_id); + +CREATE TABLE receipt ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + kind VARCHAR(16) NOT NULL, + target_id VARCHAR(64) NOT NULL, + description VARCHAR(200) NOT NULL, + amount_cents INTEGER NOT NULL, + creator VARCHAR(190) NOT NULL, + creator_share_cents INTEGER NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX receipt_username ON receipt (username); + +CREATE INDEX receipt_creator ON receipt (creator); diff --git a/scripts/lingo/backend/src/main/resources/db/migration/mysql/V3__collation.sql b/scripts/lingo/backend/src/main/resources/db/migration/mysql/V3__collation.sql new file mode 100644 index 00000000000..cd9ba4dbdef --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/mysql/V3__collation.sql @@ -0,0 +1,24 @@ +-- Makes this database's text case sensitive and NO PAD: the tables the +-- earlier scripts created, and the default every later table inherits. +-- +-- The ORM needs that of a text key: "A" and "a" are two keys, and "token " +-- keeps its trailing space -- what SQLite and PostgreSQL do. MySQL's default, +-- utf8mb4_0900_ai_ci, folds both away, and the server refuses to start on a +-- key column that uses it. +-- +-- The latest version, not the first: a database that already ran the earlier +-- scripts takes a new one only when it sorts after them, and its tables are +-- already there to convert. On a new database this runs after them too, and +-- converts the tables they have just created. +-- +-- MySQL and MariaDB share no name for that collation (utf8mb4_bin, which both +-- have, pads), and this directory serves both. The comments are executable +-- ones, each read by one family only: MySQL runs /*!80000 ...*/ and skips the +-- MariaDB-only /*M! ...*/; MariaDB runs /*M!100400 ...*/ and skips MySQL's 8.0 +-- comments. +ALTER DATABASE CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE closed_account CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE live_ticket CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE preference CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE profile CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE push_device CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; diff --git a/scripts/lingo/backend/src/main/resources/db/migration/mysql/V5__files.sql b/scripts/lingo/backend/src/main/resources/db/migration/mysql/V5__files.sql new file mode 100644 index 00000000000..3040cee07dd --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/mysql/V5__files.sql @@ -0,0 +1,30 @@ +-- The tables that hold files, whose byte type each engine spells its own way. + +CREATE TABLE certificate ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + course_id VARCHAR(64) NOT NULL, + learner_name VARCHAR(120) NOT NULL, + course_title VARCHAR(160) NOT NULL, + language VARCHAR(16) NOT NULL, + issued_at BIGINT NOT NULL, + minutes INTEGER NOT NULL, + pdf LONGBLOB NOT NULL +); + +CREATE INDEX certificate_username ON certificate (username); + +CREATE TABLE upload ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + mime VARCHAR(64) NOT NULL, + data LONGBLOB NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE signing_key ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + private_key LONGBLOB NOT NULL, + certificate LONGBLOB NOT NULL, + created_at BIGINT NOT NULL +); diff --git a/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V3__collation.sql b/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V3__collation.sql new file mode 100644 index 00000000000..7e2772a4d7d --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V3__collation.sql @@ -0,0 +1,4 @@ +-- Nothing to do here: this engine's text is already case sensitive and NO +-- PAD. The version exists for mysql/V3__collation.sql, and every version +-- needs a script for each engine the server runs on. +SELECT 1; diff --git a/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V5__files.sql b/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V5__files.sql new file mode 100644 index 00000000000..ec6f05152bb --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/postgresql/V5__files.sql @@ -0,0 +1,30 @@ +-- The tables that hold files, whose byte type each engine spells its own way. + +CREATE TABLE certificate ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + course_id VARCHAR(64) NOT NULL, + learner_name VARCHAR(120) NOT NULL, + course_title VARCHAR(160) NOT NULL, + language VARCHAR(16) NOT NULL, + issued_at BIGINT NOT NULL, + minutes INTEGER NOT NULL, + pdf BYTEA NOT NULL +); + +CREATE INDEX certificate_username ON certificate (username); + +CREATE TABLE upload ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + mime VARCHAR(64) NOT NULL, + data BYTEA NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE signing_key ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + private_key BYTEA NOT NULL, + certificate BYTEA NOT NULL, + created_at BIGINT NOT NULL +); diff --git a/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V3__collation.sql b/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V3__collation.sql new file mode 100644 index 00000000000..7e2772a4d7d --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V3__collation.sql @@ -0,0 +1,4 @@ +-- Nothing to do here: this engine's text is already case sensitive and NO +-- PAD. The version exists for mysql/V3__collation.sql, and every version +-- needs a script for each engine the server runs on. +SELECT 1; diff --git a/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V5__files.sql b/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V5__files.sql new file mode 100644 index 00000000000..682390d5801 --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/db/migration/sqlite/V5__files.sql @@ -0,0 +1,30 @@ +-- The tables that hold files, whose byte type each engine spells its own way. + +CREATE TABLE certificate ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + course_id VARCHAR(64) NOT NULL, + learner_name VARCHAR(120) NOT NULL, + course_title VARCHAR(160) NOT NULL, + language VARCHAR(16) NOT NULL, + issued_at BIGINT NOT NULL, + minutes INTEGER NOT NULL, + pdf BLOB NOT NULL +); + +CREATE INDEX certificate_username ON certificate (username); + +CREATE TABLE upload ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + mime VARCHAR(64) NOT NULL, + data BLOB NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE signing_key ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + private_key BLOB NOT NULL, + certificate BLOB NOT NULL, + created_at BIGINT NOT NULL +); diff --git a/scripts/lingo/backend/src/main/resources/seed/courses.json b/scripts/lingo/backend/src/main/resources/seed/courses.json new file mode 100644 index 00000000000..fadf6b878a3 --- /dev/null +++ b/scripts/lingo/backend/src/main/resources/seed/courses.json @@ -0,0 +1,126 @@ +{ + "courses": [ + { + "id": "spanish-travel", "title": "Spanish for Travellers", "language": "es-ES", "level": "A1", + "accent": "coral", "community": false, "price": 0, + "summary": "Greet people, order at a café, find your way and check in: the Spanish a first trip needs, said out loud from day one.", + "lessons": [ + {"title": "Hello and goodbye", "kind": "phrases", "minutes": 4, + "summary": "The five phrases you will use within an hour of landing.", + "phrases": [ + ["Hola, ¿qué tal?", "Hi, how are you?", "The h is silent: OH-la."], + ["Buenos días", "Good morning", "Run the words together: bwe-nos-DEE-as."], + ["Me llamo Ana", "My name is Ana", "ll sounds like the y in yes."], + ["Mucho gusto", "Nice to meet you", "Stress the first syllable of each word."], + ["Hasta luego", "See you later", "Silent h again: AS-ta LWE-go."]]}, + {"title": "At the café", "kind": "phrases", "minutes": 5, + "summary": "Order, ask the price and pay.", + "phrases": [ + ["Un café con leche, por favor", "A coffee with milk, please", "Keep the e in leche short and crisp."], + ["¿Cuánto cuesta?", "How much is it?", "Both words stress the first syllable."], + ["¿Tienen agua sin gas?", "Do you have still water?", "The g in agua is soft, almost a breath."], + ["La cuenta, por favor", "The bill, please", "Nobody brings it until you ask."], + ["Muchas gracias", "Thank you very much", "Tap the r in gracias once."]]}, + {"title": "Getting around", "kind": "phrases", "minutes": 5, + "summary": "Stations, tickets and directions.", + "phrases": [ + ["¿Dónde está la estación?", "Where is the station?", "Stress the last syllable: es-ta-SYON."], + ["Un billete para Madrid", "A ticket to Madrid", "The d at the end of Madrid is barely there."], + ["¿A qué hora sale el tren?", "What time does the train leave?", "Trill the r of tren lightly."], + ["Todo recto y a la derecha", "Straight on and to the right", "The r of recto is trilled: it starts the word."], + ["Está muy cerca", "It is very close", "In Spain the c of cerca is a soft th."]]}, + {"title": "Ordering tapas", "kind": "conversation", "minutes": 6, + "summary": "Talk your way through lunch with the tutor as your waiter.", + "scenario": "You are a friendly waiter at a tapas bar in Seville. Greet the learner, suggest two tapas and take their order and drink."}, + {"title": "Checking in", "kind": "conversation", "minutes": 6, + "summary": "A hotel receptionist needs your name, your booking and your passport.", + "scenario": "You are a hotel receptionist in Madrid. Check the learner in: ask their name, how many nights, and for their passport, then give them the room number."} + ] + }, + { + "id": "french-essentials", "title": "French Essentials", "language": "fr-FR", "level": "A1", + "accent": "teal", "community": false, "price": 0, + "summary": "Bonjour to the boulangerie: the sounds of French that trip up beginners, and the phrases that get you through a day in Paris.", + "lessons": [ + {"title": "Bonjour!", "kind": "phrases", "minutes": 4, + "summary": "Greetings, and the nasal vowels that make French sound French.", + "phrases": [ + ["Bonjour, madame", "Hello, madam", "The on is nasal: don't say the n."], + ["Comment allez-vous ?", "How are you?", "Link the t to allez: co-man-ta-lay-voo."], + ["Je m'appelle Paul", "My name is Paul", "Swallow the e of je."], + ["Enchanté", "Delighted to meet you", "Two nasal vowels: an and an."], + ["Au revoir", "Goodbye", "The r is made at the back of the throat."]]}, + {"title": "At the boulangerie", "kind": "phrases", "minutes": 5, + "summary": "Bread, pastries and paying.", + "phrases": [ + ["Une baguette, s'il vous plaît", "A baguette, please", "Round your lips for the u of une."], + ["Deux croissants", "Two croissants", "The x and the t are silent."], + ["C'est combien ?", "How much is it?", "Combien ends in a nasal, not an n."], + ["Je voudrais un pain au chocolat", "I would like a chocolate croissant", "Voudrais ends with an open e."], + ["Merci, bonne journée", "Thanks, have a good day", "Journée: the j is soft, like the s in measure."]]}, + {"title": "Finding your way", "kind": "phrases", "minutes": 5, + "summary": "The metro, streets and turns.", + "phrases": [ + ["Où est le métro ?", "Where is the metro?", "Où sounds like oo, with no w."], + ["C'est à gauche", "It's on the left", "Gauche rhymes with 'go-sh'."], + ["Tout droit", "Straight ahead", "Droit: drwah, with the throat r."], + ["C'est loin d'ici ?", "Is it far from here?", "Loin is a nasal: lwan, without the n."]]}, + {"title": "A coffee in Paris", "kind": "conversation", "minutes": 6, + "summary": "Small talk with the tutor at a café terrace.", + "scenario": "You are a talkative regular at a Paris café terrace. Strike up small talk with the learner: where they are from, what they are visiting, and recommend a museum."} + ] + }, + { + "id": "spanish-conversation", "title": "Spanish Conversation Lab", "language": "es-ES", "level": "B1", + "accent": "indigo", "community": false, "price": 0, + "summary": "Real conversations with the AI tutor, who corrects you as you go. No scripts: say what you would really say.", + "lessons": [ + {"title": "Weekend plans", "kind": "conversation", "minutes": 8, + "summary": "Make plans with a friend and agree on a time.", + "scenario": "You are the learner's friend in Valencia. Make plans for Saturday together: suggest the beach or a paella, and agree on a time and place."}, + {"title": "At the doctor", "kind": "conversation", "minutes": 8, + "summary": "Describe how you feel and understand the advice.", + "scenario": "You are a doctor at a clinic in Barcelona. Ask the learner what is wrong, since when, and give simple advice."}, + {"title": "A job interview", "kind": "conversation", "minutes": 10, + "summary": "Talk about your experience and ask about the role.", + "scenario": "You are interviewing the learner for a job at a hotel in Málaga. Ask about their experience, languages and availability, and invite their questions."} + ] + }, + { + "id": "rolling-r", "title": "Sounds of Spanish: Rolling your R", "language": "es-ES", "level": "A2", + "accent": "rose", "community": true, "price": 499, + "summary": "A recorded masterclass on the two Spanish Rs, then drills Lingo scores as you speak. By a teacher with twelve years in Madrid classrooms.", + "lessons": [ + {"title": "Watch: tap and trill", "kind": "video", "minutes": 3, "video": "the-spanish-r.mp4", + "summary": "How the tongue makes each R, slide by slide."}, + {"title": "Pero or perro?", "kind": "phrases", "minutes": 5, + "summary": "Minimal pairs: one tap or a trill changes the word.", + "phrases": [ + ["pero", "but", "One tap."], + ["perro", "dog", "A trill: three or four taps."], + ["caro", "expensive", "One tap."], + ["carro", "cart", "Trilled."], + ["Tres tristes tigres", "Three sad tigers", "Slowly first, then faster."]]}, + {"title": "R in conversation", "kind": "conversation", "minutes": 6, + "summary": "Use every R you have learned with the tutor.", + "scenario": "You run a small pet shop in Madrid. Chat with the learner about a dog (perro) they want, its colour (rojo, marrón) and its price (caro o barato). Use many words with r and rr."} + ] + }, + { + "id": "madrid-cafe", "title": "Café Culture in Madrid", "language": "es-ES", "level": "A2", + "accent": "amber", "community": true, "price": 0, + "summary": "What Madrileños order, when, and how: a short recorded lesson and the phrases to go with it.", + "lessons": [ + {"title": "Watch: ordering like a local", "kind": "video", "minutes": 3, "video": "madrid-cafe.mp4", + "summary": "A slide-by-slide guide to the Madrid café."}, + {"title": "Your breakfast order", "kind": "phrases", "minutes": 4, + "summary": "Order the classic Madrid breakfast.", + "phrases": [ + ["Un cortado, por favor", "An espresso with a drop of milk, please", "Tap the r in por."], + ["Una tostada con tomate", "Toast with tomato", "Stress the middle: tos-TA-da."], + ["¿Me pone un zumo de naranja?", "Could I have an orange juice?", "In Spain the z of zumo is a th."], + ["Para tomar aquí", "To have here", "Aquí stresses the last syllable."]]} + ] + } + ] +} diff --git a/scripts/lingo/backend/src/main/resources/seed/madrid-cafe.mp4 b/scripts/lingo/backend/src/main/resources/seed/madrid-cafe.mp4 new file mode 100644 index 00000000000..c333cf895ec Binary files /dev/null and b/scripts/lingo/backend/src/main/resources/seed/madrid-cafe.mp4 differ diff --git a/scripts/lingo/backend/src/main/resources/seed/the-spanish-r.mp4 b/scripts/lingo/backend/src/main/resources/seed/the-spanish-r.mp4 new file mode 100644 index 00000000000..4f02c0f4f3e Binary files /dev/null and b/scripts/lingo/backend/src/main/resources/seed/the-spanish-r.mp4 differ diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccessTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccessTest.java new file mode 100644 index 00000000000..dcff4c8f792 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccessTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codename1.backend.test.MockRequestBuilder; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.account.DemoAccounts; +import com.codenameone.examples.lingo.live.LiveTickets; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/// Who may call what, with tokens earned by signing in: these go through the +/// decoder and the role lookup the app's own requests go through. +@BackendTest +class AccessTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + @Autowired + private LiveTickets tickets; + + private MockRequestBuilder as(MockRequestBuilder request, String token) { + return request.header("Host", SignIn.HOST).header("Authorization", "Bearer " + token); + } + + @Test + void eachRoleReachesItsOwnPartOfTheApi() throws Exception { + String learner = SignIn.token(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + String creator = SignIn.token(mvc, DemoAccounts.CREATOR, DemoAccounts.PASSWORD); + + mvc.perform(as(get("/api/me"), learner)).andExpect(status().isOk()) + .andExpect(jsonPath("$.learner").value(true)) + .andExpect(jsonPath("$.creator").value(false)); + mvc.perform(as(get("/api/me/stats"), learner)).andExpect(status().isOk()) + .andExpect(jsonPath("$.dailyGoal").value(50)); + mvc.perform(as(get("/api/studio"), learner)).andExpect(status().isForbidden()); + + mvc.perform(as(get("/api/studio"), creator)).andExpect(status().isOk()) + .andExpect(jsonPath("$.courses.length()").value(2)) + .andExpect(jsonPath("$.sessions.length()").value(3)); + } + + @Test + void aNewAccountIsALearner() throws Exception { + String username = People.learner(accounts, "newcomer"); + String token = SignIn.token(mvc, username, People.PASSWORD); + mvc.perform(as(get("/api/courses"), token)).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value("spanish-travel")); + mvc.perform(as(get("/api/studio"), token)).andExpect(status().isForbidden()); + } + + @Test + void certificatesAreCheckedWithoutSigningIn() throws Exception { + mvc.perform(get("/api/verify/nonexistent")).andExpect(status().isOk()) + .andExpect(jsonPath("$.found").value(false)); + mvc.perform(get("/api/courses")).andExpect(status().isUnauthorized()); + } + + @Test + void aLiveTicketIsGoodOnce() throws Exception { + String learner = SignIn.token(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + mvc.perform(post("/api/live/ticket")).andExpect(status().isUnauthorized()); + String body = mvc.perform(as(post("/api/live/ticket"), learner)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.expiresInSeconds").value(30)) + .andReturn().getResponse().getContentAsString(); + String ticket = (String) com.codename1.backend.Json.parseObject(body).get("ticket"); + assertEquals(DemoAccounts.LEARNER, tickets.redeem(ticket)); + assertNull(tickets.redeem(ticket)); + assertNull(tickets.redeem("not-a-ticket")); + } + + @Test + void onlyAnAdminMakesACreator() throws Exception { + String username = People.learner(accounts, "teacher"); + String learner = SignIn.token(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + String creator = SignIn.token(mvc, DemoAccounts.CREATOR, DemoAccounts.PASSWORD); + String admin = SignIn.token(mvc, DemoAccounts.ADMIN, DemoAccounts.PASSWORD); + String change = "{\"username\":\"" + username + + "\",\"learner\":true,\"creator\":true,\"admin\":false,\"suspended\":false}"; + + mvc.perform(as(get("/api/admin/accounts"), learner)).andExpect(status().isForbidden()); + mvc.perform(Http.body(as(post("/api/admin/accounts"), creator), change)) + .andExpect(status().isForbidden()); + + mvc.perform(as(get("/api/admin/accounts"), admin)).andExpect(status().isOk()); + mvc.perform(Http.body(as(post("/api/admin/accounts"), admin), change)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.creator").value(true)) + .andExpect(jsonPath("$.learner").value(true)); + String teacher = SignIn.token(mvc, username, People.PASSWORD); + mvc.perform(as(get("/api/studio"), teacher)).andExpect(status().isOk()); + + // An admin cannot take away their own admin role. + mvc.perform(Http.body(as(post("/api/admin/accounts"), admin), "{\"username\":\"" + + DemoAccounts.ADMIN + "\",\"learner\":false,\"creator\":true," + + "\"admin\":false,\"suspended\":false}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccountTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccountTest.java new file mode 100644 index 00000000000..f8953738985 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/AccountTest.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.DataSource; +import com.codename1.backend.Json; +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.lingo.account.DemoAccounts; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/// Opening an account, and signing in to it, through +/// the same requests the app makes. +@BackendTest +class AccountTest { + @Autowired + private MockMvc mvc; + @Autowired + private DataSource db; + + private static String registration(String email, String password, boolean ignored) { + return "{\"email\":\"" + email + "\",\"password\":\"" + password + + "\",\"displayName\":\"Test Person\",\"phone\":\"+1 (555) 010-9999\"}"; + } + + private String bearer(String username, String password) throws Exception { + return "Bearer " + SignIn.token(mvc, username, password); + } + + @Test + void anAccountIsOpenedThenSignedInTo() throws Exception { + mvc.perform(post("/api/account/register").contentType("application/json") + .content(registration("New.Tech@Example.com", "a-long-password", false))) + .andExpect(status().isOk()) + // The name is the address in lower case, and the phone number is + // stored in one form however it was typed. + .andExpect(jsonPath("$.username").value("new.tech@example.com")) + .andExpect(jsonPath("$.phone").value("+15550109999")) + // A new account is a learner on the crew, and no more. + .andExpect(jsonPath("$.learner").value(true)) + .andExpect(jsonPath("$.creator").value(false)) + .andExpect(jsonPath("$.admin").value(false)); + + // Signing in is not case sensitive about the address either. + mvc.perform(get("/api/me").header("Host", SignIn.HOST).header("Authorization", + bearer("NEW.TECH@example.com", "a-long-password"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("new.tech@example.com")) + .andExpect(jsonPath("$.displayName").value("Test Person")); + } + + @Test + void anAccountThatCannotBeOpenedSaysWhy() throws Exception { + mvc.perform(post("/api/account/register").contentType("application/json") + .content(registration("short@example.com", "short", false))) + .andExpect(status().isBadRequest()); + mvc.perform(post("/api/account/register").contentType("application/json") + .content(registration("not-an-address", "a-long-password", false))) + .andExpect(status().isBadRequest()); + mvc.perform(post("/api/account/register").contentType("application/json") + .content(registration(DemoAccounts.LEARNER, "a-long-password", false))) + .andExpect(status().isConflict()); + } + + @Test + void aWrongPasswordSignsNobodyIn() throws Exception { + assertNull(SignIn.session(mvc, DemoAccounts.LEARNER, "not-the-password")); + assertNotNull(SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD)); + } + + @Test + void theApiWantsAToken() throws Exception { + mvc.perform(get("/api/me")).andExpect(status().isUnauthorized()); + mvc.perform(get("/api/me").header("Authorization", "Bearer not-a-token")) + .andExpect(status().isUnauthorized()); + // A session is for signing in. It is not a way into the API. + mvc.perform(get("/api/me").cookie("CN1SESSION", + SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD))) + .andExpect(status().isUnauthorized()); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/CommunityTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/CommunityTest.java new file mode 100644 index 00000000000..612bf527ae3 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/CommunityTest.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Base64; +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.account.DemoAccounts; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertTrue; + + +/// Paying creators: courses, seats, Pro and tips; questions and answers; +/// and the studio where a creator writes, records and hosts. +@BackendTest +class CommunityTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + @Test + void aPaidCourseIsBoughtOnceAndTheCreatorEarnsTheirShare() throws Exception { + String who = People.learner(accounts, "buyer"); + mvc.perform(People.asLearner(post("/api/courses/rolling-r/enroll"), who)) + .andExpect(status().is(402)); + String buy = "{\"kind\":\"course\",\"targetId\":\"rolling-r\",\"amountCents\":499," + + "\"method\":\"card\"}"; + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), + buy.replace("card", "declined")), who)).andExpect(status().is(402)); + Map before = Http.json(mvc, People.asCreator(get("/api/studio"), DemoAccounts.CREATOR)); + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), buy), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.amountCents").value(499)) + .andExpect(jsonPath("$.creatorShareCents").value(349)); + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), buy), who)) + .andExpect(status().isConflict()); + mvc.perform(People.asLearner(post("/api/courses/rolling-r/enroll"), who)) + .andExpect(status().isOk()); + Map after = Http.json(mvc, People.asCreator(get("/api/studio"), DemoAccounts.CREATOR)); + assertEquals(Http.number(before, "earningsCents") + 349, + Http.number(after, "earningsCents")); + + // A tip goes to the creator whole, and earns the patron badge. + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), + "{\"kind\":\"tip\",\"targetId\":\"madrid-cafe\",\"amountCents\":300," + + "\"method\":\"card\"}"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.creatorShareCents").value(300)); + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), + "{\"kind\":\"tip\",\"targetId\":\"spanish-travel\",\"amountCents\":300," + + "\"method\":\"card\"}"), who)).andExpect(status().isBadRequest()); + Map wallet = Http.json(mvc, People.asLearner(get("/api/wallet"), who)); + assertEquals(2, ((List) wallet.get("receipts")).size()); + List badges = Http.list(mvc, People.asLearner(get("/api/achievements"), who)); + boolean patron = false; + for (Object b : badges) { + patron |= "patron".equals(((Map) b).get("id")) && Boolean.TRUE.equals(((Map) b).get("unlocked")); + } + assertTrue(patron); + } + + @Test + void questionsAreAnsweredOneLevelDeep() throws Exception { + String who = People.learner(accounts, "asker"); + Map q = Http.json(mvc, People.asLearner(Http.body( + post("/api/courses/madrid-cafe/comments"), + "{\"text\":\"Is a cortado stronger than a latte?\"}"), who)); + Map a = Http.json(mvc, People.asCreator(Http.body( + post("/api/courses/madrid-cafe/comments"), + "{\"text\":\"Yes, much less milk.\",\"parentId\":\"" + q.get("id") + "\"}"), + DemoAccounts.CREATOR)); + assertEquals(Boolean.TRUE, a.get("creator")); + // A reply to the answer joins the same thread, under the question. + mvc.perform(People.asLearner(Http.body(post("/api/courses/madrid-cafe/comments"), + "{\"text\":\"Thanks!\",\"parentId\":\"" + a.get("id") + "\"}"), who)) + .andExpect(jsonPath("$.parentId").value((String) q.get("id"))); + mvc.perform(People.asLearner(Http.body(post("/api/courses/madrid-cafe/comments"), + "{\"text\":\"Hm\",\"parentId\":\"nonexistent\"}"), who)) + .andExpect(status().isNotFound()); + mvc.perform(People.asLearner(Http.body(post("/api/courses/madrid-cafe/comments"), + "{\"text\":\"\"}"), who)).andExpect(status().isBadRequest()); + List thread = Http.list(mvc, People.asLearner(get("/api/courses/madrid-cafe/comments"), + who)); + assertTrue(thread.size() >= 2); + } + + @Test + void aCreatorWritesRecordsPublishesAndHosts() throws Exception { + // A creator of its own: the demo creator's studio is what other + // tests count. + String creator = People.learner(accounts, "author"); + Map course = Http.json(mvc, People.asCreator(Http.body(post("/api/studio/courses"), + "{\"title\":\"Italian for food lovers\",\"language\":\"it-IT\",\"level\":\"A1\"," + + "\"summary\":\"Menus and markets\",\"priceCents\":0,\"accent\":\"teal\"}"), + creator)); + String id = (String) course.get("id"); + mvc.perform(People.asCreator(post("/api/studio/courses/" + id + "/publish"), creator)) + .andExpect(status().isConflict()); + + byte[] clip = {0, 0, 0, 24, 'f', 't', 'y', 'p', 'm', 'p', '4', '2'}; + Map uploaded = Http.json(mvc, People.asCreator(Http.body(post("/api/studio/uploads"), + "{\"name\":\"intro.mp4\",\"mime\":\"video/mp4\",\"data\":\"" + + Base64.encode(clip) + "\"}"), creator)); + String url = (String) uploaded.get("url"); + assertTrue(url.startsWith("/media/")); + mvc.perform(People.asCreator(Http.body(post("/api/studio/uploads"), + "{\"name\":\"x.exe\",\"mime\":\"application/octet-stream\",\"data\":\"AA==\"}"), + creator)).andExpect(status().isUnsupportedMediaType()); + // The recording plays from its address, a range at a time. + mvc.perform(get(url).header("Range", "bytes=4-7")).andExpect(status().isPartialContent()) + .andExpect(com.codename1.backend.test.MockMvcResultMatchers.header() + .string("Content-Range", "bytes 4-7/12")); + + mvc.perform(People.asCreator(Http.body(post("/api/studio/courses/" + id + "/lessons"), + "{\"title\":\"Welcome\",\"kind\":\"video\",\"videoUrl\":\"" + url + + "\",\"minutes\":2}"), creator)).andExpect(status().isOk()) + .andExpect(jsonPath("$.position").value(1)); + mvc.perform(People.asCreator(Http.body(post("/api/studio/courses/" + id + "/lessons"), + "{\"title\":\"Ordering\",\"kind\":\"phrases\",\"minutes\":3,\"phrases\":" + + "[{\"text\":\"Un caffe, per favore\",\"translation\":\"A coffee, please\"," + + "\"hint\":\"\"}]}"), creator)).andExpect(status().isOk()) + .andExpect(jsonPath("$.position").value(2)); + mvc.perform(People.asCreator(post("/api/studio/courses/" + id + "/publish"), creator)) + .andExpect(jsonPath("$.published").value(true)); + // Somebody else's course is not theirs to change. + String rival = People.learner(accounts, "rival"); + mvc.perform(People.asCreator(post("/api/studio/courses/" + id + "/publish"), rival)) + .andExpect(status().isNotFound()); + + Map live = Http.json(mvc, People.asCreator(Http.body(post("/api/studio/live"), + "{\"title\":\"Market words\",\"language\":\"it-IT\",\"level\":\"A1\"," + + "\"startsAt\":0,\"minutes\":30,\"priceCents\":0,\"seats\":3}"), creator)); + String session = (String) live.get("id"); + String learner = People.learner(accounts, "attendee"); + mvc.perform(People.asLearner(post("/api/live/" + session + "/join"), learner)) + .andExpect(status().isOk()).andExpect(jsonPath("$.joined").value(true)); + mvc.perform(People.asCreator(post("/api/studio/live/" + session + "/start"), creator)) + .andExpect(jsonPath("$.state").value("live")); + mvc.perform(People.asCreator(post("/api/studio/live/" + session + "/end"), creator)) + .andExpect(jsonPath("$.state").value("ended")); + mvc.perform(People.asLearner(post("/api/live/" + session + "/join"), + People.learner(accounts, "late"))).andExpect(status().isConflict()); + } + + @Test + void aPaidSeatMustBeBought() throws Exception { + List sessions = Http.list(mvc, People.asLearner(get("/api/live"), DemoAccounts.LEARNER)); + String paid = null; + for (Object s : sessions) { + if (Http.number((Map) s, "priceCents") > 0) { + paid = (String) ((Map) s).get("id"); + } + } + String who = People.learner(accounts, "seatless"); + mvc.perform(People.asLearner(post("/api/live/" + paid + "/join"), who)) + .andExpect(status().is(402)); + long price = 0; + for (Object s : sessions) { + if (paid.equals(((Map) s).get("id"))) { + price = Http.number((Map) s, "priceCents"); + } + } + mvc.perform(People.asLearner(Http.body(post("/api/purchases"), + "{\"kind\":\"live\",\"targetId\":\"" + paid + "\",\"amountCents\":" + + price + ",\"method\":\"card\"}"), who)) + .andExpect(status().isOk()); + mvc.perform(People.asLearner(post("/api/live/" + paid + "/join"), who)) + .andExpect(status().isOk()); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/Http.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/Http.java new file mode 100644 index 00000000000..13c7cf40ada --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/Http.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Json; +import com.codename1.backend.test.MockMvc; +import com.codename1.backend.test.MockRequestBuilder; + +import java.util.List; +import java.util.Map; + +import static com.codename1.backend.test.MockMvcResultMatchers.status; + +/// The plumbing of a request: a JSON body on the way in, and the object, the +/// list or the status on the way out. +final class Http { + private Http() { + } + + static MockRequestBuilder body(MockRequestBuilder request, String json) { + return request.contentType("application/json").content(json); + } + + /// The object a request that succeeds answers with. + static Map json(MockMvc mvc, MockRequestBuilder request) throws Exception { + return Json.parseObject(mvc.perform(request).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString()); + } + + /// The list a request that succeeds answers with. + static List list(MockMvc mvc, MockRequestBuilder request) throws Exception { + return (List) Json.parse(mvc.perform(request).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString()); + } + + /// The status a request is answered with, whatever it is. + static int statusOf(MockMvc mvc, MockRequestBuilder request) throws Exception { + return mvc.perform(request).andReturn().getResponse().getStatus(); + } + + static long number(Map object, String field) { + return ((Number) object.get(field)).longValue(); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LearningTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LearningTest.java new file mode 100644 index 00000000000..a68fd848725 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LearningTest.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Base64; +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.account.DemoAccounts; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.codename1.pdf.PdfSignatureInfo; + +/// A course from joining it to its signed certificate, and the XP, streak +/// and badges earned on the way. +@BackendTest +class LearningTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + static String attempt(int score) { + return "{\"score\":" + score + ",\"seconds\":120,\"spoken\":5}"; + } + + @Test + void aCourseEndsWithASignedCertificateAnyoneCanCheck() throws Exception { + String who = People.learner(accounts, "graduate"); + // Not joined yet: no lesson counts. + mvc.perform(People.asLearner(Http.body(post("/api/lessons/french-essentials-1/attempt"), + attempt(90)), who)).andExpect(status().isConflict()); + mvc.perform(People.asLearner(post("/api/courses/french-essentials/enroll"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.enrolled").value(true)); + // Lessons open in order. + mvc.perform(People.asLearner(Http.body(post("/api/lessons/french-essentials-3/attempt"), + attempt(90)), who)).andExpect(status().isConflict()); + + Map first = Http.json(mvc, People.asLearner(Http.body( + post("/api/lessons/french-essentials-1/attempt"), attempt(100)), who)); + // The lesson's XP, five more for a perfect score, and each badge's. + List unlocked = (List) first.get("unlocked"); + long badges = 0; + for (Object badge : unlocked) { + badges += Http.number((Map) badge, "xp"); + } + assertEquals(10 + 4 * 2 + 5 + badges, Http.number(first, "xpEarned")); + assertTrue(ids(unlocked).contains("first-words"), "first lesson badge: " + unlocked); + assertTrue(ids(unlocked).contains("perfect-pitch"), "perfect score badge: " + unlocked); + assertEquals(1L, Http.number((Map) first.get("stats"), "streak")); + + // A failed try earns a little and opens nothing. + Map failed = Http.json(mvc, People.asLearner(Http.body( + post("/api/lessons/french-essentials-2/attempt"), attempt(30)), who)); + assertEquals(2L, Http.number(failed, "xpEarned")); + mvc.perform(People.asLearner(Http.body(post("/api/lessons/french-essentials-3/attempt"), + attempt(90)), who)).andExpect(status().isConflict()); + + Map last = null; + for (int lesson = 2; lesson <= 4; lesson++) { + last = Http.json(mvc, People.asLearner(Http.body( + post("/api/lessons/french-essentials-" + lesson + "/attempt"), attempt(85)), + who)); + } + assertEquals(Boolean.TRUE, last.get("courseCompleted")); + assertTrue(ids((List) last.get("unlocked")).contains("graduate")); + String id = (String) last.get("certificateId"); + assertFalse(id == null || id.length() == 0); + + mvc.perform(People.asLearner(get("/api/certificates"), who)) + .andExpect(jsonPath("$[0].courseTitle").value("French Essentials")) + .andExpect(jsonPath("$[0].learnerName").value("graduate")); + + Map pdf = Http.json(mvc, People.asLearner(get("/api/certificates/" + id + "/pdf"), who)); + byte[] bytes = Base64.decode((String) pdf.get("pdf")); + List signatures = PdfSignatureInfo.find(bytes); + assertEquals(1, signatures.size()); + assertTrue(signatures.get(0).isDigestValid()); + assertTrue(signatures.get(0).coversWholeDocument()); + + // Anyone may check it, with no account. + mvc.perform(get("/api/verify/" + id)).andExpect(status().isOk()) + .andExpect(jsonPath("$.found").value(true)) + .andExpect(jsonPath("$.valid").value(true)) + .andExpect(jsonPath("$.courseTitle").value("French Essentials")); + String page = mvc.perform(get("/verify/" + id)).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("Genuine"), page); + + // Somebody else's certificate cannot be downloaded. + String other = People.learner(accounts, "nosy"); + mvc.perform(People.asLearner(get("/api/certificates/" + id + "/pdf"), other)) + .andExpect(status().isNotFound()); + // Completing again issues no second certificate. + Map again = Http.json(mvc, People.asLearner(Http.body( + post("/api/lessons/french-essentials-4/attempt"), attempt(95)), who)); + assertEquals(id, again.get("certificateId")); + assertEquals(1, Http.list(mvc, People.asLearner(get("/api/certificates"), who)).size()); + } + + @Test + void theLeaderboardRanksThisWeek() throws Exception { + List board = Http.list(mvc, People.asLearner(get("/api/leaderboard"), + DemoAccounts.LEARNER)); + assertTrue(board.size() >= 6, "the demo classmates are on it: " + board); + long previous = Long.MAX_VALUE; + boolean me = false; + for (Object row : board) { + Map entry = (Map) row; + assertTrue(Http.number(entry, "xp") <= previous); + previous = Http.number(entry, "xp"); + me |= Boolean.TRUE.equals(entry.get("me")); + } + assertTrue(me); + } + + @Test + void achievementsShowProgressTowardsEach() throws Exception { + List all = Http.list(mvc, People.asLearner(get("/api/achievements"), + DemoAccounts.SECOND_LEARNER)); + assertEquals(10, all.size()); + for (Object row : all) { + Map a = (Map) row; + assertTrue(Http.number(a, "progress") <= Http.number(a, "goal"), a.toString()); + } + } + + @Test + void theTutorSaysWhenNoCloudModelIsConfigured() throws Exception { + String who = People.learner(accounts, "talker"); + mvc.perform(People.asLearner(Http.body(post("/api/tutor/reply"), + "{\"language\":\"es-ES\",\"level\":\"A1\",\"scenario\":\"a cafe\"," + + "\"turns\":[{\"role\":\"user\",\"text\":\"Hola\"}]}"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.available").value(false)); + } + + static List ids(List achievements) { + List out = new java.util.ArrayList(); + for (Object a : achievements) { + out.add((String) ((Map) a).get("id")); + } + return out; + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LiveSocketTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LiveSocketTest.java new file mode 100644 index 00000000000..4b701dd6246 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/LiveSocketTest.java @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.Crypto; +import com.codename1.backend.Tcp; +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.LocalServerPort; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.account.DemoAccounts; +import com.codenameone.examples.lingo.api.LiveDraftDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.community.Community; +import com.codenameone.examples.lingo.live.LiveHub; +import com.codenameone.examples.lingo.studio.Studio; +import com.codenameone.examples.lingo.live.LiveTickets; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The live channel over a real socket: a ticket opens it once, and what the +/// server pushes arrives. +@BackendTest(webEnvironment = BackendTest.WebEnvironment.RANDOM_PORT) +class LiveSocketTest { + private static final int TEXT = 0x1; + private static final int CLOSE = 0x8; + + @LocalServerPort + private int port; + @Autowired + private LiveTickets tickets; + @Autowired + private LiveHub hub; + @Autowired + private Studio studio; + @Autowired + private Community community; + @Autowired + private Accounts accounts; + + /// The last frame read: its opcode, and its payload as text. + private int opcode; + private byte[] payload; + + @Test + void aTicketOpensTheChannelOnceAndPushesArrive() throws Exception { + String ticket = tickets.issue(DemoAccounts.LEARNER).ticket(); + Tcp tech = open("/ws/live?ticket=" + ticket); + try { + readFrame(tech); + assertEquals("{\"type\":\"ready\"}", text()); + + writeText(tech, "{\"type\":\"ping\"}"); + readFrame(tech); + assertEquals("{\"type\":\"pong\"}", text()); + + // A live tutorial they hold a seat in opens; one they do not is + // none of their business. + hub.sessionChanged("s-2", "live", java.util.Arrays.asList("other@test.example")); + hub.sessionChanged("s-1", "live", java.util.Arrays.asList(DemoAccounts.LEARNER)); + readFrame(tech); + assertEquals("{\"type\":\"session\",\"id\":\"s-1\",\"state\":\"live\"}", text()); + + // The same ticket again opens nothing. + Tcp again = open("/ws/live?ticket=" + ticket); + try { + readFrame(again); + assertEquals(CLOSE, opcode); + assertEquals(4401, closeCode()); + } finally { + again.close(); + } + + // Suspending the account closes what it has open. + hub.drop(DemoAccounts.LEARNER); + readFrame(tech); + assertEquals(CLOSE, opcode); + assertEquals(4403, closeCode()); + } finally { + tech.close(); + } + } + + @Test + void noTicketNoChannel() throws Exception { + String[] paths = {"/ws/live", "/ws/live?ticket=", "/ws/live?ticket=0123456789abcdef"}; + for (int iter = 0; iter < paths.length; iter++) { + Tcp stranger = open(paths[iter]); + try { + readFrame(stranger); + assertEquals(CLOSE, opcode, paths[iter]); + assertEquals(4401, closeCode()); + } finally { + stranger.close(); + } + } + } + + @Test + void signalingIsRelayedOnlyBetweenPeopleInALiveSession() throws Exception { + // People of its own: the demo creator's sessions are what other + // tests count. + String hostName = People.learner(accounts, "host"); + String learnerName = People.learner(accounts, "seated"); + String outsiderName = People.learner(accounts, "outsider"); + LiveSessionDto session = studio.schedule(hostName, new LiveDraftDto( + "Signal check", "es-ES", "A1", 0, 30, 0, 4)); + community.join(learnerName, session.id()); + Tcp host = open("/ws/live?ticket=" + tickets.issue(hostName).ticket()); + Tcp learner = open("/ws/live?ticket=" + tickets.issue(learnerName).ticket()); + Tcp outsider = open("/ws/live?ticket=" + tickets.issue(outsiderName).ticket()); + try { + readFrame(host); + readFrame(learner); + readFrame(outsider); + String hello = "{\"type\":\"signal\",\"room\":\"" + session.id() + + "\",\"kind\":\"hello\",\"data\":\"x\"}"; + // Not live yet: nothing is relayed, so the next frame the learner + // reads is the session opening. + writeText(host, hello); + studio.start(hostName, session.id()); + readFrame(learner); + assertTrue(text().startsWith("{\"type\":\"session\""), text()); + readFrame(host); + assertTrue(text().startsWith("{\"type\":\"session\""), text()); + + // Somebody without a seat cannot speak in the room. + writeText(outsider, hello); + writeText(host, hello); + readFrame(learner); + assertTrue(text().indexOf("\"from\":\"" + hostName + "\"") > 0, text()); + assertTrue(text().indexOf("\"host\":true") > 0, text()); + assertTrue(text().indexOf("\"kind\":\"hello\"") > 0, text()); + + // And the learner answers the host alone. + writeText(learner, hello.replace("hello", "answer")); + readFrame(host); + assertTrue(text().indexOf("\"kind\":\"answer\"") > 0, text()); + assertTrue(text().indexOf("\"host\":false") > 0, text()); + } finally { + host.close(); + learner.close(); + outsider.close(); + } + } + + private Tcp open(String target) throws IOException { + Tcp connection = Tcp.connect("127.0.0.1", port, 5000); + byte[] request = ascii("GET " + target + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" + + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"); + connection.write(request, 0, request.length); + StringBuilder head = new StringBuilder(); + // The head ends at the first empty line: CR LF CR LF. + int ending = 0; + while (head.length() < 8192 && ending < 4) { + int c = readByte(connection); + if (c < 0) { + break; + } + head.append((char) c); + ending = c == (ending % 2 == 0 ? '\r' : '\n') ? ending + 1 : (c == '\r' ? 1 : 0); + } + assertTrue(head.toString().startsWith("HTTP/1.1 101"), head.toString()); + return connection; + } + + private String text() throws IOException { + assertEquals(TEXT, opcode); + return new String(payload, "UTF-8"); + } + + private int closeCode() { + return payload.length < 2 ? -1 : ((payload[0] & 0xff) << 8) | (payload[1] & 0xff); + } + + private void readFrame(Tcp connection) throws IOException { + int first = readByte(connection); + if (first < 0) { + throw new IOException("the connection ended with no frame"); + } + opcode = first & 0xf; + int length = readByte(connection) & 0x7f; + if (length == 126) { + length = (readByte(connection) << 8) | readByte(connection); + } + payload = new byte[length]; + int got = 0; + while (got < length) { + int read = connection.read(payload, got, length - got); + if (read <= 0) { + throw new IOException("the connection ended after " + got + " of " + length); + } + got += read; + } + } + + /// A client's frames are masked; a server refuses one that is not. + private static void writeText(Tcp connection, String text) throws IOException { + byte[] body = ascii(text); + byte[] mask = Crypto.randomBytes(4); + byte[] frame = new byte[6 + body.length]; + frame[0] = (byte) (0x80 | TEXT); + frame[1] = (byte) (0x80 | body.length); + System.arraycopy(mask, 0, frame, 2, 4); + for (int iter = 0; iter < body.length; iter++) { + frame[6 + iter] = (byte) (body[iter] ^ mask[iter & 3]); + } + connection.write(frame, 0, frame.length); + } + + private static int readByte(Tcp connection) throws IOException { + byte[] one = new byte[1]; + int read = connection.read(one, 0, 1); + return read <= 0 ? -1 : one[0] & 0xff; + } + + private static byte[] ascii(String value) { + byte[] out = new byte[value.length()]; + for (int iter = 0; iter < out.length; iter++) { + out[iter] = (byte) value.charAt(iter); + } + return out; + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/People.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/People.java new file mode 100644 index 00000000000..f0776ee3654 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/People.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.test.MockRequestBuilder; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.api.RegisterDto; + +import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.jwt; + +/// The people a test needs, made fresh for it. +/// +/// Every test class shares one running server and one database, so a test that +/// borrowed a demo account would meet whatever the test before it left behind. +/// Each test that changes an account makes its own. +final class People { + static final String PASSWORD = "a-long-password"; + + private People() { + } + + /// Opens a learner's account, as the app's registration does, and + /// returns its name. + static String learner(Accounts accounts, String name) throws Exception { + RegisterDto request = new RegisterDto(name + "@test.example", PASSWORD, name, "+15550111"); + return accounts.register(request).username(); + } + + /// The request, made as a learner. The authorities are stated here and + /// not read from the account: `AccessTest` is the one that signs in for real. + static MockRequestBuilder asLearner(MockRequestBuilder request, String username) { + return request.with(jwt().subject(username).authorities("ROLE_LEARNER")); + } + + static MockRequestBuilder asCreator(MockRequestBuilder request, String username) { + return request.with(jwt().subject(username).authorities("ROLE_CREATOR")); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SettingsTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SettingsTest.java new file mode 100644 index 00000000000..a7fbf7e71b1 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SettingsTest.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.lingo.account.Accounts; +import com.codenameone.examples.lingo.account.DemoAccounts; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcRequestBuilders.put; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/// What someone changes about their own account: how the app behaves for them, +/// who they are, their password, and whether they have an account at all. +@BackendTest +class SettingsTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + @Test + void preferencesAreSavedAndReadBack() throws Exception { + String who = People.learner(accounts, "prefers"); + mvc.perform(People.asLearner(get("/api/account/preferences"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.language").value("en")) + .andExpect(jsonPath("$.theme").value("system")) + .andExpect(jsonPath("$.notifyLive").value(true)) + .andExpect(jsonPath("$.cloudTutor").value(true)); + + String wanted = "{\"language\":\"he\",\"theme\":\"dark\",\"notifyReminders\":true," + + "\"notifyLive\":false,\"wifiOnlyModel\":true,\"cloudTutor\":false}"; + mvc.perform(People.asLearner(Http.body(put("/api/account/preferences"), wanted), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.language").value("he")); + Map saved = Http.json(mvc, People.asLearner(get("/api/account/preferences"), who)); + assertEquals("dark", saved.get("theme")); + assertEquals(Boolean.FALSE, saved.get("notifyLive")); + assertEquals(Boolean.TRUE, saved.get("wifiOnlyModel")); + assertEquals(Boolean.FALSE, saved.get("cloudTutor")); + mvc.perform(People.asLearner(get("/api/me"), who)) + .andExpect(jsonPath("$.language").value("he")); + + // Each is one of the values it can take, or it is refused whole. + String[] wrong = {"{\"language\":\"xx\"}", "{\"theme\":\"neon\"}"}; + for (String w : wrong) { + assertEquals(400, Http.statusOf(mvc, People.asLearner(Http.body( + put("/api/account/preferences"), w), who)), w); + } + mvc.perform(People.asLearner(get("/api/account/preferences"), who)) + .andExpect(jsonPath("$.theme").value("dark")); + } + + @Test + void aProfileIsSavedAndReadBack() throws Exception { + String who = People.learner(accounts, "profiled"); + mvc.perform(People.asLearner(get("/api/account/profile"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value("profiled")); + mvc.perform(People.asLearner(Http.body(put("/api/account/profile"), + "{\"name\":\"Pat Profiled\",\"phone\":\"+1 555 010 3333\"}"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.displayName").value("Pat Profiled")); + mvc.perform(People.asLearner(get("/api/account/profile"), who)) + .andExpect(jsonPath("$.name").value("Pat Profiled")) + .andExpect(jsonPath("$.phone").value("+15550103333")); + // The name a certificate will carry is the new one too. + mvc.perform(People.asLearner(get("/api/me"), who)) + .andExpect(jsonPath("$.displayName").value("Pat Profiled")); + mvc.perform(People.asLearner(Http.body(put("/api/account/profile"), + "{\"name\":\"\"}"), who)) + .andExpect(status().isBadRequest()); + } + + @Test + void aPasswordIsChangedByWhoeverKnowsTheOldOne() throws Exception { + String who = People.learner(accounts, "rekeyed"); + mvc.perform(People.asLearner(Http.body(post("/api/account/password"), + "{\"current\":\"not-the-password\",\"replacement\":\"another-long-one\"}"), + who)) + .andExpect(status().isForbidden()); + mvc.perform(People.asLearner(Http.body(post("/api/account/password"), + "{\"current\":\"" + People.PASSWORD + "\",\"replacement\":\"short\"}"), who)) + .andExpect(status().isBadRequest()); + mvc.perform(People.asLearner(Http.body(post("/api/account/password"), + "{\"current\":\"" + People.PASSWORD + + "\",\"replacement\":\"another-long-one\"}"), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value(who)); + assertEquals(null, SignIn.session(mvc, who, People.PASSWORD)); + assertEquals(false, SignIn.session(mvc, who, "another-long-one") == null); + } + + @Test + void aChangedPasswordSignsTheOtherDevicesOut() throws Exception { + String who = People.learner(accounts, "two-devices"); + Map phone = SignIn.tokens(mvc, who, People.PASSWORD); + Map tablet = SignIn.tokens(mvc, who, People.PASSWORD); + + mvc.perform(Http.body(post("/api/account/password"), + "{\"current\":\"" + People.PASSWORD + + "\",\"replacement\":\"another-long-one\"}") + .header("Host", SignIn.HOST) + .header("Authorization", "Bearer " + phone.get("access_token"))) + .andExpect(status().isOk()); + + // The tablet's refresh token asked for no password, and would have + // gone on working for whoever held the tablet. + mvc.perform(SignIn.formPost("/oauth2/token", "grant_type", "refresh_token", + "refresh_token", (String) tablet.get("refresh_token"), + "client_id", SecurityConfig.CLIENT_ID).header("Host", SignIn.HOST)) + .andExpect(status().isBadRequest()); + // The device the password was changed on stays signed in. + mvc.perform(SignIn.formPost("/oauth2/token", "grant_type", "refresh_token", + "refresh_token", (String) phone.get("refresh_token"), + "client_id", SecurityConfig.CLIENT_ID).header("Host", SignIn.HOST)) + .andExpect(status().isOk()); + } + + @Test + void anAccountIsClosedForGood() throws Exception { + String who = People.learner(accounts, "leaving"); + String token = SignIn.token(mvc, who, People.PASSWORD); + String closure = "{\"password\":\"" + People.PASSWORD + "\"}"; + + // Not on the strength of a token: the password is asked for again. + mvc.perform(People.asLearner(post("/api/account/delete"), who)) + .andExpect(status().isBadRequest()); + mvc.perform(People.asLearner(Http.body(post("/api/account/delete"), "{}"), who)) + .andExpect(status().isForbidden()); + mvc.perform(People.asLearner(Http.body(post("/api/account/delete"), + "{\"password\":\"not-the-password\"}"), who)) + .andExpect(status().isForbidden()); + mvc.perform(People.asLearner(get("/api/me"), who)).andExpect(status().isOk()); + + mvc.perform(People.asLearner(Http.body(post("/api/account/delete"), closure), who)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value(who)); + mvc.perform(get("/api/me").header("Host", SignIn.HOST) + .header("Authorization", "Bearer " + token)) + .andExpect(status().isUnauthorized()); + assertEquals(null, SignIn.session(mvc, who, People.PASSWORD)); + // And the address is retired with it. + mvc.perform(post("/api/account/register").contentType("application/json") + .content("{\"email\":\"" + who + "\",\"password\":\"" + People.PASSWORD + + "\",\"displayName\":\"Somebody else\"," + + "\"phone\":\"+15550112\"}")) + .andExpect(status().isConflict()); + + // An admin's account is not closed this way. + mvc.perform(People.asLearner(Http.body(post("/api/account/delete"), + "{\"password\":\"" + DemoAccounts.PASSWORD + "\"}"), DemoAccounts.ADMIN)) + .andExpect(status().isConflict()); + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SignIn.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SignIn.java new file mode 100644 index 00000000000..99b17cef0c7 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/SignIn.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.appkit.server.security.AccountSecurity; + +import com.codename1.backend.Json; +import com.codename1.backend.security.oauth2.core.OAuth2Parameters; +import com.codename1.backend.test.MockMvc; +import com.codename1.backend.test.MockRequestBuilder; + +import java.util.Map; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; + +/// Signs a user in the way the app does, for the tests that need a real token: +/// the password for a session, the session for an authorization code, the code +/// for tokens. +final class SignIn { + /// The PKCE pair of RFC 7636's appendix B. + private static final String VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + private static final String CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; + static final String HOST = "lingo.test:8080"; + + private SignIn() { + } + + static MockRequestBuilder formPost(String path, String... pairs) { + StringBuilder body = new StringBuilder(); + for (int i = 0; i < pairs.length; i += 2) { + if (body.length() > 0) { + body.append('&'); + } + body.append(OAuth2Parameters.encode(pairs[i])).append('=') + .append(OAuth2Parameters.encode(pairs[i + 1])); + } + return post(path).contentType("application/x-www-form-urlencoded").content(body.toString()); + } + + /// The session cookie a correct password earns, or null for a wrong one. + static String session(MockMvc mvc, String username, String password) throws Exception { + return mvc.perform(formPost("/login", "username", username, "password", password) + .header("Host", HOST)) + .andReturn().getResponse().getCookie("CN1SESSION"); + } + + /// The token response for a user: `access_token`, `refresh_token` and the + /// rest. + static Map tokens(MockMvc mvc, String username, String password) throws Exception { + String session = session(mvc, username, password); + if (session == null) { + throw new IllegalStateException("could not sign in as " + username); + } + String location = mvc.perform(get("/oauth2/authorize?response_type=code&client_id=" + + SecurityConfig.CLIENT_ID + "&redirect_uri=" + + OAuth2Parameters.encode(AccountSecurity.LOOPBACK_REDIRECT) + + "&scope=openid%20profile&state=s-1&nonce=n-1&code_challenge=" + CHALLENGE + + "&code_challenge_method=S256") + .header("Host", HOST).cookie("CN1SESSION", session)) + .andReturn().getResponse().getRedirectedUrl(); + if (location == null || location.indexOf("code=") < 0) { + throw new IllegalStateException("no authorization code: " + location); + } + int at = location.indexOf("code=") + 5; + int end = location.indexOf('&', at); + String code = location.substring(at, end < 0 ? location.length() : end); + String body = mvc.perform(formPost("/oauth2/token", + "grant_type", "authorization_code", + "code", code, + "redirect_uri", AccountSecurity.LOOPBACK_REDIRECT, + "code_verifier", VERIFIER, + "client_id", SecurityConfig.CLIENT_ID).header("Host", HOST)) + .andReturn().getResponse().getContentAsString(); + return Json.parseObject(body); + } + + /// A bearer token for a user. + static String token(MockMvc mvc, String username, String password) throws Exception { + Object token = tokens(mvc, username, password).get("access_token"); + if (!(token instanceof String)) { + throw new IllegalStateException("no access token for " + username); + } + return (String) token; + } +} diff --git a/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/WebSignInTest.java b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/WebSignInTest.java new file mode 100644 index 00000000000..34ac70ddde2 --- /dev/null +++ b/scripts/lingo/backend/src/test/java/com/codenameone/examples/lingo/WebSignInTest.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.appkit.server.security.AccountSecurity; + +import com.codename1.backend.Json; +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.security.oauth2.core.OAuth2Parameters; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codename1.backend.test.MockResponse; +import com.codenameone.examples.lingo.account.DemoAccounts; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcResultMatchers.jsonPath; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Signing in from the app running in a browser, which sees only how each +/// request ended: no redirect it can stop at, and no cookie it can read. +@BackendTest +class WebSignInTest { + private static final String VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + private static final String CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; + private static final String HERE = "http://" + SignIn.HOST + AccountSecurity.WEB_REDIRECT_PATH; + + @Autowired + private MockMvc mvc; + + private String authorize(String session, String redirect) throws Exception { + return mvc.perform(get("/oauth2/authorize?response_type=code&client_id=" + + SecurityConfig.CLIENT_ID + "&redirect_uri=" + OAuth2Parameters.encode(redirect) + + "&scope=openid%20profile&state=s-web&code_challenge=" + CHALLENGE + + "&code_challenge_method=S256") + .header("Host", SignIn.HOST).cookie("CN1SESSION", session)) + .andReturn().getResponse().getRedirectedUrl(); + } + + @Test + void thePasswordIsAnsweredWithAStatus() throws Exception { + MockResponse accepted = mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST)) + .andExpect(status().isOk()).andReturn().getResponse(); + // Not a redirect: a browser would follow one and report the page at its end. + assertNull(accepted.getRedirectedUrl()); + assertNotNull(accepted.getCookie("CN1SESSION")); + + MockResponse refused = mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", "not-the-password") + .header("Host", SignIn.HOST)) + .andExpect(status().isUnauthorized()).andReturn().getResponse(); + assertNull(refused.getRedirectedUrl()); + assertNull(refused.getCookie("CN1SESSION")); + } + + @Test + void theCodeComesBackThroughThisServer() throws Exception { + String session = SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + String location = authorize(session, HERE); + assertNotNull(location); + assertTrue(location.startsWith(HERE + "?"), location); + + // What the browser does next, and what the app reads. + String answer = mvc.perform(get(location.substring(("http://" + SignIn.HOST).length())) + .header("Host", SignIn.HOST)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.state").value("s-web")) + .andReturn().getResponse().getContentAsString(); + String code = (String) Json.parseObject(answer).get("code"); + assertNotNull(code); + + Map tokens = Json.parseObject(mvc.perform(SignIn.formPost("/oauth2/token", + "grant_type", "authorization_code", + "code", code, + "redirect_uri", HERE, + "code_verifier", VERIFIER, + "client_id", SecurityConfig.CLIENT_ID).header("Host", SignIn.HOST)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString()); + String token = (String) tokens.get("access_token"); + assertNotNull(token); + mvc.perform(get("/api/me").header("Host", SignIn.HOST) + .header("Authorization", "Bearer " + token)) + .andExpect(status().isOk()); + } + + @Test + void aCodeIsNeverSentToAnotherServer() throws Exception { + String session = SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + // Same path, somebody else's server: the address has to be this one. + String elsewhere = authorize(session, "http://attacker.example" + AccountSecurity.WEB_REDIRECT_PATH); + assertTrue(elsewhere == null || elsewhere.indexOf("attacker.example") < 0, String.valueOf(elsewhere)); + String otherPath = authorize(session, "http://" + SignIn.HOST + "/somewhere/else"); + assertTrue(otherPath == null || otherPath.indexOf("code=") < 0, String.valueOf(otherPath)); + } + + @Test + void theInstalledAppStillSignsInItsOwnWay() throws Exception { + assertNotNull(SignIn.token(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD)); + } + + @Test + void theCodePageSaysWhenThereIsNoCode() throws Exception { + mvc.perform(get(AccountSecurity.WEB_REDIRECT_PATH + "?error=access_denied&state=s-web") + .header("Host", SignIn.HOST)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("access_denied")); + } + + @Test + void aSignInAnotherSiteSubmittedIsRefused() throws Exception { + MockResponse forged = mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST).header("Origin", "http://attacker.example")) + .andExpect(status().isForbidden()).andReturn().getResponse(); + assertNull(forged.getCookie("CN1SESSION")); + // A page in a sandboxed frame, or opened from a file. + mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST).header("Origin", "null")) + .andExpect(status().isForbidden()); + // The same name on another port or scheme is another site. + mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST).header("Origin", "https://" + SignIn.HOST)) + .andExpect(status().isForbidden()); + mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST).header("Origin", "http://lingo.test:9090")) + .andExpect(status().isForbidden()); + // The rest of what changes something on this chain is held to it too. + mvc.perform(SignIn.formPost("/oauth2/token", "grant_type", "authorization_code") + .header("Host", SignIn.HOST).header("Origin", "http://attacker.example")) + .andExpect(status().isForbidden()); + mvc.perform(SignIn.formPost("/logout") + .header("Host", SignIn.HOST).header("Origin", "http://attacker.example")) + .andExpect(status().isForbidden()); + } + + @Test + void aSignInFromThisServersOwnPageIsAccepted() throws Exception { + // A browser spells the host in lower case; the comparison does not care. + MockResponse own = mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST).header("Origin", "HTTP://LINGO.TEST:8080")) + .andExpect(status().isOk()).andReturn().getResponse(); + assertNotNull(own.getCookie("CN1SESSION")); + // And the installed app, which is not a browser and names no origin. + assertNotNull(SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD)); + } + + @Test + void theOriginIsHeldToTheIssuerWhenOneIsConfigured() { + assertTrue(AccountSecurity.sameOrigin("https://lingo.example", "https://lingo.example")); + assertTrue(AccountSecurity.sameOrigin("https://LINGO.example", "https://lingo.example/auth")); + assertTrue(!AccountSecurity.sameOrigin("https://lingo.example.attacker.example", + "https://lingo.example")); + assertTrue(!AccountSecurity.sameOrigin("http://lingo.example", "https://lingo.example")); + assertTrue(!AccountSecurity.sameOrigin("https://lingo.example:8443", "https://lingo.example")); + // With an issuer the address a request arrived at is never consulted. + assertEquals("https://lingo.example", AccountSecurity.here("https://lingo.example")); + // With none, and no request in hand, there is no address to accept. + assertNull(AccountSecurity.here("")); + } + + @Test + void theSessionCookieIsNotSentFromOtherSitesOrReadByScripts() throws Exception { + String header = mvc.perform(SignIn.formPost("/login", + "username", DemoAccounts.LEARNER, "password", DemoAccounts.PASSWORD) + .header("Host", SignIn.HOST)) + .andReturn().getResponse().getHeader("Set-Cookie"); + assertNotNull(header); + assertTrue(header.indexOf("HttpOnly") > 0, header); + assertTrue(header.indexOf("SameSite=Lax") > 0 || header.indexOf("SameSite=Strict") > 0, header); + } + + @Test + void theSessionEndsWhenTheAppHasItsTokens() throws Exception { + String session = SignIn.session(mvc, DemoAccounts.LEARNER, DemoAccounts.PASSWORD); + String location = authorize(session, HERE); + assertTrue(location.indexOf("code=") > 0, location); + String answer = mvc.perform(get(location.substring(("http://" + SignIn.HOST).length())) + .header("Host", SignIn.HOST)) + .andReturn().getResponse().getContentAsString(); + Map tokens = Json.parseObject(mvc.perform(SignIn.formPost("/oauth2/token", + "grant_type", "authorization_code", + "code", (String) Json.parseObject(answer).get("code"), + "redirect_uri", HERE, + "code_verifier", VERIFIER, + "client_id", SecurityConfig.CLIENT_ID).header("Host", SignIn.HOST)) + .andReturn().getResponse().getContentAsString()); + + // Asking nicely does not end it: only a POST does. + mvc.perform(get("/logout").header("Host", SignIn.HOST).cookie("CN1SESSION", session)); + assertTrue(authorize(session, HERE).indexOf("code=") > 0); + + MockResponse ended = mvc.perform(SignIn.formPost("/logout") + .header("Host", SignIn.HOST).header("Origin", "http://" + SignIn.HOST) + .cookie("CN1SESSION", session)) + .andExpect(status().isNoContent()).andReturn().getResponse(); + assertNull(ended.getRedirectedUrl()); + // The cookie earns no more codes... + String after = authorize(session, HERE); + assertTrue(after == null || after.indexOf("code=") < 0, String.valueOf(after)); + // ...and the tokens it earned are untouched. + mvc.perform(get("/api/me").header("Host", SignIn.HOST) + .header("Authorization", "Bearer " + tokens.get("access_token"))) + .andExpect(status().isOk()); + mvc.perform(SignIn.formPost("/oauth2/token", + "grant_type", "refresh_token", + "refresh_token", (String) tokens.get("refresh_token"), + "client_id", SecurityConfig.CLIENT_ID).header("Host", SignIn.HOST)) + .andExpect(status().isOk()); + } + + @Test + void theCodePageIsDataAndNothingElse() throws Exception { + MockResponse page = mvc.perform(get(AccountSecurity.WEB_REDIRECT_PATH + + "?code=%3Cscript%3Ealert(1)%3C/script%3E&state=s").header("Host", SignIn.HOST)) + .andExpect(status().isOk()).andReturn().getResponse(); + assertTrue(String.valueOf(page.getContentType()).startsWith("application/json"), + String.valueOf(page.getContentType())); + assertEquals("nosniff", page.getHeader("X-Content-Type-Options")); + assertEquals("no-store", page.getHeader("Cache-Control")); + } + + @Test + void anIssuerIsTheOnlyWebAddressWhenOneIsConfigured() { + com.codename1.backend.security.oauth2.server.authorization.RegisteredClient app = + com.codename1.backend.security.oauth2.server.authorization.RegisteredClient + .withId("lingo").clientId(SecurityConfig.CLIENT_ID) + .clientAuthenticationMethod(com.codename1.backend.security.oauth2.core + .ClientAuthenticationMethod.NONE) + .authorizationGrantType(com.codename1.backend.security.oauth2.core + .AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri(AccountSecurity.LOOPBACK_REDIRECT).build(); + java.util.Set uris = AccountSecurity.withWebRedirect(app, SecurityConfig.CLIENT_ID, "https://lingo.example") + .getRedirectUris(); + assertTrue(uris.contains("https://lingo.example/signin/code"), uris.toString()); + assertTrue(uris.contains(AccountSecurity.LOOPBACK_REDIRECT), uris.toString()); + assertEquals(2, uris.size(), uris.toString()); + // With none configured and no request in hand, nothing is added. + assertEquals(1, AccountSecurity.withWebRedirect(app, SecurityConfig.CLIENT_ID, "").getRedirectUris().size()); + } +} diff --git a/scripts/lingo/check-template.sh b/scripts/lingo/check-template.sh new file mode 100755 index 00000000000..4bad096fd7b --- /dev/null +++ b/scripts/lingo/check-template.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# +# Builds what the Initializr generates from this project. +# +# check-template.sh [work-directory] +# +# The Initializr offers this application as a template, from resources that +# scripts/sync-initializr-template.py derives from it. That the resources match +# is one question; this is the other: whether a project generated from them, +# under another name and in another package, still builds. The real generator +# makes the project, and it is then built against this checkout: +# +# the server's tests pass against the contract module +# the app builds from common, without platform modules and with them, and +# the client half of the contract is generated into it +# +# Needs this checkout's artifacts installed (core, javase, css-compiler, the +# Maven plugin, backend, backend-test), a JDK 17 or newer as JAVA_HOME, python3 +# and unzip. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/../.." && pwd)" +MVN="${MVN:-mvn}" +WORK="${1:-$HERE/target/template-check}" + +log() { echo "[lingo-template] $*" >&2; } + +python3 "$ROOT/scripts/sync-initializr-template.py" lingo + +# The version this checkout installs, which the generated poms are pointed at: +# the release the Initializr generates against does not have this project's +# build support until one that follows this change. +VERSION="$(sed -n 's:.*\(.*\).*:\1:p' "$ROOT/maven/pom.xml" | head -n 1)" +[ -n "$VERSION" ] || { log "could not read the version from maven/pom.xml"; exit 1; } + +rm -rf "$WORK" +mkdir -p "$WORK" +log "generating the Initializr's downloads" +python3 "$ROOT/scripts/tests/generate-initializr-fixtures.py" "$WORK/fixtures" > "$WORK/fixtures.log" 2>&1 \ + || { tail -n 60 "$WORK/fixtures.log" >&2; log "the generator failed"; exit 1; } + +# extract -- a generated project, pointed at this checkout's version +extract() { + local dir="$WORK/$1" + mkdir -p "$dir" + unzip -q "$WORK/fixtures/LINGO-$1-INTELLIJ.zip" -d "$dir" + python3 - "$dir/pom.xml" "$VERSION" <<'PY' +import re, sys +path, version = sys.argv[1], sys.argv[2] +text = open(path, encoding='utf-8').read() +for tag in ('cn1.plugin.version', 'cn1.version'): + text, count = re.subn(r'<%s>[^<]*' % (tag, tag), '<%s>%s' % (tag, version, tag), text) + assert count == 1, (tag, count) +open(path, 'w', encoding='utf-8').write(text) +PY + echo "$dir" +} + +# The fixtures are generated as com.example.probe.LauncherProbe. +PACKAGE=com/example/probe + +minimal="$(extract APP_WITH_BACKEND)" +log "running the generated server's tests" +(cd "$minimal" && "$MVN" -B -q -Dcodename1.platform=backend -pl shared,backend -am test) +ls "$minimal"/backend/target/surefire-reports/TEST-*.xml >/dev/null 2>&1 \ + || { log "the generated server's tests did not run"; exit 1; } +[ -f "$minimal/backend/target/generated-sources/cn1-annotations/$PACKAGE/api/LearnApiServer.java" ] \ + || { log "the server's half of the contract was not generated"; exit 1; } + +for layout in APP_WITH_BACKEND FULL; do + project="$WORK/$layout" + [ -d "$project" ] || project="$(extract "$layout")" + log "building the generated app ($layout)" + (cd "$project" && "$MVN" -B -q -Dcodename1.platform=javase -Djava.awt.headless=true -DskipTests package) + for built in "classes/theme.res" "classes/$PACKAGE/api/LearnApiImpl.class" "classes/cn1app/RestClientBootstrap.class"; do + [ -f "$project/common/target/$built" ] \ + || { log "$layout: common/target/$built was not built"; exit 1; } + done +done +log "passed" diff --git a/scripts/lingo/common/codenameone_settings.properties b/scripts/lingo/common/codenameone_settings.properties new file mode 100644 index 00000000000..2223de51ac5 --- /dev/null +++ b/scripts/lingo/common/codenameone_settings.properties @@ -0,0 +1,51 @@ +codename1.android.keystore= +codename1.android.keystoreAlias= +codename1.android.keystorePassword= +codename1.arg.and.themeMode=modern +# A server started on this machine is reached over plain HTTP, which Android +# refuses by default. Remove this once the app talks to a server with a +# certificate. +codename1.arg.android.xapplication_attr=android\:usesCleartextTraffic\="true" +codename1.arg.desktop.interactiveScrollbars=true +codename1.arg.desktop.titleBar=native +codename1.arg.ios.newStorageLocation=true +# What iOS shows before a creator records a video lesson or holds a live class. +codename1.arg.ios.NSCameraUsageDescription=The camera records your video lessons and shows you in live classes. +# What iOS shows when a creator picks a video they already recorded. +codename1.arg.ios.NSPhotoLibraryUsageDescription=Your library is where you pick a video lesson you already recorded. +# The microphone hears a learner say each phrase, and carries their voice in a live class. +codename1.arg.ios.NSMicrophoneUsageDescription=Lingo listens as you say each phrase, to score your pronunciation, and carries your voice in live classes. +# What iOS shows before speech recognition turns what was said into words to score. +codename1.arg.ios.NSSpeechRecognitionUsageDescription=Speech recognition writes down what you said, so Lingo can score each word. +# What iOS shows before Face ID unlocks the sign-in kept in secure storage. +codename1.arg.ios.NSFaceIDUsageDescription=Authenticate to securely access your account +# Push notifications. With push included the build adds the +# remote-notification background mode and the push entitlement itself. +codename1.arg.ios.includePush=true +# Android push is off until the app has its Firebase file: a build that +# uses PushClient without google-services.json stops with an error. Once +# native/android/google-services.json is in place, delete this line. +codename1.arg.android.messagingService=none +codename1.arg.ios.themeMode=modern +codename1.arg.java.version=17 +codename1.arg.nativeTheme=native +codename1.cssTheme=true +codename1.displayName=Lingo +codename1.icon=icon.png +codename1.ios.appid=Q5GHSKAL2F.com.codenameone.examples.lingo +codename1.ios.certificate= +codename1.ios.certificatePassword= +codename1.ios.debug.certificate= +codename1.ios.debug.certificatePassword= +codename1.ios.debug.provision= +codename1.ios.provision= +codename1.ios.release.certificate= +codename1.ios.release.certificatePassword= +codename1.ios.release.provision= +codename1.kotlin=false +codename1.languageLevel=5 +codename1.mainName=Lingo +codename1.packageName=com.codenameone.examples.lingo +codename1.secondaryTitle=Hello World +codename1.vendor=CodenameOne +codename1.version=1.0 diff --git a/scripts/lingo/common/icon.png b/scripts/lingo/common/icon.png new file mode 100644 index 00000000000..d41865b8830 Binary files /dev/null and b/scripts/lingo/common/icon.png differ diff --git a/scripts/lingo/common/pom.xml b/scripts/lingo/common/pom.xml new file mode 100644 index 00000000000..abb410a5ab3 --- /dev/null +++ b/scripts/lingo/common/pom.xml @@ -0,0 +1,1382 @@ + + + 4.0.0 + + com.codenameone.examples.lingo + lingo + 1.0-SNAPSHOT + + com.codenameone.examples.lingo + lingo-common + 1.0-SNAPSHOT + jar + + + + + com.codenameone + codenameone-core + provided + + + + ${project.groupId} + lingo-shared + ${project.version} + + + + com.codenameone + cn1-app-kit-lib + ${cn1.version} + pom + + + + + com.codenameone + codenameone-javase + test + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + + + + + install-codenameone + ${user.home}/.codenameone/guibuilder.jar + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + android-compat + + + ${basedir}/src/main/android + + + + + com.codenameone + codenameone-android-compat + provided + + + + + + kotlin + + + + ${basedir}/src/main/kotlin + + + + 2.2.10 + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + + org.jetbrains + annotations + 13.0 + + + com.codenameone + java-runtime + provided + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + process-resources + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + ${project.basedir}/src/main/android/kotlin + ${project.basedir}/src/main/android/java + ${project.build.directory}/generated-sources/android + + + -no-reflect + -no-jdk + + + + + test-compile + process-test-sources + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + -no-reflect + -no-jdk + + + + + + + + + + + + + javase + + + codename1.platform + javase + + + + javase + + + + + org.codehaus.mojo + exec-maven-plugin + + java + true + + -Xmx1024M + + -classpath + + ${exec.mainClass} + ${cn1.mainClass} + + + + + + + + + + cn1-javase-natives + + + ${basedir}/../javase/pom.xml + + + + + + com.codenameone + codenameone-maven-plugin + + + compile-javase-natives + process-classes + + compile-javase-natives + + + javase + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.apache.maven.surefire + surefire-junit-platform + 3.0.0-M5 + + + + ${skipTests} + + ${project.build.directory}/cn1-javase/classes + + + + + + + + + cn1-host-javase + + + codename1.platform + javase + + + ${basedir}/../javase/pom.xml + + + + javase + javase + none + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-javase + validate + + hosted-platform + + + javase + + + + build-javase + package + + build + + + javase + + + + + + + + + + cn1-host-android + + + codename1.platform + android + + + ${basedir}/../android/pom.xml + + + + android + android + android-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-android + validate + + hosted-platform + + + android + + + + build-android + package + + build + + + android + + + + + + + + + + cn1-host-ios + + + codename1.platform + ios + + + ${basedir}/../ios/pom.xml + + + + ios + ios + ios-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-ios + validate + + hosted-platform + + + ios + + + + build-ios + package + + build + + + ios + + + + + + + + + + cn1-host-javascript + + + codename1.platform + javascript + + + ${basedir}/../javascript/pom.xml + + + + javascript + javascript + local-javascript + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-javascript + validate + + hosted-platform + + + javascript + + + + build-javascript + package + + build + + + javascript + + + + + + + + + + cn1-host-win + + + codename1.platform + win + + + ${basedir}/../win/pom.xml + + + + win + win + windows-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-win + validate + + hosted-platform + + + win + + + + build-windows + package + + build + + + win + + + + + + + + + + cn1-host-linux + + + codename1.platform + linux + + + ${basedir}/../linux/pom.xml + + + + linux + linux + linux-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-linux + validate + + hosted-platform + + + linux + + + + build-linux + package + + build + + + linux + + + + + + + + + + simulator + + javase + com.codename1.impl.javase.Simulator + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + ${codename1.exec.args.debug} + ${codename1.exec.args.runjdwp.transport} + + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + idea-simulator + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator-idea + verify + + java + + + ${cn1.hosted.javase.skip} + + ${project.build.directory}/cn1-javase/classes + + + ${codename1.mainClass} + + + + codename1.css.compiler.args.input + ${codename1.css.compiler.args.input} + + + codename1.css.compiler.args.output + ${codename1.css.compiler.args.output} + + + codename1.css.compiler.args.merge + ${codename1.css.compiler.args.merge} + + + + cn1.class.path + ${cn1.class.path} + + + + + + + + + + + + debug-simulator + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xdebug + -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + debug-eclipse + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xdebug + -Xrunjdwp:transport=dt_socket,server=y,address=${jpda.address},suspend=y + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + run-desktop + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + generate-icons + generate-sources + + generate-desktop-app-wrapper + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-desktop + verify + + java + + + ${cn1.hosted.javase.skip} + ${codename1.packageName}.${codename1.mainName}Stub + + + ${project.build.directory}/cn1-javase/classes + ${project.build.directory}/cn1-javase/desktop + ${basedir}/src/desktop/resources + ${basedir}/../javase/src/desktop/resources + + + + + + + + + + + executable-jar + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + generate-icons + generate-sources + + generate-desktop-app-wrapper + + + javase + + + + javase-executable-jar + package + + javase-executable-jar + + + javase + + + + + + + + + + test + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + cn1-tests + test + + test + + + javase + + + + + + + + + + run-android + + + + com.codenameone + codenameone-maven-plugin + + + + run-android-hosted + validate + + hosted-platform + + + android + + + + + + maven-antrun-plugin + + + adb-install + verify + + run + + + ${cn1.hosted.android.skip} + + Running adb install + + + + + + Trying to start app on device using adb + + + + + + + + + + + + + + + + + + + + ios-debug + + + iphone + + + ios + + + + + ios-release + + + iphone + true + + + ios + true + + + + + javascript + + javascript + javascript + + + + + android + + android + android + + + + + win + + windows + win + + + + + windows + + desktop_windows + javase + + + + + mac + + desktop_macosx + javase + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 17 + 17 + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + + com.codenameone + codenameone-maven-plugin + + + + + transcode-svg + generate-sources + + transcode-svg + + + + + compile-android-res + generate-sources + + compile-android-res + + + + generate-gui-sources + process-sources + + generate-gui-sources + + + + cn1-process-classes + process-classes + + + remap-android + bytecode-compliance + css + + process-annotations + + + + + attach-test-artifact + test + + attach-test-artifact + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + true + + + + + + + + + + diff --git a/scripts/lingo/common/src/desktop/resources/NativeTheme.res b/scripts/lingo/common/src/desktop/resources/NativeTheme.res new file mode 100644 index 00000000000..83e067b6969 Binary files /dev/null and b/scripts/lingo/common/src/desktop/resources/NativeTheme.res differ diff --git a/scripts/lingo/common/src/main/css/theme.css b/scripts/lingo/common/src/main/css/theme.css new file mode 100644 index 00000000000..64f34b93277 --- /dev/null +++ b/scripts/lingo/common/src/main/css/theme.css @@ -0,0 +1,1788 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +/* + * The whole look of the app. + * + * COLOURS AND SHAPE -- change these and nothing else to re-skin the app. Every + * rule below takes its colours from here; none names a colour of its own. Each + * colour has a second value for dark mode, used by the block at the end of the + * file. + */ +#Constants { + includeNativeBool: true; + defaultSourceDPIInt: "0"; + /* ONE TYPE SCALE, in millimetres as a phone draws them: 2.1 caption, + 2.5 secondary, 2.75 body, 2.9 control, 3.5 heading, 4.4 title, 7 display. + A desktop draws a millimetre in far fewer pixels and is read from + further away, so every size is a quarter larger there. */ + device-desktop-font-scale: "1.25"; + /* Screens change quickly: nothing waits for an animation. */ + transitionSpeedInt: "200"; + /* The switch, sized from the Switch style's font. */ + switchThumbScaleY: "1.5"; + switchTrackScaleY: "1.8"; + switchTrackScaleX: "3.1"; + switchThumbInsetMM: "0.35"; + switchTrackOffOutlineWidthMM: "0"; + switchTrackOnOutlineWidthMM: "0"; + switchThumbWidthScale: "1.0"; + --brand: #4f46e5; + --brand-pressed: #4338ca; + --brand-contrast: #ffffff; + --surface: #ffffff; + --surface-alt: #f4f5f8; + --surface-press: #e6e9ee; + --text: #12161c; + --text-muted: #667085; + --line: #e6e8ed; + --line-strong: #cfd4dc; + --success: #12805c; + --warning: #b25e09; + --danger: #c5292a; + /* The pale ground a selected card and a badge sit on. */ + --brand-tint: #eef0ff; + --success-tint: #e4f4ed; + --warning-tint: #fcf0df; + --danger-tint: #fcebeb; + + --brand-dark: #8b8cff; + --brand-pressed-dark: #7072f0; + --brand-contrast-dark: #0b1020; + --surface-dark: #12161c; + --surface-alt-dark: #1c222b; + --surface-press-dark: #2a313c; + --text-dark: #f2f4f7; + --text-muted-dark: #98a2b3; + --line-dark: #2a313c; + --line-strong-dark: #3b4452; + --success-dark: #47c79a; + --warning-dark: #f0a24b; + --danger-dark: #ff7a7a; + --brand-tint-dark: #1f1f45; + --success-tint-dark: #15302a; + --warning-tint-dark: #33270f; + --danger-tint-dark: #3a1f22; + + /* ONE RADIUS for anything card- or button-shaped, a smaller one for what + sits inside a card, and the sheet's. */ + --radius: 2.4mm; + --radius-small: 1.5mm; + + /* What floats over the map: the shadow under it, the dimming behind an + open menu, and the corners of the sheet. */ + --shadow: #101828; + /* Under a card with square-ish corners. Black, and without a blur where it + is used: that is the one shadow a rounded rectangle draws for itself. + Any other is rendered to pictures of the card when the theme is + compiled, and a build that cannot render them has no card at all. */ + --shadow-card: rgba(0, 0, 0, 0.14); + --scrim: #000000; + --radius-sheet: 4.4mm; + /* The map's own drawings. The edge is the outline that keeps a pin and + the route readable over any tile. */ + --map-edge: #ffffff; + --map-edge-dark: #0b1020; + /* Lingo's own: the live colour of work under way, the urgent one, + and the soft background the cards float on. */ + --live: #0b8a6f; + --live-tint: #e2f6f0; + --urgent: #d6336c; + --urgent-tint: #fde8ef; + --canvas: #f2f3f7; + --live-dark: #4fd1ae; + --live-tint-dark: #0f2e28; + --urgent-dark: #ff6b9a; + --urgent-tint-dark: #3a1626; + --canvas-dark: #0c0f14; + /* Learning: gold for XP, flame for a streak, coral for live and for + the microphone while it listens. */ + --gold: #f5a524; + --gold-tint: #fff4dc; + --flame: #ff7a1a; + --flame-tint: #fff0e3; + --coral: #f0524f; + --coral-tint: #ffe9e8; + --hero-text: #ffffff; + --hero-muted: #d9dbff; + --gold-dark: #ffc24d; + --gold-tint-dark: #3a2c0c; + --flame-dark: #ff9a4d; + --flame-tint-dark: #3a230f; + --coral-dark: #ff7a77; + --coral-tint-dark: #3a1b1b; + --hero-text-dark: #ffffff; + --hero-muted-dark: #c7c9ff; + /* A course's colour, chosen by its creator. */ + --c-indigo: #5b5bd6; + --c-coral: #f0645a; + --c-teal: #0f9d8a; + --c-amber: #e29a12; + --c-rose: #d6457a; + --c-sky: #2f8fe0; +} + +/* ---------------------------------------------------------------- surfaces */ + +LnForm { + background-color: var(--surface); + padding: 0; + margin: 0; +} + +LnPage { + background-color: var(--surface); + padding: 3mm 3.6mm 4mm 3.6mm; + margin: 0; +} + +/* The coloured top of the welcome screen. */ +LnHero { + background-color: var(--brand); + /* Room for the logo, the name and three feature lines on a phone: the + old 14mm top left the last line zero pixels high. */ + padding: 8mm 4.4mm 4mm 4.4mm; + margin: 0; +} + +LnHeroTitle { + color: var(--brand-contrast); + font-family: "native:MainBold"; + font-size: 7mm; + padding: 2.4mm 0 0.8mm 0; + margin: 0; + background-color: transparent; +} + +LnHeroText { + color: var(--brand-contrast); + font-family: "native:MainRegular"; + font-size: 2.9mm; + padding: 0; + margin: 0; + background-color: transparent; +} + +LnHeroIcon { + color: var(--brand-contrast); + padding: 0; + margin: 0; + background-color: transparent; +} + +LnHeroFeature { + padding: 1.6mm 0 0 0; + margin: 0; + background-color: transparent; +} + +LnHeroFeatureIcon { + color: var(--brand-contrast); + padding: 0 2.4mm 0 0; + margin: 0; + background-color: transparent; +} + +/* The panel that rises over the map. */ +LnCard { + background-color: var(--surface); + border-radius: var(--radius-sheet) var(--radius-sheet) 0 0; + padding: 3.6mm 3.6mm 4mm 3.6mm; + margin: 0; +} + +/* A panel that floats over the map with a gap around it. */ +LnFloat { + background-color: var(--surface); + border-radius: var(--radius); + padding: 2.4mm 3.2mm 2.4mm 3.2mm; + margin: 2.4mm; +} + +LnPanel { + background-color: var(--surface-alt); + border-radius: var(--radius); + padding: 2.8mm 3mm 2.8mm 3mm; + margin: 1.2mm 0 1.2mm 0; +} + +LnDivider { + background-color: var(--line); + padding: 0; + margin: 2mm 0 2mm 0; +} + +/* -------------------------------------------------------------------- text */ + +LnTitle { + color: var(--text); + font-family: "native:MainBold"; + font-size: 4.4mm; + padding: 0.6mm 0 1mm 0; + margin: 0; + background-color: transparent; +} + +LnHeading { + color: var(--text); + font-family: "native:MainBold"; + font-size: 3.5mm; + padding: 0.4mm 0 0.4mm 0; + margin: 0; + background-color: transparent; +} + +LnText { + color: var(--text); + font-family: "native:MainRegular"; + font-size: 2.75mm; + padding: 0.4mm 0 0.4mm 0; + margin: 0; + background-color: transparent; +} + +LnMuted { + color: var(--text-muted); + font-family: "native:MainRegular"; + font-size: 2.5mm; + padding: 0.4mm 0 0.4mm 0; + margin: 0; + background-color: transparent; +} + +LnLabel { + color: var(--text-muted); + font-family: "native:MainBold"; + font-size: 2.1mm; + padding: 2.6mm 0 1mm 0.3mm; + margin: 0; + background-color: transparent; +} + +LnError { + color: var(--danger); + font-family: "native:MainRegular"; + font-size: 2.5mm; + padding: 1mm 0 1mm 0; + margin: 0; + background-color: transparent; +} + +LnNotice { + color: var(--text); + background-color: var(--surface-alt); + border-radius: var(--radius); + font-family: "native:MainRegular"; + font-size: 2.5mm; + padding: 2.4mm 3mm 2.4mm 3mm; + margin: 2mm 0 1mm 0; +} + +/* ----------------------------------------------------------------- buttons */ + +LnPrimary { + color: var(--brand-contrast); + background-color: var(--brand); + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 2.9mm; + text-align: center; + padding: 2.75mm 4mm 2.75mm 4mm; + margin: 1.6mm 0 0.8mm 0; +} + +LnPrimary.pressed { + background-color: var(--brand-pressed); +} + +LnPrimary.disabled { + color: var(--text-muted); + background-color: var(--surface-press); +} + +LnSecondary { + color: var(--text); + background-color: var(--surface-alt); + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 2.9mm; + text-align: center; + padding: 2.75mm 4mm 2.75mm 4mm; + margin: 1.6mm 0 0.8mm 0; +} + +LnSecondary.pressed { + background-color: var(--surface-press); +} + +LnDanger { + color: var(--danger); + background-color: var(--danger-tint); + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 2.9mm; + text-align: center; + padding: 2.75mm 4mm 2.75mm 4mm; + margin: 1.6mm 0 0.8mm 0; +} + +LnDanger.pressed { + background-color: var(--surface-press); +} + +LnLink { + color: var(--brand); + background-color: transparent; + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 2.75mm; + text-align: center; + padding: 2.4mm 2mm 2.4mm 2mm; + margin: 0; +} + +LnSecondary.disabled, LnDanger.disabled, LnLink.disabled { + color: var(--line-strong); +} + +LnLink.pressed { + color: var(--brand-pressed); + background-color: var(--brand-tint); +} + +/* The round buttons that sit on the map. */ +LnMapButton { + color: var(--text); + background: cn1-round-border; + background-color: var(--surface); + cn1-box-shadow-spread: 0.5mm; + cn1-box-shadow-blur: 1.6mm; + cn1-box-shadow-h: 0.5; + cn1-box-shadow-v: 0.7; + cn1-box-shadow-color: var(--shadow); + padding: 2.4mm; + margin: 1.2mm 2.4mm 1.2mm 2.4mm; +} + +LnMapButton.pressed { + background-color: var(--surface-alt); +} + +/* The same button on a bar: flat, because nothing on a bar floats. */ +LnBarButton { + color: var(--text); + background: cn1-round-border; + background-color: var(--surface); + padding: 2.4mm; + margin: 0.6mm 0.6mm 0.6mm 1.2mm; +} + +LnBarButton.pressed { + background-color: var(--surface-alt); +} + +/* "Where to?" -- looks like a field, behaves like a button. */ +LnSearchBar { + color: var(--text); + background-color: var(--surface-alt); + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 3.1mm; + text-align: left; + padding: 2.9mm 3.2mm 2.9mm 3.2mm; + margin: 0.8mm 0 0.8mm 0; +} + +LnSearchBar.pressed { + background-color: var(--surface-press); +} + +/* ------------------------------------------------------------------ fields */ + +LnField { + color: var(--text); + background-color: var(--surface-alt); + border-radius: var(--radius); + font-family: "native:MainRegular"; + font-size: 2.9mm; + padding: 2.7mm 3mm 2.7mm 3mm; + margin: 0; +} + +/* The field being typed in says so. */ +LnField.selected { + background-color: var(--brand-tint); +} + +LnField.disabled { + color: var(--text-muted); +} + +LnFieldHint { + color: var(--text-muted); + font-family: "native:MainRegular"; + font-size: 2.9mm; + padding: 2.7mm 3mm 2.7mm 3mm; + margin: 0; + background-color: transparent; +} + +/* ------------------------------------------------------------------- lists */ + +LnRow { + background-color: var(--surface); + border-bottom: 1px solid var(--line); + padding: 2.6mm 0 2.6mm 0; + margin: 0; +} + +LnRow.pressed { + background-color: var(--surface-alt); +} + +LnRowIcon { + color: var(--text-muted); + padding: 0 3mm 0 0.4mm; + margin: 0; + background-color: transparent; +} + +LnRowTitle { + color: var(--text); + font-family: "native:MainBold"; + font-size: 2.75mm; + padding: 0; + margin: 0; + background-color: transparent; +} + +LnRowDetail { + color: var(--text-muted); + font-family: "native:MainRegular"; + font-size: 2.4mm; + padding: 0.3mm 0 0 0; + margin: 0; + background-color: transparent; +} + +LnRowValue { + color: var(--text); + font-family: "native:MainBold"; + font-size: 2.75mm; + text-align: right; + padding: 0 0 0 2mm; + margin: 0; + background-color: transparent; +} + +/* ------------------------------------------------------------------ badges */ + +LnBadge { + color: var(--text-muted); + background: cn1-pill-border; + background-color: var(--surface-alt); + font-family: "native:MainBold"; + font-size: 2.05mm; + padding: 0.7mm 2mm 0.7mm 2mm; + margin: 0 0 0 2mm; +} + +LnBadgeGood { + cn1-derive: LnBadge; + color: var(--success); + background-color: var(--success-tint); +} + +LnBadgeWarn { + cn1-derive: LnBadge; + color: var(--warning); + background-color: var(--warning-tint); +} + +LnBadgeBad { + cn1-derive: LnBadge; + color: var(--danger); + background-color: var(--danger-tint); +} + +/* ------------------------------------------------------------------- admin */ + +LnStat { + background-color: var(--surface-alt); + border-radius: var(--radius); + padding: 2.6mm 2.6mm 2.6mm 2.6mm; + margin: 0.8mm; +} + +LnStatValue { + color: var(--text); + font-family: "native:MainBold"; + font-size: 3.9mm; + padding: 0; + margin: 0; + background-color: transparent; +} + +LnStatLabel { + color: var(--text-muted); + font-family: "native:MainRegular"; + font-size: 2.3mm; + padding: 0.3mm 0 0 0; + margin: 0; + background-color: transparent; +} + +/* --------------------------------------------------------------- title bar */ + +/* The strip the clock and the battery are drawn over. */ +StatusBar { + background-color: var(--surface); + padding: 0; + margin: 0; +} + +Toolbar { + background-color: var(--surface); + border-bottom: 1px solid var(--line); + padding: 0.6mm 0 0.6mm 0; + margin: 0; +} + +Title { + color: var(--text); + font-family: "native:MainBold"; + font-size: 3.05mm; + background-color: transparent; +} + +TitleCommand { + color: var(--text); + background-color: transparent; +} + +BackCommand { + color: var(--text); + background-color: transparent; +} + +LnRoute { + color: var(--brand); + background-color: var(--map-edge); +} + +/* The switch: the thumb is the colour, the track the background. */ +Switch { + color: #ffffff; + background-color: var(--line-strong); + font-family: "native:MainRegular"; + font-size: 2.5mm; + padding: 0.6mm 0 0.6mm 2mm; + margin: 0; +} + +Switch.selected { + color: #ffffff; + background-color: var(--brand); +} + +Switch.disabled { + color: var(--surface-alt); + background-color: var(--line); +} + +/* --------------------------------------------------------------------------- + * OVER THE MAP. The clear strip the status bar is drawn in, which the map + * runs under, the bar of floating controls, + * the sheet at the bottom and what goes in each. + */ +LnStatusShade { + background-color: transparent; + padding: 0; + margin: 0; +} + +LnMapBar { + background-color: transparent; + padding: 1.2mm 2.4mm 0 0; + margin: 0; +} + +/* A card that floats over the map and behaves like a button. */ +LnSearchCard { + color: var(--text); + background-color: var(--surface); + border-radius: var(--radius); + cn1-box-shadow-spread: 0.5mm; + cn1-box-shadow-blur: 0; + cn1-box-shadow-h: 0.5; + cn1-box-shadow-v: 0.7; + cn1-box-shadow-color: var(--shadow-card); + font-family: "native:MainBold"; + font-size: 3.1mm; + text-align: left; + padding: 3mm 3.2mm 3mm 3.2mm; + margin: 0.5mm 0 0.5mm 0; +} + +LnSearchCard.pressed { + background-color: var(--surface-alt); +} + +/* One short fact, in a pill under the bar. */ +LnChip { + color: var(--text); + background: cn1-pill-border; + background-color: var(--surface); + cn1-box-shadow-spread: 0.4mm; + cn1-box-shadow-blur: 1.4mm; + cn1-box-shadow-h: 0.5; + cn1-box-shadow-v: 0.7; + cn1-box-shadow-color: var(--shadow); + font-family: "native:MainBold"; + font-size: 2.4mm; + padding: 1.4mm 3mm 1.4mm 2.6mm; + margin: 1.2mm 2mm 1mm 2mm; +} + +LnSheet { + background-color: var(--surface); + border-radius: var(--radius-sheet) var(--radius-sheet) 0 0; + padding: 0.4mm 3.6mm 3.2mm 3.6mm; + margin: 0; +} + +/* The handle of the sheet: the colour is the bar's. */ +LnGrip { + color: var(--line-strong); + background-color: transparent; + padding: 1.6mm 0 1.8mm 0; + margin: 0; +} + +/* The countdown: the colour is the time left, the background the time gone. */ +LnRingTrack { + color: var(--line); + background-color: transparent; +} + +LnRing { + color: var(--brand); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.3mm; + padding: 0.8mm; + margin: 0 0 0 2.4mm; +} + +LnPulse { + color: var(--brand); + background-color: transparent; + padding: 0.8mm; + margin: 0.8mm 0 0.8mm 0; +} + +LnAvatar { + color: var(--brand-contrast); + background: cn1-round-border; + background-color: var(--brand); + font-family: "native:MainBold"; + font-size: 2.9mm; + text-align: center; + padding: 2.3mm; + margin: 0 3mm 0 0; +} + +LnActions { + background-color: transparent; + padding: 0; + margin: 0.8mm 0 0 0; +} + +/* Call, message, share: an icon with a word under it. */ +LnAction { + color: var(--text); + background-color: transparent; + border-radius: var(--radius); + font-family: "native:MainRegular"; + font-size: 2.2mm; + text-align: center; + padding: 1.8mm 0 1.8mm 0; + margin: 0; +} + +LnAction.pressed { + color: var(--brand); + background-color: var(--surface-alt); +} + +LnActionDanger { + cn1-derive: LnAction; + color: var(--danger); +} + +LnActionDanger.pressed { + color: var(--danger); + background-color: var(--danger-tint); +} + +/* ------------------------------------------------------ records and charts */ + +/* A list that fills a screen: rows from edge to edge, each with the page's + margin inside it. */ +LnList { + background-color: var(--surface); + padding: 0 3.6mm 3.2mm 3.6mm; + margin: 0; +} +/* One line of a receipt: what, and how much. */ +LnFact { + background-color: transparent; + padding: 1.1mm 0 1.1mm 0; + margin: 0; +} +LnFactLabel { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.6mm; + text-align: left; + padding: 0; + margin: 0; +} +LnFactValue { + color: var(--text); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.6mm; + text-align: right; + padding: 0 0 0 3mm; + margin: 0; +} +/* The line the others add up to. */ +LnFactTotal { + cn1-derive: LnFactValue; + font-family: "native:MainBold"; + font-size: 3.3mm; +} +/* The one thing a screen is about, said large at its top. */ +LnBanner { + background-color: transparent; + padding: 5mm 3mm 3mm 3mm; + margin: 0; +} +LnBannerIcon { + color: var(--brand); + background: cn1-round-border; + background-color: var(--brand-tint); + padding: 3.4mm; + margin: 0 0 2.4mm 0; +} +LnBannerIconGood { + cn1-derive: LnBannerIcon; + color: var(--success); + background-color: var(--success-tint); +} +LnBannerIconWarn { + cn1-derive: LnBannerIcon; + color: var(--warning); + background-color: var(--warning-tint); +} +LnBannerIconBad { + cn1-derive: LnBannerIcon; + color: var(--danger); + background-color: var(--danger-tint); +} +LnBannerTitle { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.5mm; + text-align: center; + padding: 0.4mm 0 0.4mm 0; + margin: 0; +} +LnBannerText { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.6mm; + text-align: center; + padding: 0.4mm 2mm 0.4mm 2mm; + margin: 0; +} +/* The amount a receipt is for. */ +LnAmount { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 7mm; + text-align: center; + padding: 1mm 0 0.4mm 0; + margin: 0; +} +/* A group of rows under one heading. */ +LnGroup { + background-color: transparent; + padding: 0; + margin: 0 0 0.8mm 0; +} +/* A chart or a breakdown, boxed with its title. */ +LnTile { + background-color: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 3mm 3mm 3mm 3mm; + margin: 0.8mm 0.8mm 1.6mm 0.8mm; +} +/* A bar chart: the colour is the bars'. */ +LnChart { + color: var(--brand); + background-color: transparent; + padding: 1.6mm 0 0 0; + margin: 0; +} +LnChartAxis { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2mm; + padding: 0.8mm 0 0 0; + margin: 0; +} +/* The number a chart adds up to, over the chart. */ +LnChartValue { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 4.2mm; + text-align: left; + padding: 0; + margin: 0; +} + +/* Something waiting for the admin, at the top of the dashboard. */ +LnAlert { + color: var(--warning); + background-color: var(--warning-tint); + border-radius: var(--radius); + font-family: "native:MainBold"; + font-size: 2.6mm; + text-align: left; + padding: 2.6mm 3mm 2.6mm 3mm; + margin: 0.8mm; +} +LnAlert.pressed { + background-color: var(--surface-press); +} + +/* ----------------------------------------------------------------- choosing */ + +/* One of several things to pick from, of which one is picked. */ +LnOption { + background-color: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 2.4mm 3mm 2.4mm 3mm; + margin: 0.8mm 0 0.8mm 0; +} +LnOption.pressed { + background-color: var(--surface-alt); +} + +/* What is fixed to the foot of a form of several steps. */ +LnFooter { + background-color: var(--surface); + border-top: 1px solid var(--line); + padding: 1mm 3.6mm 1.6mm 3.6mm; + margin: 0; +} + +/* ---------------------------------------------------------------- the menu */ + +/* Dimmed by the colour's own alpha. `opacity` would not do it: a style's + opacity fades what a component draws over its background, and the + background itself is filled at the background's transparency -- so an opaque + black with an opacity is still a black screen. */ +LnScrim { + background-color: rgba(0, 0, 0, 0.45); + padding: 0; + margin: 0; +} + +LnMenu { + background-color: var(--surface); + padding: 0; + margin: 0; +} + +LnMenuTop { + background-color: var(--surface); + border-bottom: 1px solid var(--line); + padding: 5mm 4mm 3.6mm 4mm; + margin: 0; +} + +LnMenuName { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.5mm; + text-align: left; + padding: 0; + margin: 0; +} + +LnMenuDetail { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.4mm; + text-align: left; + padding: 0.2mm 0 0 0; + margin: 0; +} + +/* Which of the three apps this is. */ +LnModeBadge { + color: var(--brand); + background: cn1-pill-border; + background-color: var(--brand-tint); + font-family: "native:MainBold"; + font-size: 2.1mm; + text-align: center; + padding: 0.8mm 2.4mm 0.8mm 2.4mm; + margin: 2.4mm 0 0 0; +} + +LnMenuLabel { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 2.1mm; + text-align: left; + padding: 3.6mm 4mm 1mm 4mm; + margin: 0; +} + +LnMenuItem { + color: var(--text); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.9mm; + text-align: left; + padding: 2.6mm 4mm 2.6mm 4mm; + margin: 0; +} + +LnMenuItem.pressed { + background-color: var(--surface-alt); +} + +LnMenuBottom { + background-color: transparent; + border-top: 1px solid var(--line); + padding: 0.8mm 0 1.6mm 0; + margin: 0; +} + +/* The top of a home screen that has no map: the menu, and what this is. */ +LnHomeBar { + background-color: var(--surface); + border-bottom: 1px solid var(--line); + padding: 0.6mm 3.6mm 0.6mm 0; + margin: 0; +} + +/* ---------------------------------------------------------------- settings */ + +LnSection { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.1mm; + text-align: left; + padding: 5mm 0 0.8mm 0; + margin: 0; +} + +/* A few options side by side, one of them chosen. */ +LnSegments { + background-color: var(--surface-alt); + border-radius: var(--radius); + padding: 0.5mm; + margin: 0.8mm 0 1.6mm 0; +} + +LnSegment { + color: var(--text-muted); + background-color: transparent; + border-radius: 1.9mm; + font-family: "native:MainBold"; + font-size: 2.5mm; + text-align: center; + padding: 2mm 0.8mm 2mm 0.8mm; + margin: 0.3mm; +} + +LnSegment.selected { + color: var(--text); + background-color: var(--surface); +} + +/* A toggle that is on wears the pressed style, so the two say the same. */ +LnSegment.pressed { + color: var(--text); + background-color: var(--surface); +} + +LnSegment.disabled { + color: var(--line-strong); +} + +/* The outline of rows that are on their way: the colour is the bars'. */ +LnSkeleton { + color: var(--surface-alt); + background-color: transparent; + padding: 1mm 0 0 0; + margin: 0; +} + +/* "Pull to refresh", over a list being pulled. */ +PullToRefresh { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.3mm; + text-align: center; + padding: 1.6mm; + margin: 0; +} + +/* What the app says in passing, over the foot of the screen. */ +ToastBar { + background-color: var(--text); + border-radius: var(--radius); + padding: 2.4mm 3mm 2.4mm 3mm; + margin: 2.4mm 3.6mm 3.2mm 3.6mm; +} + +ToastBarMessage { + color: var(--surface); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.5mm; + padding: 0; + margin: 0; +} + +/* ------------------------------------------------- the admin console, wide */ + +/* On a tablet on its side, a desktop or a browser the console is three + columns: where to go, a list, and what was picked from it. */ +LnSide { + background-color: var(--surface-alt); + border-right: 1px solid var(--line); + padding: 2.4mm 1.6mm 2.4mm 1.6mm; + margin: 0; +} + +LnSideName { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.05mm; + padding: 0.8mm 2.4mm 0 2.4mm; + margin: 0; +} + +LnSideDetail { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainRegular"; + font-size: 2.3mm; + padding: 0 2.4mm 2.4mm 2.4mm; + margin: 0; +} + +LnSideLabel { + color: var(--text-muted); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 2.15mm; + padding: 3.2mm 2.4mm 0.8mm 2.4mm; + margin: 0; +} + +LnSideItem { + color: var(--text); + background-color: transparent; + border-radius: var(--radius-small); + font-family: "native:MainRegular"; + font-size: 2.8mm; + text-align: left; + padding: 1.9mm 2.4mm 1.9mm 2.4mm; + margin: 0.2mm 0 0.2mm 0; +} + +LnSideItem.pressed { + background-color: var(--line); +} + +LnSidePicked { + cn1-derive: LnSideItem; + color: var(--brand-contrast); + background-color: var(--brand); + font-family: "native:MainBold"; +} + +LnMaster { + background-color: var(--surface); + border-right: 1px solid var(--line); + padding: 0; + margin: 0; +} + +LnPaneBar { + background-color: var(--surface); + border-bottom: 1px solid var(--line); + padding: 1.2mm 4mm 1.2mm 4mm; + margin: 0; +} + +LnPaneTitle { + color: var(--text); + background-color: transparent; + font-family: "native:MainBold"; + font-size: 3.5mm; + padding: 1.6mm 0 1.6mm 0; + margin: 0; +} + +/* The row of a list whose detail is open beside it. */ +LnRowPicked { + cn1-derive: LnRow; + background-color: var(--surface-alt); +} + +/* + * THE DESKTOP'S OWN LOOK. On macOS, Windows and Linux, and in a desktop + * browser, the platform's theme is under this one (the nativeTheme=native build + * hint), and the admin console wears it: Layouts.dress() gives each component + * the LnDesk twin of its style. A twin derives from the platform's control + * where there is one -- a button, a field, a segmented control, a group box -- + * and takes its colours from the palette every desktop theme declares, so the + * same rules are Aqua on a Mac, Fluent on Windows and Adwaita on Linux. Nothing + * here names the brand; the accent is the platform's. + * + * The values in LnDeskPalette are only what the compiler needs to resolve + * var(): each use is bound to the name, and the installed theme's own value + * replaces it when the app runs. They are declared outside #Constants so that + * they are not exported over the theme's. + */ +LnDeskPalette { + --window-bg-color: #ececec; + --window-bg-color-dark: #1e1e1e; + --view-bg-color: #ffffff; + --view-bg-color-dark: #1e1e1e; + --control-bg-color: #ffffff; + --control-bg-color-dark: #2c2c2c; + --headerbar-bg-color: #e8e8e8; + --headerbar-bg-color-dark: #2a2a2a; + --text-color: #1a1a1a; + --text-color-dark: #ffffff; + --text-secondary-color: #5d5d5d; + --text-secondary-color-dark: #c0c0c0; + --separator-color: #d8d8d8; + --separator-color-dark: #3a3a3a; + --accent-color: #007aff; + --accent-color-dark: #0a84ff; + --accent-fg-color: #ffffff; + --accent-fg-color-dark: #ffffff; + background-color: transparent; + padding: 0; + margin: 0; +} + +LnDeskForm { background-color: var(--window-bg-color); padding: 0; margin: 0; } +LnDeskPage { background-color: var(--window-bg-color); padding: 3mm 5mm 4mm 5mm; margin: 0; } +LnDeskList { background-color: var(--view-bg-color); padding: 0 3mm 2mm 3mm; margin: 0; } +LnDeskMaster { background-color: var(--view-bg-color); border-right: 1px solid #c6c6c8; padding: 0; margin: 0; } +LnDeskHomeBar { background-color: var(--headerbar-bg-color); border-bottom: 1px solid #c6c6c8; padding: 1mm 4mm 1mm 0; margin: 0; } +LnDeskPaneBar { background-color: var(--window-bg-color); border-bottom: 1px solid #c6c6c8; padding: 1mm 5mm 1mm 5mm; margin: 0; } +LnDeskPaneTitle { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 3.2mm; padding: 1.6mm 0 1.6mm 0; margin: 0; } +LnDeskBarButton { cn1-derive: Button; padding: 1.2mm; margin: 0 2mm 0 0; } + +LnDeskSide { background-color: var(--headerbar-bg-color); border-right: 1px solid #c6c6c8; padding: 2.5mm 2mm 2.5mm 2mm; margin: 0; } +LnDeskSideName { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 2.7mm; padding: 1mm 2.6mm 0 2.6mm; margin: 0; } +LnDeskSideDetail { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.25mm; padding: 0 2.6mm 2mm 2.6mm; margin: 0; } +LnDeskSideLabel { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainBold"; font-size: 2.15mm; padding: 3mm 2.6mm 1mm 2.6mm; margin: 0; } +LnDeskSideItem { color: var(--text-color); background-color: transparent; border-radius: 1.4mm; font-family: "native:MainRegular"; font-size: 2.65mm; text-align: left; padding: 1.6mm 2.6mm 1.6mm 2.6mm; margin: 0.2mm 0 0.2mm 0; } +LnDeskSideItem.pressed { background-color: var(--separator-color); } +LnDeskSidePicked { cn1-derive: LnDeskSideItem; color: var(--accent-fg-color); background-color: var(--accent-color); } + +LnDeskPrimary { cn1-derive: RaisedButton; text-align: center; margin: 2mm 0 1mm 0; } +LnDeskSecondary { cn1-derive: Button; text-align: center; margin: 1.5mm 0 1mm 0; } +LnDeskDanger { cn1-derive: Button; color: var(--danger); text-align: center; margin: 1.5mm 0 1mm 0; } +LnDeskLink { cn1-derive: Link; padding: 1.6mm 0 1.6mm 0; } +LnDeskField { cn1-derive: TextField; margin: 0; } +LnDeskFieldHint { cn1-derive: TextHint; } +LnDeskSegments { cn1-derive: TabsContainer; border-radius: 1.6mm; padding: 0.4mm; margin: 1mm 0 2mm 0; } +/* Four of these share the master pane of the console, which is narrow: the + platform's own tab padding leaves "Cancelled" no room and it was drawn cut + off at both ends. */ +LnDeskSegment { cn1-derive: Tab; text-align: center; padding: 1.4mm 0.4mm 1.4mm 0.4mm; margin: 0; } +/* Something waiting is the one thing on the console that is not the + platform's grey: it wears the warning tint the phone's does. */ +LnDeskAlert { color: var(--warning); background-color: var(--warning-tint); border-radius: 1.6mm; font-family: "native:MainBold"; font-size: 2.6mm; text-align: left; padding: 2mm 3mm 2mm 3mm; margin: 1mm 0 1mm 0; } +LnDeskAlert.pressed { color: var(--warning); background-color: var(--warning-tint); border-radius: 1.6mm; font-family: "native:MainBold"; font-size: 2.6mm; text-align: left; padding: 2mm 3mm 2mm 3mm; margin: 1mm 0 1mm 0; } + +LnDeskRow { background-color: transparent; border-bottom: 1px solid #d8d8d8; padding: 2mm 1mm 2mm 1mm; margin: 0; } +LnDeskRow.pressed { background-color: var(--separator-color); } +LnDeskRowPicked { background-color: var(--separator-color); border-bottom: 1px solid #d8d8d8; border-radius: 1.4mm; padding: 2mm 1mm 2mm 1mm; margin: 0; } +LnDeskRowIcon { color: var(--text-secondary-color); background-color: transparent; padding: 0 2.6mm 0 0; margin: 0; } +LnDeskRowTitle { color: var(--text-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.7mm; padding: 0; margin: 0; } +LnDeskRowDetail { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 0.4mm 0 0 0; margin: 0; } +LnDeskRowValue { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 2.65mm; text-align: right; padding: 0; margin: 0; } + +LnDeskSection { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 2.8mm; text-align: left; padding: 4mm 0 1.2mm 0; margin: 0; } +LnDeskTitle { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 4.4mm; padding: 0 0 2mm 0; margin: 0; } +LnDeskHeading { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 3.2mm; padding: 0; margin: 0; } +LnDeskText { color: var(--text-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.65mm; padding: 1mm 0 1mm 0; margin: 0; } +LnDeskMuted { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.4mm; padding: 0.5mm 0 0.5mm 0; margin: 0; } +LnDeskLabel { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.4mm; padding: 2.4mm 0 0.8mm 0; margin: 0; } +LnDeskError { color: var(--danger); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.5mm; padding: 1mm 0 1mm 0; margin: 0; } +LnDeskNotice { cn1-derive: GroupBox; color: var(--text-color); font-family: "native:MainRegular"; font-size: 2.55mm; padding: 2.4mm; margin: 2mm 0 1mm 0; } +LnDeskPanel { cn1-derive: GroupBox; padding: 2.6mm 3mm 2.6mm 3mm; margin: 1mm 0 1mm 0; } +LnDeskFact { background-color: transparent; padding: 1.2mm 0 1.2mm 0; margin: 0; } +LnDeskFactLabel { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.55mm; padding: 0; margin: 0; } +LnDeskFactValue { color: var(--text-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.55mm; text-align: right; padding: 0; margin: 0; } +LnDeskFactTotal { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 2.7mm; text-align: right; padding: 0; margin: 0; } +LnDeskAmount { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 6.4mm; text-align: center; padding: 2mm 0 1mm 0; margin: 0; } +LnDeskBannerIcon { color: var(--text-secondary-color); background-color: transparent; padding: 6mm 0 2mm 0; margin: 0; } +LnDeskBannerTitle { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 3.05mm; text-align: center; padding: 0; margin: 0; } +LnDeskBannerText { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.5mm; text-align: center; padding: 1mm 0 0 0; margin: 0; } + +/* The numbers and the charts have no control on any desktop: they keep their + shape, in a group box, in the platform's colours. */ +LnDeskTile { cn1-derive: GroupBox; padding: 3mm 3.4mm 3mm 3.4mm; margin: 1.2mm; } +LnDeskStat { cn1-derive: GroupBox; padding: 2.6mm 3mm 2.6mm 3mm; margin: 1.2mm; } +LnDeskStatValue { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 4.3mm; padding: 0; margin: 0; } +LnDeskStatLabel { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 0.6mm 0 0 0; margin: 0; } +LnDeskChartValue { color: var(--text-color); background-color: transparent; font-family: "native:MainBold"; font-size: 4.3mm; padding: 0.6mm 0 0 0; margin: 0; } +LnDeskChartAxis { color: var(--text-secondary-color); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.1mm; padding: 0.6mm 0 0 0; margin: 0; } + +/* =============================================================== Lingo + * The learning screens. Cards float on a soft canvas; the one thing to do + * next is a full-width brand button; progress is always a ring or a bar, + * never only a number. Gold is XP, flame is the streak, coral is live. + */ + +/* ------------------------------------------------------------ home */ +LnCanvas { background-color: var(--canvas); padding: 0; margin: 0; } +LnHomeTop { background-color: transparent; padding: 3mm 4mm 1mm 4mm; margin: 0; } +LnHello { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 5.2mm; padding: 0; margin: 0; } +LnHelloSub { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.6mm; padding: 0.6mm 0 0 0; margin: 0; } +LnStreakChip { color: var(--flame); background: cn1-pill-border; background-color: var(--flame-tint); font-family: "native:MainBold"; font-size: 2.8mm; padding: 1.2mm 2.6mm 1.2mm 2.2mm; margin: 0 0 0 1.6mm; } +LnXpChip { color: var(--gold); background: cn1-pill-border; background-color: var(--gold-tint); font-family: "native:MainBold"; font-size: 2.8mm; padding: 1.2mm 2.6mm 1.2mm 2.2mm; margin: 0 0 0 1.6mm; } +LnProChip { color: var(--brand-contrast); background: cn1-pill-border; background-color: var(--brand); font-family: "native:MainBold"; font-size: 2.2mm; padding: 0.8mm 2mm 0.8mm 2mm; margin: 0 0 0 1.6mm; } + +LnHeroCard { background-color: var(--brand); border-radius: 4.4mm; padding: 4mm 4mm 3.6mm 4mm; margin: 2.4mm 4mm 1.6mm 4mm; } +LnHeroKicker { color: var(--hero-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 2.2mm; padding: 0; margin: 0; } +LnDashTitle { color: var(--hero-text); background-color: transparent; font-family: "native:MainBold"; font-size: 4.4mm; padding: 1mm 0 0 0; margin: 0; } +/* A course title beside the goal ring: smaller, so a long word keeps whole. */ +LnContinueTitle { color: var(--hero-text); background-color: transparent; font-family: "native:MainBold"; font-size: 3.5mm; padding: 1mm 0 0 0; margin: 0; } +LnDashText { color: var(--hero-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.6mm; padding: 0.8mm 0 0 0; margin: 0; } +LnHeroButton { color: var(--brand); background: cn1-pill-border; background-color: var(--hero-text); font-family: "native:MainBold"; font-size: 2.9mm; text-align: center; padding: 2.4mm 5mm 2.4mm 4mm; margin: 2.6mm 0 0 0; } +LnHeroButton.pressed { background-color: var(--brand-tint); } +LnGoalRing { color: var(--hero-text); background-color: transparent; font-family: "native:MainBold"; font-size: 3.6mm; padding: 0; margin: 0 0 0 3mm; } +LnGoalTrack { color: var(--brand-pressed); background-color: transparent; } +LnGoalCaption { color: var(--hero-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2mm; text-align: center; padding: 0.6mm 0 0 3mm; margin: 0; } + +LnSectionTop { background-color: transparent; padding: 3.6mm 4mm 1mm 4mm; margin: 0; } +LnSectionTitle { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 3.5mm; padding: 0; margin: 0; } +LnSectionLink { color: var(--brand); background-color: transparent; font-family: "native:MainBold"; font-size: 2.5mm; padding: 0.6mm 0 0 2mm; margin: 0; } +LnSectionLink.pressed { color: var(--brand-pressed); } + +LnBlock { background-color: var(--surface); border-radius: 3.4mm; padding: 3mm 3.4mm 3mm 3.4mm; margin: 1.2mm 4mm 1.2mm 4mm; } +LnWeekDay { color: var(--text-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 2mm; text-align: center; padding: 0.8mm 0 0 0; margin: 0; } +LnWeekDot { color: var(--line-strong); background-color: transparent; text-align: center; padding: 0; margin: 0; } +LnWeekDotDone { color: var(--flame); background-color: transparent; text-align: center; padding: 0; margin: 0; } +LnWeekDotToday { color: var(--brand); background-color: transparent; text-align: center; padding: 0; margin: 0; } +LnWeekNote { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 1.6mm 0 0 0; margin: 0; } + +/* ---------------------------------------------------------- courses */ +LnScrollX { background-color: transparent; padding: 0 2.6mm 0 2.6mm; margin: 0; } +LnCourseCard { background-color: var(--surface); border-radius: 3.6mm; padding: 0; margin: 1.2mm 1.4mm 1.6mm 1.4mm; } +LnCourseCard.pressed { background-color: var(--surface-press); } +LnCourseBody { background-color: transparent; padding: 2.6mm 3mm 3mm 3mm; margin: 0; } +LnCourseTitle { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.7mm; padding: 0; margin: 0; } +LnCourseMeta { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 0.6mm 0 0 0; margin: 0; } +LnCourseBy { color: var(--text-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 2.2mm; padding: 1mm 0 0 0; margin: 0; } +LnPrice { color: var(--brand); background-color: transparent; font-family: "native:MainBold"; font-size: 2.6mm; text-align: right; padding: 1mm 0 0 0; margin: 0; } +LnPriceFree { color: var(--success); background-color: transparent; font-family: "native:MainBold"; font-size: 2.6mm; text-align: right; padding: 1mm 0 0 0; margin: 0; } +LnCover { color: #ffffff; background-color: var(--c-indigo); border-radius: 3.6mm 3.6mm 0 0; font-family: "native:MainBold"; font-size: 6mm; padding: 3mm 3mm 3mm 3mm; margin: 0; } +LnCoverIndigo { cn1-derive: LnCover; background-color: var(--c-indigo); } +LnCoverCoral { cn1-derive: LnCover; background-color: var(--c-coral); } +LnCoverTeal { cn1-derive: LnCover; background-color: var(--c-teal); } +LnCoverAmber { cn1-derive: LnCover; background-color: var(--c-amber); } +LnCoverRose { cn1-derive: LnCover; background-color: var(--c-rose); } +LnCoverSky { cn1-derive: LnCover; background-color: var(--c-sky); } +LnCoverTag { color: #ffffff; background: cn1-pill-border; background-color: rgba(0, 0, 0, 0.22); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 1.8mm 0.6mm 1.8mm; margin: 0; } +LnBar { color: var(--brand); background-color: var(--surface-alt); padding: 0; margin: 1.6mm 0 0 0; } +LnBarGold { color: var(--gold); background-color: var(--surface-alt); padding: 0; margin: 1.6mm 0 0 0; } +LnKindTag { color: var(--brand); background: cn1-pill-border; background-color: var(--brand-tint); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 1.8mm 0.6mm 1.8mm; margin: 0 1mm 0 0; } +LnKindTagCommunity { color: var(--c-rose); background: cn1-pill-border; background-color: var(--urgent-tint); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 1.8mm 0.6mm 1.8mm; margin: 0 1mm 0 0; } + +/* The course screen: a coloured header, then the path of lessons. */ +LnCourseHead { color: #ffffff; background-color: var(--c-indigo); padding: 2mm 4mm 4.4mm 4mm; margin: 0; } +LnCourseHeadTitle { color: #ffffff; background-color: transparent; font-family: "native:MainBold"; font-size: 5mm; padding: 1mm 0 0 0; margin: 0; } +LnCourseHeadText { color: #ffffff; background-color: transparent; font-family: "native:MainRegular"; font-size: 2.6mm; padding: 1mm 0 0 0; margin: 0; } +LnCourseHeadMeta { color: #ffffff; background-color: transparent; font-family: "native:MainBold"; font-size: 2.3mm; padding: 1.6mm 0 0 0; margin: 0; } +LnStep { background-color: transparent; padding: 0.4mm 4mm 0.4mm 4mm; margin: 0; } +LnStepNode { color: var(--brand-contrast); background: cn1-round-border; background-color: var(--brand); font-family: "native:MainBold"; font-size: 2.6mm; text-align: center; padding: 2mm; margin: 0 2.6mm 0 0; } +LnStepNodeDone { color: #ffffff; background: cn1-round-border; background-color: var(--success); font-family: "native:MainBold"; font-size: 2.6mm; text-align: center; padding: 2mm; margin: 0 2.6mm 0 0; } +LnStepNodeLocked { color: var(--text-muted); background: cn1-round-border; background-color: var(--surface-alt); font-family: "native:MainBold"; font-size: 2.6mm; text-align: center; padding: 2mm; margin: 0 2.6mm 0 0; } +LnStepCard { background-color: var(--surface); border-radius: 3mm; padding: 2.6mm 3mm 2.6mm 3mm; margin: 1mm 0 1mm 0; } +LnStepCard.pressed { background-color: var(--surface-press); } +LnStepCardNext { background-color: var(--surface); border: 0.5mm solid var(--brand); border-radius: 3mm; padding: 2.6mm 3mm 2.6mm 3mm; margin: 1mm 0 1mm 0; } +LnStepTitle { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.9mm; padding: 0; margin: 0; } +LnStepMeta { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 0.5mm 0 0 0; margin: 0; } +LnStepRail { color: var(--line-strong); background-color: transparent; padding: 0; margin: 0; } + +/* -------------------------------------------------------- the lesson */ +LnLessonTop { background-color: var(--surface); padding: 2mm 3mm 2mm 2mm; margin: 0; } +LnLessonBody { background-color: var(--surface); padding: 2mm 5mm 4mm 5mm; margin: 0; } +LnLessonForm { background-color: var(--surface); padding: 0; margin: 0; } +LnClose { color: var(--text-muted); background-color: transparent; padding: 1mm; margin: 0; } +LnPrompt { color: var(--text-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 2.5mm; text-align: center; padding: 6mm 0 2mm 0; margin: 0; } +LnPhrase { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 6.4mm; text-align: center; padding: 1mm 0 1mm 0; margin: 0; } +LnTranslation { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 3mm; text-align: center; padding: 1mm 0 3mm 0; margin: 0; } +LnHint { color: var(--warning); background-color: var(--warning-tint); border-radius: var(--radius); font-family: "native:MainRegular"; font-size: 2.5mm; text-align: center; padding: 2mm 3mm 2mm 3mm; margin: 2mm 0 2mm 0; } +LnListen { color: var(--brand); background: cn1-pill-border; background-color: var(--brand-tint); font-family: "native:MainBold"; font-size: 2.6mm; padding: 2mm 3.6mm 2mm 3mm; margin: 1mm; } +LnListen.pressed { background-color: var(--surface-press); } +LnMic { color: var(--brand-contrast); background: cn1-round-border; background-color: var(--brand); text-align: center; padding: 5mm; margin: 3mm; } +LnMic.pressed { background-color: var(--brand-pressed); } +LnMicLive { color: #ffffff; background: cn1-round-border; background-color: var(--coral); text-align: center; padding: 5mm; margin: 3mm; } +LnMicCaption { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.4mm; text-align: center; padding: 0 0 2mm 0; margin: 0; } +LnHeardGood { color: var(--success); background-color: transparent; font-family: "native:MainBold"; font-size: 3.6mm; padding: 0.4mm 0.8mm 0.4mm 0.8mm; margin: 0; } +LnHeardClose { color: var(--warning); background-color: transparent; font-family: "native:MainBold"; font-size: 3.6mm; padding: 0.4mm 0.8mm 0.4mm 0.8mm; margin: 0; } +LnHeardMiss { color: var(--danger); background-color: transparent; font-family: "native:MainBold"; font-size: 3.6mm; padding: 0.4mm 0.8mm 0.4mm 0.8mm; margin: 0; } +LnHeardRaw { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.4mm; text-align: center; padding: 1mm 0 0 0; margin: 0; } +LnVerdict { background-color: var(--success-tint); border-radius: 3.4mm; padding: 3mm 3.4mm 3mm 3.4mm; margin: 2mm 0 0 0; } +LnVerdictTry { background-color: var(--warning-tint); border-radius: 3.4mm; padding: 3mm 3.4mm 3mm 3.4mm; margin: 2mm 0 0 0; } +LnVerdictTitle { color: var(--success); background-color: transparent; font-family: "native:MainBold"; font-size: 3.4mm; padding: 0; margin: 0; } +LnVerdictTitleTry { color: var(--warning); background-color: transparent; font-family: "native:MainBold"; font-size: 3.4mm; padding: 0; margin: 0; } +LnVerdictScore { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 6mm; text-align: right; padding: 0; margin: 0; } +LnLessonFoot { background-color: var(--surface); border-top: 1px solid var(--line); padding: 2mm 4mm 3mm 4mm; margin: 0; } +LnTypeField { color: var(--text); background-color: var(--surface-alt); border-radius: var(--radius); font-family: "native:MainRegular"; font-size: 3mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 1mm 0 1mm 0; } +/* A hint is the size of the text it stands in for, not the platform's default. */ +TextHint { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 3mm; padding: 0; margin: 0; } + +/* The conversation. */ +LnThread { background-color: var(--canvas); padding: 2mm 3mm 2mm 3mm; margin: 0; } +LnScene { color: var(--text-muted); background-color: var(--surface); border-radius: 3mm; font-family: "native:MainRegular"; font-size: 2.4mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 1mm 1mm 2mm 1mm; } +LnBubbleTutor { background-color: var(--surface); border-radius: 3.4mm 3.4mm 3.4mm 0.8mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 1mm 12mm 1mm 0; } +LnBubbleMe { background-color: var(--brand); border-radius: 3.4mm 3.4mm 0.8mm 3.4mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 1mm 0 1mm 12mm; } +LnBubbleText { color: var(--text); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.9mm; padding: 0; margin: 0; } +LnBubbleTextMe { color: var(--brand-contrast); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.9mm; padding: 0; margin: 0; } +LnBubbleSpeak { color: var(--brand); background-color: transparent; padding: 0.4mm 0 0 1.6mm; margin: 0; } +LnFix { color: var(--warning); background-color: var(--warning-tint); border-radius: 2.4mm; font-family: "native:MainRegular"; font-size: 2.4mm; padding: 1.8mm 2.6mm 1.8mm 2.6mm; margin: 0.4mm 0 1.4mm 12mm; } +LnEngine { color: var(--text-muted); background: cn1-pill-border; background-color: var(--surface-alt); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 2mm 0.6mm 1.6mm; margin: 0; } +LnTyping { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.4mm; padding: 1mm 0 1mm 1mm; margin: 0; } + +/* Video. */ +LnVideo { background-color: #000000; padding: 0; margin: 0; } + +/* ----------------------------------------------------- the reward */ +LnReward { background-color: var(--surface); padding: 6mm 5mm 4mm 5mm; margin: 0; } +LnRewardTitle { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 5.6mm; text-align: center; padding: 3mm 0 0 0; margin: 0; } +LnRewardText { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.8mm; text-align: center; padding: 1mm 0 0 0; margin: 0; } +LnRewardXp { color: var(--gold); background-color: transparent; font-family: "native:MainBold"; font-size: 10mm; text-align: center; padding: 2mm 0 0 0; margin: 0; } +LnRewardStat { background-color: var(--surface-alt); border-radius: 3mm; padding: 2.4mm; margin: 1mm; } +LnRewardStatValue { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 4.2mm; text-align: center; padding: 0; margin: 0; } +LnRewardStatLabel { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.1mm; text-align: center; padding: 0.4mm 0 0 0; margin: 0; } +LnConfetti { color: var(--gold); background-color: transparent; padding: 0; margin: 0; } + +/* --------------------------------------------------- achievements */ +LnBadgeTile { background-color: var(--surface); border-radius: 3.4mm; padding: 3mm 2mm 3mm 2mm; margin: 1.2mm; } +LnBadgeIcon { color: #ffffff; background: cn1-round-border; background-color: var(--gold); text-align: center; padding: 3mm; margin: 0 0 1.6mm 0; } +LnBadgeIconLocked { color: var(--text-muted); background: cn1-round-border; background-color: var(--surface-alt); text-align: center; padding: 3mm; margin: 0 0 1.6mm 0; } +LnBadgeName { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.5mm; text-align: center; padding: 0; margin: 0; } +LnBadgeText { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.1mm; text-align: center; padding: 0.6mm 0 0 0; margin: 0; } +LnUnlocked { background-color: var(--surface); border-radius: 4.4mm; padding: 5mm 5mm 4mm 5mm; margin: 0; } +LnUnlockedIcon { color: #ffffff; background: cn1-round-border; background-color: var(--gold); text-align: center; padding: 5mm; margin: 0 0 2mm 0; } + +/* ---------------------------------------------------- leaderboard */ +LnRank { color: var(--text-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 3mm; text-align: center; padding: 0 2.4mm 0 0; margin: 0; } +LnRankTop { color: var(--gold); background-color: transparent; font-family: "native:MainBold"; font-size: 3mm; text-align: center; padding: 0 2.4mm 0 0; margin: 0; } +LnLeader { background-color: var(--surface); border-radius: 3mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 0.8mm 4mm 0.8mm 4mm; } +LnLeaderMe { background-color: var(--brand-tint); border: 0.4mm solid var(--brand); border-radius: 3mm; padding: 2.4mm 3mm 2.4mm 3mm; margin: 0.8mm 4mm 0.8mm 4mm; } +LnLeaderXp { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.9mm; text-align: right; padding: 0; margin: 0; } +LnPodium { background-color: transparent; padding: 2mm 4mm 2mm 4mm; margin: 0; } + +/* -------------------------------------------------- certificates */ +LnCert { background-color: #fdfbf6; border: 0.5mm solid var(--gold); border-radius: 3.4mm; padding: 3.4mm; margin: 1.2mm 4mm 1.2mm 4mm; } +LnCert.pressed { background-color: var(--gold-tint); } +LnCertKicker { color: #b07d10; background-color: transparent; font-family: "native:MainBold"; font-size: 2mm; padding: 0; margin: 0; } +LnCertTitle { color: #1d2433; background-color: transparent; font-family: "native:MainBold"; font-size: 3.4mm; padding: 0.6mm 0 0 0; margin: 0; } +LnCertMeta { color: #667085; background-color: transparent; font-family: "native:MainRegular"; font-size: 2.3mm; padding: 0.6mm 0 0 0; margin: 0; } +LnCertSeal { color: var(--gold); background-color: transparent; padding: 0 0 0 2mm; margin: 0; } +LnVerified { color: var(--success); background: cn1-pill-border; background-color: var(--success-tint); font-family: "native:MainBold"; font-size: 2.4mm; padding: 1mm 2.6mm 1mm 2mm; margin: 1mm 0 0 0; } +LnPdf { background-color: var(--surface-alt); padding: 0; margin: 0; } + +/* ------------------------------------------------------- live */ +LnLiveBadge { color: #ffffff; background: cn1-pill-border; background-color: var(--coral); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 2mm 0.6mm 1.6mm; margin: 0; } +LnSoonBadge { color: var(--brand); background: cn1-pill-border; background-color: var(--brand-tint); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 2mm 0.6mm 1.6mm; margin: 0; } +LnLiveCard { background-color: var(--surface); border-radius: 3.4mm; padding: 3mm 3.4mm 3mm 3.4mm; margin: 1.2mm 4mm 1.2mm 4mm; } +LnLiveCard.pressed { background-color: var(--surface-press); } +LnLiveWhen { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.4mm; text-align: center; padding: 0; margin: 0; } +LnLiveDay { color: var(--coral); background-color: transparent; font-family: "native:MainBold"; font-size: 2mm; text-align: center; padding: 0; margin: 0; } +LnLiveDate { background-color: var(--coral-tint); border-radius: 2.4mm; padding: 1.6mm 2mm 1.6mm 2mm; margin: 0 2.6mm 0 0; } +LnRoom { background-color: #0b0e14; padding: 0; margin: 0; } +LnRoomBar { background-color: transparent; padding: 3mm; margin: 0; } +LnRoomTitle { color: #ffffff; background-color: transparent; font-family: "native:MainBold"; font-size: 3.2mm; padding: 0; margin: 0; } +LnRoomText { color: #c4c9d4; background-color: transparent; font-family: "native:MainRegular"; font-size: 2.5mm; text-align: center; padding: 1mm 4mm 1mm 4mm; margin: 0; } +LnRoomButton { color: #ffffff; background: cn1-round-border; background-color: rgba(255, 255, 255, 0.16); padding: 3mm; margin: 2mm; } +LnRoomHangUp { color: #ffffff; background: cn1-round-border; background-color: var(--coral); padding: 3mm; margin: 2mm; } +LnSelfView { background-color: #222833; border-radius: 3mm; padding: 0; margin: 3mm; } + +/* ------------------------------------------------------ community */ +LnComment { background-color: var(--surface); border-radius: 3mm; padding: 2.6mm 3mm 2.6mm 3mm; margin: 1mm 4mm 0.6mm 4mm; } +LnReply { background-color: var(--surface-alt); border-radius: 3mm; padding: 2.2mm 3mm 2.2mm 3mm; margin: 0.4mm 4mm 0.6mm 10mm; } +LnCommentWho { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 2.5mm; padding: 0; margin: 0; } +LnCommentText { color: var(--text); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.7mm; padding: 0.6mm 0 0 0; margin: 0; } +LnCreatorTag { color: var(--brand); background: cn1-pill-border; background-color: var(--brand-tint); font-family: "native:MainBold"; font-size: 1.9mm; padding: 0.4mm 1.6mm 0.4mm 1.6mm; margin: 0 0 0 1.4mm; } +LnPlan { background-color: var(--surface); border: 0.5mm solid var(--line); border-radius: 3.4mm; padding: 3.4mm; margin: 1.2mm 4mm 1.2mm 4mm; } +LnPlanPro { background-color: var(--brand-tint); border: 0.6mm solid var(--brand); border-radius: 3.4mm; padding: 3.4mm; margin: 1.2mm 4mm 1.2mm 4mm; } +LnPlanPrice { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 5mm; padding: 0; margin: 0; } +LnTick { color: var(--success); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.6mm; padding: 0.6mm 0 0 0; margin: 0; } +LnMoney { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 7mm; padding: 0; margin: 0; } + +/* -------------------------------------------------------- tab bar */ +LnTabBar { background-color: var(--surface); border-top: 1px solid var(--line); padding: 1mm 0 1.4mm 0; margin: 0; } +LnTab { color: var(--text-muted); background-color: transparent; font-family: "native:MainBold"; font-size: 2mm; text-align: center; padding: 1.2mm 0 0.6mm 0; margin: 0; } +LnTab.pressed { color: var(--text); } +LnTabOn { color: var(--brand); background-color: transparent; font-family: "native:MainBold"; font-size: 2mm; text-align: center; padding: 1.2mm 0 0.6mm 0; margin: 0; } +LnScreenTitle { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 5.2mm; padding: 3mm 4mm 1mm 4mm; margin: 0; } +LnScreenText { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.6mm; padding: 0 4mm 1.6mm 4mm; margin: 0; } +LnProfileTile { background-color: var(--surface); border-radius: 3.4mm; padding: 3mm; margin: 1.2mm; } +LnProfileTile.pressed { background-color: var(--surface-press); } +LnProfileIcon { color: var(--brand); background: cn1-round-border; background-color: var(--brand-tint); padding: 2.4mm; margin: 0 0 1.4mm 0; } +LnProfileValue { color: var(--text); background-color: transparent; font-family: "native:MainBold"; font-size: 4mm; padding: 0; margin: 0; } +LnProfileLabel { color: var(--text-muted); background-color: transparent; font-family: "native:MainRegular"; font-size: 2.2mm; padding: 0.4mm 0 0 0; margin: 0; } + +/* ------------------------------------------------------- studio */ +LnStudioStat { background-color: var(--surface); border-radius: 3.4mm; padding: 3mm 1.6mm 3mm 1.6mm; margin: 1mm; } +LnDraftTag { color: var(--warning); background: cn1-pill-border; background-color: var(--warning-tint); font-family: "native:MainBold"; font-size: 2mm; padding: 0.6mm 1.8mm 0.6mm 1.8mm; margin: 0 1mm 0 0; } + +/* + * DARK MODE. The same rules, with the second value of each colour. A rule added + * above that names a colour needs its line here. + */ +@media (prefers-color-scheme: dark) { + LnForm { background-color: var(--surface-dark); } + LnPage { background-color: var(--surface-dark); } + LnHero { background-color: var(--brand-dark); } + LnHeroTitle { color: var(--brand-contrast-dark); } + LnHeroText { color: var(--brand-contrast-dark); } + LnHeroIcon { color: var(--brand-contrast-dark); } + LnHeroFeatureIcon { color: var(--brand-contrast-dark); } + LnCard { background-color: var(--surface-dark); } + LnFloat { background-color: var(--surface-dark); } + LnPanel { background-color: var(--surface-alt-dark); } + LnDivider { background-color: var(--line-dark); } + LnTitle { color: var(--text-dark); } + LnHeading { color: var(--text-dark); } + LnText { color: var(--text-dark); } + LnMuted { color: var(--text-muted-dark); } + LnLabel { color: var(--text-muted-dark); } + LnError { color: var(--danger-dark); } + LnNotice { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnPrimary { color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnPrimary.pressed { background-color: var(--brand-pressed-dark); } + LnPrimary.disabled { color: var(--text-muted-dark); background-color: var(--surface-press-dark); } + LnSecondary { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnSecondary.pressed { background-color: var(--surface-press-dark); } + LnDanger { color: var(--danger-dark); background-color: var(--danger-tint-dark); } + LnDanger.pressed { background-color: var(--surface-press-dark); } + LnLink { color: var(--brand-dark); } + LnLink.pressed { color: var(--brand-pressed-dark); background-color: var(--brand-tint-dark); } + LnMapButton { background: cn1-round-border; color: var(--text-dark); background-color: var(--surface-dark); } + LnMapButton.pressed { background: cn1-round-border; background-color: var(--surface-alt-dark); } + LnBarButton { background: cn1-round-border; color: var(--text-dark); background-color: var(--surface-dark); } + LnBarButton.pressed { background: cn1-round-border; background-color: var(--surface-alt-dark); } + LnSearchBar { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnSearchBar.pressed { background-color: var(--surface-press-dark); } + LnField { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnFieldHint { color: var(--text-muted-dark); } + LnRow { background-color: var(--surface-dark); border-bottom: 1px solid var(--line-dark); } + LnRow.pressed { background-color: var(--surface-alt-dark); } + LnRowIcon { color: var(--text-muted-dark); } + LnRowTitle { color: var(--text-dark); } + LnRowDetail { color: var(--text-muted-dark); } + LnRowValue { color: var(--text-dark); } + LnBadge { background: cn1-pill-border; color: var(--text-muted-dark); background-color: var(--surface-alt-dark); } + LnBadgeGood { background: cn1-pill-border; color: var(--success-dark); background-color: var(--success-tint-dark); } + LnBadgeWarn { background: cn1-pill-border; color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnBadgeBad { background: cn1-pill-border; color: var(--danger-dark); background-color: var(--danger-tint-dark); } + LnStat { background-color: var(--surface-alt-dark); } + LnStatValue { color: var(--text-dark); } + LnStatLabel { color: var(--text-muted-dark); } + StatusBar { background-color: var(--surface-dark); } + Toolbar { background-color: var(--surface-dark); border-bottom: 1px solid var(--line-dark); } + Title { color: var(--text-dark); } + TitleCommand { color: var(--text-dark); } + BackCommand { color: var(--text-dark); } + LnRoute { color: var(--brand-dark); background-color: var(--map-edge-dark); } + LnSearchCard { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnSearchCard.pressed { background-color: var(--line-dark); } + LnChip { background: cn1-pill-border; color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnSheet { background-color: var(--surface-dark); } + LnGrip { color: var(--line-strong-dark); } + LnRing { color: var(--brand-dark); } + LnRingTrack { color: var(--line-dark); } + LnPulse { color: var(--brand-dark); } + LnAvatar { background: cn1-round-border; color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnAction { color: var(--text-dark); } + LnAction.pressed { color: var(--brand-dark); background-color: var(--surface-alt-dark); } + LnActionDanger { color: var(--danger-dark); } + LnActionDanger.pressed { color: var(--danger-dark); background-color: var(--danger-tint-dark); } + LnMenu { background-color: var(--surface-dark); } + LnMenuTop { background-color: var(--surface-dark); border-bottom: 1px solid var(--line-dark); } + LnMenuName { color: var(--text-dark); } + LnMenuDetail { color: var(--text-muted-dark); } + LnModeBadge { background: cn1-pill-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnMenuLabel { color: var(--text-muted-dark); } + LnMenuItem { color: var(--text-dark); } + LnMenuItem.pressed { background-color: var(--surface-alt-dark); } + LnMenuBottom { border-top: 1px solid var(--line-dark); } + LnHomeBar { background-color: var(--surface-dark); border-bottom: 1px solid var(--line-dark); } + LnSection { color: var(--text-dark); } + LnSegments { background-color: var(--surface-alt-dark); } + LnSegment { color: var(--text-muted-dark); } + LnSegment.selected { color: var(--text-dark); background-color: var(--surface-press-dark); } + LnSegment.pressed { color: var(--text-dark); background-color: var(--surface-press-dark); } + LnList { background-color: var(--surface-dark); } + LnFactLabel { color: var(--text-muted-dark); } + LnFactValue { color: var(--text-dark); } + LnFactTotal { color: var(--text-dark); } + LnBannerIcon { background: cn1-round-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnBannerIconGood { background: cn1-round-border; color: var(--success-dark); background-color: var(--success-tint-dark); } + LnBannerIconWarn { background: cn1-round-border; color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnBannerIconBad { background: cn1-round-border; color: var(--danger-dark); background-color: var(--danger-tint-dark); } + LnBannerTitle { color: var(--text-dark); } + LnBannerText { color: var(--text-muted-dark); } + LnAmount { color: var(--text-dark); } + LnTile { background-color: var(--surface-dark); border: 1px solid var(--line-dark); } + LnChart { color: var(--brand-dark); } + LnChartAxis { color: var(--text-muted-dark); } + LnChartValue { color: var(--text-dark); } + LnAlert { color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnAlert.pressed { background-color: var(--surface-press-dark); } + LnOption { background-color: var(--surface-dark); border: 1px solid var(--line-dark); } + LnOption.pressed { background-color: var(--surface-alt-dark); } + LnFooter { background-color: var(--surface-dark); border-top: 1px solid var(--line-dark); } + LnSide { background-color: var(--surface-alt-dark); border-right: 1px solid var(--line-dark); } + LnSideName { color: var(--text-dark); } + LnSideDetail { color: var(--text-muted-dark); } + LnSideLabel { color: var(--text-muted-dark); } + LnSideItem { color: var(--text-dark); } + LnSideItem.pressed { background-color: var(--line-dark); } + LnSidePicked { color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnMaster { background-color: var(--surface-dark); border-right: 1px solid var(--line-dark); } + LnPaneBar { background-color: var(--surface-dark); border-bottom: 1px solid var(--line-dark); } + LnPaneTitle { color: var(--text-dark); } + LnRowPicked { background-color: var(--surface-alt-dark); } + LnSecondary.disabled, LnDanger.disabled, LnLink.disabled { color: var(--line-strong-dark); } + LnField.selected { background-color: var(--brand-tint-dark); } + LnField.disabled { color: var(--text-muted-dark); } + Switch { color: #ffffff; background-color: var(--line-strong-dark); } + Switch.selected { color: #ffffff; background-color: var(--brand-dark); } + Switch.disabled { color: var(--text-muted-dark); background-color: var(--line-dark); } + LnSegment.disabled { color: var(--line-strong-dark); } + LnSkeleton { color: var(--surface-alt-dark); } + PullToRefresh { color: var(--text-muted-dark); } + ToastBar { background-color: var(--text-dark); } + ToastBarMessage { color: var(--surface-dark); } + LnDeskForm { background-color: var(--window-bg-color-dark); } + LnDeskPage { background-color: var(--window-bg-color-dark); } + LnDeskList { background-color: var(--view-bg-color-dark); } + LnDeskMaster { background-color: var(--view-bg-color-dark); border-right: 1px solid #3a3a3a; } + LnDeskHomeBar { background-color: var(--headerbar-bg-color-dark); border-bottom: 1px solid #3a3a3a; } + LnDeskPaneBar { background-color: var(--window-bg-color-dark); border-bottom: 1px solid #3a3a3a; } + LnDeskPaneTitle { color: var(--text-color-dark); } + LnDeskSide { background-color: var(--headerbar-bg-color-dark); border-right: 1px solid #3a3a3a; } + LnDeskSideName { color: var(--text-color-dark); } + LnDeskSideDetail { color: var(--text-secondary-color-dark); } + LnDeskSideLabel { color: var(--text-secondary-color-dark); } + LnDeskSideItem { color: var(--text-color-dark); } + LnDeskSideItem.pressed { background-color: var(--separator-color-dark); } + LnDeskSidePicked { color: var(--accent-fg-color-dark); background-color: var(--accent-color-dark); } + LnDeskDanger { color: var(--danger-dark); } + LnDeskRow { border-bottom: 1px solid #3a3a3a; } + LnDeskRow.pressed { background-color: var(--separator-color-dark); } + LnDeskRowPicked { background-color: var(--separator-color-dark); border-bottom: 1px solid #3a3a3a; } + LnDeskAlert { color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnDeskAlert.pressed { color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnDeskRowIcon { color: var(--text-secondary-color-dark); } + LnDeskRowTitle { color: var(--text-color-dark); } + LnDeskRowDetail { color: var(--text-secondary-color-dark); } + LnDeskRowValue { color: var(--text-color-dark); } + LnDeskSection { color: var(--text-color-dark); } + LnDeskTitle { color: var(--text-color-dark); } + LnDeskHeading { color: var(--text-color-dark); } + LnDeskText { color: var(--text-color-dark); } + LnDeskMuted { color: var(--text-secondary-color-dark); } + LnDeskLabel { color: var(--text-secondary-color-dark); } + LnDeskError { color: var(--danger-dark); } + LnDeskNotice { color: var(--text-color-dark); } + LnDeskFactLabel { color: var(--text-secondary-color-dark); } + LnDeskFactValue { color: var(--text-color-dark); } + LnDeskFactTotal { color: var(--text-color-dark); } + LnDeskAmount { color: var(--text-color-dark); } + LnDeskBannerIcon { color: var(--text-secondary-color-dark); } + LnDeskBannerTitle { color: var(--text-color-dark); } + LnDeskBannerText { color: var(--text-secondary-color-dark); } + LnDeskStatValue { color: var(--text-color-dark); } + LnDeskStatLabel { color: var(--text-secondary-color-dark); } + LnDeskChartValue { color: var(--text-color-dark); } + LnDeskChartAxis { color: var(--text-secondary-color-dark); } +} + +/* Reports: charts read their colours from these rules, so the dark block can flip them. */ + +/* Lingo in the dark: the same rules, the dark half of every colour. */ + +/* Lingo's learning screens, dark. */ +@media (prefers-color-scheme: dark) { + LnCanvas { background-color: var(--canvas-dark); } + LnHello { color: var(--text-dark); } + LnHelloSub { color: var(--text-muted-dark); } + LnStreakChip { color: var(--flame-dark); background: cn1-pill-border; background-color: var(--flame-tint-dark); } + LnXpChip { color: var(--gold-dark); background: cn1-pill-border; background-color: var(--gold-tint-dark); } + LnProChip { background: cn1-pill-border; color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnHeroCard { background-color: #3b37b8; } + LnHeroButton { color: #3b37b8; } + LnGoalTrack { color: #2d2a8f; } + LnSectionTitle { color: var(--text-dark); } + LnSectionLink { color: var(--brand-dark); } + LnBlock { background-color: var(--surface-dark); } + LnWeekDay { color: var(--text-muted-dark); } + LnWeekDot { color: var(--line-strong-dark); } + LnWeekDotDone { color: var(--flame-dark); } + LnWeekDotToday { color: var(--brand-dark); } + LnWeekNote { color: var(--text-muted-dark); } + LnCourseCard { background-color: var(--surface-alt-dark); } + LnCourseTitle { color: var(--text-dark); } + LnCourseMeta { color: var(--text-muted-dark); } + LnCourseBy { color: var(--text-muted-dark); } + LnPrice { color: var(--brand-dark); } + LnPriceFree { color: var(--success-dark); } + LnBar { color: var(--brand-dark); background-color: var(--surface-press-dark); } + LnBarGold { color: var(--gold-dark); background-color: var(--surface-press-dark); } + LnKindTag { background: cn1-pill-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnKindTagCommunity { background: cn1-pill-border; color: var(--urgent-dark); background-color: var(--urgent-tint-dark); } + LnStepCard { background-color: var(--surface-alt-dark); } + LnStepCardNext { background-color: var(--surface-alt-dark); border: 0.5mm solid var(--brand-dark); } + LnStepNode { background: cn1-round-border; color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnStepNodeDone { background: cn1-round-border; background-color: var(--success-dark); } + LnStepNodeLocked { background: cn1-round-border; color: var(--text-muted-dark); background-color: var(--surface-alt-dark); } + LnStepTitle { color: var(--text-dark); } + LnStepMeta { color: var(--text-muted-dark); } + LnStepRail { color: var(--line-strong-dark); } + LnLessonTop { background-color: var(--surface-dark); } + LnLessonBody { background-color: var(--surface-dark); } + LnLessonForm { background-color: var(--surface-dark); } + LnLessonFoot { background-color: var(--surface-dark); border-top: 1px solid var(--line-dark); } + LnClose { color: var(--text-muted-dark); } + LnPrompt { color: var(--text-muted-dark); } + LnPhrase { color: var(--text-dark); } + LnTranslation { color: var(--text-muted-dark); } + LnHint { color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnListen { background: cn1-pill-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnMic { background: cn1-round-border; color: var(--brand-contrast-dark); background-color: var(--brand-dark); } + LnMicLive { background: cn1-round-border; background-color: var(--coral-dark); } + LnMicCaption { color: var(--text-muted-dark); } + LnHeardGood { color: var(--success-dark); } + LnHeardClose { color: var(--warning-dark); } + LnHeardMiss { color: var(--danger-dark); } + LnHeardRaw { color: var(--text-muted-dark); } + LnVerdict { background-color: var(--success-tint-dark); } + LnVerdictTry { background-color: var(--warning-tint-dark); } + LnVerdictTitle { color: var(--success-dark); } + LnVerdictTitleTry { color: var(--warning-dark); } + LnVerdictScore { color: var(--text-dark); } + LnTypeField { color: var(--text-dark); background-color: var(--surface-alt-dark); } + LnThread { background-color: var(--canvas-dark); } + LnScene { color: var(--text-muted-dark); background-color: var(--surface-alt-dark); } + LnBubbleTutor { background-color: var(--surface-alt-dark); } + LnBubbleMe { background-color: var(--brand-dark); } + LnBubbleText { color: var(--text-dark); } + LnBubbleTextMe { color: var(--brand-contrast-dark); } + LnBubbleSpeak { color: var(--brand-dark); } + LnFix { color: var(--warning-dark); background-color: var(--warning-tint-dark); } + LnEngine { background: cn1-pill-border; color: var(--text-muted-dark); background-color: var(--surface-alt-dark); } + LnTyping { color: var(--text-muted-dark); } + LnReward { background-color: var(--surface-dark); } + LnRewardTitle { color: var(--text-dark); } + LnRewardText { color: var(--text-muted-dark); } + LnRewardXp { color: var(--gold-dark); } + LnRewardStat { background-color: var(--surface-alt-dark); } + LnRewardStatValue { color: var(--text-dark); } + LnRewardStatLabel { color: var(--text-muted-dark); } + LnBadgeTile { background-color: var(--surface-alt-dark); } + LnBadgeIcon { background: cn1-round-border; background-color: var(--gold-dark); } + LnBadgeIconLocked { background: cn1-round-border; color: var(--text-muted-dark); background-color: var(--surface-press-dark); } + LnBadgeName { color: var(--text-dark); } + LnBadgeText { color: var(--text-muted-dark); } + LnUnlocked { background-color: var(--surface-alt-dark); } + LnRank { color: var(--text-muted-dark); } + LnRankTop { color: var(--gold-dark); } + LnLeader { background-color: var(--surface-alt-dark); } + LnLeaderMe { background-color: var(--brand-tint-dark); border: 0.4mm solid var(--brand-dark); } + LnLeaderXp { color: var(--text-dark); } + LnVerified { background: cn1-pill-border; color: var(--success-dark); background-color: var(--success-tint-dark); } + LnPdf { background-color: var(--surface-alt-dark); } + LnSoonBadge { background: cn1-pill-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnLiveBadge { background: cn1-pill-border; background-color: var(--coral-dark); } + LnLiveCard { background-color: var(--surface-alt-dark); } + LnLiveWhen { color: var(--text-dark); } + LnLiveDay { color: var(--coral-dark); } + LnLiveDate { background-color: var(--coral-tint-dark); } + LnComment { background-color: var(--surface-alt-dark); } + LnReply { background-color: var(--surface-press-dark); } + LnCommentWho { color: var(--text-dark); } + LnCommentText { color: var(--text-dark); } + LnCreatorTag { background: cn1-pill-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnPlan { background-color: var(--surface-alt-dark); border: 0.5mm solid var(--line-dark); } + LnPlanPro { background-color: var(--brand-tint-dark); border: 0.6mm solid var(--brand-dark); } + LnPlanPrice { color: var(--text-dark); } + LnTick { color: var(--success-dark); } + LnMoney { color: var(--text-dark); } + LnTabBar { background-color: var(--surface-dark); border-top: 1px solid var(--line-dark); } + LnTab { color: var(--text-muted-dark); } + LnTabOn { color: var(--brand-dark); } + LnScreenTitle { color: var(--text-dark); } + LnScreenText { color: var(--text-muted-dark); } + LnProfileTile { background-color: var(--surface-alt-dark); } + LnProfileIcon { background: cn1-round-border; color: var(--brand-dark); background-color: var(--brand-tint-dark); } + LnProfileValue { color: var(--text-dark); } + LnProfileLabel { color: var(--text-muted-dark); } + LnStudioStat { background-color: var(--surface-alt-dark); } + LnDraftTag { background: cn1-pill-border; color: var(--warning-dark); background-color: var(--warning-tint-dark); } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/AppConfig.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/AppConfig.java new file mode 100644 index 00000000000..a0479dde750 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/AppConfig.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.io.Preferences; +import com.codename1.ui.CN; + +/// The few things about the app that are settings and not code. +public final class AppConfig { + /// Where the server is when nothing says otherwise: a server started on + /// this machine with `cn1:backend`. Change this to your deployment's address + /// before you ship; until then the settings screen can point a build at + /// another server, which is how a phone reaches a laptop on the same network. + public static final String DEFAULT_SERVER = "http://localhost:8080"; + /// The id the server knows this app by. The same constant is in the + /// server's `SecurityConfig`. + public static final String CLIENT_ID = "lingo-app"; + /// The address the server hands the authorization code back to. The app + /// reads the code out of the redirect itself and never opens this address, + /// so it only has to be one the server has on its list. + public static final String REDIRECT_URI = "http://127.0.0.1/callback"; + /// The path the server hands the code back on when the app runs in a + /// browser. The same constant is in the server's `SecurityConfig`. + public static final String WEB_REDIRECT_PATH = "/signin/code"; + // tag::lingo-push-key[] + /// The app's push key, from the Push section of the Codename One console. + /// Empty, the app registers for no notifications: everything still works, + /// and a phone in a pocket simply hears nothing until it is opened. + public static final String PUSH_APP_KEY = ""; + // end::lingo-push-key[] + /// Where the map opens when the device will not say where it is, and + /// where the simulator stands: downtown Portland, among the demonstration + /// company's sites. Change it to your own service area. + public static final double DEFAULT_LAT = 45.5200; + public static final double DEFAULT_LNG = -122.6780; + + private static final String SERVER_KEY = "lingo.server"; + private static final String MODE_KEY = "lingo.mode"; + private static final String MODE_OWNER_KEY = "lingo.mode.owner"; + + private AppConfig() { + } + + /// The server's address, with no trailing slash. A `lingo.server.url` + /// system property wins, which is what the tests use; then the address saved + /// from the settings screen; then, in a browser, the address the page came + /// from, since the server that hosts the app is the server it talks to; + /// then [#DEFAULT_SERVER]. + public static String serverUrl() { + String url = System.getProperty("lingo.server.url"); + if (url == null || url.length() == 0) { + String origin = pageOrigin(); + // In a browser it is always the page's own server: see + // serverSwitchable(). An address saved before that is ignored. + url = origin != null ? origin : Preferences.get(SERVER_KEY, DEFAULT_SERVER); + } + return clean(url); + } + + /// Whether the app may be pointed at another server. Not in a browser: + /// there the authorization code is sent back to the page's own server + /// ([#redirectUri]), and another server has not registered that address + /// as one of its own, so every sign-in after a switch would be refused. + /// The hosted app is the server's own, and talks to that server. + public static boolean serverSwitchable() { + return pageOrigin() == null; + } + + /// The address of the page the app is running in -- `https://host`, with + /// no path -- or null when it is not running in a browser. + public static String pageOrigin() { + String origin = CN.getProperty("browser.window.location.origin", null); + if (origin == null || !(origin.regionMatches(true, 0, "http://", 0, 7) + || origin.regionMatches(true, 0, "https://", 0, 8))) { + return null; + } + return clean(origin); + } + + /// Where the server is asked to send the authorization code. + /// + /// The installed app names the loopback address and reads the code off the + /// redirect without following it. A browser follows a redirect itself and + /// will not show the page an answer from another origin, so there the code + /// is sent to the server the page came from, which hands it back. + public static String redirectUri() { + String origin = pageOrigin(); + return origin == null ? REDIRECT_URI : origin + WEB_REDIRECT_PATH; + } + + public static void setServerUrl(String url) { + Preferences.set(SERVER_KEY, clean(url)); + } + + /// The mode the account `owner` (see + /// [com.codenameone.examples.lingo.net.Session#owner(String)]) chose last + /// -- `learn` or `studio` -- or + /// empty when they have chosen none, or the choice on record is someone + /// else's. A choice recorded with no name is anyone's: that is how a test + /// puts the app in a mode before it signs in. + public static String mode(String owner) { + String chosenBy = Preferences.get(MODE_OWNER_KEY, ""); + if (chosenBy.length() > 0 && !chosenBy.equals(owner)) { + return ""; + } + return Preferences.get(MODE_KEY, ""); + } + + /// Records `mode` as chosen by whoever signs in next. + public static void setMode(String mode) { + setMode(mode, ""); + } + + public static void setMode(String mode, String username) { + Preferences.set(MODE_KEY, mode == null ? "" : mode); + Preferences.set(MODE_OWNER_KEY, username == null ? "" : username); + } + + /// Whether `url` names the server `current` does, as [#setServerUrl] + /// would store it. + public static boolean sameServer(String url, String current) { + return clean(url).equals(current); + } + + private static String clean(String url) { + String text = url == null ? "" : url.trim(); + while (text.endsWith("/")) { + text = text.substring(0, text.length() - 1); + } + if (text.length() == 0) { + return DEFAULT_SERVER; + } + // Compared without folding the case: a scheme is ASCII, and + // toLowerCase() follows the device's language. + if (!text.regionMatches(true, 0, "http://", 0, 7) + && !text.regionMatches(true, 0, "https://", 0, 8)) { + text = "http://" + text; + } + return text; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Lingo.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Lingo.java new file mode 100644 index 00000000000..633e2abfd2d --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Lingo.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.system.Lifecycle; +import com.codenameone.examples.lingo.net.Account; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.notify.Notifications; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Look; +import com.codenameone.examples.lingo.ui.Nav; + +/// The app. It opens on whatever the stored session allows: the mode the user +/// was last in when they are still signed in, the welcome screen when not. +/// +/// Where things are: +/// +/// - `net` -- the session, and the typed clients generated from the contracts in +/// the `shared` module. Nothing else in the app builds a URL. +/// - `live` -- the WebSocket the server pushes changes down, and the WebRTC +/// live classroom. +/// - `notify` -- push notifications, for a phone that is not looking. +/// - `ui` -- shared screens; `learn` -- the learner's tabs, lessons, +/// rewards and certificates; `studio` -- the creator's courses and classes. +/// - `ai` -- the tutor engines and how one is chosen; `speech` -- listening, +/// speaking and scoring pronunciation. +/// - `src/main/css/theme.css` -- every colour, font and margin. +/// - `src/main/l10n` -- every word, in each language the app speaks. +/// - `Prefs` -- what the user chose in Settings. +/// - `Telemetry` -- what is reported about how the app is used, once the user +/// has agreed to it. +public class Lingo extends Lifecycle { + @Override + public void runApp() { + // Before the first screen is built: a screen keeps the look and the + // words it was built with. + Look.apply(); + Lang.apply(); + Telemetry.start(); + Session.start(AppConfig.serverUrl()); + Account.start(); + Nav.launch(); + } + + /// Coming back to the app is when the app asks for its push token, which the platform + /// answers at once when nothing has changed, and when the position is + /// looked for again if going to the background put the search down. + @Override + public void start() { + super.start(); + Notifications.start(); + } + + /// The app is put away, which is the last sure moment to send the usage + /// reports gathered since the last batch. + /// + /// A learner on the road goes on reporting where they are from the + /// background; anyone else's search for the position is put down until + /// the app is back. + @Override + public void stop() { + super.stop(); + Telemetry.flush(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Prefs.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Prefs.java new file mode 100644 index 00000000000..66f4b4dce1f --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Prefs.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.io.Preferences; + +/// What the user has chosen in Settings. +/// +/// Every screen reads and writes a preference through this class and through +/// nothing else, so where the values live is decided in one place: the +/// device's `Preferences`, which survives a restart. The account keeps the +/// same values on the server; `Account` listens at [#onChange] and sends each +/// one as it changes, and puts the account's values in with the setters when +/// it has fetched them. +public final class Prefs { + /// Told when a value changes, with the value's name. + public interface Listener { + void changed(String name); + } + + public static final String LANGUAGE = "language"; + public static final String THEME = "theme"; + public static final String NOTIFY_ASSIGNMENTS = "notifyReminders"; + public static final String NOTIFY_SCHEDULE = "notifyLive"; + public static final String WIFI_ONLY_MODEL = "wifiOnlyModel"; + public static final String CLOUD_TUTOR = "cloudTutor"; + private static final String OWNER = "owner"; + + public static final String THEME_SYSTEM = "system"; + public static final String THEME_LIGHT = "light"; + public static final String THEME_DARK = "dark"; + + private static final String PREFIX = "lingo.pref."; + /// The plain values that are a copy of the account's; see [#ownedBy]. + private static final String[] ACCOUNT_OWNED = {NOTIFY_ASSIGNMENTS, NOTIFY_SCHEDULE, + WIFI_ONLY_MODEL, CLOUD_TUTOR}; + + private static Listener listener; + + private Prefs() { + } + + /// Names the one listener told of every change. A value put in by the + /// listener itself is reported to it like any other, so a listener that + /// stores what it is told must not answer by setting the value again. + public static void onChange(Listener told) { + listener = told; + } + + // -------------------------------------------------------------- appearance + + /// The language chosen, as its two-letter code; empty while the user has + /// chosen none and the device's language decides. + public static String language() { + return text(LANGUAGE, ""); + } + + public static void setLanguage(String code) { + put(LANGUAGE, code); + } + + /// [#THEME_SYSTEM], [#THEME_LIGHT] or [#THEME_DARK]. + public static String theme() { + return text(THEME, THEME_SYSTEM); + } + + public static void setTheme(String theme) { + put(THEME, theme); + } + + // ------------------------------------------------------- notifications + + /// Reminded to practise when today's goal is not done. + public static boolean notifyReminders() { + return flag(NOTIFY_ASSIGNMENTS, true); + } + + public static void setNotifyReminders(boolean on) { + put(NOTIFY_ASSIGNMENTS, on); + } + + /// Told when a live class they booked starts. + public static boolean notifyLive() { + return flag(NOTIFY_SCHEDULE, true); + } + + public static void setNotifyLive(boolean on) { + put(NOTIFY_SCHEDULE, on); + } + + /// Whether the offline tutor waits for Wi-Fi before it downloads. + public static boolean wifiOnlyModel() { + return flag(WIFI_ONLY_MODEL, false); + } + + public static void setWifiOnlyModel(boolean on) { + put(WIFI_ONLY_MODEL, on); + } + + /// Whether a phone with no tutor of its own may send the conversation to + /// the server's cloud tutor. Off until the learner turns it on, as the + /// server's copy of the setting is. + public static boolean cloudTutor() { + return flag(CLOUD_TUTOR, false); + } + + public static void setCloudTutor(boolean on) { + put(CLOUD_TUTOR, on); + } + + /// Says whose device this is now; empty for nobody. When the account + /// changes, the copy of the last account's settings is dropped, so the + /// next person never sends it as their own. How the app looks stays. + public static void ownedBy(String account) { + String owner = account == null ? "" : account; + if (owner.equals(text(OWNER, ""))) { + return; + } + for (String name : ACCOUNT_OWNED) { + Preferences.delete(PREFIX + name); + } + Preferences.set(PREFIX + OWNER, owner); + } + + // ------------------------------------------------------------- the store + + private static String text(String name, String fallback) { + return Preferences.get(PREFIX + name, fallback); + } + + private static boolean flag(String name, boolean fallback) { + return Preferences.get(PREFIX + name, fallback); + } + + private static void put(String name, String value) { + String wanted = value == null ? "" : value.trim(); + if (!wanted.equals(text(name, null))) { + Preferences.set(PREFIX + name, wanted); + changed(name); + } + } + + private static void put(String name, boolean value) { + // Compared with the opposite as the fallback, so a value never stored + // is stored the first time whatever it is. + if (flag(name, !value) != value) { + Preferences.set(PREFIX + name, value); + changed(name); + } + } + + private static void changed(String name) { + if (listener != null) { + listener.changed(name); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Telemetry.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Telemetry.java new file mode 100644 index 00000000000..c6705d88bd5 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/Telemetry.java @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.analytics.Analytics; +import com.codename1.analytics.AnalyticsConsent; +import com.codename1.analytics.AnalyticsEvent; +import com.codename1.analytics.AnalyticsProvider; +import com.codename1.analytics.CodenameOneAnalyticsProvider; +import com.codename1.analytics.LoggingAnalyticsProvider; +import com.codename1.ui.CN; +import com.codenameone.examples.lingo.ui.Lang; + +/// What the app reports about how it is used, and whether it may. +/// +/// This is the only class that talks to `com.codename1.analytics`. A screen +/// says what happened by calling one of the methods here, so the whole +/// vocabulary -- every event name and every parameter -- is in this file, and +/// it is here that the one rule is kept: nothing that says who someone is or +/// where they are ever goes into an event. No name, e-mail address, phone +/// number, voice, what they said or a course id; a count goes +/// as the bracket it falls in. What is known about the user is two things: the +/// mode they are in and the language they read. +/// +/// Nothing is reported until the user has said yes. The library starts with +/// consent withheld and drops every call made without it, so a method here is +/// always safe to call. The answer is asked for once, after the first sign-in +/// on a device ([#asked()], `ui.ConsentForm`), can be changed in Settings at +/// any time ([#allow(boolean)]), and is kept by the library on the device, in +/// `Preferences`, with the made-up id that tells one installation from the +/// next. Deleting the account forgets both ([#forget()]). +/// +/// On a device the reports go to Codename One's own service, which shows them +/// in the developer console. That service knows which app is reporting from +/// the identity a build stamps into it, so the simulator, which has none, only +/// writes what it would have sent to the log. +public final class Telemetry { + private static final String ACCOUNT = "account"; + private static final String LEARN = "learn"; + private static final String COMMUNITY = "community"; + private static final String SETTINGS = "settings"; + + /// The screen reported last, which the next one names as where it came from. + private static String screen; + /// The screen that is showing, reported or not. + private static String showing; + private static String role; + /// The role and the language as they were last reported. + private static String described; + private static boolean started; + + private Telemetry() { + } + + /// Says where the reports go. Called once, when the app starts. + public static void start() { + if (started) { + return; + } + started = true; + if (CN.isSimulator()) { + Analytics.addProvider(new LoggingAnalyticsProvider()); + } else { + Analytics.addProvider(new CodenameOneAnalyticsProvider()); + } + } + + /// Sends the reports to `providers` and nowhere else. For a test, which + /// wants to see what was reported and wants none of it to leave. + public static void use(AnalyticsProvider... providers) { + started = true; + Analytics.clearProviders(); + for (AnalyticsProvider provider : providers) { + Analytics.addProvider(provider); + } + screen = null; + described = null; + } + + // --------------------------------------------------------------- consent + + /// Whether the user has answered, either way. + public static boolean asked() { + return Analytics.getConsent() != null; + } + + /// Whether the user said yes. + public static boolean allowed() { + AnalyticsConsent consent = Analytics.getConsent(); + return consent != null && consent.isAnalytics(); + } + + /// Records the user's answer. A yes covers how the app is used and the + /// errors it runs into; nothing here follows a person or serves an + /// advertisement, and those are never granted. + public static void allow(boolean yes) { + boolean was = allowed(); + Analytics.setConsent(AnalyticsConsent.builder() + .analytics(yes) + .crashReporting(yes) + .personalization(false) + .adStorage(false) + .build()); + if (yes && !was) { + // What was dropped while the answer was no: who is using the app, + // in the two words kept about them, and the screen they are on. + screen = null; + described = null; + describe(); + if (showing != null) { + screen(showing); + } + } + } + + /// Takes the answer back, so that it is asked for again. + public static void unask() { + Analytics.setConsent(null); + } + + /// The account is gone: the installation gets a new id, which cuts what is + /// reported from now on from everything reported before, and whoever signs + /// in next is asked for themselves. + public static void forget() { + // What is waiting was gathered under the id that is about to go, and + // is sent under it. + Analytics.flush(); + Analytics.resetClientId(); + Analytics.setConsent(null); + role = null; + screen = null; + described = null; + } + + /// Sends what is waiting. Reports are gathered and sent a batch at a + /// time; this is for when the app is put away. + public static void flush() { + Analytics.flush(); + } + + // ------------------------------------------------------- screens and who + + /// A screen is showing. `name` is the one the screen was built with, which + /// is not translated and does not change with its title. + public static void screen(String name) { + if (name == null || name.length() == 0) { + return; + } + showing = name; + if (name.equals(screen) || !allowed()) { + return; + } + Analytics.screen(name, screen); + screen = name; + } + + /// The user is in `mode`: learn or studio. + public static void role(String mode) { + role = mode; + describe(); + } + + /// Reports the role and the language, when either is news: the home + /// screen is built again for every change of look, and says its mode each + /// time. + private static void describe() { + if (role == null || !allowed()) { + return; + } + String language = Lang.current(); + String now = role + "/" + language; + if (!now.equals(described)) { + described = now; + Analytics.setUserProperty("role", role); + Analytics.setUserProperty("language", language); + } + } + + // --------------------------------------------------------------- account + + public static void signedIn() { + send(ACCOUNT, "login", "method", "password"); + } + + /// @param reason `user` when they chose to, `expired` when the session + /// ended under them, `deleted` when the account was closed + public static void signedOut(String reason) { + send(ACCOUNT, "logout", "reason", reason); + role = null; + } + + public static void registered() { + send(ACCOUNT, "sign_up", "method", "password"); + } + + // ------------------------------------------------------------------ learn + + /// @param kind phrases, conversation or video + public static void lessonDone(String kind, int score) { + send(LEARN, "lesson_done", "kind", kind, "score", Integer.valueOf(score)); + } + + /// @param engine which tutor answered: system, local, cloud or scripted + public static void tutorTurn(String engine) { + send(LEARN, "tutor_turn", "engine", engine); + } + + public static void modelDownloaded(boolean ok) { + send(LEARN, "model_downloaded", "ok", Boolean.valueOf(ok)); + } + + /// @param kind course, live, pro or tip + public static void purchased(String kind) { + send(COMMUNITY, "purchase", "kind", kind); + } + + public static void liveJoined(boolean host) { + send(COMMUNITY, "live_joined", "host", Boolean.valueOf(host)); + } + + public static void certificateShared() { + send(LEARN, "certificate_shared"); + } + + // -------------------------------------------------------------- settings + + public static void languageChanged(String code) { + send(SETTINGS, "language_changed", "language", code); + describe(); + } + + public static void themeChanged(String theme) { + send(SETTINGS, "theme_changed", "theme", theme); + } + + // ---------------------------------------------------------------- errors + + /// Something failed that the app caught and carried on from. Only what + /// kind of failure it was is reported: a message can quote what the user + /// typed, or the file it was reading. + public static void error(Throwable failed) { + if (failed != null) { + Analytics.crash(failed, failed.getClass().getName(), false); + } + } + + /// Reports `name` with `pairs`: a parameter's name, then its value. + private static void send(String category, String name, Object... pairs) { + AnalyticsEvent.Builder event = AnalyticsEvent.create(name).category(category); + for (int iter = 0; iter + 1 < pairs.length; iter += 2) { + event.param((String) pairs[iter], pairs[iter + 1]); + } + Analytics.event(event.build()); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/CloudTutor.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/CloudTutor.java new file mode 100644 index 00000000000..7f7a5342dc4 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/CloudTutor.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ai; + +import com.codename1.appkit.Net; +import com.codenameone.examples.lingo.api.TutorRequestDto; +import com.codenameone.examples.lingo.api.TutorTurnDto; +import com.codenameone.examples.lingo.net.Api; +import java.util.ArrayList; +import java.util.List; + +/// A partner run by a cloud model, through the Lingo server. Only for a +/// learner who turned it on in Settings: what they say is sent to the +/// server and on to the model's provider. +final class CloudTutor implements TutorEngine { + @Override + public String kind() { + return Tutors.CLOUD; + } + + @Override + public void reply(String languageTag, String level, String scenario, + List turns, final Reply reply) { + Api.learn().tutor(new TutorRequestDto(languageTag, level, scenario, + new ArrayList(turns)), Net.to(answer -> { + if (!answer.available()) { + // The server has no model configured: the scripted + // partner keeps the lesson going. + Tutors.cloudUnavailable(); + new ScriptedTutor().reply(languageTag, level, scenario, turns, reply); + } else { + reply.said(answer.text(), answer.correction()); + } + }, (status, message) -> reply.failed(message))); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/LlmTutor.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/LlmTutor.java new file mode 100644 index 00000000000..62acea039a0 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/LlmTutor.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ai; + +import com.codename1.ai.ChatMessage; +import com.codename1.ai.ChatRequest; +import com.codename1.ai.LlmClient; +import com.codenameone.examples.lingo.api.TutorPrompt; +import com.codenameone.examples.lingo.api.TutorTurnDto; +import java.util.List; + +/// A partner run by a language model on the device: the operating system's +/// own (Apple Intelligence, Gemini Nano) or the one the app downloaded and +/// runs with llama.cpp. Nothing the learner says leaves the phone. +final class LlmTutor implements TutorEngine { + /// The turns sent: a small model's context is short, and the scenario + /// needs only the last few. + static final int RECENT = 12; + + private final LlmClient client; + private final String kind; + + LlmTutor(LlmClient client, String kind) { + this.client = client; + this.kind = kind; + } + + @Override + public String kind() { + return kind; + } + + @Override + public void reply(String languageTag, String level, String scenario, + List turns, final Reply reply) { + ChatRequest.Builder request = ChatRequest.builder() + .addMessage(ChatMessage.system(TutorPrompt.system(languageTag, level, scenario))) + .maxTokens(Integer.valueOf(160)) + .temperature(Float.valueOf(0.7f)); + if (turns.isEmpty()) { + request.addMessage(ChatMessage.user(TutorPrompt.OPENING)); + } + for (int iter = Math.max(0, turns.size() - RECENT); iter < turns.size(); iter++) { + TutorTurnDto turn = turns.get(iter); + request.addMessage("assistant".equals(turn.role()) ? ChatMessage.assistant(turn.text()) + : ChatMessage.user(turn.text())); + } + client.chat(request.build()).ready(response -> { + String[] parts = TutorPrompt.split(response.getText()); + if (parts[0].length() == 0) { + reply.failed("The tutor had nothing to say. Try again."); + } else { + reply.said(parts[0], parts[1]); + } + }).except(error -> reply.failed("The tutor could not answer: " + error.getMessage())); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/ScriptedTutor.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/ScriptedTutor.java new file mode 100644 index 00000000000..bc9e69a1cac --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/ScriptedTutor.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ai; + +import com.codenameone.examples.lingo.api.TutorTurnDto; +import java.util.List; + +/// A partner with no model at all: a short scripted exchange in the lesson's +/// language. It is what a device with no model, no download and no cloud +/// opt-in gets -- and the simulator, and the tests -- so a conversation +/// lesson always runs, if less freely. +final class ScriptedTutor implements TutorEngine { + private static final String[] SPANISH = { + "\u00a1Hola! Bienvenido. \u00bfQu\u00e9 te pongo hoy?", + "Muy bien. \u00bfY para beber?", + "Perfecto. \u00bfAlgo m\u00e1s?", + "Ahora mismo te lo traigo. \u00bfEres de aqu\u00ed?", + "\u00a1Qu\u00e9 bien! \u00bfTe gusta la ciudad?", + "Me alegro. \u00a1Que aproveche!", + }; + private static final String[] FRENCH = { + "Bonjour ! Qu'est-ce que je vous sers ?", + "Tr\u00e8s bien. Et avec \u00e7a ?", + "Parfait. Vous \u00eates en vacances ?", + "C'est super. Vous aimez Paris ?", + "Moi aussi ! Vous avez visit\u00e9 le Louvre ?", + "Bonne journ\u00e9e !", + }; + private static final String[] ENGLISH = { + "Hello! What can I get you today?", + "Great choice. Anything to drink?", + "Perfect. Are you visiting?", + "Lovely. How do you like it here?", + "Glad to hear it. Enjoy your day!", + }; + + @Override + public String kind() { + return Tutors.SCRIPTED; + } + + @Override + public void reply(String languageTag, String level, String scenario, + List turns, Reply reply) { + String[] lines = lines(languageTag); + int said = 0; + for (TutorTurnDto turn : turns) { + if ("assistant".equals(turn.role())) { + said++; + } + } + reply.said(lines[Math.min(said, lines.length - 1)], ""); + } + + static String[] lines(String languageTag) { + if (languageTag != null && languageTag.startsWith("es")) { + return SPANISH; + } + if (languageTag != null && languageTag.startsWith("fr")) { + return FRENCH; + } + return ENGLISH; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/TutorEngine.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/TutorEngine.java new file mode 100644 index 00000000000..63ba99eba9d --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/TutorEngine.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ai; + +import com.codenameone.examples.lingo.api.TutorTurnDto; +import java.util.List; + +/// A conversation partner: something that answers the learner's last turn. +/// [Tutors] picks which one a device uses. +public interface TutorEngine { + /// What answered. + interface Reply { + /// The partner's next line, and a correction of the learner's last + /// one (empty when there was nothing to correct). + void said(String text, String correction); + + /// No answer came; `why` is for the learner. + void failed(String why); + } + + /// Which engine this is: one of the `Tutors` constants. + String kind(); + + /// Answers the conversation so far, on the EDT. An empty `turns` asks + /// the partner to open. + void reply(String languageTag, String level, String scenario, List turns, + Reply reply); +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/Tutors.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/Tutors.java new file mode 100644 index 00000000000..349039635fa --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ai/Tutors.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ai; + +import com.codename1.ai.LlmClient; +import com.codename1.ai.LocalLlmClient; +import com.codename1.ai.SystemLlmClient; +import com.codename1.ai.SystemLlmFeature; +import com.codename1.ai.inference.ModelCache; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.Preferences; +import com.codename1.io.wifi.WiFi; +import com.codename1.util.AsyncResource; +import com.codenameone.examples.lingo.Prefs; + +/// Which conversation partner this device uses, best first: +/// +/// 1. **The operating system's model** -- Apple Intelligence on iOS and +/// macOS, Gemini Nano on Android -- when the device has one ready. +/// Private, free, nothing to download. +/// 2. **A model the app downloads** -- Qwen2.5 0.5B Instruct, 470 MB -- +/// run on the device with llama.cpp. Private once downloaded, and the +/// learner chooses when to fetch it. +/// 3. **The cloud model**, through the server -- only if the learner turned +/// it on in Settings, since what they say then leaves the phone. +/// 4. **A scripted partner**, which always works. +/// +/// [#choose] is that order and nothing else, so a test covers it without a +/// device. +public final class Tutors { + public static final String SYSTEM = "system"; + public static final String LOCAL = "local"; + public static final String CLOUD = "cloud"; + public static final String SCRIPTED = "scripted"; + + /// The model the app downloads. Pinned by digest: iOS refuses an + /// unpinned download, and nobody should run a model that is not the + /// one the app was tested with. + public static final String MODEL_URL = "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF" + + "/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf"; + public static final String MODEL_SHA256 = + "74a4da8c9fdbcd15bd1f6d01d621410d31c6fc00986f5eb687824e7b93d7a9db"; + public static final long MODEL_BYTES = 491400032L; + static final String MODEL_KEY = "lingo-tutor-qwen2.5-0.5b-q4km"; + private static final String MODEL_PATH = "lingoTutorModelPath"; + + private static TutorEngine engine; + /// The server said it has no cloud model; asked again next launch. + private static boolean cloudMissing; + private static AsyncResource downloading; + + private Tutors() { + } + + /// The partner to use, from what this device has. + public static String choose(boolean systemReady, boolean localSupported, + boolean modelDownloaded, boolean cloudAllowed) { + if (systemReady) { + return SYSTEM; + } + if (localSupported && modelDownloaded) { + return LOCAL; + } + if (cloudAllowed) { + return CLOUD; + } + return SCRIPTED; + } + + /// The partner, chosen now. + public static TutorEngine engine() { + String kind = choose(systemReady(), LocalLlmClient.isSupported(), modelPath() != null, + Prefs.cloudTutor() && !cloudMissing); + if (engine != null && engine.kind().equals(kind)) { + return engine; + } + if (SYSTEM.equals(kind)) { + engine = new LlmTutor(LlmClient.system(), SYSTEM); + } else if (LOCAL.equals(kind)) { + engine = new LlmTutor(LlmClient.local(modelPath()).setContextSize(2048), LOCAL); + } else if (CLOUD.equals(kind)) { + engine = new CloudTutor(); + } else { + engine = new ScriptedTutor(); + } + return engine; + } + + /// Who is answering, in words, for the conversation screen. + public static String describe(String kind) { + if (SYSTEM.equals(kind)) { + return "On-device AI"; + } + if (LOCAL.equals(kind)) { + return "Downloaded AI, on this phone"; + } + if (CLOUD.equals(kind)) { + return "Cloud AI"; + } + return "Practice partner"; + } + + static boolean systemReady() { + try { + return SystemLlmClient.getStatus(SystemLlmFeature.CHAT).isAvailable(); + } catch (RuntimeException unavailable) { + return false; + } + } + + /// Whether offering the download makes sense: the device can run it and + /// has no better model of its own. + public static boolean canDownload() { + return LocalLlmClient.isSupported() && !systemReady() && modelPath() == null; + } + + public static boolean downloading() { + return downloading != null; + } + + /// Where the downloaded model is, or null when it is not. + static String modelPath() { + String path = Preferences.get(MODEL_PATH, (String) null); + if (path == null || !FileSystemStorage.getInstance().exists(path)) { + return null; + } + return path; + } + + /// Whether the device is on Wi-Fi as far as it will say: true when it + /// cannot tell, and the download screen asks instead. + public static boolean onWifiOrUnknown() { + if (!WiFi.isInfoSupported()) { + return true; + } + String ssid = WiFi.getCurrentSSID(); + return ssid != null && ssid.length() > 0; + } + + /// Fetches the model. `done` runs on the EDT with true once it is in + /// place, false when the download failed. + public static void download(final com.codename1.util.SuccessCallback done) { + if (downloading != null) { + return; + } + downloading = ModelCache.fetch(MODEL_URL, MODEL_KEY, MODEL_SHA256).ready(source -> { + downloading = null; + Preferences.set(MODEL_PATH, source.getPath()); + engine = null; + com.codenameone.examples.lingo.Telemetry.modelDownloaded(true); + done.onSucess(Boolean.TRUE); + }).except(error -> { + downloading = null; + com.codenameone.examples.lingo.Telemetry.modelDownloaded(false); + done.onSucess(Boolean.FALSE); + }); + } + + /// Deletes the downloaded model, to give the space back. + public static void forgetModel() { + String path = modelPath(); + if (path != null) { + FileSystemStorage.getInstance().delete(path); + } + Preferences.delete(MODEL_PATH); + engine = null; + } + + static void cloudUnavailable() { + cloudMissing = true; + engine = null; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AccountsForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AccountsForm.java new file mode 100644 index 00000000000..89b69424eaa --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AccountsForm.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.AccountChangeDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// The admin's list of accounts, and the roles of each. Registering makes a +/// learner; this is where a teacher is made a creator. The server checks +/// every change again: a non-admin who calls `/api/admin` is refused, +/// whatever the app shows. +public final class AccountsForm { + private AccountsForm() { + } + + public static void show(final Form previous) { + Form form = Ui.form(Lang.tr("Accounts"), "Accounts"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.setName("accounts"); + page.add(new Skeleton(4, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + load(form, page, previous); + } + + private static void load(final Form form, final Container page, final Form previous) { + Api.admin().accounts(Net.to(users -> { + page.removeAll(); + Container list = new Container(BoxLayout.y()); + list.setUIID("LnBlock"); + for (final UserDto u : users) { + Container row = Ui.row(u.creator() ? FontImage.MATERIAL_VIDEO_CAMERA_FRONT + : FontImage.MATERIAL_PERSON, u.displayName(), + u.username() + Ui.DOT + roles(u), u.suspended() + ? Ui.badge(Lang.tr("Suspended"), "LnDraftTag") : null); + list.add(Ui.tap(row, "account-" + u.username(), + e -> account(form, u, () -> show(previous)))); + } + page.add(list); + page.revalidate(); + }, Ui.failed(page, () -> load(form, page, previous)))); + } + + private static void account(Form list, final UserDto u, final Runnable reload) { + Form form = Ui.form(u.displayName(), "Account"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, list); + Container page = Ui.page(); + page.add(Ui.person(u.displayName(), u.username(), null)); + final boolean[] r = {u.learner(), u.creator(), u.admin(), u.suspended()}; + UserDto me = Session.user(); + boolean self = me != null && me.username().equals(u.username()); + Ui.section(page, "Roles"); + Container roles = new Container(BoxLayout.y()); + roles.setUIID("LnBlock"); + roles.add(Ui.row(FontImage.MATERIAL_SCHOOL, Lang.tr("Learner"), + Lang.tr("Takes courses and practises with the tutor"), + Ui.toggle("role-learner", r[0], on -> r[0] = on))); + roles.add(Ui.row(FontImage.MATERIAL_VIDEO_CAMERA_FRONT, Lang.tr("Creator"), + Lang.tr("Publishes courses and holds live classes"), + Ui.toggle("role-creator", r[1], on -> r[1] = on))); + if (!self) { + // Your own admin role and your own account stay as they are; + // the server refuses both changes anyway. + roles.add(Ui.row(FontImage.MATERIAL_ADMIN_PANEL_SETTINGS, Lang.tr("Admin"), + Lang.tr("Grants roles to other accounts"), + Ui.toggle("role-admin", r[2], on -> r[2] = on))); + roles.add(Ui.row(FontImage.MATERIAL_BLOCK, Lang.tr("Suspended"), + Lang.tr("Cannot sign in"), + Ui.toggle("role-suspended", r[3], on -> r[3] = on))); + } + page.add(roles); + Button save = Ui.primary("Save", "saveAccount", e -> Api.admin().changeAccount( + new AccountChangeDto(u.username(), r[0], r[1], r[2], r[3]), Net.to(saved -> { + Ui.say(Lang.tr("{0} saved", saved.displayName())); + reload.run(); + }, Ui::fail))); + page.add(save); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + private static String roles(UserDto u) { + StringBuilder out = new StringBuilder(); + if (u.learner()) { + out.append(Lang.tr("Learner")); + } + if (u.creator()) { + out.append(out.length() == 0 ? "" : ", ").append(Lang.tr("Creator")); + } + if (u.admin()) { + out.append(out.length() == 0 ? "" : ", ").append(Lang.tr("Admin")); + } + return out.toString(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AchievementsForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AchievementsForm.java new file mode 100644 index 00000000000..88ea0b034a1 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/AchievementsForm.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.lingo.api.AchievementDto; +import com.codenameone.examples.lingo.api.StatsDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// The badges: earned ones in gold, the rest grey with how far along they are. +/// The server decides what was earned; the app only shows it. +public final class AchievementsForm { + private AchievementsForm() { + } + + public static void show(Form previous) { + Form form = Ui.form(Lang.tr("Achievements"), "Achievements"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.add(new Skeleton(4, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + Api.learn().stats(Net.to(stats -> Api.learn().achievements(Net.to(list -> { + page.removeAll(); + page.add(level(stats)); + int earned = 0; + for (AchievementDto a : list) { + earned += a.unlocked() ? 1 : 0; + } + page.add(Kit.section(Lang.tr("{0} of {1} badges", "" + earned, "" + list.size()), + null, null)); + Container grid = new Container(new GridLayout(2)); + grid.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + grid.getAllStyles().setPadding(0, 8, 3, 3); + for (AchievementDto a : list) { + grid.add(tile(a)); + } + page.add(grid); + page.revalidate(); + }, Ui.failed(page, null))), Ui.failed(page, null))); + } + + private static Container level(StatsDto s) { + Container card = new Container(new BorderLayout()); + card.setUIID("LnHeroCard"); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("LEVEL {0}", "" + s.level()), "LnHeroKicker")); + words.add(new Label(Lang.tr("{0} XP", "" + s.xp()), "LnDashTitle")); + // levelXp is how far into this level the learner is, nextLevelXp how + // much the level holds. + int into = s.levelXp(); + int span = Math.max(1, s.nextLevelXp()); + words.add(new Label(Lang.tr("{0} XP to level {1}", "" + Math.max(0, span - into), + "" + (s.level() + 1)), "LnDashText")); + card.add(BorderLayout.CENTER, words); + card.add(BorderLayout.EAST, new Kit.Ring("LnGoalRing", "LnGoalTrack", 16, + into / (float) span, "" + s.level())); + card.setName("level"); + return card; + } + + private static Container tile(AchievementDto a) { + Container tile = new Container(BoxLayout.y()); + tile.setUIID("LnBadgeTile"); + tile.setName("badge-" + a.id()); + Label icon = Kit.glyph(icon(a.icon()), a.unlocked() ? "LnBadgeIcon" : "LnBadgeIconLocked", + 5.4f); + tile.add(BorderLayout.centerAbsolute(icon)); + tile.add(Ui.text(a.title(), "LnBadgeName")); + if (a.unlocked()) { + tile.add(Ui.text(a.description(), "LnBadgeText")); + } else { + tile.add(new Label(Math.min(a.progress(), a.goal()) + " / " + a.goal(), + "LnBadgeText")); + tile.add(new Kit.Bar("LnBarGold", a.goal() <= 0 ? 0 + : Math.min(1f, a.progress() / (float) a.goal()))); + } + return tile; + } + + /// The material icon a badge names. + static char icon(String name) { + if ("record_voice_over".equals(name)) { + return FontImage.MATERIAL_RECORD_VOICE_OVER; + } + if ("local_fire_department".equals(name)) { + return FontImage.MATERIAL_LOCAL_FIRE_DEPARTMENT; + } + if ("graphic_eq".equals(name)) { + return FontImage.MATERIAL_GRAPHIC_EQ; + } + if ("forum".equals(name)) { + return FontImage.MATERIAL_FORUM; + } + if ("menu_book".equals(name)) { + return FontImage.MATERIAL_MENU_BOOK; + } + if ("bolt".equals(name)) { + return FontImage.MATERIAL_BOLT; + } + if ("workspace_premium".equals(name)) { + return FontImage.MATERIAL_WORKSPACE_PREMIUM; + } + if ("translate".equals(name)) { + return FontImage.MATERIAL_TRANSLATE; + } + if ("volunteer_activism".equals(name)) { + return FontImage.MATERIAL_VOLUNTEER_ACTIVISM; + } + return FontImage.MATERIAL_STAR; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CatalogTab.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CatalogTab.java new file mode 100644 index 00000000000..f7e18b2c87c --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CatalogTab.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.List; + +/// Every published course, AI-led and community-made, filtered by a row of +/// chips. +final class CatalogTab { + private static final String[] FILTERS = {"all", "mine", "ai", "community"}; + private static final String[] NAMES = {"All", "My courses", "AI tutor", "Community"}; + private static String filter = "all"; + + private CatalogTab() { + } + + static Container build(final Form home) { + final Container page = new Container(BoxLayout.y()); + page.setUIID("LnCanvas"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + page.setName("catalog"); + page.add(new Label(Lang.tr("Courses"), "LnScreenTitle")); + page.add(Ui.text(Lang.tr("Practise with the AI tutor, or learn from people who teach."), + "LnScreenText")); + final Container chips = new Container(BoxLayout.x()); + chips.setUIID("LnScrollX"); + chips.setScrollableX(true); + chips.setScrollVisible(false); + page.add(chips); + final Container grid = new Container(new GridLayout(2)); + grid.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + grid.getAllStyles().setPadding(0, 8, 3, 3); + page.add(grid); + grid.add(new Skeleton(2, "LnSkeleton")); + final Runnable[] show = new Runnable[1]; + show[0] = () -> { + chips.removeAll(); + for (int iter = 0; iter < FILTERS.length; iter++) { + final String f = FILTERS[iter]; + Button chip = new Button(Lang.tr(NAMES[iter]), + f.equals(filter) ? "LnKindTag" : "LnEngine"); + chip.setName("filter-" + f); + chip.addActionListener(e -> { + filter = f; + show[0].run(); + }); + chips.add(chip); + } + grid.removeAll(); + int count = 0; + for (final CourseDto c : LearnHome.courses) { + if (matches(c)) { + grid.add(Kit.courseCard(c, 0, () -> CourseForm.show(c.id(), home))); + count++; + } + } + if (count == 0) { + grid.setLayout(BoxLayout.y()); + grid.add(Ui.empty(com.codename1.ui.FontImage.MATERIAL_SCHOOL, + Lang.tr("Nothing here yet"), + Lang.tr("Enrol in a course and it shows up here."))); + } else { + grid.setLayout(new GridLayout(2)); + } + page.revalidate(); + }; + Api.learn().courses(Net.to((List list) -> { + LearnHome.courses = list; + show[0].run(); + }, Ui.failed(grid, null))); + return page; + } + + private static boolean matches(CourseDto c) { + if ("mine".equals(filter)) { + return c.enrolled() || c.owned(); + } + if ("ai".equals(filter)) { + return "ai".equals(c.kind()); + } + if ("community".equals(filter)) { + return !"ai".equals(c.kind()); + } + return true; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CertificatesForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CertificatesForm.java new file mode 100644 index 00000000000..2e7db922d75 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CertificatesForm.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.Log; +import com.codename1.pdf.ui.PdfViewer; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.util.Base64; +import com.codenameone.examples.lingo.api.CertificateDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.io.OutputStream; + +/// Certificates of completion. Each is a PDF the server built and signed +/// with its key; the app shows it with the built-in PDF viewer, shares the +/// file, and asks the server to check the signature -- which anyone can do, +/// signed in or not, at the address printed on the certificate. +public final class CertificatesForm { + private CertificatesForm() { + } + + public static void show(final Form previous) { + final Form form = Ui.form(Lang.tr("Certificates"), "Certificates"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.setName("certificates"); + page.add(new Skeleton(3, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + Api.learn().certificates(Net.to(list -> { + page.removeAll(); + if (list.isEmpty()) { + page.add(Ui.empty(FontImage.MATERIAL_WORKSPACE_PREMIUM, + Lang.tr("No certificates yet"), + Lang.tr("Finish every lesson of a course to earn a signed certificate."))); + } + for (final CertificateDto c : list) { + Container card = new Container(new BorderLayout()); + card.setUIID("LnCert"); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("CERTIFICATE OF COMPLETION"), "LnCertKicker")); + words.add(Ui.text(c.courseTitle(), "LnCertTitle")); + words.add(new Label(Languages.name(c.language()) + Ui.DOT + Ui.day(c.issuedAt()) + + Ui.DOT + Ui.duration(c.minutes()), "LnCertMeta")); + card.add(BorderLayout.CENTER, words); + card.add(BorderLayout.EAST, BorderLayout.centerAbsolute( + Kit.glyph(FontImage.MATERIAL_WORKSPACE_PREMIUM, "LnCertSeal", 8))); + Ui.tap(card, "certificate-" + c.id(), e -> open(c.id(), c.courseTitle(), form)); + page.add(card); + } + page.revalidate(); + }, Ui.failed(page, null))); + } + + /// Shows one certificate, with its signature checked. + public static void open(final String id, final String title, final Form previous) { + final Form form = Ui.form(title, "Certificate"); + Ui.back(form, previous); + form.add(BorderLayout.CENTER, new Skeleton(1, "LnSkeleton")); + final Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + form.add(BorderLayout.SOUTH, foot); + form.show(); + Api.learn().certificatePdf(id, Net.to(pdf -> { + final byte[] bytes = Base64.decode(pdf.pdf().getBytes()); + form.getContentPane().removeAll(); + try { + PdfViewer viewer = new PdfViewer(bytes); + viewer.setUIID("LnPdf"); + viewer.setName("pdf"); + form.add(BorderLayout.CENTER, viewer); + } catch (java.io.IOException unreadable) { + form.add(BorderLayout.CENTER, Ui.empty(FontImage.MATERIAL_ERROR, + Lang.tr("This certificate could not be shown"), null)); + } + form.add(BorderLayout.SOUTH, foot); + final Label status = Kit.pill(FontImage.MATERIAL_HOURGLASS_TOP, + Lang.tr("Checking the signature..."), "LnEngine"); + status.setName("verified"); + foot.add(BorderLayout.west(status)); + Api.learn().verify(id, Net.to(v -> { + if (v.valid() && v.wholeDocument()) { + status.setUIID("LnVerified"); + status.setText(Lang.tr("Genuine, signed by {0}", v.signer())); + FontImage.setMaterialIcon(status, FontImage.MATERIAL_VERIFIED, 3); + } else { + status.setText(Lang.tr("The signature does not match")); + FontImage.setMaterialIcon(status, FontImage.MATERIAL_GPP_BAD, 3); + } + foot.revalidate(); + }, (code, message) -> status.setText(message))); + Button share = Ui.primary(Lang.tr("Share certificate"), "share", e -> share(bytes, id)); + FontImage.setMaterialIcon(share, FontImage.MATERIAL_IOS_SHARE, 3.6f); + foot.add(share); + form.revalidate(); + }, Ui::fail)); + } + + private static void share(byte[] pdf, String id) { + String path = FileSystemStorage.getInstance().getAppHomePath() + "lingo-certificate-" + + id + ".pdf"; + try (OutputStream out = FileSystemStorage.getInstance().openOutputStream(path)) { + out.write(pdf); + } catch (java.io.IOException failed) { + Log.e(failed); + Ui.say(Lang.tr("The certificate could not be saved")); + return; + } + if (!CN.isNativeShareSupported()) { + CN.execute(path); + } else { + com.codenameone.examples.lingo.Telemetry.certificateShared(); + CN.share(Lang.tr("My Lingo certificate"), path, "application/pdf"); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Checkout.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Checkout.java new file mode 100644 index 00000000000..69ef2224906 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Checkout.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Label; +import com.codename1.ui.Sheet; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.PurchaseDto; +import com.codenameone.examples.lingo.api.ReceiptDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// Paying: a course, a seat in a live class, Pro, or a tip. +/// +/// The sample pays with a **simulated** card, which the server records as a +/// real receipt and splits with the creator (70% to them, 30% to the +/// platform). A real app replaces [#pay] with a payment provider -- the +/// platform's in-app purchase through `CommerceManager` for digital goods on +/// iOS and Android, a card processor for the rest -- and the server checks +/// the provider's receipt before it records one. +public final class Checkout { + /// What a successful payment calls. + public interface Paid { + void paid(ReceiptDto receipt); + } + + private Checkout() { + } + + public static void show(String kind, String targetId, int cents, String title, + String detail, Paid paid) { + Sheet sheet = new Sheet(null, Lang.tr("Checkout")); + Container c = sheet.getContentPane(); + c.setLayout(BoxLayout.y()); + c.setName("checkout"); + c.add(Ui.text(title, "LnCourseTitle")); + if (detail != null) { + c.add(Ui.text(detail, "LnCourseMeta")); + } + Container total = new Container(new BorderLayout()); + total.add(BorderLayout.CENTER, new Label(Lang.tr("Total"), "LnCourseMeta")); + total.add(BorderLayout.EAST, new Label(Kit.money(cents), "LnMoney")); + c.add(total); + Label card = Kit.pill(FontImage.MATERIAL_CREDIT_CARD, Lang.tr("Demo card ending 4242"), + "LnEngine"); + c.add(BorderLayout.west(card)); + if (!"pro".equals(kind)) { + c.add(Ui.text(Lang.tr("70% goes to the creator."), "LnCourseMeta")); + } + Button pay = Ui.primary(Lang.tr("Pay {0}", Kit.money(cents)), "pay", null); + pay.addActionListener(e -> { + pay.setEnabled(false); + pay(kind, targetId, cents, receipt -> { + sheet.back(); + Ui.say(Lang.tr("Payment complete")); + paid.paid(receipt); + }, () -> pay.setEnabled(true)); + }); + c.add(pay); + sheet.show(); + } + + static void pay(String kind, String targetId, int cents, Paid paid, Runnable failed) { + Api.community().purchase(new PurchaseDto(kind, targetId, cents, "simulated"), + Net.to(r -> { + com.codenameone.examples.lingo.Telemetry.purchased(kind); + paid.paid(r); + }, (status, message) -> { + Ui.fail(status, message); + failed.run(); + })); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/ConversationLesson.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/ConversationLesson.java new file mode 100644 index 00000000000..56e433a8926 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/ConversationLesson.java @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codenameone.examples.lingo.ai.TutorEngine; +import com.codenameone.examples.lingo.ai.Tutors; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.TutorTurnDto; +import com.codenameone.examples.lingo.speech.Voice; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.ArrayList; +import java.util.List; + +/// A role-play with the AI tutor: a scene, then turns. The learner speaks +/// (or types), the tutor answers aloud in the lesson's language and, when +/// the learner slipped, adds a correction under its reply. +/// +/// Who answers is [Tutors]' choice -- the phone's own model, the one the app +/// downloaded, the cloud (only when the learner allowed it) or a scripted +/// partner -- and the screen says which, so nobody wonders where their voice +/// went. +final class ConversationLesson { + /// The learner's turns that make a lesson. + static final int TURNS = 4; + + private final CourseDto course; + private final LessonDto lesson; + private final Form previous; + private final List turns = new ArrayList(); + private final long started = System.currentTimeMillis(); + private final TutorEngine engine = Tutors.engine(); + private int said; + private int fixes; + private boolean waiting; + + private Form form; + private Kit.Bar bar; + private Container thread; + private Container foot; + private Label typing; + + private ConversationLesson(CourseDto course, LessonDto lesson, Form previous) { + this.course = course; + this.lesson = lesson; + this.previous = previous; + } + + static void show(CourseDto course, LessonDto lesson, Form previous) { + new ConversationLesson(course, lesson, previous).build(); + } + + private void build() { + form = Lessons.form("ConversationLesson"); + form.setUIID("LnThread"); + form.getContentPane().setUIID("LnThread"); + bar = new Kit.Bar("LnBar", 0); + bar.setPreferredW(CN.convertToPixels(40)); + form.add(BorderLayout.NORTH, Lessons.top(form, lesson, bar, previous)); + thread = new Container(BoxLayout.y()); + thread.setUIID("LnThread"); + thread.setScrollableY(true); + thread.setScrollVisible(false); + thread.setName("thread"); + Container engineRow = new Container(new FlowLayout(Component.CENTER)); + Label who = Kit.pill(engineIcon(), Lang.tr(Tutors.describe(engine.kind())), "LnEngine"); + who.setName("engine"); + engineRow.add(who); + thread.add(engineRow); + Container scene = new Container(BoxLayout.y()); + scene.setUIID("LnScene"); + scene.add(new Label(lesson.title(), "LnStepTitle")); + scene.add(Ui.text(lesson.scenario() == null || lesson.scenario().length() == 0 + ? lesson.summary() : lesson.scenario(), "LnCourseMeta")); + thread.add(scene); + if (Tutors.canDownload() && !Tutors.downloading()) { + Container offer = Ui.row(FontImage.MATERIAL_DOWNLOAD_FOR_OFFLINE, + Lang.tr("Get the offline AI tutor"), + Lang.tr("Runs on this phone. Free, private, 470 MB."), null); + Ui.tap(offer, "offer-model", e -> TutorForm.show(form)); + offer.setUIID("LnScene"); + thread.add(offer); + } + typing = new Label(Lang.tr("Typing..."), "LnTyping"); + form.add(BorderLayout.CENTER, thread); + foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + form.add(BorderLayout.SOUTH, foot); + form.show(); + ask(); + } + + private char engineIcon() { + String kind = engine.kind(); + if (Tutors.CLOUD.equals(kind)) { + return FontImage.MATERIAL_CLOUD; + } + if (Tutors.SCRIPTED.equals(kind)) { + return FontImage.MATERIAL_CHAT; + } + return FontImage.MATERIAL_PHONE_IPHONE; + } + + /// The tutor's turn. + private void ask() { + waiting = true; + thread.add(typing); + compose(); + form.revalidate(); + thread.scrollComponentToVisible(typing); + com.codenameone.examples.lingo.Telemetry.tutorTurn(engine.kind()); + engine.reply(course.language(), course.level(), lesson.scenario(), turns, + new TutorEngine.Reply() { + @Override + public void said(String text, String correction) { + waiting = false; + typing.remove(); + if (correction != null && correction.length() > 0) { + fixes++; + com.codename1.components.SpanLabel fix = Ui.text( + Lang.tr("Better: {0}", correction), "LnFix"); + fix.setName("fix"); + thread.add(fix); + } + turns.add(new TutorTurnDto("assistant", text)); + thread.add(bubble(text, false)); + Voice.speak(text, course.language(), false); + compose(); + form.revalidate(); + // After the layout that gives the wrapped bubble its + // height, or the scroll stops short of its last line. + com.codename1.ui.CN.callSerially(() -> { + thread.revalidate(); + thread.scrollComponentToVisible( + thread.getComponentAt(thread.getComponentCount() - 1)); + }); + } + + @Override + public void failed(String why) { + waiting = false; + typing.remove(); + Ui.say(why); + compose(); + form.revalidate(); + } + }); + } + + private Container bubble(final String text, boolean mine) { + Container b = new Container(new BorderLayout()); + b.setUIID(mine ? "LnBubbleMe" : "LnBubbleTutor"); + b.setName(mine ? "said" : "tutor-said"); + b.add(BorderLayout.CENTER, Ui.text(text, mine ? "LnBubbleTextMe" : "LnBubbleText")); + if (!mine && Voice.canSpeak()) { + Button again = new Button("", "LnBubbleSpeak"); + FontImage.setMaterialIcon(again, FontImage.MATERIAL_VOLUME_UP, 3.6f); + again.addActionListener(e -> Voice.speak(text, course.language(), false)); + b.add(BorderLayout.EAST, BorderLayout.north(again)); + } + return b; + } + + /// The learner's turn: the microphone, or a field where there is none, + /// and the way out once enough was said. + private void compose() { + foot.removeAll(); + if (said >= TURNS && !waiting) { + foot.add(Ui.primary(Lang.tr("Finish conversation"), "finish", e -> finish())); + foot.add(Ui.link(Lang.tr("Keep talking"), "more", e -> { + said = -100; + compose(); + form.revalidate(); + })); + return; + } + Container row = new Container(new BorderLayout()); + final TextField field = new TextField("", Lang.tr("Reply in {0}", + com.codenameone.examples.lingo.api.Languages.name(course.language()))); + field.setUIID("LnTypeField"); + field.setName("reply"); + field.setEnabled(!waiting); + row.add(BorderLayout.CENTER, field); + final Button send = new Button("", "LnMic"); + send.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + send.getAllStyles().setPadding(3, 3, 3, 3); + send.getAllStyles().setMargin(0, 0, 4, 0); + send.setEnabled(!waiting); + row.add(BorderLayout.EAST, BorderLayout.centerAbsolute(send)); + if (Voice.canListen()) { + send.setName("mic"); + FontImage.setMaterialIcon(send, FontImage.MATERIAL_MIC, 4.4f); + send.addActionListener(e -> { + if (field.getText().trim().length() > 0) { + say(field.getText()); + return; + } + send.setUIID("LnMicLive"); + Voice.listen(course.language(), new Voice.Heard() { + @Override + public void partial(String text) { + field.setText(text); + } + + @Override + public void heard(String text, float confidence, String[] alternatives) { + say(text); + } + + @Override + public void nothing(String why) { + send.setUIID("LnMic"); + Ui.say(why); + } + }); + }); + } else { + send.setName("send"); + FontImage.setMaterialIcon(send, FontImage.MATERIAL_SEND, 4.4f); + send.addActionListener(e -> say(field.getText())); + } + field.setDoneListener(e -> say(field.getText())); + foot.add(row); + if (said > 0 && said < TURNS) { + bar.setValue(said / (float) TURNS); + } + } + + private void say(String text) { + if (waiting || text == null || text.trim().length() == 0) { + return; + } + said++; + bar.setValue(Math.min(1f, Math.max(0, said) / (float) TURNS)); + turns.add(new TutorTurnDto("user", text.trim())); + thread.add(bubble(text.trim(), true)); + ask(); + } + + private void finish() { + int learner = 0; + for (TutorTurnDto t : turns) { + if ("user".equals(t.role())) { + learner++; + } + } + int score = Math.max(50, 100 - fixes * 100 / Math.max(1, learner) / 2); + Lessons.finish(form, course, lesson, score, + (int) ((System.currentTimeMillis() - started) / 1000), learner, previous); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CourseForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CourseForm.java new file mode 100644 index 00000000000..84844b20356 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/CourseForm.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.plaf.UIManager; +import com.codenameone.examples.lingo.api.CourseDetailDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// A course: its coloured header, then its lessons as a path -- done ones +/// ticked, the next one outlined, the rest locked until it is done. +public final class CourseForm { + private CourseForm() { + } + + /// Opens the course's next lesson straight away: the home screen's + /// "Practice now". + public static void continueCourse(String courseId, final Form previous) { + Api.learn().course(courseId, Net.to(detail -> { + LessonDto next = next(detail); + if (next == null) { + show(courseId, previous); + } else { + Lessons.start(detail.course(), next, previous); + } + }, Ui::fail)); + } + + public static void show(final String courseId, final Form previous) { + final Form form = Ui.form("", "Course"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.add(new Skeleton(5, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + load(form, page, courseId, previous); + } + + private static void load(final Form form, final Container page, final String courseId, + final Form previous) { + Api.learn().course(courseId, Net.to(detail -> fill(form, page, detail, previous), + Ui.failed(page, () -> load(form, page, courseId, previous)))); + } + + private static void fill(final Form form, final Container page, final CourseDetailDto detail, + final Form previous) { + final CourseDto course = detail.course(); + page.removeAll(); + int accent = UIManager.getInstance().getComponentStyle(Kit.cover(course.accent())) + .getBgColor(); + form.getToolbar().getAllStyles().setBgColor(accent); + form.getToolbar().getAllStyles().setBgTransparency(255); + Container head = new Container(BoxLayout.y()); + head.setUIID("LnCourseHead"); + head.getAllStyles().setBgColor(accent); + Container tags = new Container(BoxLayout.x()); + tags.add(new Label(Languages.name(course.language()) + Ui.DOT + course.level(), + "LnCoverTag")); + head.add(tags); + head.add(Ui.text(course.title(), "LnCourseHeadTitle")); + head.add(Ui.text(course.summary(), "LnCourseHeadText")); + String by = "ai".equals(course.kind()) ? Lang.tr("Led by the AI tutor") + : Lang.tr("by {0}", course.creatorName()); + head.add(new Label(by + Ui.DOT + Lang.tr("{0} lessons", "" + course.lessons()) + Ui.DOT + + Ui.duration(course.minutes()), "LnCourseHeadMeta")); + if (course.enrolled() && course.lessons() > 0) { + Kit.Bar bar = new Kit.Bar("LnBarGold", course.completedLessons() + / (float) course.lessons()); + head.add(bar); + } + page.add(head); + + LessonDto next = next(detail); + page.add(Kit.section("Lessons", null, null)); + int position = 1; + for (final LessonDto lesson : detail.lessons()) { + page.add(step(form, course, lesson, lesson == next, position++, + course.enrolled() || course.owned())); + } + if (!"ai".equals(course.kind())) { + page.add(Kit.section("Community", null, null)); + Container actions = new Container(BoxLayout.y()); + actions.add(Ui.row(FontImage.MATERIAL_FORUM, Lang.tr("Questions and answers"), + Lang.tr("Ask the creator and other learners"), null)); + Ui.tap((Container) actions.getComponentAt(0), "qa", e -> QaForm.show(course, form)); + if (!course.owned() && course.creator() != null && course.creator().length() > 0) { + actions.add(Ui.row(FontImage.MATERIAL_VOLUNTEER_ACTIVISM, + Lang.tr("Tip {0}", course.creatorName()), + Lang.tr("Say thanks with $2. All of it goes to them."), null)); + Ui.tap((Container) actions.getComponentAt(1), "tip", e -> Checkout.show("tip", + course.id(), 200, Lang.tr("A tip for {0}", course.creatorName()), + course.title(), r -> Ui.say(Lang.tr("Thank you for supporting {0}", + course.creatorName())))); + } + Container wrap = new Container(BoxLayout.y()); + wrap.setUIID("LnBlock"); + wrap.add(actions); + page.add(wrap); + } + Component spacer = new Label(" "); + spacer.setPreferredH(CN.convertToPixels(4)); + page.add(spacer); + + Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + Button action; + if (course.enrolled() || course.owned()) { + if (next == null) { + action = Ui.primary(Lang.tr("Practise again"), "start", e -> Lessons.start(course, + detail.lessons().get(0), form)); + } else { + action = Ui.primary(next.position() == 1 && course.completedLessons() == 0 + ? Lang.tr("Start course") : Lang.tr("Continue: {0}", next.title()), + "start", null); + final LessonDto go = next; + action.addActionListener(e -> Lessons.start(course, go, form)); + } + } else if (course.priceCents() > 0) { + action = Ui.primary(Lang.tr("Buy for {0}", Kit.money(course.priceCents())), "buy", + e -> Checkout.show("course", course.id(), course.priceCents(), course.title(), + Lang.tr("Lifetime access, by {0}", course.creatorName()), + r -> show(course.id(), previous))); + } else { + action = Ui.primary(Lang.tr("Enrol for free"), "enroll", null); + action.addActionListener(e -> Api.learn().enroll(course.id(), Net.to(c -> { + Ui.say(Lang.tr("You're enrolled. Let's start!")); + show(course.id(), previous); + }, Ui::fail))); + } + foot.add(action); + if (form.getContentPane().getComponentCount() > 1) { + Component old = ((BorderLayout) form.getContentPane().getLayout()).getSouth(); + if (old != null) { + old.remove(); + } + } + form.add(BorderLayout.SOUTH, foot); + form.revalidate(); + } + + private static Container step(final Form form, final CourseDto course, final LessonDto lesson, + boolean isNext, int position, boolean open) { + Container row = new Container(new BorderLayout()); + row.setUIID("LnStep"); + row.setName("lesson-" + lesson.id()); + Label node; + if (lesson.completed()) { + node = Kit.glyph(FontImage.MATERIAL_CHECK, "LnStepNodeDone", 3.4f); + } else if (lesson.locked() || !open) { + node = Kit.glyph(FontImage.MATERIAL_LOCK, "LnStepNodeLocked", 3.4f); + } else { + node = Kit.glyph(icon(lesson.kind()), "LnStepNode", 3.4f); + } + row.add(BorderLayout.WEST, BorderLayout.centerAbsolute(node)); + Container card = new Container(new BorderLayout()); + card.setUIID(isNext && open ? "LnStepCardNext" : "LnStepCard"); + Container words = new Container(BoxLayout.y()); + words.add(Ui.text(lesson.title(), "LnStepTitle")); + // A done lesson shows its best score instead of what it takes, so the + // line stays one line. + String meta = kindName(lesson.kind()) + Ui.DOT + + (lesson.completed() && lesson.bestScore() > 0 + ? Lang.tr("best {0}%", "" + lesson.bestScore()) + : Ui.duration(lesson.minutes()) + Ui.DOT + "+" + lesson.xp() + " XP"); + words.add(Ui.text(meta, "LnStepMeta")); + card.add(BorderLayout.CENTER, words); + if (isNext && open) { + card.add(BorderLayout.EAST, BorderLayout.centerAbsolute( + Kit.glyph(FontImage.MATERIAL_PLAY_CIRCLE, "LnSectionLink", 5.4f))); + } + row.add(BorderLayout.CENTER, card); + if (open && !lesson.locked()) { + Ui.tap(row, "open-" + lesson.id(), e -> Lessons.start(course, lesson, form)); + } + return row; + } + + static LessonDto next(CourseDetailDto detail) { + for (LessonDto lesson : detail.lessons()) { + if (!lesson.completed()) { + return lesson; + } + } + return null; + } + + static char icon(String kind) { + if ("conversation".equals(kind)) { + return FontImage.MATERIAL_FORUM; + } + if ("video".equals(kind)) { + return FontImage.MATERIAL_PLAY_ARROW; + } + return FontImage.MATERIAL_RECORD_VOICE_OVER; + } + + static String kindName(String kind) { + if ("conversation".equals(kind)) { + return Lang.tr("Conversation"); + } + if ("video".equals(kind)) { + return Lang.tr("Video"); + } + return Lang.tr("Pronunciation"); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Kit.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Kit.java new file mode 100644 index 00000000000..d7f99a4ddc8 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Kit.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Graphics; +import com.codename1.ui.Label; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// The pieces the learning screens are built from: progress drawn as a bar +/// or a ring, a course's coloured cover, prices. +public final class Kit { + private Kit() { + } + + /// A rounded progress bar. Its colours are its style's: the text colour + /// fills, the background colour is the track. + public static final class Bar extends Component { + private float value; + + public Bar(String uiid, float value) { + setUIID(uiid); + this.value = value; + getAllStyles().setBgTransparency(0); + setFocusable(false); + } + + public void setValue(float value) { + this.value = value; + repaint(); + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(CN.convertToPixels(20), CN.convertToPixels(1.6f)); + } + + @Override + public void paint(Graphics g) { + Style theme = UIManager.getInstance().getComponentStyle(getUIID()); + int x = getX(); + int y = getY(); + int w = getWidth(); + int h = getHeight(); + boolean aa = g.isAntiAliased(); + g.setAntiAliased(true); + g.setColor(theme.getBgColor()); + g.fillRoundRect(x, y, w, h, h, h); + int filled = (int) (w * Math.max(0f, Math.min(1f, value))); + if (filled > 0) { + g.setColor(theme.getFgColor()); + g.fillRoundRect(x, y, Math.max(filled, h), h, h, h); + } + g.setAntiAliased(aa); + } + } + + /// A ring that fills clockwise from the top, with a number in its middle. + /// The fill is the text colour of `uiid`, the track the text colour of + /// `trackUiid`. + public static final class Ring extends Component { + private float value; + private String text; + private final String trackUiid; + private final float size; + + public Ring(String uiid, String trackUiid, float sizeMm, float value, String text) { + setUIID(uiid); + this.trackUiid = trackUiid; + this.size = sizeMm; + this.value = value; + this.text = text; + setFocusable(false); + } + + public void set(float value, String text) { + this.value = value; + this.text = text; + repaint(); + } + + @Override + protected Dimension calcPreferredSize() { + int s = CN.convertToPixels(size); + return new Dimension(s, s); + } + + @Override + public void paint(Graphics g) { + int s = Math.min(getWidth(), getHeight()); + int x = getX() + (getWidth() - s) / 2; + int y = getY() + (getHeight() - s) / 2; + int stroke = Math.max(2, s / 9); + boolean aa = g.isAntiAliased(); + g.setAntiAliased(true); + g.setColor(UIManager.getInstance().getComponentStyle(trackUiid).getFgColor()); + g.fillArc(x, y, s, s, 0, 360); + int fill = getStyle().getFgColor(); + int sweep = (int) (360 * Math.max(0f, Math.min(1f, value))); + if (sweep > 0) { + g.setColor(fill); + g.fillArc(x, y, s, s, 90, -sweep); + } + // The hole: whatever the ring sits on. + Component under = getParent(); + int ground = 0xffffff; + while (under != null) { + Style st = under.getStyle(); + if ((st.getBgTransparency() & 0xff) != 0) { + ground = st.getBgColor(); + break; + } + under = under.getParent(); + } + g.setColor(ground); + g.fillArc(x + stroke, y + stroke, s - 2 * stroke, s - 2 * stroke, 0, 360); + g.setAntiAliased(aa); + if (text != null) { + g.setColor(fill); + g.setFont(getStyle().getFont()); + int tw = g.getFont().stringWidth(text); + g.drawString(text, x + (s - tw) / 2, y + (s - g.getFont().getHeight()) / 2); + } + } + } + + /// The style of a course's colour. + public static String cover(String accent) { + if ("coral".equals(accent)) { + return "LnCoverCoral"; + } + if ("teal".equals(accent)) { + return "LnCoverTeal"; + } + if ("amber".equals(accent)) { + return "LnCoverAmber"; + } + if ("rose".equals(accent)) { + return "LnCoverRose"; + } + if ("sky".equals(accent)) { + return "LnCoverSky"; + } + return "LnCoverIndigo"; + } + + /// The coloured top of a course card: the language's code, large, and + /// the level on a tag. + public static Container coverOf(CourseDto course) { + Container cover = new Container(new BorderLayout()); + cover.setUIID(cover(course.accent())); + Label code = new Label(Languages.code(course.language()), "LnCoverTag"); + code.getAllStyles().setFgColor(0xffffff); + Label level = new Label(course.level(), "LnCoverTag"); + Label big = new Label("", "LnCoverTag"); + big.getAllStyles().setBgTransparency(0); + FontImage.setMaterialIcon(big, "ai".equals(course.kind()) ? FontImage.MATERIAL_AUTO_AWESOME + : FontImage.MATERIAL_GROUPS, 7); + cover.add(BorderLayout.NORTH, BorderLayout.west(code).add(BorderLayout.EAST, level)); + cover.add(BorderLayout.SOUTH, BorderLayout.east(big)); + return cover; + } + + /// A price in dollars, or "Free". + public static String money(int cents) { + if (cents <= 0) { + return Lang.tr("Free"); + } + return amount(cents); + } + + /// An amount as money even when it is nothing: `$0.00` of earnings is + /// not "Free". + public static String amount(int cents) { + int c = cents % 100; + return "$" + (cents / 100) + "." + (c < 10 ? "0" : "") + c; + } + + public static Label price(CourseDto course) { + if (course.owned() || course.enrolled()) { + return new Label(Lang.tr("Yours"), "LnPriceFree"); + } + return new Label(money(course.priceCents()), course.priceCents() <= 0 ? "LnPriceFree" + : "LnPrice"); + } + + /// A card for a course in a row or a list: cover, title, what it holds, + /// progress when it was started. + public static Container courseCard(CourseDto course, float widthMm, Runnable open) { + Container body = new Container(BoxLayout.y()); + body.setUIID("LnCourseBody"); + body.add(Ui.text(course.title(), "LnCourseTitle")); + // A half-width card: the count alone, the course page has the time. + body.add(new Label(Lang.tr("{0} lessons", "" + course.lessons()), "LnCourseMeta")); + if (course.enrolled() && course.lessons() > 0) { + body.add(new Bar("LnBar", course.completedLessons() / (float) course.lessons())); + } else { + Container foot = new Container(new BorderLayout()); + String by = "ai".equals(course.kind()) ? Lang.tr("AI tutor") + : Lang.tr("by {0}", course.creatorName()); + foot.add(BorderLayout.CENTER, Ui.text(by, "LnCourseBy")); + foot.add(BorderLayout.EAST, price(course)); + body.add(foot); + } + Container card = BorderLayout.north(coverOf(course)).add(BorderLayout.CENTER, body); + card.setUIID("LnCourseCard"); + card.setName("card-" + course.id()); + if (widthMm > 0) { + card.setPreferredW(CN.convertToPixels(widthMm)); + } + Ui.tap(card, "course-" + course.id(), e -> open.run()); + return card; + } + + /// A section heading, with a link to the rest on its right. + public static Container section(String title, String link, Runnable onLink) { + Container top = new Container(new BorderLayout()); + top.setUIID("LnSectionTop"); + top.add(BorderLayout.CENTER, new Label(Lang.tr(title), "LnSectionTitle")); + if (link != null) { + Button more = new Button(Lang.tr(link), "LnSectionLink"); + more.setName("more-" + title); + more.addActionListener(e -> onLink.run()); + top.add(BorderLayout.EAST, more); + } + return top; + } + + /// A label with only an icon. + public static Label glyph(char icon, String uiid, float mm) { + Label l = new Label("", uiid); + // On a transparent ground, for the reason [#pill] gives. + com.codename1.ui.plaf.Style glyph = new com.codename1.ui.plaf.Style(l.getUnselectedStyle()); + glyph.setBgTransparency(0); + l.setIcon(FontImage.createMaterial(icon, glyph, mm)); + return l; + } + + /// A pill with an icon and words. + public static Label pill(char icon, String text, String uiid) { + Label l = new Label(text, uiid); + // Drawn on a transparent ground: a pill's colour is its border image, + // and an icon taking the style's background paints a square over it. + com.codename1.ui.plaf.Style glyph = new com.codename1.ui.plaf.Style(l.getUnselectedStyle()); + glyph.setBgTransparency(0); + l.setIcon(FontImage.createMaterial(icon, glyph, 3)); + l.setGap(CN.convertToPixels(0.8f)); + return l; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LeaderboardForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LeaderboardForm.java new file mode 100644 index 00000000000..397eb5fe9ff --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LeaderboardForm.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.LeaderEntryDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// Who earned the most experience. Only display names are shown. +public final class LeaderboardForm { + private LeaderboardForm() { + } + + public static void show(Form previous) { + Form form = Ui.form(Lang.tr("Leaderboard"), "Leaderboard"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.setName("leaderboard"); + page.add(new Skeleton(6, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + Api.learn().leaderboard(Net.to(list -> { + page.removeAll(); + page.add(Ui.text(Lang.tr("Earn XP in lessons to climb. Keep your streak for " + + "bonus freezes."), "LnScreenText")); + for (LeaderEntryDto e : list) { + page.add(row(e)); + } + page.revalidate(); + }, Ui.failed(page, null))); + } + + private static Container row(LeaderEntryDto e) { + Container row = new Container(new BorderLayout()); + row.setUIID(e.me() ? "LnLeaderMe" : "LnLeader"); + row.setName(e.me() ? "leader-me" : "leader-" + e.rank()); + Label rank; + if (e.rank() <= 3) { + rank = Kit.glyph(FontImage.MATERIAL_MILITARY_TECH, "LnRankTop", 5); + rank.setText("" + e.rank()); + } else { + rank = new Label("" + e.rank(), "LnRank"); + } + Container west = BoxLayout.encloseX(rank, Ui.avatar(e.displayName())); + row.add(BorderLayout.WEST, BorderLayout.centerAbsolute(west)); + Container words = new Container(BoxLayout.y()); + words.add(Ui.text(e.me() ? Lang.tr("{0} (you)", e.displayName()) : e.displayName(), + "LnStepTitle")); + words.add(Kit.pill(FontImage.MATERIAL_LOCAL_FIRE_DEPARTMENT, + (e.streak() == 1 ? Lang.tr("1 day") : Lang.tr("{0} days", "" + e.streak())), "LnStepMeta")); + row.add(BorderLayout.CENTER, words); + row.add(BorderLayout.EAST, BorderLayout.centerAbsolute(new Label(e.xp() + " XP", + "LnLeaderXp"))); + return row; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LearnHome.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LearnHome.java new file mode 100644 index 00000000000..8fef56ec170 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LearnHome.java @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.StatsDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.live.LiveChannel; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Nav; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.ArrayList; +import java.util.List; + +/// The learner's home: four tabs -- Today, Courses, Live and Me -- under one +/// bar. Today is the dashboard: the streak, the day's goal as a ring, the +/// course to carry on with, the week, and what is live soon. +public final class LearnHome implements Nav.Home { + static final String TODAY = "today"; + static final String COURSES = "courses"; + static final String LIVE = "live"; + static final String ME = "me"; + + private static final String[] TABS = {TODAY, COURSES, LIVE, ME}; + private static final String[] TAB_NAMES = {"Today", "Courses", "Live", "Me"}; + private static final char[] TAB_ICONS = {FontImage.MATERIAL_HOME, FontImage.MATERIAL_SCHOOL, + FontImage.MATERIAL_SENSORS, FontImage.MATERIAL_PERSON}; + + private static LearnHome current; + + private Form form; + private final Button[] tabs = new Button[TABS.length]; + /// Kept across a rebuild: a change of theme or language builds the home + /// screen again, and should not move the learner off the tab they were on. + private static String tab = TODAY; + private Component shown; + + /// The newest numbers, for the screens that show them. + static StatsDto stats; + static List courses = new ArrayList(); + + @Override + public void start() { + current = this; + form = Ui.form("", "LearnHome"); + form.getToolbar().hideToolbar(); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Container bar = new Container(new GridLayout(1, TABS.length)); + bar.setUIID("LnTabBar"); + bar.setSafeArea(true); + for (int iter = 0; iter < TABS.length; iter++) { + final String id = TABS[iter]; + Button b = new Button(Lang.tr(TAB_NAMES[iter]), "LnTab"); + b.setName("tab-" + id); + FontImage.setMaterialIcon(b, TAB_ICONS[iter], 3.8f); + b.setTextPosition(Component.BOTTOM); + b.setGap(CN.convertToPixels(0.4f)); + b.addActionListener(e -> select(id)); + tabs[iter] = b; + bar.add(b); + } + form.add(BorderLayout.SOUTH, bar); + LiveChannel.listen(new LiveChannel.Adapter() { + @Override + public void sessionChanged(String id, String state) { + if (Nav.isHome(form) && (LIVE.equals(tab) || TODAY.equals(tab))) { + select(tab); + } + } + }); + select(tab); + } + + @Override + public Form form() { + return form; + } + + /// Back to the home screen, on `tab`, refreshed: after a lesson, a + /// purchase, a certificate. + public static void showTab(String tab) { + if (current == null || !Nav.isHome(current.form)) { + Nav.home(); + return; + } + current.select(tab); + current.form.showBack(); + } + + /// Signing out: the next person starts on Today, with nothing of the + /// last one's numbers. + public static void forget() { + tab = TODAY; + stats = null; + courses = new ArrayList(); + } + + public static Form homeForm() { + return current == null ? null : current.form; + } + + void select(String id) { + tab = id; + for (int iter = 0; iter < TABS.length; iter++) { + boolean on = TABS[iter].equals(id); + tabs[iter].setUIID(on ? "LnTabOn" : "LnTab"); + FontImage.setMaterialIcon(tabs[iter], TAB_ICONS[iter], 3.8f); + } + Component next; + if (COURSES.equals(id)) { + next = CatalogTab.build(form); + } else if (LIVE.equals(id)) { + next = LiveTab.build(form); + } else if (ME.equals(id)) { + next = MeTab.build(form); + } else { + next = today(); + } + if (shown != null) { + shown.remove(); + } + shown = next; + form.add(BorderLayout.CENTER, next); + form.revalidate(); + } + + // ------------------------------------------------------------- today + + private Container today() { + final Container page = new Container(BoxLayout.y()); + page.setUIID("LnCanvas"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + page.setName("today"); + page.add(top()); + page.add(new Skeleton(4, "LnSkeleton")); + Api.learn().stats(Net.to(s -> { + stats = s; + Api.learn().courses(Net.to(list -> { + courses = list; + fill(page, s, list); + }, Ui::fail)); + }, Ui.failed(page, () -> select(TODAY)))); + Ui.pull(page, () -> select(TODAY)); + return page; + } + + private Container top() { + UserDto user = Session.user(); + String name = user == null ? "" : first(user.displayName()); + Container top = new Container(new BorderLayout()); + top.setUIID("LnHomeTop"); + Container words = new Container(BoxLayout.y()); + words.add(Ui.text(Lang.tr(greeting()) + (name.length() > 0 ? ", " + name : ""), + "LnHello")); + words.add(new Label(Lang.tr("Ready for today's practice?"), "LnHelloSub")); + top.add(BorderLayout.CENTER, words); + top.setName("home-top"); + return top; + } + + private void fill(Container page, StatsDto s, List list) { + page.removeAll(); + Container top = top(); + Container chips = new Container(BoxLayout.x()); + Label streak = Kit.pill(FontImage.MATERIAL_LOCAL_FIRE_DEPARTMENT, "" + s.streak(), + "LnStreakChip"); + streak.setName("streak"); + chips.add(streak); + chips.add(Kit.pill(FontImage.MATERIAL_BOLT, "" + s.xp(), "LnXpChip")); + // Above the greeting, not beside it: a name and two numbers do not + // share a phone's width without one of them being cut. + top.add(BorderLayout.NORTH, BorderLayout.east(chips)); + page.add(top); + page.add(hero(s, list)); + page.add(week(s)); + List mine = new ArrayList(); + List discover = new ArrayList(); + for (CourseDto c : list) { + (c.enrolled() ? mine : discover).add(c); + } + if (!mine.isEmpty()) { + page.add(Kit.section("Your courses", "All", () -> select(COURSES))); + page.add(row(mine)); + } + if (!discover.isEmpty()) { + page.add(Kit.section(mine.isEmpty() ? "Start learning" : "Discover", "Browse", + () -> select(COURSES))); + page.add(row(discover)); + } + page.add(Kit.section("Live soon", "See all", () -> select(LIVE))); + final Container live = new Container(BoxLayout.y()); + page.add(live); + Api.community().sessions(Net.to(sessions -> { + int shownCount = 0; + for (LiveSessionDto session : sessions) { + if (!"ended".equals(session.state()) && shownCount < 2) { + live.add(LiveTab.card(form, session)); + shownCount++; + } + } + if (shownCount == 0) { + live.add(Ui.text(Lang.tr("No live classes are scheduled yet."), "LnScreenText")); + } + page.revalidate(); + }, (status, message) -> { })); + Container more = new Container(new GridLayout(1, 2)); + more.add(MeTab.tile(FontImage.MATERIAL_EMOJI_EVENTS, "" + s.level(), "Level", + "home-badges", () -> AchievementsForm.show(form))); + more.add(MeTab.tile(FontImage.MATERIAL_LEADERBOARD, Lang.tr("This week"), "Leaderboard", + "home-board", () -> LeaderboardForm.show(form))); + Container wrap = new Container(BoxLayout.y()); + wrap.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + wrap.getAllStyles().setPadding(4, 4, 8, 8); + wrap.add(more); + page.add(Kit.section("Progress", null, null)); + page.add(wrap); + page.revalidate(); + } + + /// The day's goal, and the lesson to do next. + private Container hero(StatsDto s, List list) { + final CourseDto next = nextCourse(list); + Container card = new Container(new BorderLayout()); + card.setUIID("LnHeroCard"); + card.setName("hero"); + Container words = new Container(BoxLayout.y()); + Button go; + if (next != null) { + words.add(new Label(Lang.tr("CONTINUE"), "LnHeroKicker")); + words.add(Ui.text(next.title(), "LnContinueTitle")); + words.add(new Label(Lang.tr("Lesson {0} of {1}", "" + Math.min(next.lessons(), + next.completedLessons() + 1), "" + next.lessons()), "LnDashText")); + go = new Button(Lang.tr("Practice now"), "LnHeroButton"); + go.addActionListener(e -> CourseForm.continueCourse(next.id(), form)); + } else { + words.add(new Label(Lang.tr("WELCOME"), "LnHeroKicker")); + words.add(Ui.text(Lang.tr("Pick your first course"), "LnDashTitle")); + words.add(Ui.text(Lang.tr("An AI tutor that listens, on your phone."), "LnDashText")); + go = new Button(Lang.tr("Browse courses"), "LnHeroButton"); + go.addActionListener(e -> select(COURSES)); + } + FontImage.setMaterialIcon(go, FontImage.MATERIAL_PLAY_ARROW, 3.4f); + go.setName("practice"); + card.add(BorderLayout.CENTER, words); + // Under both columns, so the label never competes with the ring. + Container foot = BorderLayout.west(go); + foot.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + foot.getAllStyles().setPaddingTop(3); + card.add(BorderLayout.SOUTH, foot); + int goal = Math.max(1, s.dailyGoal()); + Kit.Ring ring = new Kit.Ring("LnGoalRing", "LnGoalTrack", 17, + Math.min(1f, s.todayXp() / (float) goal), Math.min(s.todayXp(), goal) + "/" + goal); + ring.setName("goal"); + Container side = new Container(BoxLayout.y()); + side.add(ring); + side.add(new Label(s.todayXp() >= goal ? Lang.tr("Goal met!") : Lang.tr("XP today"), + "LnGoalCaption")); + card.add(BorderLayout.EAST, BorderLayout.centerAbsolute(side)); + return card; + } + + /// The week's streak, a dot a day ending today. + private Container week(StatsDto s) { + Container panel = new Container(BoxLayout.y()); + panel.setUIID("LnBlock"); + Container days = new Container(new GridLayout(1, 7)); + String[] names = {"S", "M", "T", "W", "T", "F", "S"}; + long now = System.currentTimeMillis(); + java.util.Calendar cal = java.util.Calendar.getInstance(); + List week = s.week(); + for (int iter = 6; iter >= 0; iter--) { + cal.setTime(new java.util.Date(now - iter * 86400000L)); + int dow = cal.get(java.util.Calendar.DAY_OF_WEEK) - 1; + int index = 6 - iter; + boolean done = week != null && index < week.size() && week.get(index).intValue() > 0; + Container day = new Container(BoxLayout.y()); + String uiid = done ? "LnWeekDotDone" : iter == 0 ? "LnWeekDotToday" : "LnWeekDot"; + char icon = done ? FontImage.MATERIAL_LOCAL_FIRE_DEPARTMENT + : iter == 0 ? FontImage.MATERIAL_RADIO_BUTTON_CHECKED + : FontImage.MATERIAL_CIRCLE; + day.add(Kit.glyph(icon, uiid, 4.4f)); + day.add(new Label(names[dow], "LnWeekDay")); + days.add(day); + } + panel.add(days); + String note = s.streak() == 0 ? Lang.tr("Do a lesson today to start a streak.") + : s.streak() == 1 ? Lang.tr("1 day streak. Come back tomorrow!") + : Lang.tr("{0} day streak. Best: {1}.", "" + s.streak(), "" + s.bestStreak()); + if (s.freezes() > 0) { + note += Ui.DOT + Lang.tr("{0} freezes", "" + s.freezes()); + } + panel.add(Ui.text(note, "LnWeekNote")); + panel.setName("week"); + return panel; + } + + private Container row(List list) { + Container row = new Container(BoxLayout.x()); + row.setUIID("LnScrollX"); + row.setScrollableX(true); + row.setScrollVisible(false); + for (final CourseDto c : list) { + row.add(Kit.courseCard(c, 46, () -> CourseForm.show(c.id(), form))); + } + return row; + } + + static CourseDto nextCourse(List list) { + CourseDto best = null; + for (CourseDto c : list) { + if (c.enrolled() && c.completedLessons() < c.lessons()) { + if (best == null || c.completedLessons() > best.completedLessons()) { + best = c; + } + } + } + return best; + } + + private static String greeting() { + int hour = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY); + return hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening"; + } + + static String first(String name) { + if (name == null) { + return ""; + } + int space = name.indexOf(' '); + return space > 0 ? name.substring(0, space) : name; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Lessons.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Lessons.java new file mode 100644 index 00000000000..c98da82b44b --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/Lessons.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.AttemptDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.speech.Voice; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// Starts a lesson of any kind, and finishes it: the score goes to the +/// server, which answers with the experience, the streak and any badges, +/// and the reward screen shows them. +public final class Lessons { + private Lessons() { + } + + public static void start(CourseDto course, LessonDto lesson, Form previous) { + if ("conversation".equals(lesson.kind())) { + ConversationLesson.show(course, lesson, previous); + } else if ("video".equals(lesson.kind())) { + VideoLesson.show(course, lesson, previous); + } else { + PhraseLesson.show(course, lesson, previous); + } + } + + /// The lesson is over with `score` (0 to 100) after `seconds`, having + /// spoken `spoken` times. + static void finish(final Form lessonForm, final CourseDto course, final LessonDto lesson, + int score, int seconds, int spoken, final Form previous) { + Voice.stop(); + com.codenameone.examples.lingo.Telemetry.lessonDone(lesson.kind(), score); + Api.learn().attempt(lesson.id(), new AttemptDto(score, seconds, spoken), + Net.to(progress -> RewardForm.show(course, lesson, score, progress, previous), + Ui::fail)); + } + + /// The bar across the top of a lesson: close, progress, and what the + /// lesson is worth. + static Container top(final Form form, LessonDto lesson, Kit.Bar bar, final Form previous) { + Container top = new Container(new BorderLayout()); + top.setUIID("LnLessonTop"); + top.setSafeArea(true); + Button close = new Button("", "LnClose"); + close.setName("close-lesson"); + FontImage.setMaterialIcon(close, FontImage.MATERIAL_CLOSE, 4.4f); + close.addActionListener(e -> { + Voice.stop(); + previous.showBack(); + }); + form.getToolbar().hideToolbar(); + form.setBackCommand(com.codename1.ui.Command.create("", null, e -> { + Voice.stop(); + previous.showBack(); + })); + top.add(BorderLayout.WEST, close); + top.add(BorderLayout.CENTER, BorderLayout.centerAbsolute(bar)); + Label xp = Kit.pill(FontImage.MATERIAL_BOLT, "+" + lesson.xp(), "LnXpChip"); + top.add(BorderLayout.EAST, xp); + return top; + } + + static Form form(String name) { + Form form = Ui.form("", name); + // The column inside carries the padding; the form and its content + // pane only the colour, or the margins add up three times over. + form.setUIID("LnLessonForm"); + form.getContentPane().setUIID("LnLessonForm"); + form.getToolbar().hideToolbar(); + return form; + } + + static Container column() { + Container c = new Container(BoxLayout.y()); + c.setScrollableY(true); + c.setScrollVisible(false); + c.setUIID("LnLessonBody"); + return c; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LiveTab.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LiveTab.java new file mode 100644 index 00000000000..d4bfb068bcf --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/LiveTab.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.live.LiveRoom; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.text.SimpleDateFormat; +import java.util.Date; + +/// Live classes with a teacher: scheduled ones to book a seat in, and the +/// ones on air now to walk into. +public final class LiveTab { + private LiveTab() { + } + + static Container build(final Form home) { + final Container page = new Container(BoxLayout.y()); + page.setUIID("LnCanvas"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + page.setName("live"); + page.add(new Label(Lang.tr("Live classes"), "LnScreenTitle")); + page.add(Ui.text(Lang.tr("Small groups with a real teacher, on video."), + "LnScreenText")); + final Container list = new Container(BoxLayout.y()); + list.add(new Skeleton(3, "LnSkeleton")); + page.add(list); + Api.community().sessions(Net.to(sessions -> { + list.removeAll(); + int count = 0; + for (LiveSessionDto s : sessions) { + if (!"ended".equals(s.state())) { + list.add(card(home, s)); + count++; + } + } + if (count == 0) { + list.add(Ui.empty(FontImage.MATERIAL_SENSORS, Lang.tr("Nothing scheduled"), + Lang.tr("Creators schedule live classes from their studio."))); + } + page.revalidate(); + }, Ui.failed(list, null))); + Ui.pull(page, () -> LearnHome.showTab(LearnHome.LIVE)); + return page; + } + + /// A session as a card: its date, what it is, who teaches, and what to do. + public static Container card(final Form from, final LiveSessionDto s) { + Container card = new Container(new BorderLayout()); + card.setUIID("LnLiveCard"); + card.setName("session-" + s.id()); + Container date = new Container(BoxLayout.y()); + date.setUIID("LnLiveDate"); + boolean live = "live".equals(s.state()); + if (live) { + date.add(Kit.glyph(FontImage.MATERIAL_SENSORS, "LnLiveDay", 5)); + date.add(new Label(Lang.tr("NOW"), "LnLiveWhen")); + } else { + date.add(new Label(new SimpleDateFormat("EEE").format(new Date(s.startsAt())), + "LnLiveDay")); + date.add(new Label(new SimpleDateFormat("HH:mm").format(new Date(s.startsAt())), + "LnLiveWhen")); + } + card.add(BorderLayout.WEST, date); + Container words = new Container(BoxLayout.y()); + Container tags = new Container(BoxLayout.x()); + tags.add(new Label(live ? Lang.tr("LIVE") : Lang.tr("SOON"), + live ? "LnLiveBadge" : "LnSoonBadge")); + words.add(tags); + words.add(Ui.text(s.title(), "LnStepTitle")); + words.add(Ui.text(s.hostName() + Ui.DOT + Languages.name(s.language()) + " " + + s.level() + Ui.DOT + Ui.duration(s.minutes()), "LnStepMeta")); + int left = Math.max(0, s.seats() - s.booked()); + words.add(new Label(s.joined() ? Lang.tr("You have a seat") + : s.mine() ? Lang.tr("You host this") + : Lang.tr("{0} of {1} seats left", "" + left, "" + s.seats()), "LnStepMeta")); + card.add(BorderLayout.CENTER, words); + Button action; + if (live && (s.joined() || s.mine())) { + action = new Button(Lang.tr("Join"), "LnLiveBadge"); + action.addActionListener(e -> LiveRoom.enter(s, from)); + } else if (s.joined() || s.mine()) { + action = null; + } else if (left == 0) { + action = null; + } else { + action = new Button(s.priceCents() > 0 ? Kit.money(s.priceCents()) : Lang.tr("Book"), + "LnSoonBadge"); + action.addActionListener(e -> book(s, from)); + } + if (action != null) { + action.setName("book-" + s.id()); + card.add(BorderLayout.EAST, BorderLayout.centerAbsolute(action)); + } + return card; + } + + static void book(final LiveSessionDto s, final Form from) { + Runnable seated = () -> { + Ui.say(Lang.tr("Your seat is booked. We'll remind you.")); + LearnHome.showTab(LearnHome.LIVE); + }; + if (s.priceCents() > 0) { + Checkout.show("live", s.id(), s.priceCents(), s.title(), + Lang.tr("Live with {0}", s.hostName()), r -> seated.run()); + } else { + Api.community().join(s.id(), Net.to(joined -> seated.run(), Ui::fail)); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/MeTab.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/MeTab.java new file mode 100644 index 00000000000..1e14519522b --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/MeTab.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.lingo.ai.Tutors; +import com.codenameone.examples.lingo.api.StatsDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Nav; +import com.codenameone.examples.lingo.ui.ProfileForm; +import com.codenameone.examples.lingo.ui.SettingsForm; +import com.codenameone.examples.lingo.ui.Ui; + +/// The learner's own page: who they are, their numbers, and the way to +/// everything that is theirs -- badges, certificates, purchases, the AI +/// tutor's model, settings. +final class MeTab { + private MeTab() { + } + + static Container build(final Form home) { + Container page = new Container(BoxLayout.y()); + page.setUIID("LnCanvas"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + page.setName("me"); + UserDto user = Session.user(); + Container head = new Container(new BorderLayout()); + head.setUIID("LnHomeTop"); + Label avatar = Ui.avatar(user == null ? "" : user.displayName()); + head.add(BorderLayout.WEST, avatar); + Container words = new Container(BoxLayout.y()); + words.add(new Label(user == null ? "" : user.displayName(), "LnHello")); + StatsDto s = LearnHome.stats; + if (s != null) { + Container chips = new Container(BoxLayout.x()); + chips.add(new Label(Lang.tr("Level {0}", "" + s.level()), "LnKindTag")); + if (s.pro()) { + chips.add(new Label("PRO", "LnProChip")); + } + words.add(chips); + } + head.add(BorderLayout.CENTER, words); + page.add(head); + if (s != null) { + Container grid = new Container(new GridLayout(2, 2)); + // Lined up with the panels below, whose margin is 4 mm: the + // tiles bring 1.2 mm of their own, so about 2.8 mm more. + grid.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + grid.getAllStyles().setPadding(3, 3, 3, 3); + grid.add(tile(FontImage.MATERIAL_LOCAL_FIRE_DEPARTMENT, "" + s.streak(), + "Day streak", "me-streak", null)); + grid.add(tile(FontImage.MATERIAL_BOLT, "" + s.xp(), "Total XP", "me-xp", null)); + grid.add(tile(FontImage.MATERIAL_MENU_BOOK, "" + s.lessonsDone(), "Lessons", + "me-lessons", null)); + grid.add(tile(FontImage.MATERIAL_SCHEDULE, Ui.duration(s.minutes()), "Practised", + "me-minutes", null)); + page.add(grid); + } + Container list = new Container(BoxLayout.y()); + list.setUIID("LnBlock"); + add(list, FontImage.MATERIAL_EMOJI_EVENTS, "Achievements", "Badges and your level", + "me-badges", () -> AchievementsForm.show(home)); + add(list, FontImage.MATERIAL_LEADERBOARD, "Leaderboard", "See who is practising most", + "me-board", () -> LeaderboardForm.show(home)); + add(list, FontImage.MATERIAL_WORKSPACE_PREMIUM, "Certificates", + "Signed proof of every course you finish", "me-certificates", + () -> CertificatesForm.show(home)); + add(list, FontImage.MATERIAL_AUTO_AWESOME, "AI tutor", + Tutors.describe(Tutors.engine().kind()), "me-tutor", () -> TutorForm.show(home)); + add(list, FontImage.MATERIAL_WORKSPACE_PREMIUM, s != null && s.pro() ? "Lingo Pro" + : "Go Pro", "Unlimited conversations and streak freezes", "me-pro", + () -> WalletForm.pro(home)); + add(list, FontImage.MATERIAL_RECEIPT_LONG, "Purchases", "Courses, classes and tips", + "me-wallet", () -> WalletForm.show(home)); + page.add(list); + Container account = new Container(BoxLayout.y()); + account.setUIID("LnBlock"); + if (user != null && (user.creator() || user.admin())) { + add(account, FontImage.MATERIAL_VIDEO_CAMERA_FRONT, "Creator studio", + "Your courses, classes and earnings", "me-studio", + () -> Nav.switchTo(Nav.STUDIO)); + } + if (user != null && user.admin()) { + add(account, FontImage.MATERIAL_ADMIN_PANEL_SETTINGS, "Accounts", + "Who can sign in, and who teaches", "me-accounts", + () -> AccountsForm.show(home)); + } + add(account, FontImage.MATERIAL_PERSON, "Profile", "Your name and language", "me-profile", + () -> ProfileForm.show(home, () -> LearnHome.showTab(LearnHome.ME))); + add(account, FontImage.MATERIAL_SETTINGS, "Settings", "Reminders, theme, privacy", + "me-settings", () -> SettingsForm.show(home)); + add(account, FontImage.MATERIAL_LOGOUT, "Sign out", null, "sign-out", Nav::signOut); + page.add(account); + return page; + } + + private static void add(Container list, char icon, String title, String detail, String name, + Runnable open) { + Container row = Ui.row(icon, Lang.tr(title), detail == null ? null : Lang.tr(detail), + Kit.glyph(FontImage.MATERIAL_CHEVRON_RIGHT, "LnStepMeta", 4)); + Ui.tap(row, name, e -> open.run()); + list.add(row); + } + + /// A square with an icon, a number and what it counts. + static Container tile(char icon, String value, String label, String name, Runnable open) { + Container tile = new Container(BoxLayout.y()); + tile.setUIID("LnProfileTile"); + tile.add(BorderLayout.west(Kit.glyph(icon, "LnProfileIcon", 4))); + tile.add(new Label(value, "LnProfileValue")); + tile.add(new Label(Lang.tr(label), "LnProfileLabel")); + if (open == null) { + tile.setName(name); + return tile; + } + Container wrap = new Container(new BorderLayout()); + wrap.add(BorderLayout.CENTER, tile); + Ui.tap(wrap, name, e -> open.run()); + return wrap; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/PhraseLesson.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/PhraseLesson.java new file mode 100644 index 00000000000..a044736749c --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/PhraseLesson.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.ui.Button; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.util.UITimer; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.speech.PronunciationScorer; +import com.codenameone.examples.lingo.speech.Voice; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.List; + +/// The pronunciation drill: hear a phrase, say it, see which words landed. +/// +/// The device's recognizer turns the learner's voice into words, and +/// [PronunciationScorer] holds them against the phrase word by word. A word +/// heard right is green, one nearly right amber, one missed red -- so the +/// learner knows what to work on, not just a number. Where the device cannot +/// listen, the learner types the phrase instead and the drill checks the +/// spelling. +final class PhraseLesson { + private final CourseDto course; + private final LessonDto lesson; + private final Form previous; + private final List phrases; + private final int[] best; + private final long started = System.currentTimeMillis(); + private int index; + private int spoken; + private boolean listening; + + private Form form; + private Kit.Bar bar; + private Container body; + private Container foot; + private Container heardBox; + private Container verdictBox; + + private PhraseLesson(CourseDto course, LessonDto lesson, Form previous) { + this.course = course; + this.lesson = lesson; + this.previous = previous; + this.phrases = lesson.phrases(); + this.best = new int[Math.max(1, phrases == null ? 0 : phrases.size())]; + } + + static void show(CourseDto course, LessonDto lesson, Form previous) { + if (lesson.phrases() == null || lesson.phrases().isEmpty()) { + Ui.say(Lang.tr("This lesson has no phrases yet.")); + return; + } + new PhraseLesson(course, lesson, previous).build(); + } + + private void build() { + form = Lessons.form("PhraseLesson"); + bar = new Kit.Bar("LnBar", 0); + bar.setPreferredW(com.codename1.ui.CN.convertToPixels(40)); + form.add(BorderLayout.NORTH, Lessons.top(form, lesson, bar, previous)); + body = Lessons.column(); + form.add(BorderLayout.CENTER, body); + foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + form.add(BorderLayout.SOUTH, foot); + phrase(); + form.show(); + } + + private PhraseDto current() { + return phrases.get(index); + } + + private void phrase() { + listening = false; + bar.setValue(index / (float) phrases.size()); + final PhraseDto p = current(); + body.removeAll(); + body.add(new Label(Lang.tr("SAY THIS PHRASE"), "LnPrompt")); + com.codename1.components.SpanLabel big = Ui.text(p.text(), "LnPhrase"); + big.setName("phrase"); + body.add(big); + if (p.translation() != null && p.translation().length() > 0) { + body.add(Ui.text(p.translation(), "LnTranslation")); + } + Container listen = new Container(new FlowLayout(Component.CENTER)); + Button hear = new Button(Lang.tr("Listen"), "LnListen"); + hear.setName("listen"); + FontImage.setMaterialIcon(hear, FontImage.MATERIAL_VOLUME_UP, 3.6f); + hear.addActionListener(e -> Voice.speak(p.text(), course.language(), false)); + Button slow = new Button(Lang.tr("Slowly"), "LnListen"); + slow.setName("listen-slow"); + FontImage.setMaterialIcon(slow, FontImage.MATERIAL_SLOW_MOTION_VIDEO, 3.6f); + slow.addActionListener(e -> Voice.speak(p.text(), course.language(), true)); + if (Voice.canSpeak()) { + listen.add(hear).add(slow); + body.add(listen); + } + if (p.hint() != null && p.hint().length() > 0) { + body.add(Ui.text(p.hint(), "LnHint")); + } + heardBox = new Container(new FlowLayout(Component.CENTER)); + heardBox.setName("heard"); + body.add(heardBox); + verdictBox = new Container(BoxLayout.y()); + body.add(verdictBox); + askToSpeak(); + form.revalidate(); + if (Voice.canSpeak()) { + // The model first, as a teacher would. + UITimer.timer(400, false, form, () -> Voice.speak(p.text(), course.language(), false)); + } + } + + private void askToSpeak() { + foot.removeAll(); + if (Voice.canListen()) { + final Button mic = new Button("", "LnMic"); + mic.setName("mic"); + FontImage.setMaterialIcon(mic, FontImage.MATERIAL_MIC, 7); + final Label caption = new Label(Lang.tr("Tap and speak"), "LnMicCaption"); + mic.addActionListener(e -> { + if (listening) { + Voice.stop(); + return; + } + listening = true; + mic.setUIID("LnMicLive"); + caption.setText(Lang.tr("Listening...")); + heardBox.removeAll(); + Voice.listen(course.language(), new Voice.Heard() { + @Override + public void partial(String text) { + heardBox.removeAll(); + heardBox.add(new Label(text, "LnHeardRaw")); + form.revalidate(); + } + + @Override + public void heard(String text, float confidence, String[] alternatives) { + listening = false; + judge(text, alternatives, confidence); + } + + @Override + public void nothing(String why) { + listening = false; + mic.setUIID("LnMic"); + caption.setText(Lang.tr(why)); + form.revalidate(); + } + }); + form.revalidate(); + }); + foot.add(FlowLayout.encloseCenter(mic)); + foot.add(caption); + } else { + final TextField typed = new TextField("", Lang.tr("Type what you would say")); + typed.setUIID("LnTypeField"); + typed.setName("typed"); + foot.add(typed); + foot.add(Ui.primary(Lang.tr("Check"), "check", e -> { + if (typed.getText().trim().length() > 0) { + judge(typed.getText(), null, 1f); + } + })); + typed.setDoneListener(e -> { + if (typed.getText().trim().length() > 0) { + judge(typed.getText(), null, 1f); + } + }); + } + } + + private void judge(String heard, String[] alternatives, float confidence) { + spoken++; + PronunciationScorer.Result result = PronunciationScorer.score(current().text(), heard, + alternatives, confidence); + best[index] = Math.max(best[index], result.score); + heardBox.removeAll(); + for (PronunciationScorer.Word word : result.words) { + Label l = new Label(word.text, word.good() ? "LnHeardGood" + : word.close() ? "LnHeardClose" : "LnHeardMiss"); + heardBox.add(l); + } + verdictBox.removeAll(); + boolean passed = result.score >= PronunciationScorer.CLOSE; + Container verdict = new Container(new BorderLayout()); + verdict.setUIID(passed ? "LnVerdict" : "LnVerdictTry"); + verdict.setName("verdict"); + Container words = new Container(BoxLayout.y()); + String title = result.score >= 90 ? Lang.tr("Excellent!") + : result.score >= PronunciationScorer.GOOD ? Lang.tr("Great job!") + : passed ? Lang.tr("Nearly there") : Lang.tr("Let's try that again"); + words.add(new Label(title, passed ? "LnVerdictTitle" : "LnVerdictTitleTry")); + List missed = result.missed(); + if (!missed.isEmpty()) { + StringBuilder list = new StringBuilder(); + for (PronunciationScorer.Word w : missed) { + list.append(list.length() == 0 ? "" : ", ").append(w.text); + } + words.add(Ui.text(Lang.tr("Work on: {0}", list.toString()), "LnCourseMeta")); + } else if (heard != null && heard.length() > 0) { + words.add(Ui.text(Lang.tr("Heard: \"{0}\"", heard), "LnCourseMeta")); + } + verdict.add(BorderLayout.CENTER, words); + Label score = new Label(result.score + "%", "LnVerdictScore"); + score.setName("score"); + verdict.add(BorderLayout.EAST, BorderLayout.centerAbsolute(score)); + verdictBox.add(verdict); + + foot.removeAll(); + Button next = Ui.primary(index + 1 < phrases.size() ? Lang.tr("Continue") + : Lang.tr("Finish lesson"), "next", e -> advance()); + foot.add(next); + foot.add(Ui.link(Lang.tr("Try again"), "again", e -> { + verdictBox.removeAll(); + heardBox.removeAll(); + askToSpeak(); + form.revalidate(); + })); + form.revalidate(); + } + + private void advance() { + if (index + 1 < phrases.size()) { + index++; + phrase(); + return; + } + bar.setValue(1); + int total = 0; + for (int b : best) { + total += b; + } + Lessons.finish(form, course, lesson, total / best.length, + (int) ((System.currentTimeMillis() - started) / 1000), spoken, previous); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/QaForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/QaForm.java new file mode 100644 index 00000000000..fef6fdcef13 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/QaForm.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.CommentDraftDto; +import com.codenameone.examples.lingo.api.CommentDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.List; + +/// A course's questions and answers: learners ask, the creator and other +/// learners answer. One level of replies -- an answer to an answer joins the +/// question's thread. +final class QaForm { + private QaForm() { + } + + static void show(final CourseDto course, final Form previous) { + final Form form = Ui.form(Lang.tr("Questions"), "Qa"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container list = new Container(BoxLayout.y()); + list.setScrollableY(true); + list.setScrollVisible(false); + list.setUIID("LnCanvas"); + list.setName("comments"); + form.add(BorderLayout.CENTER, list); + final String[] replyTo = new String[1]; + final Label replying = new Label("", "LnCourseMeta"); + Container compose = new Container(new BorderLayout()); + compose.setUIID("LnLessonFoot"); + compose.setSafeArea(true); + final TextField field = new TextField("", Lang.tr("Ask a question")); + field.setUIID("LnTypeField"); + field.setName("comment"); + Button send = new Button("", "LnMic"); + send.setName("post"); + send.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + send.getAllStyles().setPadding(3, 3, 3, 3); + send.getAllStyles().setMargin(0, 0, 4, 0); + FontImage.setMaterialIcon(send, FontImage.MATERIAL_SEND, 4); + compose.add(BorderLayout.NORTH, replying); + compose.add(BorderLayout.CENTER, field); + compose.add(BorderLayout.EAST, BorderLayout.centerAbsolute(send)); + form.add(BorderLayout.SOUTH, compose); + final Runnable[] load = new Runnable[1]; + load[0] = () -> Api.community().comments(course.id(), Net.to(comments -> { + list.removeAll(); + if (comments.isEmpty()) { + list.add(Ui.empty(FontImage.MATERIAL_FORUM, Lang.tr("No questions yet"), + Lang.tr("Be the first to ask {0}.", course.creatorName()))); + } + for (CommentDto c : comments) { + if (c.parentId() == null || c.parentId().length() == 0) { + list.add(comment(c, false, () -> { + replyTo[0] = c.id(); + replying.setText(Lang.tr("Replying to {0}", c.authorName())); + field.setHint(Lang.tr("Write an answer")); + field.startEditingAsync(); + form.revalidate(); + })); + for (CommentDto r : replies(comments, c.id())) { + list.add(comment(r, true, null)); + } + } + } + form.revalidate(); + }, Ui.failed(list, load[0]))); + Runnable post = () -> { + String text = field.getText().trim(); + if (text.length() == 0) { + return; + } + Api.community().comment(course.id(), new CommentDraftDto(text, replyTo[0]), + Net.to(saved -> { + field.setText(""); + replyTo[0] = null; + replying.setText(""); + field.setHint(Lang.tr("Ask a question")); + load[0].run(); + }, Ui::fail)); + }; + send.addActionListener(e -> post.run()); + field.setDoneListener(e -> post.run()); + list.add(new Skeleton(4, "LnSkeleton")); + form.show(); + load[0].run(); + } + + private static Container comment(CommentDto c, boolean reply, Runnable onReply) { + Container box = new Container(BoxLayout.y()); + box.setUIID(reply ? "LnReply" : "LnComment"); + box.setName("comment-" + c.id()); + Container who = new Container(BoxLayout.x()); + who.add(new Label(c.authorName(), "LnCommentWho")); + if (c.creator()) { + who.add(new Label(Lang.tr("Creator"), "LnCreatorTag")); + } + who.add(new Label(Ui.DOT + Ui.when(c.createdAt()), "LnStepMeta")); + box.add(who); + box.add(Ui.text(c.text(), "LnCommentText")); + if (onReply != null) { + box.add(BorderLayout.west(Ui.link(Lang.tr("Reply"), "reply-" + c.id(), + e -> onReply.run()))); + } + return box; + } + + private static List replies(List all, String parent) { + List out = new java.util.ArrayList(); + for (CommentDto c : all) { + if (parent.equals(c.parentId())) { + out.add(c); + } + } + return out; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/RewardForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/RewardForm.java new file mode 100644 index 00000000000..3bec1ea1b8b --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/RewardForm.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.Label; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.plaf.UIManager; +import com.codenameone.examples.lingo.api.AchievementDto; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.ProgressDto; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.Random; + +/// The end of a lesson: the experience counting up, the score, the streak, +/// and every badge it unlocked. Finishing a course offers the certificate. +final class RewardForm { + private RewardForm() { + } + + static void show(final CourseDto course, LessonDto lesson, int score, + final ProgressDto progress, final Form previous) { + LearnHome.stats = progress.stats(); + final Form form = Ui.form("", "Reward"); + form.getToolbar().hideToolbar(); + // The body carries the padding; the form only the colour. + form.setUIID("LnLessonForm"); + form.getContentPane().setUIID("LnLessonForm"); + Container body = new Container(BoxLayout.y()); + body.setUIID("LnReward"); + body.setScrollableY(true); + body.setScrollVisible(false); + body.setSafeArea(true); + Confetti confetti = new Confetti(); + Container hero = new Container(new com.codename1.ui.layouts.LayeredLayout()); + Label trophy = Kit.glyph(progress.courseCompleted() ? FontImage.MATERIAL_WORKSPACE_PREMIUM + : FontImage.MATERIAL_EMOJI_EVENTS, "LnUnlockedIcon", 12); + hero.add(confetti).add(BorderLayout.centerAbsolute(trophy)); + body.add(hero); + body.add(Ui.text(progress.courseCompleted() ? Lang.tr("Course complete!") + : Lang.tr("Lesson complete!"), "LnRewardTitle")); + body.add(Ui.text(lesson.title(), "LnRewardText")); + final Label xp = new Label("+0 XP", "LnRewardXp"); + xp.setName("xp-earned"); + body.add(xp); + Container stats = new Container(new GridLayout(1, 3)); + stats.add(stat(score + "%", Lang.tr("Score"))); + stats.add(stat("" + progress.stats().streak(), Lang.tr("Day streak"))); + stats.add(stat("" + progress.stats().level(), Lang.tr("Level"))); + body.add(stats); + int goal = Math.max(1, progress.stats().dailyGoal()); + body.add(new Label(progress.stats().todayXp() >= goal ? Lang.tr("Daily goal met") + : Lang.tr("{0} of {1} XP today", "" + progress.stats().todayXp(), "" + goal), + "LnRewardStatLabel")); + body.add(new Kit.Bar("LnBarGold", Math.min(1f, progress.stats().todayXp() + / (float) goal))); + if (progress.unlocked() != null) { + for (AchievementDto badge : progress.unlocked()) { + Container row = new Container(new BorderLayout()); + row.setUIID("LnVerdict"); + row.setName("unlocked-" + badge.id()); + row.add(BorderLayout.WEST, BorderLayout.centerAbsolute( + Kit.glyph(AchievementsForm.icon(badge.icon()), "LnBadgeIcon", 4.4f))); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("Badge unlocked"), "LnCertKicker")); + words.add(Ui.text(badge.title(), "LnStepTitle")); + words.add(Ui.text(badge.description(), "LnStepMeta")); + row.add(BorderLayout.CENTER, words); + row.add(BorderLayout.EAST, BorderLayout.centerAbsolute( + new Label("+" + badge.xp(), "LnXpChip"))); + body.add(row); + } + } + form.add(BorderLayout.CENTER, body); + Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + if (progress.courseCompleted() && progress.certificateId() != null + && progress.certificateId().length() > 0) { + foot.add(Ui.primary(Lang.tr("View your certificate"), "certificate", + e -> CertificatesForm.open(progress.certificateId(), course.title(), form))); + foot.add(Ui.link(Lang.tr("Back to the course"), "continue", + e -> CourseForm.show(course.id(), LearnHome.homeForm()))); + } else { + foot.add(Ui.primary(Lang.tr("Continue"), "continue", + e -> CourseForm.show(course.id(), LearnHome.homeForm()))); + } + form.add(BorderLayout.SOUTH, foot); + form.show(); + // The experience counts up rather than appearing. + final int earned = progress.xpEarned(); + final long t0 = System.currentTimeMillis(); + com.codename1.ui.util.UITimer.timer(30, true, form, new Runnable() { + private boolean done; + + @Override + public void run() { + if (done) { + return; + } + float t = Math.min(1f, (System.currentTimeMillis() - t0) / 900f); + xp.setText("+" + (int) (earned * (1 - (1 - t) * (1 - t))) + " XP"); + if (t >= 1) { + done = true; + } + xp.getParent().revalidateLater(); + } + }); + form.registerAnimated(confetti); + } + + private static Container stat(String value, String label) { + Container c = new Container(BoxLayout.y()); + c.setUIID("LnRewardStat"); + c.add(new Label(value, "LnRewardStatValue")); + c.add(new Label(label, "LnRewardStatLabel")); + return c; + } + + /// Paper falling behind the trophy for a second and a half. + static final class Confetti extends Component { + private final float[] x = new float[40]; + private final float[] y = new float[40]; + private final float[] speed = new float[40]; + private final int[] colour = new int[40]; + private final long started = System.currentTimeMillis(); + + Confetti() { + Random r = new Random(7); + int[] palette = { + UIManager.getInstance().getComponentStyle("LnConfetti").getFgColor(), + 0xf0524f, 0x5b5bd6, 0x0f9d8a, 0x2f8fe0, 0xff7a1a, + }; + for (int iter = 0; iter < x.length; iter++) { + x[iter] = r.nextFloat(); + y[iter] = -r.nextFloat(); + speed[iter] = 0.4f + r.nextFloat() * 0.6f; + colour[iter] = palette[iter % palette.length]; + } + setFocusable(false); + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(CN.getDisplayWidth(), CN.convertToPixels(34)); + } + + @Override + public boolean animate() { + return System.currentTimeMillis() - started < 1800; + } + + @Override + public void paint(Graphics g) { + float t = (System.currentTimeMillis() - started) / 1500f; + if (t > 1.2f) { + return; + } + int s = CN.convertToPixels(1.2f); + for (int iter = 0; iter < x.length; iter++) { + float yy = y[iter] + t * speed[iter] * 1.6f; + if (yy < 0 || yy > 1) { + continue; + } + g.setColor(colour[iter]); + g.setAlpha((int) (255 * Math.max(0f, 1f - t * 0.8f))); + g.fillRect(getX() + (int) (x[iter] * getWidth()), + getY() + (int) (yy * getHeight()), s, s * 2 / 3 + iter % 3); + } + g.setAlpha(255); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/TutorForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/TutorForm.java new file mode 100644 index 00000000000..5a76e1db37d --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/TutorForm.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.components.InfiniteProgress; +import com.codename1.ui.Container; +import com.codename1.ui.Dialog; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.ai.Tutors; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// Where the AI tutor runs, and the choice to download one. +/// +/// The phone's own model is used whenever it has one. A phone without +/// one can download a small open model -- 470 MB, once -- and run it on +/// the device; the download asks first, and waits for Wi-Fi unless the +/// learner says otherwise. The cloud tutor is a separate, explicit opt-in. +public final class TutorForm { + private TutorForm() { + } + + public static void show(final Form previous) { + final Form form = Ui.form(Lang.tr("AI tutor"), "Tutor"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setUIID("LnCanvas"); + page.setName("tutor"); + String kind = Tutors.engine().kind(); + Container now = new Container(new BorderLayout()); + now.setUIID("LnHeroCard"); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("YOUR TUTOR"), "LnHeroKicker")); + words.add(new Label(Lang.tr(Tutors.describe(kind)), "LnDashTitle")); + words.add(Ui.text(Lang.tr(explain(kind)), "LnDashText")); + now.add(BorderLayout.CENTER, words); + page.add(now); + Container list = new Container(BoxLayout.y()); + list.setUIID("LnBlock"); + if (Tutors.downloading()) { + list.add(Ui.row(FontImage.MATERIAL_DOWNLOADING, Lang.tr("Downloading the offline " + + "tutor"), Lang.tr("You can keep practising. It is ready in a few minutes."), + new InfiniteProgress())); + } else if (Tutors.canDownload()) { + Container row = Ui.row(FontImage.MATERIAL_DOWNLOAD_FOR_OFFLINE, + Lang.tr("Download the offline tutor"), + Lang.tr("Qwen2.5 0.5B, 470 MB. Runs privately on this phone."), null); + Ui.tap(row, "download-model", e -> download(previous)); + list.add(row); + } else if (Tutors.LOCAL.equals(kind)) { + Container row = Ui.row(FontImage.MATERIAL_DELETE, Lang.tr("Remove the offline tutor"), + Lang.tr("Frees 470 MB. You can download it again."), null); + Ui.tap(row, "remove-model", e -> { + Tutors.forgetModel(); + show(previous); + }); + list.add(row); + } + list.add(Ui.row(FontImage.MATERIAL_WIFI, Lang.tr("Download on Wi-Fi only"), null, + Ui.toggle("wifi-only", Prefs.wifiOnlyModel(), Prefs::setWifiOnlyModel))); + list.add(Ui.row(FontImage.MATERIAL_CLOUD, Lang.tr("Use the cloud tutor"), + Lang.tr("When this phone has no model. What you say is sent to Lingo's AI " + + "provider."), Ui.toggle("cloud-tutor", Prefs.cloudTutor(), on -> { + Prefs.setCloudTutor(on); + show(previous); + }))); + page.add(list); + page.add(Ui.text(Lang.tr("Speech recognition and the voice always run on the phone."), + "LnScreenText")); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + private static String explain(String kind) { + if (Tutors.SYSTEM.equals(kind)) { + return "Your phone's built-in AI answers. Nothing you say leaves the device."; + } + if (Tutors.LOCAL.equals(kind)) { + return "The model you downloaded answers, on this phone. Works offline."; + } + if (Tutors.CLOUD.equals(kind)) { + return "A cloud model answers through Lingo's server."; + } + return "A scripted partner keeps conversations going. Download the offline tutor or " + + "turn on the cloud tutor for free conversation."; + } + + private static void download(final Form previous) { + if (Prefs.wifiOnlyModel() && !Tutors.onWifiOrUnknown()) { + Ui.say(Lang.tr("Connect to Wi-Fi to download, or turn off Wi-Fi only.")); + return; + } + if (!Dialog.show(Lang.tr("Download 470 MB?"), Lang.tr("The tutor model is downloaded " + + "once and stays on this phone."), Lang.tr("Download"), Lang.tr("Not now"))) { + return; + } + Tutors.download(ok -> Ui.say(ok.booleanValue() ? Lang.tr("The offline tutor is ready") + : Lang.tr("The download failed. Try again later."))); + show(previous); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/VideoLesson.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/VideoLesson.java new file mode 100644 index 00000000000..40ed7c5f1fc --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/VideoLesson.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.components.MediaPlayer; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.speech.Voice; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// A recorded lesson: the creator's video, streamed from the server (which +/// answers byte ranges, so the player can seek), and the key phrases under it +/// to hear again. +final class VideoLesson { + private VideoLesson() { + } + + static void show(final CourseDto course, final LessonDto lesson, final Form previous) { + final long started = System.currentTimeMillis(); + final Form form = Lessons.form("VideoLesson"); + Kit.Bar bar = new Kit.Bar("LnBar", 0); + bar.setPreferredW(CN.convertToPixels(40)); + form.add(BorderLayout.NORTH, Lessons.top(form, lesson, bar, previous)); + Container body = Lessons.column(); + final MediaPlayer player = new MediaPlayer(); + player.setUIID("LnVideo"); + player.setName("video"); + player.setLoop(false); + // The learner opened the lesson to watch it: it starts at once. + player.setAutoplay(true); + player.setPreferredH(CN.getDisplayWidth() * 9 / 16); + if (lesson.videoUrl() != null && lesson.videoUrl().length() > 0) { + player.setDataSource(Api.absolute(lesson.videoUrl())); + } + Container video = new Container(new BorderLayout()); + video.setUIID("LnVideo"); + video.add(BorderLayout.CENTER, player); + body.add(video); + body.add(Ui.text(lesson.title(), "LnHello")); + body.add(Ui.text(lesson.summary(), "LnHelloSub")); + if (lesson.phrases() != null && !lesson.phrases().isEmpty()) { + body.add(new Label(Lang.tr("KEY PHRASES"), "LnPrompt")); + for (final PhraseDto p : lesson.phrases()) { + Container row = new Container(new BorderLayout()); + row.setUIID("LnStepCard"); + Container words = new Container(BoxLayout.y()); + words.add(Ui.text(p.text(), "LnStepTitle")); + words.add(Ui.text(p.translation(), "LnStepMeta")); + row.add(BorderLayout.CENTER, words); + if (Voice.canSpeak()) { + Button hear = new Button("", "LnListen"); + FontImage.setMaterialIcon(hear, FontImage.MATERIAL_VOLUME_UP, 3.6f); + hear.addActionListener(e -> Voice.speak(p.text(), course.language(), false)); + row.add(BorderLayout.EAST, BorderLayout.centerAbsolute(hear)); + } + body.add(row); + } + } + form.add(BorderLayout.CENTER, body); + Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + foot.add(Ui.primary(Lang.tr("I've watched it"), "watched", e -> { + if (player.getMedia() != null) { + player.getMedia().pause(); + } + Lessons.finish(form, course, lesson, 100, + (int) ((System.currentTimeMillis() - started) / 1000), 0, previous); + })); + form.add(BorderLayout.SOUTH, foot); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/WalletForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/WalletForm.java new file mode 100644 index 00000000000..6618b0ce3df --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/learn/WalletForm.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.learn; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.ReceiptDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// What the learner bought, and Lingo Pro. +final class WalletForm { + /// Pro, a month. + static final int PRO_CENTS = 999; + + private WalletForm() { + } + + static void show(final Form previous) { + Form form = Ui.form(Lang.tr("Purchases"), "Wallet"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setUIID("LnCanvas"); + page.setName("wallet"); + page.add(new Skeleton(4, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + Api.community().wallet(Net.to(wallet -> { + page.removeAll(); + if (wallet.receipts().isEmpty()) { + page.add(Ui.empty(FontImage.MATERIAL_RECEIPT_LONG, Lang.tr("Nothing bought yet"), + Lang.tr("Paid courses, live classes and tips show up here."))); + } + Container list = new Container(BoxLayout.y()); + list.setUIID("LnBlock"); + for (ReceiptDto r : wallet.receipts()) { + list.add(Ui.row(icon(r.kind()), r.description(), Ui.day(r.createdAt()), + new Label(Kit.money(r.amountCents()), "LnLeaderXp"))); + } + if (list.getComponentCount() > 0) { + page.add(list); + } + page.revalidate(); + }, Ui.failed(page, null))); + } + + static void pro(final Form previous) { + final Form form = Ui.form(Lang.tr("Lingo Pro"), "Pro"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, previous); + Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setUIID("LnCanvas"); + page.add(Ui.text(Lang.tr("Practise without limits"), "LnScreenTitle")); + page.add(Ui.text(Lang.tr("Lingo is free. Pro pays for the creators and the servers, " + + "and gives you more."), "LnScreenText")); + boolean pro = LearnHome.stats != null && LearnHome.stats.pro(); + page.add(plan(Lang.tr("Free"), Kit.money(0), false, new String[] { + "Every AI course", "On-device AI tutor", "Signed certificates", "One streak freeze", + })); + page.add(plan("Pro", Kit.money(PRO_CENTS) + Lang.tr(" / month"), true, new String[] { + "Everything in Free", "Cloud AI tutor on any phone", "Three streak freezes a week", + "10% off live classes", "Support the creators you learn from", + })); + form.add(BorderLayout.CENTER, page); + Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + if (pro) { + foot.add(Kit.pill(FontImage.MATERIAL_VERIFIED, Lang.tr("You're a Pro member. Thank " + + "you!"), "LnVerified")); + } else { + foot.add(Ui.primary(Lang.tr("Go Pro for {0}", Kit.money(PRO_CENTS)), "go-pro", + e -> Checkout.show("pro", "pro", PRO_CENTS, "Lingo Pro", + Lang.tr("Monthly, cancel any time"), + r -> LearnHome.showTab(LearnHome.ME)))); + } + form.add(BorderLayout.SOUTH, foot); + form.show(); + } + + private static Container plan(String name, String price, boolean pro, String[] ticks) { + Container card = new Container(BoxLayout.y()); + card.setUIID(pro ? "LnPlanPro" : "LnPlan"); + card.add(new Label(name, "LnStepTitle")); + card.add(new Label(price, "LnPlanPrice")); + for (String t : ticks) { + card.add(Kit.pill(FontImage.MATERIAL_CHECK, Lang.tr(t), "LnTick")); + } + return card; + } + + private static char icon(String kind) { + if ("live".equals(kind)) { + return FontImage.MATERIAL_SENSORS; + } + if ("tip".equals(kind)) { + return FontImage.MATERIAL_VOLUNTEER_ACTIVISM; + } + if ("pro".equals(kind)) { + return FontImage.MATERIAL_WORKSPACE_PREMIUM; + } + return FontImage.MATERIAL_SCHOOL; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveChannel.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveChannel.java new file mode 100644 index 00000000000..e283ba16315 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveChannel.java @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.live; + +import com.codename1.io.CharArrayReader; +import com.codename1.io.JSONParser; +import com.codename1.io.WebSocket; +import com.codename1.io.WebSocketState; +import com.codename1.ui.CN; +import com.codenameone.examples.lingo.net.Api; +import com.codename1.appkit.Net; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Nav; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Timer; + +/// The WebSocket the server pushes changes down: a live class started or +/// ended, and the signalling frames of a class in progress. +/// +/// It mostly says *that* something changed. What a session now is, the app +/// asks for over the REST API, which stays the one source of truth -- so a +/// frame that is lost, or a socket that is down, costs a few seconds and +/// nothing else. Every screen that listens here also polls, slowly while the +/// socket is up and faster while it is not ([#connected] says which). +/// +/// A WebSocket handshake cannot carry the bearer token on every platform, so +/// the connection is let in by a ticket: the app asks for one over the +/// authenticated API, and the server accepts it once, within half a minute. +public final class LiveChannel { + /// What a screen wants to hear about. All of it arrives on the EDT. + public interface Listener { + /// A live tutorial the user holds a seat in, or hosts, opened + /// (`live`) or closed (`ended`). + void sessionChanged(String id, String state); + + /// WebRTC signaling from someone in a live session: `kind` is + /// `hello`, `offer`, `answer`, `ice` or `bye`. + void signal(String room, String from, String fromName, boolean host, String kind, + String data); + } + + /// A listener that ignores everything, to override the part a screen wants. + public static class Adapter implements Listener { + @Override + public void sessionChanged(String id, String state) { + } + + @Override + public void signal(String room, String from, String fromName, boolean host, String kind, + String data) { + } + } + + /// Sends signaling to the others in live session `room`, or to `to` + /// alone. The server relays it only while the session is live and only + /// between people in it. False when the channel is down. + public static boolean signal(String room, String to, String kind, String data) { + if (socket == null || !connected) { + return false; + } + java.util.Map frame = new java.util.LinkedHashMap(); + frame.put("type", "signal"); + frame.put("room", room); + frame.put("to", to == null ? "" : to); + frame.put("kind", kind); + frame.put("data", data == null ? "" : data); + socket.send(com.codename1.io.JSONParser.mapToJson(frame)); + return true; + } + + private static final int PING_MILLIS = 25000; + + private static WebSocket socket; + /// Every screen that is listening, by its owner: the home screen and, on + /// top of it, a live room. A LinkedHashMap so they hear news in the order + /// they asked. + private static final Map LISTENERS = new LinkedHashMap(); + private static final Object HOME = new Object(); + private static boolean wanted; + private static boolean connected; + private static int attempts; + /// Counts the connections made, so that what a closed or replaced one + /// still has to say -- its `onClose`, a frame already on its way -- is + /// recognised as stale and dropped. + private static int generation; + private static Timer pinger; + + private LiveChannel() { + } + + /// Connects, and keeps reconnecting until [#stop]. + public static void start() { + if (wanted) { + return; + } + wanted = true; + attempts = 0; + connect(); + } + + public static void stop() { + wanted = false; + connected = false; + LISTENERS.clear(); + generation++; + if (pinger != null) { + pinger.cancel(); + pinger = null; + } + if (socket != null) { + socket.close(); + socket = null; + } + } + + /// The one screen that is listening: the one on display. + /// The home screen's listener; a later home screen replaces it. + public static void listen(Listener current) { + listen(HOME, current); + } + + /// A listener of `owner`'s, beside the home screen's. A second call for + /// the same owner replaces the first. + public static void listen(Object owner, Listener current) { + if (current == null) { + LISTENERS.remove(owner); + } else { + LISTENERS.put(owner, current); + } + } + + public static void unlisten(Object owner) { + LISTENERS.remove(owner); + } + + public static boolean connected() { + return connected; + } + + private static void connect() { + if (!wanted || !WebSocket.isSupported()) { + return; + } + final int mine = ++generation; + Api.account().liveTicket(Net.to(ticket -> { + if (mine == generation && wanted) { + open(ticket.ticket(), mine); + } + }, (status, message) -> lost(mine))); + } + + private static void open(String ticket, final int mine) { + String base = Session.serverUrl(); + // http -> ws and https -> wss: the scheme keeps its "s". + String url = "ws" + base.substring(4) + "/ws/live?ticket=" + ticket; + // The handlers run on the socket's thread, so each hands its news to + // the EDT, where the rest of the app lives. + socket = WebSocket.build(url) + .onConnect(ws -> CN.callSerially(() -> opened(mine))) + .onTextMessage((ws, text) -> CN.callSerially(() -> frame(text, mine))) + .onClose((ws, code, reason) -> CN.callSerially(() -> closed(mine, code))) + .onError((ws, err) -> CN.callSerially(() -> lost(mine))) + .connect(10000); + } + + private static void opened(int mine) { + if (mine != generation) { + return; + } + connected = true; + attempts = 0; + if (pinger != null) { + pinger.cancel(); + } + // Something has to cross an idle connection now and then, or a proxy + // on the way decides it is dead. + pinger = CN.setInterval(PING_MILLIS, () -> { + if (mine == generation && socket != null + && socket.getReadyState() == WebSocketState.OPEN) { + socket.send("{\"type\":\"ping\"}"); + } + }); + } + + /// The server closes with this code when the account's roles or standing + /// changed: an admin withdrew a mode, or blocked the account. + private static final int CHANGED = 4403; + + private static void closed(int mine, int code) { + if (code == CHANGED && mine == generation && wanted) { + // The account the app has cached is no longer the account the + // server knows: ask again, and go back home if the answer opens + // another mode, so a withdrawn mode is not left open and refused + // at every request. Reconnecting below happens as for any loss. + Session.refreshUser(Nav::refreshed, (status, message) -> { }); + } + lost(mine); + } + + private static void lost(int mine) { + if (mine != generation || !wanted) { + return; + } + connected = false; + final int waiting = ++generation; + if (socket != null) { + socket.close(); + socket = null; + } + // 1, 2, 4 ... 32 seconds, and then every 32. + int delay = 1000 << Math.min(attempts++, 5); + // Only if nothing has happened to the channel in the meantime. Stopped + // and started again during the wait, it has a connection of its own + // by now, and connecting here as well would take that one's place: + // its callbacks would go unheard and its socket would be left open. + CN.setTimeout(delay, () -> CN.callSerially(() -> { + if (waiting == generation) { + connect(); + } + })); + } + + private static void frame(String text, int mine) { + if (mine != generation || LISTENERS.isEmpty()) { + return; + } + Map json; + try { + json = new JSONParser().parseJSON(new CharArrayReader(text.toCharArray())); + } catch (IOException malformed) { + return; + } + Object type = json.get("type"); + // A copy: a listener may stop listening, or open a screen that starts. + List all = new ArrayList(LISTENERS.values()); + for (Listener listener : all) { + if ("session".equals(type)) { + listener.sessionChanged(text(json, "id"), text(json, "state")); + } else if ("signal".equals(type)) { + listener.signal(text(json, "room"), text(json, "from"), text(json, "fromName"), + Boolean.TRUE.equals(json.get("host")), text(json, "kind"), + text(json, "data")); + } + } + } + + // Tested, never cast and caught: a failed cast does not throw on iOS. + private static String text(Map json, String key) { + Object value = json.get(key); + return value instanceof String ? (String) value : ""; + } + +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveRoom.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveRoom.java new file mode 100644 index 00000000000..7c2e4b9bc81 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/live/LiveRoom.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.live; + +import com.codename1.io.Log; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.LayeredLayout; +import com.codename1.webrtc.IceCandidate; +import com.codename1.webrtc.LocalMedia; +import com.codename1.webrtc.MediaTrack; +import com.codename1.webrtc.PeerConnection; +import com.codename1.webrtc.PeerConnectionConfig; +import com.codename1.webrtc.SessionDescription; +import com.codename1.webrtc.VideoView; +import com.codename1.webrtc.WebRtc; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// A live class on video. +/// +/// The host is the hub: every learner holds one peer connection, to the +/// host, and the host holds one to each learner. That is the shape of a +/// small class -- everyone sees the teacher, the teacher sees everyone -- +/// and it keeps a phone from opening a connection per classmate. A class of +/// more than a handful wants an SFU instead; the signaling stays the same. +/// +/// The signaling goes over the app's live channel, which the server relays +/// only between people seated in the session while it is live: +/// +/// - a learner entering sends `hello` to the room; +/// - the host answers a `hello` with an `offer` to that learner alone; +/// - `answer` and `ice` go back and forth; `bye` closes one connection. +/// +/// Early ICE candidates are kept until the remote description is set, +/// since a candidate cannot be added before it. +public final class LiveRoom { + private static LiveRoom current; + + private final LiveSessionDto session; + private final boolean host; + private final Form previous; + private final Map peers = new LinkedHashMap(); + private LocalMedia media; + private Form form; + private Container stage; + private Container self; + private boolean muted; + private boolean cameraOff; + + private static final class Peer { + final String username; + final String name; + PeerConnection connection; + MediaTrack video; + boolean remoteSet; + final List early = new ArrayList(); + + Peer(String username, String name) { + this.username = username; + this.name = name; + } + } + + private LiveRoom(LiveSessionDto session, Form previous) { + this.session = session; + this.previous = previous; + this.host = session.mine(); + } + + public static void enter(LiveSessionDto session, Form previous) { + if (current != null) { + current.leave(false); + } + current = new LiveRoom(session, previous); + com.codenameone.examples.lingo.Telemetry.liveJoined(current.host); + current.build(); + } + + private void build() { + form = new Form("", new BorderLayout()); + form.setName("LiveRoom"); + form.setUIID("LnRoom"); + form.getContentPane().setUIID("LnRoom"); + form.getToolbar().hideToolbar(); + Ui.watch(form); + Container bar = new Container(new BorderLayout()); + bar.setUIID("LnRoomBar"); + bar.setSafeArea(true); + Container words = new Container(BoxLayout.y()); + words.add(BoxLayout.encloseX(new Label(Lang.tr("LIVE"), "LnLiveBadge"))); + words.add(new Label(session.title(), "LnRoomTitle")); + bar.add(BorderLayout.CENTER, words); + form.add(BorderLayout.NORTH, bar); + stage = new Container(new BorderLayout()); + stage.setUIID("LnRoom"); + stage.setName("stage"); + self = new Container(new BorderLayout()); + self.setUIID("LnSelfView"); + self.setPreferredSize(new com.codename1.ui.geom.Dimension(CN.convertToPixels(24), + CN.convertToPixels(32))); + Container layers = new Container(new LayeredLayout()); + layers.add(stage); + layers.add(FlowLayout.encloseRightBottom(self)); + form.add(BorderLayout.CENTER, layers); + form.add(BorderLayout.SOUTH, controls()); + form.setBackCommand(com.codename1.ui.Command.create("", null, e -> leave(true))); + waiting(host ? Lang.tr("You're live. Learners appear here as they join.") + : Lang.tr("Connecting to {0}...", session.hostName())); + form.show(); + if (!WebRtc.isSupported()) { + waiting(Lang.tr("Live video needs the phone app. The class is on: open Lingo on " + + "iOS or Android to take part.")); + return; + } + LiveChannel.listen(this, new LiveChannel.Adapter() { + @Override + public void sessionChanged(String id, String state) { + if (id.equals(session.id()) && "ended".equals(state)) { + Ui.say(Lang.tr("The class has ended")); + leave(true); + } + } + + @Override + public void signal(String room, String from, String fromName, boolean fromHost, + String kind, String data) { + if (room.equals(session.id())) { + signalled(from, fromName, fromHost, kind, data); + } + } + }); + WebRtc.openUserMedia(true, true, true).ready(opened -> { + if (current != this) { + opened.release(); + return; + } + media = opened; + if (media.getVideo() != null) { + self.removeAll(); + self.add(BorderLayout.CENTER, new VideoView(media.getVideo(), true)); + form.revalidate(); + } + if (!host) { + LiveChannel.signal(session.id(), "", "hello", ""); + } + }).except(failure -> { + Ui.say(Lang.tr("Lingo needs the camera and microphone for live classes")); + leave(true); + }); + } + + private Container controls() { + Container row = new Container(new FlowLayout(Component.CENTER)); + row.setUIID("LnRoomBar"); + row.setSafeArea(true); + final Button mute = new Button("", "LnRoomButton"); + mute.setName("mute"); + FontImage.setMaterialIcon(mute, FontImage.MATERIAL_MIC, 5); + mute.addActionListener(e -> { + muted = !muted; + if (media != null && media.getAudio() != null) { + media.getAudio().setEnabled(!muted); + } + FontImage.setMaterialIcon(mute, muted ? FontImage.MATERIAL_MIC_OFF + : FontImage.MATERIAL_MIC, 5); + }); + final Button camera = new Button("", "LnRoomButton"); + camera.setName("camera"); + FontImage.setMaterialIcon(camera, FontImage.MATERIAL_VIDEOCAM, 5); + camera.addActionListener(e -> { + cameraOff = !cameraOff; + if (media != null && media.getVideo() != null) { + media.getVideo().setEnabled(!cameraOff); + } + FontImage.setMaterialIcon(camera, cameraOff ? FontImage.MATERIAL_VIDEOCAM_OFF + : FontImage.MATERIAL_VIDEOCAM, 5); + }); + Button flip = new Button("", "LnRoomButton"); + flip.setName("flip"); + FontImage.setMaterialIcon(flip, FontImage.MATERIAL_CAMERASWITCH, 5); + flip.addActionListener(e -> { + if (media != null && media.getVideo() != null) { + media.getVideo().switchCamera(); + } + }); + Button end = new Button("", "LnRoomHangUp"); + end.setName("leave-room"); + FontImage.setMaterialIcon(end, FontImage.MATERIAL_CALL_END, 5); + end.addActionListener(e -> leave(true)); + row.add(mute).add(camera).add(flip).add(end); + return row; + } + + private void waiting(String text) { + stage.removeAll(); + // In the top part of the stage: the self view sits at its bottom. + Container box = new Container(BoxLayout.y()); + box.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + box.getAllStyles().setPaddingTop(28); + box.add(BorderLayout.centerAbsolute(Ui.avatar(host ? Session.user().displayName() + : session.hostName()))); + box.add(Ui.text(text, "LnRoomText")); + stage.add(BorderLayout.NORTH, box); + form.revalidate(); + } + + // ---------------------------------------------------------- signaling + + private void signalled(String from, String fromName, boolean fromHost, String kind, + String data) { + if ("hello".equals(kind) && host) { + Peer peer = replace(from, fromName); + peer.connection.createOffer().ready(offer -> peer.connection.setLocalDescription(offer) + .ready(done -> LiveChannel.signal(session.id(), from, "offer", + offer.getSdp())).except(this::failed)).except(this::failed); + } else if ("offer".equals(kind) && !host && fromHost) { + final Peer peer = replace(from, fromName); + peer.connection.setRemoteDescription(new SessionDescription(SessionDescription.OFFER, + data)).ready(set -> { + remoteSet(peer); + peer.connection.createAnswer().ready(answer -> + peer.connection.setLocalDescription(answer).ready(done -> + LiveChannel.signal(session.id(), from, "answer", + answer.getSdp())).except(this::failed)) + .except(this::failed); + }).except(this::failed); + } else if ("answer".equals(kind)) { + final Peer peer = peers.get(from); + if (peer != null) { + peer.connection.setRemoteDescription(new SessionDescription( + SessionDescription.ANSWER, data)).ready(set -> remoteSet(peer)) + .except(this::failed); + } + } else if ("ice".equals(kind)) { + Peer peer = peers.get(from); + IceCandidate candidate = candidate(data); + if (peer != null && candidate != null) { + if (peer.remoteSet) { + peer.connection.addIceCandidate(candidate); + } else { + peer.early.add(candidate); + } + } + } else if ("bye".equals(kind)) { + drop(from); + } + } + + /// A fresh connection to `username`, closing any older one: a learner + /// who drops and comes back says hello again. + private Peer replace(final String username, String name) { + drop(username); + final Peer peer = new Peer(username, name); + peer.connection = WebRtc.createPeerConnection(new PeerConnectionConfig(), + new PeerConnection.Listener() { + @Override + public void iceCandidate(PeerConnection connection, IceCandidate c) { + LiveChannel.signal(session.id(), username, "ice", + (c.getSdpMid() == null ? "" : c.getSdpMid()) + "\t" + + c.getSdpMLineIndex() + "\t" + c.getCandidate()); + } + + @Override + public void stateChanged(PeerConnection connection, String state) { + if (PeerConnection.FAILED.equals(state)) { + drop(username); + } + } + + @Override + public void remoteTrack(PeerConnection connection, MediaTrack track) { + if (track.isVideo()) { + peer.video = track; + render(); + } + } + }); + if (media != null) { + if (media.getAudio() != null) { + peer.connection.addTrack(media.getAudio()); + } + if (media.getVideo() != null) { + peer.connection.addTrack(media.getVideo()); + } + } + peers.put(username, peer); + return peer; + } + + private void remoteSet(Peer peer) { + peer.remoteSet = true; + for (IceCandidate each : peer.early) { + peer.connection.addIceCandidate(each); + } + peer.early.clear(); + } + + private void drop(String username) { + Peer peer = peers.remove(username); + if (peer != null) { + peer.connection.close(); + render(); + } + } + + /// The learner sees the host; the host sees everyone, in a grid. + private void render() { + List showing = new ArrayList(); + for (Peer p : peers.values()) { + if (p.video != null) { + showing.add(p); + } + } + if (showing.isEmpty()) { + waiting(host ? Lang.tr("You're live. Learners appear here as they join.") + : Lang.tr("Waiting for {0}'s video...", session.hostName())); + return; + } + stage.removeAll(); + int columns = showing.size() == 1 ? 1 : 2; + Container grid = new Container(new GridLayout((showing.size() + columns - 1) / columns, + columns)); + for (Peer p : showing) { + Container tile = new Container(new LayeredLayout()); + tile.add(new VideoView(p.video, false)); + tile.add(FlowLayout.encloseBottom(new Label(p.name, "LnEngine"))); + grid.add(tile); + } + stage.add(BorderLayout.CENTER, grid); + form.revalidate(); + } + + private void failed(Throwable why) { + Log.e(why); + Ui.say(Lang.tr("The video connection failed")); + } + + private static IceCandidate candidate(String data) { + int a = data.indexOf('\t'); + int b = a < 0 ? -1 : data.indexOf('\t', a + 1); + if (b < 0) { + return null; + } + String mid = data.substring(0, a); + int index; + try { + index = Integer.parseInt(data.substring(a + 1, b)); + } catch (NumberFormatException bad) { + return null; + } + return new IceCandidate(mid.length() == 0 ? null : mid, index, data.substring(b + 1)); + } + + /// Closes every connection; `back` returns to the screen the room was + /// opened from. + private void leave(boolean back) { + LiveChannel.unlisten(this); + LiveChannel.signal(session.id(), "", "bye", ""); + for (Peer p : new ArrayList(peers.values())) { + p.connection.close(); + } + peers.clear(); + if (media != null) { + media.release(); + media = null; + } + if (current == this) { + current = null; + } + if (back && previous != null) { + previous.showBack(); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Account.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Account.java new file mode 100644 index 00000000000..e2eeab490ee --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Account.java @@ -0,0 +1,372 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.net; + +import com.codename1.appkit.Net; + +import com.codename1.io.Preferences; +import com.codename1.ui.CN; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.api.PreferencesDto; +import com.codenameone.examples.lingo.api.ProfileDto; + +/// Keeps what the user chose in Settings with their account. +/// +/// [Prefs] is still what every screen reads and writes, and still on the +/// device: that copy is what the app starts from before the server has +/// answered, and all there is for someone who is signed out. This class is the +/// other half. When someone signs in it fetches the account's values and puts +/// them into `Prefs`, so a phone they have never used looks like the one they +/// left; and from then on it is told of every change and sends it back. +/// +/// A change is not sent the moment it is made. A name typed into a field +/// changes with every letter, so changes are gathered for a moment and sent as +/// one request with everything in it. +/// +/// A change is not forgotten when its request fails, either. The device's +/// values stay marked as unsent, on the device, until the server has taken +/// them: they are sent again a little later, and an account load that finds +/// them unsent -- the app restarted before the network came back -- sends them +/// rather than overwriting them with what the server still holds. +public final class Account { + /// How long after the last change the values are sent. + private static final int SETTLE_MILLIS = 700; + /// How long after a request failed it is sent again. + private static final int RETRY_MILLIS = 30000; + /// The keys under which each half is marked unsent; the value is the + /// account it was not sent for. + private static final String UNSENT_PREFERENCES = "lingo.account.unsent.preferences"; + private static final String UNSENT_PROFILE = "lingo.account.unsent.profile"; + + /// True while the account's values are being put into `Prefs`, which + /// reports each of them as a change like any other. + private static boolean applying; + private static boolean preferencesChanged; + private static boolean profileChanged; + private static boolean waiting; + /// Whether each half of the account's values has arrived since it signed + /// in. Until one has, the device's copy of it is not the account's -- it + /// is the defaults, or what an earlier session left -- and is not sent. + private static boolean preferencesLoaded; + private static boolean profileLoaded; + /// The profile as the server last gave it: the name and the phone are + /// part of it, and are sent back as they were with the rest. + private static ProfileDto profile; + /// What a request carries beyond the settings, for a test to look at. + private static PreferencesDto sent; + /// How many requests of each half were sent. An answer clears the unsent + /// mark only if no later request of its half went out after it. + private static int preferencesSends; + private static int profileSends; + + private Account() { + } + + /// Starts listening to `Prefs`. Called once, when the app starts. + public static void start() { + Prefs.onChange(Account::changed); + } + + /// Fetches the account's settings and profile into `Prefs`, then runs + /// `done` -- also when the server did not answer, with what the device + /// had. Each half is asked for whether or not the other came, and one that + /// did not come is asked for again before anything of it is saved. + public static void load(final Runnable done) { + if (Session.user() == null) { + done.run(); + return; + } + profile = null; + preferencesLoaded = false; + profileLoaded = false; + // What another account left unsent is not this one's to send. + String owner = Session.owner(); + if (!isUnsent(UNSENT_PREFERENCES, owner)) { + Preferences.delete(UNSENT_PREFERENCES); + } + if (!isUnsent(UNSENT_PROFILE, owner)) { + Preferences.delete(UNSENT_PROFILE); + } + fetch(done); + } + + private static void fetch(final Runnable done) { + final String owner = Session.owner(); + // An answer from a session that has since ended still runs `done`. + // Signing out and in while the account loads is rare, and the worst + // of it is the home screen shown a moment before its settings, which + // the new session's own load applies when it ends. The data itself is + // only taken for the account signed in now, which is checked below. + final Runnable thenProfile = () -> { + if (profileLoaded || !signedInAs(owner)) { + done.run(); + return; + } + Api.account().profile(Net.to(described -> { + if (signedInAs(owner)) { + if (described != null && isUnsent(UNSENT_PROFILE, owner)) { + // The device has a change the server never took: + // the server's name and phone are kept, the rest is + // the device's, and is sent. + profile = described; + profileLoaded = true; + profileChanged = true; + schedule(SETTLE_MILLIS); + } else { + apply(described); + profileLoaded = described != null; + } + } + done.run(); + }, (status, message) -> done.run())); + }; + if (preferencesLoaded) { + thenProfile.run(); + return; + } + Api.account().preferences(Net.to(preferences -> { + if (signedInAs(owner)) { + if (preferences != null && isUnsent(UNSENT_PREFERENCES, owner)) { + // As for the profile: the device's are newer. + preferencesLoaded = true; + preferencesChanged = true; + schedule(SETTLE_MILLIS); + } else { + apply(preferences); + preferencesLoaded = preferences != null; + } + } + thenProfile.run(); + }, (status, message) -> thenProfile.run())); + } + + /// The profile last fetched or saved, or null before there is one. + public static ProfileDto profile() { + return profile; + } + + /// Saves the name and the phone number, which only the profile screen + /// changes. + public static void saveProfile(final String name, final String phone, final Runnable done, + final Net.Failed failed) { + if (!profileLoaded) { + // The rest of the profile goes out with the name, and it has not + // been seen yet; see send(). + fetch(() -> { + if (profileLoaded) { + saveProfile(name, phone, done, failed); + } else { + failed.failed(0, "Could not reach the server. Check your connection."); + } + }); + return; + } + ProfileDto wanted = new ProfileDto(name, phone); + final String owner = Session.owner(); + Api.account().saveProfile(wanted, Net.to(user -> { + // The answer is about the account that asked; see send(). + if (signedInAs(owner)) { + profile = wanted; + Session.setUser(user); + } + done.run(); + }, failed)); + } + + /// The preferences sent last, or null when none were. + public static PreferencesDto lastSent() { + return sent; + } + + /// Sends what is waiting now, for a screen that is about to end the session. + public static void flush() { + waiting = false; + send(); + } + + private static void changed(String name) { + // The calendar events are this device's own, not the account's. + if (applying || Session.user() == null) { + return; + } + preferencesChanged = true; + schedule(SETTLE_MILLIS); + } + + /// Sends what has changed `millis` from now, unless a send is already + /// waiting. + private static void schedule(int millis) { + if (!waiting) { + waiting = true; + CN.setTimeout(millis, () -> CN.callSerially(() -> { + if (waiting) { + waiting = false; + send(); + } + })); + } + } + + private static void send() { + if (Session.user() == null) { + preferencesChanged = false; + profileChanged = false; + return; + } + if (preferencesChanged && !preferencesLoaded || profileChanged && !profileLoaded) { + // The account's values never arrived, so what the device holds in + // their place is not known to be this account's: sent, it would + // replace on the server what was never seen here. They are asked + // for again instead, and the change that brought this about gives + // way to them. A later change is saved as usual once they are in. + preferencesChanged = preferencesChanged && preferencesLoaded; + profileChanged = profileChanged && profileLoaded; + fetch(() -> { }); + } + final String owner = Session.owner(); + if (preferencesChanged) { + preferencesChanged = false; + sent = preferences(); + // Marked before it goes, and cleared once the server has it: until + // then the device's values are the account's newest. + Preferences.set(UNSENT_PREFERENCES, owner); + final int send = ++preferencesSends; + Api.account().savePreferences(sent, Net.to(saved -> { + if (send == preferencesSends) { + sentFor(UNSENT_PREFERENCES, owner); + } + }, (status, message) -> { + if (refused(status)) { + // Refused: sent again, it would be refused again. + if (send == preferencesSends) { + sentFor(UNSENT_PREFERENCES, owner); + } + } else if (signedInAs(owner)) { + preferencesChanged = true; + schedule(RETRY_MILLIS); + } + })); + } + if (profileChanged) { + profileChanged = false; + final ProfileDto wanted = described(); + Preferences.set(UNSENT_PROFILE, owner); + final int send = ++profileSends; + Api.account().saveProfile(wanted, Net.to(user -> { + if (send == profileSends) { + sentFor(UNSENT_PROFILE, owner); + } + // Signing out sends what is waiting and does not wait for the + // answer. If somebody else has signed in by the time it comes, + // this profile is not theirs: kept, its name and phone would + // go out with their next change and overwrite their own. + if (signedInAs(owner)) { + profile = wanted; + } + }, (status, message) -> { + if (refused(status)) { + if (send == profileSends) { + sentFor(UNSENT_PROFILE, owner); + } + } else if (signedInAs(owner)) { + profileChanged = true; + schedule(RETRY_MILLIS); + } + })); + } + } + + /// Whether the server refused a request for what it carried, so that sent + /// again it would be refused again. Anything else -- the server not + /// reached (0), busy, failing, or the session needing a new token -- may + /// succeed later, and the change is kept for then. + private static boolean refused(int status) { + return status >= 400 && status < 500 && status != 401 && status != 408 + && status != 429; + } + + /// Whether `key` marks a change that `owner`'s account has not taken. + private static boolean isUnsent(String key, String owner) { + return owner != null && owner.equals(Preferences.get(key, "")); + } + + /// The server has what `owner` left unsent under `key`. The mark is one + /// key for every account, so an answer that comes after somebody else + /// signed in leaves theirs alone: it may be a change of their own that + /// never went through, and cleared it would be lost to the server's copy. + private static void sentFor(String key, String owner) { + if (isUnsent(key, owner)) { + Preferences.delete(key); + } + } + + /// Whether the account signed in now is `owner` ([Session#owner()]): an + /// answer that comes back after the session it was asked in has ended is + /// not acted on. + private static boolean signedInAs(String owner) { + return owner != null && owner.equals(Session.owner()); + } + + private static PreferencesDto preferences() { + String language = Prefs.language(); + return new PreferencesDto( + language.length() == 0 ? com.codenameone.examples.lingo.ui.Lang.current() + : language, + Prefs.theme(), + Prefs.notifyReminders(), + Prefs.notifyLive(), + Prefs.wifiOnlyModel(), + Prefs.cloudTutor()); + } + + /// The profile to send: the one the server gave, or the session's. + private static ProfileDto described() { + return described(profile == null ? Session.user().displayName() : profile.name()); + } + + private static ProfileDto described(String name) { + return new ProfileDto(name, profile == null ? Session.user().phone() : profile.phone()); + } + + private static void apply(PreferencesDto from) { + if (from == null) { + return; + } + applying = true; + try { + // An account that has never chosen a language leaves the device's. + if (from.language() != null && from.language().length() > 0) { + Prefs.setLanguage(from.language()); + } + Prefs.setTheme(from.theme()); + Prefs.setNotifyReminders(from.notifyReminders()); + Prefs.setNotifyLive(from.notifyLive()); + Prefs.setWifiOnlyModel(from.wifiOnlyModel()); + Prefs.setCloudTutor(from.cloudTutor()); + } finally { + applying = false; + } + } + + private static void apply(ProfileDto from) { + if (from != null) { + profile = from; + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Api.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Api.java new file mode 100644 index 00000000000..de895eaf244 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Api.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.net; + +import com.codenameone.examples.lingo.api.AccountApi; +import com.codenameone.examples.lingo.api.AdminApi; +import com.codenameone.examples.lingo.api.CommunityApi; +import com.codenameone.examples.lingo.api.LearnApi; +import com.codenameone.examples.lingo.api.StudioApi; +import com.codename1.io.rest.RestClients; + +/// The server, as the app calls it. +/// +/// Each of these is an implementation the build generated from an interface in +/// the `shared` module. The server implements the other half of the same +/// interface, so a path or a field that changes on one side stops the other +/// from compiling. +public final class Api { + private static AccountApi account; + private static LearnApi learn; + private static CommunityApi community; + private static StudioApi studio; + private static AdminApi admin; + private static String base = ""; + + private Api() { + } + + static void connect(String baseUrl) { + account = RestClients.create(AccountApi.class, baseUrl); + learn = RestClients.create(LearnApi.class, baseUrl); + community = RestClients.create(CommunityApi.class, baseUrl); + studio = RestClients.create(StudioApi.class, baseUrl); + admin = RestClients.create(AdminApi.class, baseUrl); + base = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + } + + public static AccountApi account() { + return account; + } + + /// Courses, lessons, progress, badges, certificates and the tutor. + public static LearnApi learn() { + return learn; + } + + /// Questions, live tutorials and paying creators. + public static CommunityApi community() { + return community; + } + + /// A creator's courses, recordings and live sessions. + public static StudioApi studio() { + return studio; + } + + public static AdminApi admin() { + return admin; + } + + /// `path` -- a recorded lesson's `/media/...` -- as an address a media + /// player can open. One already absolute is left as it is. + public static String absolute(String path) { + if (path == null || path.length() == 0 || path.startsWith("http://") + || path.startsWith("https://")) { + return path; + } + return base + (path.startsWith("/") ? path : "/" + path); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Session.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Session.java new file mode 100644 index 00000000000..9f940bf93dc --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/net/Session.java @@ -0,0 +1,548 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.net; + +import com.codename1.appkit.Net; + +import com.codename1.io.ConnectionRequest; +import com.codename1.io.JSONParser; +import com.codename1.io.NetworkManager; +import com.codename1.io.RequestAuthorizer; +import com.codename1.io.Util; +import com.codename1.io.oidc.OidcClient; +import com.codename1.io.oidc.OidcConfiguration; +import com.codename1.io.oidc.OidcRequestAuthorizer; +import com.codename1.io.oidc.OidcTokens; +import com.codename1.io.oidc.PkceChallenge; +import com.codename1.io.oidc.SecureStorageTokenStore; +import com.codename1.io.oidc.TokenStore; +import com.codename1.ui.CN; +import com.codename1.util.SuccessCallback; +import com.codenameone.examples.lingo.AppConfig; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.api.UserDto; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Map; + +/// Who is signed in, and the tokens that say so. +/// +/// Signing in is OAuth's authorization-code flow with PKCE against the app's +/// own server, made without a browser: the app shows its own sign-in screen, +/// posts the password to the server for a short-lived session, exchanges the +/// session for an authorization code and the code for tokens. The password is +/// sent once, to the server that owns it, and is never stored; what is stored +/// is the token pair, in the device's secure storage. +/// +/// From then on [OidcRequestAuthorizer] does the work: it puts the access token +/// on every request under `/api`, renews it shortly before it expires, and +/// renews and retries when the server refuses one. When renewing fails -- the +/// refresh token ran out, or the account was suspended -- it says so, and the +/// app goes back to the welcome screen. +public final class Session { + private static final String STORE_PREFIX = "lingo"; + private static final String SESSION_COOKIE = "CN1SESSION"; + + private static String base; + private static OidcClient client; + private static OidcRequestAuthorizer authorizer; + private static TokenStore store; + private static UserDto user; + private static Runnable onSignedOut; + /// Counts the sessions: moved on whenever the server changes, an account + /// signs in, or the session ends. An answer to a request made in an + /// earlier session describes somebody who is no longer signed in here -- + /// another server's account, or the account before a sign-out on this + /// one -- and is dropped rather than installed for whoever is now. + private static int session; + + private Session() { + } + + /// Points the app at a server. Called at start-up, and again when the + /// server address is changed. + public static void start(String baseUrl) { + if (store == null) { + // Falls back to ordinary storage where the platform has no keystore + // to offer, which is the simulator. + store = new SecureStorageTokenStore().allowPlainStorageFallback(true); + } + if (base != null) { + NetworkManager.getInstance().setAuthorizer(base + "/api", null); + if (!base.equals(baseUrl)) { + // Changing the server ends the session with the old one, and + // its tokens go with it. + store.clear(storeKey(base)); + } + } + base = baseUrl; + user = null; + session++; + client = OidcClient.create(OidcConfiguration.newBuilder() + .issuer(base) + .authorizationEndpoint(base + "/oauth2/authorize") + .tokenEndpoint(base + "/oauth2/token") + .revocationEndpoint(base + "/oauth2/revoke") + .jwksUri(base + "/oauth2/jwks") + .build()) + .setClientId(AppConfig.CLIENT_ID) + .setRedirectUri(AppConfig.redirectUri()) + .setScopes("openid", "profile") + .setTokenStore(store) + .setStoreKey(storeKey(base)); + authorizer = new OidcRequestAuthorizer(client); + authorizer.install(base + "/api"); + // Not tied to this start(). A request to an earlier server still in + // flight when the app switched, answered 401 with its refresh refused, + // signs the new server out too: one more sign-in, after a server + // switch that already asked for one, and nothing of either account is + // exposed by it. + authorizer.addSignInRequiredListener((source, reason) -> { + user = null; + session++; + if (onSignedOut != null) { + onSignedOut.run(); + } + }); + Api.connect(base); + } + + /// Where the tokens issued by one server are kept: under a name made from + /// that server's address. + /// + /// One name for every server would hand the tokens of the last one to + /// whichever address is typed next -- the app would restore them and send + /// them, refresh token included, to a server that never issued them. + /// Every character that is not a letter or a digit is written as its code, + /// so two addresses never share a name and the name is one any platform's + /// storage accepts. + static String storeKey(String server) { + StringBuilder key = new StringBuilder(STORE_PREFIX).append('-'); + for (int iter = 0; iter < server.length(); iter++) { + char c = server.charAt(iter); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { + key.append(c); + } else { + key.append('_').append(Integer.toHexString(c)).append('_'); + } + } + return key.toString(); + } + + /// Keeps the tokens somewhere else. The tests keep them in memory, so one + /// run leaves nothing behind for the next. + public static void useStore(TokenStore tokens) { + store = tokens; + } + + /// What to do when the session ends without the user asking: go back to + /// the welcome screen. + public static void onSignedOut(Runnable handler) { + onSignedOut = handler; + } + + public static String serverUrl() { + return base; + } + + /// The signed-in user as the server last described them, or null. + public static UserDto user() { + return user; + } + + public static void setUser(UserDto described) { + user = described; + if (described != null && described.username() != null) { + // What the device keeps about one person is not the next one's. + Prefs.ownedBy(owner(described.username())); + } + } + + /// Who what the device keeps belongs to: the signed-in account, or null. + /// See [#owner(String)]. + public static String owner() { + return user == null || user.username() == null ? null : owner(user.username()); + } + + /// The device's name for the account `username` on the server in use. A + /// name is unique on one server only: the same e-mail address signed in + /// to two servers is two accounts, and what one left -- recent places, + /// a change it has not sent yet -- is not the other's to see or send. + public static String owner(String username) { + return storeKey(base == null ? "" : base) + "/" + accountName(username); + } + + /// Picks up the session a previous run left, if it is still good. + /// + /// @param signedIn there is a session, and [#user] is set + /// @param signedOut there is none + /// @param unreachable there is one, but the server did not answer + public static void restore(final Runnable signedIn, final Runnable signedOut, + final Runnable unreachable) { + // Loading the tokens can outlast the session it was asked in -- the + // server is changed while it reads -- and then neither answer is this + // session's to act on: see [#session]. + final int asked = session; + authorizer.load().ready(new SuccessCallback() { + @Override + public void onSucess(OidcTokens tokens) { + if (asked != session) { + return; + } + if (tokens == null || tokens.getAccessToken() == null) { + signedOut.run(); + return; + } + refreshUser(signedIn, (status, message) -> { + if (status == 0) { + unreachable.run(); + } else { + signedOut.run(); + } + }); + } + }).except(new SuccessCallback() { + @Override + public void onSucess(Throwable err) { + if (asked == session) { + signedOut.run(); + } + } + }); + } + + /// Asks the server who this is. The roles in the answer decide which modes + /// the app offers, so it is asked again whenever that could have changed. + public static void refreshUser(final Runnable done, Net.Failed failed) { + // An answer from a session that has since ended -- the server was + // changed while an approval poll waited, or the account signed out + // and another signed in -- describes that account, not this one; + // it is dropped. See [#session]. + final int asked = session; + Api.account().me(Net.to(described -> { + if (asked != session) { + return; + } + setUser(described); + done.run(); + }, (status, message) -> { + if (asked == session) { + failed.failed(status, message); + } + })); + } + + /// Signs in with an e-mail address and password. + /// An e-mail address the way the server names its account: trimmed, with + /// its ASCII letters in lower case (`Accounts.email` on the server). Signing + /// in as `Tech@Lingo.example` must reach, and record its mode under, the + /// same account as `tech@lingo.example`. Folded by hand: `toLowerCase()` + /// follows the device locale, and under Turkish the `I` would not fold to `i`. + public static String accountName(String email) { + if (email == null) { + return null; + } + char[] chars = email.trim().toCharArray(); + for (int iter = 0; iter < chars.length; iter++) { + char c = chars[iter]; + if (c >= 'A' && c <= 'Z') { + chars[iter] = (char) (c + ('a' - 'A')); + } + } + return new String(chars); + } + + public static void signIn(String email, String password, final Runnable done, + final Net.Failed failed) { + // The server can be changed while the sign-in is under way, and + // start() then puts a new authorizer in place. Tokens the old server + // issued are dropped rather than installed in the new one, which would + // send them -- the refresh token too -- to a server that never issued + // them. See [#session]. + final int asked = session; + authenticate(email, password, tokens -> { + if (asked != session) { + return; + } + session++; + authorizer.setTokens(tokens); + store.save(storeKey(base), tokens); + refreshUser(done, failed); + }, failed); + } + + /// Exchanges an e-mail address and password for tokens, and does nothing + /// with them: [#signIn] is this, and then keeping what comes back. + public static void authenticate(final String email, final String password, + final Net.Ok got, final Net.Failed failed) { + final PkceChallenge pkce = PkceChallenge.generate(); + // Any unguessable value does for the state; this is one. + final String state = PkceChallenge.generate().getVerifier(); + // In a browser the app sees neither the session cookie nor a redirect: + // the browser keeps the first and follows the second. So there the + // password's answer is its status, and the code is read from the page + // the redirect ends on -- see AppConfig.redirectUri(). + final boolean web = AppConfig.pageOrigin() != null; + final String redirect = AppConfig.redirectUri(); + + // Every step goes to the server the sign-in started with, and none goes + // anywhere once the user has changed server: the session cookie of + // step 1 and the verifier of step 3 are only for the first server, and + // a new one that received them could replay them there for tokens. + final String server = base; + // 1. The password, for a session. + final Step login = new Step("POST", server + "/login"); + login.addArgument("username", accountName(email)); + login.addArgument("password", password); + login.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + if (login.status == 0) { + failed.failed(0, "Could not reach the server. Check your connection."); + return; + } + if (login.status == 429) { + failed.failed(429, "Too many attempts. Wait a minute and try again."); + return; + } + if (web ? login.status != 200 : login.session == null) { + failed.failed(401, "That e-mail and password do not match an account."); + return; + } + // 2. The session, for an authorization code. + final Step authorize = new Step("GET", server + "/oauth2/authorize"); + if (web) { + // Or a session that did not take is answered with a page. + authorize.addRequestHeader("Accept", "application/json"); + } else { + authorize.addRequestHeader("Cookie", login.session); + } + authorize.addArgument("response_type", "code"); + authorize.addArgument("client_id", AppConfig.CLIENT_ID); + authorize.addArgument("redirect_uri", redirect); + authorize.addArgument("scope", "openid profile"); + authorize.addArgument("state", state); + authorize.addArgument("code_challenge", pkce.getChallenge()); + authorize.addArgument("code_challenge_method", pkce.getMethod()); + authorize.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + String code = web ? authorize.answer("code") + : parameter(authorize.location, "code"); + String returned = web ? authorize.answer("state") + : parameter(authorize.location, "state"); + // The state has to come back as it went: a code that arrives + // with another was not issued for this sign-in. + if (code == null || !state.equals(returned)) { + failed.failed(authorize.status, "Signing in failed. Try again."); + return; + } + // 3. The code, for tokens. + final Step token = new Step("POST", server + "/oauth2/token"); + token.addArgument("grant_type", "authorization_code"); + token.addArgument("code", code); + token.addArgument("redirect_uri", redirect); + token.addArgument("code_verifier", pkce.getVerifier()); + token.addArgument("client_id", AppConfig.CLIENT_ID); + token.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + OidcTokens tokens = token.status == 200 ? token.tokens() : null; + if (tokens == null || tokens.getAccessToken() == null) { + failed.failed(token.status, "Signing in failed. Try again."); + return; + } + // 4. The session has done its work, and is ended rather + // than left to run out: in a browser it is a cookie that + // would go on signing this user in to whoever sat down + // next. Nothing waits on the answer; the tokens stand + // without it. + Step end = new Step("POST", server + "/logout"); + if (!web) { + end.addRequestHeader("Cookie", login.session); + } + end.send(() -> { }); + got.got(tokens); + }); + }); + }); + } + + /// Signs out: the refresh token is revoked at the server, so the session + /// is over there too and not only forgotten here. + public static void signOut(final Runnable done) { + OidcTokens tokens = authorizer.getTokens(); + if (tokens != null && tokens.getRefreshToken() != null) { + // Sent and not waited for. Signing out is something the user does + // to this phone, and it is done here whether or not the server + // answers: the tokens are gone from the device either way. A + // revocation that is lost leaves a refresh token only someone who + // already copied it off the phone could use, and it expires on + // its own; holding the sign-out until the network allows would + // trap the user signed in on a phone with no connection. + client.revoke(tokens.getRefreshToken()); + } + user = null; + session++; + authorizer.signOut().ready(new SuccessCallback() { + @Override + public void onSucess(Boolean cleared) { + done.run(); + } + }).except(new SuccessCallback() { + @Override + public void onSucess(Throwable err) { + done.run(); + } + }); + } + + /// A parameter of the query string of `url`, or null. + static String parameter(String url, String name) { + int query = url == null ? -1 : url.indexOf('?'); + if (query < 0) { + return null; + } + int at = query + 1; + while (at < url.length()) { + int end = url.indexOf('&', at); + if (end < 0) { + end = url.length(); + } + if (url.startsWith(name + "=", at)) { + return Util.decode(url.substring(at + name.length() + 1, end), "UTF-8", false); + } + at = end + 1; + } + return null; + } + + /// One request of the sign-in. It follows no redirect and keeps no cookie + /// jar, because the redirect and the cookie are the answers it is after; + /// and it carries no bearer token, because there is not one yet. + private static final class Step extends ConnectionRequest { + int status; + String location; + String session; + private byte[] body; + private Runnable then; + private boolean reported; + + Step(String method, String url) { + setUrl(url); + setHttpMethod(method); + setPost(!"GET".equals(method)); + setFollowRedirects(false); + setCookiesEnabled(false); + setReadResponseForErrors(true); + setDuplicateSupported(true); + setFailSilently(true); + setAuthorizer(RequestAuthorizer.NONE); + } + + void send(Runnable next) { + then = next; + NetworkManager.getInstance().addToQueue(this); + } + + /// A text member of the JSON this request was answered with, or null. + String answer(String name) { + if (status != 200 || body == null) { + return null; + } + try { + Map json = new JSONParser().parseJSON(new InputStreamReader( + new ByteArrayInputStream(body), "UTF-8")); + Object value = json == null ? null : json.get(name); + return value instanceof String ? (String) value : null; + } catch (IOException malformed) { + return null; + } catch (RuntimeException malformed) { + return null; + } + } + + OidcTokens tokens() { + try { + Map json = new JSONParser().parseJSON(new InputStreamReader( + new ByteArrayInputStream(body == null ? new byte[0] : body), "UTF-8")); + return OidcTokens.fromTokenResponse(json, null); + } catch (IOException malformed) { + return null; + } catch (RuntimeException malformed) { + return null; + } + } + + @Override + protected void readHeaders(Object connection) throws IOException { + location = getHeader(connection, "Location"); + String[] cookies = getHeaders(connection, "Set-Cookie"); + for (int iter = 0; cookies != null && iter < cookies.length; iter++) { + if (cookies[iter] != null && cookies[iter].startsWith(SESSION_COOKIE + "=")) { + int end = cookies[iter].indexOf(';'); + session = end < 0 ? cookies[iter] : cookies[iter].substring(0, end); + } + } + } + + @Override + protected void handleErrorResponseCode(int code, String message) { + status = code; + } + + @Override + protected void readResponse(InputStream input) throws IOException { + if (status == 0) { + status = getResponseCode(); + } + body = Util.readInputStream(input); + } + + @Override + protected void postResponse() { + if (status == 0) { + status = getResponseCode(); + } + report(); + } + + @Override + protected void handleException(Exception err) { + status = 0; + report(); + } + + private void report() { + if (!reported) { + reported = true; + CN.callSerially(then); + } + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/notify/Notifications.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/notify/Notifications.java new file mode 100644 index 00000000000..af3491f496a --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/notify/Notifications.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.notify; + +import com.codename1.push.PushClient; +import com.codename1.push.PushError; +import com.codename1.push.PushListener; +import com.codename1.push.PushMessage; +import com.codename1.push.PushSubscription; +import com.codename1.ui.CN; +import com.codenameone.examples.lingo.AppConfig; +import com.codenameone.examples.lingo.api.PushDeviceDto; +import com.codenameone.examples.lingo.net.Api; +import com.codename1.appkit.Net; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Nav; + +/// Push notifications: a practice reminder or a class starting, for a phone in a pocket. +/// +/// The phone registers with the platform's push service once, and the token +/// it gets is handed to the Lingo server for whoever is signed in. Signing +/// out takes it back, so the next person to use the phone is not told about +/// the last one's classes. The server decides what to send and when; see the +/// server's `Notices`. +/// +/// Only on a phone (Android and iOS) and only with [AppConfig#PUSH_APP_KEY] +/// set. The simulator has no push service to register with, and a browser +/// build is told everything over the live channel while its page is open. +public final class Notifications { + private static final Net.Failed QUIET = (status, message) -> { }; + private static PushClient client; + private static PushSubscription subscription; + + private Notifications() { + } + + // tag::lingo-push-register[] + /// Asks the platform for a push token. Called every time the app comes to + /// the foreground; registering is idempotent, and the platform answers + /// with the token it already gave when nothing has changed. + public static void start() { + if (!available()) { + return; + } + if (client == null) { + client = PushClient.builder(AppConfig.PUSH_APP_KEY) + .listener(new Listener()) + .build(); + } + client.register(); + } + + /// Someone has signed in: the server learns where to reach them. + public static void signedIn() { + PushDeviceDto device = device(); + if (device != null && Session.user() != null) { + Api.account().registerPush(device, Net.to(saved -> { }, QUIET)); + } + } + + /// Someone is signing out: the server forgets this phone for them, and + /// then `then` runs. It runs whether or not the server could be reached; + /// signing out never waits on a notification. + public static void signingOut(Runnable then) { + PushDeviceDto device = device(); + if (device == null || Session.user() == null) { + then.run(); + return; + } + // A failure is not kept for retrying. The row it would remove names + // this phone's token, and the next sign-in on the phone takes that row + // over for whoever signs in, as the server keeps a phone on the + // account that signed in on it last. What is lost to an outage is + // the window until then, on the phone of the account that signed out + // -- noted in the implementor's guide among the hardening a + // production deployment adds, not worth a durable queue in a sample. + Api.account().unregisterPush(device, Net.to(gone -> then.run(), + (status, message) -> then.run())); + } + // end::lingo-push-register[] + + /// Whether this build can be sent notifications at all. + public static boolean available() { + if (AppConfig.PUSH_APP_KEY.length() == 0 || CN.isSimulator()) { + return false; + } + String platform = CN.getPlatformName(); + return "and".equals(platform) || "ios".equals(platform); + } + + private static PushDeviceDto device() { + if (subscription == null) { + return null; + } + return new PushDeviceDto(subscription.getTransportId(), subscription.getToken(), + CN.getPlatformName()); + } + + // tag::lingo-push-listener[] + /// Called on the event thread. A message is a reminder or a class + /// starting: the app opens the learner's home, which reads the rest from + /// the server. The + /// message's own words are for the notification shade, not for the app. + private static final class Listener implements PushListener { + @Override + public void onRegistration(PushSubscription registered) { + subscription = registered; + signedIn(); + } + + @Override + public void onMessage(PushMessage message) { + // A reminder to practise, or a live session about to start: + // either way the learner's home is where to go. + if (Session.user() != null) { + Nav.showLearn(); + } + } + + @Override + public void onError(PushError error) { + // Nothing to tell the user: the app works without notifications, + // and asks again the next time it comes to the foreground. + System.out.println("Push registration failed: " + error.getCode() + " " + + error.getMessage()); + } + } + // end::lingo-push-listener[] +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/PronunciationScorer.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/PronunciationScorer.java new file mode 100644 index 00000000000..445db722274 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/PronunciationScorer.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.speech; + +import java.util.ArrayList; +import java.util.List; + +/// Scores how closely what the recognizer heard matches the phrase the +/// learner was asked to say, word by word. +/// +/// A recognizer writes down words, not sounds, so this is a measure of +/// intelligibility: whether a native listener -- the recognizer, trained on +/// native speech -- understood each word. That is the bar a learner cares +/// about, and it needs no model of the language's phonology. The words are +/// aligned (an edit distance over words, where swapping one word for another +/// costs how different their letters are), so a dropped or extra word costs +/// one word and does not shift every word after it. +/// +/// Comparison ignores case, accents and punctuation: recognizers disagree on +/// all three ("como" for "como" with an accent, no inverted question mark), +/// and a learner should not lose points for the recognizer's spelling. The +/// folding is done here, character by character, never with +/// `toLowerCase()`, which depends on the device's locale. +public final class PronunciationScorer { + /// A word at or above this likeness was said well. + public static final int GOOD = 80; + /// A word at or above this likeness was close. + public static final int CLOSE = 50; + + /// Accented Latin letters, and the plain letter each folds to. + private static final String FOLD_FROM = "\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d9\u00da\u00db\u00dc\u00dd\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f9\u00fa\u00fb\u00fc\u00fd\u00ff\u0100\u0101\u0102\u0103\u0104\u0105\u0106\u0107\u0108\u0109\u010a\u010b\u010c\u010d\u010e\u010f\u0112\u0113\u0114\u0115\u0116\u0117\u0118\u0119\u011a\u011b\u011c\u011d\u011e\u011f\u0120\u0121\u0122\u0123\u0124\u0125\u0128\u0129\u012a\u012b\u012c\u012d\u012e\u012f\u0130\u0134\u0135\u0136\u0137\u0139\u013a\u013b\u013c\u013d\u013e\u0143\u0144\u0145\u0146\u0147\u0148\u014c\u014d\u014e\u014f\u0150\u0151\u0154\u0155\u0156\u0157\u0158\u0159\u015a\u015b\u015c\u015d\u015e\u015f\u0160\u0161\u0162\u0163\u0164\u0165\u0168\u0169\u016a\u016b\u016c\u016d\u016e\u016f\u0170\u0171\u0172\u0173\u0174\u0175\u0176\u0177\u0178\u0179\u017a\u017b\u017c\u017d\u017e"; + private static final String FOLD_TO = "aaaaaaceeeeiiiinooooouuuuyaaaaaaceeeeiiiinooooouuuuyyaaaaaaccccccccddeeeeeeeeeegggggggghhiiiiiiiiijjkkllllllnnnnnnoooooorrrrrrssssssssttttuuuuuuuuuuuuwwyyyzzzzzz"; + + private PronunciationScorer() { + } + + /// How one word of the target was said. + public static final class Word { + /// The word as the phrase spells it, for display. + public final String text; + /// What was heard in its place, folded; empty when nothing was. + public final String heard; + /// 0 to 100. + public final int likeness; + + Word(String text, String heard, int likeness) { + this.text = text; + this.heard = heard; + this.likeness = likeness; + } + + public boolean good() { + return likeness >= GOOD; + } + + public boolean close() { + return likeness >= CLOSE && likeness < GOOD; + } + } + + /// The outcome of one try. + public static final class Result { + /// 0 to 100. + public final int score; + public final List words; + /// The transcript the score was taken from: the best of those offered. + public final String heard; + + Result(int score, List words, String heard) { + this.score = score; + this.words = words; + this.heard = heard; + } + + /// The words said badly or not at all, for the tutor to explain. + public List missed() { + List out = new ArrayList(); + for (Word word : words) { + if (!word.good()) { + out.add(word); + } + } + return out; + } + } + + /// Scores `heard` and each of `alternatives` (a recognizer's other + /// guesses, which may be null) against `target`, and keeps the best: + /// the recognizer's first guess is its most likely, not necessarily the + /// learner's. `confidence` (0 to 1, or below 0 when unknown) counts for a + /// sixth of the score. + public static Result score(String target, String heard, String[] alternatives, + float confidence) { + Result best = score(target, heard); + if (alternatives != null) { + for (String other : alternatives) { + Result r = score(target, other); + if (r.score > best.score) { + best = r; + } + } + } + if (confidence < 0 || confidence > 1 || best.score == 0) { + return best; + } + int blended = Math.round(best.score * 5f / 6f + confidence * 100f / 6f); + return new Result(Math.min(100, blended), best.words, best.heard); + } + + /// Scores one transcript against `target`. + public static Result score(String target, String heard) { + List shown = split(target, false); + List want = split(target, true); + List got = split(heard == null ? "" : heard, true); + int n = want.size(); + int m = got.size(); + // cost[i][j]: aligning the first i target words with the first j + // heard ones; a word missed or added costs 100, a swap 100 - likeness. + int[][] cost = new int[n + 1][m + 1]; + for (int i = 0; i <= n; i++) { + cost[i][0] = i * 100; + } + for (int j = 0; j <= m; j++) { + cost[0][j] = j * 100; + } + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + int swap = cost[i - 1][j - 1] + 100 - likeness(want.get(i - 1), got.get(j - 1)); + int skip = Math.min(cost[i - 1][j], cost[i][j - 1]) + 100; + cost[i][j] = Math.min(swap, skip); + } + } + // Walk back to find what each target word was matched with. + String[] matched = new String[n]; + int[] like = new int[n]; + int i = n; + int j = m; + while (i > 0 && j > 0) { + int l = likeness(want.get(i - 1), got.get(j - 1)); + if (cost[i][j] == cost[i - 1][j - 1] + 100 - l) { + matched[i - 1] = got.get(j - 1); + like[i - 1] = l; + i--; + j--; + } else if (cost[i][j] == cost[i - 1][j] + 100) { + i--; + } else { + j--; + } + } + List words = new ArrayList(); + int total = 0; + for (int k = 0; k < n; k++) { + words.add(new Word(k < shown.size() ? shown.get(k) : want.get(k), + matched[k] == null ? "" : matched[k], like[k])); + total += like[k]; + } + // Extra words the learner added count against them, a little. + int extra = Math.max(0, m - n); + int score = n == 0 ? 0 : Math.max(0, (total - extra * 25) / n); + return new Result(Math.min(100, score), words, heard == null ? "" : heard); + } + + /// 0 to 100: one minus the edit distance between the two folded words + /// over the longer one's length. + static int likeness(String a, String b) { + if (a.equals(b)) { + return 100; + } + int longest = Math.max(a.length(), b.length()); + if (longest == 0) { + return 100; + } + int[] previous = new int[b.length() + 1]; + int[] current = new int[b.length() + 1]; + for (int j = 0; j <= b.length(); j++) { + previous[j] = j; + } + for (int i = 1; i <= a.length(); i++) { + current[0] = i; + for (int j = 1; j <= b.length(); j++) { + int same = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1; + current[j] = Math.min(Math.min(current[j - 1] + 1, previous[j] + 1), + previous[j - 1] + same); + } + int[] swap = previous; + previous = current; + current = swap; + } + return Math.max(0, 100 - previous[b.length()] * 100 / longest); + } + + /// The words of `text`: split on anything that is not a letter or a digit, + /// an apostrophe joining the two sides ("m'appelle" is one word). Folded + /// for comparing when `fold`, else as written, for showing. + static List split(String text, boolean fold) { + List out = new ArrayList(); + StringBuilder word = new StringBuilder(); + StringBuilder shown = new StringBuilder(); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '\'' || c == '\u2019') { + shown.append(c); + continue; + } + int before = word.length(); + fold(c, word); + if (word.length() > before) { + shown.append(c); + } else if (word.length() > 0) { + out.add(fold ? word.toString() : shown.toString()); + word.setLength(0); + shown.setLength(0); + } else { + shown.setLength(0); + } + } + if (word.length() > 0) { + out.add(fold ? word.toString() : shown.toString()); + } + return out; + } + + /// Appends `c` folded to plain lower-case ASCII -- nothing for a + /// character that is not a letter or a digit. Letters outside Latin + /// (Japanese, Cyrillic) are kept as they are: they have no case or + /// accents to fold, and a recognizer writes them the same way. + static void fold(char c, StringBuilder out) { + if (c >= 'a' && c <= 'z' || c >= '0' && c <= '9') { + out.append(c); + return; + } + if (c >= 'A' && c <= 'Z') { + out.append((char) (c + ('a' - 'A'))); + return; + } + if (c < 0xC0) { + return; + } + int at = FOLD_FROM.indexOf(c); + if (at >= 0) { + out.append(FOLD_TO.charAt(at)); + return; + } + switch (c) { + case '\u00df': + out.append("ss"); + return; + case '\u00e6': + out.append("ae"); + return; + case '\u00c6': + out.append("ae"); + return; + case '\u0153': + out.append("oe"); + return; + case '\u0152': + out.append("oe"); + return; + case '\u00f8': + out.append("o"); + return; + case '\u00d8': + out.append("o"); + return; + case '\u0142': + out.append("l"); + return; + case '\u0141': + out.append("l"); + return; + case '\u0111': + out.append("d"); + return; + case '\u0110': + out.append("d"); + return; + default: + break; + } + if (c >= 0x370 && Character.isLetterOrDigit(c)) { + out.append(c); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/Voice.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/Voice.java new file mode 100644 index 00000000000..fe22712829c --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/speech/Voice.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.speech; + +import com.codename1.media.RecognitionCallback; +import com.codename1.media.RecognitionOptions; +import com.codename1.media.SpeechRecognizer; +import com.codename1.media.TextToSpeech; +import com.codename1.media.TtsOptions; +import com.codename1.ui.CN; + +/// The device's voice and ears: text to speech for the model phrase, speech +/// recognition for the learner's answer, both in the lesson's language. +/// +/// Both run on the device -- iOS's and Android's own engines -- so a +/// pronunciation drill works offline. Where there is no recognizer (the +/// simulator, some desktops) the lesson offers a keyboard instead, and the +/// tests put their own [Ears] in. +public final class Voice { + /// What was heard, on the EDT. + public interface Heard { + /// Words so far, while the learner is still speaking. + void partial(String text); + + /// The final transcript, the recognizer's confidence (0 to 1, or + /// below 0 when it gives none) and its other guesses. + void heard(String text, float confidence, String[] alternatives); + + /// Nothing was heard, or the recognizer failed. + void nothing(String why); + } + + /// Something that listens: the device's recognizer, or a test's. + public interface Ears { + boolean available(); + + void listen(String languageTag, Heard heard); + + void stop(); + } + + private static Ears ears = new DeviceEars(); + /// Slower than a native speaker by default: this is a model to copy. + private static float rate = 0.85f; + + private Voice() { + } + + /// Replaces the recognizer, for a test; null puts the device's back. + public static void useEars(Ears replacement) { + ears = replacement == null ? new DeviceEars() : replacement; + } + + public static boolean canSpeak() { + return TextToSpeech.isSupported(); + } + + public static boolean canListen() { + return ears.available(); + } + + /// Says `text` in `languageTag`. `slow` slows the pace, for the + /// "say it slowly" button. + public static void speak(String text, String languageTag, boolean slow) { + if (!canSpeak() || text == null || text.length() == 0) { + return; + } + TextToSpeech.stop(); + TextToSpeech.speak(text, new TtsOptions().setLanguageTag(languageTag) + .setRate(slow ? rate * 0.6f : rate)); + } + + public static void listen(String languageTag, Heard heard) { + TextToSpeech.stop(); + ears.listen(languageTag, heard); + } + + public static void stop() { + ears.stop(); + if (canSpeak()) { + TextToSpeech.stop(); + } + } + + /// The platform recognizer. Its callbacks may come on any thread; each + /// is moved to the EDT, and only the first ending is passed on. + static final class DeviceEars implements Ears { + @Override + public boolean available() { + return SpeechRecognizer.isSupported(); + } + + @Override + public void listen(String languageTag, final Heard heard) { + final boolean[] ended = new boolean[1]; + SpeechRecognizer.recognize(new RecognitionOptions().setLanguageTag(languageTag) + .setPartialResults(true).setMaxResults(5), new RecognitionCallback() { + @Override + public void onPartialResult(final String transcript) { + CN.callSerially(() -> { + if (!ended[0]) { + heard.partial(transcript); + } + }); + } + + @Override + public void onResult(final String transcript, final float confidence, + final String[] alternatives) { + CN.callSerially(() -> { + if (!ended[0]) { + ended[0] = true; + heard.heard(transcript == null ? "" : transcript, confidence, + alternatives); + } + }); + } + + @Override + public void onEnd() { + CN.callSerially(() -> { + if (!ended[0]) { + ended[0] = true; + heard.nothing("Nothing was heard. Tap the microphone and " + + "speak."); + } + }); + } + + @Override + public void onError(final Throwable t) { + CN.callSerially(() -> { + if (!ended[0]) { + ended[0] = true; + heard.nothing("Listening failed. Check the microphone " + + "permission."); + } + }); + } + }); + } + + @Override + public void stop() { + SpeechRecognizer.stop(); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/CourseEditor.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/CourseEditor.java new file mode 100644 index 00000000000..0dde57a59c2 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/CourseEditor.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.api.CourseDetailDto; +import com.codenameone.examples.lingo.api.CourseDraftDto; +import com.codenameone.examples.lingo.api.LessonDto; +import com.codenameone.examples.lingo.learn.Kit; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; + +/// Making a course: its details first, then its lessons one by one, then +/// publishing it. A draft is seen by nobody but its creator. +final class CourseEditor { + static final String[] LANGUAGES = {"es-ES", "fr-FR", "de-DE", "it-IT", "pt-BR", "ja-JP"}; + static final String[] LEVELS = {"A1", "A2", "B1", "B2", "C1"}; + static final String[] PRICES = {"0", "299", "499", "999"}; + static final String[] ACCENTS = {"indigo", "coral", "teal", "amber", "rose", "sky"}; + + private CourseEditor() { + } + + static void create(final Form previous) { + final Form form = Ui.form(Lang.tr("New course"), "NewCourse"); + Ui.back(form, previous); + Container page = Ui.page(); + final TextField title = Ui.field(page, Lang.tr("Title"), "course-title", + Lang.tr("Spanish for the market")); + final TextArea summary = Ui.field(page, Lang.tr("What learners will be able to do"), + "course-summary", Lang.tr("Order, haggle and chat with stallholders")); + final String[] chosen = {LANGUAGES[0], LEVELS[0], PRICES[0], ACCENTS[0]}; + page.add(new Label(Lang.tr("Language"), "LnLabel")); + String[] names = new String[LANGUAGES.length]; + for (int iter = 0; iter < names.length; iter++) { + names[iter] = com.codenameone.examples.lingo.api.Languages.name(LANGUAGES[iter]); + } + page.add(Ui.choice("course-language", names, LANGUAGES, chosen[0], v -> chosen[0] = v, 3)); + page.add(new Label(Lang.tr("Level"), "LnLabel")); + page.add(Ui.choice("course-level", LEVELS, LEVELS, chosen[1], v -> chosen[1] = v)); + page.add(new Label(Lang.tr("Price"), "LnLabel")); + String[] prices = new String[PRICES.length]; + for (int iter = 0; iter < prices.length; iter++) { + prices[iter] = Kit.money(Integer.parseInt(PRICES[iter])); + } + page.add(Ui.choice("course-price", prices, PRICES, chosen[2], v -> chosen[2] = v)); + page.add(Ui.text(Lang.tr("You keep 70% of every sale."), "LnFieldHint")); + page.add(new Label(Lang.tr("Colour"), "LnLabel")); + Container colours = new Container(BoxLayout.x()); + final Label[] swatches = new Label[ACCENTS.length]; + for (int iter = 0; iter < ACCENTS.length; iter++) { + final String accent = ACCENTS[iter]; + final Label swatch = new Label(iter == 0 ? "\u2713" : " ", Kit.cover(accent)); + swatches[iter] = swatch; + Container hit = BorderLayout.center(swatch); + Ui.tap(hit, "accent-" + accent, e -> { + chosen[3] = accent; + for (int j = 0; j < swatches.length; j++) { + swatches[j].setText(ACCENTS[j].equals(accent) ? "\u2713" : " "); + } + colours.revalidate(); + }); + colours.add(hit); + } + page.add(colours); + page.add(Ui.primary(Lang.tr("Create course"), "save-course", e -> { + if (title.getText().trim().length() < 3) { + Ui.say(Lang.tr("Give the course a title")); + return; + } + Api.studio().createCourse(new CourseDraftDto(title.getText().trim(), chosen[0], + chosen[1], summary.getText().trim(), Integer.parseInt(chosen[2]), chosen[3]), + Net.to(course -> edit(course.id(), StudioHome.home()), Ui::fail)); + })); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + static void edit(final String courseId, final Form previous) { + final Form form = Ui.form(Lang.tr("Course"), "EditCourse"); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + Ui.back(form, () -> StudioHome.back()); + final Container page = new Container(BoxLayout.y()); + page.setScrollableY(true); + page.setUIID("LnCanvas"); + page.add(new Skeleton(4, "LnSkeleton")); + form.add(BorderLayout.CENTER, page); + form.show(); + Api.learn().course(courseId, Net.to(detail -> fill(form, page, detail), + Ui.failed(page, null))); + } + + private static void fill(final Form form, Container page, final CourseDetailDto detail) { + page.removeAll(); + Container card = new Container(BoxLayout.y()); + card.setUIID("LnCourseCard"); + card.add(Kit.coverOf(detail.course())); + Container body = new Container(BoxLayout.y()); + body.setUIID("LnCourseBody"); + body.add(Ui.text(detail.course().title(), "LnCourseTitle")); + body.add(Ui.text(detail.course().summary(), "LnCourseMeta")); + body.add(new Label((detail.course().published() ? Lang.tr("Published") + : Lang.tr("Draft")) + Ui.DOT + Kit.money(detail.course().priceCents()), + detail.course().published() ? "LnKindTag" : "LnDraftTag")); + card.add(body); + Container wrap = new Container(BoxLayout.y()); + wrap.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + wrap.getAllStyles().setPadding(4, 4, 12, 12); + wrap.add(card); + page.add(wrap); + page.add(com.codenameone.examples.lingo.learn.Kit.section("Lessons", "Add", + () -> LessonEditor.show(detail.course(), form))); + if (detail.lessons().isEmpty()) { + page.add(Ui.empty(FontImage.MATERIAL_PLAYLIST_ADD, Lang.tr("No lessons yet"), + Lang.tr("Add a video, phrases to practise or a conversation scene."))); + } + int n = 1; + for (LessonDto l : detail.lessons()) { + Container row = Ui.row(icon(l.kind()), n++ + ". " + l.title(), + Ui.duration(l.minutes()) + Ui.DOT + l.summary(), null); + row.setUIID("LnStepCard"); + page.add(row); + } + Container foot = new Container(BoxLayout.y()); + foot.setUIID("LnLessonFoot"); + foot.setSafeArea(true); + foot.add(Ui.secondary(Lang.tr("Add a lesson"), "add-lesson", + e -> LessonEditor.show(detail.course(), form))); + if (!detail.course().published()) { + foot.add(Ui.primary(Lang.tr("Publish"), "publish", e -> + Api.studio().publish(detail.course().id(), Net.to(c -> { + Ui.say(Lang.tr("Your course is live")); + StudioHome.back(); + }, Ui::fail)))); + } + com.codename1.ui.Component old = ((BorderLayout) form.getContentPane().getLayout()) + .getSouth(); + if (old != null) { + old.remove(); + } + form.add(BorderLayout.SOUTH, foot); + form.revalidate(); + } + + static char icon(String kind) { + if ("video".equals(kind)) { + return FontImage.MATERIAL_SMART_DISPLAY; + } + if ("conversation".equals(kind)) { + return FontImage.MATERIAL_FORUM; + } + return FontImage.MATERIAL_RECORD_VOICE_OVER; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LessonEditor.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LessonEditor.java new file mode 100644 index 00000000000..d25b627c89a --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LessonEditor.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.Net; +import com.codename1.capture.Capture; +import com.codename1.capture.VideoCaptureConstraints; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.Log; +import com.codename1.io.Util; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.util.Base64; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LessonDraftDto; +import com.codenameone.examples.lingo.api.PhraseDto; +import com.codenameone.examples.lingo.api.UploadDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +/// One lesson: a video the creator records or picks, phrases to practise +/// aloud, or a scene for the AI tutor to role-play. +final class LessonEditor { + /// What the server accepts in one upload. + static final int MAX_BYTES = 8 * 1024 * 1024; + + private LessonEditor() { + } + + static void show(final CourseDto course, final Form previous) { + final Form form = Ui.form(Lang.tr("New lesson"), "NewLesson"); + Ui.back(form, previous); + final Container page = Ui.page(); + final String[] kind = {"phrases"}; + final String[] video = {null}; + final TextField title = Ui.field(page, Lang.tr("Title"), "lesson-title", + Lang.tr("At the fruit stall")); + final TextField summary = Ui.field(page, Lang.tr("In one line"), "lesson-summary", + Lang.tr("Ask for prices and quantities")); + page.add(new Label(Lang.tr("Kind"), "LnLabel")); + final Container detail = new Container(BoxLayout.y()); + final List phrases = new ArrayList(); + final TextField scenario = new TextField("", Lang.tr("You are a stallholder at a busy " + + "market..."), 20, TextField.ANY); + scenario.setUIID("LnField"); + scenario.setName("lesson-scenario"); + scenario.setSingleLineTextArea(false); + scenario.setRows(3); + final Runnable[] render = new Runnable[1]; + render[0] = () -> { + detail.removeAll(); + if ("phrases".equals(kind[0])) { + detail.add(new Label(Lang.tr("Phrases to say aloud"), "LnLabel")); + if (phrases.isEmpty()) { + phrases.add(phraseFields()); + } + for (TextField[] p : phrases) { + Container pair = new Container(new GridLayout(1, 2)); + pair.add(p[0]).add(p[1]); + detail.add(pair); + } + detail.add(Ui.link(Lang.tr("Add a phrase"), "add-phrase", e -> { + phrases.add(phraseFields()); + render[0].run(); + })); + } else if ("conversation".equals(kind[0])) { + detail.add(new Label(Lang.tr("The scene the AI tutor plays"), "LnLabel")); + detail.add(scenario); + detail.add(Ui.text(Lang.tr("The tutor stays in the scene, speaks the course's " + + "language at its level, and corrects mistakes."), "LnFieldHint")); + } else { + detail.add(new Label(Lang.tr("Video"), "LnLabel")); + Label state = new Label(video[0] == null ? Lang.tr("No video yet") + : Lang.tr("Video uploaded"), video[0] == null ? "LnStepMeta" : "LnTick"); + state.setName("video-state"); + detail.add(state); + Container buttons = new Container(new GridLayout(1, 2)); + Button record = Ui.secondary(Lang.tr("Record"), "record", e -> + Capture.captureVideo(new VideoCaptureConstraints() + .preferredMaxLength(90).preferredMaxFileSize(MAX_BYTES), + ev -> upload(ev == null ? null : (String) ev.getSource(), + url -> { + video[0] = url; + render[0].run(); + }))); + FontImage.setMaterialIcon(record, FontImage.MATERIAL_VIDEOCAM, 3.6f); + Button pick = Ui.secondary(Lang.tr("Choose"), "pick", e -> + CN.openGallery(ev -> upload(ev == null ? null : (String) ev.getSource(), + url -> { + video[0] = url; + render[0].run(); + }), CN.GALLERY_VIDEO)); + FontImage.setMaterialIcon(pick, FontImage.MATERIAL_VIDEO_LIBRARY, 3.6f); + buttons.add(record).add(pick); + detail.add(buttons); + detail.add(Ui.text(Lang.tr("Up to 90 seconds and 8 MB. Learners can replay " + + "and seek."), "LnFieldHint")); + } + page.revalidate(); + }; + page.add(Ui.choice("lesson-kind", new String[] {Lang.tr("Phrases"), Lang.tr("Talk"), + Lang.tr("Video")}, new String[] {"phrases", "conversation", "video"}, kind[0], v -> { + kind[0] = v; + render[0].run(); + })); + page.add(detail); + render[0].run(); + page.add(Ui.primary(Lang.tr("Save lesson"), "save-lesson", e -> { + List list = new ArrayList(); + for (TextField[] p : phrases) { + if (p[0].getText().trim().length() > 0) { + list.add(new PhraseDto(p[0].getText().trim(), p[1].getText().trim(), "")); + } + } + int minutes = "conversation".equals(kind[0]) ? 6 : "video".equals(kind[0]) ? 4 + : Math.max(2, list.size()); + Api.studio().addLesson(course.id(), new LessonDraftDto(title.getText().trim(), + kind[0], summary.getText().trim(), list, scenario.getText().trim(), video[0], + minutes), Net.to(saved -> CourseEditor.edit(course.id(), + StudioHome.home()), Ui::fail)); + })); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + private static TextField[] phraseFields() { + TextField text = new TextField("", Lang.tr("\u00bfCu\u00e1nto cuesta?")); + text.setUIID("LnField"); + text.setName("phrase-text"); + TextField meaning = new TextField("", Lang.tr("How much is it?")); + meaning.setUIID("LnField"); + meaning.setName("phrase-meaning"); + return new TextField[] {text, meaning}; + } + + interface Uploaded { + void uploaded(String url); + } + + /// Sends the file at `path` to the server, which stores it and answers + /// the address learners play it from. + static void upload(String path, Uploaded done) { + if (path == null) { + return; + } + byte[] data; + try (InputStream in = FileSystemStorage.getInstance().openInputStream(path)) { + data = Util.readInputStream(in); + } catch (java.io.IOException unreadable) { + Log.e(unreadable); + Ui.say(Lang.tr("The video could not be read")); + return; + } + if (data.length > MAX_BYTES) { + Ui.say(Lang.tr("The video is over 8 MB. Record a shorter one.")); + return; + } + String name = path.substring(path.lastIndexOf('/') + 1); + String mime = name.endsWith(".mov") ? "video/quicktime" : "video/mp4"; + Ui.say(Lang.tr("Uploading...")); + Api.studio().upload(new UploadDto(name, mime, Base64.encodeNoNewline(data)), + Net.to(up -> done.uploaded(up.url()), Ui::fail)); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LiveScheduler.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LiveScheduler.java new file mode 100644 index 00000000000..1b101f3c963 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/LiveScheduler.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.Net; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.spinner.Picker; +import com.codenameone.examples.lingo.api.LiveDraftDto; +import com.codenameone.examples.lingo.api.Languages; +import com.codenameone.examples.lingo.learn.Kit; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Ui; +import java.util.Date; + +/// Scheduling a live class: when, how long, how many seats, at what price. +final class LiveScheduler { + private LiveScheduler() { + } + + static void show(final Form previous) { + final Form form = Ui.form(Lang.tr("Schedule a class"), "ScheduleLive"); + Ui.back(form, previous); + Container page = Ui.page(); + final TextField title = Ui.field(page, Lang.tr("Title"), "live-title", + Lang.tr("Rolling your R, live")); + final String[] chosen = {CourseEditor.LANGUAGES[0], "A2", "45", "0", "8"}; + page.add(new Label(Lang.tr("Starts"), "LnLabel")); + final Picker when = new Picker(); + when.setType(com.codename1.ui.Display.PICKER_TYPE_DATE_AND_TIME); + when.setDate(new Date(System.currentTimeMillis() + 86400000L)); + when.setUIID("LnField"); + when.setName("live-when"); + page.add(when); + page.add(new Label(Lang.tr("Language"), "LnLabel")); + String[] names = new String[CourseEditor.LANGUAGES.length]; + for (int iter = 0; iter < names.length; iter++) { + names[iter] = Languages.name(CourseEditor.LANGUAGES[iter]); + } + page.add(Ui.choice("live-language", names, CourseEditor.LANGUAGES, chosen[0], + v -> chosen[0] = v, 3)); + page.add(new Label(Lang.tr("Level"), "LnLabel")); + page.add(Ui.choice("live-level", CourseEditor.LEVELS, CourseEditor.LEVELS, chosen[1], + v -> chosen[1] = v)); + page.add(new Label(Lang.tr("Length"), "LnLabel")); + page.add(Ui.choice("live-minutes", new String[] {"30 min", "45 min", "60 min"}, + new String[] {"30", "45", "60"}, chosen[2], v -> chosen[2] = v)); + page.add(new Label(Lang.tr("Seat price"), "LnLabel")); + String[] prices = new String[CourseEditor.PRICES.length]; + for (int iter = 0; iter < prices.length; iter++) { + prices[iter] = Kit.money(Integer.parseInt(CourseEditor.PRICES[iter])); + } + page.add(Ui.choice("live-price", prices, CourseEditor.PRICES, chosen[3], + v -> chosen[3] = v)); + page.add(new Label(Lang.tr("Seats"), "LnLabel")); + page.add(Ui.choice("live-seats", new String[] {"4", "8", "12"}, + new String[] {"4", "8", "12"}, chosen[4], v -> chosen[4] = v)); + page.add(Ui.primary(Lang.tr("Schedule"), "save-live", e -> { + if (title.getText().trim().length() < 3) { + Ui.say(Lang.tr("Give the class a title")); + return; + } + Api.studio().schedule(new LiveDraftDto(title.getText().trim(), chosen[0], chosen[1], + when.getDate().getTime(), Integer.parseInt(chosen[2]), + Integer.parseInt(chosen[3]), Integer.parseInt(chosen[4])), Net.to(s -> { + Ui.say(Lang.tr("Scheduled. Learners can book seats now.")); + StudioHome.back(); + }, Ui::fail)); + })); + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/StudioHome.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/StudioHome.java new file mode 100644 index 00000000000..21bb3b78b30 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/studio/StudioHome.java @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.studio; + +import com.codename1.appkit.Net; +import com.codename1.appkit.Skeleton; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.lingo.api.CourseDto; +import com.codenameone.examples.lingo.api.LiveSessionDto; +import com.codenameone.examples.lingo.api.StudioDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.learn.Kit; +import com.codenameone.examples.lingo.live.LiveChannel; +import com.codenameone.examples.lingo.live.LiveRoom; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Nav; +import com.codenameone.examples.lingo.ui.Ui; + +/// The creator's studio: what they earned, their courses (drafts and +/// published), their live classes -- and the button to make something new. +public final class StudioHome implements Nav.Home { + private static StudioHome current; + private Form form; + private Container page; + + @Override + public void start() { + current = this; + form = Ui.form("", "StudioHome"); + form.getToolbar().hideToolbar(); + form.setUIID("LnCanvas"); + form.getContentPane().setUIID("LnCanvas"); + page = new Container(BoxLayout.y()); + page.setUIID("LnCanvas"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + page.setName("studio"); + // Courses and classes are started from the "New" and "Schedule" links + // of their own sections, so nothing floats over the page. + form.add(BorderLayout.CENTER, page); + LiveChannel.listen(new LiveChannel.Adapter() { + @Override + public void sessionChanged(String id, String state) { + if (Nav.isHome(form)) { + load(); + } + } + }); + load(); + } + + @Override + public Form form() { + return form; + } + + /// Back to the studio, refreshed. + static void back() { + if (current == null || !Nav.isHome(current.form)) { + Nav.home(); + return; + } + current.load(); + current.form.showBack(); + } + + static Form home() { + return current == null ? null : current.form; + } + + void load() { + page.removeAll(); + page.add(head()); + page.add(new Skeleton(4, "LnSkeleton")); + page.revalidate(); + Api.studio().studio(Net.to(this::fill, Ui.failed(page, this::load))); + } + + private Container head() { + UserDto user = Session.user(); + Container top = new Container(new BorderLayout()); + top.setUIID("LnHomeTop"); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("Studio"), "LnHello")); + words.add(new Label(user == null ? "" : user.displayName(), "LnHelloSub")); + top.add(BorderLayout.CENTER, words); + Container east = new Container(BoxLayout.x()); + if (user != null && user.admin()) { + // Where a deployment makes its creators: registering makes a learner. + Button people = new Button("", "LnClose"); + people.setName("accounts"); + people.setAccessibilityText(Lang.tr("Accounts")); + FontImage.setMaterialIcon(people, FontImage.MATERIAL_ADMIN_PANEL_SETTINGS, 4); + people.addActionListener(e -> com.codenameone.examples.lingo.learn.AccountsForm.show( + people.getComponentForm())); + east.add(people); + } + if (user != null && user.learner()) { + Button learn = new Button(Lang.tr("Learn"), "LnKindTag"); + learn.setName("to-learn"); + FontImage.setMaterialIcon(learn, FontImage.MATERIAL_SCHOOL, 3); + learn.addActionListener(e -> Nav.switchTo(Nav.LEARN)); + east.add(learn); + } else { + Button out = new Button("", "LnClose"); + out.setName("sign-out"); + out.setAccessibilityText(Lang.tr("Sign out")); + FontImage.setMaterialIcon(out, FontImage.MATERIAL_LOGOUT, 4); + out.addActionListener(e -> Nav.signOut()); + east.add(out); + } + top.add(BorderLayout.EAST, BorderLayout.centerAbsolute(east)); + return top; + } + + private void fill(StudioDto studio) { + page.removeAll(); + page.add(head()); + Container earnings = new Container(new BorderLayout()); + earnings.setUIID("LnHeroCard"); + earnings.setName("earnings"); + Container words = new Container(BoxLayout.y()); + words.add(new Label(Lang.tr("YOUR EARNINGS"), "LnHeroKicker")); + words.add(new Label(Kit.amount(studio.earningsCents()), "LnDashTitle")); + words.add(new Label(Lang.tr("{0} learners in your courses", "" + studio.learners()), + "LnDashText")); + earnings.add(BorderLayout.CENTER, words); + earnings.add(BorderLayout.EAST, BorderLayout.centerAbsolute( + Kit.glyph(FontImage.MATERIAL_SAVINGS, "LnGoalRing", 9))); + page.add(earnings); + int published = 0; + for (CourseDto c : studio.courses()) { + published += c.published() ? 1 : 0; + } + Container stats = new Container(new GridLayout(1, 3)); + stats.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + stats.getAllStyles().setPadding(0, 0, 5, 5); + stats.add(stat("" + published, Lang.tr("Published"))); + stats.add(stat("" + (studio.courses().size() - published), Lang.tr("Drafts"))); + stats.add(stat("" + studio.sessions().size(), Lang.tr("Live classes"))); + page.add(stats); + + page.add(Kit.section("Courses", "New", () -> CourseEditor.create(form))); + if (studio.courses().isEmpty()) { + page.add(Ui.empty(FontImage.MATERIAL_VIDEO_LIBRARY, Lang.tr("Teach what you know"), + Lang.tr("Make a course of videos, phrases and conversations."))); + } + for (final CourseDto c : studio.courses()) { + Container row = new Container(new BorderLayout()); + row.setUIID("LnLiveCard"); + Label cover = new Label(com.codenameone.examples.lingo.api.Languages.code( + c.language()), Kit.cover(c.accent())); + Container coverBox = BorderLayout.centerAbsolute(cover); + coverBox.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_DIPS); + coverBox.getAllStyles().setPaddingRight(3); + row.add(BorderLayout.WEST, coverBox); + Container text = new Container(BoxLayout.y()); + Container tags = new Container(BoxLayout.x()); + tags.add(new Label(c.published() ? Lang.tr("Published") : Lang.tr("Draft"), + c.published() ? "LnKindTag" : "LnDraftTag")); + text.add(tags); + text.add(Ui.text(c.title(), "LnStepTitle")); + text.add(Ui.text(Lang.tr("{0} lessons", "" + c.lessons()) + Ui.DOT + + Lang.tr("{0} learners", "" + c.learners()) + Ui.DOT + + Kit.money(c.priceCents()), "LnStepMeta")); + row.add(BorderLayout.CENTER, text); + Ui.tap(row, "edit-" + c.id(), e -> CourseEditor.edit(c.id(), form)); + page.add(row); + } + + page.add(Kit.section("Live classes", "Schedule", () -> LiveScheduler.show(form))); + for (final LiveSessionDto s : studio.sessions()) { + page.add(session(s)); + } + if (studio.sessions().isEmpty()) { + page.add(Ui.text(Lang.tr("Teach a small group on video. Learners book seats, free " + + "or paid."), "LnScreenText")); + } + Label pad = new Label(" "); + pad.setPreferredH(com.codename1.ui.CN.convertToPixels(20)); + page.add(pad); + page.revalidate(); + } + + private Container session(final LiveSessionDto s) { + Container card = com.codenameone.examples.lingo.learn.LiveTab.card(form, s); + com.codename1.ui.Component action = null; + if ("scheduled".equals(s.state())) { + Button start = new Button(Lang.tr("Go live"), "LnLiveBadge"); + start.setName("start-" + s.id()); + start.addActionListener(e -> Api.studio().start(s.id(), Net.to(live -> { + LiveRoom.enter(live, form); + }, Ui::fail))); + action = start; + } else if ("live".equals(s.state())) { + Button end = new Button(Lang.tr("End"), "LnDraftTag"); + end.setName("end-" + s.id()); + end.addActionListener(e -> Api.studio().end(s.id(), Net.to(ended -> load(), + Ui::fail))); + Button join = new Button(Lang.tr("Join"), "LnLiveBadge"); + join.setName("join-" + s.id()); + join.addActionListener(e -> LiveRoom.enter(s, form)); + action = BoxLayout.encloseY(join, end); + } + if (action != null) { + com.codename1.ui.Component old = ((BorderLayout) card.getLayout()).getEast(); + if (old != null) { + old.remove(); + } + card.add(BorderLayout.EAST, BorderLayout.centerAbsolute(action)); + } + return card; + } + + private static Container stat(String value, String label) { + Container c = new Container(BoxLayout.y()); + c.setUIID("LnStudioStat"); + c.add(new Label(value, "LnProfileValue")); + c.add(new Label(label, "LnProfileLabel")); + return c; + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/BottomSheet.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/BottomSheet.java new file mode 100644 index 00000000000..4c375382eb7 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/BottomSheet.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Display; +import com.codename1.ui.Graphics; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.geom.Rectangle; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.plaf.Style; + +/// The sheet that rises from the bottom of a map. +/// +/// It has two parts. [#peek()] is what is always there: the headline and the +/// one thing to do next. [#more()] is the rest -- the details, the lesser +/// actions -- and is shown when the sheet is pulled up and put away when it is +/// pushed down, so the map keeps most of the screen until the user asks for +/// the sheet. The handle at the top is what is pulled; a tap on it does the +/// same. A sheet with nothing in `more` has no handle. +/// +/// A screen fills it the same way each time: [#reset()], add to the two parts, +/// [#ready()]. +public final class BottomSheet extends Container { + private final Grip grip = new Grip(); + private final Container peek = new Container(BoxLayout.y()); + private final Container more = new Container(BoxLayout.y()); + private boolean expanded; + + public BottomSheet() { + super(new BorderLayout()); + setUIID("LnSheet"); + setName("panel"); + setSafeArea(true); + // A touch on the sheet is the sheet's, and does not reach through to + // drag the map under it. + setGrabsPointerEvents(true); + // The handle stays put and everything under it scrolls. A day of + // stops is taller than a phone, and the sheet is the south of a + // BorderLayout, which gives it its preferred height and nothing + // more: unscrolled, the last stops were below the screen with no + // way to reach them. The summary scrolls too -- pinned, it left a + // sliver of the screen for the stops. + Container body = new Container(BoxLayout.y()); + body.add(peek).add(more); + body.setScrollableY(true); + body.setScrollVisible(false); + add(BorderLayout.NORTH, grip); + add(BorderLayout.CENTER, body); + more.setHidden(true); + } + + /// The padding under the sheet's content as the theme has it, and as it + /// was last made here. + private int styledUnder = -1; + private int madeUnder = -1; + + /// Keeps the content clear of what the device draws over the bottom of + /// the screen, by making the sheet's own padding at least that deep. + /// + /// Marking the sheet a safe area is not enough. A safe area is padded + /// while it is laid out, from where it then is; asked how tall it wants + /// to be before that, it answers without the padding, is given that + /// height, and then spends some of it on the padding after all -- which + /// came out of the last thing in the sheet. Padding that is there both + /// times cannot disagree with itself. The mark stays for the sides, which + /// do not change how tall the sheet is. + private void clearOfTheDevice() { + Style style = getUnselectedStyle(); + int now = style.getPaddingBottom(); + if (now != madeUnder) { + // Styled again since: a change of theme, or of name. + styledUnder = now; + } + Rectangle safe = Display.getInstance().getDisplaySafeArea(new Rectangle()); + int covered = safe.getHeight() <= 0 ? 0 + : Math.max(0, CN.getDisplayHeight() - safe.getY() - safe.getHeight()); + int wanted = Math.max(styledUnder, covered); + if (wanted != now) { + getAllStyles().setPaddingUnitBottom(Style.UNIT_TYPE_PIXELS); + getAllStyles().setPaddingBottom(wanted); + } + madeUnder = wanted; + } + + @Override + protected Dimension calcPreferredSize() { + clearOfTheDevice(); + Dimension size = super.calcPreferredSize(); + // Never taller than most of the screen, so some map stays in view + // and `more` scrolls inside the rest. + int most = CN.getDisplayHeight() * 85 / 100; + if (size.getHeight() > most) { + size.setHeight(most); + } + return size; + } + + @Override + public void layoutContainer() { + clearOfTheDevice(); + super.layoutContainer(); + } + + public Container peek() { + return peek; + } + + public Container more() { + return more; + } + + /// Empties the sheet, for the next thing it will show. + public void reset() { + peek.removeAll(); + more.removeAll(); + } + + /// The sheet has been filled: lays it out. + /// + /// @param open whether to show `more` straight away + public void ready(boolean open) { + boolean extra = more.getComponentCount() > 0; + grip.handle(extra); + expanded = extra && open; + more.setHidden(!expanded); + Container parent = getParent(); + if (parent != null) { + parent.revalidate(); + } + } + + public boolean isExpanded() { + return expanded; + } + + public void setExpanded(boolean wanted) { + if (wanted == expanded || more.getComponentCount() == 0) { + return; + } + expanded = wanted; + more.setHidden(!wanted); + Container parent = getParent(); + if (parent != null) { + parent.animateLayout(180); + } + } + + /// The handle: a short bar, pulled up or down, or tapped. + private final class Grip extends Component { + private int pressedY; + private boolean pulled; + /// Whether there is anything to pull the sheet up for. With nothing, + /// the handle is not drawn and still takes its room: without it the + /// first line of the sheet sat against the sheet's top edge. + private boolean handle; + + void handle(boolean wanted) { + if (handle != wanted) { + handle = wanted; + setShouldCalcPreferredSize(true); + } + } + + Grip() { + setUIID("LnGrip"); + setGrabsPointerEvents(true); + } + + @Override + protected Dimension calcPreferredSize() { + Style style = getStyle(); + return new Dimension(CN.convertToPixels(12f), handle + ? CN.convertToPixels(1.2f) + style.getVerticalPadding() + : CN.convertToPixels(2.6f)); + } + + @Override + public void paint(Graphics g) { + if (!handle) { + return; + } + Style style = getStyle(); + int width = CN.convertToPixels(10f); + int height = CN.convertToPixels(1.2f); + g.setColor(style.getFgColor()); + g.setAntiAliased(true); + g.fillRoundRect(getX() + (getWidth() - width) / 2, + getY() + (getHeight() - height) / 2, width, height, height, height); + } + + @Override + public void pointerPressed(int x, int y) { + pressedY = y; + pulled = false; + } + + @Override + public void pointerDragged(int x, int y) { + // Far enough to be meant, and once for each pull. + if (!pulled && Math.abs(y - pressedY) > CN.convertToPixels(2f)) { + pulled = true; + setExpanded(y < pressedY); + } + } + + @Override + public void pointerReleased(int x, int y) { + if (!pulled) { + setExpanded(!expanded); + } + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ConsentForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ConsentForm.java new file mode 100644 index 00000000000..56236eae856 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ConsentForm.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.Telemetry; + +/// Asks, once on a device, whether the app may report how it is used. +/// +/// It is shown after the first sign-in and before anything is counted, and it +/// has no way out but an answer: nothing is reported while there is none, so +/// leaving the question open would be a no that is asked again at every +/// start. Either answer can be changed in Settings, which is said here. +public final class ConsentForm { + private ConsentForm() { + } + + /// @param then where to go once there is an answer + public static void show(final Runnable then) { + Form form = Ui.form("Usage statistics", "Consent"); + Container page = Ui.page(); + Container banner = Ui.banner(FontImage.MATERIAL_INSIGHTS, "Help improve Lingo", + "Lingo can count which screens are opened and which features are used, " + + "so that we can see what works and fix what does not.", "LnBannerIcon"); + // The page has its own top padding, and the banner's on top of it + // pushed the last line of the promise below under the answers. + banner.getAllStyles().setPaddingTop(0); + page.add(banner); + page.add(Ui.row(FontImage.MATERIAL_VISIBILITY_OFF, "No personal details", + "Never your name, e-mail, phone number, places or card details", null)); + // The two answers stay in view however much there is to read. + Container answers = new Container(BoxLayout.y()); + answers.setUIID("LnPage"); + answers.setSafeArea(true); + answers.add(Ui.primary("Share usage statistics", "consentYes", e -> answer(true, then))); + answers.add(Ui.secondary("Not now", "consentNo", e -> answer(false, then))); + answers.add(Ui.text("Turn it on or off at any time in Settings", "LnMuted")); + form.add(BorderLayout.SOUTH, answers); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + private static void answer(boolean yes, Runnable then) { + Telemetry.allow(yes); + then.run(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Lang.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Lang.java new file mode 100644 index 00000000000..8049ed3a20f --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Lang.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.l10n.L10NManager; +import com.codename1.ui.plaf.UIManager; +import com.codename1.ui.util.Resources; +import com.codenameone.examples.lingo.Prefs; +import java.util.HashMap; +import java.util.Map; + +/// The language the app speaks. +/// +/// The translations are the `Bundle_.properties` files in +/// `src/main/l10n`, which the build packs into the theme. One of them at a +/// time is installed as the `UIManager`'s bundle, and from then on every +/// label, button, title and hint looks its text up there as it is set: the +/// English text in the source is the key, and a text with no entry is shown as +/// it is. So a screen written in English is translated without saying so. +/// +/// What a component cannot do by itself is a sentence with something put into +/// it -- "Pick up Riley". Those go through [#tr(String, Object...)], with the +/// whole sentence as the key and `{0}` where the name goes, because where it +/// goes is the translator's decision. +/// +/// To add a string: write it in English in the code, and add a line for it to +/// each of the four translated files. To add a language: add its file, and its +/// code to [#CODES]. +public final class Lang { + /// The languages there is a translation for. English is the source. + public static final String[] CODES = {"en", "es", "fr", "de", "he"}; + + private static final String BUNDLE = "Bundle"; + /// The entry each file names its own language in, in that language. + private static final String NAME_KEY = "language.name"; + + private Lang() { + } + + /// The language in use: the one chosen in Settings, else the device's when + /// there is a translation for it, else English. + public static String current() { + String chosen = known(Prefs.language()); + if (chosen != null) { + return chosen; + } + String device = known(L10NManager.getInstance().getLanguage()); + return device == null ? CODES[0] : device; + } + + /// Installs the translation for [#current()]. A screen built after this is + /// in the new language, and laid out right to left when the language is + /// written that way; one already built keeps the words it was built with. + public static void apply() { + Map bundle = new HashMap(); + // Always said, one way or the other: a bundle that is silent about the + // direction leaves the one before it in force. + bundle.put("@rtl", "false"); + Map translated = table(current()); + if (translated != null) { + bundle.putAll(translated); + } + UIManager.getInstance().setBundle(bundle); + } + + /// What `code`'s language calls itself. + public static String name(String code) { + Map translated = table(code); + String name = translated == null ? null : translated.get(NAME_KEY); + return name == null || name.length() == 0 ? code : name; + } + + public static String tr(String text) { + return UIManager.getInstance().localize(text, text); + } + + /// `one` translated when `count` is 1, otherwise `many` with the count in + /// place of `{0}`: "1 lesson left", "3 lessons left". + public static String count(int count, String one, String many) { + return count == 1 ? tr(one) : tr(many, String.valueOf(count)); + } + + /// Translates `pattern` and puts `values` where it says `{0}`, `{1}`... + public static String tr(String pattern, Object... values) { + String text = tr(pattern); + for (int iter = 0; iter < values.length; iter++) { + String mark = "{" + iter + "}"; + String value = String.valueOf(values[iter]); + int at = text.indexOf(mark); + while (at >= 0) { + text = text.substring(0, at) + value + text.substring(at + mark.length()); + at = text.indexOf(mark, at + value.length()); + } + } + return text; + } + + /// The code among [#CODES] that `language` is, or null. A device reports + /// its language with or without a country (`es`, `es_MX`) and Hebrew under + /// either of two codes; this is compared as the ASCII it is, since folding + /// the case would follow the very language being worked out. + private static String known(String language) { + if (language == null || language.length() < 2) { + return null; + } + if (language.regionMatches(true, 0, "iw", 0, 2)) { + return "he"; + } + for (String code : CODES) { + if (language.regionMatches(true, 0, code, 0, 2)) { + return code; + } + } + return null; + } + + private static Map table(String code) { + Resources theme = Resources.getGlobalResources(); + return theme == null ? null : theme.getL10N(BUNDLE, code); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Layouts.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Layouts.java new file mode 100644 index 00000000000..600042400ea --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Layouts.java @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; +import java.util.HashMap; +import java.util.Map; + +/// How much room there is, and whose look the app wears. +/// +/// The app is laid out for a phone. Two things change that, and both are +/// asked here so that no screen works them out for itself: +/// +/// - [#wide()]: the window is as wide as a tablet on its side, a desktop +/// window or a browser. The admin console then shows its navigation and a +/// list with its detail side by side; every other screen keeps its column +/// and stops it growing past [#column()]. +/// - [#desktopLook()]: the platform's own desktop theme is installed -- macOS +/// Aqua, Windows Fluent or GNOME Adwaita, chosen by the `nativeTheme=native` +/// build hint. The admin console then dresses its controls in that theme's +/// buttons, fields and lists with [#dress(Container)], and keeps the app's +/// own styles only for what a desktop has no control for: the charts and +/// the numbers. +/// +/// Both are read when a screen is built. A window that is resized across the +/// line, or a device that is turned, rebuilds the screen: see +/// [#onChange(Form, Runnable)]. +public final class Layouts { + /// A window at least this wide, in millimetres, is laid out side by side. + /// A phone on its side is narrower; a tablet on its side is not. + private static final float WIDE_MM = 165f; + /// The widest a column of text and controls is left to grow. + private static final float COLUMN_MM = 150f; + + /// The app's own style names, and the name each goes by under a desktop + /// theme. Those are declared at the end of `theme.css`, each deriving from + /// the native control it stands for. + private static final Map DESKTOP = new HashMap(); + + static { + String[] dressed = {"LnForm", "LnPage", "LnList", "LnPrimary", "LnSecondary", "LnDanger", + "LnLink", "LnField", "LnFieldHint", "LnRow", "LnRowPicked", "LnRowIcon", "LnRowTitle", + "LnRowDetail", "LnRowValue", "LnSection", "LnHeading", "LnText", "LnMuted", "LnLabel", + "LnTitle", "LnError", "LnNotice", "LnPanel", "LnFact", "LnFactLabel", "LnFactValue", + "LnFactTotal", "LnSegments", "LnSegment", "LnTile", "LnStat", "LnStatValue", + "LnStatLabel", "LnChartValue", "LnChartAxis", "LnAmount", "LnBannerIcon", + "LnBannerTitle", "LnBannerText", "LnAlert", "LnSide", "LnSideItem", "LnSidePicked", + "LnSideLabel", "LnSideName", "LnSideDetail", "LnPaneBar", "LnPaneTitle", "LnMaster", + "LnBarButton", "LnHomeBar"}; + for (int iter = 0; iter < dressed.length; iter++) { + DESKTOP.put(dressed[iter], "LnDesk" + dressed[iter].substring(2)); + } + } + + private Layouts() { + } + + /// Whether there is room to lay a screen out side by side. + public static boolean wide() { + return CN.getDisplayWidth() >= CN.convertToPixels(WIDE_MM); + } + + /// The widest a single column of content is drawn, in pixels. + public static int column() { + return CN.convertToPixels(COLUMN_MM); + } + + /// How many columns of `millimetres` each fit in `width` pixels: at least + /// one, and no more than `most`. + public static int columns(int width, float millimetres, int most) { + int fit = width / Math.max(1, CN.convertToPixels(millimetres)); + return Math.max(1, Math.min(most, fit)); + } + + /// Whether the platform's desktop theme is the one under the app's own. + /// + /// The three desktop themes are the only ones installed on a desktop that + /// mark themselves as a platform's defaults; a desktop build that kept the + /// legacy theme, a phone and a tablet all answer false and keep the app's + /// look everywhere. + public static boolean desktopLook() { + return CN.isDesktop() + && UIManager.getInstance().isThemeConstant("nativeThemeDefaultsBool", false); + } + + /// Dresses everything under `root` in the desktop theme, when there is one: + /// each component styled by the app takes the twin of its style that + /// derives from the platform's control, and whatever scrolls shows the + /// platform's scrollbar. Does nothing anywhere else. + /// + /// It is done to a finished tree rather than where each piece is made, so + /// that the screens are written once, for a phone, and the console alone + /// decides what a desktop makes of them. + public static void dress(Container root) { + if (!desktopLook()) { + return; + } + dressed(root); + } + + private static void dressed(Component component) { + String twin = DESKTOP.get(component.getUIID()); + if (twin != null) { + component.setUIID(twin); + if (component instanceof Label) { + redraw((Label) component); + } + } + if (component instanceof SpanLabel) { + SpanLabel span = (SpanLabel) component; + String text = DESKTOP.get(span.getTextUIID()); + if (text != null) { + span.setTextUIID(text); + } + return; + } + if (component instanceof Container) { + Container holder = (Container) component; + if (holder.isScrollableY()) { + holder.setScrollVisible(true); + } + // A row that is one button is still a container of labels. + for (int iter = 0; iter < holder.getComponentCount(); iter++) { + dressed(holder.getComponentAt(iter)); + } + } + } + + /// Draws the icon of `label` again in the colours of the style it now has: + /// an icon is an image, made once from the style the label had then. + private static void redraw(Label label) { + if (!(label.getIcon() instanceof FontImage)) { + return; + } + FontImage icon = (FontImage) label.getIcon(); + String glyph = icon.getText(); + float pixels = icon.getFont() == null ? 0 : icon.getFont().getPixelSize(); + if (glyph == null || glyph.length() != 1 || pixels <= 0) { + return; + } + FontImage.setMaterialIcon(label, glyph.charAt(0), + pixels * 100f / CN.convertToPixels(100f)); + } + + /// Keeps the content of `page` in a column no wider than [#column()], in + /// the middle of however much room there is: called by the page as it is + /// laid out, with the padding its style gave it. + /// + /// @param margin the side padding of the page's own style, in pixels + static void centre(Container page, int margin) { + int side = Math.max(margin, (page.getWidth() - column()) / 2); + Style style = page.getAllStyles(); + Style now = page.getUnselectedStyle(); + if (now.getPaddingLeftNoRTL() != side || now.getPaddingRightNoRTL() != side) { + style.setPaddingUnitLeft(Style.UNIT_TYPE_PIXELS); + style.setPaddingUnitRight(Style.UNIT_TYPE_PIXELS); + style.setPaddingLeft(side); + style.setPaddingRight(side); + } + } + + /// Calls `rebuild` when `form` stops being wide or starts to be, which is + /// a window dragged across the line or a tablet turned. The screen was + /// built for the room there was; it is built again for the room there is. + public static void onChange(final Form form, final Runnable rebuild) { + final boolean[] was = {wide()}; + form.addSizeChangedListener(e -> { + boolean now = wide(); + if (now != was[0]) { + was[0] = now; + // After the event: the form is in the middle of being resized. + CN.callSerially(rebuild); + } + }); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Look.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Look.java new file mode 100644 index 00000000000..3090d397df8 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Look.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.CN; +import com.codename1.ui.plaf.UIManager; +import com.codenameone.examples.lingo.Prefs; + +/// Light or dark. +/// +/// `theme.css` has both: every rule has its dark twin in the block at the end +/// of the file. Which of the two a component gets is decided when its style is +/// resolved, so a screen built after [#apply()] is in the new look and one +/// already built is not -- the caller rebuilds what is on screen. +public final class Look { + private Look() { + } + + /// Makes the look the one chosen in Settings: light, dark, or whichever + /// the device is in. + public static void apply() { + String theme = Prefs.theme(); + CN.setDarkMode(Prefs.THEME_DARK.equals(theme) ? Boolean.TRUE + : Prefs.THEME_LIGHT.equals(theme) ? Boolean.FALSE : null); + if (CN.isDesktop()) { + // On a desktop the platform's theme takes the colours and the font + // the user chose for the whole machine -- the accent among them. + // It reaches only what that theme styles, which is what the admin + // console wears; see Layouts. + UIManager.getInstance().setUseNativeColors(true); + UIManager.getInstance().setUseNativeFonts(true); + } + UIManager.getInstance().refreshTheme(); + } + + /// Whether the app is drawn dark right now. A platform that cannot say is + /// taken to be light. + public static boolean dark() { + Boolean dark = CN.isDarkMode(); + return dark != null && dark.booleanValue(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Nav.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Nav.java new file mode 100644 index 00000000000..02e7c42e657 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Nav.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codenameone.examples.lingo.learn.LearnHome; +import com.codenameone.examples.lingo.studio.StudioHome; + +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.layouts.BorderLayout; +import com.codenameone.examples.lingo.AppConfig; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.Telemetry; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.live.LiveChannel; +import com.codenameone.examples.lingo.net.Account; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.notify.Notifications; + +/// Decides which screen the app is on. +/// +/// The app is two apps in one -- the learner's day in the field and the +/// creator's board -- and which of them a user may enter is the server's +/// decision: it is the roles on their account, as `/api/me` reports them. Each +/// has a home screen of its own, with its own menu. Hiding a mode here is a +/// courtesy and not the protection; the server refuses a creator's call +/// from anyone without the role, whatever the app shows. +public final class Nav { + public static final String LEARN = "learn"; + public static final String STUDIO = "studio"; + + /// The home screen of a mode. + public interface Home { + /// Fills the screen in and starts it talking to the server. Called + /// once, before the screen is first shown. + void start(); + + Form form(); + } + + /// The home screen last built, and the mode it is the home of. + private static Form homeForm; + private static String homeMode = ""; + + private Nav() { + } + + /// Whether `form` is still the home screen, for an answer that arrives + /// after the user has gone to another mode or signed out and should then + /// change nothing. + public static boolean isHome(Form form) { + return form != null && form == homeForm; + } + + /// The first screen: wherever the stored session leads. + public static void launch() { + Session.onSignedOut(() -> { + LiveChannel.stop(); + Telemetry.signedOut("expired"); + WelcomeForm.show(); + }); + Form starting = Ui.form("", "Starting"); + starting.getToolbar().hideToolbar(); + starting.show(); + Session.restore(Nav::enter, WelcomeForm::show, Nav::unreachable); + } + + /// Someone has just signed in, or been found still signed in: their + /// account's settings are fetched, applied, and then their home is shown in + /// the language and the colours they chose. + public static void enter() { + // Where this phone is to be sent notifications, now that there is + // someone to send them to. + Notifications.signedIn(); + Account.load(() -> { + Look.apply(); + Lang.apply(); + if (Telemetry.asked()) { + home(); + } else { + // Once on a device, before the first screen that would be + // counted: whether it may be. + ConsentForm.show(Nav::home); + } + }); + } + + /// Shows the home screen of the mode the user is in. + public static void home() { + Form home = build(); + if (home != null) { + home.show(); + } + } + + /// The account was asked about again: back to the home screen only if + /// the mode it opens in is no longer the one on screen, so somebody whose + /// roles did not change is not pulled out of what they were doing. + public static void refreshed() { + UserDto user = Session.user(); + if (user == null || !mode(user).equals(homeMode)) { + home(); + } + } + + /// Builds the home screen of the mode the user is in, without showing it: + /// for a caller that is about to show something on top of it. Null, and + /// the welcome screen showing, when nobody is signed in. + public static Form build() { + UserDto user = Session.user(); + if (user == null) { + WelcomeForm.show(); + return null; + } + LiveChannel.start(); + String mode = mode(user); + Telemetry.role(mode); + // A creator at a desk gets the console; on a phone, the board. + Home home = STUDIO.equals(mode) ? new StudioHome() : new LearnHome(); + home.start(); + homeForm = home.form(); + homeMode = mode; + return homeForm; + } + + /// The mode to open for `user`: the one they chose last while their + /// account still allows it, else the one their account is for. A + /// creator who is not also a learner has no learner home. + public static String mode(UserDto user) { + String saved = AppConfig.mode(Session.owner(user.username())); + boolean desk = user.creator() || user.admin(); + if (STUDIO.equals(saved) && desk) { + return STUDIO; + } + if (LEARN.equals(saved) && user.learner()) { + return LEARN; + } + return user.learner() ? LEARN : STUDIO; + } + + /// The user chose `mode` from the menu. + public static void switchTo(String mode) { + UserDto user = Session.user(); + AppConfig.setMode(mode, user == null ? "" : Session.owner(user.username())); + home(); + } + + /// A notification about the plan was opened: the learner's day, unless + /// it is on screen already, where the live channel has refreshed it. + public static void showLearn() { + UserDto user = Session.user(); + if (user == null || !user.learner()) { + return; + } + if (LEARN.equals(homeMode) && homeForm != null && CN.getCurrentForm() == homeForm) { + return; + } + AppConfig.setMode(LEARN, Session.owner(user.username())); + home(); + } + + public static void signOut() { + leave("user", true); + } + + /// The account was closed: signed out, and what the device kept for the + /// usage reports forgotten with it. + public static void deleted() { + // Closing the account already made the server forget its devices. + leave("deleted", false); + Telemetry.forget(); + // Nobody is coming back for where that account went. + Prefs.ownedBy(""); + } + + private static void leave(final String reason, boolean forgetDevice) { + com.codenameone.examples.lingo.learn.LearnHome.forget(); + Account.flush(); + LiveChannel.stop(); + homeForm = null; + homeMode = ""; + // The server forgets this phone for the account first, while there is + // still a session to ask with. + Runnable out = () -> { + Telemetry.signedOut(reason); + Session.signOut(WelcomeForm::show); + }; + if (forgetDevice) { + Notifications.signingOut(out); + } else { + out.run(); + } + } + + /// Points the app at another server, which ends the session with this one. + public static void changeServer(final String url) { + Runnable switchOver = () -> { + AppConfig.setServerUrl(url); + Session.start(AppConfig.serverUrl()); + launch(); + }; + if (AppConfig.sameServer(url, Session.serverUrl()) || Session.user() == null) { + LiveChannel.stop(); + switchOver.run(); + return; + } + // Signed in: sign out the way the Sign out button does, against the + // server still in use, before pointing anywhere else. Session.start + // only forgets the tokens on this phone, so the old server would keep + // a live refresh token and this phone's push registration, and go on + // notifying it about that account. + Account.flush(); + LiveChannel.stop(); + homeForm = null; + homeMode = ""; + Notifications.signingOut(() -> { + Telemetry.signedOut("server"); + Session.signOut(switchOver); + }); + } + + /// There is a session, and no server to use it with. + private static void unreachable() { + Form form = Ui.form("Lingo", "Unreachable"); + Container page = Ui.page(); + page.add(Ui.label("No connection", "LnTitle")); + page.add(Ui.text(Lang.tr("The server at {0} did not answer.", Session.serverUrl()), + "LnText")); + page.add(Ui.primary("Try again", "retry", e -> launch())); + if (AppConfig.serverSwitchable()) { + page.add(Ui.secondary("Server address", "server", e -> ServerForm.show(form))); + } + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Photos.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Photos.java new file mode 100644 index 00000000000..50118d0c244 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Photos.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.capture.Capture; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.Log; +import com.codename1.io.Util; +import com.codename1.ui.CN; +import com.codename1.ui.Image; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.util.ImageIO; +import com.codenameone.examples.lingo.Telemetry; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/// A picture from the camera or from the gallery, made small enough to send. +/// +/// A phone's camera makes pictures of several megabytes, and the server takes +/// documents of up to one and a half. So whatever comes back is scaled to fit +/// in [#LONGEST_SIDE] and written as a JPEG, which leaves a page of a licence +/// perfectly readable in a fraction of that. +public final class Photos { + /// Where the pictures come from, for a test that has no camera. + public interface Source { + /// @param camera true when the camera was asked for, false the gallery + /// @return the picture, or null as when the user backs out + Image take(boolean camera); + } + + public interface Taken { + /// @param jpeg the picture, encoded + /// @param picture the same picture, to show + void taken(byte[] jpeg, Image picture); + } + + private static final int LONGEST_SIDE = 1280; + private static final float QUALITY = 0.8f; + + private static Source source; + + private Photos() { + } + + /// Takes every picture from `from` from now on, and opens neither the + /// camera nor the gallery. The tests use it to hand in a picture of their + /// own. + public static void useSource(Source from) { + source = from; + } + + public static void camera(Taken taken) { + if (source != null) { + deliver(source.take(true), taken); + return; + } + Capture.capturePhoto(e -> picked(e, taken)); + } + + public static void gallery(Taken taken) { + if (source != null) { + deliver(source.take(false), taken); + return; + } + CN.openGallery(e -> picked(e, taken), CN.GALLERY_IMAGE); + } + + /// The camera and the gallery both answer with the path of a file, or + /// with nothing when the user backed out. + private static void picked(ActionEvent event, Taken taken) { + Object path = event == null ? null : event.getSource(); + if (!(path instanceof String)) { + return; + } + InputStream in = null; + try { + in = FileSystemStorage.getInstance().openInputStream((String) path); + deliver(Image.createImage(in), taken); + } catch (IOException failed) { + Log.e(failed); + Telemetry.error(failed); + Ui.say("That picture could not be read"); + } finally { + Util.cleanup(in); + } + } + + private static void deliver(Image picture, Taken taken) { + if (picture == null) { + return; + } + Image small = picture; + if (picture.getWidth() > LONGEST_SIDE || picture.getHeight() > LONGEST_SIDE) { + small = picture.scaledSmallerRatio(LONGEST_SIDE, LONGEST_SIDE); + } + ImageIO encoder = ImageIO.getImageIO(); + if (encoder == null) { + Ui.say("This device cannot prepare a picture to send"); + return; + } + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + encoder.save(small, out, ImageIO.FORMAT_JPEG, QUALITY); + taken.taken(out.toByteArray(), small); + } catch (IOException failed) { + Log.e(failed); + Telemetry.error(failed); + Ui.say("That picture could not be read"); + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ProfileForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ProfileForm.java new file mode 100644 index 00000000000..91e4b0c3390 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ProfileForm.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codenameone.examples.lingo.api.ProfileDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.net.Account; +import com.codenameone.examples.lingo.net.Session; + +/// The name printed on the learner's certificates, and their number. +public final class ProfileForm { + private ProfileForm() { + } + + /// @param saved where to go once the profile is saved: a screen that shows + /// the name is built again there + public static void show(final Form previous, final Runnable saved) { + final Form form = Ui.form("Profile", "Profile"); + Ui.back(form, previous); + UserDto user = Session.user(); + ProfileDto profile = Account.profile(); + Container page = Ui.page(); + page.add(Ui.person(user.displayName(), user.username(), null)); + final TextField name = Ui.field(page, "Name", "name", "As it appears on your certificates"); + name.setText(profile == null ? user.displayName() : profile.name()); + final TextField phone = Ui.field(page, "Mobile number", "phone", "+1 555 010 0000", + TextArea.PHONENUMBER); + phone.setText(profile == null ? user.phone() : profile.phone()); + page.add(Ui.text("Used only to reach you about a live class you booked.", + "LnMuted")); + + final SpanLabel error = Ui.text("", "LnError"); + error.setName("error"); + final Button save = Ui.primary("Save", "submit", null); + save.addActionListener(e -> { + save.setEnabled(false); + error.setText(""); + Account.saveProfile(name.getText().trim(), phone.getText().trim(), saved, + (status, message) -> { + save.setEnabled(true); + error.setText(message); + Ui.refresh(form); + }); + }); + page.add(error).add(save); + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Pulse.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Pulse.java new file mode 100644 index 00000000000..ac10915bfcd --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Pulse.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.plaf.Style; + +/// "Still looking": a dot that sends out rings, the way a search does on a +/// map. It runs for as long as it is on screen. +/// +/// The colour is the `LnPulse` style's text colour. +public final class Pulse extends Component { + /// How long one ring takes from the dot to the edge. + private static final int PERIOD_MILLIS = 1800; + private static final int RINGS = 3; + + public Pulse() { + setUIID("LnPulse"); + } + + @Override + protected void initComponent() { + super.initComponent(); + Form form = getComponentForm(); + if (form != null) { + form.registerAnimated(this); + } + } + + @Override + protected void deinitialize() { + Form form = getComponentForm(); + if (form != null) { + form.deregisterAnimated(this); + } + super.deinitialize(); + } + + @Override + public boolean animate() { + return true; + } + + @Override + protected Dimension calcPreferredSize() { + Style style = getStyle(); + int side = CN.convertToPixels(13f); + return new Dimension(side + style.getHorizontalPadding(), + side + style.getVerticalPadding()); + } + + @Override + public void paint(Graphics g) { + Style style = getStyle(); + int side = Math.min(getWidth() - style.getHorizontalPadding(), + getHeight() - style.getVerticalPadding()); + if (side <= 0) { + return; + } + int centerX = getX() + getWidth() / 2; + int centerY = getY() + getHeight() / 2; + int dot = Math.max(4, CN.convertToPixels(2f)); + int alpha = g.getAlpha(); + g.setAntiAliased(true); + g.setColor(style.getFgColor()); + long now = System.currentTimeMillis() % PERIOD_MILLIS; + for (int ring = 0; ring < RINGS; ring++) { + // Each ring is a third of the way behind the one before it, and + // fades as it grows. + double part = ((now + (long) ring * PERIOD_MILLIS / RINGS) % PERIOD_MILLIS) + / (double) PERIOD_MILLIS; + int size = dot + (int) ((side - dot) * part); + g.setAlpha((int) (90 * (1d - part))); + g.fillArc(centerX - size / 2, centerY - size / 2, size, size, 0, 360); + } + g.setAlpha(alpha); + g.fillArc(centerX - dot / 2, centerY - dot / 2, dot, dot, 0, 360); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/RegisterForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/RegisterForm.java new file mode 100644 index 00000000000..a417621dffb --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/RegisterForm.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.appkit.Net; +import com.codename1.components.SpanLabel; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codenameone.examples.lingo.AppConfig; +import com.codenameone.examples.lingo.Telemetry; +import com.codenameone.examples.lingo.api.RegisterDto; +import com.codenameone.examples.lingo.net.Api; +import com.codenameone.examples.lingo.net.Session; + +/// Creates a learner's account and signs in with it. +/// +/// Everyone who registers is a learner. Nobody registers as a creator or an +/// admin; those roles are granted. +public final class RegisterForm { + private RegisterForm() { + } + + public static void show(Form previous) { + final Form form = Ui.form("Start learning", "Register"); + Ui.back(form, previous); + Container page = Ui.page(); + page.add(Ui.banner(FontImage.MATERIAL_TRANSLATE, "Five minutes a day", + "Practise speaking with an AI tutor, keep a streak and earn signed " + + "certificates.", "LnBannerIcon")); + final TextField name = Ui.field(page, "Name", "name", "As it appears on your certificates"); + final TextField email = Ui.field(page, "E-mail", "email", "you@example.com", + TextArea.EMAILADDR); + final TextField phone = Ui.field(page, "Mobile number", "phone", "+1 555 010 0000", + TextArea.PHONENUMBER); + final TextField password = Ui.field(page, "Password", "password", + "At least 8 characters", TextArea.PASSWORD); + + final SpanLabel error = Ui.text("", "LnError"); + error.setName("error"); + final Button create = Ui.primary("Create account", "submit", null); + create.addActionListener(e -> { + final RegisterDto request = new RegisterDto(email.getText().trim(), + password.getText(), name.getText().trim(), phone.getText().trim()); + final Net.Failed failed = (status, message) -> { + create.setEnabled(true); + error.setText(message); + Ui.refresh(form); + }; + create.setEnabled(false); + error.setText(""); + // The server checks every field and says what is wrong with the + // first that fails, so nothing is validated twice. + Api.account().register(request, Net.to(user -> Session.signIn(request.email(), + request.password(), () -> { + AppConfig.setMode(Nav.LEARN, Session.owner(request.email())); + Telemetry.registered(); + Nav.enter(); + }, failed), failed)); + }); + page.add(error).add(create); + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ring.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ring.java new file mode 100644 index 00000000000..fcd8eb0cb20 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ring.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Font; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; + +/// A countdown drawn as a ring that empties, with the seconds left inside it. +/// +/// The colours are two styles' text colours: `LnRing` for the part of the +/// ring still left and `LnRingTrack` for the part used up. Neither has a +/// background, so whatever the ring sits on shows through its middle. +public final class Ring extends Component { + private long endsAt; + private int total = 1; + private int shown = -1; + + public Ring() { + setUIID("LnRing"); + } + + /// Starts counting down from `seconds`, of a count that began at `of`. + public void start(int seconds, int of) { + total = Math.max(1, Math.max(seconds, of)); + endsAt = System.currentTimeMillis() + seconds * 1000L; + repaint(); + } + + /// The whole seconds left, never less than none. + public int secondsLeft() { + long left = endsAt - System.currentTimeMillis(); + return left <= 0 ? 0 : (int) ((left + 999) / 1000); + } + + @Override + protected void initComponent() { + super.initComponent(); + Form form = getComponentForm(); + if (form != null) { + form.registerAnimated(this); + } + } + + @Override + protected void deinitialize() { + Form form = getComponentForm(); + if (form != null) { + form.deregisterAnimated(this); + } + super.deinitialize(); + } + + /// Repaints while the count is running, which is what makes the ring + /// shrink smoothly and not a second at a time. + @Override + public boolean animate() { + boolean running = endsAt > System.currentTimeMillis() || shown != 0; + shown = secondsLeft(); + return running; + } + + @Override + protected Dimension calcPreferredSize() { + Style style = getStyle(); + int side = CN.convertToPixels(10.5f); + return new Dimension(side + style.getHorizontalPadding(), + side + style.getVerticalPadding()); + } + + @Override + public void paint(Graphics g) { + Style style = getStyle(); + int track = UIManager.getInstance().getComponentStyle("LnRingTrack").getFgColor(); + int side = Math.min(getWidth() - style.getHorizontalPadding(), + getHeight() - style.getVerticalPadding()); + if (side <= 0) { + return; + } + int centerX = getX() + getWidth() / 2; + int centerY = getY() + getHeight() / 2; + int stroke = Math.max(2, CN.convertToPixels(0.9f)); + int radius = (side - stroke) / 2; + long left = Math.max(0L, endsAt - System.currentTimeMillis()); + double part = Math.min(1d, left / (total * 1000d)); + + // The ring as dots around the circle, the first at the top and going + // clockwise: enough of them that they join up. + g.setAntiAliased(true); + int dots = Math.max(60, (int) (2 * Math.PI * radius / Math.max(1, stroke / 2))); + int lit = (int) Math.round(dots * part); + for (int dot = 0; dot < dots; dot++) { + double angle = 2 * Math.PI * dot / dots; + int x = centerX + (int) Math.round(Math.sin(angle) * radius); + int y = centerY - (int) Math.round(Math.cos(angle) * radius); + g.setColor(dot < lit ? style.getFgColor() : track); + g.fillArc(x - stroke / 2, y - stroke / 2, stroke, stroke, 0, 360); + } + + String text = String.valueOf(secondsLeft()); + Font font = style.getFont(); + g.setFont(font); + g.setColor(style.getFgColor()); + g.drawString(text, centerX - font.stringWidth(text) / 2, centerY - font.getHeight() / 2); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ServerForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ServerForm.java new file mode 100644 index 00000000000..03670f8a9b2 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/ServerForm.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codenameone.examples.lingo.net.Session; + +/// Where the server is. A released app has one answer and no use for this +/// screen; while you are developing, it is how a phone is pointed at the server +/// running on your computer -- `http://` and the computer's address on the +/// network, since `localhost` on a phone is the phone. +public final class ServerForm { + private ServerForm() { + } + + public static void show(Form previous) { + Form form = Ui.form("Server address", "Server"); + Ui.back(form, previous); + Container page = Ui.page(); + page.add(Ui.text("The address of the Lingo server this app talks to. " + + "Changing it signs you out.", "LnText")); + final TextField url = Ui.field(page, "Address", "url", "http://192.168.1.20:8080", + TextArea.URL); + url.setText(Session.serverUrl()); + page.add(Ui.primary("Save", "submit", e -> Nav.changeServer(url.getText()))); + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SettingsForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SettingsForm.java new file mode 100644 index 00000000000..5dc4e304c05 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SettingsForm.java @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.AppConfig; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.Telemetry; +import com.codenameone.examples.lingo.api.AccountClosureDto; +import com.codenameone.examples.lingo.api.PasswordChangeDto; +import com.codenameone.examples.lingo.api.UserDto; +import com.codenameone.examples.lingo.net.Api; +import com.codename1.appkit.Net; +import com.codenameone.examples.lingo.net.Session; + +/// Settings: the account, and everything about the app a person may want +/// their own way. +/// +/// Every control here reads and writes [Prefs] and nothing else, so this +/// screen does not know where a setting is kept: `Prefs` keeps it on the +/// device, and `net.Account` hears of the change and keeps it with the account. +/// The three under Appearance change what is already on screen -- the +/// language, light or dark, miles or kilometres -- and take effect at once: the +/// look and the words are applied, and the screens are built again in them, +/// this one included. +public final class SettingsForm { + private SettingsForm() { + } + + public static void show(final Form previous) { + final Form form = Ui.form("Settings", "Settings"); + Ui.back(form, previous); + final UserDto user = Session.user(); + Container page = Ui.page(); + + page.add(Ui.person(user.displayName(), user.username(), null)); + + Ui.section(page, "Account"); + Container account = group(); + account.add(Ui.tap(Ui.row(FontImage.MATERIAL_PERSON, "Profile", + "Your name and mobile number", chevron()), "profile", + e -> ProfileForm.show(form, () -> show(previous)))); + account.add(Ui.tap(Ui.row(FontImage.MATERIAL_LOCK, "Password", + "Change the password you sign in with", chevron()), "password", + e -> password(form))); + page.add(account); + + if (user.learner()) { + Ui.section(page, "Learning"); + Container work = group(); + work.add(Ui.row(FontImage.MATERIAL_WIFI, "Wait for Wi-Fi", + "The on-device language model is large; wait for Wi-Fi to fetch it", + Ui.toggle("wifiOnlyModel", Prefs.wifiOnlyModel(), Prefs::setWifiOnlyModel))); + work.add(Ui.row(FontImage.MATERIAL_CLOUD, "Cloud tutor", + "When this phone cannot run the tutor, ask the server's AI instead", + Ui.toggle("cloudTutor", Prefs.cloudTutor(), Prefs::setCloudTutor))); + page.add(work); + } + + Ui.section(page, "Notifications"); + Container notify = group(); + notify.add(Ui.row(FontImage.MATERIAL_ALARM, "Practice reminder", + "A nudge when today's goal is not done yet", + Ui.toggle("notifyReminders", Prefs.notifyReminders(), + Prefs::setNotifyReminders))); + notify.add(Ui.row(FontImage.MATERIAL_SENSORS, "Live classes", + "A class you booked is starting", + Ui.toggle("notifyLive", Prefs.notifyLive(), + Prefs::setNotifyLive))); + page.add(notify); + + Ui.section(page, "Appearance"); + Container look = group(); + look.add(Ui.label("Language", "LnLabel")); + String speaking = Lang.current(); + for (int iter = 0; iter < Lang.CODES.length; iter++) { + final String code = Lang.CODES[iter]; + Label tick = new Label("", "LnRowIcon"); + if (code.equals(speaking)) { + Ui.icon(tick, FontImage.MATERIAL_CHECK, 3.4f); + } + Container row = new Container(new BorderLayout()); + row.setUIID("LnRow"); + // A language is called what its speakers call it, whatever + // language the rest of the screen is in. + row.add(BorderLayout.CENTER, Ui.plain(Lang.name(code), "LnRowTitle")); + row.add(BorderLayout.EAST, tick); + look.add(Ui.tap(row, "language-" + code, e -> { + boolean other = !code.equals(Lang.current()); + Prefs.setLanguage(code); + if (other) { + Telemetry.languageChanged(code); + } + again(previous); + })); + } + look.add(Ui.label("Theme", "LnLabel")); + look.add(Ui.choice("theme", new String[] {"System", "Light", "Dark"}, + new String[] {Prefs.THEME_SYSTEM, Prefs.THEME_LIGHT, Prefs.THEME_DARK}, + Prefs.theme(), value -> { + if (!value.equals(Prefs.theme())) { + Prefs.setTheme(value); + Telemetry.themeChanged(value); + } + again(previous); + })); + page.add(look); + + Ui.section(page, "Privacy"); + Container safe = group(); + // Kept on this device and not with the account: it is this + // installation that reports or does not. + safe.add(Ui.row(FontImage.MATERIAL_INSIGHTS, "Usage statistics", + "Share which screens and features are used. Never your name, voice or " + + "what you say.", + Ui.toggle("usageStatistics", Telemetry.allowed(), Telemetry::allow))); + page.add(safe); + + Ui.section(page, "About"); + Container about = group(); + about.add(Ui.row(FontImage.MATERIAL_INFO, "Lingo", + "A sample learning app built with Codename One", null)); + about.add(Ui.tap(Ui.row(FontImage.MATERIAL_DESCRIPTION, "Terms of service", null, + chevron()), "terms", e -> legal(form, "Terms of service", + "Lingo is a sample. Payments are simulated and certificates are " + + "signed with a demonstration key.", null))); + about.add(Ui.tap(Ui.row(FontImage.MATERIAL_POLICY, "Privacy policy", null, chevron()), + "privacy", e -> legal(form, "Privacy policy", + "Speech recognition and the AI tutor run on this phone. What you " + + "say leaves it only if you turn on the cloud tutor. Your progress " + + "and settings are kept with your account on the server you signed " + + "in to.", + "With usage statistics turned on, the app also counts which screens " + + "are opened and which features are used, and reports that to " + + "Codename One's analytics service under a made-up id for this " + + "device. Your name, e-mail, phone number, voice and conversations " + + "are never part of it, and turning it off in Settings stops it."))); + if (AppConfig.serverSwitchable()) { + about.add(Ui.tap(Ui.row(FontImage.MATERIAL_DNS, "Server address", null, chevron()), + "server", e -> ServerForm.show(form))); + } + page.add(about); + + page.add(Ui.secondary("Sign out", "signOut", e -> Nav.signOut())); + page.add(Ui.link("Delete my account", "deleteAccount", e -> delete(form))); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + /// Applies the look and the language, and shows everything again in them. + /// + /// A screen that is already built keeps the words and colours it was built + /// with, so the mode's first screen is built anew to go back to, and this + /// one over it. + private static void again(Form previous) { + Look.apply(); + Lang.apply(); + Form home = Nav.build(); + show(home == null ? previous : home); + } + + static Container group() { + Container group = new Container(BoxLayout.y()); + group.setUIID("LnGroup"); + return group; + } + + /// The mark at the end of a row that leads somewhere. + static Label chevron() { + Label chevron = new Label("", "LnRowIcon"); + Ui.icon(chevron, FontImage.MATERIAL_CHEVRON_RIGHT, 3.4f); + return chevron; + } + + /// Changing the password. The server wants the current one as well as the + /// new: being signed in is what a borrowed phone is, too. + private static void password(final Form previous) { + final Form form = Ui.form("Password", "Password"); + Ui.back(form, previous); + Container page = Ui.page(); + final TextField current = Ui.field(page, "Current password", "current", "", + TextArea.PASSWORD); + final TextField replacement = Ui.field(page, "New password", "replacement", + "At least 8 characters", TextArea.PASSWORD); + final TextField again = Ui.field(page, "New password, again", "again", "", + TextArea.PASSWORD); + final SpanLabel error = Ui.text("", "LnError"); + error.setName("error"); + final Button save = Ui.primary("Change password", "submit", null); + save.addActionListener(e -> { + if (!replacement.getText().equals(again.getText())) { + error.setText(Lang.tr("The two new passwords are not the same.")); + Ui.refresh(form); + return; + } + PasswordChangeDto change = new PasswordChangeDto(current.getText(), + replacement.getText()); + save.setEnabled(false); + error.setText(""); + Api.account().changePassword(change, Net.to(user -> { + Ui.say("Your password was changed"); + previous.showBack(); + }, (status, message) -> { + save.setEnabled(true); + error.setText(message); + Ui.refresh(form); + })); + }); + page.add(error).add(save); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + /// Closing the account, which cannot be taken back, so it is its own + /// screen that says what goes and has one red button. + private static void delete(final Form previous) { + final Form form = Ui.form("Delete account", "DeleteAccount"); + Ui.back(form, previous); + Container page = Ui.page(); + page.add(Ui.banner(FontImage.MATERIAL_DELETE_FOREVER, "Delete your account?", + "Your sign-in, profile, progress and settings are removed for good. " + + "Certificates already issued can still be verified.", + "LnBannerIconBad")); + // Asked for again, as changing the password asks: being signed in is + // what a borrowed phone is, too, and the server refuses without it. + final TextField password = Ui.field(page, "Current password", "password", "", + TextArea.PASSWORD); + final SpanLabel error = Ui.text("", "LnError"); + error.setName("error"); + page.add(error); + final Button go = Ui.danger("Delete my account", "confirmDelete", null); + go.addActionListener(e -> { + go.setEnabled(false); + AccountClosureDto closure = new AccountClosureDto(password.getText()); + Api.account().deleteAccount(closure, Net.to(gone -> Nav.deleted(), (status, message) -> { + go.setEnabled(true); + error.setText(message); + Ui.refresh(form); + })); + }); + page.add(go); + page.add(Ui.link("Keep my account", "keep", e -> previous.showBack())); + form.add(BorderLayout.CENTER, page); + form.show(); + } + + private static void legal(Form previous, String title, String text, String more) { + Form form = Ui.form(title, "Legal"); + Ui.back(form, previous); + Container page = Ui.page(); + page.add(Ui.text(text, "LnText")); + if (more != null) { + page.add(Ui.text(more, "LnText")); + } + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SignInForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SignInForm.java new file mode 100644 index 00000000000..8a8e72a47e0 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/SignInForm.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codenameone.examples.lingo.Telemetry; +import com.codenameone.examples.lingo.net.Session; + +/// E-mail and password. The form is the app's own; what happens when it is +/// submitted is in [Session#signIn]. +public final class SignInForm { + private SignInForm() { + } + + public static void show(Form previous) { + final Form form = Ui.form("Sign in", "SignIn"); + Ui.back(form, previous); + Container page = Ui.page(); + final TextField email = Ui.field(page, "E-mail", "email", "you@example.com", + TextArea.EMAILADDR); + final TextField password = Ui.field(page, "Password", "password", "", + TextArea.PASSWORD); + final SpanLabel error = Ui.text("", "LnError"); + error.setName("error"); + final Button signIn = Ui.primary("Sign in", "submit", null); + signIn.addActionListener(e -> { + if (email.getText().trim().length() == 0 || password.getText().length() == 0) { + error.setText("Enter your e-mail and password."); + Ui.refresh(form); + return; + } + signIn.setEnabled(false); + error.setText(""); + Session.signIn(email.getText().trim(), password.getText(), () -> { + Telemetry.signedIn(); + Nav.enter(); + }, (status, message) -> { + signIn.setEnabled(true); + error.setText(message); + Ui.refresh(form); + }); + }); + page.add(error).add(signIn); + form.add(BorderLayout.CENTER, page); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/StatRow.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/StatRow.java new file mode 100644 index 00000000000..8b89aee8dc7 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/StatRow.java @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.Font; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; + +import java.util.ArrayList; +import java.util.List; + +/// A row of dashboard numbers, each over its caption, sized as one thing. +/// +/// A label asked to fit its own text decides alone and after the fact: it +/// changes its font once it has been given a width, by which time the tile +/// around it has its height from the font it had before, and its neighbour +/// has decided something else. The result was a row whose numbers were three +/// sizes and whose captions were cut off, or pushed out of the tile. +/// +/// So the row decides, before it lays its tiles out and from the width it +/// really has: one size for every number, the largest at which the longest +/// fits, and one for every caption, which goes onto a second line before it +/// is made any smaller. +public final class StatRow extends Container { + /// The smallest a number and a caption are drawn, in millimetres. + private static final float SMALLEST_VALUE = 2.6f; + private static final float SMALLEST_CAPTION = 1.9f; + + private final int columns; + private final List tiles = new ArrayList(); + private int laidOutAt; + private String fitted = ""; + private String planned = ""; + private boolean correcting; + + StatRow(int columns) { + super(new GridLayout(1, columns)); + this.columns = columns; + } + + /// Adds a number: `value` as it is, over `caption` in the user's language. + /// The number's label is called `name`. + public StatRow stat(String value, String caption, String name) { + Tile tile = new Tile(value, Lang.tr(caption), name); + tiles.add(tile); + add(tile); + return this; + } + + /// Takes every number out, for a row that is filled again. + public void clear() { + tiles.clear(); + removeAll(); + } + + @Override + protected Dimension calcPreferredSize() { + // Asked how tall it is before it knows how wide: answered for the + // width it last had, or the room its nearest sized ancestor offers. + fit(laidOutAt > 0 ? laidOutAt : roomOffered()); + planned = fitted; + return super.calcPreferredSize(); + } + + @Override + public void layoutContainer() { + int width = getWidth(); + if (width > 0) { + laidOutAt = width; + fit(width); + if (!fitted.equals(planned) && !correcting) { + // The height was answered for another width, and the tiles + // are a different height at this one. + correcting = true; + CN.callSerially(() -> { + correcting = false; + setShouldCalcPreferredSize(true); + Form form = getComponentForm(); + if (form != null) { + form.revalidate(); + } + }); + } + } + super.layoutContainer(); + } + + private int roomOffered() { + Container parent = getParent(); + while (parent != null) { + if (parent.getWidth() > 0) { + return parent.getWidth() - parent.getStyle().getHorizontalPadding(); + } + parent = parent.getParent(); + } + return CN.getDisplayWidth(); + } + + private void fit(int width) { + if (tiles.isEmpty() || width <= 0) { + return; + } + int across = Math.min(columns, tiles.size()); + Tile first = tiles.get(0); + int room = (width - getStyle().getHorizontalPadding()) / across + - first.getStyle().getHorizontalPadding() + - first.getStyle().getHorizontalMargins(); + if (room <= 0) { + return; + } + float value = 1f; + float caption = 1f; + for (Tile tile : tiles) { + value = Math.min(value, share(room - tile.value.sides(), tile.value.width(tile.number))); + tile.split(room - tile.upper.sides()); + caption = Math.min(caption, share(room - tile.upper.sides(), tile.widest())); + } + StringBuilder made = new StringBuilder(); + for (Tile tile : tiles) { + made.append(tile.value.scale(value, SMALLEST_VALUE)).append('/'); + made.append(tile.upper.scale(caption, SMALLEST_CAPTION)).append('/'); + tile.lower.scale(caption, SMALLEST_CAPTION); + made.append(tile.show()).append(' '); + } + fitted = made.toString(); + } + + /// The part of its full size at which text `needed` pixels wide fits + /// `room`. + private static float share(int room, int needed) { + return needed <= room || needed <= 0 ? 1f : Math.max(0f, room) / (float) needed; + } + + /// One number over its caption. + private static final class Tile extends Container { + private final String number; + private final String caption; + private final Sized value; + private final Sized upper; + private final Sized lower; + private String top; + private String bottom; + + Tile(String number, String caption, String name) { + super(BoxLayout.y()); + setUIID("LnStat"); + this.number = number == null ? "" : number; + this.caption = caption == null ? "" : caption; + value = new Sized(Ui.plain(this.number, "LnStatValue")); + value.label.setName(name); + upper = new Sized(Ui.plain(this.caption, "LnStatLabel")); + lower = new Sized(Ui.plain("", "LnStatLabel")); + top = this.caption; + bottom = ""; + add(value.label).add(upper.label).add(lower.label); + show(); + } + + /// Puts the caption on one line if `room` holds it, and otherwise on + /// two, broken at the space that leaves the longer line shortest. + void split(int room) { + top = caption; + bottom = ""; + int whole = upper.width(caption); + if (whole <= room) { + return; + } + int best = whole; + for (int at = caption.indexOf(' '); at > 0; at = caption.indexOf(' ', at + 1)) { + String before = caption.substring(0, at); + String after = caption.substring(at + 1); + int longer = Math.max(upper.width(before), upper.width(after)); + if (longer < best) { + best = longer; + top = before; + bottom = after; + } + } + } + + int widest() { + return Math.max(upper.width(top), upper.width(bottom)); + } + + /// Writes the lines decided by [#split]; answers how many there are. + int show() { + if (!top.equals(upper.label.getText())) { + upper.label.setText(top); + } + if (!bottom.equals(lower.label.getText())) { + lower.label.setText(bottom); + } + boolean second = bottom.length() > 0; + if (lower.label.isHidden() == second) { + lower.label.setHidden(!second); + lower.label.setVisible(second); + } + return second ? 2 : 1; + } + } + + /// A label and the font its style gave it, which is the size it is drawn + /// at when there is room. The style is asked again every time, because a + /// label is restyled under us: the desktop console gives it another name, + /// and a change of theme gives it another font. + private static final class Sized { + private final Label label; + private Font styled; + private Font applied; + private int appliedPixels; + + Sized(Label label) { + this.label = label; + } + + private Font styled() { + Font now = label.getUnselectedStyle().getFont(); + if (now != applied || styled == null) { + styled = now; + applied = now; + appliedPixels = Math.round(now.getPixelSize()); + } + return styled; + } + + int sides() { + return label.getUnselectedStyle().getHorizontalPadding() + + label.getUnselectedStyle().getHorizontalMargins(); + } + + /// How wide `text` is at the full size. + int width(String text) { + return text.length() == 0 ? 0 : styled().stringWidth(text); + } + + /// Draws the label at `share` of its full size, and never smaller + /// than `smallest` millimetres; answers the size in pixels. + int scale(float share, float smallest) { + Font full = styled(); + int most = Math.round(full.getPixelSize()); + if (most <= 0) { + // Not a font that can be drawn at another size. + return 0; + } + int least = Math.min(most, CN.convertToPixels(smallest)); + int pixels = share >= 1f ? most : Math.max(least, (int) Math.floor(most * share)); + if (pixels != appliedPixels) { + applied = pixels == most ? full : full.derive(pixels, full.getStyle()); + appliedPixels = pixels; + label.getAllStyles().setFont(applied); + } + return pixels; + } + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ui.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ui.java new file mode 100644 index 00000000000..8d686d6630e --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/Ui.java @@ -0,0 +1,707 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.appkit.Skeleton; + +import com.codename1.components.SpanLabel; +import com.codename1.components.Switch; +import com.codename1.components.ToastBar; +import com.codename1.l10n.SimpleDateFormat; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Command; +import com.codename1.ui.ButtonGroup; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Display; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.RadioButton; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.geom.Rectangle; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.LayeredLayout; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; +import com.codename1.appkit.Net; +import com.codenameone.examples.lingo.Prefs; +import com.codenameone.examples.lingo.Telemetry; + +import java.util.Date; + +/// The pieces every screen is made of. Each one is a component with a style +/// name from `theme.css`; nothing here, or in any screen, sets a colour or a +/// font in code. +public final class Ui { + /// What goes between two short facts on one line: a raised dot. + public static final String DOT = " \u00b7 "; + + private Ui() { + } + + /// A screen with a title bar. + /// + /// @param name what a test waits for; the title is for people and changes + public static Form form(String title, String name) { + Form form = new Form(title, new BorderLayout()); + form.setUIID("LnForm"); + form.setName(name); + watch(form); + clearOfTheStatusBar(form); + form.addSizeChangedListener(e -> clearOfTheStatusBar(form)); + return form; + } + + /// Keeps the title bar of `form` under what the device draws over the top + /// of the screen -- the clock, a notch -- the same way the map screens + /// keep their floating bar under it: by the inset the device reports. The + /// strip a form reserves for the status bar is as tall as the theme makes + /// it, which says nothing of a notch; the title bar is padded by whatever + /// that strip leaves uncovered. + private static void clearOfTheStatusBar(Form form) { + Container bar = form.getToolbar(); + if (bar == null) { + return; + } + Rectangle safe = Display.getInstance().getDisplaySafeArea(new Rectangle()); + int covered = Math.max(0, safe.getY()); + Container area = bar.getParent(); + int kept = 0; + if (area != null && area.getLayout() instanceof BorderLayout) { + Component strip = ((BorderLayout) area.getLayout()).getNorth(); + if (strip != null && strip != bar) { + kept = strip.getPreferredH(); + } + } + int styled = UIManager.getInstance().getComponentStyle("Toolbar").getPaddingTop(); + int wanted = styled + Math.max(0, covered - kept); + if (bar.getUnselectedStyle().getPaddingTop() != wanted) { + bar.getAllStyles().setPaddingUnitTop(Style.UNIT_TYPE_PIXELS); + bar.getAllStyles().setPaddingTop(wanted); + } + } + + /// Gives `label` a material icon `size` millimetres tall, and the space + /// between it and the label's words: without one the two touch. + public static void icon(Label label, char icon, float size) { + FontImage.setMaterialIcon(label, icon, size); + label.setGap(CN.convertToPixels(ICON_GAP)); + } + + /// The space between an icon and the words beside it, in millimetres. + private static final float ICON_GAP = 1.4f; + + /// Has `form` counted as a screen each time it is shown, under its name. + /// Every screen of the app is made by this class or handed to this method, + /// so this is the one place a screen view is reported from. + public static void watch(final Form form) { + form.addShowListener(e -> viewed(form.getName())); + } + + /// Counts something that takes the place of a screen without being a + /// form: a pane of the admin's console on a wide window. + public static void viewed(String name) { + Telemetry.screen(name); + } + + /// The first screen of a mode: no title bar, and layers, so that a map can + /// fill the screen with the controls floating over it and the menu sliding + /// in over both. + public static Form home(String name) { + Form form = new Form("", new LayeredLayout()); + form.setUIID("LnForm"); + form.setName(name); + watch(form); + form.getToolbar().hideToolbar(); + // What is on the screen scrolls, where it needs to. The screen itself + // does not, or it would offer to scroll the map away. + form.setScrollable(false); + return form; + } + + /// Gives `form` a back arrow that returns to `previous`. + public static void back(Form form, final Form previous) { + back(form, () -> previous.showBack()); + } + + /// Gives `form` a back arrow that runs `leave`. + /// + /// On a desktop whose window owns the title bar there is no title bar in + /// the app to carry an arrow. The command is then named, so that it is in + /// the window's menu, and the screen gets a line of its own to go back + /// from. A screen that has put something of its own at its top keeps it, + /// under that line: a screen with no way back is one nobody can leave + /// without a device's back button, and a desktop has none. + public static void back(final Form form, final Runnable leave) { + boolean window = CN.isDesktop() && form.getToolbar().getParent() == null; + Command back = form.getToolbar().setBackCommand(window ? Lang.tr("Back") : "", + e -> leave.run()); + if (!window) { + return; + } + back.setDesktopMenu(Command.DESKTOP_MENU_VIEW); + back.setDesktopShortcut('['); + final boolean[] added = new boolean[1]; + form.addShowListener(e -> { + if (added[0] || form.getToolbar().getParent() != null + || !(form.getContentPane().getLayout() instanceof BorderLayout)) { + return; + } + added[0] = true; + Container bar = new Container(new BorderLayout()); + bar.setUIID("LnPaneBar"); + Button arrow = button("Back", "back-bar", "LnLink", e2 -> leave.run()); + icon(arrow, FontImage.MATERIAL_ARROW_BACK, 3.4f); + bar.add(BorderLayout.WEST, arrow); + Component top = ((BorderLayout) form.getContentPane().getLayout()).getNorth(); + if (top == null) { + form.add(BorderLayout.NORTH, bar); + } else { + top.remove(); + Container both = new Container(BoxLayout.y()); + both.add(bar).add(top); + form.add(BorderLayout.NORTH, both); + } + Layouts.dress(bar); + form.revalidate(); + }); + } + + /// A column of content with the page's margins, that scrolls when it has to. + public static Container page() { + Container page = new Column(); + page.setUIID("LnPage"); + page.setScrollableY(true); + page.setScrollVisible(false); + page.setSafeArea(true); + return page; + } + + public static Container card() { + Container card = new Container(BoxLayout.y()); + card.setUIID("LnCard"); + return card; + } + + public static Label label(String text, String uiid) { + return new Label(text == null ? "" : text, uiid); + } + + /// Lays `form` out after wrapped text was added to it while it is on + /// screen. The first pass measures new text before it knows how wide it + /// may be, and keeps that answer: a paragraph came out as one clipped + /// line. A second pass, once the widths are settled, measures it again. + public static void relayout(final Form form, final Runnable then) { + form.revalidate(); + CN.callSerially(new Runnable() { + @Override + public void run() { + form.getContentPane().setShouldCalcPreferredSize(true); + form.revalidate(); + if (then != null) { + then.run(); + } + } + }); + } + + /// [#relayout(Form, Runnable)] for the form `inside` is on, or just + /// `inside` while it is on none. + public static void relayout(Container inside) { + Form form = inside.getComponentForm(); + if (form == null) { + inside.revalidate(); + } else { + relayout(form, null); + } + } + + /// Text that wraps. + public static SpanLabel text(String text, String uiid) { + SpanLabel label = new SpanLabel(text == null ? "" : text); + label.setUIID("Container"); + label.setTextUIID(uiid); + return label; + } + + public static Button primary(String text, String name, ActionListener onClick) { + return button(text, name, "LnPrimary", onClick); + } + + public static Button secondary(String text, String name, ActionListener onClick) { + return button(text, name, "LnSecondary", onClick); + } + + public static Button danger(String text, String name, ActionListener onClick) { + return button(text, name, "LnDanger", onClick); + } + + public static Button link(String text, String name, ActionListener onClick) { + return button(text, name, "LnLink", onClick); + } + + /// A round button that floats over the map. + public static Button round(char icon, String name, ActionListener onClick) { + Button button = button("", name, "LnMapButton", onClick); + icon(button, icon, 4f); + speak(button, name); + return button; + } + + /// What a screen reader says for a button that shows only an icon: + /// without it VoiceOver and TalkBack announce a bare "button". + private static void speak(Button button, String name) { + String words; + if ("menu-open".equals(name)) { + words = "Menu"; + } else if ("closeSheet".equals(name)) { + words = "Close"; + } else if ("fitRoute".equals(name)) { + words = "Show the whole route"; + } else if ("askAssistant".equals(name)) { + words = "Assistant"; + } else if ("send".equals(name)) { + words = "Send"; + } else { + return; + } + button.setAccessibilityText(Lang.tr(words)); + } + + /// The same button for a bar that is a surface of its own: flat, since a + /// shadow says "this floats", and on a bar nothing does. + public static Button flat(char icon, String name, ActionListener onClick) { + Button button = button("", name, "LnBarButton", onClick); + icon(button, icon, 4f); + speak(button, name); + return button; + } + + /// One of a row of things to do: an icon with a word under it. + public static Button action(char icon, String text, String name, + ActionListener onClick) { + Button button = button(text, name, "LnAction", onClick); + icon(button, icon, 4f); + button.setTextPosition(Component.BOTTOM); + button.setGap(CN.convertToPixels(0.6f)); + return button; + } + + /// A short fact in a pill: how far, how long. The icon may be 0. + public static Label chip(String text, char icon) { + Label chip = new Label(text == null ? "" : text, "LnChip"); + if (icon != 0) { + icon(chip, icon, 2.7f); + } + return chip; + } + + /// A person, as the initials of their name in a circle. + public static Label avatar(String name) { + Label avatar = new Label("", "LnAvatar"); + // Initials are not words: looking them up would translate "OK". + avatar.setShouldLocalize(false); + avatar.setText(initials(name)); + return avatar; + } + + /// The first letters of the first and last words of `name`. + public static String initials(String name) { + String text = name == null ? "" : name.trim(); + if (text.length() == 0) { + return "?"; + } + int space = text.lastIndexOf(' '); + String first = text.substring(0, 1); + return space < 0 || space + 1 >= text.length() ? first + : first + text.substring(space + 1, space + 2); + } + + public interface Flipped { + void flipped(boolean on); + } + + /// A switch that reports each change. + public static Switch toggle(String name, boolean value, final Flipped flipped) { + final Switch toggle = new Switch(); + toggle.setName(name); + toggle.setValue(value); + toggle.addChangeListener(e -> flipped.flipped(toggle.isValue())); + return toggle; + } + + public interface Chosen { + void chosen(String value); + } + + /// A few options side by side, one of them selected. Each button is named + /// `name-value`. + /// + /// @param labels what each option is called, for people + /// @param values what each option is, for the code + public static Container choice(String name, String[] labels, final String[] values, + String current, final Chosen chosen) { + return choice(name, labels, values, current, chosen, values.length); + } + + /// The same, in rows of `columns`, for options that do not fit in one. + public static Container choice(String name, String[] labels, final String[] values, + String current, final Chosen chosen, int columns) { + Container row = new Container(new GridLayout((values.length + columns - 1) / columns, + columns)); + row.setUIID("LnSegments"); + ButtonGroup group = new ButtonGroup(); + for (int iter = 0; iter < values.length; iter++) { + final String value = values[iter]; + RadioButton option = RadioButton.createToggle(labels[iter], group); + option.setUIID("LnSegment"); + option.setName(name + "-" + value); + option.setSelected(value.equals(current)); + option.addActionListener(e -> chosen.chosen(value)); + row.add(option); + } + return row; + } + + /// The longest address that is still shown on one line. + private static final int LONG_ADDRESS = 26; + + /// Who a screen is about: their initials, their name, the address they sign + /// in with, and under those `value` when there is something to say about + /// them. The address wraps rather than being cut off; it is what tells + /// two people with the same name apart. + public static Container person(String name, String username, Component value) { + Container who = new Container(new BorderLayout()); + who.setUIID("LnPanel"); + Container names = new Container(BoxLayout.y()); + Label called = plain(name, "LnHeading"); + shrink(called, 3f); + String signsIn = username == null ? "" : username; + Component address; + if (signsIn.length() > LONG_ADDRESS) { + // An address has no spaces to break at: a long one is broken + // where the line ends, which keeps all of it readable. + SpanLabel wrapped = text("", "LnMuted"); + wrapped.setShouldLocalize(false); + wrapped.setText(signsIn); + address = wrapped; + } else { + Label line = plain(signsIn, "LnMuted"); + shrink(line, 2f); + address = line; + } + names.add(called).add(address); + if (value != null) { + names.add(FlowLayout.encloseIn(value)); + } + who.add(BorderLayout.WEST, FlowLayout.encloseCenterMiddle(avatar(name))); + who.add(BorderLayout.CENTER, names); + return who; + } + + /// Lets `label` draw its text smaller, down to `smallest` millimetres, + /// when it would otherwise be cut off -- and never larger than its style + /// says, which is what fitting text to its space does when left alone. + public static void shrink(Label label, float smallest) { + float styled = label.getUnselectedStyle().getFont().getPixelSize() + / (float) CN.convertToPixels(1f); + label.setAutoSizeMode(true); + label.setMaxAutoSize(styled); + label.setMinAutoSize(Math.min(smallest, styled)); + } + + /// Lays `form` out again after its content changed while it was showing. + /// + /// Twice, the second time after the first has been drawn: text that wraps + /// learns its width from the first pass, and only then knows how many + /// lines it is. + public static void refresh(final Form form) { + form.revalidate(); + CN.callSerially(() -> form.revalidate()); + } + + /// The heading over a group of settings or facts. + public static void section(Container page, String title) { + page.add(label(title, "LnSection")); + } + + /// A label for text that is a name or a number, not a word to translate. + public static Label plain(String text, String uiid) { + Label label = new Label("", uiid); + label.setShouldLocalize(false); + label.setText(text == null ? "" : text); + return label; + } + + /// One line of a receipt or a record: what it is on one side, and its + /// value, which is never translated, on the other. + public static Container fact(String caption, String value) { + return fact(caption, value, "LnFactValue"); + } + + public static Container fact(String caption, String value, String valueUiid) { + Container fact = new Container(new BorderLayout()); + fact.setUIID("LnFact"); + fact.add(BorderLayout.CENTER, label(caption, "LnFactLabel")); + fact.add(BorderLayout.EAST, plain(value, valueUiid)); + return fact; + } + + /// What a screen shows instead of a list with nothing in it, and at the top + /// of a screen that is about one thing: a large icon, a line, and a few + /// words under it. + public static Container banner(char icon, String title, String text, String iconUiid) { + Container banner = new Container(BoxLayout.y()); + banner.setUIID("LnBanner"); + Label image = new Label("", iconUiid); + icon(image, icon, 6f); + banner.add(FlowLayout.encloseCenter(image)); + SpanLabel heading = text(title, "LnBannerTitle"); + heading.getTextComponent().setAlignment(Component.CENTER); + banner.add(heading); + if (text != null && text.length() > 0) { + SpanLabel words = text(text, "LnBannerText"); + words.getTextComponent().setAlignment(Component.CENTER); + banner.add(words); + } + return banner; + } + + public static Container empty(char icon, String title, String text) { + return banner(icon, title, text, "LnBannerIcon"); + } + + /// A list that fills a screen: rows from edge to edge, scrolling. + public static Container list(String name) { + Container list = new Column(); + list.setUIID("LnList"); + list.setScrollableY(true); + list.setScrollVisible(false); + list.setName(name); + // Until it is filled: every list is emptied by what fills it. + list.add(new Skeleton(5, "LnSkeleton")); + return list; + } + + /// Has a pull down on `list` fetch what is in it again, with `load`. A + /// window on a desktop is not pulled, and gets nothing. + public static void pull(Container list, final Runnable load) { + if (!CN.isDesktop()) { + list.addPullToRefresh(load); + } + } + + /// A column that stays a column: on a window wider than a column of text + /// should be, it keeps its content in the middle rather than stretching + /// every row and every button from one edge to the other. + private static final class Column extends Container { + private String styled; + private int margin; + + Column() { + super(BoxLayout.y()); + } + + @Override + public void layoutContainer() { + // The margin is the style's own, read once for each style the + // column is given: what is set below replaces it. + if (!getUIID().equals(styled)) { + styled = getUIID(); + margin = getUnselectedStyle().getPaddingLeftNoRTL(); + } + Layouts.centre(this, margin); + super.layoutContainer(); + } + } + + private static Button button(String text, String name, String uiid, + ActionListener onClick) { + Button button = new Button(text, uiid); + // The name is what a test finds the button by. + button.setName(name); + if (onClick != null) { + button.addActionListener(onClick); + } + return button; + } + + /// Adds a caption and a text field under it to `to`, and returns the field. + public static TextField field(Container to, String caption, String name, String hint, + int constraint) { + TextField field = new TextField("", hint, 24, constraint); + field.setUIID("LnField"); + field.getHintLabel().setUIID("LnFieldHint"); + field.setName(name); + // The caption above it is what a screen reader reads for the field. + field.setAccessibilityText(Lang.tr(caption)); + to.add(label(caption, "LnLabel")).add(field); + return field; + } + + public static TextField field(Container to, String caption, String name, String hint) { + return field(to, caption, name, hint, TextArea.ANY); + } + + /// A row of a list: an icon, two lines of text, and something at the end. + /// The icon may be 0, and the last two null. + public static Container row(char icon, String title, String detail, Component value) { + Container row = new Container(new BorderLayout()); + row.setUIID("LnRow"); + if (icon != 0) { + Label image = new Label("", "LnRowIcon"); + icon(image, icon, 4f); + row.add(BorderLayout.WEST, image); + } + Container lines = new Container(BoxLayout.y()); + lines.add(label(title, "LnRowTitle")); + if (detail != null && detail.length() > 0) { + lines.add(text(detail, "LnRowDetail")); + } + row.add(BorderLayout.CENTER, lines); + if (value != null) { + // Its own height, in the middle of the row: straight into EAST it + // would be stretched to the height of the row. + row.add(BorderLayout.EAST, FlowLayout.encloseCenterMiddle(value)); + } + return row; + } + + /// Makes the whole of `row` one button. The name is the button's, for a + /// test to click. + public static Container tap(Container row, String name, ActionListener onClick) { + Button lead = new Button(); + lead.setName(name); + lead.setHidden(true); + lead.addActionListener(onClick); + row.add(BorderLayout.SOUTH, lead); + row.setLeadComponent(lead); + return row; + } + + /// A day, without the time. + public static String day(long millis) { + return new SimpleDateFormat("MMM d, yyyy").format(new Date(millis)); + } + + /// A day, as its weekday and date: "Monday, Nov 16". + public static String weekday(long millis) { + return new SimpleDateFormat("EEEE, MMM d").format(new Date(millis)); + } + + /// A moment, as a short date and time. + public static String when(long millis) { + return new SimpleDateFormat("MMM d, HH:mm").format(new Date(millis)); + } + + public static Label badge(String text, String uiid) { + return new Label(text, uiid); + } + + /// A row of numbers, each with a caption under it, `columns` across: + /// add them with [StatRow#stat]. More than `columns` of them run onto a + /// further row. + public static StatRow stats(int columns) { + return new StatRow(columns); + } + + /// Tells the user something failed. The signature is `Net.Failed`'s, so a + /// call can end `Ui::fail`. + public static void fail(int status, String message) { + // What the server says is the server's wording; what the app says of + // its own is translated. Looking both up costs nothing. + ToastBar.showErrorMessage(Lang.tr(message)); + } + + /// What a list's load ends with when it fails: the user is told, as with + /// [#fail], and a list still showing the outline of rows that are not + /// coming shows what went wrong instead, with a way to ask again. A list + /// that already has rows keeps them. + /// + /// @param load fetches the list again, or null when there is no asking again + public static Net.Failed failed(final Container list, final Runnable load) { + return (status, message) -> { + fail(status, message); + if (list.getComponentCount() != 1 || !(list.getComponentAt(0) instanceof Skeleton)) { + return; + } + list.removeAll(); + list.add(empty(FontImage.MATERIAL_CLOUD_OFF, message, null)); + if (load != null) { + list.add(FlowLayout.encloseCenter(link("Try again", "retry", e -> { + list.removeAll(); + list.add(new Skeleton(5, "LnSkeleton")); + list.revalidate(); + load.run(); + }))); + } + list.revalidate(); + }; + } + + public static void say(String message) { + ToastBar.showInfoMessage(Lang.tr(message)); + } + + /// A time of day, `14:05`. + public static String clock(long millis) { + java.util.Calendar c = java.util.Calendar.getInstance(); + c.setTime(new java.util.Date(millis)); + int h = c.get(java.util.Calendar.HOUR_OF_DAY); + int m = c.get(java.util.Calendar.MINUTE); + return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m; + } + + /// A duration, `1 h 20 min`. + public static String duration(int minutes) { + if (minutes < 60) { + return minutes + " min"; + } + if (minutes >= 10 * 60) { + // Hours of practice: the minutes are noise and do not fit a tile. + return Math.round(minutes / 60f) + " h"; + } + return minutes / 60 + " h" + (minutes % 60 == 0 ? "" : " " + minutes % 60 + " min"); + } + + /// A phone number as people read it. A North American number in E.164 + /// (+1 and ten digits) is grouped as (503) 555-0101; anything else is + /// shown as stored, since grouping differs by country. Dialing keeps the + /// stored form. + public static String phone(String e164) { + if (e164 == null || e164.length() != 12 || !e164.startsWith("+1")) { + return e164; + } + for (int iter = 2; iter < 12; iter++) { + char c = e164.charAt(iter); + if (c < '0' || c > '9') { + return e164; + } + } + return "(" + e164.substring(2, 5) + ") " + e164.substring(5, 8) + "-" + e164.substring(8); + } +} diff --git a/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/WelcomeForm.java b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/WelcomeForm.java new file mode 100644 index 00000000000..0d6012e2864 --- /dev/null +++ b/scripts/lingo/common/src/main/java/com/codenameone/examples/lingo/ui/WelcomeForm.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.ui; + +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.lingo.AppConfig; + +/// What a signed-out user sees. +public final class WelcomeForm { + private WelcomeForm() { + } + + private static Container feature(char glyph, String text) { + Container row = new Container(new BorderLayout(), "LnHeroFeature"); + Label icon = new Label("", "LnHeroFeatureIcon"); + Ui.icon(icon, glyph, 3.6f); + row.add(BorderLayout.WEST, icon); + row.add(BorderLayout.CENTER, Ui.text(text, "LnHeroText")); + return row; + } + + public static void show() { + final Form form = Ui.form("", "Welcome"); + form.getToolbar().hideToolbar(); + + Container hero = new Container(BoxLayout.y()); + hero.setUIID("LnHero"); + hero.setSafeArea(true); + Label icon = new Label("", "LnHeroIcon"); + Ui.icon(icon, FontImage.MATERIAL_TRANSLATE, 10f); + hero.add(icon); + hero.add(Ui.label("Lingo", "LnHeroTitle")); + hero.add(Ui.text("Speak a new language with an AI tutor that listens.", "LnHeroText")); + // What the app does, in three lines, rather than a logo over an + // empty field of colour. + hero.add(feature(FontImage.MATERIAL_RECORD_VOICE_OVER, + "Pronunciation scored word by word, on your phone")); + hero.add(feature(FontImage.MATERIAL_GROUPS, "Courses and live classes from real teachers")); + hero.add(feature(FontImage.MATERIAL_WORKSPACE_PREMIUM, + "Signed certificates anyone can verify")); + + Container actions = Ui.page(); + actions.setScrollableY(false); + actions.add(Ui.primary("Sign in", "signIn", e -> SignInForm.show(form))); + actions.add(Ui.secondary("Create an account", "register", e -> RegisterForm.show(form))); + if (AppConfig.serverSwitchable()) { + actions.add(Ui.link("Server address", "server", e -> ServerForm.show(form))); + } + + form.add(BorderLayout.CENTER, hero); + form.add(BorderLayout.SOUTH, actions); + form.show(); + } +} diff --git a/scripts/lingo/common/src/main/l10n/Bundle.properties b/scripts/lingo/common/src/main/l10n/Bundle.properties new file mode 100644 index 00000000000..c07a695976e --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle.properties @@ -0,0 +1,3 @@ +# Workaround for the simulator AutoLocalizationBundle @im fabrication crash +# in Codename One <= 7.0.236. Once the framework fix ships, this file can be removed. +@im= diff --git a/scripts/lingo/common/src/main/l10n/Bundle_de.properties b/scripts/lingo/common/src/main/l10n/Bundle_de.properties new file mode 100644 index 00000000000..db180ff01ec --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle_de.properties @@ -0,0 +1,387 @@ +# Lingo in German. The key of every line is the English text the code +# names; see ui/Lang.java for how a line is found and how to add one. +@rtl=false +language.name=Deutsch + +Today=Heute +Accept=Annehmen +Could\ not\ reach\ the\ server.\ Check\ your\ connection.=Der Server ist nicht erreichbar. Pr\u00fcfe deine Verbindung. +Too\ many\ attempts.\ Wait\ a\ minute\ and\ try\ again.=Zu viele Versuche. Warte eine Minute und versuche es erneut. +That\ e-mail\ and\ password\ do\ not\ match\ an\ account.=Diese E-Mail und dieses Passwort passen zu keinem Konto. +Signing\ in\ failed.\ Try\ again.=Anmeldung fehlgeschlagen. Versuche es erneut. +Not\ now=Nicht jetzt +Settings=Einstellungen +Sign\ out=Abmelden +No\ connection=Keine Verbindung +The\ server\ at\ {0}\ did\ not\ answer.=Der Server unter {0} hat nicht geantwortet. +Try\ again=Erneut versuchen +Server\ address=Serveradresse +Create\ an\ account=Konto erstellen +Name=Name +Mobile\ number=Handynummer +Password=Passwort +At\ least\ 8\ characters=Mindestens 8 Zeichen +Create\ account=Konto erstellen +Server=Server +The\ address\ of\ the\ Lingo\ server\ this\ app\ talks\ to.\ Changing\ it\ signs\ you\ out.=Die Adresse des Lingo-Servers, mit dem diese App spricht. Eine \u00c4nderung meldet dich ab. +Address=Adresse +Save=Speichern +Account=Konto +Notifications=Benachrichtigungen +Appearance=Darstellung +Language=Sprache +Theme=Design +System=System +Light=Hell +Dark=Dunkel +About=Info +Terms\ of\ service=Nutzungsbedingungen +Privacy\ policy=Datenschutzerkl\u00e4rung +Sign\ in=Anmelden +Enter\ your\ e-mail\ and\ password.=Gib deine E-Mail und dein Passwort ein. + +# Driving applications, payments, the admin console and the account. +Back=Zur\u00fcck +Change\ password=Passwort \u00e4ndern +Change\ the\ password\ you\ sign\ in\ with=\u00c4ndere das Passwort f\u00fcr die Anmeldung +Current\ password=Aktuelles Passwort +Delete\ account=Konto l\u00f6schen +Delete\ my\ account=Mein Konto l\u00f6schen +Delete\ your\ account?=Dein Konto l\u00f6schen? +Keep\ my\ account=Mein Konto behalten +New\ password=Neues Passwort +New\ password,\ again=Neues Passwort, noch einmal +Profile=Profil +That\ picture\ could\ not\ be\ read=Das Bild konnte nicht gelesen werden +The\ two\ new\ passwords\ are\ not\ the\ same.=Die beiden neuen Passw\u00f6rter stimmen nicht \u00fcberein. +This\ device\ cannot\ prepare\ a\ picture\ to\ send=Dieses Ger\u00e4t kann kein Bild zum Senden vorbereiten +Your\ password\ was\ changed=Dein Passwort wurde ge\u00e4ndert +Usage\ statistics=Nutzungsstatistiken +Help\ improve\ Lingo=Hilf mit, Lingo zu verbessern +Lingo\ can\ count\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ so\ that\ we\ can\ see\ what\ works\ and\ fix\ what\ does\ not.=Lingo kann z\u00e4hlen, welche Bildschirme ge\u00f6ffnet und welche Funktionen genutzt werden, damit wir sehen, was funktioniert, und beheben k\u00f6nnen, was nicht funktioniert. +No\ personal\ details=Keine pers\u00f6nlichen Daten +Never\ your\ name,\ e-mail,\ phone\ number,\ places\ or\ card\ details=Niemals dein Name, deine E-Mail-Adresse, deine Telefonnummer, deine Orte oder deine Kartendaten +Turn\ it\ on\ or\ off\ at\ any\ time\ in\ Settings=Jederzeit in den Einstellungen ein- oder ausschalten +Share\ usage\ statistics=Nutzungsstatistiken teilen +The\ server\ changed.\ Sign\ in\ again.=Der Server hat sich ge\u00e4ndert. Melde dich erneut an. + +# Lingo: the field and dispatch screens. +Assistant=Assistent +Consent=Einwilligung +Lingo=Lingo +Kind=Art +Legal=Rechtliches +Location=Ort +Privacy=Datenschutz +Register=Registrieren +Software=Software +Starting=Wird gestartet +Unreachable=Nicht erreichbar +Welcome=Willkommen +Your\ name\ and\ mobile\ number=Dein Name und deine Handynummer +Close=Schlie\u00dfen +Menu=Men\u00fc +Send=Senden +Show\ the\ whole\ route=Ganze Route zeigen +# Back-office console, admin pages and the tablet day +All=Alle +Creator=Disponent +# Workforce rules, staffing reports and planning rules +This\ week=Diese Woche +Certificates=Zertifikate +# Company settings, labour rates, timesheets and the clock +# Company settings, labour rates, timesheets and the clock +# Sign-in and the report draft +E-mail=E-Mail + + +A\ class\ you\ booked\ is\ starting=Ein gebuchter Kurs beginnt gleich +A\ cloud\ model\ answers\ through\ Lingo's\ server.=Ein Cloud-Modell antwortet \u00fcber den Server von Lingo. +A\ nudge\ when\ today's\ goal\ is\ not\ done\ yet=Eine Erinnerung, wenn das heutige Ziel noch nicht erreicht ist +A\ sample\ learning\ app\ built\ with\ Codename\ One=Eine Beispiel-Lern-App, gebaut mit Codename One +A\ scripted\ partner\ keeps\ conversations\ going.\ Download\ the\ offline\ tutor\ or\ turn\ on\ the\ cloud\ tutor\ for\ free\ conversation.=Ein geskripteter Partner h\u00e4lt das Gespr\u00e4ch am Laufen. Lade den Offline-Tutor herunter oder aktiviere den Cloud-Tutor f\u00fcr freie Gespr\u00e4che. +A\ tip\ for\ {0}=Ein Tipp f\u00fcr {0} +AI\ tutor=KI-Tutor +Achievements=Erfolge +Add=Hinzuf\u00fcgen +Add\ a\ lesson=Lektion hinzuf\u00fcgen +Add\ a\ phrase=Satz hinzuf\u00fcgen +Add\ a\ video,\ phrases\ to\ practise\ or\ a\ conversation\ scene.=F\u00fcge ein Video, S\u00e4tze zum \u00dcben oder eine Gespr\u00e4chsszene hinzu. +An\ AI\ tutor\ that\ listens,\ on\ your\ phone.=Ein KI-Tutor, der zuh\u00f6rt, auf deinem Handy. +As\ it\ appears\ on\ your\ certificates=So erscheint es auf deinen Zertifikaten +Ask\ a\ question=Eine Frage stellen +Ask\ for\ prices\ and\ quantities=Frag nach Preisen und Mengen +Ask\ the\ creator\ and\ other\ learners=Frag den Ersteller und andere Lernende +At\ the\ fruit\ stall=Am Obststand +Back\ to\ the\ course=Zur\u00fcck zum Kurs +Badge\ unlocked=Abzeichen freigeschaltet +Badges\ and\ your\ level=Abzeichen und dein Level +Be\ the\ first\ to\ ask\ {0}.=Stell als Erste(r) {0} eine Frage. +Better\:\ {0}=Besser: {0} +Book=Buchen +Browse=St\u00f6bern +Browse\ courses=Kurse durchsuchen +Bundle=Paket +Buy\ for\ {0}=F\u00fcr {0} kaufen +Certificate=Zertifikat +Check=Pr\u00fcfen +Checking\ the\ signature...=Signatur wird gepr\u00fcft... +Checkout=Zur Kasse +Choose=Ausw\u00e4hlen +Cloud\ AI=Cloud-KI +Cloud\ AI\ tutor\ on\ any\ phone=Cloud-KI-Tutor auf jedem Handy +Cloud\ tutor=Cloud-Tutor +Colour=Farbe +Community=Community +Connect\ to\ Wi-Fi\ to\ download,\ or\ turn\ off\ Wi-Fi\ only.=Verbinde dich zum Herunterladen mit dem WLAN oder schalte \u201eNur WLAN\u201c aus. +Connecting\ to\ {0}...=Verbindung zu {0}... +Container=Container +Continue=Weiter +Continue\:\ {0}=Weiter: {0} +Conversation=Gespr\u00e4ch +Cookie=Cookie +Course=Kurs +Course\ complete\!=Kurs abgeschlossen! +Courses=Kurse +Courses\ and\ live\ classes\ from\ real\ teachers=Kurse und Live-Klassen von echten Lehrenden +Courses,\ classes\ and\ tips=Kurse, Klassen und Tipps +Create\ course=Kurs erstellen +Creator\ studio=Creator-Studio +Creators\ schedule\ live\ classes\ from\ their\ studio.=Creator planen Live-Klassen in ihrem Studio. +Daily\ goal\ met=Tagesziel erreicht +Day\ streak=Tage in Folge +Demo\ card\ ending\ 4242=Demo-Karte mit den Endziffern 4242 +Discover=Entdecken +Do\ a\ lesson\ today\ to\ start\ a\ streak.=Mach heute eine Lektion, um eine Serie zu starten. +Download=Herunterladen +Download\ 470\ MB?=470 MB herunterladen? +Download\ on\ Wi-Fi\ only=Nur \u00fcber WLAN herunterladen +Download\ the\ offline\ tutor=Offline-Tutor herunterladen +Downloaded\ AI,\ on\ this\ phone=KI heruntergeladen, auf diesem Handy +Downloading\ the\ offline\ tutor=Offline-Tutor wird heruntergeladen +Draft=Entwurf +Drafts=Entw\u00fcrfe +EEEE,\ MMM\ d=EEEE, d. MMM +Earn\ XP\ in\ lessons\ to\ climb.\ Keep\ your\ streak\ for\ bonus\ freezes.=Sammle in Lektionen XP, um aufzusteigen. Halte deine Serie f\u00fcr Bonus-Freezes. +End=Beenden +Enrol\ for\ free=Kostenlos einschreiben +Enrol\ in\ a\ course\ and\ it\ shows\ up\ here.=Schreib dich in einen Kurs ein, dann erscheint er hier. +Every\ AI\ course=Jeder KI-Kurs +Everything\ in\ Free=Alles aus Kostenlos +Excellent\!=Ausgezeichnet! +Finish\ conversation=Gespr\u00e4ch beenden +Finish\ every\ lesson\ of\ a\ course\ to\ earn\ a\ signed\ certificate.=Schlie\u00dfe alle Lektionen eines Kurses ab, um ein signiertes Zertifikat zu erhalten. +Finish\ lesson=Lektion beenden +Five\ minutes\ a\ day=F\u00fcnf Minuten am Tag +Free=Kostenlos +Frees\ 470\ MB.\ You\ can\ download\ it\ again.=Gibt 470 MB frei. Du kannst ihn erneut herunterladen. +Genuine,\ signed\ by\ {0}=Echt, signiert von {0} +Get\ the\ offline\ AI\ tutor=Offline-KI-Tutor holen +Give\ the\ class\ a\ title=Gib der Klasse einen Titel +Give\ the\ course\ a\ title=Gib dem Kurs einen Titel +Go\ Pro=Pro holen +Go\ Pro\ for\ {0}=Pro f\u00fcr {0} holen +Go\ live=Live gehen +Goal\ met\!=Ziel erreicht! +Good\ afternoon=Guten Tag +Good\ evening=Guten Abend +Good\ morning=Guten Morgen +Great\ job\!=Super gemacht! +HH\:mm=HH:mm +Heard\:\ "{0}"=Geh\u00f6rt: \u201e{0}\u201c +How\ much\ is\ it?=Wie viel kostet das? +I've\ watched\ it=Ich habe es mir angesehen +In\ one\ line=In einer Zeile +Join=Beitreten +Keep\ talking=Sprich weiter +Leaderboard=Bestenliste +Learn=Lernen +Learning=Lernen +Led\ by\ the\ AI\ tutor=Geleitet vom KI-Tutor +Length=L\u00e4nge +Lesson\ complete\!=Lektion abgeschlossen! +Lesson\ {0}\ of\ {1}=Lektion {0} von {1} +Lessons=Lektionen +Let's\ try\ that\ again=Versuchen wir es noch einmal +Level=Level +Level\ {0}=Level {0} +Lifetime\ access,\ by\ {0}=Lebenslanger Zugriff, von {0} +Lingo\ Pro=Lingo Pro +Lingo\ is\ a\ sample.\ Payments\ are\ simulated\ and\ certificates\ are\ signed\ with\ a\ demonstration\ key.=Lingo ist ein Beispiel. Zahlungen werden simuliert und Zertifikate mit einem Demo-Schl\u00fcssel signiert. +Lingo\ is\ free.\ Pro\ pays\ for\ the\ creators\ and\ the\ servers,\ and\ gives\ you\ more.=Lingo ist kostenlos. Pro bezahlt die Creator und die Server und bietet dir mehr. +Lingo\ needs\ the\ camera\ and\ microphone\ for\ live\ classes=Lingo braucht Kamera und Mikrofon f\u00fcr Live-Klassen +Listen=Zuh\u00f6ren +Listening\ failed.\ Check\ the\ microphone\ permission.=Zuh\u00f6ren fehlgeschlagen. Pr\u00fcfe die Mikrofonberechtigung. +Listening...=H\u00f6rt zu... +Live=Live +Live\ classes=Live-Klassen +Live\ soon=Bald live +Live\ video\ needs\ the\ phone\ app.\ The\ class\ is\ on\:\ open\ Lingo\ on\ iOS\ or\ Android\ to\ take\ part.=Live-Video braucht die Handy-App. Die Klasse l\u00e4uft: \u00d6ffne Lingo auf iOS oder Android, um teilzunehmen. +Live\ with\ {0}=Live mit {0} +MMM\ d,\ HH\:mm=d. MMM, HH:mm +MMM\ d,\ yyyy=d. MMM yyyy +Make\ a\ course\ of\ videos,\ phrases\ and\ conversations.=Erstelle einen Kurs aus Videos, S\u00e4tzen und Gespr\u00e4chen. +Me=Ich +Monday,\ Nov\ 16=Montag, 16. Nov. +Monthly,\ cancel\ any\ time=Monatlich, jederzeit k\u00fcndbar +My\ Lingo\ certificate=Mein Lingo-Zertifikat +My\ courses=Meine Kurse +Nearly\ there=Fast geschafft +New=Neu +New\ course=Neuer Kurs +New\ lesson=Neue Lektion +No\ certificates\ yet=Noch keine Zertifikate +No\ lessons\ yet=Noch keine Lektionen +No\ live\ classes\ are\ scheduled\ yet.=Noch keine Live-Klassen geplant. +No\ questions\ yet=Noch keine Fragen +No\ video\ yet=Noch kein Video +Nothing\ bought\ yet=Noch nichts gekauft +Nothing\ here\ yet=Hier ist noch nichts +Nothing\ scheduled=Nichts geplant +Nothing\ was\ heard.\ Tap\ the\ microphone\ and\ speak.=Es wurde nichts geh\u00f6rt. Tippe auf das Mikrofon und sprich. +On-device\ AI=KI auf dem Ger\u00e4t +On-device\ AI\ tutor=KI-Tutor auf dem Ger\u00e4t +One\ streak\ freeze=Ein Streak-Freeze +Order,\ haggle\ and\ chat\ with\ stallholders=Bestelle, feilsche und plaudere mit Standbetreibern +Paid\ courses,\ live\ classes\ and\ tips\ show\ up\ here.=Bezahlte Kurse, Live-Klassen und Trinkgelder erscheinen hier. +Pay\ {0}={0} bezahlen +Payment\ complete=Zahlung abgeschlossen +Phrases=S\u00e4tze +Phrases\ to\ say\ aloud=S\u00e4tze zum Laut-Sprechen +Pick\ up\ Riley=Triff Riley wieder +Pick\ your\ first\ course=W\u00e4hl deinen ersten Kurs +Practice\ now=Jetzt \u00fcben +Practice\ partner=\u00dcbungspartner +Practice\ reminder=\u00dcbungserinnerung +Practise\ again=Nochmal \u00fcben +Practise\ speaking\ with\ an\ AI\ tutor,\ keep\ a\ streak\ and\ earn\ signed\ certificates.=\u00dcbe das Sprechen mit einem KI-Tutor, halte eine Serie und sammle signierte Zertifikate. +Practise\ with\ the\ AI\ tutor,\ or\ learn\ from\ people\ who\ teach.=\u00dcbe mit dem KI-Tutor oder lerne von Menschen, die unterrichten. +Practise\ without\ limits=\u00dcben ohne Limit +Practised=Ge\u00fcbt +Price=Preis +Pro=Pro +Progress=Fortschritt +Pronunciation=Aussprache +Pronunciation\ scored\ word\ by\ word,\ on\ your\ phone=Aussprache Wort f\u00fcr Wort bewertet, auf deinem Handy +Publish=Ver\u00f6ffentlichen +Published=Ver\u00f6ffentlicht +Purchases=K\u00e4ufe +Push\ registration\ failed\:\ =Push-Registrierung fehlgeschlagen: +Qa=F&A +Questions=Fragen +Questions\ and\ answers=Fragen und Antworten +Qwen2.5\ 0.5B,\ 470\ MB.\ Runs\ privately\ on\ this\ phone.=Qwen2.5 0.5B, 470 MB. L\u00e4uft privat auf diesem Handy. +Ready\ for\ today's\ practice?=Bereit f\u00fcr die heutige \u00dcbung? +Record=Aufnehmen +Reminders,\ theme,\ privacy=Erinnerungen, Design, Datenschutz +Remove\ the\ offline\ tutor=Offline-Tutor entfernen +Reply=Antworten +Reply\ in\ {0}=Auf {0} antworten +Replying\ to\ {0}=Antwort an {0} +Reward=Belohnung +Rolling\ your\ R,\ live=Das R rollen, live +Runs\ on\ this\ phone.\ Free,\ private,\ 470\ MB.=L\u00e4uft auf diesem Handy. Kostenlos, privat, 470 MB. +Save\ lesson=Lektion speichern +Say\ thanks\ with\ $2.\ All\ of\ it\ goes\ to\ them.=Sag Danke mit 2 $. Alles geht an sie. +Schedule=Planen +Schedule\ a\ class=Klasse planen +Scheduled.\ Learners\ can\ book\ seats\ now.=Geplant. Lernende k\u00f6nnen jetzt Pl\u00e4tze buchen. +Score=Punktzahl +Seat\ price=Preis pro Platz +Seats=Pl\u00e4tze +See\ all=Alle ansehen +See\ who\ is\ practising\ most=Sieh, wer am meisten \u00fcbt +Set-Cookie=Set-Cookie +Share\ certificate=Zertifikat teilen +Share\ which\ screens\ and\ features\ are\ used.\ Never\ your\ name,\ voice\ or\ what\ you\ say.=Teile, welche Bildschirme und Funktionen genutzt werden. Nie deinen Namen, deine Stimme oder was du sagst. +Signed\ certificates=Signierte Zertifikate +Signed\ certificates\ anyone\ can\ verify=Signierte Zertifikate, die jeder pr\u00fcfen kann +Signed\ proof\ of\ every\ course\ you\ finish=Signierter Nachweis f\u00fcr jeden abgeschlossenen Kurs +Slowly=Langsam +Small\ groups\ with\ a\ real\ teacher,\ on\ video.=Kleine Gruppen mit echten Lehrenden, per Video. +Spanish\ for\ the\ market=Spanisch f\u00fcr den Markt +Speak\ a\ new\ language\ with\ an\ AI\ tutor\ that\ listens.=Sprich eine neue Sprache mit einem KI-Tutor, der zuh\u00f6rt. +Speech\ recognition\ and\ the\ AI\ tutor\ run\ on\ this\ phone.\ What\ you\ say\ leaves\ it\ only\ if\ you\ turn\ on\ the\ cloud\ tutor.\ Your\ progress\ and\ settings\ are\ kept\ with\ your\ account\ on\ the\ server\ you\ signed\ in\ to.=Spracherkennung und KI-Tutor laufen auf diesem Handy. Was du sagst, verl\u00e4sst es nur, wenn du den Cloud-Tutor aktivierst. Dein Fortschritt und deine Einstellungen werden mit deinem Konto auf dem Server gespeichert, bei dem du angemeldet bist. +Speech\ recognition\ and\ the\ voice\ always\ run\ on\ the\ phone.=Spracherkennung und Stimme laufen immer auf dem Handy. +Start\ course=Kurs starten +Start\ learning=Mit dem Lernen starten +Starts=Beginn +Still\ looking=Suche noch +Studio=Studio +Support\ the\ creators\ you\ learn\ from=Unterst\u00fctze die Creator, von denen du lernst +Talk=Sprechen +Tap\ and\ speak=Tippen und sprechen +Teach\ a\ small\ group\ on\ video.\ Learners\ book\ seats,\ free\ or\ paid.=Unterrichte eine kleine Gruppe per Video. Lernende buchen Pl\u00e4tze, kostenlos oder bezahlt. +Teach\ what\ you\ know=Lehre, was du kannst +Thank\ you\ for\ supporting\ {0}=Danke f\u00fcr deine Unterst\u00fctzung f\u00fcr {0} +The\ certificate\ could\ not\ be\ saved=Das Zertifikat konnte nicht gespeichert werden +The\ class\ has\ ended=Die Klasse ist beendet +The\ download\ failed.\ Try\ again\ later.=Der Download ist fehlgeschlagen. Versuche es sp\u00e4ter erneut. +The\ model\ you\ downloaded\ answers,\ on\ this\ phone.\ Works\ offline.=Das heruntergeladene Modell antwortet auf diesem Handy. Funktioniert offline. +The\ offline\ tutor\ is\ ready=Der Offline-Tutor ist bereit +The\ on-device\ language\ model\ is\ large;\ wait\ for\ Wi-Fi\ to\ fetch\ it=Das Sprachmodell auf dem Ger\u00e4t ist gro\u00df; warte auf WLAN, um es zu laden +The\ scene\ the\ AI\ tutor\ plays=Die Szene, die der KI-Tutor spielt +The\ signature\ does\ not\ match=Die Signatur stimmt nicht \u00fcberein +The\ tutor\ could\ not\ answer\:\ =Der Tutor konnte nicht antworten: +The\ tutor\ had\ nothing\ to\ say.\ Try\ again.=Der Tutor hatte nichts zu sagen. Versuche es erneut. +The\ tutor\ model\ is\ downloaded\ once\ and\ stays\ on\ this\ phone.=Das Tutor-Modell wird einmal heruntergeladen und bleibt auf diesem Handy. +The\ tutor\ stays\ in\ the\ scene,\ speaks\ the\ course's\ language\ at\ its\ level,\ and\ corrects\ mistakes.=Der Tutor bleibt in der Szene, spricht die Sprache des Kurses auf dem passenden Niveau und korrigiert Fehler. +The\ video\ connection\ failed=Die Videoverbindung ist fehlgeschlagen +The\ video\ could\ not\ be\ read=Das Video konnte nicht gelesen werden +The\ video\ is\ over\ 8\ MB.\ Record\ a\ shorter\ one.=Das Video ist gr\u00f6\u00dfer als 8 MB. Nimm ein k\u00fcrzeres auf. +This\ certificate\ could\ not\ be\ shown=Dieses Zertifikat konnte nicht angezeigt werden +This\ lesson\ has\ no\ phrases\ yet.=Diese Lektion hat noch keine S\u00e4tze. +Three\ streak\ freezes\ a\ week=Drei Streak-Freezes pro Woche +Tip\ {0}=Trinkgeld {0} +Title=Titel +Toolbar=Symbolleiste +Total=Gesamt +Total\ XP=XP gesamt +Tutor=Tutor +Type\ what\ you\ would\ say=Schreib, was du sagen w\u00fcrdest +Typing...=Tippt... +Unlimited\ conversations\ and\ streak\ freezes=Unbegrenzte Gespr\u00e4che und Streak-Freezes +Up\ to\ 90\ seconds\ and\ 8\ MB.\ Learners\ can\ replay\ and\ seek.=Bis zu 90 Sekunden und 8 MB. Lernende k\u00f6nnen wiederholen und vorspulen. +Uploading...=Wird hochgeladen... +Use\ the\ cloud\ tutor=Cloud-Tutor verwenden +Used\ only\ to\ reach\ you\ about\ a\ live\ class\ you\ booked.=Wird nur genutzt, um dich zu einer gebuchten Live-Klasse zu erreichen. +Video=Video +Video\ uploaded=Video hochgeladen +View\ your\ certificate=Dein Zertifikat ansehen +Waiting\ for\ {0}'s\ video...=Warte auf das Video von {0}... +Wallet=Wallet +What\ learners\ will\ be\ able\ to\ do=Was Lernende danach k\u00f6nnen +When\ this\ phone\ cannot\ run\ the\ tutor,\ ask\ the\ server's\ AI\ instead=Wenn dieses Handy den Tutor nicht ausf\u00fchren kann, die KI des Servers fragen +When\ this\ phone\ has\ no\ model.\ What\ you\ say\ is\ sent\ to\ Lingo's\ AI\ provider.=Wenn dieses Handy kein Modell hat. Was du sagst, wird an den KI-Anbieter von Lingo gesendet. +With\ usage\ statistics\ turned\ on,\ the\ app\ also\ counts\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ and\ reports\ that\ to\ Codename\ One's\ analytics\ service\ under\ a\ made-up\ id\ for\ this\ device.\ Your\ name,\ e-mail,\ phone\ number,\ voice\ and\ conversations\ are\ never\ part\ of\ it,\ and\ turning\ it\ off\ in\ Settings\ stops\ it.=Bei aktivierten Nutzungsstatistiken z\u00e4hlt die App auch, welche Bildschirme ge\u00f6ffnet und welche Funktionen genutzt werden, und meldet das unter einer ausgedachten ID f\u00fcr dieses Ger\u00e4t an den Analysedienst von Codename One. Dein Name, deine E-Mail, Telefonnummer, Stimme und Gespr\u00e4che sind nie Teil davon, und das Ausschalten in den Einstellungen stoppt es. +Work\ on\:\ {0}=Arbeite an: {0} +Write\ an\ answer=Schreib eine Antwort +XP\ today=XP heute +You\ are\ a\ stallholder\ at\ a\ busy\ market...=Du bist Standbetreiber auf einem belebten Markt... +You\ can\ keep\ practising.\ It\ is\ ready\ in\ a\ few\ minutes.=Du kannst weiter\u00fcben. In ein paar Minuten ist er bereit. +You\ have\ a\ seat=Du hast einen Platz +You\ host\ this=Du leitest das +You\ keep\ 70%\ of\ every\ sale.=Du beh\u00e4ltst 70 % jedes Verkaufs. +You're\ a\ Pro\ member.\ Thank\ you\!=Du bist Pro-Mitglied. Danke! +You're\ enrolled.\ Let's\ start\!=Du bist eingeschrieben. Los geht's! +You're\ live.\ Learners\ appear\ here\ as\ they\ join.=Du bist live. Lernende erscheinen hier, sobald sie beitreten. +Your\ course\ is\ live=Dein Kurs ist live +Your\ courses=Deine Kurse +Your\ courses,\ classes\ and\ earnings=Deine Kurse, Klassen und Einnahmen +Your\ name\ and\ language=Dein Name und deine Sprache +Your\ phone's\ built-in\ AI\ answers.\ Nothing\ you\ say\ leaves\ the\ device.=Die integrierte KI deines Handys antwortet. Nichts, was du sagst, verl\u00e4sst das Ger\u00e4t. +Your\ seat\ is\ booked.\ We'll\ remind\ you.=Dein Platz ist gebucht. Wir erinnern dich. +Your\ sign-in,\ profile,\ progress\ and\ settings\ are\ removed\ for\ good.\ Certificates\ already\ issued\ can\ still\ be\ verified.=Deine Anmeldung, dein Profil, dein Fortschritt und deine Einstellungen werden endg\u00fcltig gel\u00f6scht. Bereits ausgestellte Zertifikate k\u00f6nnen weiterhin gepr\u00fcft werden. +Yours=Deins +Wait\ for\ Wi-Fi=Auf WLAN warten +Accounts=Konten +Admin=Administrator +Cannot\ sign\ in=Kann sich nicht anmelden +Grants\ roles\ to\ other\ accounts=Vergibt Rollen an andere Konten +Learner=Lernende +Publishes\ courses\ and\ holds\ live\ classes=Ver\u00f6ffentlicht Kurse und gibt Live-Kurse +Roles=Rollen +Suspended=Gesperrt +Takes\ courses\ and\ practises\ with\ the\ tutor=Belegt Kurse und \u00fcbt mit dem Tutor +Who\ can\ sign\ in,\ and\ who\ teaches=Wer sich anmelden darf und wer unterrichtet +1\ day=1 Tag diff --git a/scripts/lingo/common/src/main/l10n/Bundle_en.properties b/scripts/lingo/common/src/main/l10n/Bundle_en.properties new file mode 100644 index 00000000000..e45d7fc9f3c --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle_en.properties @@ -0,0 +1,387 @@ +# Lingo in English. The key of every line is the English text the code +# names; see ui/Lang.java for how a line is found and how to add one. +@rtl=false +language.name=English + +Today=Today +Accept=Accept +Could\ not\ reach\ the\ server.\ Check\ your\ connection.=Could not reach the server. Check your connection. +Too\ many\ attempts.\ Wait\ a\ minute\ and\ try\ again.=Too many attempts. Wait a minute and try again. +That\ e-mail\ and\ password\ do\ not\ match\ an\ account.=That e-mail and password do not match an account. +Signing\ in\ failed.\ Try\ again.=Signing in failed. Try again. +Not\ now=Not now +Settings=Settings +Sign\ out=Sign out +No\ connection=No connection +The\ server\ at\ {0}\ did\ not\ answer.=The server at {0} did not answer. +Try\ again=Try again +Server\ address=Server address +Create\ an\ account=Create an account +Name=Name +Mobile\ number=Mobile number +Password=Password +At\ least\ 8\ characters=At least 8 characters +Create\ account=Create account +Server=Server +The\ address\ of\ the\ Lingo\ server\ this\ app\ talks\ to.\ Changing\ it\ signs\ you\ out.=The address of the Lingo server this app talks to. Changing it signs you out. +Address=Address +Save=Save +Account=Account +Notifications=Notifications +Appearance=Appearance +Language=Language +Theme=Theme +System=System +Light=Light +Dark=Dark +About=About +Terms\ of\ service=Terms of service +Privacy\ policy=Privacy policy +Sign\ in=Sign in +Enter\ your\ e-mail\ and\ password.=Enter your e-mail and password. + +# Driving applications, payments, the admin console and the account. +Back=Back +Change\ password=Change password +Change\ the\ password\ you\ sign\ in\ with=Change the password you sign in with +Current\ password=Current password +Delete\ account=Delete account +Delete\ my\ account=Delete my account +Delete\ your\ account?=Delete your account? +Keep\ my\ account=Keep my account +New\ password=New password +New\ password,\ again=New password, again +Profile=Profile +That\ picture\ could\ not\ be\ read=That picture could not be read +The\ two\ new\ passwords\ are\ not\ the\ same.=The two new passwords are not the same. +This\ device\ cannot\ prepare\ a\ picture\ to\ send=This device cannot prepare a picture to send +Your\ password\ was\ changed=Your password was changed +Usage\ statistics=Usage statistics +Help\ improve\ Lingo=Help improve Lingo +Lingo\ can\ count\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ so\ that\ we\ can\ see\ what\ works\ and\ fix\ what\ does\ not.=Lingo can count which screens are opened and which features are used, so that we can see what works and fix what does not. +No\ personal\ details=No personal details +Never\ your\ name,\ e-mail,\ phone\ number,\ places\ or\ card\ details=Never your name, e-mail, phone number, places or card details +Turn\ it\ on\ or\ off\ at\ any\ time\ in\ Settings=Turn it on or off at any time in Settings +Share\ usage\ statistics=Share usage statistics +The\ server\ changed.\ Sign\ in\ again.=The server changed. Sign in again. + +# Lingo: the field and dispatch screens. +Assistant=Assistant +Consent=Consent +Lingo=Lingo +Kind=Kind +Legal=Legal +Location=Location +Privacy=Privacy +Register=Register +Software=Software +Starting=Starting +Unreachable=Unreachable +Welcome=Welcome +Your\ name\ and\ mobile\ number=Your name and mobile number +Close=Close +Menu=Menu +Send=Send +Show\ the\ whole\ route=Show the whole route +# Back-office console, admin pages and the tablet day +All=All +Creator=Creator +# Workforce rules, staffing reports and planning rules +This\ week=This week +Certificates=Certificates +# Company settings, labour rates, timesheets and the clock +# Company settings, labour rates, timesheets and the clock +# Sign-in and the report draft +E-mail=E-mail + + +A\ class\ you\ booked\ is\ starting=A class you booked is starting +A\ cloud\ model\ answers\ through\ Lingo's\ server.=A cloud model answers through Lingo's server. +A\ nudge\ when\ today's\ goal\ is\ not\ done\ yet=A nudge when today's goal is not done yet +A\ sample\ learning\ app\ built\ with\ Codename\ One=A sample learning app built with Codename One +A\ scripted\ partner\ keeps\ conversations\ going.\ Download\ the\ offline\ tutor\ or\ turn\ on\ the\ cloud\ tutor\ for\ free\ conversation.=A scripted partner keeps conversations going. Download the offline tutor or turn on the cloud tutor for free conversation. +A\ tip\ for\ {0}=A tip for {0} +AI\ tutor=AI tutor +Achievements=Achievements +Add=Add +Add\ a\ lesson=Add a lesson +Add\ a\ phrase=Add a phrase +Add\ a\ video,\ phrases\ to\ practise\ or\ a\ conversation\ scene.=Add a video, phrases to practise or a conversation scene. +An\ AI\ tutor\ that\ listens,\ on\ your\ phone.=An AI tutor that listens, on your phone. +As\ it\ appears\ on\ your\ certificates=As it appears on your certificates +Ask\ a\ question=Ask a question +Ask\ for\ prices\ and\ quantities=Ask for prices and quantities +Ask\ the\ creator\ and\ other\ learners=Ask the creator and other learners +At\ the\ fruit\ stall=At the fruit stall +Back\ to\ the\ course=Back to the course +Badge\ unlocked=Badge unlocked +Badges\ and\ your\ level=Badges and your level +Be\ the\ first\ to\ ask\ {0}.=Be the first to ask {0}. +Better\:\ {0}=Better: {0} +Book=Book +Browse=Browse +Browse\ courses=Browse courses +Bundle=Bundle +Buy\ for\ {0}=Buy for {0} +Certificate=Certificate +Check=Check +Checking\ the\ signature...=Checking the signature... +Checkout=Checkout +Choose=Choose +Cloud\ AI=Cloud AI +Cloud\ AI\ tutor\ on\ any\ phone=Cloud AI tutor on any phone +Cloud\ tutor=Cloud tutor +Colour=Colour +Community=Community +Connect\ to\ Wi-Fi\ to\ download,\ or\ turn\ off\ Wi-Fi\ only.=Connect to Wi-Fi to download, or turn off Wi-Fi only. +Connecting\ to\ {0}...=Connecting to {0}... +Container=Container +Continue=Continue +Continue\:\ {0}=Continue: {0} +Conversation=Conversation +Cookie=Cookie +Course=Course +Course\ complete\!=Course complete! +Courses=Courses +Courses\ and\ live\ classes\ from\ real\ teachers=Courses and live classes from real teachers +Courses,\ classes\ and\ tips=Courses, classes and tips +Create\ course=Create course +Creator\ studio=Creator studio +Creators\ schedule\ live\ classes\ from\ their\ studio.=Creators schedule live classes from their studio. +Daily\ goal\ met=Daily goal met +Day\ streak=Day streak +Demo\ card\ ending\ 4242=Demo card ending 4242 +Discover=Discover +Do\ a\ lesson\ today\ to\ start\ a\ streak.=Do a lesson today to start a streak. +Download=Download +Download\ 470\ MB?=Download 470 MB? +Download\ on\ Wi-Fi\ only=Download on Wi-Fi only +Download\ the\ offline\ tutor=Download the offline tutor +Downloaded\ AI,\ on\ this\ phone=Downloaded AI, on this phone +Downloading\ the\ offline\ tutor=Downloading the offline tutor +Draft=Draft +Drafts=Drafts +EEEE,\ MMM\ d=EEEE, MMM d +Earn\ XP\ in\ lessons\ to\ climb.\ Keep\ your\ streak\ for\ bonus\ freezes.=Earn XP in lessons to climb. Keep your streak for bonus freezes. +End=End +Enrol\ for\ free=Enrol for free +Enrol\ in\ a\ course\ and\ it\ shows\ up\ here.=Enrol in a course and it shows up here. +Every\ AI\ course=Every AI course +Everything\ in\ Free=Everything in Free +Excellent\!=Excellent! +Finish\ conversation=Finish conversation +Finish\ every\ lesson\ of\ a\ course\ to\ earn\ a\ signed\ certificate.=Finish every lesson of a course to earn a signed certificate. +Finish\ lesson=Finish lesson +Five\ minutes\ a\ day=Five minutes a day +Free=Free +Frees\ 470\ MB.\ You\ can\ download\ it\ again.=Frees 470 MB. You can download it again. +Genuine,\ signed\ by\ {0}=Genuine, signed by {0} +Get\ the\ offline\ AI\ tutor=Get the offline AI tutor +Give\ the\ class\ a\ title=Give the class a title +Give\ the\ course\ a\ title=Give the course a title +Go\ Pro=Go Pro +Go\ Pro\ for\ {0}=Go Pro for {0} +Go\ live=Go live +Goal\ met\!=Goal met! +Good\ afternoon=Good afternoon +Good\ evening=Good evening +Good\ morning=Good morning +Great\ job\!=Great job! +HH\:mm=HH:mm +Heard\:\ "{0}"=Heard: "{0}" +How\ much\ is\ it?=How much is it? +I've\ watched\ it=I've watched it +In\ one\ line=In one line +Join=Join +Keep\ talking=Keep talking +Leaderboard=Leaderboard +Learn=Learn +Learning=Learning +Led\ by\ the\ AI\ tutor=Led by the AI tutor +Length=Length +Lesson\ complete\!=Lesson complete! +Lesson\ {0}\ of\ {1}=Lesson {0} of {1} +Lessons=Lessons +Let's\ try\ that\ again=Let's try that again +Level=Level +Level\ {0}=Level {0} +Lifetime\ access,\ by\ {0}=Lifetime access, by {0} +Lingo\ Pro=Lingo Pro +Lingo\ is\ a\ sample.\ Payments\ are\ simulated\ and\ certificates\ are\ signed\ with\ a\ demonstration\ key.=Lingo is a sample. Payments are simulated and certificates are signed with a demonstration key. +Lingo\ is\ free.\ Pro\ pays\ for\ the\ creators\ and\ the\ servers,\ and\ gives\ you\ more.=Lingo is free. Pro pays for the creators and the servers, and gives you more. +Lingo\ needs\ the\ camera\ and\ microphone\ for\ live\ classes=Lingo needs the camera and microphone for live classes +Listen=Listen +Listening\ failed.\ Check\ the\ microphone\ permission.=Listening failed. Check the microphone permission. +Listening...=Listening... +Live=Live +Live\ classes=Live classes +Live\ soon=Live soon +Live\ video\ needs\ the\ phone\ app.\ The\ class\ is\ on\:\ open\ Lingo\ on\ iOS\ or\ Android\ to\ take\ part.=Live video needs the phone app. The class is on: open Lingo on iOS or Android to take part. +Live\ with\ {0}=Live with {0} +MMM\ d,\ HH\:mm=MMM d, HH:mm +MMM\ d,\ yyyy=MMM d, yyyy +Make\ a\ course\ of\ videos,\ phrases\ and\ conversations.=Make a course of videos, phrases and conversations. +Me=Me +Monday,\ Nov\ 16=Monday, Nov 16 +Monthly,\ cancel\ any\ time=Monthly, cancel any time +My\ Lingo\ certificate=My Lingo certificate +My\ courses=My courses +Nearly\ there=Nearly there +New=New +New\ course=New course +New\ lesson=New lesson +No\ certificates\ yet=No certificates yet +No\ lessons\ yet=No lessons yet +No\ live\ classes\ are\ scheduled\ yet.=No live classes are scheduled yet. +No\ questions\ yet=No questions yet +No\ video\ yet=No video yet +Nothing\ bought\ yet=Nothing bought yet +Nothing\ here\ yet=Nothing here yet +Nothing\ scheduled=Nothing scheduled +Nothing\ was\ heard.\ Tap\ the\ microphone\ and\ speak.=Nothing was heard. Tap the microphone and speak. +On-device\ AI=On-device AI +On-device\ AI\ tutor=On-device AI tutor +One\ streak\ freeze=One streak freeze +Order,\ haggle\ and\ chat\ with\ stallholders=Order, haggle and chat with stallholders +Paid\ courses,\ live\ classes\ and\ tips\ show\ up\ here.=Paid courses, live classes and tips show up here. +Pay\ {0}=Pay {0} +Payment\ complete=Payment complete +Phrases=Phrases +Phrases\ to\ say\ aloud=Phrases to say aloud +Pick\ up\ Riley=Pick up Riley +Pick\ your\ first\ course=Pick your first course +Practice\ now=Practice now +Practice\ partner=Practice partner +Practice\ reminder=Practice reminder +Practise\ again=Practise again +Practise\ speaking\ with\ an\ AI\ tutor,\ keep\ a\ streak\ and\ earn\ signed\ certificates.=Practise speaking with an AI tutor, keep a streak and earn signed certificates. +Practise\ with\ the\ AI\ tutor,\ or\ learn\ from\ people\ who\ teach.=Practise with the AI tutor, or learn from people who teach. +Practise\ without\ limits=Practise without limits +Practised=Practised +Price=Price +Pro=Pro +Progress=Progress +Pronunciation=Pronunciation +Pronunciation\ scored\ word\ by\ word,\ on\ your\ phone=Pronunciation scored word by word, on your phone +Publish=Publish +Published=Published +Purchases=Purchases +Push\ registration\ failed\:\ =Push registration failed: +Qa=Qa +Questions=Questions +Questions\ and\ answers=Questions and answers +Qwen2.5\ 0.5B,\ 470\ MB.\ Runs\ privately\ on\ this\ phone.=Qwen2.5 0.5B, 470 MB. Runs privately on this phone. +Ready\ for\ today's\ practice?=Ready for today's practice? +Record=Record +Reminders,\ theme,\ privacy=Reminders, theme, privacy +Remove\ the\ offline\ tutor=Remove the offline tutor +Reply=Reply +Reply\ in\ {0}=Reply in {0} +Replying\ to\ {0}=Replying to {0} +Reward=Reward +Rolling\ your\ R,\ live=Rolling your R, live +Runs\ on\ this\ phone.\ Free,\ private,\ 470\ MB.=Runs on this phone. Free, private, 470 MB. +Save\ lesson=Save lesson +Say\ thanks\ with\ $2.\ All\ of\ it\ goes\ to\ them.=Say thanks with $2. All of it goes to them. +Schedule=Schedule +Schedule\ a\ class=Schedule a class +Scheduled.\ Learners\ can\ book\ seats\ now.=Scheduled. Learners can book seats now. +Score=Score +Seat\ price=Seat price +Seats=Seats +See\ all=See all +See\ who\ is\ practising\ most=See who is practising most +Set-Cookie=Set-Cookie +Share\ certificate=Share certificate +Share\ which\ screens\ and\ features\ are\ used.\ Never\ your\ name,\ voice\ or\ what\ you\ say.=Share which screens and features are used. Never your name, voice or what you say. +Signed\ certificates=Signed certificates +Signed\ certificates\ anyone\ can\ verify=Signed certificates anyone can verify +Signed\ proof\ of\ every\ course\ you\ finish=Signed proof of every course you finish +Slowly=Slowly +Small\ groups\ with\ a\ real\ teacher,\ on\ video.=Small groups with a real teacher, on video. +Spanish\ for\ the\ market=Spanish for the market +Speak\ a\ new\ language\ with\ an\ AI\ tutor\ that\ listens.=Speak a new language with an AI tutor that listens. +Speech\ recognition\ and\ the\ AI\ tutor\ run\ on\ this\ phone.\ What\ you\ say\ leaves\ it\ only\ if\ you\ turn\ on\ the\ cloud\ tutor.\ Your\ progress\ and\ settings\ are\ kept\ with\ your\ account\ on\ the\ server\ you\ signed\ in\ to.=Speech recognition and the AI tutor run on this phone. What you say leaves it only if you turn on the cloud tutor. Your progress and settings are kept with your account on the server you signed in to. +Speech\ recognition\ and\ the\ voice\ always\ run\ on\ the\ phone.=Speech recognition and the voice always run on the phone. +Start\ course=Start course +Start\ learning=Start learning +Starts=Starts +Still\ looking=Still looking +Studio=Studio +Support\ the\ creators\ you\ learn\ from=Support the creators you learn from +Talk=Talk +Tap\ and\ speak=Tap and speak +Teach\ a\ small\ group\ on\ video.\ Learners\ book\ seats,\ free\ or\ paid.=Teach a small group on video. Learners book seats, free or paid. +Teach\ what\ you\ know=Teach what you know +Thank\ you\ for\ supporting\ {0}=Thank you for supporting {0} +The\ certificate\ could\ not\ be\ saved=The certificate could not be saved +The\ class\ has\ ended=The class has ended +The\ download\ failed.\ Try\ again\ later.=The download failed. Try again later. +The\ model\ you\ downloaded\ answers,\ on\ this\ phone.\ Works\ offline.=The model you downloaded answers, on this phone. Works offline. +The\ offline\ tutor\ is\ ready=The offline tutor is ready +The\ on-device\ language\ model\ is\ large;\ wait\ for\ Wi-Fi\ to\ fetch\ it=The on-device language model is large; wait for Wi-Fi to fetch it +The\ scene\ the\ AI\ tutor\ plays=The scene the AI tutor plays +The\ signature\ does\ not\ match=The signature does not match +The\ tutor\ could\ not\ answer\:\ =The tutor could not answer: +The\ tutor\ had\ nothing\ to\ say.\ Try\ again.=The tutor had nothing to say. Try again. +The\ tutor\ model\ is\ downloaded\ once\ and\ stays\ on\ this\ phone.=The tutor model is downloaded once and stays on this phone. +The\ tutor\ stays\ in\ the\ scene,\ speaks\ the\ course's\ language\ at\ its\ level,\ and\ corrects\ mistakes.=The tutor stays in the scene, speaks the course's language at its level, and corrects mistakes. +The\ video\ connection\ failed=The video connection failed +The\ video\ could\ not\ be\ read=The video could not be read +The\ video\ is\ over\ 8\ MB.\ Record\ a\ shorter\ one.=The video is over 8 MB. Record a shorter one. +This\ certificate\ could\ not\ be\ shown=This certificate could not be shown +This\ lesson\ has\ no\ phrases\ yet.=This lesson has no phrases yet. +Three\ streak\ freezes\ a\ week=Three streak freezes a week +Tip\ {0}=Tip {0} +Title=Title +Toolbar=Toolbar +Total=Total +Total\ XP=Total XP +Tutor=Tutor +Type\ what\ you\ would\ say=Type what you would say +Typing...=Typing... +Unlimited\ conversations\ and\ streak\ freezes=Unlimited conversations and streak freezes +Up\ to\ 90\ seconds\ and\ 8\ MB.\ Learners\ can\ replay\ and\ seek.=Up to 90 seconds and 8 MB. Learners can replay and seek. +Uploading...=Uploading... +Use\ the\ cloud\ tutor=Use the cloud tutor +Used\ only\ to\ reach\ you\ about\ a\ live\ class\ you\ booked.=Used only to reach you about a live class you booked. +Video=Video +Video\ uploaded=Video uploaded +View\ your\ certificate=View your certificate +Waiting\ for\ {0}'s\ video...=Waiting for {0}'s video... +Wallet=Wallet +What\ learners\ will\ be\ able\ to\ do=What learners will be able to do +When\ this\ phone\ cannot\ run\ the\ tutor,\ ask\ the\ server's\ AI\ instead=When this phone cannot run the tutor, ask the server's AI instead +When\ this\ phone\ has\ no\ model.\ What\ you\ say\ is\ sent\ to\ Lingo's\ AI\ provider.=When this phone has no model. What you say is sent to Lingo's AI provider. +With\ usage\ statistics\ turned\ on,\ the\ app\ also\ counts\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ and\ reports\ that\ to\ Codename\ One's\ analytics\ service\ under\ a\ made-up\ id\ for\ this\ device.\ Your\ name,\ e-mail,\ phone\ number,\ voice\ and\ conversations\ are\ never\ part\ of\ it,\ and\ turning\ it\ off\ in\ Settings\ stops\ it.=With usage statistics turned on, the app also counts which screens are opened and which features are used, and reports that to Codename One's analytics service under a made-up id for this device. Your name, e-mail, phone number, voice and conversations are never part of it, and turning it off in Settings stops it. +Work\ on\:\ {0}=Work on: {0} +Write\ an\ answer=Write an answer +XP\ today=XP today +You\ are\ a\ stallholder\ at\ a\ busy\ market...=You are a stallholder at a busy market... +You\ can\ keep\ practising.\ It\ is\ ready\ in\ a\ few\ minutes.=You can keep practising. It is ready in a few minutes. +You\ have\ a\ seat=You have a seat +You\ host\ this=You host this +You\ keep\ 70%\ of\ every\ sale.=You keep 70% of every sale. +You're\ a\ Pro\ member.\ Thank\ you\!=You're a Pro member. Thank you! +You're\ enrolled.\ Let's\ start\!=You're enrolled. Let's start! +You're\ live.\ Learners\ appear\ here\ as\ they\ join.=You're live. Learners appear here as they join. +Your\ course\ is\ live=Your course is live +Your\ courses=Your courses +Your\ courses,\ classes\ and\ earnings=Your courses, classes and earnings +Your\ name\ and\ language=Your name and language +Your\ phone's\ built-in\ AI\ answers.\ Nothing\ you\ say\ leaves\ the\ device.=Your phone's built-in AI answers. Nothing you say leaves the device. +Your\ seat\ is\ booked.\ We'll\ remind\ you.=Your seat is booked. We'll remind you. +Your\ sign-in,\ profile,\ progress\ and\ settings\ are\ removed\ for\ good.\ Certificates\ already\ issued\ can\ still\ be\ verified.=Your sign-in, profile, progress and settings are removed for good. Certificates already issued can still be verified. +Yours=Yours +Wait\ for\ Wi-Fi=Wait for Wi-Fi +Accounts=Accounts +Admin=Admin +Cannot\ sign\ in=Cannot sign in +Grants\ roles\ to\ other\ accounts=Grants roles to other accounts +Learner=Learner +Publishes\ courses\ and\ holds\ live\ classes=Publishes courses and holds live classes +Roles=Roles +Suspended=Suspended +Takes\ courses\ and\ practises\ with\ the\ tutor=Takes courses and practises with the tutor +Who\ can\ sign\ in,\ and\ who\ teaches=Who can sign in, and who teaches +1\ day=1 day diff --git a/scripts/lingo/common/src/main/l10n/Bundle_es.properties b/scripts/lingo/common/src/main/l10n/Bundle_es.properties new file mode 100644 index 00000000000..faed5e757e8 --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle_es.properties @@ -0,0 +1,387 @@ +# Lingo in Spanish. The key of every line is the English text the code +# names; see ui/Lang.java for how a line is found and how to add one. +@rtl=false +language.name=Espa\u00f1ol + +Today=Hoy +Accept=Aceptar +Could\ not\ reach\ the\ server.\ Check\ your\ connection.=No se pudo contactar con el servidor. Comprueba tu conexi\u00f3n. +Too\ many\ attempts.\ Wait\ a\ minute\ and\ try\ again.=Demasiados intentos. Espera un minuto y vuelve a intentarlo. +That\ e-mail\ and\ password\ do\ not\ match\ an\ account.=Ese correo y contrase\u00f1a no corresponden a ninguna cuenta. +Signing\ in\ failed.\ Try\ again.=No se pudo iniciar sesi\u00f3n. Int\u00e9ntalo de nuevo. +Not\ now=Ahora no +Settings=Ajustes +Sign\ out=Cerrar sesi\u00f3n +No\ connection=Sin conexi\u00f3n +The\ server\ at\ {0}\ did\ not\ answer.=El servidor en {0} no respondi\u00f3. +Try\ again=Reintentar +Server\ address=Direcci\u00f3n del servidor +Create\ an\ account=Crear una cuenta +Name=Nombre +Mobile\ number=N\u00famero de m\u00f3vil +Password=Contrase\u00f1a +At\ least\ 8\ characters=Al menos 8 caracteres +Create\ account=Crear cuenta +Server=Servidor +The\ address\ of\ the\ Lingo\ server\ this\ app\ talks\ to.\ Changing\ it\ signs\ you\ out.=La direcci\u00f3n del servidor Lingo que usa esta app. Cambiarla cierra tu sesi\u00f3n. +Address=Direcci\u00f3n +Save=Guardar +Account=Cuenta +Notifications=Notificaciones +Appearance=Apariencia +Language=Idioma +Theme=Tema +System=Sistema +Light=Claro +Dark=Oscuro +About=Acerca de +Terms\ of\ service=Condiciones del servicio +Privacy\ policy=Pol\u00edtica de privacidad +Sign\ in=Iniciar sesi\u00f3n +Enter\ your\ e-mail\ and\ password.=Introduce tu correo y contrase\u00f1a. + +# Driving applications, payments, the admin console and the account. +Back=Atr\u00e1s +Change\ password=Cambiar contrase\u00f1a +Change\ the\ password\ you\ sign\ in\ with=Cambia la contrase\u00f1a con la que entras +Current\ password=Contrase\u00f1a actual +Delete\ account=Eliminar cuenta +Delete\ my\ account=Eliminar mi cuenta +Delete\ your\ account?=\u00bfEliminar tu cuenta? +Keep\ my\ account=Conservar mi cuenta +New\ password=Nueva contrase\u00f1a +New\ password,\ again=Nueva contrase\u00f1a, otra vez +Profile=Perfil +That\ picture\ could\ not\ be\ read=No se pudo leer esa imagen +The\ two\ new\ passwords\ are\ not\ the\ same.=Las dos contrase\u00f1as nuevas no coinciden. +This\ device\ cannot\ prepare\ a\ picture\ to\ send=Este dispositivo no puede preparar una imagen para enviar +Your\ password\ was\ changed=Tu contrase\u00f1a se cambi\u00f3 +Usage\ statistics=Estad\u00edsticas de uso +Help\ improve\ Lingo=Ayuda a mejorar Lingo +Lingo\ can\ count\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ so\ that\ we\ can\ see\ what\ works\ and\ fix\ what\ does\ not.=Lingo puede contar qu\u00e9 pantallas se abren y qu\u00e9 funciones se usan, para que podamos ver qu\u00e9 funciona y arreglar lo que no. +No\ personal\ details=Sin datos personales +Never\ your\ name,\ e-mail,\ phone\ number,\ places\ or\ card\ details=Nunca tu nombre, correo electr\u00f3nico, n\u00famero de tel\u00e9fono, lugares ni datos de tarjeta +Turn\ it\ on\ or\ off\ at\ any\ time\ in\ Settings=Act\u00edvalo o desact\u00edvalo cuando quieras en Ajustes +Share\ usage\ statistics=Compartir estad\u00edsticas de uso +The\ server\ changed.\ Sign\ in\ again.=El servidor cambi\u00f3. Vuelve a iniciar sesi\u00f3n. + +# Lingo: the field and dispatch screens. +Assistant=Asistente +Consent=Consentimiento +Lingo=Lingo +Kind=Tipo +Legal=Legal +Location=Ubicaci\u00f3n +Privacy=Privacidad +Register=Registrarse +Software=Software +Starting=Iniciando +Unreachable=Inalcanzable +Welcome=Bienvenido +Your\ name\ and\ mobile\ number=Tu nombre y n\u00famero de m\u00f3vil +Close=Cerrar +Menu=Men\u00fa +Send=Enviar +Show\ the\ whole\ route=Ver toda la ruta +# Back-office console, admin pages and the tablet day +All=Todos +Creator=Despachador +# Workforce rules, staffing reports and planning rules +This\ week=Esta semana +Certificates=Certificados +# Company settings, labour rates, timesheets and the clock +# Company settings, labour rates, timesheets and the clock +# Sign-in and the report draft +E-mail=Correo electr\u00f3nico + + +A\ class\ you\ booked\ is\ starting=Una clase que reservaste est\u00e1 por empezar +A\ cloud\ model\ answers\ through\ Lingo's\ server.=Un modelo en la nube responde a trav\u00e9s del servidor de Lingo. +A\ nudge\ when\ today's\ goal\ is\ not\ done\ yet=Un recordatorio si a\u00fan no has cumplido el objetivo de hoy +A\ sample\ learning\ app\ built\ with\ Codename\ One=Una app de aprendizaje de ejemplo creada con Codename One +A\ scripted\ partner\ keeps\ conversations\ going.\ Download\ the\ offline\ tutor\ or\ turn\ on\ the\ cloud\ tutor\ for\ free\ conversation.=Un compa\u00f1ero con guion mantiene la conversaci\u00f3n. Descarga el tutor sin conexi\u00f3n o activa el tutor en la nube para conversar libremente. +A\ tip\ for\ {0}=Un consejo para {0} +AI\ tutor=Tutor de IA +Achievements=Logros +Add=A\u00f1adir +Add\ a\ lesson=A\u00f1adir una lecci\u00f3n +Add\ a\ phrase=A\u00f1adir una frase +Add\ a\ video,\ phrases\ to\ practise\ or\ a\ conversation\ scene.=A\u00f1ade un v\u00eddeo, frases para practicar o una escena de conversaci\u00f3n. +An\ AI\ tutor\ that\ listens,\ on\ your\ phone.=Un tutor de IA que te escucha, en tu m\u00f3vil. +As\ it\ appears\ on\ your\ certificates=Tal como aparece en tus certificados +Ask\ a\ question=Haz una pregunta +Ask\ for\ prices\ and\ quantities=Pregunta precios y cantidades +Ask\ the\ creator\ and\ other\ learners=Pregunta al creador y a otros estudiantes +At\ the\ fruit\ stall=En el puesto de frutas +Back\ to\ the\ course=Volver al curso +Badge\ unlocked=Insignia desbloqueada +Badges\ and\ your\ level=Insignias y tu nivel +Be\ the\ first\ to\ ask\ {0}.=S\u00e9 el primero en preguntar a {0}. +Better\:\ {0}=Mejor: {0} +Book=Reservar +Browse=Explorar +Browse\ courses=Explorar cursos +Bundle=Paquete +Buy\ for\ {0}=Comprar por {0} +Certificate=Certificado +Check=Comprobar +Checking\ the\ signature...=Comprobando la firma... +Checkout=Pagar +Choose=Elegir +Cloud\ AI=IA en la nube +Cloud\ AI\ tutor\ on\ any\ phone=Tutor de IA en la nube en cualquier m\u00f3vil +Cloud\ tutor=Tutor en la nube +Colour=Color +Community=Comunidad +Connect\ to\ Wi-Fi\ to\ download,\ or\ turn\ off\ Wi-Fi\ only.=Con\u00e9ctate al Wi-Fi para descargar o activa solo Wi-Fi. +Connecting\ to\ {0}...=Conectando con {0}... +Container=Contenedor +Continue=Continuar +Continue\:\ {0}=Continuar: {0} +Conversation=Conversaci\u00f3n +Cookie=Cookie +Course=Curso +Course\ complete\!=\u00a1Curso completado! +Courses=Cursos +Courses\ and\ live\ classes\ from\ real\ teachers=Cursos y clases en vivo con profesores reales +Courses,\ classes\ and\ tips=Cursos, clases y consejos +Create\ course=Crear curso +Creator\ studio=Estudio de creador +Creators\ schedule\ live\ classes\ from\ their\ studio.=Los creadores programan clases en vivo desde su estudio. +Daily\ goal\ met=Objetivo diario cumplido +Day\ streak=D\u00edas de racha +Demo\ card\ ending\ 4242=Tarjeta de prueba terminada en 4242 +Discover=Descubrir +Do\ a\ lesson\ today\ to\ start\ a\ streak.=Haz una lecci\u00f3n hoy para empezar una racha. +Download=Descargar +Download\ 470\ MB?=\u00bfDescargar 470 MB? +Download\ on\ Wi-Fi\ only=Descargar solo con Wi-Fi +Download\ the\ offline\ tutor=Descargar el tutor sin conexi\u00f3n +Downloaded\ AI,\ on\ this\ phone=IA descargada, en este m\u00f3vil +Downloading\ the\ offline\ tutor=Descargando el tutor sin conexi\u00f3n +Draft=Borrador +Drafts=Borradores +EEEE,\ MMM\ d=EEEE, d MMM +Earn\ XP\ in\ lessons\ to\ climb.\ Keep\ your\ streak\ for\ bonus\ freezes.=Gana XP en las lecciones para subir. Mant\u00e9n tu racha para conseguir protectores extra. +End=Terminar +Enrol\ for\ free=Inscribirse gratis +Enrol\ in\ a\ course\ and\ it\ shows\ up\ here.=Inscr\u00edbete en un curso y aparecer\u00e1 aqu\u00ed. +Every\ AI\ course=Todos los cursos de IA +Everything\ in\ Free=Todo lo de Gratis +Excellent\!=\u00a1Excelente! +Finish\ conversation=Terminar conversaci\u00f3n +Finish\ every\ lesson\ of\ a\ course\ to\ earn\ a\ signed\ certificate.=Termina todas las lecciones de un curso para conseguir un certificado firmado. +Finish\ lesson=Terminar lecci\u00f3n +Five\ minutes\ a\ day=Cinco minutos al d\u00eda +Free=Gratis +Frees\ 470\ MB.\ You\ can\ download\ it\ again.=Libera 470 MB. Puedes volver a descargarlo. +Genuine,\ signed\ by\ {0}=Aut\u00e9ntico, firmado por {0} +Get\ the\ offline\ AI\ tutor=Obt\u00e9n el tutor de IA sin conexi\u00f3n +Give\ the\ class\ a\ title=Ponle un t\u00edtulo a la clase +Give\ the\ course\ a\ title=Ponle un t\u00edtulo al curso +Go\ Pro=P\u00e1sate a Pro +Go\ Pro\ for\ {0}=P\u00e1sate a Pro por {0} +Go\ live=Empezar en directo +Goal\ met\!=\u00a1Objetivo cumplido! +Good\ afternoon=Buenas tardes +Good\ evening=Buenas noches +Good\ morning=Buenos d\u00edas +Great\ job\!=\u00a1Buen trabajo! +HH\:mm=HH:mm +Heard\:\ "{0}"=O\u00eddo: "{0}" +How\ much\ is\ it?=\u00bfCu\u00e1nto cuesta? +I've\ watched\ it=Ya lo he visto +In\ one\ line=En una l\u00ednea +Join=Unirse +Keep\ talking=Sigue hablando +Leaderboard=Clasificaci\u00f3n +Learn=Aprender +Learning=Aprendizaje +Led\ by\ the\ AI\ tutor=Dirigido por el tutor de IA +Length=Duraci\u00f3n +Lesson\ complete\!=\u00a1Lecci\u00f3n completada! +Lesson\ {0}\ of\ {1}=Lecci\u00f3n {0} de {1} +Lessons=Lecciones +Let's\ try\ that\ again=Vamos a intentarlo de nuevo +Level=Nivel +Level\ {0}=Nivel {0} +Lifetime\ access,\ by\ {0}=Acceso de por vida, por {0} +Lingo\ Pro=Lingo Pro +Lingo\ is\ a\ sample.\ Payments\ are\ simulated\ and\ certificates\ are\ signed\ with\ a\ demonstration\ key.=Lingo es una muestra. Los pagos son simulados y los certificados se firman con una clave de demostraci\u00f3n. +Lingo\ is\ free.\ Pro\ pays\ for\ the\ creators\ and\ the\ servers,\ and\ gives\ you\ more.=Lingo es gratis. Pro paga a los creadores y los servidores, y te da m\u00e1s. +Lingo\ needs\ the\ camera\ and\ microphone\ for\ live\ classes=Lingo necesita la c\u00e1mara y el micr\u00f3fono para las clases en vivo +Listen=Escuchar +Listening\ failed.\ Check\ the\ microphone\ permission.=Error al escuchar. Revisa el permiso del micr\u00f3fono. +Listening...=Escuchando... +Live=En vivo +Live\ classes=Clases en vivo +Live\ soon=Pronto en vivo +Live\ video\ needs\ the\ phone\ app.\ The\ class\ is\ on\:\ open\ Lingo\ on\ iOS\ or\ Android\ to\ take\ part.=El v\u00eddeo en directo requiere la app del m\u00f3vil. La clase est\u00e1 en marcha: abre Lingo en iOS o Android para participar. +Live\ with\ {0}=En vivo con {0} +MMM\ d,\ HH\:mm=d MMM, HH:mm +MMM\ d,\ yyyy=d MMM yyyy +Make\ a\ course\ of\ videos,\ phrases\ and\ conversations.=Crea un curso con v\u00eddeos, frases y conversaciones. +Me=Yo +Monday,\ Nov\ 16=lunes, 16 nov +Monthly,\ cancel\ any\ time=Mensual, cancela cuando quieras +My\ Lingo\ certificate=Mi certificado de Lingo +My\ courses=Mis cursos +Nearly\ there=Casi lo logras +New=Nuevo +New\ course=Nuevo curso +New\ lesson=Nueva lecci\u00f3n +No\ certificates\ yet=A\u00fan no hay certificados +No\ lessons\ yet=A\u00fan no hay lecciones +No\ live\ classes\ are\ scheduled\ yet.=A\u00fan no hay clases en vivo programadas. +No\ questions\ yet=A\u00fan no hay preguntas +No\ video\ yet=A\u00fan no hay v\u00eddeo +Nothing\ bought\ yet=A\u00fan no has comprado nada +Nothing\ here\ yet=A\u00fan no hay nada aqu\u00ed +Nothing\ scheduled=Nada programado +Nothing\ was\ heard.\ Tap\ the\ microphone\ and\ speak.=No se oy\u00f3 nada. Toca el micr\u00f3fono y habla. +On-device\ AI=IA en el dispositivo +On-device\ AI\ tutor=Tutor de IA en el dispositivo +One\ streak\ freeze=Un protector de racha +Order,\ haggle\ and\ chat\ with\ stallholders=Pide, regatea y charla con los vendedores +Paid\ courses,\ live\ classes\ and\ tips\ show\ up\ here.=Aqu\u00ed aparecer\u00e1n los cursos de pago, las clases en vivo y las propinas. +Pay\ {0}=Pagar {0} +Payment\ complete=Pago completado +Phrases=Frases +Phrases\ to\ say\ aloud=Frases para decir en voz alta +Pick\ up\ Riley=Retoma la charla con Riley +Pick\ your\ first\ course=Elige tu primer curso +Practice\ now=Practicar ahora +Practice\ partner=Compa\u00f1ero de pr\u00e1ctica +Practice\ reminder=Recordatorio de pr\u00e1ctica +Practise\ again=Practicar de nuevo +Practise\ speaking\ with\ an\ AI\ tutor,\ keep\ a\ streak\ and\ earn\ signed\ certificates.=Practica la conversaci\u00f3n con un tutor de IA, mant\u00e9n una racha y consigue certificados firmados. +Practise\ with\ the\ AI\ tutor,\ or\ learn\ from\ people\ who\ teach.=Practica con el tutor de IA o aprende de quienes ense\u00f1an. +Practise\ without\ limits=Practica sin l\u00edmites +Practised=Practicado +Price=Precio +Pro=Pro +Progress=Progreso +Pronunciation=Pronunciaci\u00f3n +Pronunciation\ scored\ word\ by\ word,\ on\ your\ phone=Pronunciaci\u00f3n puntuada palabra por palabra, en tu m\u00f3vil +Publish=Publicar +Published=Publicado +Purchases=Compras +Push\ registration\ failed\:\ =Error al registrar las notificaciones push: +Qa=P&R +Questions=Preguntas +Questions\ and\ answers=Preguntas y respuestas +Qwen2.5\ 0.5B,\ 470\ MB.\ Runs\ privately\ on\ this\ phone.=Qwen2.5 0.5B, 470 MB. Se ejecuta de forma privada en este m\u00f3vil. +Ready\ for\ today's\ practice?=\u00bfListo para la pr\u00e1ctica de hoy? +Record=Grabar +Reminders,\ theme,\ privacy=Recordatorios, tema, privacidad +Remove\ the\ offline\ tutor=Quitar el tutor sin conexi\u00f3n +Reply=Responder +Reply\ in\ {0}=Responder en {0} +Replying\ to\ {0}=Respondiendo a {0} +Reward=Recompensa +Rolling\ your\ R,\ live=Haciendo rodar la R, en vivo +Runs\ on\ this\ phone.\ Free,\ private,\ 470\ MB.=Se ejecuta en este m\u00f3vil. Gratis, privado, 470 MB. +Save\ lesson=Guardar lecci\u00f3n +Say\ thanks\ with\ $2.\ All\ of\ it\ goes\ to\ them.=Da las gracias con 2 $. Todo va para ellos. +Schedule=Programar +Schedule\ a\ class=Programar una clase +Scheduled.\ Learners\ can\ book\ seats\ now.=Programada. Los estudiantes ya pueden reservar plazas. +Score=Puntuaci\u00f3n +Seat\ price=Precio por plaza +Seats=Plazas +See\ all=Ver todo +See\ who\ is\ practising\ most=Mira qui\u00e9n practica m\u00e1s +Set-Cookie=Set-Cookie +Share\ certificate=Compartir certificado +Share\ which\ screens\ and\ features\ are\ used.\ Never\ your\ name,\ voice\ or\ what\ you\ say.=Comparte qu\u00e9 pantallas y funciones se usan. Nunca tu nombre, tu voz ni lo que dices. +Signed\ certificates=Certificados firmados +Signed\ certificates\ anyone\ can\ verify=Certificados firmados que cualquiera puede verificar +Signed\ proof\ of\ every\ course\ you\ finish=Prueba firmada de cada curso que terminas +Slowly=Despacio +Small\ groups\ with\ a\ real\ teacher,\ on\ video.=Grupos peque\u00f1os con un profesor real, por v\u00eddeo. +Spanish\ for\ the\ market=Espa\u00f1ol para el mercado +Speak\ a\ new\ language\ with\ an\ AI\ tutor\ that\ listens.=Habla un nuevo idioma con un tutor de IA que te escucha. +Speech\ recognition\ and\ the\ AI\ tutor\ run\ on\ this\ phone.\ What\ you\ say\ leaves\ it\ only\ if\ you\ turn\ on\ the\ cloud\ tutor.\ Your\ progress\ and\ settings\ are\ kept\ with\ your\ account\ on\ the\ server\ you\ signed\ in\ to.=El reconocimiento de voz y el tutor de IA se ejecutan en este m\u00f3vil. Lo que dices solo sale de \u00e9l si activas el tutor en la nube. Tu progreso y tus ajustes se guardan con tu cuenta en el servidor en el que iniciaste sesi\u00f3n. +Speech\ recognition\ and\ the\ voice\ always\ run\ on\ the\ phone.=El reconocimiento de voz y la voz siempre se ejecutan en el m\u00f3vil. +Start\ course=Empezar curso +Start\ learning=Empezar a aprender +Starts=Empieza +Still\ looking=Sigo buscando +Studio=Estudio +Support\ the\ creators\ you\ learn\ from=Apoya a los creadores de los que aprendes +Talk=Hablar +Tap\ and\ speak=Toca y habla +Teach\ a\ small\ group\ on\ video.\ Learners\ book\ seats,\ free\ or\ paid.=Ense\u00f1a a un grupo peque\u00f1o por v\u00eddeo. Los estudiantes reservan plazas, gratis o de pago. +Teach\ what\ you\ know=Ense\u00f1a lo que sabes +Thank\ you\ for\ supporting\ {0}=Gracias por apoyar a {0} +The\ certificate\ could\ not\ be\ saved=No se pudo guardar el certificado +The\ class\ has\ ended=La clase ha terminado +The\ download\ failed.\ Try\ again\ later.=La descarga fall\u00f3. Int\u00e9ntalo m\u00e1s tarde. +The\ model\ you\ downloaded\ answers,\ on\ this\ phone.\ Works\ offline.=El modelo que descargaste responde en este m\u00f3vil. Funciona sin conexi\u00f3n. +The\ offline\ tutor\ is\ ready=El tutor sin conexi\u00f3n est\u00e1 listo +The\ on-device\ language\ model\ is\ large;\ wait\ for\ Wi-Fi\ to\ fetch\ it=El modelo de lenguaje en el dispositivo es grande; espera a tener Wi-Fi para descargarlo +The\ scene\ the\ AI\ tutor\ plays=La escena que representa el tutor de IA +The\ signature\ does\ not\ match=La firma no coincide +The\ tutor\ could\ not\ answer\:\ =El tutor no pudo responder: +The\ tutor\ had\ nothing\ to\ say.\ Try\ again.=El tutor no ten\u00eda nada que decir. Int\u00e9ntalo de nuevo. +The\ tutor\ model\ is\ downloaded\ once\ and\ stays\ on\ this\ phone.=El modelo del tutor se descarga una vez y se queda en este m\u00f3vil. +The\ tutor\ stays\ in\ the\ scene,\ speaks\ the\ course's\ language\ at\ its\ level,\ and\ corrects\ mistakes.=El tutor se mantiene en la escena, habla el idioma del curso a su nivel y corrige los errores. +The\ video\ connection\ failed=Fall\u00f3 la conexi\u00f3n de v\u00eddeo +The\ video\ could\ not\ be\ read=No se pudo leer el v\u00eddeo +The\ video\ is\ over\ 8\ MB.\ Record\ a\ shorter\ one.=El v\u00eddeo pesa m\u00e1s de 8 MB. Graba uno m\u00e1s corto. +This\ certificate\ could\ not\ be\ shown=No se pudo mostrar este certificado +This\ lesson\ has\ no\ phrases\ yet.=Esta lecci\u00f3n a\u00fan no tiene frases. +Three\ streak\ freezes\ a\ week=Tres protectores de racha a la semana +Tip\ {0}=Propina {0} +Title=T\u00edtulo +Toolbar=Barra de herramientas +Total=Total +Total\ XP=XP totales +Tutor=Tutor +Type\ what\ you\ would\ say=Escribe lo que dir\u00edas +Typing...=Escribiendo... +Unlimited\ conversations\ and\ streak\ freezes=Conversaciones y protectores de racha ilimitados +Up\ to\ 90\ seconds\ and\ 8\ MB.\ Learners\ can\ replay\ and\ seek.=Hasta 90 segundos y 8 MB. Los estudiantes pueden repetir y avanzar. +Uploading...=Subiendo... +Use\ the\ cloud\ tutor=Usar el tutor en la nube +Used\ only\ to\ reach\ you\ about\ a\ live\ class\ you\ booked.=Solo se usa para avisarte de una clase que reservaste. +Video=V\u00eddeo +Video\ uploaded=V\u00eddeo subido +View\ your\ certificate=Ver tu certificado +Waiting\ for\ {0}'s\ video...=Esperando el v\u00eddeo de {0}... +Wallet=Cartera +What\ learners\ will\ be\ able\ to\ do=Lo que los estudiantes podr\u00e1n hacer +When\ this\ phone\ cannot\ run\ the\ tutor,\ ask\ the\ server's\ AI\ instead=Cuando este m\u00f3vil no puede ejecutar el tutor, pregunta a la IA del servidor +When\ this\ phone\ has\ no\ model.\ What\ you\ say\ is\ sent\ to\ Lingo's\ AI\ provider.=Cuando este m\u00f3vil no tiene modelo. Lo que dices se env\u00eda al proveedor de IA de Lingo. +With\ usage\ statistics\ turned\ on,\ the\ app\ also\ counts\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ and\ reports\ that\ to\ Codename\ One's\ analytics\ service\ under\ a\ made-up\ id\ for\ this\ device.\ Your\ name,\ e-mail,\ phone\ number,\ voice\ and\ conversations\ are\ never\ part\ of\ it,\ and\ turning\ it\ off\ in\ Settings\ stops\ it.=Con las estad\u00edsticas de uso activadas, la app tambi\u00e9n cuenta qu\u00e9 pantallas se abren y qu\u00e9 funciones se usan, y lo env\u00eda al servicio de anal\u00edtica de Codename One bajo un id inventado para este dispositivo. Tu nombre, correo, tel\u00e9fono, voz y conversaciones nunca forman parte de ello, y desactivarlo en Ajustes lo detiene. +Work\ on\:\ {0}=Trabaja en: {0} +Write\ an\ answer=Escribe una respuesta +XP\ today=XP de hoy +You\ are\ a\ stallholder\ at\ a\ busy\ market...=Eres un vendedor en un mercado concurrido... +You\ can\ keep\ practising.\ It\ is\ ready\ in\ a\ few\ minutes.=Puedes seguir practicando. Estar\u00e1 listo en unos minutos. +You\ have\ a\ seat=Tienes una plaza +You\ host\ this=T\u00fa organizas esto +You\ keep\ 70%\ of\ every\ sale.=Te quedas con el 70 % de cada venta. +You're\ a\ Pro\ member.\ Thank\ you\!=\u00a1Eres miembro Pro. Gracias! +You're\ enrolled.\ Let's\ start\!=\u00a1Ya est\u00e1s inscrito. Empecemos! +You're\ live.\ Learners\ appear\ here\ as\ they\ join.=Est\u00e1s en directo. Los estudiantes aparecer\u00e1n aqu\u00ed al unirse. +Your\ course\ is\ live=Tu curso est\u00e1 en l\u00ednea +Your\ courses=Tus cursos +Your\ courses,\ classes\ and\ earnings=Tus cursos, clases y ganancias +Your\ name\ and\ language=Tu nombre e idioma +Your\ phone's\ built-in\ AI\ answers.\ Nothing\ you\ say\ leaves\ the\ device.=La IA integrada de tu m\u00f3vil responde. Nada de lo que dices sale del dispositivo. +Your\ seat\ is\ booked.\ We'll\ remind\ you.=Tu plaza est\u00e1 reservada. Te lo recordaremos. +Your\ sign-in,\ profile,\ progress\ and\ settings\ are\ removed\ for\ good.\ Certificates\ already\ issued\ can\ still\ be\ verified.=Tu inicio de sesi\u00f3n, perfil, progreso y ajustes se eliminan para siempre. Los certificados ya emitidos a\u00fan se pueden verificar. +Yours=Tuyo +Wait\ for\ Wi-Fi=Esperar al Wi-Fi +Accounts=Cuentas +Admin=Administrador +Cannot\ sign\ in=No puede iniciar sesi\u00f3n +Grants\ roles\ to\ other\ accounts=Asigna roles a otras cuentas +Learner=Estudiante +Publishes\ courses\ and\ holds\ live\ classes=Publica cursos e imparte clases en directo +Roles=Roles +Suspended=Suspendida +Takes\ courses\ and\ practises\ with\ the\ tutor=Hace cursos y practica con el tutor +Who\ can\ sign\ in,\ and\ who\ teaches=Qui\u00e9n puede entrar y qui\u00e9n ense\u00f1a +1\ day=1 d\u00eda diff --git a/scripts/lingo/common/src/main/l10n/Bundle_fr.properties b/scripts/lingo/common/src/main/l10n/Bundle_fr.properties new file mode 100644 index 00000000000..9af872bdc05 --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle_fr.properties @@ -0,0 +1,387 @@ +# Lingo in French. The key of every line is the English text the code +# names; see ui/Lang.java for how a line is found and how to add one. +@rtl=false +language.name=Fran\u00e7ais + +Today=Aujourd'hui +Accept=Accepter +Could\ not\ reach\ the\ server.\ Check\ your\ connection.=Impossible de joindre le serveur. V\u00e9rifiez votre connexion. +Too\ many\ attempts.\ Wait\ a\ minute\ and\ try\ again.=Trop de tentatives. Patientez une minute et r\u00e9essayez. +That\ e-mail\ and\ password\ do\ not\ match\ an\ account.=Cet e-mail et ce mot de passe ne correspondent \u00e0 aucun compte. +Signing\ in\ failed.\ Try\ again.=La connexion a \u00e9chou\u00e9. R\u00e9essayez. +Not\ now=Pas maintenant +Settings=R\u00e9glages +Sign\ out=Se d\u00e9connecter +No\ connection=Pas de connexion +The\ server\ at\ {0}\ did\ not\ answer.=Le serveur \u00e0 {0} n'a pas r\u00e9pondu. +Try\ again=R\u00e9essayer +Server\ address=Adresse du serveur +Create\ an\ account=Cr\u00e9er un compte +Name=Nom +Mobile\ number=Num\u00e9ro de mobile +Password=Mot de passe +At\ least\ 8\ characters=Au moins 8 caract\u00e8res +Create\ account=Cr\u00e9er le compte +Server=Serveur +The\ address\ of\ the\ Lingo\ server\ this\ app\ talks\ to.\ Changing\ it\ signs\ you\ out.=L'adresse du serveur Lingo utilis\u00e9 par cette application. La modifier vous d\u00e9connecte. +Address=Adresse +Save=Enregistrer +Account=Compte +Notifications=Notifications +Appearance=Apparence +Language=Langue +Theme=Th\u00e8me +System=Syst\u00e8me +Light=Clair +Dark=Sombre +About=\u00c0 propos +Terms\ of\ service=Conditions d'utilisation +Privacy\ policy=Politique de confidentialit\u00e9 +Sign\ in=Se connecter +Enter\ your\ e-mail\ and\ password.=Saisissez votre e-mail et votre mot de passe. + +# Driving applications, payments, the admin console and the account. +Back=Retour +Change\ password=Changer le mot de passe +Change\ the\ password\ you\ sign\ in\ with=Changez le mot de passe de connexion +Current\ password=Mot de passe actuel +Delete\ account=Supprimer le compte +Delete\ my\ account=Supprimer mon compte +Delete\ your\ account?=Supprimer votre compte ? +Keep\ my\ account=Garder mon compte +New\ password=Nouveau mot de passe +New\ password,\ again=Nouveau mot de passe, encore +Profile=Profil +That\ picture\ could\ not\ be\ read=Cette image n'a pas pu \u00eatre lue +The\ two\ new\ passwords\ are\ not\ the\ same.=Les deux nouveaux mots de passe sont diff\u00e9rents. +This\ device\ cannot\ prepare\ a\ picture\ to\ send=Cet appareil ne peut pas pr\u00e9parer une image \u00e0 envoyer +Your\ password\ was\ changed=Votre mot de passe a \u00e9t\u00e9 modifi\u00e9 +Usage\ statistics=Statistiques d'utilisation +Help\ improve\ Lingo=Aidez \u00e0 am\u00e9liorer Lingo +Lingo\ can\ count\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ so\ that\ we\ can\ see\ what\ works\ and\ fix\ what\ does\ not.=Lingo peut compter quels \u00e9crans sont ouverts et quelles fonctions sont utilis\u00e9es, pour que nous puissions voir ce qui marche et corriger ce qui ne marche pas. +No\ personal\ details=Aucune donn\u00e9e personnelle +Never\ your\ name,\ e-mail,\ phone\ number,\ places\ or\ card\ details=Jamais votre nom, votre e-mail, votre num\u00e9ro de t\u00e9l\u00e9phone, vos lieux ni les donn\u00e9es de votre carte +Turn\ it\ on\ or\ off\ at\ any\ time\ in\ Settings=Activez ou d\u00e9sactivez-les \u00e0 tout moment dans R\u00e9glages +Share\ usage\ statistics=Partager les statistiques d'utilisation +The\ server\ changed.\ Sign\ in\ again.=Le serveur a chang\u00e9. Reconnectez-vous. + +# Lingo: the field and dispatch screens. +Assistant=Assistant +Consent=Consentement +Lingo=Lingo +Kind=Type +Legal=Mentions l\u00e9gales +Location=Lieu +Privacy=Confidentialit\u00e9 +Register=S'inscrire +Software=Logiciel +Starting=D\u00e9marrage +Unreachable=Injoignable +Welcome=Bienvenue +Your\ name\ and\ mobile\ number=Ton nom et ton num\u00e9ro de mobile +Close=Fermer +Menu=Menu +Send=Envoyer +Show\ the\ whole\ route=Voir tout l'itin\u00e9raire +# Back-office console, admin pages and the tablet day +All=Tous +Creator=R\u00e9partiteur +# Workforce rules, staffing reports and planning rules +This\ week=Cette semaine +Certificates=Certificats +# Company settings, labour rates, timesheets and the clock +# Company settings, labour rates, timesheets and the clock +# Sign-in and the report draft +E-mail=E-mail + + +A\ class\ you\ booked\ is\ starting=Un cours que tu as r\u00e9serv\u00e9 va commencer +A\ cloud\ model\ answers\ through\ Lingo's\ server.=Un mod\u00e8le dans le cloud r\u00e9pond via le serveur de Lingo. +A\ nudge\ when\ today's\ goal\ is\ not\ done\ yet=Un rappel si l'objectif du jour n'est pas encore atteint +A\ sample\ learning\ app\ built\ with\ Codename\ One=Une appli d'apprentissage d'exemple cr\u00e9\u00e9e avec Codename One +A\ scripted\ partner\ keeps\ conversations\ going.\ Download\ the\ offline\ tutor\ or\ turn\ on\ the\ cloud\ tutor\ for\ free\ conversation.=Un partenaire script\u00e9 entretient la conversation. T\u00e9l\u00e9charge le tuteur hors ligne ou active le tuteur cloud pour discuter librement. +A\ tip\ for\ {0}=Un conseil pour {0} +AI\ tutor=Tuteur IA +Achievements=Succ\u00e8s +Add=Ajouter +Add\ a\ lesson=Ajouter une le\u00e7on +Add\ a\ phrase=Ajouter une phrase +Add\ a\ video,\ phrases\ to\ practise\ or\ a\ conversation\ scene.=Ajoute une vid\u00e9o, des phrases \u00e0 pratiquer ou une sc\u00e8ne de conversation. +An\ AI\ tutor\ that\ listens,\ on\ your\ phone.=Un tuteur IA qui t'\u00e9coute, sur ton t\u00e9l\u00e9phone. +As\ it\ appears\ on\ your\ certificates=Tel qu'il appara\u00eet sur tes certificats +Ask\ a\ question=Poser une question +Ask\ for\ prices\ and\ quantities=Demande les prix et les quantit\u00e9s +Ask\ the\ creator\ and\ other\ learners=Demande au cr\u00e9ateur et aux autres apprenants +At\ the\ fruit\ stall=\u00c0 l'\u00e9tal de fruits +Back\ to\ the\ course=Retour au cours +Badge\ unlocked=Badge d\u00e9bloqu\u00e9 +Badges\ and\ your\ level=Badges et ton niveau +Be\ the\ first\ to\ ask\ {0}.=Sois le premier \u00e0 demander \u00e0 {0}. +Better\:\ {0}=Mieux : {0} +Book=R\u00e9server +Browse=Parcourir +Browse\ courses=Parcourir les cours +Bundle=Pack +Buy\ for\ {0}=Acheter pour {0} +Certificate=Certificat +Check=V\u00e9rifier +Checking\ the\ signature...=V\u00e9rification de la signature... +Checkout=Paiement +Choose=Choisir +Cloud\ AI=IA cloud +Cloud\ AI\ tutor\ on\ any\ phone=Tuteur IA cloud sur n'importe quel t\u00e9l\u00e9phone +Cloud\ tutor=Tuteur cloud +Colour=Couleur +Community=Communaut\u00e9 +Connect\ to\ Wi-Fi\ to\ download,\ or\ turn\ off\ Wi-Fi\ only.=Connecte-toi au Wi-Fi pour t\u00e9l\u00e9charger, ou d\u00e9sactive l'option Wi-Fi uniquement. +Connecting\ to\ {0}...=Connexion \u00e0 {0}... +Container=Conteneur +Continue=Continuer +Continue\:\ {0}=Continuer : {0} +Conversation=Conversation +Cookie=Cookie +Course=Cours +Course\ complete\!=Cours termin\u00e9 ! +Courses=Cours +Courses\ and\ live\ classes\ from\ real\ teachers=Des cours et des classes en direct avec de vrais profs +Courses,\ classes\ and\ tips=Cours, classes et conseils +Create\ course=Cr\u00e9er un cours +Creator\ studio=Studio cr\u00e9ateur +Creators\ schedule\ live\ classes\ from\ their\ studio.=Les cr\u00e9ateurs programment des classes en direct depuis leur studio. +Daily\ goal\ met=Objectif du jour atteint +Day\ streak=Jours de s\u00e9rie +Demo\ card\ ending\ 4242=Carte de d\u00e9mo se terminant par 4242 +Discover=D\u00e9couvrir +Do\ a\ lesson\ today\ to\ start\ a\ streak.=Fais une le\u00e7on aujourd'hui pour lancer une s\u00e9rie. +Download=T\u00e9l\u00e9charger +Download\ 470\ MB?=T\u00e9l\u00e9charger 470 Mo ? +Download\ on\ Wi-Fi\ only=T\u00e9l\u00e9charger en Wi-Fi uniquement +Download\ the\ offline\ tutor=T\u00e9l\u00e9charger le tuteur hors ligne +Downloaded\ AI,\ on\ this\ phone=IA t\u00e9l\u00e9charg\u00e9e, sur ce t\u00e9l\u00e9phone +Downloading\ the\ offline\ tutor=T\u00e9l\u00e9chargement du tuteur hors ligne +Draft=Brouillon +Drafts=Brouillons +EEEE,\ MMM\ d=EEEE d MMM +Earn\ XP\ in\ lessons\ to\ climb.\ Keep\ your\ streak\ for\ bonus\ freezes.=Gagne des XP en le\u00e7on pour monter. Garde ta s\u00e9rie pour des gels bonus. +End=Terminer +Enrol\ for\ free=S'inscrire gratuitement +Enrol\ in\ a\ course\ and\ it\ shows\ up\ here.=Inscris-toi \u00e0 un cours et il appara\u00eetra ici. +Every\ AI\ course=Tous les cours d'IA +Everything\ in\ Free=Tout ce qui est dans Gratuit +Excellent\!=Excellent ! +Finish\ conversation=Terminer la conversation +Finish\ every\ lesson\ of\ a\ course\ to\ earn\ a\ signed\ certificate.=Termine toutes les le\u00e7ons d'un cours pour obtenir un certificat sign\u00e9. +Finish\ lesson=Terminer la le\u00e7on +Five\ minutes\ a\ day=Cinq minutes par jour +Free=Gratuit +Frees\ 470\ MB.\ You\ can\ download\ it\ again.=Lib\u00e8re 470 Mo. Tu pourras le ret\u00e9l\u00e9charger. +Genuine,\ signed\ by\ {0}=Authentique, sign\u00e9 par {0} +Get\ the\ offline\ AI\ tutor=Obtenir le tuteur IA hors ligne +Give\ the\ class\ a\ title=Donne un titre \u00e0 la classe +Give\ the\ course\ a\ title=Donne un titre au cours +Go\ Pro=Passer \u00e0 Pro +Go\ Pro\ for\ {0}=Passer \u00e0 Pro pour {0} +Go\ live=Passer en direct +Goal\ met\!=Objectif atteint ! +Good\ afternoon=Bon apr\u00e8s-midi +Good\ evening=Bonsoir +Good\ morning=Bonjour +Great\ job\!=Bravo ! +HH\:mm=HH:mm +Heard\:\ "{0}"=Entendu : \u00ab {0} \u00bb +How\ much\ is\ it?=C'est combien ? +I've\ watched\ it=Je l'ai regard\u00e9e +In\ one\ line=En une ligne +Join=Rejoindre +Keep\ talking=Continue de parler +Leaderboard=Classement +Learn=Apprendre +Learning=Apprentissage +Led\ by\ the\ AI\ tutor=Anim\u00e9 par le tuteur IA +Length=Dur\u00e9e +Lesson\ complete\!=Le\u00e7on termin\u00e9e ! +Lesson\ {0}\ of\ {1}=Le\u00e7on {0} sur {1} +Lessons=Le\u00e7ons +Let's\ try\ that\ again=R\u00e9essayons +Level=Niveau +Level\ {0}=Niveau {0} +Lifetime\ access,\ by\ {0}=Acc\u00e8s \u00e0 vie, par {0} +Lingo\ Pro=Lingo Pro +Lingo\ is\ a\ sample.\ Payments\ are\ simulated\ and\ certificates\ are\ signed\ with\ a\ demonstration\ key.=Lingo est un exemple. Les paiements sont simul\u00e9s et les certificats sont sign\u00e9s avec une cl\u00e9 de d\u00e9monstration. +Lingo\ is\ free.\ Pro\ pays\ for\ the\ creators\ and\ the\ servers,\ and\ gives\ you\ more.=Lingo est gratuit. Pro r\u00e9mun\u00e8re les cr\u00e9ateurs et les serveurs, et t'offre plus. +Lingo\ needs\ the\ camera\ and\ microphone\ for\ live\ classes=Lingo a besoin de la cam\u00e9ra et du micro pour les classes en direct +Listen=\u00c9couter +Listening\ failed.\ Check\ the\ microphone\ permission.=\u00c9chec de l'\u00e9coute. V\u00e9rifie l'autorisation du micro. +Listening...=\u00c9coute en cours... +Live=En direct +Live\ classes=Classes en direct +Live\ soon=Bient\u00f4t en direct +Live\ video\ needs\ the\ phone\ app.\ The\ class\ is\ on\:\ open\ Lingo\ on\ iOS\ or\ Android\ to\ take\ part.=La vid\u00e9o en direct n\u00e9cessite l'appli mobile. La classe est en cours : ouvre Lingo sur iOS ou Android pour participer. +Live\ with\ {0}=En direct avec {0} +MMM\ d,\ HH\:mm=d MMM, HH:mm +MMM\ d,\ yyyy=d MMM yyyy +Make\ a\ course\ of\ videos,\ phrases\ and\ conversations.=Cr\u00e9e un cours avec des vid\u00e9os, des phrases et des conversations. +Me=Moi +Monday,\ Nov\ 16=lundi 16 nov. +Monthly,\ cancel\ any\ time=Mensuel, r\u00e9siliable \u00e0 tout moment +My\ Lingo\ certificate=Mon certificat Lingo +My\ courses=Mes cours +Nearly\ there=Presque l\u00e0 +New=Nouveau +New\ course=Nouveau cours +New\ lesson=Nouvelle le\u00e7on +No\ certificates\ yet=Pas encore de certificats +No\ lessons\ yet=Pas encore de le\u00e7ons +No\ live\ classes\ are\ scheduled\ yet.=Aucune classe en direct n'est encore programm\u00e9e. +No\ questions\ yet=Pas encore de questions +No\ video\ yet=Pas encore de vid\u00e9o +Nothing\ bought\ yet=Aucun achat pour l'instant +Nothing\ here\ yet=Rien ici pour l'instant +Nothing\ scheduled=Rien de programm\u00e9 +Nothing\ was\ heard.\ Tap\ the\ microphone\ and\ speak.=Rien n'a \u00e9t\u00e9 entendu. Appuie sur le micro et parle. +On-device\ AI=IA sur l'appareil +On-device\ AI\ tutor=Tuteur IA sur l'appareil +One\ streak\ freeze=Un gel de s\u00e9rie +Order,\ haggle\ and\ chat\ with\ stallholders=Commande, marchande et discute avec les commer\u00e7ants +Paid\ courses,\ live\ classes\ and\ tips\ show\ up\ here.=Les cours payants, les classes en direct et les pourboires appara\u00eetront ici. +Pay\ {0}=Payer {0} +Payment\ complete=Paiement effectu\u00e9 +Phrases=Phrases +Phrases\ to\ say\ aloud=Phrases \u00e0 dire \u00e0 voix haute +Pick\ up\ Riley=Retrouve Riley +Pick\ your\ first\ course=Choisis ton premier cours +Practice\ now=S'entra\u00eener maintenant +Practice\ partner=Partenaire d'entra\u00eenement +Practice\ reminder=Rappel d'entra\u00eenement +Practise\ again=S'entra\u00eener encore +Practise\ speaking\ with\ an\ AI\ tutor,\ keep\ a\ streak\ and\ earn\ signed\ certificates.=Entra\u00eene-toi \u00e0 parler avec un tuteur IA, garde une s\u00e9rie et gagne des certificats sign\u00e9s. +Practise\ with\ the\ AI\ tutor,\ or\ learn\ from\ people\ who\ teach.=Entra\u00eene-toi avec le tuteur IA, ou apprends aupr\u00e8s de ceux qui enseignent. +Practise\ without\ limits=Entra\u00eene-toi sans limites +Practised=Pratiqu\u00e9 +Price=Prix +Pro=Pro +Progress=Progression +Pronunciation=Prononciation +Pronunciation\ scored\ word\ by\ word,\ on\ your\ phone=Prononciation not\u00e9e mot par mot, sur ton t\u00e9l\u00e9phone +Publish=Publier +Published=Publi\u00e9 +Purchases=Achats +Push\ registration\ failed\:\ =\u00c9chec de l'enregistrement push : +Qa=Q&R +Questions=Questions +Questions\ and\ answers=Questions et r\u00e9ponses +Qwen2.5\ 0.5B,\ 470\ MB.\ Runs\ privately\ on\ this\ phone.=Qwen2.5 0.5B, 470 Mo. Fonctionne en priv\u00e9 sur ce t\u00e9l\u00e9phone. +Ready\ for\ today's\ practice?=Pr\u00eat pour l'entra\u00eenement du jour ? +Record=Enregistrer +Reminders,\ theme,\ privacy=Rappels, th\u00e8me, confidentialit\u00e9 +Remove\ the\ offline\ tutor=Supprimer le tuteur hors ligne +Reply=R\u00e9pondre +Reply\ in\ {0}=R\u00e9pondre en {0} +Replying\ to\ {0}=R\u00e9ponse \u00e0 {0} +Reward=R\u00e9compense +Rolling\ your\ R,\ live=Rouler le R, en direct +Runs\ on\ this\ phone.\ Free,\ private,\ 470\ MB.=Fonctionne sur ce t\u00e9l\u00e9phone. Gratuit, priv\u00e9, 470 Mo. +Save\ lesson=Enregistrer la le\u00e7on +Say\ thanks\ with\ $2.\ All\ of\ it\ goes\ to\ them.=Dis merci avec 2 $. Tout leur revient. +Schedule=Programmer +Schedule\ a\ class=Programmer une classe +Scheduled.\ Learners\ can\ book\ seats\ now.=Programm\u00e9. Les apprenants peuvent r\u00e9server leur place. +Score=Score +Seat\ price=Prix par place +Seats=Places +See\ all=Tout voir +See\ who\ is\ practising\ most=Vois qui s'entra\u00eene le plus +Set-Cookie=Set-Cookie +Share\ certificate=Partager le certificat +Share\ which\ screens\ and\ features\ are\ used.\ Never\ your\ name,\ voice\ or\ what\ you\ say.=Partage les \u00e9crans et fonctions utilis\u00e9s. Jamais ton nom, ta voix ni ce que tu dis. +Signed\ certificates=Certificats sign\u00e9s +Signed\ certificates\ anyone\ can\ verify=Des certificats sign\u00e9s que tout le monde peut v\u00e9rifier +Signed\ proof\ of\ every\ course\ you\ finish=Une preuve sign\u00e9e de chaque cours termin\u00e9 +Slowly=Lentement +Small\ groups\ with\ a\ real\ teacher,\ on\ video.=De petits groupes avec un vrai prof, en vid\u00e9o. +Spanish\ for\ the\ market=Espagnol pour le march\u00e9 +Speak\ a\ new\ language\ with\ an\ AI\ tutor\ that\ listens.=Parle une nouvelle langue avec un tuteur IA qui t'\u00e9coute. +Speech\ recognition\ and\ the\ AI\ tutor\ run\ on\ this\ phone.\ What\ you\ say\ leaves\ it\ only\ if\ you\ turn\ on\ the\ cloud\ tutor.\ Your\ progress\ and\ settings\ are\ kept\ with\ your\ account\ on\ the\ server\ you\ signed\ in\ to.=La reconnaissance vocale et le tuteur IA fonctionnent sur ce t\u00e9l\u00e9phone. Ce que tu dis n'en sort que si tu actives le tuteur cloud. Ta progression et tes r\u00e9glages sont conserv\u00e9s avec ton compte sur le serveur auquel tu t'es connect\u00e9. +Speech\ recognition\ and\ the\ voice\ always\ run\ on\ the\ phone.=La reconnaissance vocale et la voix fonctionnent toujours sur le t\u00e9l\u00e9phone. +Start\ course=Commencer le cours +Start\ learning=Commencer \u00e0 apprendre +Starts=D\u00e9but +Still\ looking=Toujours en recherche +Studio=Studio +Support\ the\ creators\ you\ learn\ from=Soutiens les cr\u00e9ateurs dont tu apprends +Talk=Parler +Tap\ and\ speak=Appuie et parle +Teach\ a\ small\ group\ on\ video.\ Learners\ book\ seats,\ free\ or\ paid.=Enseigne \u00e0 un petit groupe en vid\u00e9o. Les apprenants r\u00e9servent des places, gratuites ou payantes. +Teach\ what\ you\ know=Enseigne ce que tu sais +Thank\ you\ for\ supporting\ {0}=Merci de soutenir {0} +The\ certificate\ could\ not\ be\ saved=Le certificat n'a pas pu \u00eatre enregistr\u00e9 +The\ class\ has\ ended=La classe est termin\u00e9e +The\ download\ failed.\ Try\ again\ later.=Le t\u00e9l\u00e9chargement a \u00e9chou\u00e9. R\u00e9essaie plus tard. +The\ model\ you\ downloaded\ answers,\ on\ this\ phone.\ Works\ offline.=Le mod\u00e8le que tu as t\u00e9l\u00e9charg\u00e9 r\u00e9pond sur ce t\u00e9l\u00e9phone. Fonctionne hors ligne. +The\ offline\ tutor\ is\ ready=Le tuteur hors ligne est pr\u00eat +The\ on-device\ language\ model\ is\ large;\ wait\ for\ Wi-Fi\ to\ fetch\ it=Le mod\u00e8le de langage sur l'appareil est volumineux ; attends d'avoir le Wi-Fi pour le t\u00e9l\u00e9charger +The\ scene\ the\ AI\ tutor\ plays=La sc\u00e8ne que joue le tuteur IA +The\ signature\ does\ not\ match=La signature ne correspond pas +The\ tutor\ could\ not\ answer\:\ =Le tuteur n'a pas pu r\u00e9pondre : +The\ tutor\ had\ nothing\ to\ say.\ Try\ again.=Le tuteur n'avait rien \u00e0 dire. R\u00e9essaie. +The\ tutor\ model\ is\ downloaded\ once\ and\ stays\ on\ this\ phone.=Le mod\u00e8le du tuteur est t\u00e9l\u00e9charg\u00e9 une seule fois et reste sur ce t\u00e9l\u00e9phone. +The\ tutor\ stays\ in\ the\ scene,\ speaks\ the\ course's\ language\ at\ its\ level,\ and\ corrects\ mistakes.=Le tuteur reste dans la sc\u00e8ne, parle la langue du cours \u00e0 son niveau et corrige les erreurs. +The\ video\ connection\ failed=La connexion vid\u00e9o a \u00e9chou\u00e9 +The\ video\ could\ not\ be\ read=La vid\u00e9o n'a pas pu \u00eatre lue +The\ video\ is\ over\ 8\ MB.\ Record\ a\ shorter\ one.=La vid\u00e9o d\u00e9passe 8 Mo. Enregistres-en une plus courte. +This\ certificate\ could\ not\ be\ shown=Ce certificat n'a pas pu \u00eatre affich\u00e9 +This\ lesson\ has\ no\ phrases\ yet.=Cette le\u00e7on n'a pas encore de phrases. +Three\ streak\ freezes\ a\ week=Trois gels de s\u00e9rie par semaine +Tip\ {0}=Pourboire {0} +Title=Titre +Toolbar=Barre d'outils +Total=Total +Total\ XP=XP total +Tutor=Tuteur +Type\ what\ you\ would\ say=\u00c9cris ce que tu dirais +Typing...=Saisie... +Unlimited\ conversations\ and\ streak\ freezes=Conversations et gels de s\u00e9rie illimit\u00e9s +Up\ to\ 90\ seconds\ and\ 8\ MB.\ Learners\ can\ replay\ and\ seek.=Jusqu'\u00e0 90 secondes et 8 Mo. Les apprenants peuvent revoir et naviguer. +Uploading...=Envoi... +Use\ the\ cloud\ tutor=Utiliser le tuteur cloud +Used\ only\ to\ reach\ you\ about\ a\ live\ class\ you\ booked.=Utilis\u00e9 uniquement pour te contacter \u00e0 propos d'une classe en direct que tu as r\u00e9serv\u00e9e. +Video=Vid\u00e9o +Video\ uploaded=Vid\u00e9o envoy\u00e9e +View\ your\ certificate=Voir ton certificat +Waiting\ for\ {0}'s\ video...=En attente de la vid\u00e9o de {0}... +Wallet=Portefeuille +What\ learners\ will\ be\ able\ to\ do=Ce que les apprenants sauront faire +When\ this\ phone\ cannot\ run\ the\ tutor,\ ask\ the\ server's\ AI\ instead=Quand ce t\u00e9l\u00e9phone ne peut pas faire tourner le tuteur, demander \u00e0 l'IA du serveur +When\ this\ phone\ has\ no\ model.\ What\ you\ say\ is\ sent\ to\ Lingo's\ AI\ provider.=Quand ce t\u00e9l\u00e9phone n'a pas de mod\u00e8le. Ce que tu dis est envoy\u00e9 au fournisseur d'IA de Lingo. +With\ usage\ statistics\ turned\ on,\ the\ app\ also\ counts\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ and\ reports\ that\ to\ Codename\ One's\ analytics\ service\ under\ a\ made-up\ id\ for\ this\ device.\ Your\ name,\ e-mail,\ phone\ number,\ voice\ and\ conversations\ are\ never\ part\ of\ it,\ and\ turning\ it\ off\ in\ Settings\ stops\ it.=Quand les statistiques d'usage sont activ\u00e9es, l'appli compte aussi les \u00e9crans ouverts et les fonctions utilis\u00e9es, et le transmet au service d'analyse de Codename One sous un identifiant invent\u00e9 pour cet appareil. Ton nom, e-mail, num\u00e9ro de t\u00e9l\u00e9phone, voix et conversations n'en font jamais partie, et le d\u00e9sactiver dans les R\u00e9glages l'arr\u00eate. +Work\ on\:\ {0}=Travailler sur : {0} +Write\ an\ answer=\u00c9cris une r\u00e9ponse +XP\ today=XP aujourd'hui +You\ are\ a\ stallholder\ at\ a\ busy\ market...=Tu es commer\u00e7ant sur un march\u00e9 anim\u00e9... +You\ can\ keep\ practising.\ It\ is\ ready\ in\ a\ few\ minutes.=Tu peux continuer \u00e0 t'entra\u00eener. Il sera pr\u00eat dans quelques minutes. +You\ have\ a\ seat=Tu as une place +You\ host\ this=Tu animes cette classe +You\ keep\ 70%\ of\ every\ sale.=Tu gardes 70 % de chaque vente. +You're\ a\ Pro\ member.\ Thank\ you\!=Tu es membre Pro. Merci ! +You're\ enrolled.\ Let's\ start\!=Tu es inscrit. C'est parti ! +You're\ live.\ Learners\ appear\ here\ as\ they\ join.=Tu es en direct. Les apprenants appara\u00eetront ici en rejoignant. +Your\ course\ is\ live=Ton cours est en ligne +Your\ courses=Tes cours +Your\ courses,\ classes\ and\ earnings=Tes cours, classes et revenus +Your\ name\ and\ language=Ton nom et ta langue +Your\ phone's\ built-in\ AI\ answers.\ Nothing\ you\ say\ leaves\ the\ device.=L'IA int\u00e9gr\u00e9e \u00e0 ton t\u00e9l\u00e9phone r\u00e9pond. Rien de ce que tu dis ne quitte l'appareil. +Your\ seat\ is\ booked.\ We'll\ remind\ you.=Ta place est r\u00e9serv\u00e9e. On te le rappellera. +Your\ sign-in,\ profile,\ progress\ and\ settings\ are\ removed\ for\ good.\ Certificates\ already\ issued\ can\ still\ be\ verified.=Ta connexion, ton profil, ta progression et tes r\u00e9glages sont supprim\u00e9s d\u00e9finitivement. Les certificats d\u00e9j\u00e0 \u00e9mis restent v\u00e9rifiables. +Yours=\u00c0 toi +Wait\ for\ Wi-Fi=Attendre le Wi-Fi +Accounts=Comptes +Admin=Administrateur +Cannot\ sign\ in=Ne peut pas se connecter +Grants\ roles\ to\ other\ accounts=Attribue des r\u00f4les aux autres comptes +Learner=Apprenant +Publishes\ courses\ and\ holds\ live\ classes=Publie des cours et donne des cours en direct +Roles=R\u00f4les +Suspended=Suspendu +Takes\ courses\ and\ practises\ with\ the\ tutor=Suit des cours et s'entra\u00eene avec le tuteur +Who\ can\ sign\ in,\ and\ who\ teaches=Qui peut se connecter, et qui enseigne +1\ day=1 jour diff --git a/scripts/lingo/common/src/main/l10n/Bundle_he.properties b/scripts/lingo/common/src/main/l10n/Bundle_he.properties new file mode 100644 index 00000000000..75190eb106b --- /dev/null +++ b/scripts/lingo/common/src/main/l10n/Bundle_he.properties @@ -0,0 +1,387 @@ +# Lingo in Hebrew. The key of every line is the English text the code +# names; see ui/Lang.java for how a line is found and how to add one. +@rtl=true +language.name=\u05e2\u05d1\u05e8\u05d9\u05ea + +Today=\u05d4\u05d9\u05d5\u05dd +Accept=\u05e7\u05d1\u05dc +Could\ not\ reach\ the\ server.\ Check\ your\ connection.=\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05dc\u05d4\u05d2\u05d9\u05e2 \u05dc\u05e9\u05e8\u05ea. \u05d1\u05d3\u05d5\u05e7 \u05d0\u05ea \u05d4\u05d7\u05d9\u05d1\u05d5\u05e8. +Too\ many\ attempts.\ Wait\ a\ minute\ and\ try\ again.=\u05d9\u05d5\u05ea\u05e8 \u05de\u05d3\u05d9 \u05e0\u05d9\u05e1\u05d9\u05d5\u05e0\u05d5\u05ea. \u05d4\u05de\u05ea\u05df \u05d3\u05e7\u05d4 \u05d5\u05e0\u05e1\u05d4 \u05e9\u05d5\u05d1. +That\ e-mail\ and\ password\ do\ not\ match\ an\ account.=\u05d4\u05d3\u05d5\u05d0"\u05dc \u05d5\u05d4\u05e1\u05d9\u05e1\u05de\u05d4 \u05d0\u05d9\u05e0\u05dd \u05ea\u05d5\u05d0\u05de\u05d9\u05dd \u05dc\u05d7\u05e9\u05d1\u05d5\u05df. +Signing\ in\ failed.\ Try\ again.=\u05d4\u05d4\u05ea\u05d7\u05d1\u05e8\u05d5\u05ea \u05e0\u05db\u05e9\u05dc\u05d4. \u05e0\u05e1\u05d4 \u05e9\u05d5\u05d1. +Not\ now=\u05dc\u05d0 \u05e2\u05db\u05e9\u05d9\u05d5 +Settings=\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea +Sign\ out=\u05d4\u05ea\u05e0\u05ea\u05e7 +No\ connection=\u05d0\u05d9\u05df \u05d7\u05d9\u05d1\u05d5\u05e8 +The\ server\ at\ {0}\ did\ not\ answer.=\u05d4\u05e9\u05e8\u05ea \u05d1\u05db\u05ea\u05d5\u05d1\u05ea {0} \u05dc\u05d0 \u05e2\u05e0\u05d4. +Try\ again=\u05e0\u05e1\u05d4 \u05e9\u05d5\u05d1 +Server\ address=\u05db\u05ea\u05d5\u05d1\u05ea \u05d4\u05e9\u05e8\u05ea +Create\ an\ account=\u05e6\u05d5\u05e8 \u05d7\u05e9\u05d1\u05d5\u05df +Name=\u05e9\u05dd +Mobile\ number=\u05de\u05e1\u05e4\u05e8 \u05e0\u05d9\u05d9\u05d3 +Password=\u05e1\u05d9\u05e1\u05de\u05d4 +At\ least\ 8\ characters=\u05dc\u05e4\u05d7\u05d5\u05ea 8 \u05ea\u05d5\u05d5\u05d9\u05dd +Create\ account=\u05e6\u05d5\u05e8 \u05d7\u05e9\u05d1\u05d5\u05df +Server=\u05e9\u05e8\u05ea +The\ address\ of\ the\ Lingo\ server\ this\ app\ talks\ to.\ Changing\ it\ signs\ you\ out.=\u05db\u05ea\u05d5\u05d1\u05ea \u05e9\u05e8\u05ea Lingo \u05e9\u05d4\u05d0\u05e4\u05dc\u05d9\u05e7\u05e6\u05d9\u05d4 \u05e4\u05d5\u05e0\u05d4 \u05d0\u05dc\u05d9\u05d5. \u05e9\u05d9\u05e0\u05d5\u05d9 \u05e9\u05dc\u05d4 \u05d9\u05e0\u05ea\u05e7 \u05d0\u05d5\u05ea\u05da. +Address=\u05db\u05ea\u05d5\u05d1\u05ea +Save=\u05e9\u05de\u05d5\u05e8 +Account=\u05d7\u05e9\u05d1\u05d5\u05df +Notifications=\u05d4\u05ea\u05e8\u05d0\u05d5\u05ea +Appearance=\u05de\u05e8\u05d0\u05d4 +Language=\u05e9\u05e4\u05d4 +Theme=\u05e2\u05e8\u05db\u05ea \u05e0\u05d5\u05e9\u05d0 +System=\u05de\u05e2\u05e8\u05db\u05ea +Light=\u05d1\u05d4\u05d9\u05e8 +Dark=\u05db\u05d4\u05d4 +About=\u05d0\u05d5\u05d3\u05d5\u05ea +Terms\ of\ service=\u05ea\u05e0\u05d0\u05d9 \u05d4\u05e9\u05d9\u05e8\u05d5\u05ea +Privacy\ policy=\u05de\u05d3\u05d9\u05e0\u05d9\u05d5\u05ea \u05e4\u05e8\u05d8\u05d9\u05d5\u05ea +Sign\ in=\u05d4\u05ea\u05d7\u05d1\u05e8 +Enter\ your\ e-mail\ and\ password.=\u05d4\u05d6\u05df \u05d3\u05d5\u05d0"\u05dc \u05d5\u05e1\u05d9\u05e1\u05de\u05d4. + +# Driving applications, payments, the admin console and the account. +Back=\u05d7\u05d6\u05e8\u05d4 +Change\ password=\u05e9\u05d9\u05e0\u05d5\u05d9 \u05e1\u05d9\u05e1\u05de\u05d4 +Change\ the\ password\ you\ sign\ in\ with=\u05e9\u05d9\u05e0\u05d5\u05d9 \u05d4\u05e1\u05d9\u05e1\u05de\u05d4 \u05e9\u05d0\u05d9\u05ea\u05d4 \u05e0\u05db\u05e0\u05e1\u05d9\u05dd +Current\ password=\u05e1\u05d9\u05e1\u05de\u05d4 \u05e0\u05d5\u05db\u05d7\u05d9\u05ea +Delete\ account=\u05de\u05d7\u05d9\u05e7\u05ea \u05d7\u05e9\u05d1\u05d5\u05df +Delete\ my\ account=\u05de\u05d7\u05d9\u05e7\u05ea \u05d4\u05d7\u05e9\u05d1\u05d5\u05df \u05e9\u05dc\u05d9 +Delete\ your\ account?=\u05dc\u05de\u05d7\u05d5\u05e7 \u05d0\u05ea \u05d4\u05d7\u05e9\u05d1\u05d5\u05df? +Keep\ my\ account=\u05dc\u05d4\u05e9\u05d0\u05d9\u05e8 \u05d0\u05ea \u05d4\u05d7\u05e9\u05d1\u05d5\u05df +New\ password=\u05e1\u05d9\u05e1\u05de\u05d4 \u05d7\u05d3\u05e9\u05d4 +New\ password,\ again=\u05e1\u05d9\u05e1\u05de\u05d4 \u05d7\u05d3\u05e9\u05d4, \u05e9\u05d5\u05d1 +Profile=\u05e4\u05e8\u05d5\u05e4\u05d9\u05dc +That\ picture\ could\ not\ be\ read=\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05dc\u05e7\u05e8\u05d5\u05d0 \u05d0\u05ea \u05d4\u05ea\u05de\u05d5\u05e0\u05d4 +The\ two\ new\ passwords\ are\ not\ the\ same.=\u05e9\u05ea\u05d9 \u05d4\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05d4\u05d7\u05d3\u05e9\u05d5\u05ea \u05d0\u05d9\u05e0\u05df \u05d6\u05d4\u05d5\u05ea. +This\ device\ cannot\ prepare\ a\ picture\ to\ send=\u05d4\u05de\u05db\u05e9\u05d9\u05e8 \u05d0\u05d9\u05e0\u05d5 \u05d9\u05db\u05d5\u05dc \u05dc\u05d4\u05db\u05d9\u05df \u05ea\u05de\u05d5\u05e0\u05d4 \u05dc\u05e9\u05dc\u05d9\u05d7\u05d4 +Your\ password\ was\ changed=\u05d4\u05e1\u05d9\u05e1\u05de\u05d4 \u05e9\u05d5\u05e0\u05ea\u05d4 +Usage\ statistics=\u05e0\u05ea\u05d5\u05e0\u05d9 \u05e9\u05d9\u05de\u05d5\u05e9 +Help\ improve\ Lingo=\u05e2\u05d6\u05e8\u05d5 \u05dc\u05e9\u05e4\u05e8 \u05d0\u05ea Lingo +Lingo\ can\ count\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ so\ that\ we\ can\ see\ what\ works\ and\ fix\ what\ does\ not.=Lingo \u05d9\u05db\u05d5\u05dc\u05d4 \u05dc\u05e1\u05e4\u05d5\u05e8 \u05d0\u05d9\u05dc\u05d5 \u05de\u05e1\u05db\u05d9\u05dd \u05e0\u05e4\u05ea\u05d7\u05d9\u05dd \u05d5\u05d1\u05d0\u05d9\u05dc\u05d5 \u05ea\u05db\u05d5\u05e0\u05d5\u05ea \u05de\u05e9\u05ea\u05de\u05e9\u05d9\u05dd, \u05db\u05d3\u05d9 \u05e9\u05e0\u05d5\u05db\u05dc \u05dc\u05e8\u05d0\u05d5\u05ea \u05de\u05d4 \u05e2\u05d5\u05d1\u05d3 \u05d5\u05dc\u05ea\u05e7\u05df \u05d0\u05ea \u05de\u05d4 \u05e9\u05dc\u05d0. +No\ personal\ details=\u05dc\u05dc\u05d0 \u05e4\u05e8\u05d8\u05d9\u05dd \u05d0\u05d9\u05e9\u05d9\u05d9\u05dd +Never\ your\ name,\ e-mail,\ phone\ number,\ places\ or\ card\ details=\u05dc\u05e2\u05d5\u05dc\u05dd \u05dc\u05d0 \u05d4\u05e9\u05dd \u05e9\u05dc\u05da, \u05d4\u05d3\u05d5\u05d0"\u05dc, \u05de\u05e1\u05e4\u05e8 \u05d4\u05d8\u05dc\u05e4\u05d5\u05df, \u05d4\u05de\u05e7\u05d5\u05de\u05d5\u05ea \u05d0\u05d5 \u05e4\u05e8\u05d8\u05d9 \u05d4\u05db\u05e8\u05d8\u05d9\u05e1 +Turn\ it\ on\ or\ off\ at\ any\ time\ in\ Settings=\u05d0\u05e4\u05e9\u05e8 \u05dc\u05d4\u05e4\u05e2\u05d9\u05dc \u05d0\u05d5 \u05dc\u05db\u05d1\u05d5\u05ea \u05d1\u05db\u05dc \u05e2\u05ea \u05d1\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea +Share\ usage\ statistics=\u05e9\u05d9\u05ea\u05d5\u05e3 \u05e0\u05ea\u05d5\u05e0\u05d9 \u05e9\u05d9\u05de\u05d5\u05e9 +The\ server\ changed.\ Sign\ in\ again.=\u05d4\u05e9\u05e8\u05ea \u05d4\u05e9\u05ea\u05e0\u05d4. \u05d9\u05e9 \u05dc\u05d4\u05d9\u05db\u05e0\u05e1 \u05e9\u05d5\u05d1. + +# Lingo: the field and dispatch screens. +Assistant=\u05e2\u05d5\u05d6\u05e8 +Consent=\u05d4\u05e1\u05db\u05de\u05d4 +Lingo=Lingo +Kind=\u05e1\u05d5\u05d2 +Legal=\u05de\u05e9\u05e4\u05d8\u05d9 +Location=\u05de\u05d9\u05e7\u05d5\u05dd +Privacy=\u05e4\u05e8\u05d8\u05d9\u05d5\u05ea +Register=\u05d4\u05e8\u05e9\u05de\u05d4 +Software=\u05ea\u05d5\u05db\u05e0\u05d4 +Starting=\u05de\u05ea\u05d7\u05d9\u05dc +Unreachable=\u05dc\u05d0 \u05d6\u05de\u05d9\u05df \u05d1\u05d8\u05dc\u05e4\u05d5\u05df +Welcome=\u05d1\u05e8\u05d5\u05da \u05d4\u05d1\u05d0 +Your\ name\ and\ mobile\ number=\u05e9\u05de\u05da \u05d5\u05de\u05e1\u05e4\u05e8 \u05d4\u05e0\u05d9\u05d9\u05d3 \u05e9\u05dc\u05da +Close=\u05e1\u05d2\u05d5\u05e8 +Menu=\u05ea\u05e4\u05e8\u05d9\u05d8 +Send=\u05e9\u05dc\u05d7 +Show\ the\ whole\ route=\u05d4\u05e6\u05d2 \u05d0\u05ea \u05db\u05dc \u05d4\u05de\u05e1\u05dc\u05d5\u05dc +# Back-office console, admin pages and the tablet day +All=\u05d4\u05db\u05dc +Creator=\u05e1\u05d3\u05e8\u05df +# Workforce rules, staffing reports and planning rules +This\ week=\u05d4\u05e9\u05d1\u05d5\u05e2 +Certificates=\u05ea\u05e2\u05d5\u05d3\u05d5\u05ea +# Company settings, labour rates, timesheets and the clock +# Company settings, labour rates, timesheets and the clock +# Sign-in and the report draft +E-mail=\u05d3\u05d5\u05d0"\u05dc + + +A\ class\ you\ booked\ is\ starting=\u05e9\u05d9\u05e2\u05d5\u05e8 \u05e9\u05d4\u05d6\u05de\u05e0\u05ea \u05e2\u05d5\u05de\u05d3 \u05dc\u05d4\u05ea\u05d7\u05d9\u05dc +A\ cloud\ model\ answers\ through\ Lingo's\ server.=\u05de\u05d5\u05d3\u05dc \u05d1\u05e2\u05e0\u05df \u05e2\u05d5\u05e0\u05d4 \u05d3\u05e8\u05da \u05d4\u05e9\u05e8\u05ea \u05e9\u05dc Lingo. +A\ nudge\ when\ today's\ goal\ is\ not\ done\ yet=\u05ea\u05d6\u05db\u05d5\u05e8\u05ea \u05db\u05e9\u05d4\u05d9\u05e2\u05d3 \u05e9\u05dc \u05d4\u05d9\u05d5\u05dd \u05e2\u05d3\u05d9\u05d9\u05df \u05dc\u05d0 \u05d4\u05d5\u05e9\u05dc\u05dd +A\ sample\ learning\ app\ built\ with\ Codename\ One=\u05d0\u05e4\u05dc\u05d9\u05e7\u05e6\u05d9\u05d9\u05ea \u05dc\u05d9\u05de\u05d5\u05d3 \u05dc\u05d3\u05d5\u05d2\u05de\u05d4 \u05e9\u05e0\u05d1\u05e0\u05ea\u05d4 \u05e2\u05dd Codename One +A\ scripted\ partner\ keeps\ conversations\ going.\ Download\ the\ offline\ tutor\ or\ turn\ on\ the\ cloud\ tutor\ for\ free\ conversation.=\u05e9\u05d5\u05ea\u05e3 \u05de\u05ea\u05d5\u05e1\u05e8\u05d8 \u05de\u05de\u05e9\u05d9\u05da \u05d0\u05ea \u05d4\u05e9\u05d9\u05d7\u05d4. \u05d4\u05d5\u05e8\u05d9\u05d3\u05d5 \u05d0\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df \u05d0\u05d5 \u05d4\u05e4\u05e2\u05d9\u05dc\u05d5 \u05d0\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d1\u05e2\u05e0\u05df \u05dc\u05e9\u05d9\u05d7\u05d4 \u05d7\u05d5\u05e4\u05e9\u05d9\u05ea. +A\ tip\ for\ {0}=\u05d8\u05d9\u05e4 \u05e2\u05d1\u05d5\u05e8 {0} +AI\ tutor=\u05de\u05d5\u05e8\u05d4 AI +Achievements=\u05d4\u05d9\u05e9\u05d2\u05d9\u05dd +Add=\u05d4\u05d5\u05e1\u05e4\u05d4 +Add\ a\ lesson=\u05d4\u05d5\u05e1\u05e4\u05ea \u05e9\u05d9\u05e2\u05d5\u05e8 +Add\ a\ phrase=\u05d4\u05d5\u05e1\u05e4\u05ea \u05d1\u05d9\u05d8\u05d5\u05d9 +Add\ a\ video,\ phrases\ to\ practise\ or\ a\ conversation\ scene.=\u05d4\u05d5\u05e1\u05d9\u05e4\u05d5 \u05e1\u05e8\u05d8\u05d5\u05df, \u05d1\u05d9\u05d8\u05d5\u05d9\u05d9\u05dd \u05dc\u05ea\u05e8\u05d2\u05d5\u05dc \u05d0\u05d5 \u05e1\u05e6\u05e0\u05ea \u05e9\u05d9\u05d7\u05d4. +An\ AI\ tutor\ that\ listens,\ on\ your\ phone.=\u05de\u05d5\u05e8\u05d4 AI \u05e9\u05de\u05e7\u05e9\u05d9\u05d1, \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05e9\u05dc\u05db\u05dd. +As\ it\ appears\ on\ your\ certificates=\u05db\u05e4\u05d9 \u05e9\u05d6\u05d4 \u05de\u05d5\u05e4\u05d9\u05e2 \u05d1\u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05e9\u05dc\u05db\u05dd +Ask\ a\ question=\u05dc\u05e9\u05d0\u05d5\u05dc \u05e9\u05d0\u05dc\u05d4 +Ask\ for\ prices\ and\ quantities=\u05e9\u05d0\u05dc\u05d5 \u05e2\u05dc \u05de\u05d7\u05d9\u05e8\u05d9\u05dd \u05d5\u05db\u05de\u05d5\u05d9\u05d5\u05ea +Ask\ the\ creator\ and\ other\ learners=\u05e9\u05d0\u05dc\u05d5 \u05d0\u05ea \u05d4\u05d9\u05d5\u05e6\u05e8 \u05d5\u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05d0\u05d7\u05e8\u05d9\u05dd +At\ the\ fruit\ stall=\u05d1\u05d3\u05d5\u05db\u05df \u05d4\u05e4\u05d9\u05e8\u05d5\u05ea +Back\ to\ the\ course=\u05d7\u05d6\u05e8\u05d4 \u05dc\u05e7\u05d5\u05e8\u05e1 +Badge\ unlocked=\u05ea\u05d2 \u05e0\u05e4\u05ea\u05d7 +Badges\ and\ your\ level=\u05ea\u05d2\u05d9\u05dd \u05d5\u05d4\u05e8\u05de\u05d4 \u05e9\u05dc\u05db\u05dd +Be\ the\ first\ to\ ask\ {0}.=\u05d4\u05d9\u05d5 \u05d4\u05e8\u05d0\u05e9\u05d5\u05e0\u05d9\u05dd \u05dc\u05e9\u05d0\u05d5\u05dc \u05d0\u05ea {0}. +Better\:\ {0}=\u05e2\u05d3\u05d9\u05e3: {0} +Book=\u05d4\u05d6\u05de\u05e0\u05d4 +Browse=\u05e2\u05d9\u05d5\u05df +Browse\ courses=\u05e2\u05d9\u05d5\u05df \u05d1\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd +Bundle=\u05d7\u05d1\u05d9\u05dc\u05d4 +Buy\ for\ {0}=\u05e7\u05e0\u05d5 \u05d1-{0} +Certificate=\u05ea\u05e2\u05d5\u05d3\u05d4 +Check=\u05d1\u05d3\u05d9\u05e7\u05d4 +Checking\ the\ signature...=\u05d1\u05d5\u05d3\u05e7\u05d9\u05dd \u05d0\u05ea \u05d4\u05d7\u05ea\u05d9\u05de\u05d4... +Checkout=\u05ea\u05e9\u05dc\u05d5\u05dd +Choose=\u05d1\u05d7\u05d9\u05e8\u05d4 +Cloud\ AI=AI \u05d1\u05e2\u05e0\u05df +Cloud\ AI\ tutor\ on\ any\ phone=\u05de\u05d5\u05e8\u05d4 AI \u05d1\u05e2\u05e0\u05df \u05d1\u05db\u05dc \u05d8\u05dc\u05e4\u05d5\u05df +Cloud\ tutor=\u05de\u05d5\u05e8\u05d4 \u05d1\u05e2\u05e0\u05df +Colour=\u05e6\u05d1\u05e2 +Community=\u05e7\u05d4\u05d9\u05dc\u05d4 +Connect\ to\ Wi-Fi\ to\ download,\ or\ turn\ off\ Wi-Fi\ only.=\u05d4\u05ea\u05d7\u05d1\u05e8\u05d5 \u05dc-Wi-Fi \u05db\u05d3\u05d9 \u05dc\u05d4\u05d5\u05e8\u05d9\u05d3, \u05d0\u05d5 \u05db\u05d1\u05d5 \u05d0\u05ea \u05d4\u05d0\u05e4\u05e9\u05e8\u05d5\u05ea Wi-Fi \u05d1\u05dc\u05d1\u05d3. +Connecting\ to\ {0}...=\u05de\u05ea\u05d7\u05d1\u05e8\u05d9\u05dd \u05d0\u05dc {0}... +Container=\u05de\u05db\u05d5\u05dc\u05d4 +Continue=\u05d4\u05de\u05e9\u05da +Continue\:\ {0}=\u05d4\u05de\u05e9\u05da: {0} +Conversation=\u05e9\u05d9\u05d7\u05d4 +Cookie=Cookie +Course=\u05e7\u05d5\u05e8\u05e1 +Course\ complete\!=\u05d4\u05e7\u05d5\u05e8\u05e1 \u05d4\u05d5\u05e9\u05dc\u05dd! +Courses=\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd +Courses\ and\ live\ classes\ from\ real\ teachers=\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05d5\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd \u05de\u05de\u05d5\u05e8\u05d9\u05dd \u05d0\u05de\u05d9\u05ea\u05d9\u05d9\u05dd +Courses,\ classes\ and\ tips=\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd, \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d5\u05d8\u05d9\u05e4\u05d9\u05dd +Create\ course=\u05d9\u05e6\u05d9\u05e8\u05ea \u05e7\u05d5\u05e8\u05e1 +Creator\ studio=\u05e1\u05d8\u05d5\u05d3\u05d9\u05d5 \u05d9\u05d5\u05e6\u05e8\u05d9\u05dd +Creators\ schedule\ live\ classes\ from\ their\ studio.=\u05d9\u05d5\u05e6\u05e8\u05d9\u05dd \u05e7\u05d5\u05d1\u05e2\u05d9\u05dd \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd \u05de\u05d4\u05e1\u05d8\u05d5\u05d3\u05d9\u05d5 \u05e9\u05dc\u05d4\u05dd. +Daily\ goal\ met=\u05d9\u05e2\u05d3 \u05d9\u05d5\u05de\u05d9 \u05d4\u05d5\u05e9\u05d2 +Day\ streak=\u05d9\u05de\u05d9 \u05e8\u05e6\u05e3 +Demo\ card\ ending\ 4242=\u05db\u05e8\u05d8\u05d9\u05e1 \u05d4\u05d3\u05d2\u05de\u05d4 \u05e9\u05de\u05e1\u05ea\u05d9\u05d9\u05dd \u05d1-4242 +Discover=\u05d2\u05d9\u05dc\u05d5\u05d9 +Do\ a\ lesson\ today\ to\ start\ a\ streak.=\u05e2\u05e9\u05d5 \u05e9\u05d9\u05e2\u05d5\u05e8 \u05d4\u05d9\u05d5\u05dd \u05db\u05d3\u05d9 \u05dc\u05d4\u05ea\u05d7\u05d9\u05dc \u05e8\u05e6\u05e3. +Download=\u05d4\u05d5\u05e8\u05d3\u05d4 +Download\ 470\ MB?=\u05dc\u05d4\u05d5\u05e8\u05d9\u05d3 470 MB? +Download\ on\ Wi-Fi\ only=\u05d4\u05d5\u05e8\u05d3\u05d4 \u05d1-Wi-Fi \u05d1\u05dc\u05d1\u05d3 +Download\ the\ offline\ tutor=\u05d4\u05d5\u05e8\u05d3\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df +Downloaded\ AI,\ on\ this\ phone=AI \u05e9\u05d4\u05d5\u05e8\u05d3, \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4 +Downloading\ the\ offline\ tutor=\u05de\u05d5\u05e8\u05d9\u05d3 \u05d0\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df +Draft=\u05d8\u05d9\u05d5\u05d8\u05d4 +Drafts=\u05d8\u05d9\u05d5\u05d8\u05d5\u05ea +EEEE,\ MMM\ d=EEEE, d MMM +Earn\ XP\ in\ lessons\ to\ climb.\ Keep\ your\ streak\ for\ bonus\ freezes.=\u05e6\u05d1\u05e8\u05d5 XP \u05d1\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05db\u05d3\u05d9 \u05dc\u05e2\u05dc\u05d5\u05ea. \u05e9\u05de\u05e8\u05d5 \u05e2\u05dc \u05d4\u05e8\u05e6\u05e3 \u05dc\u05e7\u05d1\u05dc\u05ea \u05d4\u05e7\u05e4\u05d0\u05d5\u05ea \u05d1\u05d5\u05e0\u05d5\u05e1. +End=\u05e1\u05d9\u05d5\u05dd +Enrol\ for\ free=\u05d4\u05e8\u05e9\u05de\u05d4 \u05d1\u05d7\u05d9\u05e0\u05dd +Enrol\ in\ a\ course\ and\ it\ shows\ up\ here.=\u05d4\u05d9\u05e8\u05e9\u05de\u05d5 \u05dc\u05e7\u05d5\u05e8\u05e1 \u05d5\u05d4\u05d5\u05d0 \u05d9\u05d5\u05e4\u05d9\u05e2 \u05db\u05d0\u05df. +Every\ AI\ course=\u05db\u05dc \u05e7\u05d5\u05e8\u05e1\u05d9 \u05d4-AI +Everything\ in\ Free=\u05db\u05dc \u05de\u05d4 \u05e9\u05d9\u05e9 \u05d1-Free +Excellent\!=\u05de\u05e6\u05d5\u05d9\u05df! +Finish\ conversation=\u05e1\u05d9\u05d5\u05dd \u05d4\u05e9\u05d9\u05d7\u05d4 +Finish\ every\ lesson\ of\ a\ course\ to\ earn\ a\ signed\ certificate.=\u05e1\u05d9\u05d9\u05de\u05d5 \u05d0\u05ea \u05db\u05dc \u05d4\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d1\u05e7\u05d5\u05e8\u05e1 \u05db\u05d3\u05d9 \u05dc\u05e7\u05d1\u05dc \u05ea\u05e2\u05d5\u05d3\u05d4 \u05d7\u05ea\u05d5\u05de\u05d4. +Finish\ lesson=\u05e1\u05d9\u05d5\u05dd \u05d4\u05e9\u05d9\u05e2\u05d5\u05e8 +Five\ minutes\ a\ day=\u05d7\u05de\u05e9 \u05d3\u05e7\u05d5\u05ea \u05d1\u05d9\u05d5\u05dd +Free=\u05d7\u05d9\u05e0\u05dd +Frees\ 470\ MB.\ You\ can\ download\ it\ again.=\u05e4\u05d5\u05ea\u05d7 470 MB. \u05d0\u05e4\u05e9\u05e8 \u05dc\u05d4\u05d5\u05e8\u05d9\u05d3 \u05e9\u05d5\u05d1. +Genuine,\ signed\ by\ {0}=\u05de\u05e7\u05d5\u05e8\u05d9\u05ea, \u05d7\u05ea\u05d5\u05de\u05d4 \u05e2\u05dc \u05d9\u05d3\u05d9 {0} +Get\ the\ offline\ AI\ tutor=\u05e7\u05d1\u05dc\u05d5 \u05d0\u05ea \u05de\u05d5\u05e8\u05d4 \u05d4-AI \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df +Give\ the\ class\ a\ title=\u05ea\u05e0\u05d5 \u05db\u05d5\u05ea\u05e8\u05ea \u05dc\u05e9\u05d9\u05e2\u05d5\u05e8 +Give\ the\ course\ a\ title=\u05ea\u05e0\u05d5 \u05db\u05d5\u05ea\u05e8\u05ea \u05dc\u05e7\u05d5\u05e8\u05e1 +Go\ Pro=\u05e9\u05d3\u05e8\u05d2\u05d5 \u05dc-Pro +Go\ Pro\ for\ {0}=\u05e9\u05d3\u05e8\u05d2\u05d5 \u05dc-Pro \u05d1-{0} +Go\ live=\u05d4\u05ea\u05d7\u05dc\u05ea \u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9 +Goal\ met\!=\u05d4\u05d9\u05e2\u05d3 \u05d4\u05d5\u05e9\u05d2! +Good\ afternoon=\u05e6\u05d4\u05e8\u05d9\u05d9\u05dd \u05d8\u05d5\u05d1\u05d9\u05dd +Good\ evening=\u05e2\u05e8\u05d1 \u05d8\u05d5\u05d1 +Good\ morning=\u05d1\u05d5\u05e7\u05e8 \u05d8\u05d5\u05d1 +Great\ job\!=\u05db\u05dc \u05d4\u05db\u05d1\u05d5\u05d3! +HH\:mm=HH:mm +Heard\:\ "{0}"=\u05e0\u05e9\u05de\u05e2: "{0}" +How\ much\ is\ it?=\u05db\u05de\u05d4 \u05d6\u05d4 \u05e2\u05d5\u05dc\u05d4? +I've\ watched\ it=\u05e6\u05e4\u05d9\u05ea\u05d9 \u05d1\u05d5 +In\ one\ line=\u05d1\u05e9\u05d5\u05e8\u05d4 \u05d0\u05d7\u05ea +Join=\u05d4\u05e6\u05d8\u05e8\u05e4\u05d5\u05ea +Keep\ talking=\u05d4\u05de\u05e9\u05d9\u05db\u05d5 \u05dc\u05d3\u05d1\u05e8 +Leaderboard=\u05dc\u05d5\u05d7 \u05d4\u05de\u05d5\u05d1\u05d9\u05dc\u05d9\u05dd +Learn=\u05dc\u05de\u05d9\u05d3\u05d4 +Learning=\u05dc\u05d5\u05de\u05d3\u05d9\u05dd +Led\ by\ the\ AI\ tutor=\u05d1\u05d4\u05e0\u05d7\u05d9\u05d9\u05ea \u05de\u05d5\u05e8\u05d4 \u05d4-AI +Length=\u05d0\u05d5\u05e8\u05da +Lesson\ complete\!=\u05d4\u05e9\u05d9\u05e2\u05d5\u05e8 \u05d4\u05d5\u05e9\u05dc\u05dd! +Lesson\ {0}\ of\ {1}=\u05e9\u05d9\u05e2\u05d5\u05e8 {0} \u05de\u05ea\u05d5\u05da {1} +Lessons=\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd +Let's\ try\ that\ again=\u05d1\u05d5\u05d0\u05d5 \u05e0\u05e0\u05e1\u05d4 \u05e9\u05d5\u05d1 +Level=\u05e8\u05de\u05d4 +Level\ {0}=\u05e8\u05de\u05d4 {0} +Lifetime\ access,\ by\ {0}=\u05d2\u05d9\u05e9\u05d4 \u05dc\u05db\u05dc \u05d4\u05d7\u05d9\u05d9\u05dd, \u05de\u05d0\u05ea {0} +Lingo\ Pro=Lingo Pro +Lingo\ is\ a\ sample.\ Payments\ are\ simulated\ and\ certificates\ are\ signed\ with\ a\ demonstration\ key.=Lingo \u05d4\u05d9\u05d0 \u05d3\u05d5\u05d2\u05de\u05d4. \u05d4\u05ea\u05e9\u05dc\u05d5\u05de\u05d9\u05dd \u05de\u05d3\u05d5\u05de\u05d9\u05dd \u05d5\u05d4\u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05e0\u05d7\u05ea\u05de\u05d5\u05ea \u05d1\u05de\u05e4\u05ea\u05d7 \u05d4\u05d3\u05d2\u05de\u05d4. +Lingo\ is\ free.\ Pro\ pays\ for\ the\ creators\ and\ the\ servers,\ and\ gives\ you\ more.=Lingo \u05d1\u05d7\u05d9\u05e0\u05dd. Pro \u05de\u05e9\u05dc\u05dd \u05dc\u05d9\u05d5\u05e6\u05e8\u05d9\u05dd \u05d5\u05dc\u05e9\u05e8\u05ea\u05d9\u05dd, \u05d5\u05e0\u05d5\u05ea\u05df \u05dc\u05db\u05dd \u05d9\u05d5\u05ea\u05e8. +Lingo\ needs\ the\ camera\ and\ microphone\ for\ live\ classes=Lingo \u05e6\u05e8\u05d9\u05db\u05d4 \u05de\u05e6\u05dc\u05de\u05d4 \u05d5\u05de\u05d9\u05e7\u05e8\u05d5\u05e4\u05d5\u05df \u05dc\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd +Listen=\u05d4\u05d0\u05d6\u05e0\u05d4 +Listening\ failed.\ Check\ the\ microphone\ permission.=\u05d4\u05d4\u05d0\u05d6\u05e0\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4. \u05d1\u05d3\u05e7\u05d5 \u05d0\u05ea \u05d4\u05e8\u05e9\u05d0\u05ea \u05d4\u05de\u05d9\u05e7\u05e8\u05d5\u05e4\u05d5\u05df. +Listening...=\u05de\u05d0\u05d6\u05d9\u05e0\u05d9\u05dd... +Live=\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9 +Live\ classes=\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd +Live\ soon=\u05d1\u05e7\u05e8\u05d5\u05d1 \u05d1\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9 +Live\ video\ needs\ the\ phone\ app.\ The\ class\ is\ on\:\ open\ Lingo\ on\ iOS\ or\ Android\ to\ take\ part.=\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d5\u05d9\u05d3\u05d0\u05d5 \u05d7\u05d9 \u05d3\u05d5\u05e8\u05e9 \u05d0\u05ea \u05d0\u05e4\u05dc\u05d9\u05e7\u05e6\u05d9\u05d9\u05ea \u05d4\u05d8\u05dc\u05e4\u05d5\u05df. \u05d4\u05e9\u05d9\u05e2\u05d5\u05e8 \u05e4\u05e2\u05d9\u05dc: \u05e4\u05ea\u05d7\u05d5 \u05d0\u05ea Lingo \u05d1-iOS \u05d0\u05d5 \u05d1\u05d0\u05e0\u05d3\u05e8\u05d5\u05d0\u05d9\u05d3 \u05db\u05d3\u05d9 \u05dc\u05d4\u05e9\u05ea\u05ea\u05e3. +Live\ with\ {0}=\u05d1\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9 \u05e2\u05dd {0} +MMM\ d,\ HH\:mm=d MMM, HH:mm +MMM\ d,\ yyyy=d MMM yyyy +Make\ a\ course\ of\ videos,\ phrases\ and\ conversations.=\u05e6\u05e8\u05d5 \u05e7\u05d5\u05e8\u05e1 \u05de\u05e1\u05e8\u05d8\u05d5\u05e0\u05d9\u05dd, \u05d1\u05d9\u05d8\u05d5\u05d9\u05d9\u05dd \u05d5\u05e9\u05d9\u05d7\u05d5\u05ea. +Me=\u05d0\u05e0\u05d9 +Monday,\ Nov\ 16=\u05d9\u05d5\u05dd \u05e9\u05e0\u05d9, 16 \u05d1\u05e0\u05d5\u05d1\u05f3 +Monthly,\ cancel\ any\ time=\u05d7\u05d5\u05d3\u05e9\u05d9, \u05d0\u05e4\u05e9\u05e8 \u05dc\u05d1\u05d8\u05dc \u05d1\u05db\u05dc \u05e2\u05ea +My\ Lingo\ certificate=\u05ea\u05e2\u05d5\u05d3\u05ea Lingo \u05e9\u05dc\u05d9 +My\ courses=\u05d4\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05e9\u05dc\u05d9 +Nearly\ there=\u05db\u05de\u05e2\u05d8 \u05e9\u05dd +New=\u05d7\u05d3\u05e9 +New\ course=\u05e7\u05d5\u05e8\u05e1 \u05d7\u05d3\u05e9 +New\ lesson=\u05e9\u05d9\u05e2\u05d5\u05e8 \u05d7\u05d3\u05e9 +No\ certificates\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05ea\u05e2\u05d5\u05d3\u05d5\u05ea +No\ lessons\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd +No\ live\ classes\ are\ scheduled\ yet.=\u05e2\u05d3\u05d9\u05d9\u05df \u05dc\u05d0 \u05e0\u05e7\u05d1\u05e2\u05d5 \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd. +No\ questions\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05e9\u05d0\u05dc\u05d5\u05ea +No\ video\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05e1\u05e8\u05d8\u05d5\u05df +Nothing\ bought\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05dc\u05d0 \u05e0\u05e7\u05e0\u05d4 \u05d3\u05d1\u05e8 +Nothing\ here\ yet=\u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05db\u05d0\u05df \u05db\u05dc\u05d5\u05dd +Nothing\ scheduled=\u05dc\u05d0 \u05e0\u05e7\u05d1\u05e2 \u05d3\u05d1\u05e8 +Nothing\ was\ heard.\ Tap\ the\ microphone\ and\ speak.=\u05dc\u05d0 \u05e0\u05e9\u05de\u05e2 \u05d3\u05d1\u05e8. \u05d4\u05e7\u05d9\u05e9\u05d5 \u05e2\u05dc \u05d4\u05de\u05d9\u05e7\u05e8\u05d5\u05e4\u05d5\u05df \u05d5\u05d3\u05d1\u05e8\u05d5. +On-device\ AI=AI \u05d1\u05de\u05db\u05e9\u05d9\u05e8 +On-device\ AI\ tutor=\u05de\u05d5\u05e8\u05d4 AI \u05d1\u05de\u05db\u05e9\u05d9\u05e8 +One\ streak\ freeze=\u05d4\u05e7\u05e4\u05d0\u05ea \u05e8\u05e6\u05e3 \u05d0\u05d7\u05ea +Order,\ haggle\ and\ chat\ with\ stallholders=\u05d4\u05d6\u05de\u05d9\u05e0\u05d5, \u05ea\u05ea\u05de\u05e7\u05d7\u05d5 \u05d5\u05ea\u05e9\u05d5\u05d7\u05d7\u05d5 \u05e2\u05dd \u05d1\u05e2\u05dc\u05d9 \u05d4\u05d3\u05d5\u05db\u05e0\u05d9\u05dd +Paid\ courses,\ live\ classes\ and\ tips\ show\ up\ here.=\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05d1\u05ea\u05e9\u05dc\u05d5\u05dd, \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd \u05d5\u05d8\u05d9\u05e4\u05d9\u05dd \u05d9\u05d5\u05e4\u05d9\u05e2\u05d5 \u05db\u05d0\u05df. +Pay\ {0}=\u05ea\u05e9\u05dc\u05d5\u05dd {0} +Payment\ complete=\u05d4\u05ea\u05e9\u05dc\u05d5\u05dd \u05d4\u05d5\u05e9\u05dc\u05dd +Phrases=\u05d1\u05d9\u05d8\u05d5\u05d9\u05d9\u05dd +Phrases\ to\ say\ aloud=\u05d1\u05d9\u05d8\u05d5\u05d9\u05d9\u05dd \u05dc\u05d5\u05de\u05e8 \u05d1\u05e7\u05d5\u05dc +Pick\ up\ Riley=\u05d7\u05d6\u05e8\u05d5 \u05dc\u05e9\u05d5\u05d7\u05d7 \u05e2\u05dd Riley +Pick\ your\ first\ course=\u05d1\u05d7\u05e8\u05d5 \u05d0\u05ea \u05d4\u05e7\u05d5\u05e8\u05e1 \u05d4\u05e8\u05d0\u05e9\u05d5\u05df \u05e9\u05dc\u05db\u05dd +Practice\ now=\u05ea\u05e8\u05d2\u05d5\u05dc \u05e2\u05db\u05e9\u05d9\u05d5 +Practice\ partner=\u05e9\u05d5\u05ea\u05e3 \u05dc\u05ea\u05e8\u05d2\u05d5\u05dc +Practice\ reminder=\u05ea\u05d6\u05db\u05d5\u05e8\u05ea \u05dc\u05ea\u05e8\u05d2\u05d5\u05dc +Practise\ again=\u05ea\u05e8\u05d2\u05d5\u05dc \u05e0\u05d5\u05e1\u05e3 +Practise\ speaking\ with\ an\ AI\ tutor,\ keep\ a\ streak\ and\ earn\ signed\ certificates.=\u05ea\u05e8\u05d2\u05dc\u05d5 \u05d3\u05d9\u05d1\u05d5\u05e8 \u05e2\u05dd \u05de\u05d5\u05e8\u05d4 AI, \u05e9\u05de\u05e8\u05d5 \u05e2\u05dc \u05e8\u05e6\u05e3 \u05d5\u05e7\u05d1\u05dc\u05d5 \u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05d7\u05ea\u05d5\u05de\u05d5\u05ea. +Practise\ with\ the\ AI\ tutor,\ or\ learn\ from\ people\ who\ teach.=\u05ea\u05e8\u05d2\u05dc\u05d5 \u05e2\u05dd \u05de\u05d5\u05e8\u05d4 \u05d4-AI, \u05d0\u05d5 \u05dc\u05de\u05d3\u05d5 \u05de\u05d0\u05e0\u05e9\u05d9\u05dd \u05e9\u05de\u05dc\u05de\u05d3\u05d9\u05dd. +Practise\ without\ limits=\u05ea\u05e8\u05d2\u05d5\u05dc \u05dc\u05dc\u05d0 \u05d4\u05d2\u05d1\u05dc\u05d4 +Practised=\u05ea\u05d5\u05e8\u05d2\u05dc +Price=\u05de\u05d7\u05d9\u05e8 +Pro=Pro +Progress=\u05d4\u05ea\u05e7\u05d3\u05de\u05d5\u05ea +Pronunciation=\u05d4\u05d2\u05d9\u05d9\u05d4 +Pronunciation\ scored\ word\ by\ word,\ on\ your\ phone=\u05e6\u05d9\u05d5\u05df \u05d4\u05d2\u05d9\u05d9\u05d4 \u05de\u05d9\u05dc\u05d4 \u05d0\u05d7\u05e8 \u05de\u05d9\u05dc\u05d4, \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05e9\u05dc\u05db\u05dd +Publish=\u05e4\u05e8\u05e1\u05d5\u05dd +Published=\u05e4\u05d5\u05e8\u05e1\u05dd +Purchases=\u05e8\u05db\u05d9\u05e9\u05d5\u05ea +Push\ registration\ failed\:\ =\u05e8\u05d9\u05e9\u05d5\u05dd \u05dc-Push \u05e0\u05db\u05e9\u05dc: +Qa=\u05e9&\u05ea +Questions=\u05e9\u05d0\u05dc\u05d5\u05ea +Questions\ and\ answers=\u05e9\u05d0\u05dc\u05d5\u05ea \u05d5\u05ea\u05e9\u05d5\u05d1\u05d5\u05ea +Qwen2.5\ 0.5B,\ 470\ MB.\ Runs\ privately\ on\ this\ phone.=Qwen2.5 0.5B, 470 MB. \u05e4\u05d5\u05e2\u05dc \u05d1\u05d0\u05d5\u05e4\u05df \u05e4\u05e8\u05d8\u05d9 \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4. +Ready\ for\ today's\ practice?=\u05de\u05d5\u05db\u05e0\u05d9\u05dd \u05dc\u05ea\u05e8\u05d2\u05d5\u05dc \u05e9\u05dc \u05d4\u05d9\u05d5\u05dd? +Record=\u05d4\u05e7\u05dc\u05d8\u05d4 +Reminders,\ theme,\ privacy=\u05ea\u05d6\u05db\u05d5\u05e8\u05d5\u05ea, \u05e2\u05e8\u05db\u05ea \u05e0\u05d5\u05e9\u05d0, \u05e4\u05e8\u05d8\u05d9\u05d5\u05ea +Remove\ the\ offline\ tutor=\u05d4\u05e1\u05e8\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df +Reply=\u05ea\u05d2\u05d5\u05d1\u05d4 +Reply\ in\ {0}=\u05ea\u05d2\u05d5\u05d1\u05d4 \u05d1{0} +Replying\ to\ {0}=\u05de\u05e9\u05d9\u05d1\u05d9\u05dd \u05dc{0} +Reward=\u05e4\u05e8\u05e1 +Rolling\ your\ R,\ live=\u05de\u05d2\u05dc\u05d2\u05dc\u05d9\u05dd \u05d0\u05ea \u05d4-R, \u05d1\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9 +Runs\ on\ this\ phone.\ Free,\ private,\ 470\ MB.=\u05e4\u05d5\u05e2\u05dc \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4. \u05d7\u05d9\u05e0\u05dd, \u05e4\u05e8\u05d8\u05d9, 470 MB. +Save\ lesson=\u05e9\u05de\u05d9\u05e8\u05ea \u05d4\u05e9\u05d9\u05e2\u05d5\u05e8 +Say\ thanks\ with\ $2.\ All\ of\ it\ goes\ to\ them.=\u05d0\u05de\u05e8\u05d5 \u05ea\u05d5\u05d3\u05d4 \u05e2\u05dd $2. \u05d4\u05db\u05d5\u05dc \u05d4\u05d5\u05dc\u05da \u05d0\u05dc\u05d9\u05d4\u05dd. +Schedule=\u05e7\u05d1\u05d9\u05e2\u05ea \u05de\u05d5\u05e2\u05d3 +Schedule\ a\ class=\u05e7\u05d1\u05d9\u05e2\u05ea \u05e9\u05d9\u05e2\u05d5\u05e8 +Scheduled.\ Learners\ can\ book\ seats\ now.=\u05e0\u05e7\u05d1\u05e2. \u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05d9\u05db\u05d5\u05dc\u05d9\u05dd \u05dc\u05d4\u05d6\u05de\u05d9\u05df \u05de\u05e7\u05d5\u05de\u05d5\u05ea \u05e2\u05db\u05e9\u05d9\u05d5. +Score=\u05e6\u05d9\u05d5\u05df +Seat\ price=\u05de\u05d7\u05d9\u05e8 \u05dc\u05de\u05e7\u05d5\u05dd +Seats=\u05de\u05e7\u05d5\u05de\u05d5\u05ea +See\ all=\u05d4\u05e6\u05d2 \u05d4\u05db\u05d5\u05dc +See\ who\ is\ practising\ most=\u05e8\u05d0\u05d5 \u05de\u05d9 \u05de\u05ea\u05e8\u05d2\u05dc \u05d4\u05db\u05d9 \u05d4\u05e8\u05d1\u05d4 +Set-Cookie=Set-Cookie +Share\ certificate=\u05e9\u05d9\u05ea\u05d5\u05e3 \u05d4\u05ea\u05e2\u05d5\u05d3\u05d4 +Share\ which\ screens\ and\ features\ are\ used.\ Never\ your\ name,\ voice\ or\ what\ you\ say.=\u05e9\u05ea\u05e4\u05d5 \u05d0\u05d9\u05dc\u05d5 \u05de\u05e1\u05db\u05d9\u05dd \u05d5\u05ea\u05db\u05d5\u05e0\u05d5\u05ea \u05d1\u05e9\u05d9\u05de\u05d5\u05e9. \u05d0\u05e3 \u05e4\u05e2\u05dd \u05dc\u05d0 \u05d0\u05ea \u05e9\u05de\u05db\u05dd, \u05e7\u05d5\u05dc\u05db\u05dd \u05d0\u05d5 \u05de\u05d4 \u05e9\u05d0\u05ea\u05dd \u05d0\u05d5\u05de\u05e8\u05d9\u05dd. +Signed\ certificates=\u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05d7\u05ea\u05d5\u05de\u05d5\u05ea +Signed\ certificates\ anyone\ can\ verify=\u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05d7\u05ea\u05d5\u05de\u05d5\u05ea \u05e9\u05db\u05dc \u05d0\u05d7\u05d3 \u05d9\u05db\u05d5\u05dc \u05dc\u05d0\u05de\u05ea +Signed\ proof\ of\ every\ course\ you\ finish=\u05d4\u05d5\u05db\u05d7\u05d4 \u05d7\u05ea\u05d5\u05de\u05d4 \u05dc\u05db\u05dc \u05e7\u05d5\u05e8\u05e1 \u05e9\u05e1\u05d9\u05d9\u05de\u05ea\u05dd +Slowly=\u05dc\u05d0\u05d8 +Small\ groups\ with\ a\ real\ teacher,\ on\ video.=\u05e7\u05d1\u05d5\u05e6\u05d5\u05ea \u05e7\u05d8\u05e0\u05d5\u05ea \u05e2\u05dd \u05de\u05d5\u05e8\u05d4 \u05d0\u05de\u05d9\u05ea\u05d9, \u05d1\u05d5\u05d5\u05d9\u05d3\u05d0\u05d5. +Spanish\ for\ the\ market=\u05e1\u05e4\u05e8\u05d3\u05d9\u05ea \u05dc\u05e9\u05d5\u05e7 +Speak\ a\ new\ language\ with\ an\ AI\ tutor\ that\ listens.=\u05d3\u05d1\u05e8\u05d5 \u05d1\u05e9\u05e4\u05d4 \u05d7\u05d3\u05e9\u05d4 \u05e2\u05dd \u05de\u05d5\u05e8\u05d4 AI \u05e9\u05de\u05e7\u05e9\u05d9\u05d1. +Speech\ recognition\ and\ the\ AI\ tutor\ run\ on\ this\ phone.\ What\ you\ say\ leaves\ it\ only\ if\ you\ turn\ on\ the\ cloud\ tutor.\ Your\ progress\ and\ settings\ are\ kept\ with\ your\ account\ on\ the\ server\ you\ signed\ in\ to.=\u05d6\u05d9\u05d4\u05d5\u05d9 \u05d4\u05d3\u05d9\u05d1\u05d5\u05e8 \u05d5\u05de\u05d5\u05e8\u05d4 \u05d4-AI \u05e4\u05d5\u05e2\u05dc\u05d9\u05dd \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4. \u05de\u05d4 \u05e9\u05d0\u05ea\u05dd \u05d0\u05d5\u05de\u05e8\u05d9\u05dd \u05d9\u05d5\u05e6\u05d0 \u05de\u05de\u05e0\u05d5 \u05e8\u05e7 \u05d0\u05dd \u05ea\u05e4\u05e2\u05d9\u05dc\u05d5 \u05d0\u05ea \u05d4\u05de\u05d5\u05e8\u05d4 \u05d1\u05e2\u05e0\u05df. \u05d4\u05d4\u05ea\u05e7\u05d3\u05de\u05d5\u05ea \u05d5\u05d4\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e9\u05dc\u05db\u05dd \u05e0\u05e9\u05de\u05e8\u05d5\u05ea \u05d1\u05d7\u05e9\u05d1\u05d5\u05df \u05e9\u05dc\u05db\u05dd \u05d1\u05e9\u05e8\u05ea \u05e9\u05d0\u05dc\u05d9\u05d5 \u05d4\u05ea\u05d7\u05d1\u05e8\u05ea\u05dd. +Speech\ recognition\ and\ the\ voice\ always\ run\ on\ the\ phone.=\u05d6\u05d9\u05d4\u05d5\u05d9 \u05d4\u05d3\u05d9\u05d1\u05d5\u05e8 \u05d5\u05d4\u05e7\u05d5\u05dc \u05ea\u05de\u05d9\u05d3 \u05e4\u05d5\u05e2\u05dc\u05d9\u05dd \u05d1\u05d8\u05dc\u05e4\u05d5\u05df. +Start\ course=\u05d4\u05ea\u05d7\u05dc\u05ea \u05d4\u05e7\u05d5\u05e8\u05e1 +Start\ learning=\u05d4\u05ea\u05d7\u05d9\u05dc\u05d5 \u05dc\u05dc\u05de\u05d5\u05d3 +Starts=\u05de\u05ea\u05d7\u05d9\u05dc +Still\ looking=\u05e2\u05d3\u05d9\u05d9\u05df \u05de\u05d7\u05e4\u05e9\u05d9\u05dd +Studio=\u05e1\u05d8\u05d5\u05d3\u05d9\u05d5 +Support\ the\ creators\ you\ learn\ from=\u05ea\u05de\u05db\u05d5 \u05d1\u05d9\u05d5\u05e6\u05e8\u05d9\u05dd \u05e9\u05d0\u05ea\u05dd \u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05de\u05d4\u05dd +Talk=\u05d3\u05d9\u05d1\u05d5\u05e8 +Tap\ and\ speak=\u05d4\u05e7\u05d9\u05e9\u05d5 \u05d5\u05d3\u05d1\u05e8\u05d5 +Teach\ a\ small\ group\ on\ video.\ Learners\ book\ seats,\ free\ or\ paid.=\u05dc\u05de\u05d3\u05d5 \u05e7\u05d1\u05d5\u05e6\u05d4 \u05e7\u05d8\u05e0\u05d4 \u05d1\u05d5\u05d5\u05d9\u05d3\u05d0\u05d5. \u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05de\u05d6\u05de\u05d9\u05e0\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d5\u05ea, \u05d1\u05d7\u05d9\u05e0\u05dd \u05d0\u05d5 \u05d1\u05ea\u05e9\u05dc\u05d5\u05dd. +Teach\ what\ you\ know=\u05dc\u05de\u05d3\u05d5 \u05d0\u05ea \u05de\u05d4 \u05e9\u05d0\u05ea\u05dd \u05d9\u05d5\u05d3\u05e2\u05d9\u05dd +Thank\ you\ for\ supporting\ {0}=\u05ea\u05d5\u05d3\u05d4 \u05e2\u05dc \u05d4\u05ea\u05de\u05d9\u05db\u05d4 \u05d1{0} +The\ certificate\ could\ not\ be\ saved=\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05d4\u05d9\u05d4 \u05dc\u05e9\u05de\u05d5\u05e8 \u05d0\u05ea \u05d4\u05ea\u05e2\u05d5\u05d3\u05d4 +The\ class\ has\ ended=\u05d4\u05e9\u05d9\u05e2\u05d5\u05e8 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd +The\ download\ failed.\ Try\ again\ later.=\u05d4\u05d4\u05d5\u05e8\u05d3\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4. \u05e0\u05e1\u05d5 \u05e9\u05d5\u05d1 \u05de\u05d0\u05d5\u05d7\u05e8 \u05d9\u05d5\u05ea\u05e8. +The\ model\ you\ downloaded\ answers,\ on\ this\ phone.\ Works\ offline.=\u05d4\u05de\u05d5\u05d3\u05dc \u05e9\u05d4\u05d5\u05e8\u05d3\u05ea\u05dd \u05e2\u05d5\u05e0\u05d4 \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4. \u05e2\u05d5\u05d1\u05d3 \u05d2\u05dd \u05dc\u05dc\u05d0 \u05d7\u05d9\u05d1\u05d5\u05e8. +The\ offline\ tutor\ is\ ready=\u05d4\u05de\u05d5\u05e8\u05d4 \u05d4\u05dc\u05d0 \u05de\u05e7\u05d5\u05d5\u05df \u05de\u05d5\u05db\u05df +The\ on-device\ language\ model\ is\ large;\ wait\ for\ Wi-Fi\ to\ fetch\ it=\u05de\u05d5\u05d3\u05dc \u05d4\u05e9\u05e4\u05d4 \u05d1\u05de\u05db\u05e9\u05d9\u05e8 \u05d2\u05d3\u05d5\u05dc; \u05d4\u05de\u05ea\u05d9\u05e0\u05d5 \u05dc-Wi-Fi \u05db\u05d3\u05d9 \u05dc\u05d4\u05d5\u05e8\u05d9\u05d3 \u05d0\u05d5\u05ea\u05d5 +The\ scene\ the\ AI\ tutor\ plays=\u05d4\u05e1\u05e6\u05e0\u05d4 \u05e9\u05de\u05d5\u05e8\u05d4 \u05d4-AI \u05de\u05e9\u05d7\u05e7 +The\ signature\ does\ not\ match=\u05d4\u05d7\u05ea\u05d9\u05de\u05d4 \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05ea +The\ tutor\ could\ not\ answer\:\ =\u05d4\u05de\u05d5\u05e8\u05d4 \u05dc\u05d0 \u05d4\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e2\u05e0\u05d5\u05ea: +The\ tutor\ had\ nothing\ to\ say.\ Try\ again.=\u05dc\u05de\u05d5\u05e8\u05d4 \u05dc\u05d0 \u05d4\u05d9\u05d4 \u05de\u05d4 \u05dc\u05d5\u05de\u05e8. \u05e0\u05e1\u05d5 \u05e9\u05d5\u05d1. +The\ tutor\ model\ is\ downloaded\ once\ and\ stays\ on\ this\ phone.=\u05de\u05d5\u05d3\u05dc \u05d4\u05de\u05d5\u05e8\u05d4 \u05d9\u05d5\u05e8\u05d3 \u05e4\u05e2\u05dd \u05d0\u05d7\u05ea \u05d5\u05e0\u05e9\u05d0\u05e8 \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4. +The\ tutor\ stays\ in\ the\ scene,\ speaks\ the\ course's\ language\ at\ its\ level,\ and\ corrects\ mistakes.=\u05d4\u05de\u05d5\u05e8\u05d4 \u05e0\u05e9\u05d0\u05e8 \u05d1\u05e1\u05e6\u05e0\u05d4, \u05de\u05d3\u05d1\u05e8 \u05d0\u05ea \u05e9\u05e4\u05ea \u05d4\u05e7\u05d5\u05e8\u05e1 \u05d1\u05e8\u05de\u05d4 \u05e9\u05dc\u05db\u05dd \u05d5\u05de\u05ea\u05e7\u05df \u05d8\u05e2\u05d5\u05d9\u05d5\u05ea. +The\ video\ connection\ failed=\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d4\u05d5\u05d5\u05d9\u05d3\u05d0\u05d5 \u05e0\u05db\u05e9\u05dc +The\ video\ could\ not\ be\ read=\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05d4\u05d9\u05d4 \u05dc\u05e7\u05e8\u05d5\u05d0 \u05d0\u05ea \u05d4\u05e1\u05e8\u05d8\u05d5\u05df +The\ video\ is\ over\ 8\ MB.\ Record\ a\ shorter\ one.=\u05d4\u05e1\u05e8\u05d8\u05d5\u05df \u05d2\u05d3\u05d5\u05dc \u05de-8 MB. \u05d4\u05e7\u05dc\u05d9\u05d8\u05d5 \u05e7\u05e6\u05e8 \u05d9\u05d5\u05ea\u05e8. +This\ certificate\ could\ not\ be\ shown=\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05d4\u05d9\u05d4 \u05dc\u05d4\u05e6\u05d9\u05d2 \u05d0\u05ea \u05d4\u05ea\u05e2\u05d5\u05d3\u05d4 \u05d4\u05d6\u05d5 +This\ lesson\ has\ no\ phrases\ yet.=\u05d1\u05e9\u05d9\u05e2\u05d5\u05e8 \u05d4\u05d6\u05d4 \u05e2\u05d3\u05d9\u05d9\u05df \u05d0\u05d9\u05df \u05d1\u05d9\u05d8\u05d5\u05d9\u05d9\u05dd. +Three\ streak\ freezes\ a\ week=\u05e9\u05dc\u05d5\u05e9 \u05d4\u05e7\u05e4\u05d0\u05d5\u05ea \u05e8\u05e6\u05e3 \u05d1\u05e9\u05d1\u05d5\u05e2 +Tip\ {0}=\u05d8\u05d9\u05e4 {0} +Title=\u05db\u05d5\u05ea\u05e8\u05ea +Toolbar=\u05e1\u05e8\u05d2\u05dc \u05db\u05dc\u05d9\u05dd +Total=\u05e1\u05da \u05d4\u05db\u05d5\u05dc +Total\ XP=\u05e1\u05da XP +Tutor=\u05de\u05d5\u05e8\u05d4 +Type\ what\ you\ would\ say=\u05d4\u05e7\u05dc\u05d9\u05d3\u05d5 \u05de\u05d4 \u05d4\u05d9\u05d9\u05ea\u05dd \u05d0\u05d5\u05de\u05e8\u05d9\u05dd +Typing...=\u05de\u05e7\u05dc\u05d9\u05d3\u05d9\u05dd... +Unlimited\ conversations\ and\ streak\ freezes=\u05e9\u05d9\u05d7\u05d5\u05ea \u05d5\u05d4\u05e7\u05e4\u05d0\u05d5\u05ea \u05e8\u05e6\u05e3 \u05dc\u05dc\u05d0 \u05d4\u05d2\u05d1\u05dc\u05d4 +Up\ to\ 90\ seconds\ and\ 8\ MB.\ Learners\ can\ replay\ and\ seek.=\u05e2\u05d3 90 \u05e9\u05e0\u05d9\u05d5\u05ea \u05d5-8 MB. \u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05d9\u05db\u05d5\u05dc\u05d9\u05dd \u05dc\u05e0\u05d2\u05df \u05e9\u05d5\u05d1 \u05d5\u05dc\u05d3\u05dc\u05d2. +Uploading...=\u05de\u05e2\u05dc\u05d9\u05dd... +Use\ the\ cloud\ tutor=\u05e9\u05d9\u05de\u05d5\u05e9 \u05d1\u05de\u05d5\u05e8\u05d4 \u05d1\u05e2\u05e0\u05df +Used\ only\ to\ reach\ you\ about\ a\ live\ class\ you\ booked.=\u05de\u05e9\u05de\u05e9 \u05e8\u05e7 \u05db\u05d3\u05d9 \u05dc\u05d9\u05e6\u05d5\u05e8 \u05d0\u05d9\u05ea\u05db\u05dd \u05e7\u05e9\u05e8 \u05dc\u05d2\u05d1\u05d9 \u05e9\u05d9\u05e2\u05d5\u05e8 \u05d7\u05d9 \u05e9\u05d4\u05d6\u05de\u05e0\u05ea\u05dd. +Video=\u05d5\u05d9\u05d3\u05d0\u05d5 +Video\ uploaded=\u05d4\u05e1\u05e8\u05d8\u05d5\u05df \u05d4\u05d5\u05e2\u05dc\u05d4 +View\ your\ certificate=\u05d4\u05e6\u05d2\u05ea \u05d4\u05ea\u05e2\u05d5\u05d3\u05d4 \u05e9\u05dc\u05db\u05dd +Waiting\ for\ {0}'s\ video...=\u05de\u05de\u05ea\u05d9\u05e0\u05d9\u05dd \u05dc\u05e1\u05e8\u05d8\u05d5\u05df \u05e9\u05dc {0}... +Wallet=\u05d0\u05e8\u05e0\u05e7 +What\ learners\ will\ be\ able\ to\ do=\u05de\u05d4 \u05d4\u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05d9\u05d5\u05db\u05dc\u05d5 \u05dc\u05e2\u05e9\u05d5\u05ea +When\ this\ phone\ cannot\ run\ the\ tutor,\ ask\ the\ server's\ AI\ instead=\u05db\u05e9\u05d4\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4 \u05dc\u05d0 \u05d9\u05db\u05d5\u05dc \u05dc\u05d4\u05e8\u05d9\u05e5 \u05d0\u05ea \u05d4\u05de\u05d5\u05e8\u05d4, \u05dc\u05e9\u05d0\u05d5\u05dc \u05d0\u05ea \u05d4-AI \u05e9\u05dc \u05d4\u05e9\u05e8\u05ea +When\ this\ phone\ has\ no\ model.\ What\ you\ say\ is\ sent\ to\ Lingo's\ AI\ provider.=\u05db\u05e9\u05d0\u05d9\u05df \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05d4\u05d6\u05d4 \u05de\u05d5\u05d3\u05dc. \u05de\u05d4 \u05e9\u05d0\u05ea\u05dd \u05d0\u05d5\u05de\u05e8\u05d9\u05dd \u05e0\u05e9\u05dc\u05d7 \u05dc\u05e1\u05e4\u05e7 \u05d4-AI \u05e9\u05dc Lingo. +With\ usage\ statistics\ turned\ on,\ the\ app\ also\ counts\ which\ screens\ are\ opened\ and\ which\ features\ are\ used,\ and\ reports\ that\ to\ Codename\ One's\ analytics\ service\ under\ a\ made-up\ id\ for\ this\ device.\ Your\ name,\ e-mail,\ phone\ number,\ voice\ and\ conversations\ are\ never\ part\ of\ it,\ and\ turning\ it\ off\ in\ Settings\ stops\ it.=\u05db\u05e9\u05e1\u05d8\u05d8\u05d9\u05e1\u05d8\u05d9\u05e7\u05d5\u05ea \u05e9\u05d9\u05de\u05d5\u05e9 \u05de\u05d5\u05e4\u05e2\u05dc\u05d5\u05ea, \u05d4\u05d0\u05e4\u05dc\u05d9\u05e7\u05e6\u05d9\u05d4 \u05d2\u05dd \u05e1\u05d5\u05e4\u05e8\u05ea \u05d0\u05d9\u05dc\u05d5 \u05de\u05e1\u05db\u05d9\u05dd \u05e0\u05e4\u05ea\u05d7\u05d9\u05dd \u05d5\u05d1\u05d0\u05d9\u05dc\u05d5 \u05ea\u05db\u05d5\u05e0\u05d5\u05ea \u05de\u05e9\u05ea\u05de\u05e9\u05d9\u05dd, \u05d5\u05de\u05d3\u05d5\u05d5\u05d7\u05ea \u05e2\u05dc \u05db\u05da \u05dc\u05e9\u05d9\u05e8\u05d5\u05ea \u05d4\u05d0\u05e0\u05dc\u05d9\u05d8\u05d9\u05e7\u05d4 \u05e9\u05dc Codename One \u05ea\u05d7\u05ea \u05de\u05d6\u05d4\u05d4 \u05d1\u05d3\u05d5\u05d9 \u05e9\u05dc \u05d4\u05de\u05db\u05e9\u05d9\u05e8 \u05d4\u05d6\u05d4. \u05d4\u05e9\u05dd, \u05d4\u05d0\u05d9\u05de\u05d9\u05d9\u05dc, \u05d4\u05d8\u05dc\u05e4\u05d5\u05df, \u05d4\u05e7\u05d5\u05dc \u05d5\u05d4\u05e9\u05d9\u05d7\u05d5\u05ea \u05e9\u05dc\u05db\u05dd \u05d0\u05d9\u05e0\u05dd \u05d7\u05dc\u05e7 \u05de\u05d6\u05d4 \u05dc\u05e2\u05d5\u05dc\u05dd, \u05d5\u05db\u05d9\u05d1\u05d5\u05d9 \u05d4\u05d4\u05d2\u05d3\u05e8\u05d4 \u05d1\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e2\u05d5\u05e6\u05e8 \u05d0\u05d5\u05ea\u05d4. +Work\ on\:\ {0}=\u05e2\u05d5\u05d1\u05d3\u05d9\u05dd \u05e2\u05dc: {0} +Write\ an\ answer=\u05db\u05ea\u05d1\u05d5 \u05ea\u05e9\u05d5\u05d1\u05d4 +XP\ today=XP \u05d4\u05d9\u05d5\u05dd +You\ are\ a\ stallholder\ at\ a\ busy\ market...=\u05d0\u05ea\u05dd \u05d1\u05e2\u05dc\u05d9 \u05d3\u05d5\u05db\u05df \u05d1\u05e9\u05d5\u05e7 \u05d4\u05d5\u05de\u05d4... +You\ can\ keep\ practising.\ It\ is\ ready\ in\ a\ few\ minutes.=\u05d0\u05e4\u05e9\u05e8 \u05dc\u05d4\u05de\u05e9\u05d9\u05da \u05dc\u05ea\u05e8\u05d2\u05dc. \u05d6\u05d4 \u05d9\u05d4\u05d9\u05d4 \u05de\u05d5\u05db\u05df \u05d1\u05e2\u05d5\u05d3 \u05db\u05de\u05d4 \u05d3\u05e7\u05d5\u05ea. +You\ have\ a\ seat=\u05d9\u05e9 \u05dc\u05db\u05dd \u05de\u05e7\u05d5\u05dd +You\ host\ this=\u05d0\u05ea\u05dd \u05de\u05d0\u05e8\u05d7\u05d9\u05dd \u05d0\u05ea \u05d6\u05d4 +You\ keep\ 70%\ of\ every\ sale.=\u05d0\u05ea\u05dd \u05e9\u05d5\u05de\u05e8\u05d9\u05dd 70% \u05de\u05db\u05dc \u05de\u05db\u05d9\u05e8\u05d4. +You're\ a\ Pro\ member.\ Thank\ you\!=\u05d0\u05ea\u05dd \u05d7\u05d1\u05e8\u05d9 Pro. \u05ea\u05d5\u05d3\u05d4! +You're\ enrolled.\ Let's\ start\!=\u05e0\u05e8\u05e9\u05de\u05ea\u05dd. \u05d1\u05d5\u05d0\u05d5 \u05e0\u05ea\u05d7\u05d9\u05dc! +You're\ live.\ Learners\ appear\ here\ as\ they\ join.=\u05d0\u05ea\u05dd \u05d1\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d7\u05d9. \u05dc\u05d5\u05de\u05d3\u05d9\u05dd \u05d9\u05d5\u05e4\u05d9\u05e2\u05d5 \u05db\u05d0\u05df \u05db\u05e9\u05d9\u05e6\u05d8\u05e8\u05e4\u05d5. +Your\ course\ is\ live=\u05d4\u05e7\u05d5\u05e8\u05e1 \u05e9\u05dc\u05db\u05dd \u05d1\u05d0\u05d5\u05d5\u05d9\u05e8 +Your\ courses=\u05d4\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05e9\u05dc\u05db\u05dd +Your\ courses,\ classes\ and\ earnings=\u05d4\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd, \u05d4\u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d5\u05d4\u05d4\u05db\u05e0\u05e1\u05d5\u05ea \u05e9\u05dc\u05db\u05dd +Your\ name\ and\ language=\u05d4\u05e9\u05dd \u05d5\u05d4\u05e9\u05e4\u05d4 \u05e9\u05dc\u05db\u05dd +Your\ phone's\ built-in\ AI\ answers.\ Nothing\ you\ say\ leaves\ the\ device.=\u05d4-AI \u05d4\u05de\u05d5\u05d1\u05e0\u05d4 \u05d1\u05d8\u05dc\u05e4\u05d5\u05df \u05e9\u05dc\u05db\u05dd \u05e2\u05d5\u05e0\u05d4. \u05e9\u05d5\u05dd \u05d3\u05d1\u05e8 \u05de\u05de\u05d4 \u05e9\u05d0\u05ea\u05dd \u05d0\u05d5\u05de\u05e8\u05d9\u05dd \u05dc\u05d0 \u05e2\u05d5\u05d6\u05d1 \u05d0\u05ea \u05d4\u05de\u05db\u05e9\u05d9\u05e8. +Your\ seat\ is\ booked.\ We'll\ remind\ you.=\u05d4\u05de\u05e7\u05d5\u05dd \u05e9\u05dc\u05db\u05dd \u05d4\u05d5\u05d6\u05de\u05df. \u05e0\u05d6\u05db\u05d9\u05e8 \u05dc\u05db\u05dd. +Your\ sign-in,\ profile,\ progress\ and\ settings\ are\ removed\ for\ good.\ Certificates\ already\ issued\ can\ still\ be\ verified.=\u05d4\u05d4\u05ea\u05d7\u05d1\u05e8\u05d5\u05ea, \u05d4\u05e4\u05e8\u05d5\u05e4\u05d9\u05dc, \u05d4\u05d4\u05ea\u05e7\u05d3\u05de\u05d5\u05ea \u05d5\u05d4\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e9\u05dc\u05db\u05dd \u05e0\u05de\u05d7\u05e7\u05d9\u05dd \u05dc\u05e6\u05de\u05d9\u05ea\u05d5\u05ea. \u05ea\u05e2\u05d5\u05d3\u05d5\u05ea \u05e9\u05db\u05d1\u05e8 \u05d4\u05d5\u05e0\u05e4\u05e7\u05d5 \u05e2\u05d3\u05d9\u05d9\u05df \u05e0\u05d9\u05ea\u05e0\u05d5\u05ea \u05dc\u05d0\u05d9\u05de\u05d5\u05ea. +Yours=\u05e9\u05dc\u05db\u05dd +Wait\ for\ Wi-Fi=\u05dc\u05d4\u05de\u05ea\u05d9\u05df \u05dc-Wi-Fi +Accounts=\u05d7\u05e9\u05d1\u05d5\u05e0\u05d5\u05ea +Admin=\u05de\u05e0\u05d4\u05dc +Cannot\ sign\ in=\u05dc\u05d0 \u05d9\u05db\u05d5\u05dc \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 +Grants\ roles\ to\ other\ accounts=\u05de\u05e2\u05e0\u05d9\u05e7 \u05ea\u05e4\u05e7\u05d9\u05d3\u05d9\u05dd \u05dc\u05d7\u05e9\u05d1\u05d5\u05e0\u05d5\u05ea \u05d0\u05d7\u05e8\u05d9\u05dd +Learner=\u05dc\u05d5\u05de\u05d3 +Publishes\ courses\ and\ holds\ live\ classes=\u05de\u05e4\u05e8\u05e1\u05dd \u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05d5\u05de\u05e2\u05d1\u05d9\u05e8 \u05e9\u05d9\u05e2\u05d5\u05e8\u05d9\u05dd \u05d7\u05d9\u05d9\u05dd +Roles=\u05ea\u05e4\u05e7\u05d9\u05d3\u05d9\u05dd +Suspended=\u05de\u05d5\u05e9\u05e2\u05d4 +Takes\ courses\ and\ practises\ with\ the\ tutor=\u05dc\u05d5\u05de\u05d3 \u05d1\u05e7\u05d5\u05e8\u05e1\u05d9\u05dd \u05d5\u05de\u05ea\u05e8\u05d2\u05dc \u05e2\u05dd \u05d4\u05de\u05d5\u05e8\u05d4 +Who\ can\ sign\ in,\ and\ who\ teaches=\u05de\u05d9 \u05d9\u05db\u05d5\u05dc \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05d5\u05de\u05d9 \u05de\u05dc\u05de\u05d3 +1\ day=\u05d9\u05d5\u05dd \u05d0\u05d7\u05d3 diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/Actor.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/Actor.java new file mode 100644 index 00000000000..824b64d4396 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/Actor.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.io.CharArrayReader; +import com.codename1.io.ConnectionRequest; +import com.codename1.io.JSONParser; +import com.codename1.io.NetworkManager; +import com.codename1.io.RequestAuthorizer; +import com.codename1.ui.CN; +import com.codenameone.examples.lingo.net.Session; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/// The other person in a test. The app on screen is one user; a creator +/// and a learner are two, so the second one acts through the API directly, with their own token. +/// +/// Their requests opt out of the app's authorizer, which would otherwise put +/// the on-screen user's token on anything sent to `/api`. +final class Actor { + private final String token; + int status; + + /// One sign-in for each account for the whole run. The server limits how + /// often an address may sign in, as it should, and a suite that signed in + /// again for every step would be turned away by it. + private static final Map SIGNED_IN = new HashMap(); + + private Actor(String token) { + this.token = token; + } + + /// Signs `email` in the way the app does, and keeps the token to itself. + static Actor signIn(String email) { + Actor known = SIGNED_IN.get(email); + if (known != null) { + return new Actor(known.token); + } + Actor fresh = authenticate(email); + SIGNED_IN.put(email, fresh); + return fresh; + } + + /// Whether `email` can sign in at this moment, asked of the server and + /// kept by nobody: this is how a test sees a blocked account refused. + static boolean canSignIn(String email) { + try { + authenticate(email); + return true; + } catch (RuntimeException refused) { + return false; + } + } + + private static Actor authenticate(String email) { + final String[] token = new String[1]; + final String[] problem = new String[1]; + CN.callSerially(() -> Session.authenticate(email, E2e.PASSWORD, + tokens -> token[0] = tokens.getAccessToken(), + (status, message) -> problem[0] = status + " " + message)); + long deadline = System.currentTimeMillis() + 30000; + while (token[0] == null && problem[0] == null && System.currentTimeMillis() < deadline) { + try { + Thread.sleep(50); + } catch (InterruptedException stop) { + break; + } + } + if (token[0] == null) { + throw new RuntimeException("Could not sign " + email + " in: " + problem[0]); + } + return new Actor(token[0]); + } + + Map get(String path) { + return send("GET", path, null); + } + + Map put(String path, String json) { + return send("PUT", path, json); + } + + Map post(String path, String json) { + return send("POST", path, json == null ? "{}" : json); + } + + private Map send(String method, String path, String json) { + ConnectionRequest request = new ConnectionRequest(); + request.setUrl(AppConfig.serverUrl() + path); + request.setHttpMethod(method); + request.setPost(json != null); + if (json != null) { + request.setContentType("application/json"); + request.setRequestBody(json); + } + request.addRequestHeader("Authorization", "Bearer " + token); + request.setAuthorizer(RequestAuthorizer.NONE); + request.setReadResponseForErrors(true); + request.setFailSilently(true); + request.setDuplicateSupported(true); + NetworkManager.getInstance().addToQueueAndWait(request); + status = request.getResponseCode(); + byte[] body = request.getResponseData(); + if (body == null || body.length == 0 || body[0] != '{') { + return new HashMap(); + } + try { + return new JSONParser().parseJSON(new CharArrayReader( + new String(body, "UTF-8").toCharArray())); + } catch (IOException malformed) { + return new HashMap(); + } + } + + static String text(Map json, String key) { + Object value = json.get(key); + return value instanceof String ? (String) value : ""; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/DesktopTourTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/DesktopTourTest.java new file mode 100644 index 00000000000..2b9af0d7137 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/DesktopTourTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +/// The app in a desktop window: the learner's home, the catalogue and a +/// course, the studio, and the admin's accounts, each captured. +public class DesktopTourTest extends E2e { + @Override + protected boolean desktop() { + return true; + } + + @Override + protected boolean run() throws Exception { + signIn(LEARNER, "LearnHome"); + settle(); + pace(); + shot("desktop-today"); + click("tab-courses"); + settle(); + pace(); + shot("desktop-courses"); + click("course-spanish-travel"); + waitForForm("Course"); + settle(); + pace(); + shot("desktop-course"); + back(); + waitForForm("LearnHome"); + signOut(); + + signIn(ADMIN, "StudioHome"); + settle(); + pace(); + shot("desktop-studio"); + click("accounts"); + waitForForm("Accounts"); + settle(); + pace(); + shot("desktop-accounts"); + back(); + waitForForm("StudioHome"); + signOut(); + return true; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/E2e.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/E2e.java new file mode 100644 index 00000000000..f8464c84909 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/E2e.java @@ -0,0 +1,456 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.components.SpanLabel; +import com.codename1.components.Switch; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.oidc.OidcTokens; +import com.codename1.io.oidc.TokenStore; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Display; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; +import com.codename1.ui.spinner.Picker; +import com.codename1.ui.util.ImageIO; +import com.codename1.util.AsyncResource; +import com.codenameone.examples.lingo.live.LiveChannel; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Lang; +import com.codenameone.examples.lingo.ui.Look; +import com.codenameone.examples.lingo.ui.Nav; +import com.codenameone.examples.lingo.ui.Photos; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Calendar; +import java.util.Map; + +/// What the end-to-end tests share. Each of them drives the real app, through +/// its real screens, against a real server -- the one `run-e2e.sh` starts on the +/// `test` profile, which has the demo accounts and the seeded courses. +/// +/// Speech is pinned so that a run is the same wherever it happens: the +/// tests hear what they type, through [com.codenameone.examples.lingo.speech.Voice#useEars], +/// and the tutor is the scripted one. None of it touches the server. +public abstract class E2e extends AbstractTest { + public static final String PASSWORD = "lingo-demo"; + public static final String LEARNER = "learner@lingo.example"; + public static final String LEARNER2 = "learner2@lingo.example"; + public static final String CREATOR = "creator@lingo.example"; + public static final String ADMIN = "admin@lingo.example"; + + protected interface Check { + boolean ok(); + } + + @Override + public boolean shouldExecuteOnEDT() { + return false; + } + + @Override + public int getTimeoutMillis() { + return 180000; + } + + /// Whether this run of the tests is the one in a desktop window. + /// + /// `run-e2e.sh` runs the tests twice: on the simulator's phone, and then + /// with the simulator as a desktop, where the app is a window an admin + /// works in. A test belongs to one of the two -- see [#desktop()] -- and + /// passes without doing anything in the other. + static boolean desktopRun() { + return "true".equals(System.getProperty("lingo.e2e.desktop")); + } + + /// Whether this test is one for the desktop window. The phone's are not. + protected boolean desktop() { + return false; + } + + private boolean mine() { + return desktop() == desktopRun(); + } + + /// The test itself. + protected abstract boolean run() throws Exception; + + @Override + public final boolean runTest() throws Exception { + if (!mine()) { + log("Not a test for " + (desktopRun() ? "the desktop" : "the phone") + "; skipped"); + return true; + } + // -Dlingo.e2e.only=A,B runs just those classes: how the recordings of + // the showcase are made without the rest of the suite. + String only = System.getProperty("lingo.e2e.only"); + if (only != null && only.length() > 0 + && ("," + only + ",").indexOf("," + getClass().getSimpleName() + ",") < 0) { + log("Not in lingo.e2e.only; skipped"); + return true; + } + return run(); + } + + @Override + public void prepare() { + if (!mine()) { + return; + } + Session.useStore(new MemoryStore()); + onEdt(() -> { + LiveChannel.stop(); + // The tests read the screens in English, whatever the machine + // they run on speaks. + Prefs.setLanguage("en"); + Prefs.setTheme(Prefs.THEME_LIGHT); + // Answered, with a no: no test is stopped by the question a first + // sign-in is asked, and none reports how it used the app. The + // test of the reports gives its own answers. + Telemetry.allow(false); + Look.apply(); + Lang.apply(); + Session.start(AppConfig.serverUrl()); + AppConfig.setMode(Nav.LEARN); + Nav.launch(); + }); + waitForForm("Welcome"); + quiet(); + } + + /// Puts the client back where a test expects to find it. The server's + /// demo data is reseeded by the run script, and each test that changes a + /// job changes one of its own. + private void quiet() { + Photos.useSource(null); + } + + @Override + public void cleanup() { + if (!mine()) { + return; + } + onEdt(() -> { + LiveChannel.stop(); + Session.start(AppConfig.serverUrl()); + }); + } + + // ------------------------------------------------------------- driving + + protected void onEdt(Runnable work) { + CN.callSeriallyAndWait(work); + } + + /// Clicks the button called `name` on the screen that is showing, once it + /// is there. + protected void click(final String name) { + until(() -> findByName(name) instanceof Button, 20000, "a button called " + name); + onEdt(() -> { + Button button = (Button) findByName(name); + button.pressed(); + button.released(); + }); + pace(); + } + + /// A pause between steps when -Dlingo.e2e.pace gives one in milliseconds, + /// so a recording of the run can be followed. Nothing otherwise. + protected void pace() { + int ms = Integer.parseInt(System.getProperty("lingo.e2e.pace", "0")); + if (ms > 0) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + /// Flips the switch called `name`, as a tap on it does: the change event + /// its screen listens for is fired by the new value. + protected void flip(final String name) { + until(() -> findByName(name) instanceof Switch, 20000, "a switch called " + name); + onEdt(() -> { + Component found = findByName(name); + if (found instanceof Switch) { + Switch toggle = (Switch) found; + toggle.setValue(!toggle.isValue()); + } + }); + } + + /// Clicks the button called `name` if it is on the screen at this moment. + /// + /// For a button the server may take away while the test looks: asking + /// whether it is there and then clicking it are two turns of the event + /// thread, and the screen can change between them. + protected void clickIfThere(final String name) { + onEdt(() -> { + Component found = findByName(name); + if (found instanceof Button) { + Button button = (Button) found; + button.pressed(); + button.released(); + } + }); + } + + protected void type(final String name, final String text) { + until(() -> findByName(name) instanceof TextArea, 20000, "a field called " + name); + onEdt(() -> { + TextArea field = (TextArea) findByName(name); + field.setText(text); + }); + pace(); + } + + /// The text of the label or field called `name`, or "" while there is none. + protected String text(String name) { + Component found = findByName(name); + if (found instanceof SpanLabel) { + return ((SpanLabel) found).getText(); + } + if (found instanceof Label) { + return ((Label) found).getText(); + } + if (found instanceof TextArea) { + return ((TextArea) found).getText(); + } + return ""; + } + + protected void until(Check check, int timeoutMillis, String what) { + long deadline = System.currentTimeMillis() + timeoutMillis; + while (!check.ok()) { + if (System.currentTimeMillis() > deadline) { + Form current = Display.getInstance().getCurrent(); + throw new RuntimeException("Timed out waiting for " + what + " (on " + + (current == null ? "no form" : current.getName()) + ")"); + } + waitFor(100); + } + } + + /// Waits for the screen called `name` to be the one showing. + protected void waitForForm(final String name) { + until(() -> { + Form current = Display.getInstance().getCurrent(); + return current != null && name.equals(current.getName()); + }, 30000, "the " + name + " screen"); + waitFor(100); + } + + protected void untilText(final String name, final String expected) { + until(() -> expected.equals(text(name)), 30000, + name + " to read \"" + expected + "\" (it reads \"" + text(name) + "\")"); + } + + /// Signs in through the app's own screens. + protected void signIn(String email, String homeForm) { + click("signIn"); + waitForForm("SignIn"); + type("email", email); + type("password", PASSWORD); + click("submit"); + waitForForm(homeForm); + } + + /// Whether there is something to press called `name` on the screen. + protected boolean has(String name) { + return findByName(name) instanceof Button; + } + + /// Scrolls whatever is called `name` into view. + protected void reveal(final String name) { + until(() -> findByName(name) != null, 20000, name + " to be there"); + onEdt(() -> { + Component found = findByName(name); + // The nearest thing above it that scrolls, which on a home screen + // is not the form. + Container holder = found.getParent(); + while (holder != null && !holder.isScrollableY()) { + holder = holder.getParent(); + } + if (holder != null) { + holder.scrollComponentToVisible(found); + } + }); + } + + /// Goes back, the way the arrow in the title bar does. + protected void back() { + onEdt(() -> Display.getInstance().getCurrent().getBackCommand().actionPerformed(null)); + } + + /// Signs out through the menu of a home screen. + protected void signOut() { + // The way out is on each home's own page (the Me tab, the studio's + // header); the tests take it directly, from wherever they are. + onEdt(Nav::signOut); + waitForForm("Welcome"); + } + + /// Sets the date field called `name`. A test cannot turn the wheels of + /// the platform's date picker, which is not part of the app. + protected void date(final String name, final int year, final int month, final int day) { + until(() -> findByName(name) instanceof Picker, 20000, "a date called " + name); + onEdt(() -> { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month - 1); + calendar.set(Calendar.DAY_OF_MONTH, day); + ((Picker) findByName(name)).setDate(calendar.getTime()); + }); + } + + /// A picture for the app to take as a photograph: the tests have neither + /// a camera nor a gallery. It is drawn rather than read from a file so + /// that it is the same picture wherever the tests run. + protected static Image photograph() { + Image picture = Image.createImage(640, 400, 0xffe9edf2); + Graphics g = picture.getGraphics(); + g.setColor(0x2f6fed); + g.fillRect(0, 0, 640, 70); + g.setColor(0xb8c2cf); + g.fillRect(40, 110, 150, 190); + g.setColor(0x8795a7); + for (int line = 0; line < 5; line++) { + g.fillRect(230, 120 + line * 38, line % 2 == 0 ? 340 : 250, 16); + } + return picture; + } + + // -------------------------------------------------------- screenshots + + /// Captures the screen as `name`.png and holds it against the golden of + /// the same name. + /// + /// `lingo.shots.dir` is where the capture goes; without it nothing is + /// captured, which is a run from an IDE. `lingo.goldens.dir` is where + /// the goldens are. A capture with no golden passes -- that is how a new + /// one is made: run, look at it, copy it over. + /// + /// The comparison is loose on purpose: a pixel counts as different only + /// when it is far off, and a capture fails only when a twentieth of it is. + /// Text is drawn a little differently from one machine to the next, and + /// this is here to notice a screen that changed, not a glyph. + protected void shot(String name) { + String out = fileUrl(System.getProperty("lingo.shots.dir")); + if (out == null) { + return; + } + settle(); + final Image[] captured = new Image[1]; + onEdt(() -> captured[0] = Display.getInstance().captureScreen()); + FileSystemStorage files = FileSystemStorage.getInstance(); + try { + files.mkdir(out); + OutputStream png = files.openOutputStream(out + "/" + name + ".png"); + try { + ImageIO.getImageIO().save(captured[0], png, ImageIO.FORMAT_PNG, 1f); + } finally { + png.close(); + } + String goldens = fileUrl(System.getProperty("lingo.goldens.dir")); + String golden = goldens == null ? "" : goldens + "/" + name + ".png"; + if (golden.length() == 0 || !files.exists(golden)) { + log("No golden for " + name + "; captured only"); + return; + } + InputStream in = files.openInputStream(golden); + Image expected; + try { + expected = Image.createImage(in); + } finally { + in.close(); + } + assertEqual(expected.getWidth(), captured[0].getWidth(), name + ": width changed"); + assertEqual(expected.getHeight(), captured[0].getHeight(), name + ": height changed"); + int[] want = expected.getRGB(); + int[] got = captured[0].getRGB(); + int off = 0; + for (int iter = 0; iter < want.length; iter++) { + if (far(want[iter], got[iter])) { + off++; + } + } + assertTrue(off * 20L <= want.length, name + ": " + off + " of " + want.length + + " pixels differ from the golden"); + } catch (java.io.IOException err) { + throw new RuntimeException("Could not capture " + name + ": " + err); + } + } + + /// A directory the build names as an ordinary path, in the form + /// `FileSystemStorage` takes one; null when it names none. + private static String fileUrl(String path) { + if (path == null || path.length() == 0) { + return null; + } + return path.startsWith("file:") ? path : "file://" + path; + } + + private static boolean far(int a, int b) { + return Math.abs(((a >> 16) & 0xff) - ((b >> 16) & 0xff)) > 60 + || Math.abs(((a >> 8) & 0xff) - ((b >> 8) & 0xff)) > 60 + || Math.abs((a & 0xff) - (b & 0xff)) > 60; + } + + /// Waits for the screen to stop moving: transitions and count-ups over. + protected void settle() { + waitFor(2000); + } + + /// Tokens kept for the length of the run and nowhere else. + static final class MemoryStore implements TokenStore { + private OidcTokens kept; + + @Override + public AsyncResource load(String key) { + AsyncResource out = new AsyncResource(); + out.complete(kept); + return out; + } + + @Override + public AsyncResource save(String key, OidcTokens tokens) { + kept = tokens; + AsyncResource out = new AsyncResource(); + out.complete(Boolean.TRUE); + return out; + } + + @Override + public AsyncResource clear(String key) { + kept = null; + AsyncResource out = new AsyncResource(); + out.complete(Boolean.TRUE); + return out; + } + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/LessonTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/LessonTest.java new file mode 100644 index 00000000000..04e94cf447a --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/LessonTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import java.util.Map; + +/// A pronunciation lesson, start to reward: the learner says each phrase +/// (typed, since a test has no microphone), is scored word by word, and +/// lands on the reward screen with the XP on their account. +public class LessonTest extends E2e { + @Override + protected boolean run() throws Exception { + Actor learner = Actor.signIn(LEARNER); + Object before = learner.get("/api/me/stats").get("xp"); + signIn(LEARNER, "LearnHome"); + until(() -> has("practice"), 20000, "the continue button"); + click("practice"); + waitForForm("PhraseLesson"); + shot("phrase"); + boolean first = true; + for (int iter = 0; iter < 12 && !"Reward".equals(currentForm()); iter++) { + until(() -> findByName("typed") != null || has("next"), 20000, "a phrase to say"); + if (findByName("typed") != null) { + String phrase = text("phrase"); + // The first is said with a word missing, to see the scoring. + type("typed", first ? phrase.substring(0, phrase.lastIndexOf(' ') + 1) + : phrase); + click("check"); + until(() -> has("next"), 20000, "the verdict"); + if (first) { + shot("phrase-scored"); + first = false; + } + } + click("next"); + waitFor(800); + } + waitForForm("Reward"); + until(() -> findByName("xp-earned") != null, 20000, "the reward"); + shot("reward"); + Map after = learner.get("/api/me/stats"); + assertTrue(Double.parseDouble(String.valueOf(after.get("xp"))) + > Double.parseDouble(String.valueOf(before)), "the lesson earned XP"); + click("continue"); + waitFor(1000); + signOut(); + return true; + } + + private String currentForm() { + return com.codename1.ui.Display.getInstance().getCurrent().getName(); + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/RegisterTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/RegisterTest.java new file mode 100644 index 00000000000..482ec1d4d13 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/RegisterTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codenameone.examples.lingo.net.Session; + +/// A new account: register, be signed in, and arrive on the learner's home. +public class RegisterTest extends E2e { + @Override + protected boolean run() throws Exception { + // One address per pass: both passes share the run's server. + String email = "new." + (desktopRun() ? "desk" : "phone") + "@lingo.example"; + click("register"); + waitForForm("Register"); + type("name", "Nico Newcomer"); + type("email", email); + type("phone", "+1 555 010 4242"); + type("password", PASSWORD); + shot("register"); + click("submit"); + + // A new account is a learner with no streak yet. + waitForForm("LearnHome"); + assertEqual(email, Session.user().username()); + assertTrue(Session.user().learner(), "a new account is a learner"); + signOut(); + return true; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SettingsTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SettingsTest.java new file mode 100644 index 00000000000..f2e5cb3e207 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SettingsTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import java.util.Map; + +/// The settings: a language and a theme that change the app on the spot, and +/// the learner's switches, kept with the account. +public class SettingsTest extends E2e { + @Override + protected boolean run() throws Exception { + final Actor tech = Actor.signIn(LEARNER); + signIn(LEARNER, "LearnHome"); + click("tab-me"); + reveal("me-settings"); + click("me-settings"); + waitForForm("Settings"); + untilText("signOut", "Sign out"); + shot("settings"); + + // Another language, at once and on the account. + click("language-he"); + until(() -> text("signOut").length() > 0 && !"Sign out".equals(text("signOut")), 20000, + "the screen to be in Hebrew"); + until(() -> "he".equals(Actor.text(tech.get("/api/account/preferences"), "language")), + 20000, "the language to be kept with the account"); + shot("settings-hebrew"); + click("language-en"); + untilText("signOut", "Sign out"); + + // Dark, and the screen behind is dark as well. + click("theme-dark"); + until(() -> "dark".equals(Actor.text(tech.get("/api/account/preferences"), "theme")), + 20000, "the theme to be kept with the account"); + shot("settings-dark"); + back(); + waitForForm("LearnHome"); + shot("me-dark"); + reveal("me-settings"); + click("me-settings"); + waitForForm("Settings"); + click("theme-system"); + + // A switch reaches the server, and is put back for the next test. The + // parser hands a JSON boolean back as its text, so it is compared as one. + reveal("notifyReminders"); + flip("notifyReminders"); + until(() -> "false".equals(String.valueOf(tech.get("/api/account/preferences") + .get("notifyReminders"))), 20000, "the switch to be kept with the account"); + flip("notifyReminders"); + until(() -> { + Map kept = tech.get("/api/account/preferences"); + return "true".equals(String.valueOf(kept.get("notifyReminders"))) + && "system".equals(Actor.text(kept, "theme")) + && "en".equals(Actor.text(kept, "language")); + }, 20000, "the account to hold what was chosen"); + click("signOut"); + waitForForm("Welcome"); + return true; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/ShowcaseTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/ShowcaseTest.java new file mode 100644 index 00000000000..391e9ca1b2d --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/ShowcaseTest.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Form; + +/// The app at work, a scene at a time: a conversation with the tutor, a +/// teacher's video lesson, a finished course's signed certificate, and a live +/// class the teacher hosts. Each scene ends in a capture, and with +/// -Dlingo.e2e.pace the run is slow enough to record. +public class ShowcaseTest extends E2e { + @Override + protected boolean run() throws Exception { + // A finished course, so there is a certificate to open. The lessons + // are done through the API, in order, as the app would send them. + Actor learner = Actor.signIn(LEARNER); + learner.post("/api/courses/french-essentials/enroll", "{}"); + for (int iter = 1; iter <= 4; iter++) { + learner.post("/api/lessons/french-essentials-" + iter + "/attempt", + "{\"score\":92,\"seconds\":240,\"spoken\":6}"); + } + + signIn(LEARNER, "LearnHome"); + pace(); + + // A conversation: the learner orders, the tutor answers in role. The + // drills before it are done first, so it is open. + for (int iter = 1; iter <= 3; iter++) { + learner.post("/api/lessons/spanish-travel-" + iter + "/attempt", + "{\"score\":88,\"seconds\":180,\"spoken\":5}"); + } + click("tab-courses"); + settle(); + click("course-spanish-travel"); + waitForForm("Course"); + settle(); + pace(); + // The simulator has no model of its own: the learner opts in to the + // cloud tutor, as Settings would. + Prefs.setCloudTutor(true); + click("open-spanish-travel-4"); + waitForForm("ConversationLesson"); + settle(); + pace(); + say("Hola, buenas tardes. Quiero unas patatas bravas, por favor."); + say("Y para beber, un agua con gas."); + shot("conversation"); + click("close-lesson"); + waitForForm("Course"); + back(); + waitForForm("LearnHome"); + + // A video lesson from a teacher's course. + click("tab-courses"); + settle(); + click("course-madrid-cafe"); + waitForForm("Course"); + settle(); + pace(); + if (findByName("enroll") instanceof Button) { + click("enroll"); + } + click("open-madrid-cafe-1"); + waitForForm("VideoLesson"); + settle(); + pace(); + pace(); + shot("video-lesson"); + back(); + waitForForm("Course"); + back(); + waitForForm("LearnHome"); + + // The certificate: signed, verified, shown as the PDF itself. + click("tab-me"); + reveal("me-certificates"); + click("me-certificates"); + waitForForm("Certificates"); + settle(); + shot("certificates-list"); + final String[] first = new String[1]; + until(() -> (first[0] = firstNamed("certificate-")) != null, 20000, "a certificate"); + click(first[0]); + waitForForm("Certificate"); + settle(); + pace(); + pace(); + shot("certificate"); + back(); + waitForForm("Certificates"); + back(); + waitForForm("LearnHome"); + signOut(); + + // A live class: the teacher goes live and is on the stage. + signIn(CREATOR, "StudioHome"); + pace(); + final String[] start = new String[1]; + until(() -> (start[0] = firstNamed("start-")) != null, 20000, "a class to start"); + reveal(start[0]); + click(start[0]); + waitForForm("LiveRoom"); + settle(); + pace(); + pace(); + shot("live-room"); + click("leave-room"); + waitForForm("StudioHome"); + final String[] end = new String[1]; + until(() -> (end[0] = firstNamed("end-")) != null, 20000, "the class to end"); + click(end[0]); + signOut(); + return true; + } + + /// Says a line in the conversation: typed, then sent, then the tutor's + /// answer waited for. + private void say(String line) { + final int before = count(); + type("reply", line); + click("send"); + until(() -> count() >= before + 2, 30000, "the tutor to answer"); + settle(); + pace(); + } + + private static int count() { + Form f = CN.getCurrentForm(); + Component thread = f == null ? null : find(f, "thread", true); + return thread instanceof Container ? ((Container) thread).getComponentCount() : 0; + } + + private static String firstNamed(String prefix) { + Form f = CN.getCurrentForm(); + Component c = f == null ? null : find(f, prefix, false); + return c == null ? null : c.getName(); + } + + private static Component find(Container root, String name, boolean exact) { + for (int iter = 0; iter < root.getComponentCount(); iter++) { + Component c = root.getComponentAt(iter); + String n = c.getName(); + if (n != null && (exact ? n.equals(name) : n.startsWith(name)) && c instanceof Button == !exact) { + return c; + } + if (c instanceof Container) { + Component inner = find((Container) c, name, exact); + if (inner != null) { + return inner; + } + } + } + return null; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SignInTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SignInTest.java new file mode 100644 index 00000000000..12dac01eb0a --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/SignInTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.ui.Display; +import com.codenameone.examples.lingo.net.Session; +import com.codenameone.examples.lingo.ui.Nav; + +/// Signing in, and what a role does and does not open. +public class SignInTest extends E2e { + @Override + protected boolean run() throws Exception { + shot("welcome"); + + // A wrong password says so and stays put. + click("signIn"); + waitForForm("SignIn"); + type("email", LEARNER); + type("password", "not-the-password"); + click("submit"); + until(() -> text("error").length() > 0, 20000, "the sign-in error"); + assertEqual("SignIn", Display.getInstance().getCurrent().getName()); + assertNull(Session.user(), "nobody is signed in after a wrong password"); + + // The right one lands a learner on today's practice. + type("password", PASSWORD); + click("submit"); + waitForForm("LearnHome"); + assertEqual(LEARNER, Session.user().username()); + assertTrue(Session.user().learner() && !Session.user().creator() + && !Session.user().admin(), "the demo learner has that role and no other"); + until(() -> findByName("hero") != null, 20000, "today's dashboard"); + shot("today"); + + // Asking for the studio without the role keeps the learner home. + onEdt(() -> Nav.switchTo(Nav.STUDIO)); + waitForForm("LearnHome"); + // And the server agrees, which is the part that matters. + Actor learner = Actor.signIn(LEARNER); + learner.get("/api/studio"); + assertEqual(403, learner.status, "a learner asking for the studio"); + learner.get("/api/me/stats"); + assertEqual(200, learner.status); + signOut(); + + // A creator lands in the studio. + signIn(CREATOR, "StudioHome"); + until(() -> findByName("earnings") != null, 20000, "the studio dashboard"); + shot("studio"); + signOut(); + return true; + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TourTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TourTest.java new file mode 100644 index 00000000000..25a8a3d0799 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TourTest.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.ui.CN; +import com.codename1.ui.Form; + +/// A walk past the screens the other tests do not stop at, as a learner, a +/// creator and an admin, capturing each: the catalogue, a course, a +/// conversation, the Live tab, badges, the leaderboard, certificates, the +/// wallet, the tutor, the studio's editors and the accounts. +public class TourTest extends E2e { + @Override + protected boolean run() throws Exception { + signIn(LEARNER, "LearnHome"); + click("tab-courses"); + settle(); + shot("catalog"); + click("course-spanish-travel"); + waitForForm("Course"); + shot("course"); + back(); + waitForForm("LearnHome"); + + click("tab-today"); + click("practice"); + until(() -> named("ConversationLesson") || named("PhraseLesson"), 20000, + "the next lesson to open"); + settle(); + shot("next-lesson"); + click("close-lesson"); + waitForForm("LearnHome"); + + click("tab-live"); + settle(); + shot("live"); + + visit("me-badges", "Achievements", "achievements"); + visit("me-board", "Leaderboard", "leaderboard"); + visit("me-certificates", "Certificates", "certificates"); + visit("me-wallet", "Wallet", "wallet"); + visit("me-tutor", "Tutor", "tutor"); + + // The same screens dark, then the device's own mode again. + dark(Boolean.TRUE); + try { + visit("me-badges", "Achievements", "achievements-dark"); + click("tab-courses"); + settle(); + shot("catalog-dark"); + click("course-spanish-travel"); + waitForForm("Course"); + settle(); + shot("course-dark"); + back(); + waitForForm("LearnHome"); + click("tab-live"); + settle(); + shot("live-dark"); + } finally { + dark(null); + } + signOut(); + + signIn(CREATOR, "StudioHome"); + click("more-Courses"); + waitForForm("NewCourse"); + settle(); + shot("course-editor"); + back(); + waitForForm("StudioHome"); + signOut(); + + signIn(ADMIN, "StudioHome"); + click("accounts"); + waitForForm("Accounts"); + settle(); + shot("accounts"); + back(); + waitForForm("StudioHome"); + signOut(); + return true; + } + + private void visit(String row, String form, String shot) { + click("tab-me"); + reveal(row); + click(row); + waitForForm(form); + settle(); + shot(shot); + back(); + waitForForm("LearnHome"); + } + + private void dark(final Boolean on) { + onEdt(() -> { + CN.setDarkMode(on); + com.codename1.ui.plaf.UIManager.getInstance().refreshTheme(); + Form f = CN.getCurrentForm(); + if (f != null) { + f.refreshTheme(); + f.revalidate(); + } + }); + } + + private static boolean named(String name) { + Form f = CN.getCurrentForm(); + return f != null && name.equals(f.getName()); + } +} diff --git a/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TutorLogicTest.java b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TutorLogicTest.java new file mode 100644 index 00000000000..3c617958f33 --- /dev/null +++ b/scripts/lingo/common/src/test/java/com/codenameone/examples/lingo/TutorLogicTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo; + +import com.codename1.testing.AbstractTest; +import com.codenameone.examples.lingo.ai.Tutors; +import com.codenameone.examples.lingo.speech.PronunciationScorer; + +/// The two decisions the tutor makes with no server and no device: which +/// engine answers, and how close what was heard is to what was meant. +public class TutorLogicTest extends AbstractTest { + @Override + public boolean runTest() throws Exception { + // The phone's own model first, then a downloaded one, then the cloud + // only if the learner allowed it, and the scripted partner last. + assertEqual(Tutors.SYSTEM, Tutors.choose(true, true, true, true)); + assertEqual(Tutors.LOCAL, Tutors.choose(false, true, true, true)); + assertEqual(Tutors.CLOUD, Tutors.choose(false, true, false, true)); + assertEqual(Tutors.CLOUD, Tutors.choose(false, false, true, true), + "a model on disk is no use where it cannot run"); + assertEqual(Tutors.SCRIPTED, Tutors.choose(false, true, false, false), + "nothing is sent to the cloud without the opt-in"); + + // Case, accents and punctuation are not pronunciation. + PronunciationScorer.Result exact = PronunciationScorer.score("Hola, \u00bfqu\u00e9 tal?", + "hola que tal"); + assertTrue(exact.score >= PronunciationScorer.GOOD, "same words: " + exact.score); + assertEqual(3, exact.words.size()); + + // A missing word costs, and is the one marked. + PronunciationScorer.Result missing = PronunciationScorer.score("Quiero un caf\u00e9 con leche", + "quiero un cafe con"); + assertTrue(missing.score < exact.score, "a missing word scores lower"); + assertFalse(missing.words.get(missing.words.size() - 1).good(), "the last word was not said"); + assertTrue(missing.words.get(0).good(), "the first word was said"); + + // Nothing heard is nothing scored. + assertEqual(0, PronunciationScorer.score("Bonjour", "").score); + + // An alternative the recognizer offered can rescue a near miss. + PronunciationScorer.Result alt = PronunciationScorer.score("La cuenta, por favor", + "la cuesta por favor", new String[] {"la cuenta por favor"}, 0.6f); + assertTrue(alt.score >= PronunciationScorer.GOOD, "the alternative counts: " + alt.score); + return true; + } + + @Override + public boolean shouldExecuteOnEDT() { + return false; + } +} diff --git a/scripts/lingo/pom.xml b/scripts/lingo/pom.xml new file mode 100644 index 00000000000..03f1b474f17 --- /dev/null +++ b/scripts/lingo/pom.xml @@ -0,0 +1,321 @@ + + 4.0.0 + com.codenameone.examples.lingo + lingo + 1.0-SNAPSHOT + pom + lingo + lingo + https://www.codenameone.com + + + MIT No Attribution + https://opensource.org/license/mit-0 + repo + The same terms as the LICENSE file beside this pom + + + + + + shared + common + + + 8.0-SNAPSHOT + 8.0-SNAPSHOT + UTF-8 + 1.8 + 11 + 1.7.11 + 3.8.0 + 1.8 + 1.8 + 1.8 + lingo + + + + + com.codenameone + java-runtime + ${cn1.version} + + + com.codenameone + codenameone-core + ${cn1.version} + + + com.codenameone + codenameone-javase + ${cn1.version} + + + com.codenameone + codenameone-android-compat + ${cn1.version} + provided + + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + com.codenameone + codenameone-buildclient + ${cn1.version} + system + ${user.home}/.codenameone/CodeNameOneBuildClient.jar + + + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + + maven-antrun-plugin + org.apache.maven.plugins + 3.1.0 + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + + + + codenameone + https://repo.codenameone.com/maven2 + + true + + + false + + + + + + codenameone-plugins + https://repo.codenameone.com/maven2 + + true + + + false + + + + + + + + cn1-client-tests + + + codename1.platform + !backend + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + + + + + javascript + + + codename1.platform + javascript + + + ${basedir}/javascript/pom.xml + + + + javascript + + + + ios + + + codename1.platform + ios + + + ${basedir}/ios/pom.xml + + + + ios + + + + win + + + codename1.platform + win + + + ${basedir}/win/pom.xml + + + + win + + + + linux + + + codename1.platform + linux + + + ${basedir}/linux/pom.xml + + + + linux + + + + + backend + + + codename1.platform + backend + + + ${basedir}/backend/pom.xml + + + + backend + + + + android + + + codename1.platform + android + + + ${basedir}/android/pom.xml + + + + android + + + + javase + + + codename1.platform + javase + + + ${basedir}/javase/pom.xml + + + + javase + + + + cn1libs + + + ${basedir}/cn1libs/pom.xml + + + + cn1libs + + + + diff --git a/scripts/lingo/run-e2e.sh b/scripts/lingo/run-e2e.sh new file mode 100755 index 00000000000..31b507d3c84 --- /dev/null +++ b/scripts/lingo/run-e2e.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# +# The end-to-end tests: starts the Lingo server on the `test` profile, then +# runs the app's test suite against it in the Codename One simulator. +# +# run-e2e.sh [--native] [--prebuilt] +# +# --native runs the tests against the compiled server +# --prebuilt uses the server as it was last built, without building it again +# +# The tests drive the real screens: they sign in as a learner and a +# creator, register, and change the settings, while a second user acts +# through the API. They capture a few +# screens into target/e2e-shots and hold them against screenshots/. +# +# Needs JAVA_HOME on JDK 17 or newer, and the Codename One artifacts this project +# builds against in the local Maven repository. The simulator needs a display: +# xvfb-run is used when there is one, which is what makes this run on a CI +# machine and in a container. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +MVN="${MVN:-mvn}" +PORT="${LINGO_PORT:-18080}" +LOG="${LINGO_SERVER_LOG:-$HERE/target/e2e-server.log}" +SHOTS="$HERE/target/e2e-shots" +MODE="--jvm" +BUILD=1 +for arg in "$@"; do + case "$arg" in + --native) MODE="--native" ;; + --prebuilt) BUILD=0 ;; + *) echo "[lingo-e2e] unknown option: $arg" >&2; exit 2 ;; + esac +done + +mkdir -p "$HERE/target" +rm -rf "$SHOTS" +mkdir -p "$SHOTS" + +echo "[lingo-e2e] java: $(java -version 2>&1 | head -1)" +if [ "$BUILD" = 1 ]; then + "$HERE/backend/server.sh" build "$MODE" +fi + +echo "[lingo-e2e] starting the server on port $PORT" +CN1_PROFILE=test "$HERE/backend/server.sh" run "$MODE" --prebuilt --port "$PORT" >"$LOG" 2>&1 & +SERVER_PID=$! +cleanup() { + kill "$SERVER_PID" >/dev/null 2>&1 || true + wait "$SERVER_PID" 2>/dev/null || true +} +trap cleanup EXIT + +ready=0 +for _ in $(seq 1 90); do + if curl -fs -o /dev/null "http://localhost:$PORT/oauth2/jwks" 2>/dev/null; then + ready=1 + break + fi + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + break + fi + sleep 1 +done +if [ "$ready" != "1" ]; then + echo "[lingo-e2e] the server did not start; its log:" >&2 + cat "$LOG" >&2 || true + exit 1 +fi + +RUNNER=() +if command -v xvfb-run >/dev/null 2>&1; then + RUNNER=(xvfb-run -a -s "-screen 0 1280x1024x24") +fi + +# The simulator is a JVM the build forks, and JAVA_TOOL_OPTIONS is what reaches +# it: where the server is, where the captures go and where the goldens are. +# The heap is given a ceiling too. Left alone a JVM takes a quarter of the +# machine's memory before it collects anything, which on a shared runner is +# enough to have the kernel end it between two tests. +export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} -Xmx768m -Dlingo.server.url=http://localhost:$PORT -Dlingo.shots.dir=$SHOTS -Dlingo.goldens.dir=$HERE/screenshots" + +set +e +${RUNNER[@]+"${RUNNER[@]}"} "$MVN" -B -f "$HERE/pom.xml" -Dcodename1.platform=javase -Ptest verify +STATUS=$? +set -e + +# The second pass: the same tests with the simulator as a desktop window and +# not a phone, which is where the admin console is laid out side by side and +# wears the platform's own theme. Each test knows which pass it is for and +# passes untouched in the other (E2e.desktop()). +# +# The simulator is a desktop when its "desktopSkin" preference says so; there +# is no switch for it on the command line. Java keeps preferences in files only +# on Linux, where java.util.prefs.userRoot can point them at a directory of +# this run's own -- so that is where this pass runs, which covers CI and a +# container. Elsewhere it would mean rewriting the developer's own simulator +# preferences, and it is skipped with a word. +if [ "$STATUS" -eq 0 ] && [ "$(uname -s)" = "Linux" ]; then + PREFS="$HERE/target/e2e-desktop-prefs" + NODE="$PREFS/.java/.userPrefs/com/codename1/impl/javase" + rm -rf "$PREFS" + mkdir -p "$NODE" + cat >"$NODE/prefs.xml" <<'XML' + + + + + +XML + echo "[lingo-e2e] the desktop pass" + # The last two are the project's own build hints, from + # common/codenameone_settings.properties. A packaged desktop app is given + # them by its launcher; a test run starts the simulator in + # common/target/cn1-reports, from where it does not find the project's + # settings, so it has to be told. + export JAVA_TOOL_OPTIONS="$JAVA_TOOL_OPTIONS -Dlingo.e2e.desktop=true -Djava.util.prefs.userRoot=$PREFS -Dcodename1.arg.nativeTheme=native -Dcodename1.arg.desktop.titleBar=native" + set +e + ${RUNNER[@]+"${RUNNER[@]}"} "$MVN" -B -f "$HERE/pom.xml" -Dcodename1.platform=javase -Ptest verify + STATUS=$? + set -e +elif [ "$STATUS" -eq 0 ]; then + echo "[lingo-e2e] not on Linux: the desktop pass was skipped" +fi + +if [ "$STATUS" -ne 0 ]; then + echo "[lingo-e2e] the tests failed; the end of the server's log:" >&2 + tail -n 80 "$LOG" >&2 || true + exit "$STATUS" +fi +echo "[lingo-e2e] passed; captures are in $SHOTS" diff --git a/scripts/lingo/run-web-e2e.sh b/scripts/lingo/run-web-e2e.sh new file mode 100755 index 00000000000..55b01f11022 --- /dev/null +++ b/scripts/lingo/run-web-e2e.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# +# The web app, end to end: builds the Lingo server and the browser build of +# the app, starts the server with the app staged where it serves it from, and +# drives the hosted app in a headless browser (web-e2e.mjs). +# +# run-web-e2e.sh [--native] [--prebuilt] +# +# --native runs the compiled server; --prebuilt skips both builds and uses what +# `backend/server.sh build --web` left. +# +# What it proves: a person who opens the server's address gets the app, can sign +# in as the demo technician and reaches their day, with the live channel open. +# Screenshots of each step and the browser's log go to target/web-e2e. +# +# Needs JAVA_HOME on JDK 17 or newer, the Codename One artifacts this project builds +# against in the local Maven repository, and Node with Playwright and its +# Chromium: `npm ci && npx playwright install chromium` in scripts/, or a +# NODE_PATH that has it. Nothing here opens a window. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +PORT="${LINGO_WEB_PORT:-18081}" +OUT="${LINGO_WEB_OUT:-$HERE/target/web-e2e}" +LOG="$OUT/server.log" +MODE="--jvm" +PREBUILT=0 +for arg in "$@"; do + case "$arg" in + --native) MODE="--native" ;; + --prebuilt) PREBUILT=1 ;; + *) echo "[lingo-web] unknown argument $arg" >&2; exit 2 ;; + esac +done + +if ! command -v node >/dev/null 2>&1; then + echo "[lingo-web] node is not on the PATH; the browser is driven with Playwright" >&2 + exit 2 +fi + +rm -rf "$OUT" +mkdir -p "$OUT" + +echo "[lingo-web] java: $(java -version 2>&1 | head -1)" +if [ "$PREBUILT" = 0 ]; then + "$HERE/backend/server.sh" build "$MODE" --web +fi +if [ ! -f "$HERE/backend/target/webapp/index.html" ]; then + echo "[lingo-web] no web app is staged in backend/target/webapp" >&2 + exit 1 +fi + +echo "[lingo-web] starting the server on port $PORT" +CN1_PROFILE=test "$HERE/backend/server.sh" run "$MODE" --prebuilt --port "$PORT" >"$LOG" 2>&1 & +SERVER_PID=$! +cleanup() { + kill "$SERVER_PID" >/dev/null 2>&1 || true + wait "$SERVER_PID" 2>/dev/null || true +} +trap cleanup EXIT + +ready=0 +for _ in $(seq 1 90); do + if curl -fs -o /dev/null "http://localhost:$PORT/oauth2/jwks" 2>/dev/null; then + ready=1 + break + fi + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + break + fi + sleep 1 +done +if [ "$ready" != "1" ]; then + echo "[lingo-web] the server did not start; its log:" >&2 + cat "$LOG" >&2 || true + exit 1 +fi + +fail() { + echo "[lingo-web] FAILED: $*" >&2 + exit 1 +} + +# What no browser is needed to see: the app is at /, the API kept its paths, and +# the script that is most of the download goes out compressed. +headers="$(curl -fsS -D - -o /dev/null "http://localhost:$PORT/")" \ + || fail "the server did not answer at /" +echo "$headers" | grep -qi '^content-type: text/html' || fail "/ is not served as a page" +echo "$headers" | grep -qi '^cache-control: no-cache' || fail "/ is not revalidated" +headers="$(curl -fsS -H 'Accept-Encoding: gzip' -D - -o /dev/null \ + "http://localhost:$PORT/translated_app.js")" || fail "translated_app.js is not served" +echo "$headers" | grep -qi '^content-encoding: gzip' \ + || fail "translated_app.js was not served compressed" +status="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$PORT/api/me")" +[ "$status" = "401" ] || fail "/api/me answered $status without a token, not 401" + +set +e +URL="http://localhost:$PORT/" OUT="$OUT" node "$HERE/web-e2e.mjs" +STATUS=$? +set -e + +if [ "$STATUS" -ne 0 ]; then + echo "[lingo-web] the end of the browser's log:" >&2 + tail -n 40 "$OUT/browser.log" >&2 || true + echo "[lingo-web] the end of the server's log:" >&2 + tail -n 40 "$LOG" >&2 || true + exit "$STATUS" +fi +echo "[lingo-web] passed; screenshots are in $OUT" diff --git a/scripts/lingo/shared/pom.xml b/scripts/lingo/shared/pom.xml new file mode 100644 index 00000000000..9418b59ac72 --- /dev/null +++ b/scripts/lingo/shared/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.codenameone.examples.lingo + lingo + 1.0-SNAPSHOT + + com.codenameone.examples.lingo + lingo-shared + 1.0-SNAPSHOT + jar + lingo-shared + + + + 17 + 17 + + + + + com.codenameone + codenameone-core + provided + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + + diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountApi.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountApi.java new file mode 100644 index 00000000000..877cea7ea1c --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountApi.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.PUT; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; + +/// Opening an account, asking who is signed in, and the +/// settings an account keeps. +/// +/// The app calls these through the generated client. The server implements the +/// generated `AccountApiServer`, and its build routes each path to that +/// implementation; neither side writes the other's half. +@RestClient +public interface AccountApi { + /// Opens an account. The one call here that needs no sign-in. + @POST("/api/account/register") + void register(@Body RegisterDto request, OnComplete> callback); + + @GET("/api/me") + void me(OnComplete> callback); + + /// A ticket for the live channel; see [TicketDto]. + @POST("/api/live/ticket") + void liveTicket(OnComplete> callback); + + @GET("/api/account/preferences") + void preferences(OnComplete> callback); + + @PUT("/api/account/preferences") + void savePreferences(@Body PreferencesDto preferences, + OnComplete> callback); + + @GET("/api/account/profile") + void profile(OnComplete> callback); + + @PUT("/api/account/profile") + void saveProfile(@Body ProfileDto profile, OnComplete> callback); + + @POST("/api/account/password") + void changePassword(@Body PasswordChangeDto change, OnComplete> callback); + + /// Closes the account for good. Refused without the account's password: a token is what a borrowed phone + /// holds too, and this cannot be taken back. + @POST("/api/account/delete") + void deleteAccount(@Body AccountClosureDto closure, OnComplete> callback); + + // tag::lingo-push-contract[] + /// Records a device the signed-in account is to be sent notifications on. + /// Registering the same token again moves it to this account: a phone + /// belongs to whoever signed in on it last. + @POST("/api/account/push") + void registerPush(@Body PushDeviceDto device, OnComplete> callback); + + /// Forgets a device, on signing out: the next person to use the phone is + /// not to be told about this account's classes. + @POST("/api/account/push/remove") + void unregisterPush(@Body PushDeviceDto device, OnComplete> callback); + // end::lingo-push-contract[] +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountChangeDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountChangeDto.java new file mode 100644 index 00000000000..c156e352774 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountChangeDto.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// What an admin sets on an account: its roles and whether it may sign in. +@Mapped +public record AccountChangeDto( + String username, + boolean learner, + boolean creator, + boolean admin, + boolean suspended) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountClosureDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountClosureDto.java new file mode 100644 index 00000000000..e2184c7ccaf --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AccountClosureDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// The request to close an account: the password of whoever is asking. +@Mapped +public record AccountClosureDto(String password) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AchievementDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AchievementDto.java new file mode 100644 index 00000000000..5b2678c1090 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AchievementDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A badge. `icon` is a Material icon name the app maps to a glyph. +@Mapped +public record AchievementDto( + String id, String title, String description, String icon, int xp, boolean unlocked, long unlockedAt, int progress, int goal) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AdminApi.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AdminApi.java new file mode 100644 index 00000000000..cb840b7da92 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AdminApi.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// The admin's console: who has an account and what it may do. Everything +/// here needs the ADMIN role. This is how a deployment gets its first +/// creators: registering makes a learner, and only an admin grants more. +/// +/// An account is named in the body, not the path: account names are e-mail +/// addresses, and an `@` in a path segment is one more thing to escape. +@RestClient +public interface AdminApi { + /// Every account, newest first. + @GET("/api/admin/accounts") + void accounts(OnComplete>> callback); + + /// Sets an account's roles and whether it is suspended. + @POST("/api/admin/accounts") + void changeAccount(@Body AccountChangeDto change, OnComplete> callback); +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AttemptDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AttemptDto.java new file mode 100644 index 00000000000..7ab51f72937 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/AttemptDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// What a learner did in a lesson: the score (0 to 100) and how long it took. +@Mapped +public record AttemptDto( + int score, int seconds, int spoken) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificateDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificateDto.java new file mode 100644 index 00000000000..7f009ddc5e6 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificateDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A certificate of completion the server issued and signed. +@Mapped +public record CertificateDto( + String id, String courseId, String courseTitle, String learnerName, String language, + long issuedAt, int minutes, String verifyUrl) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificatePdfDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificatePdfDto.java new file mode 100644 index 00000000000..65dc5de06de --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CertificatePdfDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// The signed PDF of a certificate, base 64 encoded. +@Mapped +public record CertificatePdfDto( + String id, String pdf) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDraftDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDraftDto.java new file mode 100644 index 00000000000..8d23dba342c --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDraftDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A new comment. +@Mapped +public record CommentDraftDto( + String text, String parentId) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDto.java new file mode 100644 index 00000000000..4c9a585d861 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommentDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A question or answer under a course. +@Mapped +public record CommentDto( + String id, String courseId, String parentId, String author, String authorName, String text, long createdAt, boolean creator) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommunityApi.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommunityApi.java new file mode 100644 index 00000000000..80aad8e14af --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CommunityApi.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.Path; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// Community: questions under a course, live tutorials and payments. +@RestClient +public interface CommunityApi { + @GET("/api/courses/{id}/comments") + void comments(@Path("id") String courseId, OnComplete>> callback); + + @POST("/api/courses/{id}/comments") + void comment(@Path("id") String courseId, @Body CommentDraftDto draft, + OnComplete> callback); + + @GET("/api/live") + void sessions(OnComplete>> callback); + + /// Takes a seat. A paid session must be bought first, through + /// [#purchase]. + @POST("/api/live/{id}/join") + void join(@Path("id") String id, OnComplete> callback); + + @POST("/api/purchases") + void purchase(@Body PurchaseDto purchase, OnComplete> callback); + + @GET("/api/wallet") + void wallet(OnComplete> callback); +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDetailDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDetailDto.java new file mode 100644 index 00000000000..06e2641abe1 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDetailDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A course with its lessons, in order. +@Mapped +public record CourseDetailDto( + CourseDto course, List lessons) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDraftDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDraftDto.java new file mode 100644 index 00000000000..d34740e902b --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDraftDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A course a creator writes. +@Mapped +public record CourseDraftDto( + String title, String language, String level, String summary, int priceCents, String accent) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDto.java new file mode 100644 index 00000000000..4229ff23f2d --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/CourseDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A course in the catalogue, as a learner sees it. +@Mapped +public record CourseDto( + String id, String title, String language, String level, String summary, + String kind, String creator, String creatorName, int priceCents, int lessons, + int minutes, boolean enrolled, boolean owned, int completedLessons, String accent, + boolean published, int learners) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/Languages.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/Languages.java new file mode 100644 index 00000000000..347ed19c6da --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/Languages.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +/// The names of the languages courses are taught in, by BCP 47 tag. +public final class Languages { + private static final String[][] NAMES = { + {"es", "Spanish"}, {"fr", "French"}, {"de", "German"}, {"it", "Italian"}, + {"pt", "Portuguese"}, {"ja", "Japanese"}, {"en", "English"}, {"nl", "Dutch"}, + }; + + private Languages() { + } + + /// `Spanish` for `es-ES` or `es`; the tag itself for one not listed. + public static String name(String tag) { + String base = tag == null ? "" : tag; + int dash = base.indexOf('-'); + if (dash > 0) { + base = base.substring(0, dash); + } + for (String[] row : NAMES) { + if (row[0].equals(base)) { + return row[1]; + } + } + return tag == null ? "" : tag; + } + + /// The flag-free short label a course card shows: `ES` for `es-ES`. + /// Folded by hand: a tag is ASCII, and `toUpperCase()` follows the + /// device's locale. + public static String code(String tag) { + StringBuilder out = new StringBuilder(); + for (int iter = 0; tag != null && iter < tag.length() && tag.charAt(iter) != '-'; iter++) { + char c = tag.charAt(iter); + out.append(c >= 'a' && c <= 'z' ? (char) (c - ('a' - 'A')) : c); + } + return out.toString(); + } +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LeaderEntryDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LeaderEntryDto.java new file mode 100644 index 00000000000..a903f6403fd --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LeaderEntryDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A row of the weekly leaderboard. +@Mapped +public record LeaderEntryDto( + int rank, String displayName, int xp, int streak, boolean me) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LearnApi.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LearnApi.java new file mode 100644 index 00000000000..094dd0d5d76 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LearnApi.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.Path; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// Learning: the catalogue, lessons, progress, badges and certificates. +@RestClient +public interface LearnApi { + @GET("/api/courses") + void courses(OnComplete>> callback); + + @GET("/api/courses/{id}") + void course(@Path("id") String id, OnComplete> callback); + + /// Joins a free course, or one already bought. + @POST("/api/courses/{id}/enroll") + void enroll(@Path("id") String id, OnComplete> callback); + + /// Records a finished lesson. The server works out the experience, + /// the streak and the badges, so a modified app cannot award itself any. + @POST("/api/lessons/{id}/attempt") + void attempt(@Path("id") String id, @Body AttemptDto attempt, + OnComplete> callback); + + @GET("/api/me/stats") + void stats(OnComplete> callback); + + @GET("/api/achievements") + void achievements(OnComplete>> callback); + + @GET("/api/leaderboard") + void leaderboard(OnComplete>> callback); + + @GET("/api/certificates") + void certificates(OnComplete>> callback); + + @GET("/api/certificates/{id}/pdf") + void certificatePdf(@Path("id") String id, OnComplete> callback); + + /// Anyone may ask, signed in or not: this is what the QR code on a + /// certificate opens. + @GET("/api/verify/{id}") + void verify(@Path("id") String id, OnComplete> callback); + + /// The cloud tutor, for a phone that cannot run a model and whose owner + /// opted in. Answers `available == false` when the server has no key. + @POST("/api/tutor/reply") + void tutor(@Body TutorRequestDto request, OnComplete> callback); +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDraftDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDraftDto.java new file mode 100644 index 00000000000..3382f550e4d --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDraftDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A lesson a creator adds. +@Mapped +public record LessonDraftDto( + String title, String kind, String summary, List phrases, String scenario, String videoUrl, int minutes) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDto.java new file mode 100644 index 00000000000..d7493f9327b --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LessonDto.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A lesson of a course. `kind` is `phrases` (say each phrase), `conversation` +/// (talk with the tutor about `scenario`) or `video` (watch `videoUrl`). +@Mapped +public record LessonDto( + String id, String courseId, int position, String title, String kind, + String summary, List phrases, String scenario, String videoUrl, + int minutes, int xp, boolean completed, int bestScore, boolean locked) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveDraftDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveDraftDto.java new file mode 100644 index 00000000000..39880920841 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveDraftDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A live tutorial a creator schedules. +@Mapped +public record LiveDraftDto( + String title, String language, String level, long startsAt, int minutes, int priceCents, int seats) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveSessionDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveSessionDto.java new file mode 100644 index 00000000000..873c3314290 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/LiveSessionDto.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A live tutorial a creator hosts. `state` is `scheduled`, `live` or `ended`. +@Mapped +public record LiveSessionDto( + String id, String title, String language, String level, String host, String hostName, + long startsAt, int minutes, int priceCents, int seats, int booked, String state, + boolean joined, boolean mine) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PasswordChangeDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PasswordChangeDto.java new file mode 100644 index 00000000000..55db0276410 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PasswordChangeDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A change of password: the one in use, and the one to use from now on. +@Mapped +public record PasswordChangeDto(String current, String replacement) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PhraseDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PhraseDto.java new file mode 100644 index 00000000000..5e16a9eb7e0 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PhraseDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// One thing to say: the target text, what it means, and a tip for saying it. +@Mapped +public record PhraseDto( + String text, String translation, String hint) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PreferencesDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PreferencesDto.java new file mode 100644 index 00000000000..2d136ca4ac1 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PreferencesDto.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// Settings that follow the account between devices. +@Mapped +public record PreferencesDto( + String language, + String theme, + boolean notifyReminders, + boolean notifyLive, + boolean wifiOnlyModel, + boolean cloudTutor) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProfileDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProfileDto.java new file mode 100644 index 00000000000..203e224684d --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProfileDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// What an account says about itself. +@Mapped +public record ProfileDto( + String name, + String phone) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProgressDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProgressDto.java new file mode 100644 index 00000000000..c198fb0c58a --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ProgressDto.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// The outcome of an attempt: what it earned and what it unlocked. +@Mapped +public record ProgressDto( + int xpEarned, StatsDto stats, List unlocked, + boolean courseCompleted, String certificateId) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PurchaseDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PurchaseDto.java new file mode 100644 index 00000000000..fc3ad41b7f0 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PurchaseDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// Something to pay for. `kind` is `course`, `live`, `pro` or `tip`; the +/// amount is only read for a tip. +@Mapped +public record PurchaseDto( + String kind, String targetId, int amountCents, String method) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PushDeviceDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PushDeviceDto.java new file mode 100644 index 00000000000..2ce6e08a31b --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/PushDeviceDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A device that can be sent push notifications, as the app registers it. +/// +/// `provider` is the push service the device's token belongs to -- `fcm`, +/// `apns`, `huawei`, `wns` or `web` -- and `token` the token that service gave +/// the app. `platform` is the device's platform name, for the record only. +@Mapped +public record PushDeviceDto(String provider, String token, String platform) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ReceiptDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ReceiptDto.java new file mode 100644 index 00000000000..f8ed21c3470 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/ReceiptDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A payment that went through, and the creator's share of it. +@Mapped +public record ReceiptDto( + String id, String kind, String description, int amountCents, int creatorShareCents, long createdAt) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/RegisterDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/RegisterDto.java new file mode 100644 index 00000000000..7011b96865e --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/RegisterDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// Opening an account. New accounts are learners; the creator role is granted. +@Mapped +public record RegisterDto( + String email, + String password, + String displayName, + String phone) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StatsDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StatsDto.java new file mode 100644 index 00000000000..9b90a3231ce --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StatsDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A learner's standing: experience, level, streak and today's goal. +@Mapped +public record StatsDto( + int xp, int level, int levelXp, int nextLevelXp, int streak, int bestStreak, + int todayXp, int dailyGoal, int lessonsDone, int minutes, int freezes, boolean pro, + List week) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioApi.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioApi.java new file mode 100644 index 00000000000..7ca77ddc852 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioApi.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.Path; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// The creator's studio: writing courses, recording lessons, hosting live +/// tutorials. Every call needs the creator role. +@RestClient +public interface StudioApi { + @GET("/api/studio") + void studio(OnComplete> callback); + + @POST("/api/studio/courses") + void createCourse(@Body CourseDraftDto draft, OnComplete> callback); + + @POST("/api/studio/courses/{id}/lessons") + void addLesson(@Path("id") String courseId, @Body LessonDraftDto draft, + OnComplete> callback); + + @POST("/api/studio/courses/{id}/publish") + void publish(@Path("id") String courseId, OnComplete> callback); + + @POST("/api/studio/uploads") + void upload(@Body UploadDto upload, OnComplete> callback); + + @POST("/api/studio/live") + void schedule(@Body LiveDraftDto draft, OnComplete> callback); + + /// Opens a session to the learners who booked it; they are told over the + /// live channel. + @POST("/api/studio/live/{id}/start") + void start(@Path("id") String id, OnComplete> callback); + + @POST("/api/studio/live/{id}/end") + void end(@Path("id") String id, OnComplete> callback); +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioDto.java new file mode 100644 index 00000000000..12305fb25d1 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/StudioDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A creator's dashboard: their courses, sessions and earnings. +@Mapped +public record StudioDto( + List courses, List sessions, int earningsCents, int learners) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TicketDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TicketDto.java new file mode 100644 index 00000000000..0bbe1247733 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TicketDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A single-use ticket for opening the live channel. +/// +/// A WebSocket handshake cannot carry the bearer token on every platform, so the +/// app asks for a ticket over the authenticated API and presents it in the +/// connection address. It is good for one connection and for a few seconds. +@Mapped +public record TicketDto(String ticket, int expiresInSeconds) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorPrompt.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorPrompt.java new file mode 100644 index 00000000000..9eabcb2eb5d --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorPrompt.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +/// What the tutor is told, and how its answer is read, wherever it runs: the +/// phone's own model, one the app downloaded, or the cloud model the server +/// calls. One prompt, so a learner gets the same partner from each. +public final class TutorPrompt { + /// The marker of the correction line. + public static final String FIX = "FIX:"; + + private TutorPrompt() { + } + + /// The system prompt for a conversation in `languageTag` at CEFR + /// `level`, playing out `scenario`. + public static String system(String languageTag, String level, String scenario) { + String language = Languages.name(languageTag); + return "You are a friendly " + language + " conversation partner for a learner at CEFR " + + "level " + (level == null || level.length() == 0 ? "A1" : level) + ". " + + "Role-play this scenario: " + + (scenario == null || scenario.length() == 0 ? "small talk" : scenario) + + ". Reply only in " + language + ", in one or two short sentences the learner " + + "can say back, and end with a question that keeps the conversation going. " + + "If the learner's last message had a mistake, add a final line starting " + + "with " + FIX + " giving the corrected sentence and a five-word reason in " + + "English. Never discuss anything unrelated to practising the language."; + } + + /// What a model is sent to open the conversation, before the learner + /// has said anything. + public static final String OPENING = "(The learner is ready. Open the conversation.)"; + + /// The reply and the correction (empty for none) a model's `text` holds. + public static String[] split(String text) { + String all = text == null ? "" : text.trim(); + int at = all.lastIndexOf(FIX); + if (at < 0) { + return new String[] {all, ""}; + } + return new String[] {all.substring(0, at).trim(), all.substring(at + FIX.length()).trim()}; + } +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorReplyDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorReplyDto.java new file mode 100644 index 00000000000..20d914279a5 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorReplyDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// The cloud tutor's next turn, and a correction of the learner's last one. +@Mapped +public record TutorReplyDto( + String text, String correction, boolean available) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorRequestDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorRequestDto.java new file mode 100644 index 00000000000..c09cfc8e1a1 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorRequestDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A conversation for the server's cloud tutor to continue. +@Mapped +public record TutorRequestDto( + String language, String level, String scenario, List turns) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorTurnDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorTurnDto.java new file mode 100644 index 00000000000..b3024ae74d3 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/TutorTurnDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// One turn of a conversation with the tutor; `role` is `user` or `assistant`. +@Mapped +public record TutorTurnDto( + String role, String text) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadDto.java new file mode 100644 index 00000000000..54336b816e1 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// A file the app uploads in one request, base 64 encoded: a recorded lesson. +@Mapped +public record UploadDto( + String name, String mime, String data) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadedDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadedDto.java new file mode 100644 index 00000000000..0cda0b424c6 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UploadedDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// Where an uploaded file can be played from. +@Mapped +public record UploadedDto( + String url, int bytes) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UserDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UserDto.java new file mode 100644 index 00000000000..b493b11ee83 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/UserDto.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// An account as the app sees it. A learner account carries the id of its learner record. +@Mapped +public record UserDto( + String username, + String displayName, + String phone, + boolean learner, + boolean creator, + boolean admin, + boolean suspended, + String targetLanguage, + String language) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/VerificationDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/VerificationDto.java new file mode 100644 index 00000000000..e4bbd1f98cd --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/VerificationDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; + +/// What the server found when it checked a certificate's signature. +@Mapped +public record VerificationDto( + String id, boolean found, boolean valid, boolean wholeDocument, String learnerName, + String courseTitle, long issuedAt, String signer, String algorithm) { +} diff --git a/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/WalletDto.java b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/WalletDto.java new file mode 100644 index 00000000000..24b35c26888 --- /dev/null +++ b/scripts/lingo/shared/src/main/java/com/codenameone/examples/lingo/api/WalletDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.lingo.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// A learner's purchases, and a creator's earnings. +@Mapped +public record WalletDto( + boolean pro, int earningsCents, int pendingCents, List receipts, List sales) { +} diff --git a/scripts/lingo/tools/make-seed-videos.py b/scripts/lingo/tools/make-seed-videos.py new file mode 100644 index 00000000000..6dd7d115ab2 --- /dev/null +++ b/scripts/lingo/tools/make-seed-videos.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Codename One and/or its affiliates. MIT-0, see LICENSE. +"""Renders the two recorded lessons the demo server seeds, as slide decks. + +Each slide is drawn with Pillow and held for a few seconds; ffmpeg encodes the +deck as a small H.264 MP4 that every port's media player can play. Run it +again after editing a slide; the outputs are committed under +backend/src/main/resources/seed. + + python3 tools/make-seed-videos.py +""" +import os +import shutil +import subprocess +import sys +import tempfile + +from PIL import Image, ImageDraw, ImageFont + +W, H = 960, 540 +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(HERE, "..", "backend", "src", "main", "resources", "seed") +FONTS = ["/System/Library/Fonts/Supplemental/Arial Bold.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"] +REGULAR = ["/System/Library/Fonts/Supplemental/Arial.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] + +DECKS = { + "the-spanish-r.mp4": ("#e5484d", [ + ("Sounds of Spanish", "Rolling your R", "Lesson 1 of 3"), + ("Tap R", "pero (but)", "One quick flick of the tongue, like the tt in 'butter'"), + ("Trilled R", "perro (dog)", "Several taps in a row. Relax the tongue and blow"), + ("Where each one goes", "rojo | carro", "R at the start of a word, or RR: always trilled"), + ("Practice", "Tres tristes tigres", "Three sad tigers. Say it slowly, then faster"), + ("Your turn", "Open the next lesson", "Lingo listens and scores every R"), + ]), + "madrid-cafe.mp4": ("#f59e0b", [ + ("Cafe culture in Madrid", "Ordering like a local", "A recorded lesson"), + ("Morning", "Un cafe con leche", "Coffee with milk: the classic breakfast order"), + ("Short and strong", "Un cortado", "Espresso with a drop of milk, after lunch"), + ("Something to eat", "Una tostada con tomate", "Toast rubbed with tomato and olive oil"), + ("Paying", "La cuenta, por favor", "Nobody brings the bill until you ask"), + ("Your turn", "Order your breakfast", "Practise it in the next lesson"), + ]), +} + + +def font(paths, size): + for path in paths: + if os.path.exists(path): + return ImageFont.truetype(path, size) + return ImageFont.load_default() + + +def centred(draw, text, y, fnt, fill): + box = draw.textbbox((0, 0), text, font=fnt) + draw.text(((W - (box[2] - box[0])) / 2, y), text, font=fnt, fill=fill) + + +def slide(accent, kicker, title, body, index, count): + img = Image.new("RGB", (W, H), "#12161c") + d = ImageDraw.Draw(img) + d.rectangle([0, 0, W, 10], fill=accent) + d.rounded_rectangle([60, 70, W - 60, H - 70], radius=36, fill="#1c222b") + centred(d, kicker.upper(), 130, font(FONTS, 26), accent) + centred(d, title, 200, font(FONTS, 64), "#f2f4f7") + centred(d, body, 320, font(REGULAR, 28), "#98a2b3") + # Progress dots along the bottom. + for i in range(count): + x = W / 2 - (count - 1) * 14 + i * 28 + d.ellipse([x - 6, H - 120, x + 6, H - 108], fill=accent if i <= index else "#3b4452") + centred(d, "LINGO", H - 60, font(FONTS, 20), "#8b8cff") + return img + + +def main(): + if shutil.which("ffmpeg") is None: + sys.exit("ffmpeg is needed on the PATH") + os.makedirs(OUT, exist_ok=True) + for name, (accent, slides) in DECKS.items(): + work = tempfile.mkdtemp(prefix="lingo-seed-") + try: + listing = [] + for i, (kicker, title, body) in enumerate(slides): + path = os.path.join(work, "s%02d.png" % i) + slide(accent, kicker, title, body, i, len(slides)).save(path) + listing.append("file '%s'\nduration 4\n" % path) + # The concat demuxer needs the last file named again to hold it. + listing.append("file '%s'\n" % os.path.join(work, "s%02d.png" % (len(slides) - 1))) + concat = os.path.join(work, "deck.txt") + with open(concat, "w") as f: + f.write("".join(listing)) + subprocess.check_call([ + "ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", + "-i", concat, "-vf", "fps=12,format=yuv420p", "-c:v", "libx264", + "-profile:v", "baseline", "-level", "3.0", "-crf", "30", + "-movflags", "+faststart", os.path.join(OUT, name)]) + print(name, os.path.getsize(os.path.join(OUT, name)), "bytes") + finally: + shutil.rmtree(work) + + +if __name__ == "__main__": + main() diff --git a/scripts/lingo/web-e2e.mjs b/scripts/lingo/web-e2e.mjs new file mode 100644 index 00000000000..6622acbc337 --- /dev/null +++ b/scripts/lingo/web-e2e.mjs @@ -0,0 +1,333 @@ +// The Lingo web app, hosted by its own server, driven in a headless browser. +// +// URL=http://localhost:18081/ OUT=target/web-e2e node web-e2e.mjs +// +// It checks what a person opening the server's address gets: the app loads from +// the server, reaches the welcome screen, signs in as the demo learner, lands on +// today's practice, and has its live channel open. Then it signs out from the Me +// tab, signs in as the demo creator and reaches the studio. +// run-web-e2e.sh builds everything, starts the server and runs this; see there. +// +// The app draws on a canvas, so there are no buttons in the page to ask a +// browser automation tool for. What there is, is the accessibility tree the +// port keeps over the canvas -- an element per component, with its role, its +// label and where it is -- and that is what this reads to find a button and +// what it clicks at. Text fields become real elements while they are +// being edited, so typing is ordinary typing. +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'node:module'; + +// require() and not import: it also looks in NODE_PATH, which is how a +// container whose packages are installed somewhere else finds Playwright. +const require = createRequire(import.meta.url); +let chromium; +try { + ({ chromium } = require('playwright')); +} catch (err) { + console.error('[lingo-web] Playwright is not installed. Run `npm ci` in scripts/ and ' + + '`npx playwright install chromium`, or point NODE_PATH at a node_modules that has it.'); + console.error(String(err)); + process.exit(2); +} + +const url = process.env.URL; +const out = process.env.OUT || 'target/web-e2e'; +const email = process.env.LINGO_USER || 'learner@lingo.example'; +const password = process.env.LINGO_PASSWORD || 'lingo-demo'; +const admin = process.env.LINGO_CREATOR || 'creator@lingo.example'; +// A cold runner translates nothing at this point, but it does parse several +// megabytes of JavaScript before the first screen. +const startSeconds = Number(process.env.LINGO_WEB_START_SECONDS || '120'); +const stepSeconds = Number(process.env.LINGO_WEB_STEP_SECONDS || '45'); +if (!url) { + console.error('[lingo-web] URL is required'); + process.exit(2); +} +fs.mkdirSync(out, { recursive: true }); +const logFile = path.join(out, 'browser.log'); +fs.writeFileSync(logFile, ''); +const note = line => fs.appendFileSync(logFile, line + '\n'); +const say = line => { console.log('[lingo-web] ' + line); note('# ' + line); }; + +const origin = new URL(url).origin; +const requests = []; // "200 POST /login", in order +const problems = []; // anything that must not happen +const sockets = []; // { url, frames: [...] } + +const browser = await chromium.launch({ + headless: true, + // A headless page counts as hidden, and a hidden page's timers are throttled + // to about one a minute once its budget is spent. The app's threads sleep on + // those timers. + args: ['--disable-background-timer-throttling', '--disable-renderer-backgrounding', + '--disable-backgrounding-occluded-windows', '--disable-features=IntensiveWakeUpThrottling'] +}); +const page = await browser.newPage({ viewport: { width: 420, height: 860 } }); +page.on('console', message => { + const text = message.text(); + if (text.startsWith('LF-SHIM')) { + return; + } + note(`[${message.type()}] ${text}`); + if (/internal application error|Missing JS member/i.test(text)) { + problems.push('the app reported an error: ' + text.split('\n')[0]); + } +}); +page.on('pageerror', err => { + note('[pageerror] ' + err); + problems.push('the page threw: ' + err); +}); +page.on('response', response => { + const at = new URL(response.url()); + if (at.origin !== origin) { + return; + } + const line = `${response.status()} ${response.request().method()} ${at.pathname}`; + requests.push(line); + note('NET ' + line); +}); +page.on('websocket', socket => { + const seen = { url: socket.url(), frames: [] }; + sockets.push(seen); + note('WS open ' + socket.url().replace(/ticket=.*/, 'ticket=...')); + socket.on('framereceived', frame => { + seen.frames.push(String(frame.payload)); + note('WS frame ' + String(frame.payload).slice(0, 200)); + }); +}); + +/// What the app has on screen, as the port describes it to assistive technology. +async function components() { + return page.evaluate(() => Array.from( + document.querySelectorAll('#cn1-accessibility-tree [data-cn1-accessibility-id]')).map(el => { + const box = el.getBoundingClientRect(); + return { + role: el.getAttribute('role'), + label: el.getAttribute('aria-label'), + text: el.innerText, + x: box.x, y: box.y, width: box.width, height: box.height + }; + })); +} + +async function screenText() { + return page.evaluate(() => document.body.innerText); +} + +async function waitFor(what, seconds, probe) { + const end = Date.now() + seconds * 1000; + for (;;) { + const hit = await probe(); + if (hit) { + return hit; + } + if (problems.length > 0) { + throw new Error(problems[0]); + } + if (Date.now() > end) { + throw new Error(`timed out after ${seconds}s waiting for ${what}`); + } + await page.waitForTimeout(250); + } +} + +const button = label => async () => + (await components()).find(c => c.role === 'button' && c.label === label); + +/// The single-line fields of the form on screen, top to bottom. +async function fields() { + return (await components()).filter(c => c.role === 'textbox' && c.height > 40 && c.height < 120) + .sort((a, b) => a.y - b.y); +} + +async function click(component) { + await page.mouse.click(component.x + component.width / 2, component.y + component.height / 2); +} + +/// Waits until nothing on screen has moved for a moment. A form slides in, and +/// a click aimed at where a field is half-way through lands on what was there. +async function settled() { + let before = JSON.stringify(await components()); + await waitFor('the screen to stop moving', stepSeconds, async () => { + await page.waitForTimeout(350); + const now = JSON.stringify(await components()); + const still = now === before; + before = now; + return still; + }); +} + +async function typeInto(index, text, type) { + const editing = () => page.evaluate( + wanted => document.activeElement && document.activeElement.tagName === 'INPUT' + && document.activeElement.type === wanted, type); + await waitFor(`the ${type} field to take the keyboard`, stepSeconds, async () => { + await settled(); + const all = await fields(); + if (all.length <= index) { + return false; + } + await click(all[index]); + await page.waitForTimeout(500); + return editing(); + }); + await page.keyboard.type(text, { delay: 10 }); +} + +/// Fills in the sign-in form the welcome screen opens, and sends it. +async function signInAs(who) { + await click(await waitFor('the welcome screen', startSeconds, button('Sign in'))); + await typeInto(0, who, 'email'); + await typeInto(1, password, 'password'); + // The form's own button now: the welcome screen's is gone with its form. + await settled(); + await click(await waitFor('the form\'s Sign in button', stepSeconds, async () => + (await fields()).length >= 2 ? button('Sign in')() : null)); + say('submitted the sign-in form as ' + who); +} + +/// Fails on the dialog the app shows for an error nothing handled. +async function noErrorDialog() { + if (/internal application error/i.test(await screenText())) { + problems.push('the app is showing its internal-error dialog'); + } + if (problems.length > 0) { + throw new Error(problems[0]); + } +} + +let failed = null; +try { + say('opening ' + url); + const first = await page.goto(url, { waitUntil: 'load' }); + if (!first || first.status() !== 200) { + throw new Error('the server answered ' + (first ? first.status() : 'nothing') + ' at /'); + } + const type = first.headers()['content-type'] || ''; + if (!type.startsWith('text/html')) { + throw new Error('/ is served as ' + type + ', not as a page'); + } + + // 1. The welcome screen: the app started, in the browser, from this server. + const signIn = await waitFor('the welcome screen', startSeconds, button('Sign in')); + await waitFor('the welcome screen to offer an account', stepSeconds, button('Create an account')); + await page.screenshot({ path: path.join(out, '1-welcome.png') }); + say('the welcome screen is up'); + for (const file of ['/translated_app.js', '/port.js', '/worker.js']) { + if (!requests.includes('200 GET ' + file)) { + throw new Error(file + ' was not served by this server: ' + requests.join(', ')); + } + } + + // 2. Signing in. The form is the app's own; the flow behind it is the + // authorization-code flow against the server the page came from. + await signInAs(email); + + // The first sign-in in a browser is asked whether usage statistics may be + // shared. The answer is kept with the page's storage, so the creator's + // sign-in further down is not asked again. + await click(await waitFor('the usage statistics question', stepSeconds, button('Not now'))); + say('declined usage statistics'); + + // 3. The home screen: today's practice, with the bottom tabs. + await waitFor('the home screen', stepSeconds, async () => + (await screenText()).includes('Your courses')); + await page.screenshot({ path: path.join(out, '3-home.png') }); + say('signed in: the home screen is up'); + + const expected = ['200 POST /login', '200 GET /signin/code', '200 POST /oauth2/token', + '200 GET /api/me']; + for (const line of expected) { + if (!requests.includes(line)) { + throw new Error('signing in did not make the request "' + line + '"; it made: ' + + requests.filter(r => !/\.(js|css|png|res|gif|json|ttf)$/.test(r)).join(', ')); + } + } + + // 4. The live channel, a WebSocket to the same origin. + const live = await waitFor('the live channel', stepSeconds, async () => + sockets.find(s => s.frames.some(f => f.includes('"ready"')))); + const expectedSocket = origin.replace(/^http/, 'ws') + '/ws/live?ticket='; + if (!live.url.startsWith(expectedSocket)) { + throw new Error('the live channel went to ' + live.url + ', not to ' + expectedSocket); + } + say('the live channel is open'); + + // Give a late failure -- the first course cover, the first progress call -- + // the moment it needs to show itself. + await page.waitForTimeout(3000); + await noErrorDialog(); + await page.screenshot({ path: path.join(out, '4-settled.png') }); + + // 5. The session that carried the sign-in is over: the app ended it when it + // had its tokens, so the cookie the browser still holds is worth nothing. + await waitFor('the app to end its sign-in session', stepSeconds, async () => + requests.includes('204 POST /logout')); + const again = await page.evaluate(async () => (await fetch('/oauth2/authorize?response_type=code' + + '&client_id=lingo-app&scope=openid&state=x&code_challenge_method=S256' + + '&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM' + + '&redirect_uri=' + encodeURIComponent(location.origin + '/signin/code'), + { headers: { Accept: 'application/json' } })).status); + if (again === 200) { + throw new Error('the browser can still get an authorization code after signing in'); + } + say('the sign-in session is over (asking for another code is answered ' + again + ')'); + + // 6. Signing out, from the Me tab. Sign out is the last row of the tab, so + // the page is scrolled until it is on screen. + await settled(); + await click(await waitFor('the Me tab', stepSeconds, button('Me'))); + await settled(); + const signOut = await waitFor('Sign out on the Me tab', stepSeconds, async () => { + // The row is a tappable row, not a button, so it is found by its label; + // the tab bar takes the bottom of the screen. + const hit = (await components()).find(c => c.label === 'Sign out' + && c.y + c.height < page.viewportSize().height - 60); + if (!hit) { + await page.mouse.move(page.viewportSize().width / 2, page.viewportSize().height / 2); + await page.mouse.wheel(0, 400); + await page.waitForTimeout(300); + } + return hit; + }); + await settled(); + await click(signOut); + await waitFor('the welcome screen after signing out', stepSeconds, button('Create an account')); + await settled(); + await noErrorDialog(); + await page.screenshot({ path: path.join(out, '5-signed-out.png') }); + say('signed out: the welcome screen is back'); + + // 7. The creator, who lands on the studio. + await signInAs(admin); + await waitFor('the studio', stepSeconds, async () => { + const text = await screenText(); + return /Studio/.test(text) && /Courses/.test(text); + }); + await waitFor('the studio to ask the server for its numbers', stepSeconds, async () => + requests.some(r => /^200 GET \/api\/studio$/.test(r))); + await page.waitForTimeout(3000); + await settled(); + await noErrorDialog(); + await page.screenshot({ path: path.join(out, '6-studio.png') }); + say('signed in as ' + admin + ': the studio is up'); +} catch (err) { + failed = err; + try { + await page.screenshot({ path: path.join(out, 'failure.png') }); + fs.writeFileSync(path.join(out, 'failure.txt'), await screenText()); + fs.writeFileSync(path.join(out, 'failure-components.json'), + JSON.stringify(await components(), null, 1)); + } catch (ignored) { + // The page is gone; the log is what there is. + } +} +await browser.close(); + +if (failed) { + console.error('[lingo-web] FAILED: ' + failed.message); + console.error('[lingo-web] the browser log is ' + logFile); + process.exit(1); +} +say('passed'); diff --git a/scripts/pre-push-gates.sh b/scripts/pre-push-gates.sh index ea515ef5d58..9cb73c60507 100755 --- a/scripts/pre-push-gates.sh +++ b/scripts/pre-push-gates.sh @@ -149,6 +149,13 @@ export CN1_MAVEN_REPO_LOCAL="$REPO" on17() { if [ "$VALIDATE" = 1 ]; then "$@"; return; fi if [ -z "$JDK17" ]; then echo "no JDK 17: set JAVA17_HOME" >&2; return 1; fi JAVA_HOME="$JDK17" PATH="$JDK17/bin:$PATH" "$@"; } +# website-docs.yml runs scripts/website/build.sh on JDK 25: the skin designer +# it builds targets release 17, so tools/env.sh's JDK 8 cannot compile it. +JDK25="${JAVA25_HOME:-}" +if [ -z "$JDK25" ] && [ -x /usr/libexec/java_home ]; then JDK25="$(/usr/libexec/java_home -v 25 2>/dev/null || true)"; fi +on25() { if [ "$VALIDATE" = 1 ]; then "$@"; return; fi + if [ -z "$JDK25" ]; then echo "no JDK 25: set JAVA25_HOME" >&2; return 1; fi + JAVA_HOME="$JDK25" PATH="$JDK25/bin:$PATH" "$@"; } # Snapshots in this checkout's repository, for the gates that compile against # Codename One. Installed once, and reinstalled when @@ -157,8 +164,14 @@ SNAPSHOTS_READY=0 need_snapshots() { [ "$SNAPSHOTS_READY" = 1 ] && return 0 [ "$VALIDATE" = 1 ] && return 0 + # Keyed on the sources themselves, not on this branch's diff: merging master + # brings new core without the branch touching it, and the old key then kept + # snapshots that lacked master's new API (the site build failed compiling + # the JavaScript port against them). + local tree + tree="$( (git ls-tree -r HEAD -- CodenameOne Ports/JavaSE Ports/Android Ports/CLDC11 Ports/JavaScriptPort maven vm/JavaAPI vm/backend; git diff HEAD -- CodenameOne Ports maven vm) | git hash-object --stdin)" if [ -f "$REPO/com/codenameone/codenameone-maven-plugin/8.0-SNAPSHOT/codenameone-maven-plugin-8.0-SNAPSHOT.jar" ] && [ -f "$REPO/com/codenameone/codenameone-javac/8.0-SNAPSHOT/codenameone-javac-8.0-SNAPSHOT.jar" ] && - ! changed '^(CodenameOne|Ports/(JavaSE|Android|CLDC11)|maven/(core|javase|android|css-compiler|codenameone-maven-plugin|build-engine|annotation-processor|backend|python-runtime|flutter-runtime|dart-runtime|rive-runtime))/'; then + [ "$(cat "$REPO/.cn1-snapshot-tree" 2>/dev/null)" = "$tree" ]; then SNAPSHOTS_READY=1; return 0 fi note "installing Codename One snapshots into maven/.m2-repo" @@ -168,6 +181,7 @@ need_snapshots() { # JDK 17, as CI: it is what activates the flutter-modules profile. if (cd maven && on17 mvn -B -q -ntp install -Plocal-dev-javase -DskipTests -Dmaven.javadoc.skip=true \ -Dmaven.source.skip=true -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true); then + echo "$tree" > "$REPO/.cn1-snapshot-tree" SNAPSHOTS_READY=1 else FAILED+=("installing snapshots (mvn install -Plocal-dev-javase)"); return 1 @@ -257,7 +271,14 @@ if selected website-docs; then --step "Test developer guide chapter generation" \ --step "Check developer guide links against the routes this site serves" if [ "$FULL" = 1 ]; then - gate "Hugo site build (scripts/website/build.sh)" scripts/website/build.sh + # As website-docs.yml: the site's apps build against this tree's snapshots, + # never the pinned release plugin (which compiles today's JavaScript port + # against an old core). need_snapshots installs them, so build.sh is told + # the bootstrap is done rather than running setup-workspace.sh, which + # writes ../cn1-binaries and ~/.codenameone. + need_snapshots + gate "Hugo site build (scripts/website/build.sh)" on25 \ + env WEBSITE_BOOTSTRAP_CN1_SNAPSHOTS=true __CN1_SNAPSHOTS_BOOTSTRAPPED=true scripts/website/build.sh else skip "Hugo site build" "--full runs scripts/website/build.sh (local Hugo must match the CI pin)" fi diff --git a/scripts/sync-initializr-template.py b/scripts/sync-initializr-template.py index 510efda8ecc..de17b3945ae 100644 --- a/scripts/sync-initializr-template.py +++ b/scripts/sync-initializr-template.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Keep an Initializr full-stack template aligned with its sample (--write to update). - python3 scripts/sync-initializr-template.py wayline|savor|bazaar|skirmish|dash|splat|papercut|parley|bastion|reel|pulse|slate|fieldline [--write] + python3 scripts/sync-initializr-template.py wayline|savor|bazaar|skirmish|dash|splat|papercut|parley|bastion|reel|pulse|slate|fieldline|lingo [--write] scripts/ is the project CI builds and tests. The Initializr offers the same project as a template, from five resources this script derives from it: @@ -48,7 +48,7 @@ root = Path(__file__).resolve().parents[1] # The samples the Initializr offers as full-stack templates. Each is a project # under scripts/ whose Java package is com.codenameone.examples.. -SAMPLES = ('wayline', 'savor', 'bazaar', 'skirmish', 'dash', 'splat', 'papercut', 'parley', 'bastion', 'reel', 'pulse', 'slate', 'fieldline') +SAMPLES = ('wayline', 'savor', 'bazaar', 'skirmish', 'dash', 'splat', 'papercut', 'parley', 'bastion', 'reel', 'pulse', 'slate', 'fieldline', 'lingo') args = [a for a in sys.argv[1:] if not a.startswith('--')] if len(args) != 1 or args[0] not in SAMPLES: raise SystemExit('usage: sync-initializr-template.py ' + '|'.join(SAMPLES) + ' [--write]') diff --git a/scripts/tests/GenerateInitializr.java b/scripts/tests/GenerateInitializr.java index e9817f8b30d..bd193d6d609 100644 --- a/scripts/tests/GenerateInitializr.java +++ b/scripts/tests/GenerateInitializr.java @@ -90,7 +90,7 @@ public static void main(String[] args) throws Exception { } // The full-stack templates, each in both of its layouts and in a colour scheme of // its own with an icon: an app, its server and the module they share. - for (Template template : new Template[] {Template.WAYLINE, Template.SAVOR, Template.SKIRMISH, Template.DASH, Template.SPLAT, Template.PAPERCUT, Template.PARLEY, Template.BASTION, Template.REEL, Template.PULSE, Template.SLATE, Template.FIELDLINE, Template.BAZAAR}) { + for (Template template : new Template[] {Template.WAYLINE, Template.SAVOR, Template.SKIRMISH, Template.DASH, Template.SPLAT, Template.PAPERCUT, Template.PARLEY, Template.BASTION, Template.REEL, Template.PULSE, Template.SLATE, Template.FIELDLINE, Template.BAZAAR, Template.LINGO}) { for (boolean full : new boolean[] {false, true}) { ProjectOptions options = ProjectOptions.defaults().forFullStack().withPlatformModules(full) .withScheme(0x0f766e, false).withIcon(new byte[] {(byte)0x89, 'P', 'N', 'G'}); diff --git a/scripts/tests/generate-initializr-fixtures.py b/scripts/tests/generate-initializr-fixtures.py index de175a7a9c0..70d8ed8490a 100644 --- a/scripts/tests/generate-initializr-fixtures.py +++ b/scripts/tests/generate-initializr-fixtures.py @@ -107,6 +107,7 @@ def check_maven_layout_fixture(archive, z): 'SLATE': ('api/AppointmentApi.java', 'ui/WelcomeForm.java'), 'FIELDLINE': ('api/FieldApi.java', 'field/TodayForm.java'), 'BAZAAR': ('api/OrderApi.java', 'shop/CheckoutForm.java'), + 'LINGO': ('api/LearnApi.java', 'learn/LearnHome.java'), } @@ -125,6 +126,7 @@ def check_maven_layout_fixture(archive, z): 'SLATE': 'codename1.arg.ios.NSCalendarsFullAccessUsageDescription=', 'FIELDLINE': 'codename1.arg.ios.NSLocationWhenInUseUsageDescription=', 'BAZAAR': 'codename1.arg.ios.NSCameraUsageDescription=', + 'LINGO': 'codename1.arg.ios.NSSpeechRecognitionUsageDescription=', } diff --git a/scripts/website/build.sh b/scripts/website/build.sh index 07372271921..b6efde0f666 100755 --- a/scripts/website/build.sh +++ b/scripts/website/build.sh @@ -590,13 +590,13 @@ build_initializr_for_site() { # Ensure attached classifier artifact initializr-ZipSupport:jar:common is present # in the local Maven repo before building modules that depend on it (e.g. initializr-common). run_initializr_mvn -q -U -pl cn1libs/ZipSupport -am \ - "${initializr_workspace_args[@]}" \ + ${initializr_workspace_args+"${initializr_workspace_args}"} \ -DskipTests \ -Dcodename1.platform=javascript \ install run_initializr_mvn -q -U -pl javascript -am \ - "${initializr_workspace_args[@]}" \ + ${initializr_workspace_args+"${initializr_workspace_args}"} \ -DskipTests \ -Dautomated=true \ -Dcodename1.platform=javascript \ @@ -684,7 +684,7 @@ build_playground_for_site() { export CN1_TRANSLATOR_OPTS="${CN1_TRANSLATOR_OPTS:-$(cat "${REPO_ROOT}/scripts/cn1playground/javascript/translator-opts.txt")}" run_playground_mvn -q -U -pl javascript -am \ - "${playground_workspace_args[@]}" \ + ${playground_workspace_args+"${playground_workspace_args}"} \ -DskipTests \ -Dautomated=true \ -Dcodename1.platform=javascript \ @@ -760,6 +760,8 @@ build_skindesigner_for_site() { fi } + # Expanded as ${a[@]+"${a[@]}"}: macOS bash 3.2 treats an empty array as + # unbound under set -u, and this is empty outside a snapshot bootstrap. local skindesigner_workspace_args=() if [ "${WEBSITE_BOOTSTRAP_CN1_SNAPSHOTS}" = "true" ]; then skindesigner_workspace_args+=(-Dcn1.localWorkspace=true) @@ -768,13 +770,13 @@ build_skindesigner_for_site() { # Ensure attached classifier artifact skindesigner-ZipSupport:jar:common # is present in the local Maven repo before building skindesigner-common. run_skindesigner_mvn -q -U -pl cn1libs/ZipSupport -am \ - "${skindesigner_workspace_args[@]}" \ + ${skindesigner_workspace_args[@]+"${skindesigner_workspace_args[@]}"} \ -DskipTests \ -Dcodename1.platform=javascript \ install run_skindesigner_mvn -q -U -pl javascript -am \ - "${skindesigner_workspace_args[@]}" \ + ${skindesigner_workspace_args[@]+"${skindesigner_workspace_args[@]}"} \ -DskipTests \ -Dautomated=true \ -Dcodename1.platform=javascript \ diff --git a/scripts/website/validate_mermaid.mjs b/scripts/website/validate_mermaid.mjs index 1b5d5107fbe..3b4a78b0d76 100644 --- a/scripts/website/validate_mermaid.mjs +++ b/scripts/website/validate_mermaid.mjs @@ -151,8 +151,19 @@ async function main(args) { } for (const item of renderedFiles) { const relative = path.relative(site, item.file).split(path.sep).map(encodeURIComponent).join("/"); - try { await checkRenderedPage(page, `${served.base}/${relative}`, item.count); } - catch (err) { failures.push(`${engine}: ${item.source} -> ${item.file}\n${err.message}`); } + // Every generated page imports Mermaid from the CDN again, so over a + // few hundred pages one slow fetch times a page out. Retry a timeout + // once; a render error is reported the first time, and a page that + // times out twice still fails. + let attempt = 0; + for (;;) { + try { await checkRenderedPage(page, `${served.base}/${relative}`, item.count); break; } + catch (err) { + if (attempt++ === 0 && /timed out|Timeout \d+ms exceeded/.test(err.message)) continue; + failures.push(`${engine}: ${item.source} -> ${item.file}\n${err.message}`); + break; + } + } } console.log(`${engine}: checked ${diagrams.length} source renders and ${renderedFiles.length} generated pages.`); } finally { await browser.close(); }