diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82a8d9ba6dd..93422b75b39 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,7 @@ jobs: gpui: ${{ steps.filter.outputs.rust-without-cli == 'true' || steps.filter.outputs.gpui == 'true' }} gpui-patches: ${{ steps.filter.outputs.gpui-patches }} ios: ${{ steps.filter.outputs.ios }} + android: ${{ steps.filter.outputs.android }} steps: - name: Checkout uses: actions/checkout@v4 @@ -85,6 +86,10 @@ jobs: - 'scripts/prepare-gpui-dependency.sh' ios: - 'apps/mobile-ios/**' + android: + - '.github/workflows/ci.yml' + - 'apps/mobile-android/**' + - 'apps/mobile-ios/CapKit/Tests/CapKitTests/Fixtures/**' typecheck: name: Typecheck @@ -162,6 +167,28 @@ jobs: -derivedDataPath "$RUNNER_TEMP/cap-ios" CODE_SIGNING_ALLOWED=NO build + android: + name: Android + needs: changes + if: needs.changes.outputs.android == 'true' + runs-on: blacksmith-8vcpu-ubuntu-2404 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 17 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Check, test and build + working-directory: apps/mobile-android + run: ./gradlew spotlessCheck :capkit:test :app:testDebugUnitTest :app:lintDebug :app:assembleRelease + format-biome: name: Format (Biome) runs-on: blacksmith-8vcpu-ubuntu-2404 diff --git a/apps/mobile-android/.gitignore b/apps/mobile-android/.gitignore new file mode 100644 index 00000000000..40a37838734 --- /dev/null +++ b/apps/mobile-android/.gitignore @@ -0,0 +1,6 @@ +build/ +.gradle/ +.kotlin/ +local.properties +captures/ +*.iml diff --git a/apps/mobile-android/PLAN.md b/apps/mobile-android/PLAN.md new file mode 100644 index 00000000000..1db2160db7f --- /dev/null +++ b/apps/mobile-android/PLAN.md @@ -0,0 +1,1068 @@ +# Cap for Android: iOS audit and build plan + +Draft, 30 November 2026. This file is the whole of this branch: an audit of the iPhone app and a plan for a native Android app at feature parity. There is no Android code yet. It is opened as a draft to ask the Cap maintainers whether they want an Android app at all (Part 4, Q1). No Android code is proposed until they answer. + +Repo state audited: main at 5a1b9c73a (2026-11-29, "Merge pull request #4647 from CapSoftware/fix/linux-mic-false-disconnect"). + +## How to read this + +- Paths are repo-relative. To keep tables readable these prefixes are used: [A] apps/mobile-ios/Cap/App, [F] apps/mobile-ios/Cap/Features, [D] apps/mobile-ios/Cap/DesignSystem, [K] apps/mobile-ios/CapKit/Sources/CapKit, [B] apps/mobile-ios/CapBroadcast, [W] apps/mobile-ios/CapWidgets, [C] apps/mobile-ios/Config, [P] apps/mobile-ios/Cap.xcodeproj/project.pbxproj, [T] apps/mobile-ios/CapKit/Tests/CapKitTests, [U] apps/mobile-ios/CapUITests. "route.ts" means apps/web/app/api/mobile/[...route]/route.ts. "Mobile.ts" means packages/web-domain/src/Mobile.ts. +- UNCONFIRMED means the code that was read does not settle it. Nothing marked UNCONFIRMED should be built on without checking. +- Element-level detail (every string, size, animation and gesture constant) is in four audit notes that are kept out of this branch to keep it to one file: ios-ui-a.md (auth, home, settings, analytics, design system, shell), ios-ui-b.md (Cap detail, player, recorder, upload, editor, broadcast extension, Live Activities), ios-tests-config.md (tests, fixtures, project config, CI, history) and web-api.md (server side). References such as "A section 2.7" or "B section 4.4" point into ios-ui-a.md and ios-ui-b.md. Part 1 here is the map; the notes are the territory, and can be added to the branch if a reviewer wants them. +- Re-checked directly against the code after the audit notes were written: route.ts:563-592 (one mobile key per user), route.ts:820-832 and Mobile.ts:201-204 (push token schema), route.ts:3016-3024 (view tracking strings), route.ts:3441-3444 and :3485-3487 (upload source tag), route.ts:3556-3566 (recording metadata), route.ts:3630-3741 (recording completion), apps/web/lib/mobile-events.ts:15-28 and :52-62 (user agent and platform), Mobile.ts:18-34, :47-95, :233-239 and :1139-1150, .github/workflows/ci.yml:84-88 and :144-150, biome.json:3-21, the removed Expo app (git show ea1372851), the CapKit sources and Config plists, Theme.swift and the three colour sets. Line ranges that the audit notes mark "area" are approximate and are flagged where used. + +## 0. Key findings + +1. The iOS "widgets" are not widgets. [W]/CapWidgetsBundle.swift:5-9 contains two Live Activities (upload progress and screen recording) and nothing else: no home screen, lock screen or Control Centre widget. The Android counterpart is ongoing notifications (Live Updates on Android 16 and later). A Glance home-screen widget would be new scope beyond parity. +2. One mobile API key per user. createMobileApiKey deletes every auth_api_keys row with source "mobile" for the user before inserting the new one (route.ts:563-592). Signing in on Android signs the same user out of their iPhone, and the other way round. Desktop allows 20 keys (apps/web/app/api/desktop/[...route]/session.ts:111-165). +3. Push cannot work on Android without server work. The token schema only accepts 32 to 200 hex characters and environment "sandbox" or "production" (Mobile.ts:201-204), and the only sender is APNs (apps/web/lib/apns.ts, apps/web/lib/mobile-push.ts). There is no FCM code anywhere in the repo. +4. The server labels every mobile client as iOS: usage events get an iPhone user agent and platform "ios" (apps/web/lib/mobile-events.ts:19-26, :57), view tracking records browser "Cap for iOS" and os "iOS" (route.ts:3022-3024), and uploads are tagged x-amz-meta-source "cap-mobile-ios" (route.ts:3443, :3486). Android would be counted as iOS until that is generalised. +5. Everything else works against today's server with no change: email code sign-in, browser sign-in through cap://auth (already on the server allow-list, Mobile.ts:49-62), library, playback, comments, both upload pipelines, editor, settings and analytics. +6. Upstream has never shipped Android. The Expo app that Richie McIlroy removed in ea1372851 (2026-11-06, inside PR #3880, the same PR that added the native iOS app) declared `platforms: ["ios"]` in apps/mobile/app.config.js. So Android would be new territory for the maintainers, not a restoration. +7. Screen recording is simpler on Android than on iOS. iOS needs a separate broadcast extension process, an app group, a shared keychain, Darwin notifications and a hand-off protocol ([B]/SampleHandler.swift, [K]/ScreenRecordingStop.swift, [K]/RecordingHandoff.swift). Android does it in one process with MediaProjection and a foreground service, and can be tested on the emulator (iOS screen recording only runs on a device, apps/mobile-ios/README.md:59). +8. The hard technical risk is the encoder output, not the UI. The server only accepts fragmented MP4 as init.mp4 plus numbered .m4s segments per track (route.ts:3596-3628). Android's MediaMuxer does not write that, so the plan needs its own segment writer and a proof against a real Cap server before the recorder UI is built. +9. The development Mac needs little: JDK 17 and Gradle are already installed through Homebrew. What is missing is the emulator, a system image, an AVD, the API 37 platform, and Docker for a local Cap server. Details in Part 5. +10. Publishing has to go through Cap Software: the name, logo, application id and store account are theirs. That makes the maintainers' buy-in a hard dependency for release, not only for an upstream PR. + +--- + +# Part 1. iOS audit + +## 1.1 Size and shape (measured) + +| Area | Swift lines | Notes | +|---|---|---| +| [A] Cap/App | 2,225 | app state, session, library, uploads, recording coordinator, push, usage | +| [D] Cap/DesignSystem | 460 | Theme.swift, RemoteImage.swift, SafariView.swift | +| [F]/Auth | 891 | sign-in view, model, hero animation | +| [F]/Home | 1,320 | library, folders, scope bar, add menu, sheets, Cap actions | +| [F]/Cap | 3,000 | Cap detail, player, comments, transcript, summary | +| [F]/Edit | 1,327 | editor model and timeline UI | +| [F]/Record | 1,952 | recorder UI, camera capture, screen recording, recent list | +| [F]/Settings | 812 | settings, profile, organisation, notifications, delete account | +| [F]/Analytics | 510 | one file | +| [K] CapKit sources | 5,552 | API client, models, links, storage, uploads, recording, editing, analytics | +| [T] CapKit tests | 2,300 | 131 @Test declarations in 10 files | +| [U] CapUITests | 1,440 | 52 XCTest methods in 6 files | +| [B] CapBroadcast | 321 | ReplayKit upload extension | +| [W] CapWidgets | 293 | two Live Activities | +| Total | 22,421 lines in 81 Swift files | plus Fixtures/server.py, 378 lines | + +Counted with `git ls-files | grep .swift | xargs cat | wc -l` per directory at 5a1b9c73a. + +Product facts: bundle id so.cap.mobile ([P]:566); deployment target iOS 26.0 ([P]:500, :528); iPhone only (TARGETED_DEVICE_FAMILY = 1, [P]:578) but with iPad-class layouts for the open iPhone Duo; version 1.0.0 build 1; zero third-party dependencies (apps/mobile-ios/README.md:3); English only (no string catalogue in the directory, UNCONFIRMED beyond the listing). It landed in 15 pull requests (#3880 to #4487) and 83 commits between 2026-11-06 and 2026-11-23 (ios-tests-config.md section 5). + +## 1.2 App shell and lifecycle + +| Behaviour | iOS source | What it does | +|---|---|---| +| Process launch | [A]/CapApp.swift:10-18 | Starts the upload and recording coordinators on every launch, including background wakes; registers for push if allowed; starts usage tracking | +| Root switch | [A]/CapApp.swift:99-117 | signedOut shows SignInView; signedIn shows MainTabView keyed on the API key; 0.3 s cross fade | +| Session restore | [A]/AppModel.swift:166-203 | Reads {apiKey, userId} from the keychain; wipes it on first launch after install (:25-34); re-checks after first unlock | +| Environment | [A]/AppModel.swift:105-120, [K]/Links.swift:6-47 | Base URL from Info.plist CapAPIBaseURL, default https://cap.so; debug builds accept an env override and http for local hosts | +| Forced sign-out | [A]/AppModel.swift:236-240 | Any 401 signs out with "Your session expired. Sign in again.", but only if the stored credentials still match the request's | +| Sign out | [A]/AppModel.swift:250-289 | Unregister push, POST session/revoke with a 4 s cap, wipe vault, uploads, recordings, caches, cookies and temp files | +| Tabs | [A]/CapApp.swift:262-294 | Caps, Record, Analytics, Settings. Record is not a page: selecting it opens the recorder full screen and snaps the tab back (:176-184) | +| Routes | [A]/CapApp.swift:139-148, :301-321 | cap(id), share(target), folder, capAnalytics, profile, organization, notifications, deleteAccount; every tab can push a Cap | +| Large screens | [A]/CapApp.swift:57-77, [F]/Home/LibrarySplitView.swift:6-13 | "Large" means both size classes regular. Caps tab becomes a split view sharing one path so folding keeps the open Cap; phones are portrait except fullscreen video | +| Deep links | [K]/Links.swift:135-165 | cap://auth, cap://record/stop, cap://s/?t=&comment=&reply=, and https:///s/ | +| Universal links | [C]/Cap.entitlements, apps/mobile-ios/README.md:83 | Not enabled: no associated-domains entitlement and cap.so serves no apple-app-site-association. https links never reach the app today | +| Toasts | [A]/ToastCenter.swift:16-87 | One at a time, top of screen, 2.4 s (errors 4 s), haptic and VoiceOver announcement | +| Usage events | [A]/Usage.swift, [K]/Analytics.swift | Named events with plain values, batched to POST api/mobile/events; never titles, links, ids or typed text | +| Push | [A]/PushNotifications.swift | Asks once after the first upload; registers the APNs token; a tap with capId opens that Cap | + +## 1.3 Screens and flows + +Each row names the screen, its entry, the states it can show and where the full element list is. "A" and "B" are ios-ui-a.md and ios-ui-b.md in the audit folder. + +### Sign in ([F]/Auth, detail in A section 2) + +| Flow | Source | Behaviour | +|---|---|---| +| Layout | SignInView.swift:13-99 | One screen, two steps. Hero animation, form, legal text. Column capped at 520 pt. Titles "Sign in to Cap" / "Check your email" | +| Email step | SignInView.swift:145-174, SignInModel.swift:44-63 | Field "you@company.com", button "Continue with email", POST session/email/request, then a 30 s resend cooldown | +| Code step | SignInView.swift:237-346, SignInModel.swift:80-93 | Six boxes over one hidden field, one-time-code autofill, auto submit at 6 digits, "Different email", "Resend code" / "Resend in Ns" | +| Provider sign-in | SignInModel.swift:101-123, [K]/Links.swift:193-229 | Apple and Google buttons shown per GET session/config. Opens session/request in an ephemeral web auth session, callback cap://auth?api_key=&user_id= or ?error_description= | +| Errors | SignInModel.swift:127-140 | Fixed copy per error class (table in A section 2.7) | +| Hero | SignInHero.swift | 3.9 s decorative animation ending on the logo and wordmark lockup; frozen at the end frame under Reduce Motion | + +workosAuthAvailable is decoded and never used by the UI (A section 2.5). + +### Home, the Caps tab ([F]/Home, [A]/LibraryModel.swift, [A]/SessionModel.swift, detail in A sections 1.11, 1.12 and 3) + +| Flow | Source | Behaviour | +|---|---|---| +| Bootstrap | SessionModel.swift:75-124 | Cached bootstrap shown first, then GET bootstrap and GET /api/desktop/plan in parallel | +| Library list | LibraryModel.swift:32-124, HomeView.swift:66-190 | Page size 30, cache first, refresh if stale or 20 s old, infinite scroll at 6 from the end, inline "Couldn't load more. Tap to retry." | +| Processing poll | LibraryModel.swift:152-190 | POST caps/statuses for up to 25 own Caps still processing; 3 s growing by 1.5x to 15 s | +| States | HomeView.swift:131-173 | Skeleton, "Couldn't load Caps" with Try again, "No Caps yet" / "This folder is empty", offline toast over cached data | +| Scope bar | HomeView.swift:330-459, SessionModel.swift:126-162 | "My Caps" plus one chip per Space; organisation switcher chip when the user has more than one; scope persisted per user and organisation | +| Folders | HomeView.swift:42-64, :248-285 | Horizontal folder strip at the root; a folder screen with the same list | +| Cap actions | CapActions.swift:7-138 | Long-press menu: Copy link, Share, Make private or public, Delete with confirmation; optimistic with rollback | +| Add menu | AddMenu.swift:21-97 | Record, Upload from Photos, Upload from Files, Import from Loom, New folder, Open a Cap link | +| Sheets | Sheets.swift:4-236 | New folder (name up to 100, four colours), Open a Cap link (paste and parse), Import from Loom (Pro only) | +| Upload banner | AddMenu.swift:130-231 | One job at a time: Preparing, Uploading N%, Finishing, Uploaded, Upload failed | +| Split layout | LibrarySplitView.swift:17-246 | Sidebar 300 to 380 pt, compact rows, "Pick a Cap" placeholder | + +### Cap detail and player ([F]/Cap, detail in B section 1) + +| Flow | Source | Behaviour | +|---|---|---| +| Load and access | CapDetailModel.swift:181-203 | GET caps/{id}; on 403, GET caps/{id}/access decides locked (password) or restricted | +| State screens | CapDetailView.swift:169-227 | Loading skeleton, "You don't have access", "Cap not found", "Couldn't load this Cap", password gate | +| Polling | CapDetailModel.swift:258-286 | While processing, transcribing or generating AI: 6 s doubling to 30 s, up to 34 tries | +| Playback | CapDetailModel.swift:218-237, :310-349 | GET caps/{id}/playback gives {kind mp4 or hls, url, transcriptUrl}. One player for both kinds. URL must be https or same origin | +| Controls | CapPlayer.swift:97-431 | Tap to show, auto hide after 3 s, double tap to skip 10 s, scrubber with chapter gaps and a time bubble, speeds 0.5 to 2 persisted, captions toggle | +| Fullscreen, PiP, AirPlay, lock screen | CapPlayer.swift:29-72, :435-474, :567-639 | Fullscreen cover with landscape, automatic Picture in Picture on backgrounding, AirPlay picker, Now Playing controls | +| Captions | CapPlayer.swift:478-521, [K]/Formatting.swift:51-133 | Drawn by the app from the transcript VTT, phrases of at most 64 characters | +| View count | CapDetailModel.swift:381-386 | First real playback by a non-owner posts caps/{id}/views with a per-process session id | +| Comments | CapDetailModel.swift:598-706, CapSections.swift:229-666 | Threads flattened to top-level, three sort orders, optimistic send, timestamp pin, replies, delete own, 2,000 character cap | +| Reactions | [K]/Social.swift:3-6, CapPlayer.swift:523-563 | Six emoji, optimistic, floating bursts during playback | +| Timeline markers | [K]/Social.swift:48-101, CapDetailView.swift:556-657 | Comment and reaction badges or a density bar chart along the timeline | +| Transcript | CapDetailModel.swift:564-594, CapSections.swift:108-225 | VTT list with active row, search, copy, copy with timestamps, share | +| Summary and chapters | CapSections.swift:7-104 | Markdown summary and tappable chapters, with generating and empty states | +| Owner menu | CapDetailView.swift:411-482, :768-822 | Edit, visibility, link access, Rename, password, Analytics, Delete | +| Viewer menu | CapDetailView.swift:411-482 | Copy link, Copy link at time, Open in Safari, Share, Report Cap, Block owner, Save to Photos when allowed | +| Save to Photos | CapDetailModel.swift:784-861 | GET caps/{id}/download then download and add to the photo library | + +### Recorder ([F]/Record, [A]/RecordingCoordinator.swift, [B], detail in B section 2) + +| Flow | Source | Behaviour | +|---|---|---| +| Modes | ScreenRecording.swift:11-67, RecordView.swift:266-365 | Capture modes Instant (only live one), Studio and Screenshot ("coming soon"). Record modes Camera and Screen. Screen + Camera is built but hidden | +| Camera state machine | RecordModel.swift:10-17, :62-282 | preparing, cameraDenied, unavailable, ready, recording, finishing (transition table in B section 2.2) | +| Camera capture | CameraCapture.swift:22-234 | 1080x1920 at 30 fps, about 4 Mbps, front camera by default, flip allowed mid-recording, saved un-mirrored | +| Start | RecordModel.swift:144-192 | Creates the job, the segment writer and the server Cap in parallel with the first frames; title "Cap Recording " | +| Stop | RecordModel.swift:194-234 | Under 1 s: discard, toast "Recording was too short", delete the server Cap. Otherwise finish, start the upload Live Activity, stay on the recorder | +| Free plan | RecordModel.swift:184-191, [K]/Recording.swift:158-162 | Client stops at 300 s; the server refuses longer with 403 on complete (Mobile.ts:20-33, 5 s grace) | +| Screen recording | ScreenRecording.swift:69-273, [B]/SampleHandler.swift:42-301 | System broadcast picker starts the extension, which encodes and uploads live; three stop paths; hand-off back to the app (B section 2.5) | +| Recent list | RecordingCoordinator.swift:142-273, RecentRecordingsList.swift | Up to 3 rows: Saving, Uploading N%, Ready, failed; the newest link is copied automatically | +| No pause | [B]/SampleHandler.swift:102-103 | There is no pause or resume for either mode | + +### Upload ([A]/UploadCenter.swift, [A]/BackgroundUploadCoordinator.swift, [K], detail in B section 3) + +Two pipelines. A: one file from Photos or Files (B section 3.1). B: live segments from the recorder (B section 3.2). Both are described with the server in 1.4. + +### Editor ([F]/Edit, [K]/Editing.swift, [K]/TrimTrack.swift, detail in B section 4) + +| Flow | Source | Behaviour | +|---|---|---| +| Model | [K]/Editing.swift | One model only: a list of kept source ranges. Minimum clip 0.1 s. Operations: trim start or end, split at playhead, delete clip, undo, redo, restore original | +| No other tools | [F]/Edit (whole folder) | No speed, crop, rotate, volume, caption edit, filters, text or overlays | +| Gate | CapDetailView.swift:69-95, :377-399 | GET caps/{id}/edit returns available, pro_required, busy or not_editable; only mp4 sources are editable | +| Preview | EditorModel.swift:28-38, :230-310 | Nothing is re-encoded on the phone; a composition of the kept ranges plays locally | +| Timeline | EditorView.swift:175-476, [K]/TrimTrack.swift:13-25 | Modelled on the system Photos trimmer: 24 thumbnails, handles, hold 0.53 s to zoom 5x (constants in B section 4.4) | +| Save | [K]/Editing.swift:187-198 | POST caps/{id}/edit {sourceDuration, keepRanges}; the server renders; POST caps/{id}/edit/restore reverts. 30 edits per hour (apps/web/lib/rate-limit.ts:254) | + +### Settings ([F]/Settings, detail in A section 4) + +| Screen | Source | Behaviour | +|---|---|---| +| Root | SettingsView.swift:5-204 | Profile row, plan row ("Cap Pro" or "Free"), upgrade link (US storefront only), organisation picker, Notifications, dashboard link, Permissions, Version, Help and legal, Sign out, Delete account | +| Profile | SettingsView.swift:206-318 | First and last name, read-only email, photo (PUT or DELETE user/profile/image) | +| Organisation | OrganizationSettingsView.swift:5-209 | Name, allowed email domain, icon, read-only custom domain and id; managers only can save | +| Image picker | OrganizationSettingsView.swift:211-268, [K]/ImageCoding.swift | Downsample to 1024 px, JPEG quality ladder to fit 1 MiB, sent as base64 JSON | +| Notifications | NotificationSettingsView.swift | Push permission row plus five toggles (comments, replies, views, anonymousViews, reactions) saved through a one-at-a-time queue | +| Delete account | SettingsView.swift:320-392 | Type DELETE, confirm, POST user/account-deletion, then sign out. Deletion is completed by Cap Support, not instantly | + +### Analytics ([F]/Analytics/AnalyticsScreen.swift, detail in A section 5) + +Organisation scope on the tab and per-Cap scope pushed from Cap detail. Range picker 24H, 7D, 30D, All. Metric tiles, one area chart with scrubbing, Locations and Technology breakdown cards, Top Caps. States: skeleton, "Analytics is a Cap Pro feature", "Analytics unavailable". Organisation data is cached to disk; per-Cap data is not. + +### Live Activities ([W], [K]/UploadActivity.swift, detail in B sections 3.3 and 5) + +| Activity | Source | Behaviour | +|---|---|---| +| Upload | [W]/UploadLiveActivity.swift:8-83, [A]/BackgroundUploadCoordinator.swift:160-263 | Kinds video, image, loom, recording. Phases preparing, uploading, importing, finishing, done, failed. Throttled to 2% or 2 s, stale after 45 s, dismissed 15 min after done and 60 min after failed. Tap opens cap://s/ | +| Screen recording | [W]/ScreenRecordingLiveActivity.swift, [F]/Record/ScreenRecording.swift:169-243 | Counting timer, Stop button linking to cap://record/stop, "Saving your recording" while stopping | + +## 1.4 Backend: endpoints, auth, upload path, data models + +### Where the contract lives + +One Effect HttpApi group. Contract: Mobile.ts:1141-1149 (prefix /api/mobile, OpenAPI title "Cap Mobile API", description "Authenticated API used by the Cap iOS app"), 51 HttpApiEndpoint declarations. Handlers: route.ts (4,438 lines), wired from :3743, exporting GET, POST, PUT, PATCH and DELETE only (:4432-4438). Server tests: apps/web/__tests__/unit/mobile-*.test.ts (listed, not read). The contract is not mounted in the public API (packages/web-domain/src/Http/Api.ts) and nothing generates an OpenAPI file for it (web-api.md section 7). + +### Auth + +- Header `Authorization: Bearer ` ([K]/APIClient.swift:217). The key is a crypto.randomUUID() stored as the id of an auth_api_keys row with source "mobile", no expiry and no refresh token (route.ts:563-592; table packages/database/schema.ts:1023-1044). +- Server check: packages/web-backend/src/Auth.ts:76-131 takes the second word of the header, and if it is 36 characters long looks it up by id with no source check. So desktop and extension keys also work on mobile routes. +- Email code: POST session/email/request sends a 6-digit code valid for 10 minutes (route.ts:594-643); POST session/email/verify returns {type: "api_key", apiKey, userId} (route.ts:645-707). Rate limits: 10 sends and 20 verifies per 10 minutes per email (apps/web/lib/rate-limit.ts, ids rl_auth_otp_send and rl_auth_otp_verify). +- Browser sign-in: GET session/request?redirectUri=cap://auth&provider=apple|google (route.ts:3762-3809). With no cookie session it sends the browser to /login?next=...&mobileProvider=...; with one it mints a key and redirects to the redirectUri with api_key and user_id. Allowed redirect URIs are exactly cap://auth plus Expo dev-client forms (Mobile.ts:49-93). +- Sign out: POST session/revoke deletes the key row and its push tokens (route.ts:3820-3845). +- Client storage: keychain service so.cap.mobile.session, account primary, JSON {apiKey, userId}, this device only ([K]/Storage.swift:27-89). +- Other headers: User-Agent "Cap-iOS/ ()" ([A]/AppModel.swift:64), Accept application/json, and X-Cap-Video-Access carrying a per-Cap unlock token after a password unlock ([K]/APIClient.swift:218-220, :267-276). Timeouts 30 s request and 120 s resource; redirects refused; one automatic retry of a GET on a dropped connection ([K]/APIClient.swift:117-147, :249-252). +- Error mapping: 400 and 422 badRequest, 401 unauthorized, 403 forbidden, 404 and 410 notFound, 409 conflict, 413 payloadTooLarge, 429 rateLimited, 5xx server ([K]/APIClient.swift:47-60), each with fixed user copy (:21-37, listed in A section 1.14). + +### Endpoint list + +Paths are under /api/mobile. "iOS" is the line in [K]/APIClient.swift unless stated. Server lines are from web-api.md; ranges it marks "area" are approximate. + +| Method and path | iOS | Server | Notes | +|---|---|---|---| +| GET session/config | :344 | route.ts:3751-3761 | public; {appleAuthAvailable, googleAuthAvailable, workosAuthAvailable} | +| POST session/email/request | :349 | route.ts:594-643 | public; {email} | +| POST session/email/verify | :354 | route.ts:645-707 | public; {email, code} gives {apiKey, userId} | +| GET session/request | :359-366 | route.ts:3762-3809 | opened in a browser, not through the client | +| POST session/revoke | :369 | route.ts:3820-3845 | | +| GET bootstrap | :373 | | {user, organizations, activeOrganizationId, rootFolders, spaces} | +| PATCH user/active-organization | :377 | | {organizationId} gives a fresh bootstrap | +| PATCH user/profile | :382 | | {name, lastName or null} | +| PUT, DELETE user/profile/image | :386, :390 | route.ts:185 (1 MiB cap) | base64 JSON payload | +| POST user/account-deletion | :394 | packages/database/auth/revoke-credentials.ts:25-68 | {confirmation: "DELETE"} | +| POST user/blocks | :398 | | {userId} | +| GET, PATCH user/notification-preferences | :402, :406 | | five booleans; PATCH sends one key | +| POST user/push-tokens | :410 | route.ts:820-864, Mobile.ts:201-204 | {token hex 32 to 200, environment sandbox or production} | +| POST user/push-tokens/remove | :414 | | {token} | +| GET caps | :418 | | folderId, spaceId, page, limit (iOS 30, server default 20, max 50) | +| POST caps/statuses | :429 | | {ids} up to 25 | +| POST folders | :439 | packages/web-domain/src/Folder.ts:15 | {name, color normal, blue, red or yellow, spaceId} | +| GET caps/{id} | :443 | | CapDetail | +| GET caps/{id}/access | :447 | | {status granted, password_required, restricted} | +| POST caps/{id}/unlock | :452 | route.ts:2179-2181, :2257-2263 | {password}; token valid 12 h; 20 tries per 10 min, answered with 400 not 429 | +| POST caps/{id}/views | :458 | route.ts:2952, :3016-3024 | {sessionId} | +| POST caps/{id}/report | :462 | | {reason} | +| PATCH caps/{id}/sharing | :466 | | {public, linkAccess?} gives CapSummary | +| PATCH caps/{id}/title | :470 | | {title} | +| PATCH caps/{id}/password | :474 | | {password or null} | +| DELETE caps/{id} | :478 | | | +| GET caps/{id}/playback | :482 | apps/web/app/api/playlist/route.ts:164 | segmented Caps return a web-origin playlist URL that needs the Bearer header | +| GET caps/{id}/download | :486 | | {fileName, url} | +| GET caps/{id}/thumbnail | :599-613 | route.ts:3934-3949 | answers 302 to storage; the image loader follows it and strips auth headers cross-origin ([K]/ImagePipeline.swift:54-80) | +| GET, POST caps/{id}/edit, POST caps/{id}/edit/restore | [K]/Editing.swift:187-198 | apps/web/lib/rate-limit.ts:254 | 30 per hour per user | +| GET caps/{id}/analytics, GET analytics | :490, :494 | | range 24h, 7d, 30d or lifetime; spaceId optional | +| POST events | :590 | route.ts:3307, Mobile.ts:233-239, apps/web/lib/mobile-events.ts | 1 to 50 events, 30 requests per minute; body {sentAt, app {version, build, os, device phone or tablet}, events} | +| GET, PATCH organization/settings | :501, :506 | | | +| PUT, DELETE organization/settings/icon | :510, :514 | | | +| POST imports/loom | :518 | route.ts:3333-3339 | Pro only; rate limit answered with 400 | +| POST caps/{id}/comments | :537 | route.ts:2872-2874 | {content, timestamp or null, parentCommentId?} | +| DELETE comments/{id} | :541 | | | +| POST caps/{id}/reactions | :546 | | {content emoji, timestamp or null} | +| POST uploads | :550 | route.ts:3363-3495 | pipeline A, step 1 | +| POST uploads/{id}/progress | :554 | route.ts:4282-4309 | | +| POST uploads/{id}/complete | :562 | route.ts:4310-4413 | {rawFileKey, contentLength} | +| POST recordings | :575 | route.ts:3500-3578 | pipeline B, step 1 | +| POST recordings/{id}/segments/targets | :580 | route.ts:3596-3628 | 1 to 25 subpaths per call | +| POST recordings/{id}/complete | :585 | route.ts:3630-3741 | | +| GET /api/desktop/plan (outside the prefix) | :596 | apps/web/app/api/desktop/[...route]/root.ts:355-398 | {upgraded, stripeSubscriptionStatus} | + +### Upload path + +Pipeline A, single file ([A]/UploadCenter.swift:114-230, [K]/UploadEngine.swift:57-116, [K]/BackgroundUploads.swift): +1. Stage a copy of the picked file. Images are re-encoded to JPEG (quality 0.9, longest side 4,096 px), which strips location data. Probe duration, size and fps. +2. POST uploads {organizationId, folderId, fileName, contentType, contentLength, durationSeconds, width, height, fps} returns {id, shareUrl, rawFileKey, upload}. +3. The upload target is a tagged union ([K]/Models.swift:892-940): s3Post (multipart form with the returned fields, then the file), put (PUT with returned headers) or driveResumable (PUT with Content-Range for the whole file). Only https targets; the Cap Bearer key is never sent to storage; reserved headers are never forwarded. +4. The transfer runs in a background URLSession that survives the app being killed. Progress is posted to the server at most every 5 s. +5. POST uploads/{id}/complete. Retryable failures keep the record and retry on next launch or foreground. There is no automatic retry of a failed transfer. + +Pipeline B, live segments ([K]/SegmentWriter.swift, [K]/Recording.swift, [K]/RecordingUploads.swift, server route.ts:3500-3741): +1. The writer produces fragmented MP4 (CMAF) with separate video and audio tracks, cut every 2 s. Video: H.264 High, no B-frames, a keyframe every 2 s. Audio: 48 kHz mono AAC at 96 kbps, gaps filled with silence. +2. POST recordings {organizationId, folderId, fileName, width, height, fps} returns {id, shareUrl}. The server stores source type desktopSegments and metadata source "mobileCamera" for every mobile recording, camera or screen (route.ts:3556-3563). +3. POST recordings/{id}/segments/targets with subpaths matching `segments/(video|audio)/(init.mp4|segment_[0-9]{3,6}.m4s)` returns one presigned PUT per subpath. The client asks 8 segments ahead and refetches links after 25 minutes. +4. Each segment is PUT as video/mp4, 3 at a time, init segments first, up to 20 attempts each, backoff 0.5 s doubling to 30 s. A segment file is deleted only after the job file records it as uploaded. +5. POST recordings/{id}/complete {durationSeconds, totalBytes, videoSegments [{index, duration}], audioSegments}. The server checks indices run 1..n, each duration is at most 10 s, at most 18,000 segments and 43,200 s, and the free-plan limit, then writes a version 2 manifest and queues finalisation (all within route.ts:3630-3741). +6. Jobs are persisted, so a crash mid-recording is finished on next launch with what reached disk. A job belonging to a different signed-in user is discarded. + +### Data models ([K]/Models.swift) + +Decoding is deliberately lenient: unknown enum values fall back to a safe default, bad array elements are dropped, counts accept whole or fractional JSON numbers (rounded, and clamped to zero and above) but not a number sent as a string, which fails or falls back to the field's default, dates are ISO 8601 with or without fractional seconds ([K]/Decoding.swift:19-66). The Android models must copy that behaviour; the five JSON fixtures in [T]/Fixtures pin it. + +| Model | Lines | Fields that matter | +|---|---|---| +| CapUser | :61-85 | id, name, lastName, email, imageUrl, activeOrganizationId | +| Bootstrap | (A section 7.1) | user, organizations (role owner, admin, member; unknown is member), activeOrganizationId, rootFolders, spaces (kind organization or space, privacy, canManage) | +| Folder, FolderColor | :138-155 | id, name, color (unknown is normal), parentId, videoCount | +| UploadProgress | :185-250 | uploaded, total, phase uploading, processing, generating_thumbnail, complete, error (unknown is processing), processingProgress, processingMessage | +| CapSummary | :257-364 | id, shareUrl, title, dates, ownerId, ownerName, durationSeconds, thumbnailUrl, thumbnailCacheKey, folderId, public, protected, counts, upload, ownedByCurrentUser, linkAccess, linkRestricted | +| CapComment | :386-408 | id, type text or emoji, content, timestamp, parentCommentId, author | +| CapViewer | :464-510 | six disable flags, defaultPlaybackSpeed, canDownload, isScreenshot, overShareLimit, aiGenerationStatus | +| CapAccessStatus | :512-519 | granted, password_required, restricted, unknown | +| CapDetail | :530-563 | cap, summary, chapters, transcriptionStatus, comments, shareUrl, viewer | +| Playback | :643-660 | kind mp4 or hls, url, transcriptUrl | +| Analytics | :667-863 | range, counts, chart buckets, six breakdowns | +| OrganizationSettings | :865-885 | id, name, role, canManage, iconUrl, allowedEmailDomain, customDomain, domainVerified | +| UploadTarget, UploadCreated | :892-947 | s3Post, put, driveResumable | +| APIKeySession, AuthConfig, Plan | :949-981 | sign-in and plan responses | +| Report reasons | :983-1003 | harassment, hate, sexual, violence, copyright, other | + +## 1.5 Platform features + +The full table with sources is B section 6. The items that drive Android design: + +| iOS capability | Source | Purpose | +|---|---|---| +| ReplayKit broadcast upload extension | [B]/SampleHandler.swift, [C]/CapBroadcast-Info.plist | Whole-screen recording in a separate process with a small memory budget | +| App group, shared keychain group, Darwin notifications | [C]/Cap.entitlements:7-10, [K]/ScreenRecordingStop.swift | App and extension share files, the session and stop signals | +| AVCaptureSession with data outputs | [F]/Record/CameraCapture.swift | Camera and microphone frames into the segment writer | +| AVAssetWriter CMAF segments, in-process AAC | [K]/SegmentWriter.swift | 2 s fragmented MP4 pieces | +| Background URLSession, three identifiers | [K]/BackgroundUploads.swift:48, [K]/RecordingUploads.swift:13-14, [A]/CapApp.swift:40-55 | Transfers that survive suspension and kill | +| ActivityKit Live Activities | [W], [P]:554-555 | Progress and stop control on the Lock Screen and Dynamic Island | +| AVPlayer, PiP, AirPlay, Now Playing | [F]/Cap/CapPlayer.swift | Playback surfaces | +| AVMutableComposition, AVAssetImageGenerator | [F]/Edit/EditorModel.swift | Editor preview and filmstrip | +| APNs | [A]/PushNotifications.swift, [C]/Cap.entitlements:5-6 | Comment, reply, reaction and view alerts | +| Local notifications | [B]/SampleHandler.swift:288-301 | "Your recording is saved" when stopped outside the app | +| PhotosPicker, fileImporter, PhotoKit add-only | [F]/Home/AddMenu.swift:54-58, [A]/PhotoLibrary.swift | Pick media without a library permission; save downloads | +| ASWebAuthenticationSession, SFSafariViewController | [F]/Auth/SignInModel.swift:101-123, [D]/SafariView.swift | Sign-in and in-app web pages | +| StoreKit storefront | [A]/WebUpgrade.swift:4-28 | Upgrade link only on the US storefront, an App Store rule | +| Keychain, UserDefaults, file protection, no-backup flags | [K]/Storage.swift, B section 7.6 | Credentials, preferences, durable queues | +| Privacy manifest | apps/mobile-ios/Cap/PrivacyInfo.xcprivacy | Declares email, name, photos or videos, other user content, product interaction, coarse location | +| Permission copy | [C]/Info.plist:22-27 | Camera: "Cap records you with the camera so you can share a video message." Microphone: "Cap records your voice with your videos." Photos add: "Cap saves videos you download to your photo library." | + +Not used on iOS: BGTaskScheduler, location permission, speech recognition, associated domains, any third-party SDK. + +## 1.6 Design system + +Sources: [D]/Theme.swift (178 lines), [D]/RemoteImage.swift (239), [D]/SafariView.swift (43) and apps/mobile-ios/Cap/Assets.xcassets. Full tables are in A section 6. + +| Token | Light | Dark | Source | +|---|---|---|---| +| AccentColor (app tint) | #276BF0 | #5C93FF | Assets.xcassets/AccentColor.colorset/Contents.json | +| CapBlue | #4785FF | #5C93FF | Assets.xcassets/CapBlue.colorset/Contents.json | +| CapBlueSoft | #ADC9FF | #2B4A85 | Assets.xcassets/CapBlueSoft.colorset/Contents.json | +| Brand gradient | #4785FF to #295CF0 | same | Theme.swift:12-16 (only used by an unused button style) | +| Record red | #FF3B30 | same | [F]/Record/RecordView.swift:448-483 | +| Editor chrome and trim accent | #6C6C6F, #FFCC00 | same | [F]/Edit/EditorView.swift (B section 4.4) | + +- Spacing and radii (Theme.swift:4-17): page padding 16, card radius 22, thumbnail radius 18, control radius 14. +- Type: system font only, Dynamic Type text styles, rounded design for big numbers, monospaced digits wherever numbers change. No custom font ships in the iOS app. +- Surfaces: Liquid Glass everywhere (toasts, chips, badges, banners, glass buttons, the floating tab bar). This has no Android equivalent and is the one place where parity has to mean "same structure, native material". +- Components: InkButtonStyle (primary-colour capsule, 52 pt), ProviderButton, ErrorText, SectionHeader, GlassBadge, StatLabel, capCardBackground, readableWidth(620), AvatarView, OrganizationIcon, CapThumbnail with duration and "Protected" badges and an upload overlay, skeleton shimmer, ContentUnavailableView for every empty and error state. +- Image pipeline ([K]/ImagePipeline.swift): memory cache 96 MiB, disk cache 150 MiB pruned at 30 days, key includes the size bucket, Bearer header only to the Cap origin, 25 MiB download cap. +- Motion constants and haptics are inventoried in A section 7.5. +- Assets: AppIcon (1024 px, light and dark), CapLogo, CapLogoLarge, CapWordmark (light and dark), GoogleLogo (SVG). There is no Android adaptive icon, no monochrome icon and no vector logo in the repo. + +## 1.7 Tests, fixtures and CI + +| Layer | Where | Count | Runs in CI | +|---|---|---|---| +| CapKit unit tests (Swift Testing, no simulator) | [T] | 131 @Test in 10 files | Yes: `swift test` | +| UI tests (XCTest, simulator, fixture or live server) | [U] | 52 methods in 6 files | No | +| Fixture API | apps/mobile-ios/Fixtures/server.py | 378 lines, Python standard library, default port 4310 | No | +| Server tests | apps/web/__tests__/unit/mobile-*.test.ts | 8 files (not read) | Yes, with the web suite | + +- CapKit suites: APIClientTests (19), DecodingTests (8), LinkTests (14), SocialTests (11), EditingTests (9), TrimTrackTests (9), AnalyticsTests (26), RecordingTests (16), BackgroundUploadTests (5), UtilityTests (14). They use an injected transport and manual timers, so nothing sleeps and nothing leaves the process (ios-tests-config.md section 1.1). +- Fixture server: fixed keys for a Pro user and an empty free user, sign-in code 123456, locked-Cap password letmein, synthetic media made with ffmpeg on first run. It does not implement recordings, folders, profile, report, password, active-organization, session/revoke, account-deletion or blocks; those return 404 (ios-tests-config.md section 2.7). It emits absolute http://localhost: URLs, which matters on an emulator. +- Debug hooks the UI tests rely on (debug builds only): CAP_API_BASE_URL, CAP_DEBUG_SESSION, CAP_DEBUG_SIGNED_OUT, CAP_DEBUG_ROUTE, CAP_DEBUG_STOREFRONT, CAP_DEBUG_RECORDER_FILE (ios-tests-config.md section 1.2.1). +- CI: job "ios" in .github/workflows/ci.yml:144-163 on macos-26, gated on the path filter 'apps/mobile-ios/**' (:86-87). Two steps: `swift test` in CapKit, then an unsigned Release simulator build. No UI tests, no artefacts. How the merge-queue gate treats the job is UNCONFIRMED. +- Monorepo wiring: apps/mobile-ios has no package.json, so Bun and Turbo ignore it; turbo.json does not mention it; Biome has no exclusion for it and formats its JSON with tabs (biome.json:8-21). There is no release workflow; App Store builds are archived by hand. + +## 1.8 UNCONFIRMED register + +Carried from the audits. None of these blocks the plan, but each needs a look before the code that depends on it. + +| # | Item | Where it matters | +|---|---|---| +| 1 | Whether the server puts a screen recording in the user's active organisation and root folder when the client sends neither (the extension sends nil for both, [B]/SampleHandler.swift:132-169) | Screen recorder | +| 2 | Whether the server tracks recording progress without the uploads/{id}/progress call | Recording uploads | +| 3 | In-process fallback for the comment rate limit outside Vercel (apps/web/lib/rate-limit.ts:243-244) | Local testing | +| 4 | Whether anything uses the cap://account?checkout= redirect (apps/web/lib/mobile-checkout.ts:35-37); no handler exists in the iOS app | Billing | +| 5 | Whether the live front-camera preview is mirrored (the saved file is not) | Camera recorder | +| 6 | Behaviour of a screen broadcast during a call or Siri; pause and resume handlers are empty | Screen recorder | +| 7 | How the EditorUITests fixture on port 4312 is produced | Editor tests | +| 8 | Seed data for CapLiveTests against a real server | End-to-end tests | +| 9 | Which Xcode the CI runner uses; how the merge-queue gate handles path-filtered jobs; branch protection and review rules | CI | +| 10 | Whether Biome reports anything for unknown file types (CI passes with Swift, plist and Python present) | Monorepo fit | +| 11 | Whether the identity "x " on 48 of the 83 iOS commits is scripted | Contribution norms | +| 12 | Whether a share link held while signed out opens after sign-in (inferred from code, not run) | Deep links | +| 13 | Behaviour at the largest accessibility text sizes (fixed heights on the email field, code boxes, chips) | Accessibility | +| 14 | Apple platform colour and type-size defaults quoted in A sections 6.1 and 6.2 are platform knowledge, not repo values | Design system | +| 15 | Whether pushes use content-available (there is no remote-notification background mode) | Push | +| 16 | The complete share-page speed list as asserted in UI tests; the list in code is [0.5, 0.75, 1, 1.2, 1.5, 1.75, 2] ([K]/Models.swift:465) | Player | +| 17 | What cap.so shows an Android phone on the download page (apps/web/components/pages/DownloadPage.tsx:134 routes phones to a PhoneDownload component, not read) | Upstream intent | + +Quirks to decide on rather than copy blindly (B section 8): the server's defaultPlaybackSpeed (1.2) is decoded and never used, so the real default is 1; the over-share-limit wording compares ownerId with itself; "Open a Cap link" drops ?t= and ?comment= from a pasted https link ([F]/Home/Sheets.swift:143); showingCachedData is set and never shown. + +--- + +# Part 2. Android plan + +## 2.1 Stack: Kotlin and Jetpack Compose, with a small dependency list + +Kotlin and Jetpack Compose is the right default and I would not argue for anything else. The reasons are in the repo, not in taste: + +- Upstream already made this choice once. The cross-platform Expo app was deleted in the same PR that added a native SwiftUI app with zero third-party dependencies (ea1372851 and 9e66cde2e in PR #3880; apps/mobile-ios/README.md:3). A React Native, Flutter or Compose Multiplatform Android app would be the thing the maintainers just removed. +- The hard parts are platform media APIs: MediaProjection, MediaCodec, camera, foreground services, background transfer, Picture in Picture. Every cross-platform layer ends in Kotlin for those anyway. +- Nothing can be shared with the iOS code. CapKit is Swift on Foundation and AVFoundation. Kotlin Multiplatform would only pay off if iOS adopted it, which nobody has asked for. +- Compose is the direct counterpart of SwiftUI's model (state-driven UI, a navigation path that is plain data), so the iOS structure ports file for file. + +Where I would push back is on the usual Android dependency pile. The iOS app has no dependencies, and an unsolicited Android app is easier to accept if it is equally plain. The plan uses AndroidX plus four small libraries, and deliberately leaves out the rest: + +| Need | Choice | Left out, and why | +|---|---|---| +| Language, UI | Kotlin, Jetpack Compose, Material 3 | Views and XML layouts | +| Navigation | AndroidX Navigation 3 (the back stack is a plain list the app owns, which matches the single shared path in [F]/Home/LibrarySplitView.swift:17-38 and gives list-detail on large screens) | Navigation 2 (route strings, awkward for the two-pane path) | +| Dependency wiring | One hand-written `AppServices` container, like `AppServices.shared` in [A]/AppModel.swift:25-34 | Hilt, Koin: code generation and build time for about a dozen singletons | +| HTTP | OkHttp, with a hand-written client mirroring [K]/APIClient.swift (about 50 calls) | Retrofit, Ktor: the client needs custom redirect, retry and header rules that are clearer written out | +| JSON | kotlinx.serialization with lenient custom serialisers | Moshi, Gson | +| Async | Kotlin coroutines and Flow | RxJava | +| Images | Coil 3 on the same OkHttp client | Glide | +| Video playback | Media3 ExoPlayer (HLS and MP4), Media3 session | A WebView player | +| Camera | Camera2 directly, one stream into a GL stage that feeds both the viewfinder and our encoder (decision in 2.5.1) | CameraX: its VideoCapture writes one file where the server needs segments, and with our own GL stage its use-case plumbing is unused | +| Encoding | MediaCodec (H.264, AAC) and a small fragmented MP4 writer | MediaMuxer and MediaRecorder: neither writes init plus .m4s segments | +| Background work | WorkManager for uploads after capture; a foreground service only while the screen is being recorded | A permanent service | +| Preferences | DataStore Preferences | SharedPreferences | +| Credentials | An Android Keystore AES-GCM key wrapping a small file in no-backup storage | EncryptedSharedPreferences (androidx.security-crypto is deprecated, to be re-checked at scaffold time) | +| Durable queues and caches | JSON files, as on iOS (pending.json, job.json, snapshot cache) | Room: there is no relational data, and files keep the port one to one | +| Charts | One custom Canvas area chart (the app has exactly one chart) | A chart library | +| Web pages and sign-in | AndroidX Browser: Custom Tabs, and Auth Tab where the browser supports it | WebView | +| Push | Firebase Cloud Messaging, isolated in its own module and only once the server supports it (Part 4) | Baking Firebase into the base app | +| Formatting and lint | Spotless with ktfmt, Android Lint with warnings as errors, Kotlin `allWarningsAsErrors` | detekt for now | +| Tests | JUnit and kotlinx-coroutines-test on the JVM; Compose UI tests and UI Automator on the emulator | Mocking libraries: tests use a real local HTTP server, in the spirit of AGENTS.md "Tests: wait on signals, not time" | + +SDK levels: targetSdk 37 and compileSdk 37.2 (corrected when the scaffold was built: Compose 1.13.0 only compiles against API 37.1 or later); minSdk 29 (Android 10). Android 10 is the floor because playback audio capture for screen recordings (AudioPlaybackCapture) and permission-free saving to MediaStore both start there. The iOS app only supports the newest OS, so if the maintainers would rather have fewer code paths, minSdk 34 removes most version branches (foreground service types, per-session capture consent, native photo picker, notification permission). That is a maintainer decision (Part 4, Q9). + +## 2.2 Versions, checked on 30 November 2026 + +Checked against developer.android.com on the day (the AndroidX stable channel page dated 18 November 2026, the Compose BOM mapping page) and against the tools on the development Mac. The Android Gradle plugin rows were first taken from the AGP 9.6 release notes, which describe a version that is only published as alphas (9.6.0-alpha07 on that day). They were corrected against the AGP 9.5 release notes and Google's Maven repository when the scaffold was built. + +| Piece | Version | Source | +|---|---|---| +| Android Gradle plugin | 9.5.3, the newest stable release (supports up to API 37) | AGP 9.5.0 release notes; Google Maven metadata | +| Gradle | 9.6.0 or later (AGP 9.5 minimum and default); 9.9.3 pinned in the wrapper; Homebrew has 9.9.3 | AGP 9.5.0 release notes; `gradle --version` | +| JDK | 17 (the AGP minimum and default) | AGP 9.5.0 release notes; Homebrew openjdk@17 17.0.21.1 | +| SDK Build Tools | 36.0.0 (AGP 9.5 minimum and default; the plugin downloads it) | AGP 9.5.0 release notes | +| Platform | android-37.2 to compile against (37.0 and 37.1 also exist; Compose 1.13.0 needs 37.1 or later) | `sdkmanager --list`; the build's AAR metadata check | +| Kotlin | 2.4.x (Gradle 9.9.3 embeds 2.4.21) | `gradle --version`; latest stable Kotlin UNCONFIRMED | +| Compose BOM | 2026.11.01 (Compose 1.13.0, Material 3 1.5.0) | BOM mapping page, stable channel | +| Navigation 3 | 1.2.2 | stable channel | +| Lifecycle | 2.11.1 | stable channel | +| CameraX | not used (1.7.0 is current, should 2.5.1 be revisited) | stable channel | +| Media3 | 1.11.1 seen (10 September); a newer stable is likely, UNCONFIRMED | stable channel | +| WorkManager | 2.12.0 | stable channel | +| Glance (only if a widget is wanted) | 1.2.0 | stable channel | +| OkHttp, kotlinx.serialization, coroutines, Coil, DataStore, AndroidX Browser | not checked; pin at scaffold time | UNCONFIRMED | + +All versions go in one catalogue, `gradle/libs.versions.toml`, pinned exactly, with the Gradle wrapper checked in so CI and every machine build with the same toolchain. + +## 2.3 Module layout under apps/mobile-android + +The iOS split is the model: a Foundation-only package that tests without a simulator, and an app that owns UI and platform glue ([K] and apps/mobile-ios/Cap). The two iOS extensions have no Android counterpart because Android records the screen in the app's own process. + +``` +apps/mobile-android/ + README.md build, run, test, debug hooks (mirrors apps/mobile-ios/README.md) + .gitignore build/, .gradle/, .kotlin/, local.properties, captures/ + settings.gradle.kts + build.gradle.kts + gradle.properties + gradle/libs.versions.toml + gradle/wrapper/ gradle-wrapper.jar and properties + gradlew, gradlew.bat + capkit/ pure Kotlin on the JVM, no Android imports + src/main/kotlin/so/cap/kit/ + ApiClient.kt ApiError.kt Models.kt Decoding.kt Links.kt Formatting.kt + Social.kt Editing.kt TrimTrack.kt Recording.kt RecordingUploads.kt + UploadEngine.kt PendingUploads.kt Analytics.kt SnapshotCache.kt WebVtt.kt + src/test/kotlin/so/cap/kit/ one test file per iOS suite, same names + (test resources point at ../../mobile-ios/CapKit/Tests/CapKitTests/Fixtures) + media/ Android library: everything that touches codecs and capture + src/main/kotlin/so/cap/media/ + SegmentWriter.kt Fmp4Writer.kt VideoEncoder.kt AudioEncoder.kt + CameraCapture.kt ScreenCapture.kt GlFrameRenderer.kt + src/androidTest/ encode synthetic frames on the emulator and check the segments + app/ + src/main/AndroidManifest.xml + src/main/kotlin/so/cap/mobile/ + CapApplication.kt MainActivity.kt + app/ AppServices, AppModel, SessionModel, LibraryModel, UploadCenter, + RecordingCoordinator, ToastCenter, Usage, CredentialVault, Notifications + designsystem/ Theme, Buttons, Badges, RemoteImage, EmptyState, Skeleton, Toast + features/ auth/ home/ cap/ edit/ record/ settings/ analytics/ + services/ ScreenRecordingService, UploadWorker, RecordingUploadWorker + src/debug/ debug-only launch arguments and the network security config for local servers + src/androidTest/ Compose and UI Automator tests against the fixture server +``` + +Three Gradle modules, not thirty. `capkit` holds everything iOS keeps in CapKit so the 131 unit tests can be ported one for one and run on a plain Linux runner with no emulator. `media` is separate because it is the only code that needs instrumented tests and the only code with real device risk. Feature folders inside `app` mirror [F] so a reviewer can put the Swift and Kotlin files side by side. + +Package and application id: `so.cap.mobile`, matching the iOS bundle id, with a `.debug` suffix for debug builds so a debug and a store build can coexist. The final id is the publisher's call (Part 4, Q2). + +## 2.4 iOS to Android mapping + +| iOS | Source | Android | Notes | +|---|---|---|---| +| SwiftUI, @Observable models | apps/mobile-ios/Cap | Compose, state holders exposing StateFlow, ViewModel for screen models | | +| TabView with a Record tab that is really an action | [A]/CapApp.swift:176-184, :262-294 | Navigation bar with three destinations and a centre Record action; navigation rail on large screens | | +| NavigationStack paths, NavigationSplitView | [A]/CapApp.swift:156-158, [F]/Home/LibrarySplitView.swift | Navigation 3 back stacks per tab; Material 3 adaptive list-detail scene over the same back stack | Keeps the open Cap across fold, unfold and rotation | +| Liquid Glass | throughout | Material 3 tonal surfaces with Cap colours; optional blur on API 31 and later | Visual gap, needs design sign-off (Q11) | +| ContentUnavailableView | every empty and error state | One `EmptyState` composable | | +| Keychain item {apiKey, userId} | [K]/Storage.swift:27-89 | Keystore-wrapped file in `noBackupFilesDir` | Excluded from Auto Backup and device transfer, like "this device only" | +| First-launch keychain wipe | [A]/AppModel.swift:25-34 | Not needed: app data goes with the uninstall | | +| Re-check after first unlock | [A]/AppModel.swift:195-203 | Not direct-boot aware; the app only starts after unlock | | +| UserDefaults | B section 7.6 | DataStore Preferences, same key meanings | | +| JSON snapshot cache | [K]/Storage.swift:150-193 | Files in `cacheDir/snapshots//` | | +| Image pipeline | [K]/ImagePipeline.swift | Coil with a 150 MiB disk cache, size-bucketed keys, an interceptor that adds Bearer only for the Cap origin and strips both auth headers on cross-origin redirects | | +| ASWebAuthenticationSession (ephemeral) | [F]/Auth/SignInModel.swift:101-123 | Auth Tab where supported, else an ephemeral Custom Tab, else a normal Custom Tab with a cap://auth intent filter | See risk R6 on redirect interception | +| SFSafariViewController sheet | [D]/SafariView.swift | Custom Tabs | | +| Open in Safari, dashboard links | [F]/Settings/SettingsView.swift:37-56, :87-111 | `ACTION_VIEW` to the default browser | | +| cap:// URL scheme | [C]/Info.plist:7-19 | Intent filters for cap://s/*, cap://auth | cap://record/stop is not needed: the notification Stop action talks to the service directly | +| Universal links (not enabled) | [C]/Cap.entitlements | App Links for https://cap.so/s/* would be new scope and need assetlinks.json on cap.so | Not parity (Q7) | +| APNs | [A]/PushNotifications.swift | FCM, blocked on server work | Q5 | +| Local notification "Your recording is saved" | [B]/SampleHandler.swift:288-301 | Notification from the recording service | | +| Live Activity: upload | [W]/UploadLiveActivity.swift | Progress notification; on Android 16 and later a promoted Live Update (`Notification.ProgressStyle`), verify the API at build time | Same phases and copy | +| Live Activity: screen recording | [W]/ScreenRecordingLiveActivity.swift | The foreground service notification with a chronometer and a Stop action | Stop works without opening the app, which iOS cannot do | +| WidgetKit extension | [W]/CapWidgetsBundle.swift | Nothing to port. A Glance widget or Quick Settings tile would be an extra | Finding 1 | +| ReplayKit broadcast extension | [B]/SampleHandler.swift | MediaProjection plus a foreground service of type mediaProjection, in process | No app group, hand-off or Darwin notifications | +| Broadcast mic toggle, app audio fallback | [B]/SampleHandler.swift:87-99 | AudioRecord for the microphone; AudioPlaybackCapture for app audio when the mic is off | Some apps opt out of playback capture; then the track is silence | +| Idle frame repeat for static screens | [B]/SampleHandler.swift:176-191 | Same: re-submit the last frame every 0.5 s so segments keep their rhythm | | +| AVCaptureSession | [F]/Record/CameraCapture.swift | Camera2: one repeating request into a SurfaceTexture; a GL renderer draws each frame to the viewfinder and to the encoder's input surface | The GL step rotates to upright 1080x1920 and un-mirrors the front camera, as iOS saves it; the encoder surface outlives a camera switch (2.5.1) | +| AVAssetWriter CMAF segments | [K]/SegmentWriter.swift | `media/SegmentWriter.kt`: MediaCodec plus `Fmp4Writer` | Section 2.5 | +| In-process AAC with priming trim and silence fill | [K]/SegmentWriter.swift:236-479 | MediaCodec AAC-LC, 48 kHz mono, 96 kbps, same gap rules | | +| Background URLSession | [K]/BackgroundUploads.swift, [K]/RecordingUploads.swift | WorkManager long-running work with a foreground notification (dataSync type); OkHttp inside | On Android 14 and later also evaluate user-initiated data transfer jobs | +| beginBackgroundTask | [A]/UploadCenter.swift:350-368 | Covered by the same worker | | +| handleEventsForBackgroundURLSession relaunch | [A]/CapApp.swift:40-55 | WorkManager restarts the worker after process death and reboot | | +| AVPlayer | [F]/Cap/CapDetailModel.swift:310-349 | Media3 ExoPlayer with a data source that adds Bearer for same-origin URLs only. capkit decides the origin with OkHttp's URL parser, so the player must load through OkHttp or be given the URL in the form SafeUrl.media returns: Media3's default data source opens a java.net.URL, which reads `https://cap.so\@evil.example/x` as evil.example where OkHttp reads cap.so | | +| AVPictureInPictureController | [F]/Cap/CapPlayer.swift:29-36 | Activity Picture in Picture with auto-enter | | +| AirPlay picker | [F]/Cap/CapPlayer.swift:62-72 | Leave out in v1; Cast needs Google Play services and a receiver app | Not behaviourally required (Q12) | +| Now Playing and remote commands, background audio mode | [F]/Cap/CapPlayer.swift:567-639, [C]/Info.plist:28-31 | Media3 MediaSession; a MediaSessionService if background audio should continue | | +| App-drawn captions | [F]/Cap/CapPlayer.swift:478-521 | A Compose overlay using the same cue and phrase logic in capkit | | +| AVMutableComposition preview | [F]/Edit/EditorModel.swift:28-38 | ExoPlayer playlist of clipped items over the same source, or Media3 CompositionPlayer; decided by a spike in the editor PR | | +| AVAssetImageGenerator filmstrip | [F]/Edit/EditorModel.swift:139-186 | MediaMetadataRetriever or Media3 frame extraction on the remote MP4 | Slow seeks on long-GOP sources (R4) | +| Swift Charts | [F]/Analytics/AnalyticsScreen.swift:272-373 | Compose Canvas | | +| PhotosPicker | [F]/Home/AddMenu.swift:54 | Android Photo Picker (ActivityResultContracts.PickVisualMedia) | No permission needed | +| fileImporter | [F]/Home/AddMenu.swift:55-58 | Storage Access Framework (OpenDocument) | | +| PHAssetCreationRequest, Photos add permission | [A]/PhotoLibrary.swift | MediaStore insert into Movies/Cap | No permission on API 29 and later | +| StoreKit storefront gate | [A]/WebUpgrade.swift | A build-time flag, off by default, until Cap decides the Play billing position | Q8 | +| UIImpactFeedbackGenerator, sensoryFeedback | A section 7.5 | HapticFeedbackConstants | | +| isIdleTimerDisabled | [F]/Record/RecordModel.swift:182, :199 | `keepScreenOn` on the recorder | | +| Orientation control | [A]/CapApp.swift:57-77 | Portrait on phones except fullscreen video; free rotation on large screens | Recent Android versions ignore orientation locks on large screens anyway (verify for API 37) | +| Privacy manifest | apps/mobile-ios/Cap/PrivacyInfo.xcprivacy | Play Data safety form with the same six data types | | +| Debug env hooks (CAP_DEBUG_*) | ios-tests-config.md section 1.2.1 | Instrumentation arguments and intent extras read only in `src/debug` | Release builds compile none of it | +| Dynamic Type, VoiceOver, Reduce Motion | A section 7.4 | Font scale, TalkBack semantics with the same labels, the system animation scale | | + +## 2.5 Recording architecture + +This is where the real work and the real risk are, so it gets its own section. + +What the server needs (route.ts:3596-3741): per track, one init.mp4 and media segments named segment_001.m4s upward, indices consecutive from 1, each at most 10 s, uploaded by presigned PUT as video/mp4, then a completion call listing index and duration per segment. iOS produces these with AVAssetWriter's CMAF profile at a 2 s interval ([K]/SegmentWriter.swift:79-121). + +Android design: + +1. `VideoEncoder`: MediaCodec H.264 with a surface input, bitrate as on iOS (camera 4 Mbps; screen min(8 Mbps, max(2.5 Mbps, width x height x 2)), [B]/SampleHandler.swift:171-174), 30 fps, key-frame interval 2 s, no B-frames, High profile where the device offers it. A sync frame is requested at each 2 s boundary so every segment starts on a key frame. +2. `AudioEncoder`: AudioRecord (microphone) or AudioPlaybackCapture (app audio) into MediaCodec AAC-LC at 48 kHz mono, 96 kbps, with the iOS silence-fill rules ([K]/SegmentWriter.swift:127-163). +3. `Fmp4Writer`: turns encoded samples into ftyp plus moov (the init segment) and moof plus mdat pairs (media segments), one writer per track, cutting on the first key frame at or after each 2 s mark. Two ways to get there, to be settled by the spike in PR 10: + - a. Media3's muxer module has a fragmented MP4 muxer. If its output can be split cleanly at top-level box boundaries into init and media segments, use it and write only the splitter. + - b. Otherwise write the boxes directly. For one H.264 or AAC track with no B-frames this is a few hundred lines (ftyp, moov with mvex and trex, then moof with tfhd, tfdt and trun per segment) and has no dependency. +4. `SegmentWriter`: owns the two encoders and writers, shifts timestamps so the first sample is zero, skips non-monotonic samples, lets audio fail without stopping video, holds the last frame to the stop time, and reports each finished segment with its duration, exactly as [K]/SegmentWriter.swift does. +5. `RecordingUploads` in capkit: a direct port of [K]/RecordingUploads.swift and [K]/Recording.swift (job.json, target planner, three concurrent PUTs, retry and backoff, completion validation, crash recovery). It is pure Kotlin and fully testable on the JVM against a local HTTP server. +6. Capture sources: camera frames come from Camera2 into a SurfaceTexture and pass through a GL renderer that rotates and crops to upright 1080x1920 (1920x1080 on large screens in landscape) and un-mirrors the front camera (2.5.1); screen frames come from a MediaProjection virtual display rendering into the encoder surface, thinned to 30 fps, with the last frame repeated every 0.5 s when the screen is static. +7. Process model: camera recording runs in the foreground activity and stops when the app is backgrounded, the same outcome iOS has ([F]/Record/RecordModel.swift:271-273). Screen recording runs in `ScreenRecordingService`, a foreground service of type mediaProjection (plus microphone when the mic is on), which also uploads segments live. After stop, whatever is left is drained by `RecordingUploadWorker`. + +### 2.5.1 Camera2 or CameraX + +Two routes were on the table for getting camera frames into the encoder, and each had half of the right answer. + +- Camera2 directly, with the capture session targeting the viewfinder surface and the MediaCodec input surface. The point in its favour is the mid-recording flip, which iOS allows by swapping the input inside one session ([F]/Record/CameraCapture.swift:200-214): the encoder's input surface belongs to the app, so it survives closing one camera and opening the other, and the recording carries on in the same segment sequence. +- CameraX for the device and preview, with a GL renderer between the camera and the encoder to produce upright, un-mirrored frames. + +Decision: Camera2, and keep the GL stage. Reasons: + +1. The flip needs the GL stage whichever API opens the camera. MediaCodec encodes the buffers it is given and does not rotate them, and the front and back sensors are normally mounted at different orientations (to be confirmed per device from `SENSOR_ORIENTATION` in PR 11). A session that feeds the encoder surface straight from the sensor would change picture orientation at the flip, and the front camera would be saved mirrored or not depending on the device. iOS records upright pixels with the front camera un-mirrored ([F]/Record/CameraCapture.swift:178-189), so the pixels have to be transformed before the encoder. A rotation flag in the container cannot express a change part-way through a track. +2. With the GL stage in place, the "surface survives a reopen" property holds for free: the camera only ever sees a SurfaceTexture owned by the renderer, the encoder only ever sees the renderer's output, and a flip is close, open, carry on, with the renderer holding the last frame across the gap. +3. What is then left for the camera layer is small: open a device, run one repeating request at a fixed 30 fps into one surface, and report disconnects and errors. Camera2 does that in one file with exact control of the request (record template, fixed frame-rate range, stabilisation) and gives the raw device callbacks the recorder's state machine wants: disconnected maps to the iOS "interrupted" event and error to its runtime error ([F]/Record/CameraCapture.swift:216-234). CameraX's value is its use-case plumbing and VideoCapture, and this design uses neither. +4. It removes a dependency family, in keeping with 2.1. + +Cost: CameraX carries workarounds for device-specific camera bugs that Camera2 code has to meet on its own. Mitigation: one conservative stream configuration (a single 1920x1080 preview-class stream), testing on real phones from PR 11, and keeping all camera code inside `media/CameraCapture.kt` so that swapping in a CameraX Preview feeding the same SurfaceTexture is a one-file change if a device forces it. + +The gate: before any recorder UI is built, PR 10 must show that a recording made by this writer on the emulator and on one physical phone is accepted by a real Cap server's finaliser (queueDesktopSegmentsFinalization, apps/web/lib/desktop-segments-finalization.ts) and plays on the share page. The fixture server cannot prove this because it has no recording routes. If the finaliser rejects something about Android's output, that is found in week one instead of after the UI exists. + +Platform rules to design around (to be re-verified against current documentation when the PR is written): capture consent is asked for every session and the token is single use on Android 14 and later; the foreground service must start after consent and before the virtual display; the user can choose to share one app instead of the whole screen; newer Android versions end projection when the device locks; sensitive content such as one-time codes can be hidden from capture by the system. Each of these maps to an existing iOS stop path ("stopped elsewhere", B section 2.5), so the app needs no new behaviour, only the right handling. + +## 2.6 Shared contracts with the web API + +Today there is no machine-readable contract to share: MobileApiContract is not in the generated spec and nothing emits one (web-api.md section 7). The plan therefore has three layers, cheapest first: + +1. Hand-written Kotlin models and client that mirror [K]/Models.swift and [K]/APIClient.swift, with the same lenient decoding. This is what iOS does. +2. Shared fixtures. `capkit` tests decode the same five JSON files the iOS tests use ([T]/Fixtures: bootstrap.json, caps.json, cap-detail.json, analytics.json, org-settings.json) by pointing a test resource directory at them. Both clients are then pinned to identical payloads, including the deliberately broken entries. The Android CI path filter includes that directory so a fixture change re-runs the Android tests. +3. The same request-shape tests as iOS: every endpoint's method, path, query and body is asserted against a recording transport, ported from [T]/APIClientTests.swift, plus the endpoints iOS never tests (session/revoke, active-organization, folders, report, blocks, account deletion, image uploads; ios-tests-config.md section 6.2). + +What would make drift detectable, and needs the maintainers: a small `feat(web)` change that exports `OpenApi.fromApi(MobileApiContract)` to a checked-in or CI-generated file. Android (and iOS) could then validate their models against it. I would propose it to Richie rather than include it, because it touches packages/web-domain (Q6). + +UI tests reuse apps/mobile-ios/Fixtures/server.py in place rather than copying it. It binds 127.0.0.1 and returns absolute http://localhost: URLs (server.py:12, :378), so the emulator reaches it through `adb reverse tcp:4310 tcp:4310`, which makes localhost inside the emulator point at the Mac. Its missing recording routes mean the recorder is verified against a real local Cap server instead (Part 5). + +## 2.7 Monorepo fit + +- Workspaces and Turbo: `apps/*` is a workspace glob (package.json:118-122), but a directory without a package.json is ignored by Bun and Turbo, which is how apps/mobile-ios sits there today. apps/mobile-android gets no package.json and no Turbo task. Gradle is the only build tool inside it. +- Biome: `biome ci . --linter-enabled=false` runs over the whole repo (ci.yml:180) with tabs for JSON and `vcs.useIgnoreFile` on (biome.json:3-7). Consequences: any JSON committed under apps/mobile-android must be tab-indented (the shared fixtures already are); Gradle's build output contains JSON, so apps/mobile-android/.gitignore must exist from the first commit or a local `biome ci` will trip over `build/`; Kotlin, Gradle scripts, XML, TOML and properties files are not Biome's business (the Swift, plist and Python files pass today; UNCONFIRMED until run, so PR 1 runs `bun run biome ci . --linter-enabled=false` as an acceptance check). +- AGENTS.md rules that bind this work: no code comments except hard-won context (AGENTS.md:8); conventional commits; never a Co-authored-by or any other trailer (AGENTS.md:88-90); do not start dev servers; tests wait on signals, not time. For Kotlin that means virtual time in coroutine tests, Compose test clocks and idling for UI tests, and no `Thread.sleep` or `delay` in tests. +- Kotlin hygiene, in the spirit of the repo's `-D warnings`: ktfmt through Spotless (a formatter with no options, like rustfmt and Biome), Kotlin warnings as errors, Android Lint with `warningsAsErrors` and a checked-in empty baseline. +- Commit and branch style, copied from the iOS history: subjects like `feat(mobile-android): add the email code step`, lower case, imperative, no full stop; branches `feat/mobile-android-`; server changes in their own `feat(web)` or `fix(web)` commits. +- CI: add `android: - 'apps/mobile-android/**'` (plus the shared fixtures path) to the change filter beside `ios` (ci.yml:86-87) and a job beside the iOS one (ci.yml:144-163): + +```yaml + android: + name: Android + needs: changes + if: needs.changes.outputs.android == 'true' + runs-on: blacksmith-8vcpu-ubuntu-2404 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v6 + with: { distribution: temurin, java-version: 17 } + - uses: gradle/actions/setup-gradle@v6 + - name: Check, test and build + working-directory: apps/mobile-android + run: ./gradlew spotlessCheck :capkit:test :app:testDebugUnitTest :app:lintDebug :app:assembleRelease +``` + + This mirrors the iOS job (unit tests plus an unsigned release build), but on the Linux runner the rest of CI uses, so it costs less than the macOS job. Action versions are to be matched to what the repo already pins. Emulator tests stay out of CI, as the iOS UI tests do. How the merge-queue gate treats a new path-filtered job is UNCONFIRMED (scripts/ci/merge_queue.py was not read) and must be checked with the maintainers before an upstream PR. +- Docs: apps/mobile-android/README.md in the shape of the iOS one. AGENTS.md and CONTRIBUTING.md do not mention the iOS app, so they are left alone. +- Licence: the repo is AGPLv3 apart from named crates (LICENSE). PR 1 lists every dependency with its licence in the README, read from the published POMs: everything shipped in the app is Apache 2.0, and two test-only dependencies are not (JUnit 4 is under the Eclipse Public License 1.0 and Hamcrest under the New BSD licence). + +## 2.8 Copy that has to change + +The iOS strings name the platform in about a dozen places. These need a wording decision, ideally from Cap, before they are typed in (Q10): + +| iOS string | Source | Proposed Android wording | +|---|---|---| +| "Sign out of Cap on this iPhone?" | [F]/Settings/SettingsView.swift:164 | "Sign out of Cap on this device?" | +| "You'll be signed out on this iPhone." | [F]/Settings/SettingsView.swift:377 | "You'll be signed out on this device." | +| "On this iPhone", "...push notifications on this iPhone, emails..." | [F]/Settings/NotificationSettingsView.swift:52, :69 | "On this device" | +| "Turn on in iOS Settings" | [F]/Settings/NotificationSettingsView.swift:99 | "Turn on in Settings" | +| "Opens your Cap dashboard in Safari", "Opens cap.so in Safari", "Open in Safari" | [F]/Settings/SettingsView.swift:55, :99, [F]/Cap/CapDetailView.swift:224, :463 | "in your browser", "Open in browser" | +| "You won't see their Caps or comments in Cap for iPhone." | [F]/Cap/CapDetailView.swift:140 | "...in Cap for Android." | +| "Save to Photos", "Saved to Photos", "Saving to Photos…", "Allow Cap to add videos in Settings > Privacy > Photos." | [F]/Cap/CapDetailView.swift:454, [F]/Cap/CapDetailModel.swift:784-807 | "Save to device", "Saved to your device"; no permission message needed | +| Screen recording steps naming the Dynamic Island and Lock Screen, and "Tap the record button, then **Start Recording**" | [F]/Record/ScreenRecording.swift:275-366 | "Tap record, then allow Cap to record your screen." / "Use any app. Cap keeps recording." / "Stop from the notification. Your link is ready straight away." | +| "Upload from Photos", "Upload from Files" | [F]/Home/AddMenu.swift:22-40 | Keep, or "Upload from gallery" | + +Everything else is kept word for word, including accessibility labels, so one test plan can describe both apps (label inventory in ios-tests-config.md section 6.3). + +## 2.9 What ships with no server change, and what does not + +| Area | Works against today's server | Needs upstream server work | +|---|---|---| +| Email code sign-in, browser sign-in | Yes | Per-device keys, so Android does not sign out the iPhone (Q4); a safer redirect for Android (R6) | +| Library, Cap detail, playback, comments, reactions, transcript, summary | Yes | | +| File upload, Loom import | Yes | Source tag reads "cap-mobile-ios" (route.ts:3443, :3486) | +| Camera and screen recording | Yes, if the segment writer passes the PR 10 gate | | +| Editor, settings, analytics | Yes | | +| View counting | Yes | Recorded as browser "Cap for iOS", os "iOS" (route.ts:3022-3024) | +| Usage events | Accepted, but stored as platform "ios" with an iPhone user agent (apps/web/lib/mobile-events.ts:19-26, :57) | A platform field in MobileEventsInput (Mobile.ts:233-239). Until then Android sends none | +| Push notifications | No | FCM token schema, an FCM sender beside apps/web/lib/apns.ts, a Firebase project owned by Cap | +| https share links opening the app | No (not on iOS either) | /.well-known/assetlinks.json on cap.so | + +--- + +# Part 3. Build plan as a PR stack + +## 3.0 Rules for the stack + +- Seventeen PRs in the base stack, three more that wait on server-side changes (3.3). Each one builds, installs, runs and can be reviewed alone, and each leaves the app in a usable state: a later PR never has to land for an earlier one to make sense. +- Built as draft PRs on the contributor's fork first, stacked with `gh stack`, one branch per PR named `feat/mobile-android-`. They are proposed to CapSoftware/Cap only once the maintainers have said they want them and in what shape (Part 4, Q1). +- One commit per real step. The step lists below are the commits. Nothing is split to raise a count, and a step that turns out to be two real changes becomes two commits. The planned total is about 167 commits across the base stack before review fixes (the iOS app took 83 commits and 15 PRs for 22,421 lines). That number is a consequence of the step lists, not a target. +- Commit subjects: `feat(mobile-android): ...`, `test(mobile-android): ...`, `build(mobile-android): ...`, `ci: ...`. No trailers of any kind. Tests land in the PR that adds the behaviour. +- One ordering choice worth stating: file upload comes before recording. Recording depends on the upload engine, target handling and notifications, and file upload is the low-risk way to prove those first. + +Standing acceptance checks, run for every PR from apps/mobile-android unless the PR says otherwise: + +```sh +./gradlew spotlessCheck :capkit:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleRelease +bun run biome ci . --linter-enabled=false # from the repo root, when the PR adds or changes JSON +``` + +Standing emulator checks: the debug build installs and cold-starts with no entry in `adb logcat -b crash` on two AVDs, API 37 (primary) and API 29 (the floor); screenshots for the PR body are taken with `adb exec-out screencap -p` in light and dark; TalkBack reads the new screen's controls with the labels from the iOS inventory. + +Emulator session used by most PRs (fixture data, no real account needed): + +```sh +python3 apps/mobile-ios/Fixtures/server.py 4310 # needs ffmpeg on first run; both are installed +adb reverse tcp:4310 tcp:4310 +adb install -r app/build/outputs/apk/debug/app-debug.apk +adb shell am start -n so.cap.mobile.debug/so.cap.mobile.MainActivity \ + --es capApiBaseUrl http://localhost:4310 \ + --es capDebugSession 0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie +``` + +The two extras are read only by code in `app/src/debug`, the Android form of CAP_API_BASE_URL and CAP_DEBUG_SESSION ([A]/AppModel.swift:105-120, :206-219). The second fixture key, 1f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e with user_empty, gives the empty free-plan account. + +## 3.1 The stack at a glance + +| # | Branch slug | What a reviewer can do when it lands | iOS source mirrored | Planned commits | +|---|---|---|---|---| +| 1 | scaffold | Build an empty app; CI is green | project, CI job | 8 | +| 2 | capkit-core | Run the ported unit tests for the API client, models and links | [K] APIClient, Models, Decoding, Links, Formatting | 12 | +| 3 | design-system | Open a component gallery and the four-tab shell | [D], [A]/ToastCenter.swift, [A]/CapApp.swift | 9 | +| 4 | auth | Sign in by email code or browser, stay signed in, sign out | [F]/Auth, [A]/AppModel.swift, [K]/Storage.swift | 11 | +| 5 | library | Browse Caps, folders, spaces and organisations | [F]/Home, [A]/SessionModel.swift, [A]/LibraryModel.swift | 13 | +| 6 | playback | Open a Cap and watch it, including locked Caps and deep links | [F]/Cap (model, view, player) | 14 | +| 7 | social | Comment, react, read transcript and summary | [F]/Cap/CapSections.swift, [K]/Social.swift | 10 | +| 8 | cap-management | Share, rename, protect, delete, report, block, save | [F]/Cap/CapDetailView.swift, [F]/Home/CapActions.swift | 9 | +| 9 | upload | Upload a video or photo, import from Loom | [A]/UploadCenter.swift, [A]/BackgroundUploadCoordinator.swift, [K]/UploadEngine.swift, [K]/BackgroundUploads.swift | 11 | +| 10 | recording-engine | Run tests that encode, segment and upload a synthetic recording | [K]/SegmentWriter.swift, Recording.swift, RecordingUploads.swift | 10 | +| 11 | camera-recorder | Record with the camera and get a link | [F]/Record (RecordView, RecordModel, CameraCapture, RecentRecordingsList) | 9 | +| 12 | screen-recorder | Record the screen and get a link | [F]/Record/ScreenRecording.swift, [B]/SampleHandler.swift | 9 | +| 13 | editor | Trim, split and cut a Cap | [F]/Edit, [K]/Editing.swift, [K]/TrimTrack.swift | 11 | +| 14 | settings | Edit profile, organisation, notification preferences; delete account | [F]/Settings | 9 | +| 15 | analytics | Read organisation and per-Cap analytics | [F]/Analytics | 7 | +| 16 | live-updates | See upload and recording progress outside the app with the iOS copy and states | [W], [K]/UploadActivity.swift | 6 | +| 17 | large-screens-polish | Use the app on a tablet or foldable; pass the accessibility pass | [F]/Home/LibrarySplitView.swift, A section 7.6 | 9 | +| 18 | usage-events (waits on server) | Send usage events once the server can label Android | [A]/Usage.swift, [K]/Analytics.swift | 5 | +| 19 | push (waits on server) | Receive comment and view notifications | [A]/PushNotifications.swift | 6 | +| 20 | app-links (new scope, waits on server) | Open https://cap.so/s/ in the app | none | 3 | + +## 3.2 The PRs + +### PR 1. Scaffold and CI + +Scope: an empty Compose app and an empty capkit module that build, format, lint and test, wired into CI and invisible to Bun, Turbo and Biome. + +Files: apps/mobile-android/{settings.gradle.kts, build.gradle.kts, gradle.properties, gradlew, gradlew.bat, gradle/wrapper/*, gradle/libs.versions.toml, .gitignore, README.md}; capkit/build.gradle.kts and one placeholder test; app/build.gradle.kts, AndroidManifest.xml, CapApplication.kt, MainActivity.kt, res (adaptive icon placeholder from the existing AppIcon.png, themes), src/debug/res/xml/network_security_config.xml; .github/workflows/ci.yml (filter and job). + +Commits: (1) Gradle wrapper, settings and version catalogue; (2) capkit JVM module with a placeholder test; (3) app module with an empty Compose activity; (4) Spotless with ktfmt, warnings as errors, lint settings; (5) debug and release build types, debug-only cleartext for local hosts; (6) ignore Gradle and IDE output; (7) CI filter and Android job; (8) README with build, run and dependency licences. + +Acceptance: standing checks pass locally with `JAVA_HOME` set to JDK 17; `bun run biome ci . --linter-enabled=false` and `bun install` behave exactly as before (proves Bun, Turbo and Biome ignore the directory); the CI job runs on the fork PR and is skipped on a PR that touches nothing under apps/mobile-android; the wrapper jar passes Gradle's wrapper validation; the release APK builds unsigned. + +Emulator: install the debug APK on API 37 and API 29, launch, see a blank screen titled "Cap", no crash. Screenshot of each. + +### PR 2. CapKit core + +Scope: everything a screen needs to talk to the server, with no UI. Environment and URL rules, CapID, share links, deep-link and auth-callback parsing, validators, lenient decoding, all models, the error model, the client transport (headers, Bearer, video-access header, an unauthorised callback that carries the credentials that failed, single GET retry, refused redirects) and every endpoint. + +Files: capkit/src/main/kotlin/so/cap/kit/{Environment.kt, Links.kt, Decoding.kt, Models.kt, ApiError.kt, ApiClient.kt, Formatting.kt}; tests ApiClientTest, DecodingTest, LinkTest, UtilityTest; test resources pointing at [T]/Fixtures. + +Commits: (1) environment and base URL validation; (2) CapID, share URLs and the deep-link parser; (3) email, code and auth-callback validators; (4) lenient decoding helpers; (5) user, bootstrap, organisation, space and folder models; (6) Cap summary, upload progress, detail, comment and viewer models; (7) analytics, organisation settings, playback and upload-target models; (8) error model and status mapping; (9) client transport; (10) endpoints; (11) formatting helpers; (12) decode the shared iOS fixtures. + +Acceptance: `./gradlew :capkit:test` passes with the 16 tests of the APIClientTests suite, DecodingTests (8), LinkTests (14) and the 3 FormattingTests in UtilityTests.swift ported test for test (the other 3 tests in APIClientTests.swift are CredentialVaultTests and belong with the vault in PR 4; UtilityTests has no validator tests, the validators are covered by LinkTests), plus request-shape tests for the endpoints iOS leaves untested (ios-tests-config.md section 6.2); the module has no Android import (enforced by it being a plain JVM module); tests use a loopback HTTP server from the JDK, no mocks and no sleeps. + +Emulator: none needed; the app is unchanged. This PR is reviewed from the tests. + +### PR 3. Design system and app shell + +Scope: theme (colours from 1.6 for light and dark, type scale, shapes, motion constants), the reusable components, the toast host, the image pipeline, and the four-destination shell with placeholder pages. + +Files: app/.../designsystem/{Theme.kt, Color.kt, Type.kt, Buttons.kt, Badges.kt, SectionHeader.kt, StatLabel.kt, ErrorText.kt, EmptyState.kt, Skeleton.kt, Toast.kt, RemoteImage.kt, Avatar.kt, OrganizationIcon.kt, CapThumbnail.kt}; app/.../app/{AppServices.kt, ToastCenter.kt}; app/.../MainShell.kt; app/src/debug/.../GalleryActivity.kt. + +Commits: (1) colours and type; (2) shapes, spacing and motion; (3) ink, provider and tonal buttons; (4) error text, section header, stat label and badges; (5) toast host with haptics and announcement; (6) image pipeline, avatar, organisation icon and thumbnail; (7) empty state and skeleton; (8) tab shell with the Record action; (9) debug gallery and a Compose test that renders every component. + +Acceptance: standing checks; the gallery test renders each component in light, dark and at font scale 2.0 without clipping; an image request to a non-Cap host carries no Authorization header (unit test on the interceptor). + +Emulator: open the gallery (`adb shell am start -n so.cap.mobile.debug/so.cap.mobile.GalleryActivity`); screenshot every component in light and dark beside the iOS screenshots; tap through the four tabs; the Record action opens a placeholder full-screen page and returns. + +### PR 4. Auth + +Scope: the sign-in screen (both steps, hero as the final lockup with a short fade, static under reduced motion), email code flow, browser sign-in, credential vault, session restore, forced sign-out on 401, sign-out with server revoke, and a minimal Settings page holding Version and Sign out so the flow can be exercised end to end. + +Files: app/.../features/auth/{SignInScreen.kt, SignInModel.kt, CodeField.kt, SignInHero.kt}; app/.../app/{AppModel.kt, CredentialVault.kt}; app/.../features/settings/SettingsScreen.kt (minimal); manifest intent filter for cap://auth; res/xml backup rules; src/debug launch-argument reader. + +Commits: (1) credential vault with an instrumented round-trip test; (2) app phases, session restore and backup exclusion; (3) sign-in layout and hero; (4) email step; (5) code step with six boxes, auto-submit and resend timer; (6) browser sign-in and the cap://auth callback; (7) error copy; (8) 401 handling and the expired-session notice; (9) sign-out and the minimal settings page; (10) debug launch arguments; (11) UI tests against the fixture. + +Acceptance: standing checks; UI tests cover: invalid email message, code 123456 signs in, a wrong code shows "That code didn't work...", resend countdown, sign-out returns to sign-in, relaunch stays signed in; the vault file is excluded by the backup and device-transfer rules and is not readable as plain text; a 401 from any call signs out with the notice. + +Emulator: fixture session without the seeded key. Sign in with any email and 123456; kill and relaunch (still signed in); sign out. For browser sign-in, point the app at https://cap.so with a real account once (the contributor's own) and confirm the Google and Apple buttons return to the app through cap://auth. Screenshots: start step, code step, error state, dark mode, font scale 2.0 with the keyboard up on a small-screen AVD. + +### PR 5. Library + +Scope: session bootstrap and plan, cache-first library with paging and the processing poll, the Caps home with all states, folders, the scope bar with spaces and the organisation switcher, Cap row actions, the Add menu shell, New folder and Open a Cap link. + +Files: capkit SnapshotCache.kt; app/.../app/{SessionModel.kt, LibraryModel.kt}; app/.../features/home/{HomeScreen.kt, LibraryContent.kt, CapCard.kt, FolderStrip.kt, FolderScreen.kt, ScopeBar.kt, CapActions.kt, AddMenu.kt, NewFolderSheet.kt, OpenLinkSheet.kt}. + +Commits: (1) session model, cache first; (2) snapshot cache; (3) library model with refresh and generation counter; (4) paging and load-more retry; (5) processing poll; (6) home list, Cap card and states; (7) pull to refresh; (8) folder strip and folder screen; (9) scope bar, organisation switch and scope persistence; (10) Cap actions menu; (11) Add menu and New folder; (12) Open a Cap link; (13) UI tests. + +Acceptance: standing checks; unit tests for the library model (stale-response discard, dedupe on load more, poll backoff 3 s to 15 s on virtual time); UI tests against the fixture: list loads, scroll loads page 2, scope chips switch, a private toggle updates and rolls back on a forced error, delete confirms with the exact iOS wording, empty account shows "No Caps yet". + +Emulator: seeded fixture session. Scroll the stress Caps, switch scope and organisation, open a folder, long-press a Cap for the menu, create a folder (the fixture returns 404 for folders, so this one step is checked against a real server later, in PR 9's session), paste a share link. Turn on aeroplane mode: the cached list stays and a toast reports offline. Screenshots: list, skeleton, empty, error, scope bar, menu, both sheets. + +### PR 6. Cap detail and playback + +Scope: the detail screen with its five states, the Media3 player for HLS and MP4, the control overlay, scrubber with chapter gaps, speed menu, app-drawn captions, fullscreen with landscape, Picture in Picture, media session, the password gate with the video-access token, polling while processing, view counting, and cap://s deep links with ?t= and ?comment=. + +Files: capkit WebVtt.kt; app/.../features/cap/{CapDetailScreen.kt, CapDetailModel.kt, CapPlayer.kt, PlayerControls.kt, Timeline.kt, Captions.kt, PasswordGate.kt}; manifest: intent filter for cap://s, PiP flags on the activity. + +Commits: (1) detail model: load, access check, states; (2) header and state screens; (3) player attach with same-origin auth only; (4) controls overlay with auto-hide and double tap; (5) scrubber; (6) speed menu and persistence; (7) fullscreen and orientation; (8) Picture in Picture; (9) media session; (10) captions; (11) password gate; (12) processing poll; (13) view counting; (14) deep links and tests. + +Acceptance: standing checks; unit tests port the VTT parser, cue lookup and phrase splitting; UI tests: play and pause, speed change persists across relaunch, wrong password shows "That password didn't work." and letmein unlocks, `adb shell am start -a android.intent.action.VIEW -d "cap://s/?t=30"` opens the Cap at 30 s; the Bearer header is never sent to a storage host (data-source unit test). + +Emulator: fixture session. Play demo.mp4 and long.mp4, scrub, change speed, toggle captions, go fullscreen and rotate, press Home during playback and confirm PiP, check the media notification controls, open the locked Cap. A segmented (HLS) Cap is checked against a real server in PR 10's session. Screenshots: each state, controls, fullscreen, PiP, password gate. + +### PR 7. Comments, reactions, transcript and summary + +Scope: the three sections under the player, with the section selector: comment threads with sort orders, composer with the timestamp pin, optimistic send, replies, delete; the reaction bar, optimistic reactions and bursts over the video; timeline markers; transcript list with active row, search and copy or share; summary and chapters with their generating and empty states. + +Files: capkit Social.kt; app/.../features/cap/{CommentsSection.kt, Composer.kt, Reactions.kt, TimelineMarkers.kt, TranscriptSection.kt, SummarySection.kt}. + +Commits: (1) thread model with tests; (2) comment list and rows; (3) composer, pin and optimistic send; (4) replies, collapse and highlight; (5) delete; (6) reactions and bursts; (7) timeline markers; (8) transcript list and search; (9) transcript copy and share; (10) summary and chapters. + +Acceptance: standing checks; SocialTests (11) ported; UI tests: post a comment and see "Sending…" become the server comment, reply, delete with confirmation, react, search the transcript, tap a chapter to seek; a failed send restores the draft. + +Emulator: fixture session on a Cap with comments. Exercise each section with the keyboard up on a small-screen AVD to confirm the video steps aside as on iOS ([F]/Cap/CapDetailView.swift:152-158). Screenshots: each section, empty states, the composer with a pin. + +### PR 8. Sharing and Cap management + +Scope: the More menu and its flows: copy link and copy link at time, open in browser, system share, visibility and link access, rename, set or remove password, delete, report, block owner, save to device, and the entry points for Analytics and Edit (shown, routed to placeholders until PRs 13 and 15). + +Files: app/.../features/cap/{MoreMenu.kt, RenameDialog.kt, PasswordSheet.kt, ReportDialog.kt, BlockDialog.kt, SaveToDevice.kt}. + +Commits: (1) copy, open and share; (2) visibility and link access; (3) rename; (4) password; (5) delete; (6) report; (7) block; (8) save to device through MediaStore; (9) UI tests. + +Acceptance: standing checks; UI tests: visibility toggles with the three iOS toast texts, rename trims and caps at 255, delete closes the screen and removes the row; a saved video appears in `adb shell content query --uri content://media/external/video/media`; no storage permission is declared in the merged manifest. + +Emulator: fixture session for owner flows; the empty account or a second real account for viewer flows (report, block). Save a Cap and open it in the system gallery. Screenshots: menu as owner and as viewer, each dialog. + +### PR 9. File upload and Loom import + +Scope: pipeline A end to end: pick from the Photo Picker or Files, stage and probe, create, transfer to an s3Post, put or driveResumable target, report progress, complete with retry, survive process death; the in-list banner; a plain progress notification; Loom import with its status poll. + +Files: capkit {UploadEngine.kt, PendingUploads.kt}; app/.../app/{UploadCenter.kt, MediaProbe.kt}; app/.../services/UploadWorker.kt; app/.../features/home/{UploadBanner.kt, LoomImportSheet.kt}; manifest: POST_NOTIFICATIONS, foreground service type dataSync. + +Commits: (1) request builder for the three target kinds with tests; (2) pending-upload store; (3) staging, probing and image re-encode; (4) upload worker; (5) progress reporting; (6) completion and retry; (7) upload centre and banner; (8) Photos and Files entries; (9) Loom import; (10) progress notification; (11) tests. + +Acceptance: standing checks; BackgroundUploadTests (5) and the upload parts of UtilityTests ported; a JVM test uploads to a loopback server for each target kind and asserts headers (no Authorization, no reserved headers, correct Content-Range); UI test with the fixture: pick a file pushed with `adb push`, see "Uploading", then "Uploaded"; kill the backgrounded app's process mid-transfer with `adb shell am kill` (not `force-stop`, which also cancels scheduled work) and confirm the worker finishes the transfer and the completion call. + +Emulator: fixture session for the happy path. Then a real Cap server (Part 5): upload a 200 MB file on the API 37 AVD, background the app, confirm the notification progresses and the Cap plays on the share page; repeat with aeroplane mode toggled mid-transfer. Screenshots: banner in each phase, notification, Loom sheet. + +### PR 10. Recording engine (no UI) + +Scope: the gate from section 2.5. The segment writer (H.264 and AAC encoders, fragmented MP4 writer, silence fill, finish semantics) in `media`, and the recording job, target planner, upload state machine, completion validation and crash recovery in `capkit`. + +Files: capkit {Recording.kt, RecordingUploads.kt}; media {SegmentWriter.kt, Fmp4Writer.kt, VideoEncoder.kt, AudioEncoder.kt} and androidTest; app/.../services/RecordingUploadWorker.kt; a debug-only screen that records a generated test pattern. + +Commits: (1) job model and segment naming; (2) target planner; (3) completion validation; (4) upload state machine with a loopback storage server; (5) crash recovery and resume; (6) fragmented MP4 writer; (7) video encoder wrapper; (8) audio encoder and silence fill; (9) segment writer; (10) instrumented tests on synthetic frames. + +Acceptance: RecordingTests (16) ported and passing on the JVM; instrumented tests on the emulator encode 10 s of generated frames and tone and assert: init.mp4 and segment_001.m4s onward exist per track, every media segment starts with a key frame, durations are 2 s within a frame, the concatenation init plus segments is accepted by `ffprobe` on the Mac. The gate itself: a recording from the debug screen, made on the emulator and on one physical phone, is completed against a real Cap server, finalises and plays on the share page with correct duration and audio in sync. The PR body carries the ffprobe output and the share-page screenshot. If the finaliser rejects it, the writer is fixed here before PR 11 starts. + +Emulator: real Cap server session (Part 5). Run the debug pattern recorder for 10 s, 2 min and 6 min (the last on a free account to see the server's 403 and the client message). Kill the app mid-recording, relaunch and confirm the job is finished with what reached disk. + +### PR 11. Camera recorder + +Scope: the recorder screen in camera mode: capture mode switch with "coming soon" modes, camera and screen mode picker (screen disabled until PR 12), preview, record button, timer with the free-plan suffix, flip, permission and unavailable states, the state machine, too-short discard, discard confirmation, the free-plan stop, stop on backgrounding, the recent recordings list with automatic link copy. + +Files: media {CameraCapture.kt, GlFrameRenderer.kt}; app/.../features/record/{RecordScreen.kt, RecordModel.kt, RecordButton.kt, RecordTimer.kt, RecentRecordingsList.kt}; app/.../app/RecordingCoordinator.kt; manifest: CAMERA, RECORD_AUDIO. + +Commits: (1) Camera2 capture through the GL renderer into the viewfinder and the encoder; (2) record state machine; (3) recorder UI; (4) permission flows and blocked views; (5) free-plan limit and too-short discard; (6) discard and teardown; (7) stop on backgrounding and interruptions; (8) recent recordings and link copy; (9) tests with a file-backed camera source in debug. + +Acceptance: standing checks; state-machine unit tests cover every row of the transition table in B section 2.2 on virtual time (the 300 s limit does not wait 300 s); a recording under 1 s deletes the server Cap; the saved video is upright and not mirrored for the front camera; flipping the camera mid-recording yields one recording whose segment indices stay consecutive and whose picture stays upright on both sides of the flip. + +Emulator: real Cap server session. The AVD's front camera can be mapped to the Mac's webcam and the back camera to the emulator's virtual scene, so both are testable. Record 15 s front, flip mid-recording, stop; the link is on the clipboard and the Cap plays. Deny the camera permission and check the blocked view and "Open Settings". Press Home while recording and confirm the recording is kept. Screenshots: ready, recording, last 30 s warning (debug clock), blocked, recent list. + +### PR 12. Screen recorder + +Scope: screen mode end to end in one process: consent, the foreground service, the virtual display into the encoder with 30 fps thinning and idle-frame repeat, microphone or app audio, the ongoing notification with timer and Stop, every stop path (notification, in app, system stop, device lock, free-plan limit), finishing, the completion notification and link copy. + +Files: media/ScreenCapture.kt; app/.../services/ScreenRecordingService.kt; app/.../features/record/ScreenModePanel.kt; manifest: foreground service types mediaProjection and microphone. + +Commits: (1) consent flow and service start; (2) virtual display, thinning and idle frames; (3) audio source selection; (4) screen panel UI and copy; (5) ongoing notification with Stop; (6) stop paths and finishing; (7) completion notification and link copy; (8) coordinator integration; (9) UI Automator test that accepts the system dialog and stops from the notification. + +Acceptance: standing checks; the UI Automator test passes on API 37 and API 29; a 10 s recording of a static screen yields five 2 s segments (idle-frame repeat works); stopping from the notification never opens the app; a recording under 1 s is discarded and its Cap deleted. + +Emulator: real Cap server session. Record the home screen and another app with the mic on, then with the mic off while a video plays; stop from the notification; lock the device mid-recording; choose "share one app" in the system dialog and switch apps. Each case must end with a playable Cap or a clear message. Then repeat the basic case on a physical phone, because emulator encoders are not representative. Screenshots: panel idle and recording, system dialog, notification, completion notification. + +### PR 13. Editor + +Scope: the editor opened from the More menu: gate handling, the kept-ranges model, preview playback of the edit, filmstrip, the trim timeline with its gestures and zoom-on-hold, split, delete, undo, redo, save, restore original, and the refresh of the detail screen afterwards. + +Files: capkit {Editing.kt, TrimTrack.kt}; app/.../features/edit/{EditorScreen.kt, EditorModel.kt, EditorTimeline.kt, Filmstrip.kt, EditorPreview.kt}. + +Commits: (1) timeline model and operations with tests; (2) trim geometry with tests; (3) edit API; (4) entry and gating; (5) preview from kept ranges; (6) filmstrip; (7) timeline UI; (8) trim gestures and zoom; (9) split, delete, undo, redo; (10) save, restore and post-save refresh; (11) UI tests. + +Acceptance: standing checks; EditingTests (9) and TrimTrackTests (9) ported; UI tests: split makes "Clip 2", delete removes it, undo restores, save posts the expected keepRanges, Cancel with changes asks "Discard your changes?"; the first commit of step 5 is a short spike choosing between an ExoPlayer clipped playlist and CompositionPlayer, with the choice and why in the commit body. + +Emulator: fixture session on port 4310 for the UI (the fixture logs the EDIT body); a real server to see the edited Cap re-render and replace the video. Check scrubbing stays responsive on long.mp4. Screenshots: untouched, split, trimming with the readout bubble, zoomed, discard dialog. + +### PR 14. Settings + +Scope: the full settings tree replacing the minimal page from PR 4: account and plan rows, organisation picker, organisation settings and icon, profile and photo, notification preferences with the save queue, permissions and browser links, help and legal, delete account. The upgrade link stays behind a build flag that is off (Q8). + +Files: app/.../features/settings/{SettingsScreen.kt, ProfileScreen.kt, OrganizationScreen.kt, NotificationSettingsScreen.kt, DeleteAccountScreen.kt, ImagePickerControl.kt}; app/.../app/ImageEncoder.kt. + +Commits: (1) root sections; (2) plan row and refresh on resume; (3) profile name; (4) image picker and encoder, profile photo; (5) organisation settings and icon; (6) notification preferences; (7) delete account; (8) links, permissions and version; (9) tests. + +Acceptance: standing checks; the image encoder test reproduces the 1,024 px and 1 MiB ladder ([K]/ImageCoding.swift:35-88); the notification queue test shows out-of-order responses cannot revert a switch (the class of bug in upstream issue #3150, "Mobile Cap settings revert when independent saves finish out of order"); UI tests: Free and Cap Pro rows, toggles, the DELETE confirmation enabling the button. + +Emulator: fixture session for layout and toggles; a real server for profile, photo, organisation and deletion on a throwaway account (the fixture has none of those routes). Screenshots: each screen, light and dark. + +### PR 15. Analytics + +Scope: the Analytics tab and the per-Cap screen: range picker, states, metric tiles, the area chart with scrubbing and haptics, breakdown cards with tabs, Top Caps, the space filter, disk cache for organisation data. + +Files: app/.../features/analytics/{AnalyticsScreen.kt, AnalyticsModel.kt, TrendChart.kt, BreakdownCard.kt, MetricTile.kt}. + +Commits: (1) model and cache; (2) range picker and states; (3) metric tiles; (4) trend chart; (5) breakdown cards; (6) Top Caps and the per-Cap route; (7) tests. + +Acceptance: standing checks; model tests for cache-first load and the Pro-required state; a screenshot test of the chart at three data shapes (empty, one point, many); UI test: switching range re-queries with 24h, 7d, 30d, lifetime. + +Emulator: fixture session (it generates analytics); the empty account shows the Pro state. Drag across the chart and check the subtitle and haptic. Screenshots: loaded, Pro required, error, skeleton, per-Cap. + +### PR 16. Live Updates (the CapWidgets counterpart) + +Scope: bring the notifications from PRs 9, 11 and 12 to parity with the two Live Activities: the same kinds, phases and copy, the "in the background" stale state, throttling, dismissal timings, the "Saving your recording" state, taps that open cap://s/, and on Android 16 and later the promoted progress style with a status-bar chip. + +Files: app/.../app/Notifications.kt; app/.../services/{UploadWorker.kt, ScreenRecordingService.kt} (use the shared builder); res: channels and strings. + +Commits: (1) channels and a shared builder; (2) upload phases, copy and stale state; (3) recording stopping state; (4) promoted Live Update style with a fallback; (5) taps open the Cap; (6) tests. + +Acceptance: standing checks; a unit test maps every (kind, phase) pair to the iOS status line ([W]/UploadLiveActivity.swift:56-83); UI Automator reads the notification shade during an upload and after completion; nothing is posted when the notification permission is denied and the upload still completes. + +Emulator: fixture session, upload a file and watch the shade through preparing, uploading, finishing and done on API 37 (promoted style) and API 29 (plain style). Screenshots of each phase on both. + +Optional and outside parity, only if Cap wants it: a Quick Settings tile or a one-button Glance widget that starts a screen recording. Neither exists on iOS. + +### PR 17. Large screens, accessibility and release polish + +Scope: the two-pane Caps layout over the shared back stack with the "Pick a Cap" placeholder and compact rows, readable widths for settings and sign-in, the wide analytics layout, the orientation policy, a TalkBack and font-scale pass against the iOS label inventory, edge-to-edge and predictive back, R8 rules, a baseline profile, and the store notes in the README. + +Files: app/.../features/home/{LibraryTwoPane.kt, CapRow.kt}; touch-ups across features; app/proguard-rules.pro; a baseline profile module; README.md. + +Commits: (1) two-pane layout; (2) readable widths and wide analytics; (3) orientation policy; (4) TalkBack labels; (5) font scale and reduced motion fixes; (6) edge-to-edge and predictive back; (7) R8 rules with a release smoke test; (8) baseline profile; (9) large-screen UI tests and README. + +Acceptance: standing checks; the LargeScreenUITests (4) equivalents pass on a tablet AVD; the release build with R8 signs in, plays, uploads and records (reflection and serialisation survive shrinking); Android Lint accessibility checks are clean; cold start measured before and after the baseline profile on the same AVD and reported as measured numbers. + +Emulator: tablet and foldable AVDs. Fold and unfold with a Cap open and confirm it stays open; open the editor and rotate; run TalkBack through sign-in, library, player and recorder. Screenshots: two-pane, folded, settings width, analytics wide. + +### PRs 18 to 20. Waiting on server-side changes (3.3) + +- PR 18, usage events: port [K]/Analytics.swift (queue, batching at 20 events or 30 s, retry, one-week and 500-event limits) and AnalyticsTests (26), with the event names from B section 7.6. Ships disabled until S1 lands; then the flag flips. Commits: (1) queue and batching; (2) persistence and retry; (3) call sites; (4) disable on debug and non-local hosts; (5) tests. +- PR 19, push: FCM in its own module so the base app has no Firebase dependency, token registration, the permission prompt after the first upload, tap-to-open. Needs S2 and the Firebase project in Q5. Commits: (1) module and manifest; (2) token registration and removal; (3) permission prompt timing; (4) notification rendering and channels; (5) tap handling; (6) tests. +- PR 20, App Links: verified https://cap.so/s/* links. New scope, needs S3. Commits: (1) intent filter with auto-verify; (2) link handling shares the cap://s path; (3) tests. + +## 3.3 Server-side PRs the last three wait on + +These are changes to apps/web and packages/, so they are upstream work that needs the maintainers to agree and, for push, to own the credentials. They are listed so the dependency is explicit; none of them is started here. + +| # | Server PR | What it changes | Unblocks | +|---|---|---|---| +| S1 | `feat(web): label mobile events and views by platform` | An optional platform on `MobileEventsInput.app` (Mobile.ts:233-239), used by `mobileUserAgent` and the `properties.platform` line (apps/web/lib/mobile-events.ts:19-26, :57) instead of the fixed iPhone values; the same for the view-tracking strings (route.ts:3022-3024) and the upload source tag (route.ts:3443, :3486). Absent platform keeps today's iOS behaviour, so the iPhone app is unaffected. Tests beside apps/web/__tests__/unit/mobile-events.test.ts | PR 18 | +| S2 | `feat(web): send push to Android through FCM` | A platform or provider on push tokens: a column on mobile_push_tokens (packages/database/schema.ts:1105), so a Drizzle schema change with `bun run db:generate` and the generated migration committed; `MobilePushTokenInput` accepting FCM tokens, which contain characters outside hex, and not requiring the APNs-only `environment` value of sandbox or production (Mobile.ts:201-204; the column is also an enum of those two, schema.ts:1113-1116); the token column is 200 characters (schema.ts:1110) and FCM does not promise a token length, so it may need widening (verify); an FCM HTTP v1 sender beside apps/web/lib/apns.ts, whose payload is APNs-shaped (apps/web/lib/apns.ts:92-97), with its project id and service-account secret in the server environment; apps/web/lib/mobile-push.ts choosing the sender per token. Needs a Firebase project owned by Cap. Tests beside mobile-push.test.ts and apns.test.ts | PR 19 | +| S3 | `feat(web): serve assetlinks.json for Android App Links` | A /.well-known/assetlinks.json route under apps/web/app/.well-known naming the Android package and its signing certificate fingerprint, which only exists once the publisher and signing key are settled (Q2) | PR 20 | + +Smaller server items that are not PRs in this plan but are raised as questions in Part 4: per-device mobile keys (Q4), an OpenAPI export of the mobile contract (Q6) and a sign-in redirect that cannot be intercepted on Android (R6). + +## 3.4 What "done" means for the stack + +Every screen in 1.3 exists; every endpoint in 1.4 is called by the same flow as on iOS; the 131 CapKit tests have Kotlin counterparts; the 52 iOS UI test scenarios that make sense on Android have counterparts that run on a local emulator; a camera and a screen recording made on a physical phone play on cap.so. Push, usage events and https links are explicitly listed as waiting on the server, not silently missing. + +--- + +# Part 4. Risks and open questions + +## 4.1 Questions only Richie or the Cap maintainers can answer + +| # | Question | Why it matters | Evidence | +|---|---|---|---| +| Q1 | Does Cap want an Android app in this repo at all, and if so in what shape: one foundation PR like #3880 followed by small ones, or a reviewed stack? | Everything else depends on it. An unsolicited app of this size is a large review load | The Expo app was iOS only (`platforms: ["ios"]`, apps/mobile/app.config.js at ea1372851^) and was removed in favour of native iOS; no Android app issue or PR turned up in a search of CapSoftware/Cap issues and PRs on 30 Nov (search was by keyword, not exhaustive) | +| Q2 | Who publishes? Play Console account, application id (so.cap.mobile?), signing key custody, and whether a GitHub release APK is acceptable in the meantime | The name, logo and application id are Cap's, so the store account and signing key have to be too | iOS uses bundle id so.cap.mobile under team 47B7FCLL43 (apps/mobile-ios/README.md:83) | +| Q3 | Will the server stop labelling every mobile client as iOS? | Otherwise Android usage, views and uploads are recorded as iPhone | apps/web/lib/mobile-events.ts:19-26, :57; route.ts:3022-3024, :3443, :3486; Mobile.ts:1146 | +| Q4 | Can mobile keys be per device or per platform instead of one per user? | Today signing in on Android signs the user out of their iPhone | route.ts:563-592; desktop keeps up to 20 (apps/web/app/api/desktop/[...route]/session.ts:111-165) | +| Q5 | Push: will Cap add FCM (token schema, sender, a Firebase project it owns), or should Android ship without push? FCM also needs Google Play services, so phones without them would get no push; is that acceptable? | No Android push is possible today | Mobile.ts:201-204; apps/web/lib/apns.ts; apps/web/lib/mobile-push.ts:25-75 | +| Q6 | Is /api/mobile a contract a second client may rely on? It has no version and changes with the iPhone app. Would Cap accept exporting it as OpenAPI so both apps can be checked against it? | A change made for iOS would silently break Android; an exported contract is the only way to detect drift without a live server | MobileApiContract is not in packages/web-domain/src/Http/Api.ts; packages/web-domain/scripts/generate-openapi.ts:10 | +| Q7 | Are verified https share links wanted (assetlinks.json for Android, and the matching file for iOS)? | Not parity: iOS does not have them yet either | apps/mobile-ios/README.md:83; apps/web/app/.well-known has only api-catalog, mcp and oauth routes | +| Q8 | What is Cap's position on upgrade links under Google Play's payments rules? | iOS shows the dashboard upgrade link only on the US storefront, an App Store rule. Play's rules are different and change by region. The plan ships with the link off | [A]/WebUpgrade.swift:4-28; [F]/Settings/SettingsView.swift:37-56; [F]/Record/RecordView.swift:367-394 | +| Q9 | Minimum Android version: 10 (API 29, wide reach) or 14 (API 34, far fewer code paths, closer to the iOS "newest only" stance)? | Sets the amount of version-specific code in the recorder, picker and notifications | iOS targets 26.0 only ([P]:500) | +| Q10 | Sign-off on the Android wording in section 2.8 | About a dozen strings name iPhone, Safari, Photos or the Dynamic Island | section 2.8 | +| Q11 | Design: is Material 3 in Cap colours acceptable where iOS uses Liquid Glass, and can Cap supply an adaptive icon (foreground, background and monochrome layers) and vector logo and wordmark? | The repo only has PNG logos and a 1,024 px iOS icon | apps/mobile-ios/Cap/Assets.xcassets | +| Q12 | Is a Cast button needed to stand in for AirPlay? | Cast needs Google Play services and a receiver; the plan leaves it out | [F]/Cap/CapPlayer.swift:62-72 | +| Q13 | Screen + Camera: iOS has it built but hidden for lack of an entitlement. Should Android leave it out too? | Android could do it with an overlay permission; that would be ahead of iOS | [F]/Record/ScreenRecording.swift:66; [F]/Record/CameraBubble.swift | +| Q14 | Where should Android screen recordings land? The iOS extension sends no organisation or folder; Android can send the active ones as the camera does | Parity says send nothing; correctness may say otherwise. What the server does with neither is UNCONFIRMED | [B]/SampleHandler.swift:132-169 | +| Q15 | May Android PRs extend apps/mobile-ios/Fixtures/server.py (recordings, folders, profile routes), or move it somewhere shared? | It would let both apps test the recorder without a real server, but it lives in the iOS directory | ios-tests-config.md section 2.7 | +| Q16 | CI: is a new path-filtered job on the Linux runner welcome, and how does the merge-queue gate treat it? | scripts/ci/merge_queue.py was not read | .github/workflows/ci.yml:86-87, :144-163; .github/workflows/merge-queue.yml:39-46 | +| Q17 | Contribution terms for something this large: any CLA, and who reviews Kotlin? | CONTRIBUTING.md only says "Submit a PR" (line 21); the repo is AGPLv3 (LICENSE) | CONTRIBUTING.md, LICENSE | +| Q18 | Is there a public web page for requesting account deletion? | Play's listing asks for one in addition to the in-app flow | [F]/Settings/SettingsView.swift:320-392; UNCONFIRMED on cap.so | + +## 4.2 Open on the contributor's side + +| # | Item | Plan | +|---|---|---| +| A1 | Install the missing toolchain pieces listed in Part 5 | When building starts; nothing is needed before then | +| A2 | A physical Android phone to test on | Needed from PR 10: emulator encoders, Picture in Picture and OEM battery rules are not representative | +| A3 | End-to-end recording tests: run the Cap web stack locally (needs Docker or OrbStack), or use a real cap.so account and delete the test Caps | Local stack. It keeps test data off production and lets the finaliser logs be read | +| A4 | When to show working code | A demo once PRs 1 to 6 and the PR 10 gate work on the fork (sign in, browse, play, and one Android recording playing on a Cap share page). Building all 17 before asking would risk the whole effort on Q1 | +| A5 | What v1 is | The 17-PR base stack, with push, usage events and https links waiting on the server | + +## 4.3 Risks + +| # | Risk | Likelihood and impact | Mitigation | +|---|---|---|---| +| R1 | Upstream declines, or cannot review roughly as much code as the iOS app (22,421 lines of Swift) | The biggest risk; it decides whether the work ships at all | Fork-first; ask early (A4); mirror the iOS structure so review is by comparison; keep dependencies few; small PRs with tests and screenshots | +| R2 | The server finaliser rejects Android's segments | Unknown until tried; would stall both recorders | The PR 10 gate proves it before any recorder UI exists (section 2.5) | +| R3 | Encoder differences between devices: key-frame interval only approximately honoured, profile support, bitrate control, the emulator's software codec | Likely somewhere; affects segment timing and quality | Cut on real key frames and report measured durations (the server allows up to 10 s per segment, route.ts:3630-3741); test on a physical phone; fall back from High to Main profile when needed | +| R4 | Editor preview and filmstrip are slow on remote long-GOP video | Likely; iOS notes 250-frame GOPs making exact seeks cost up to 8 s (B section 4.4) | Reuse the iOS policy: key-frame seeks while dragging, one exact seek on release; cache filmstrip frames; spike in PR 13 | +| R5 | MediaProjection rules keep tightening, vendors kill background services, and Play requires a declaration for each foreground service type | Certain to need care | One service, started after consent, with correct types; every system stop path ends in a saved recording; Play declarations written into the README in PR 17 | +| R6 | Sign-in redirect interception. The browser flow returns the API key in a cap://auth URL (route.ts:3762-3809), and on Android any app can register that scheme | Low likelihood, high impact (a long-lived key with no expiry) | Use Auth Tab where the browser supports it, which returns the result only to the calling app; raise a server-side fix with the maintainers (a verified https redirect or a one-time code exchanged for the key) | +| R7 | Users with both phones are signed out of one by the other | Certain under today's server | Q4; until then the sign-in screen can say so | +| R8 | API drift while the stack is in review. The mobile API changed in 31 commits during November (ios-tests-config.md section 4.6) and has no version header that I saw | Likely | Lenient decoding; shared fixtures; rebase the stack often; Q6 | +| R9 | Play policy items: payments wording, data safety form, account deletion link, target API deadlines, 16 KB page-size support for bundled native libraries | Certain to need doing, low technical risk | No upgrade link by default; test on the 16 KB system image; checklist in the README | +| R10 | Long uploads in the background: time limits on data-sync foreground services on recent Android, Doze, vendor task killers | Possible on big files | Resumable job state as on iOS; completion call is retryable work; evaluate user-initiated data transfer jobs on Android 14 and later | +| R11 | The work reads as generated filler | Fatal for acceptance if it happens | One commit per real step, no padding; every PR runs, has tests, screenshots and measured numbers; no narrating comments; no trailers | +| R12 | Secrets and private data leak through logs or screenshots: presigned upload URLs, API keys, real account data | Possible | Never log URLs or headers; fixture data for all PR screenshots; credentials excluded from backup | +| R13 | The fixture server cannot exercise recordings, folders, profile, report, password, organisation switch, revoke, deletion or blocks | Certain (ios-tests-config.md section 2.7) | Those flows are checked against a local Cap server; Q15 | +| R14 | Licence and distribution: the repo is AGPLv3; a Firebase dependency rules out F-Droid | Low | Firebase isolated in its own module so a build without it stays possible | +| R15 | Facts in this plan about recent Android APIs that were not checked against current documentation (Auth Tab, Live Update style, capture rules on the newest releases, Media3's fragmented muxer) | Possible | Each is marked "verify" where it is used and is checked against current documentation in the PR that depends on it | +| R16 | Camera2 without CameraX's device workarounds (2.5.1) | Possible on unusual devices | One conservative stream configuration; real-phone tests in PR 11; camera code confined to one file so CameraX Preview can replace it | + +--- + +# Part 5. Emulator and toolchain needs + +Checked on the development Mac on 30 November 2026 by reading only. Nothing was installed. + +## 5.1 The machine + +MacBook Pro, Apple M5 Max, 18 cores, 128 GB RAM (`hw.memsize` 137438953472), macOS 27.0.1, 1.9 TB free on the system volume, hypervisor support on (`kern.hv_support` 1), Xcode 27.2. This is far more than Android emulation needs; several emulators can run at once beside a local Cap server. + +## 5.2 What is already there + +| Item | State | +|---|---| +| JDK 17 | Installed: Homebrew openjdk@17 17.0.21.1 at /opt/homebrew/opt/openjdk@17. Keg-only, so `/usr/libexec/java_home` reports no runtime and `JAVA_HOME` is empty | +| JDK 27 | Installed: Homebrew openjdk 27.0.1.1 (what Homebrew's Gradle launches with) | +| Gradle | Homebrew 9.9.3, which satisfies AGP 9.5's minimum of 9.6.0. Only needed once, to generate the wrapper | +| Android SDK root | ~/Library/Android/sdk with build-tools 34.0.0 and 35.0.0, platform-tools 37.0.3, platforms android-35, and the licences folder | +| adb, sdkmanager, avdmanager | Homebrew copies on the PATH (adb 37.0.1). sdkmanager needs `--sdk_root` because there is no cmdline-tools inside the SDK root | +| ffmpeg, python3 | Installed, so the iOS fixture server runs as is | + +So a correct JDK is already on disk and only needs pointing at. + +## 5.3 What is missing + +| Item | Needed for | Package or step (not run yet) | +|---|---|---| +| `JAVA_HOME` and `ANDROID_HOME` | Every Gradle and SDK command | Environment only, no install | +| Platform API 37.2 | compileSdk 37.2 | `platforms;android-37.2` | +| Build Tools 36.0.0 | AGP 9.5's minimum and default | `build-tools;36.0.0`, or let the plugin download it | +| Emulator | Running any AVD | `emulator` (37.3.10 listed) | +| Command-line tools in the SDK root | avdmanager and sdkmanager without the `--sdk_root` flag | `cmdline-tools;latest` | +| System image, primary | Daily testing on the target API | `system-images;android-37.0;google_apis_playstore;arm64-v8a` | +| System image, floor | Testing minSdk behaviour | `system-images;android-29;google_apis;arm64-v8a` | +| System image, 16 KB pages | Play's 16 KB check | `system-images;android-37.0;google_apis_ps16k;arm64-v8a` | +| AVDs | None exist (`~/.android/avd` is absent) | Four, below | +| Docker or OrbStack | Running the Cap web stack locally for upload and recording tests (CONTRIBUTING.md recommends OrbStack) | Not installed (A3) | +| Android Studio | Optional: Layout Inspector, profilers, the AVD camera and microphone settings UI | Not installed; the plan works from the command line without it | +| A physical Android phone | Real encoders, Picture in Picture, vendor battery behaviour, push | A2 | + +Only arm64-v8a images run on Apple Silicon. All the images named above are listed as available by `sdkmanager --list`. + +## 5.4 Commands, for when building starts + +```sh +export JAVA_HOME=/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home +export ANDROID_HOME=$HOME/Library/Android/sdk + +sdkmanager --sdk_root=$ANDROID_HOME \ + "cmdline-tools;latest" "emulator" "platform-tools" \ + "platforms;android-37.2" "build-tools;36.0.0" \ + "system-images;android-37.0;google_apis_playstore;arm64-v8a" \ + "system-images;android-29;google_apis;arm64-v8a" \ + "system-images;android-37.0;google_apis_ps16k;arm64-v8a" + +avdmanager create avd -n cap_phone_37 -k "system-images;android-37.0;google_apis_playstore;arm64-v8a" -d pixel_9 +avdmanager create avd -n cap_phone_29 -k "system-images;android-29;google_apis;arm64-v8a" -d pixel_4 +avdmanager create avd -n cap_tablet_37 -k "system-images;android-37.0;google_apis_playstore;arm64-v8a" -d pixel_tablet +avdmanager create avd -n cap_16k_37 -k "system-images;android-37.0;google_apis_ps16k;arm64-v8a" -d pixel_9 + +$ANDROID_HOME/emulator/emulator -avd cap_phone_37 -no-snapshot -no-boot-anim +``` + +The device profile names (pixel_9, pixel_4, pixel_tablet) are to be checked with `avdmanager list device` once the tools are installed; a foldable profile is added the same way for PR 17. Licences are accepted with `sdkmanager --licenses`. If Android Studio is installed later it brings its own JDK and can manage the same SDK root. + +## 5.5 What the emulator can and cannot prove + +| Area | On the emulator | Needs a physical phone | +|---|---|---| +| UI, navigation, sign-in, library, settings, analytics | Yes, on all four AVDs | No | +| Playback, captions, fullscreen | Yes | Picture in Picture and media controls behave slightly differently per vendor | +| File upload and background transfer | Yes, including killing the app mid-upload | Vendor task killers | +| Camera recording | Yes: the AVD's front camera can be mapped to the Mac's webcam and the back camera to the virtual scene; the host microphone can be enabled in the emulator settings (macOS will ask for camera and microphone access for the emulator) | Real sensor orientation, real hardware encoder | +| Screen recording | Yes, including the consent dialog and the notification Stop. This is better than iOS, where it needs a device | Hardware encoder quality and bitrate, lock-screen stop on real builds | +| Segment acceptance by the server | Yes, against a local Cap server | Repeat once on a phone before calling PR 10 done | +| Push | Play services exist on the playstore image | Real delivery timing | +| Large screens and folding | Tablet and foldable AVDs | Optional | + +Two practical points. The fixture server answers with http://localhost: URLs and binds 127.0.0.1, so each session runs `adb reverse tcp:4310 tcp:4310`; the debug build allows cleartext to local hosts only, as the iOS debug build does ([C]/Info.plist:34-42). And screenshots or screen recordings for PR bodies come straight from adb (`adb exec-out screencap -p > shot.png`, `adb shell screenrecord`), so no extra tooling is needed to meet the crew rule that UI changes carry screenshots. diff --git a/apps/mobile-android/README.md b/apps/mobile-android/README.md new file mode 100644 index 00000000000..f3f7db21a97 --- /dev/null +++ b/apps/mobile-android/README.md @@ -0,0 +1,117 @@ +# Cap for Android + +Native Android app for Cap, written in Kotlin and Jetpack Compose. So far it holds `capkit`, the client core the screens will be built on, and an app with the design system, sign-in and the tab shell, whose pages are still placeholders apart from a first Settings page. [PLAN.md](PLAN.md) holds the audit of the iOS app and the plan for the rest. + +## Layout + +- `capkit/` is a plain Kotlin module on the JVM with no Android imports, the counterpart of the Foundation-only CapKit Swift package. It holds the server environment and its URL rules, the share-link, deep-link and sign-in callback parsers, the JSON models with their lenient decoding, the error model, the API client with every mobile endpoint, and the text formatting helpers. It has no UI, and the only thing it stores is the snapshot cache: JSON files, one directory per user, under a directory the app hands it. +- `app/` is the Android application, `so.cap.mobile`. With no saved session it opens on the sign-in screen, under `features/auth/`: an emailed code, or Google through the browser, which returns to the app at `cap://auth`. With one it opens on the tab shell: Caps and Analytics pages, which are placeholders for now, a Settings page under `features/settings/` that so far holds the version and Sign out, and a Record action that opens a placeholder full-screen page. `designsystem/` holds the theme and the shared components, and `app/src/debug` adds a gallery activity that shows every one of them. +- `gradle/libs.versions.toml` is the one place versions are pinned. The Gradle wrapper is checked in with its distribution checksum. + +The directory has no `package.json`, so it is not a Bun workspace member and has no Turbo task. Gradle is the only build tool here. + +## Develop + +You need JDK 17 and an Android SDK with the API 37.2 platform (`platforms;android-37.2`). The Android Gradle plugin downloads its default Build Tools, 36.0.0, into the SDK on the first build if the SDK licences have been accepted. + +```sh +export JAVA_HOME=/path/to/jdk-17 +export ANDROID_HOME=$HOME/Library/Android/sdk +``` + +Run the checks from this directory. This is also what CI runs, apart from the debug build: + +```sh +./gradlew spotlessCheck :capkit:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleRelease +``` + +- `:app:testDebugUnitTest` runs the app's JVM unit tests: the toast timing, the image request rules, the thumbnail, the credential vault, the app phases, the sign-in model, the session and library models, the Cap detail model, the player controls, the media request rules, the playback preferences, the backup rules and, for the debug build, the launch arguments. +- `spotlessCheck` checks Kotlin sources and Gradle scripts against ktfmt in the kotlinlang style. `./gradlew spotlessApply` rewrites them. +- Kotlin warnings fail the build in both modules. +- Android Lint treats warnings as errors. `app/lint-baseline.xml` is empty and should stay empty. + +## capkit tests + +`./gradlew :capkit:test` runs on the JVM, with no emulator and no network beyond loopback. + +- The client tests send real requests with OkHttp to an HTTP server from the JDK bound to 127.0.0.1, and check the method, path, query, headers and body that arrive. There are no mocks and no sleeps. +- The decoding tests read the five JSON fixtures of the iOS tests in place, from `apps/mobile-ios/CapKit/Tests/CapKitTests/Fixtures`, which `capkit/build.gradle.kts` adds as a test resource directory. The files are not copied, so a change to a fixture reaches both clients, and CI runs the Android job when that directory changes. +- `capkit/src/test/resources/relative-dates.txt` is relative-date text recorded from Swift's formatter for the en_US locale. The formatting tests compare against it, because the JVM has no formatter that produces the same wording. + +Any decision about where an HTTP request may go, or which URL may carry the API key, is made with OkHttp's own URL parser, the one that sends the request. Load a URL with OkHttp, or load the form `SafeUrl.media` returns, so that the loader and the check read the same host. + +## Run on an emulator + +```sh +adb install -r app/build/outputs/apk/debug/app-debug.apk +adb shell am start -n so.cap.mobile.debug/so.cap.mobile.MainActivity +``` + +Debug builds read two launch extras, the Android form of the iOS app's `CAP_API_BASE_URL` and `CAP_DEBUG_SESSION`, so the app can be driven against the fixture server of the iOS app with no real account: + +```sh +python3 ../mobile-ios/Fixtures/server.py 4310 +adb reverse tcp:4310 tcp:4310 +adb shell am start -S -n so.cap.mobile.debug/so.cap.mobile.MainActivity \ + --es capApiBaseUrl http://localhost:4310 \ + --es capDebugSession 0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie +``` + +- `capApiBaseUrl` points the app at another server until the process ends: any https origin, or http on a local development host. It is read when `MainActivity` is created, so pass `-S` to start from a stopped app. +- `capDebugSession` is `:` and saves that session before the first screen, only when the server is a local development host. Leave it out to reach the sign-in screen; on the fixture any email signs in with the code 123456. +- Both are read by code in `app/src/debug` only. A release build ignores them. + +Debug builds also carry a component gallery. `section` is optional and takes one of `foundations`, `controls`, `panels`, `buttons`, `text`, `badges`, `toasts`, `images`, `thumbnails`, `emptystates` or `skeletons`; `theme` takes `light` or `dark` and `fontScale` a number, and both default to the system setting. The gallery loads its sample images through the real image pipeline from a small HTTP server it runs on the device's loopback address. + +```sh +adb shell am start -n so.cap.mobile.debug/so.cap.mobile.GalleryActivity --es section thumbnails --es theme dark --ef fontScale 2.0 +``` + +The instrumented tests need a running emulator or device. They render every gallery component in light, in dark and at font scale 2.0 and fail if any text is clipped or truncated, they drive the tab shell, and they drive sign-in, sign-out and a rejected session against the fixture server. For those the fixture has to be running and reachable from the device at `http://localhost:4310`, which is what the two commands at the top of this section set up. + +```sh +./gradlew :app:connectedDebugAndroidTest +``` + +If the fixture listens somewhere else, say where: + +```sh +./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.capFixtureUrl=http://localhost:4314 +``` + +## Debug and release builds + +- Debug builds install as `so.cap.mobile.debug`, so a debug and a release build can sit on one device. +- Only debug builds allow HTTP, and only to `localhost` and `127.0.0.1`, through `app/src/debug/res/xml/network_security_config.xml`. Release builds carry no network security config. +- Release builds are unsigned and not shrunk yet. +- minSdk is 29 and targetSdk is 37. compileSdk is 37.2 because Compose 1.13.0 only compiles against API 37.1 or later. +- Backup is switched off (`allowBackup="false"`) and both backup rule files exclude every domain, for cloud backup and for device transfer. The saved session is a file in the no-backup directory, sealed with a key that stays in the Android Keystore, so it is neither copied off the device nor readable on it. + +## Dependencies and licences + +Read from each artefact's published POM on 30 November 2026, and AndroidX Browser's, Media3's and DataStore's on 1 December 2026. + +| Scope | Dependency | Licence | +|---|---|---| +| Shipped in the app | Jetpack Compose (BOM 2026.11.01, Material 3 1.5.0), AndroidX Activity Compose 1.13.0, AndroidX Browser 1.10.0, Navigation 3 1.2.2, kotlinx.coroutines 1.11.0, Coil 3.6.3 (`coil-compose-core`, `coil-network-okhttp`), OkHttp 5.5.1, Media3 1.11.1 (`media3-exoplayer`, `media3-exoplayer-hls`, `media3-datasource-okhttp`, `media3-ui-compose`, `media3-session`), DataStore Preferences core 1.3.0, `capkit` and what they bring in: 180 artefacts on the release runtime classpath. They are AndroidX, Kotlin, kotlinx, Compose Multiplatform, Coil, OkHttp and Okio libraries, plus Accompanist Drawable Painter, JSpecify, JetBrains annotations and Guava | Apache 2.0 for 179 of them; 176 state it in their own POM; Guava 33.3.1-android, `failureaccess` 1.0.2 and the empty `listenablefuture` state none and inherit it from `guava-parent`. `androidx.datastore:datastore-preferences-external-protobuf`, DataStore's repackaged copy of Protocol Buffers, is BSD 3-Clause | +| Shipped in the app | The Cap logo and wordmark on the sign-in screen, converted without loss to WebP from the iOS app's `CapLogoLarge` and `CapWordmark` images | Cap's own artwork, from this repository | +| Shipped in the app | The Google mark on "Continue with Google", the iOS app's `GoogleLogo` image as a vector drawable | From this repository; the mark is a trademark of Google | +| Shipped in the app | Material Symbols icons (Rounded), copied from [google/material-design-icons](https://github.com/google/material-design-icons) as vector drawables in `app/src/main/res/drawable` | Apache 2.0, from that repository's LICENSE file | +| Shipped in the app | Inter 4.1 Regular, Medium and SemiBold, copied unmodified from [rsms/inter](https://github.com/rsms/inter) into `app/src/main/res/font`; its licence is bundled in `app/src/main/assets/fonts/INTER_LICENSE.txt` | SIL Open Font License 1.1, from the release's LICENSE.txt | +| `capkit` | kotlinx.serialization JSON 1.13.0 and the kotlinx-serialization-core it brings in | Apache 2.0 | +| `capkit` | OkHttp 5.5.1 and the Okio 3.18.1 it brings in | Apache 2.0 | +| `capkit` | kotlinx.coroutines core 1.11.0 and the JetBrains annotations 23.0.0 it brings in | Apache 2.0 | +| Tests only | kotlinx.coroutines test 1.11.0 | Apache 2.0 | +| Tests only | JUnit 4.13.2 | Eclipse Public License 1.0 | +| Tests only | Hamcrest core 1.3, brought in by JUnit | New BSD, stated in `hamcrest-parent` | +| Tests only | Compose UI test (`ui-test-junit4` from the BOM), AndroidX Test ext JUnit 1.3.0, runner 1.7.0 and Espresso core 3.7.0, and what they bring in: 15 artefacts that are not in the app, among them JSR 305, Error Prone annotations and `javax.inject` | Apache 2.0 for all 15 | +| Tests only | Hamcrest library 1.3, brought in by Espresso | New BSD, stated in `hamcrest-parent` | +| Build | Android Gradle plugin 9.5.3 | Apache 2.0 | +| Build | Kotlin Gradle plugin, Compose compiler plugin and serialization plugin 2.4.21 | Apache 2.0 | +| Build | Spotless Gradle plugin 8.12.0, ktfmt 0.64 | Apache 2.0 | + +The build plugins' own dependencies were not surveyed; they run on the build machine and are not part of the app. To list what ships: + +```sh +./gradlew -q :app:dependencies --configuration releaseRuntimeClasspath +``` diff --git a/apps/mobile-android/app/build.gradle.kts b/apps/mobile-android/app/build.gradle.kts new file mode 100644 index 00000000000..13e4decc430 --- /dev/null +++ b/apps/mobile-android/app/build.gradle.kts @@ -0,0 +1,78 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +android { + namespace = "so.cap.mobile" + compileSdk { + version = release(37) { minorApiLevel = 2 } + } + + defaultConfig { + applicationId = "so.cap.mobile" + minSdk = 29 + targetSdk = 37 + versionCode = 1 + versionName = "1.0.0" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + debug { + applicationIdSuffix = ".debug" + } + release { + isMinifyEnabled = false + } + } + + buildFeatures { + compose = true + } + + lint { + warningsAsErrors = true + disable += "NewerVersionAvailable" + disable += "GradleDependency" + abortOnError = true + baseline = file("lint-baseline.xml") + } +} + +kotlin { + jvmToolchain(17) + compilerOptions { + allWarningsAsErrors = true + } +} + +dependencies { + implementation(project(":capkit")) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.browser) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.navigation3.runtime) + implementation(libs.androidx.navigation3.ui) + implementation(libs.coil.compose.core) + implementation(libs.coil.network.okhttp) + implementation(libs.datastore.preferences.core) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.media3.datasource.okhttp) + implementation(libs.media3.exoplayer) + implementation(libs.media3.exoplayer.hls) + implementation(libs.media3.session) + implementation(libs.media3.ui.compose) + implementation(libs.okhttp) + + testImplementation(libs.junit) + testImplementation(libs.kotlinx.coroutines.test) + + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.test.espresso.core) + androidTestImplementation(libs.androidx.test.ext.junit) + androidTestImplementation(libs.androidx.test.runner) +} diff --git a/apps/mobile-android/app/lint-baseline.xml b/apps/mobile-android/app/lint-baseline.xml new file mode 100644 index 00000000000..9897205afc2 --- /dev/null +++ b/apps/mobile-android/app/lint-baseline.xml @@ -0,0 +1,4 @@ + + + + diff --git a/apps/mobile-android/app/src/androidTest/AndroidManifest.xml b/apps/mobile-android/app/src/androidTest/AndroidManifest.xml new file mode 100644 index 00000000000..62444260801 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/BrowserSignInTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/BrowserSignInTest.kt new file mode 100644 index 00000000000..4beeec660be --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/BrowserSignInTest.kt @@ -0,0 +1,129 @@ +package so.cap.mobile + +import android.content.Intent +import android.os.ParcelFileDescriptor +import android.view.accessibility.AccessibilityEvent +import androidx.browser.customtabs.CustomTabsClient +import androidx.browser.customtabs.CustomTabsService +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.core.net.toUri +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class BrowserSignInTest { + @get:Rule val compose = createEmptyComposeRule() + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val automation = instrumentation.uiAutomation + private val app = ApplicationProvider.getApplicationContext() + private val fakeBrowser = instrumentation.context.packageName + private var previousBrowser: String? = null + private var scenario: ActivityScenario? = null + + private fun shell(command: String): String = + ParcelFileDescriptor.AutoCloseInputStream(automation.executeShellCommand(command)) + .bufferedReader() + .use { it.readText() } + + private fun defaultBrowser(): String? = + Intent(Intent.ACTION_VIEW, "https://cap.so".toUri()) + .resolveActivity(app.packageManager) + ?.packageName + ?.takeIf { it != "android" } + + private fun makeDefaultBrowser(browser: String) { + shell("cmd role add-role-holder --user 0 $BROWSER_ROLE $browser 0") + } + + @Before + fun makeTheFakeBrowserTheDefault() { + app.services.vault.clear() + previousBrowser = defaultBrowser() + makeDefaultBrowser(fakeBrowser) + assertEquals(fakeBrowser, defaultBrowser()) + } + + @After + fun restoreTheDefaultBrowser() { + try { + scenario?.close() + } finally { + val previous = previousBrowser + if (previous == null) { + shell("cmd role remove-role-holder --user 0 $BROWSER_ROLE $fakeBrowser 0") + } else { + makeDefaultBrowser(previous) + } + app.services.vault.clear() + } + } + + private fun chromeWasOpenedOn(url: String): Boolean = + shell("dumpsys activity activities").lineSequence().any { + "cmp=$CHROME/" in it && "dat=$url" in it + } + + private fun browserOpenedByGoogleSignIn(): CharSequence { + scenario = + ActivityScenario.launch( + Intent(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, "https://cap.so") + ) + val google = compose.onNode(hasText("Continue with Google")) + google.performScrollTo() + return automation + .executeAndWaitForEvent( + { google.performClick() }, + { + it.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && + it.packageName in listOf(CHROME, fakeBrowser) + }, + TIMEOUT_MILLIS, + ) + .packageName + } + + @Test + fun googleSignInOpensChromesAuthTabWhenTheDefaultBrowserHasNone() { + assumeTrue(CustomTabsClient.isAuthTabSupported(app, CHROME)) + + assertEquals(CHROME, browserOpenedByGoogleSignIn()) + assertTrue(chromeWasOpenedOn("https://cap.so/api/mobile/session/request")) + } + + @Test + fun googleSignInOpensTheDefaultBrowserWhenNoBrowserHasAuthTab() { + val customTabsBrowsers = + app.packageManager.queryIntentServices( + Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION), + 0, + ) + assumeTrue( + customTabsBrowsers.none { + CustomTabsClient.isAuthTabSupported(app, it.serviceInfo.packageName) + } + ) + + assertEquals(fakeBrowser, browserOpenedByGoogleSignIn()) + } + + private companion object { + const val CHROME = "com.android.chrome" + const val BROWSER_ROLE = "android.app.role.BROWSER" + const val TIMEOUT_MILLIS = 20_000L + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapDetailTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapDetailTest.kt new file mode 100644 index 00000000000..4427de0f186 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapDetailTest.kt @@ -0,0 +1,245 @@ +package so.cap.mobile + +import android.content.Intent +import android.net.Uri +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup +import androidx.compose.ui.test.IdlingResource +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import androidx.lifecycle.ViewModelProvider +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import kotlinx.coroutines.Job +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.mobile.app.SessionHolder +import so.cap.mobile.features.cap.CapDetailModel +import so.cap.mobile.features.cap.CapDetailModels +import so.cap.mobile.features.cap.CapPlayer + +@RunWith(AndroidJUnit4::class) +class CapDetailTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val relay = + FixtureRelay( + InstrumentationRegistry.getArguments().getString("capFixtureUrl") + ?: "http://localhost:4310" + ) + private val richie = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie" + + private var scenario: ActivityScenario? = null + private lateinit var models: CapDetailModels + private lateinit var sessions: SessionHolder + + @Before + fun forgetEverything() { + app.services.vault.clear() + runBlocking { + app.services.cache.removeAll() + app.services.playback.setSpeed(1f) + app.services.playback.setCaptionsEnabled(true) + } + } + + @After + fun closeTheApp() { + scenario?.close() + relay.close() + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + private fun open(link: String) { + scenario?.close() + scenario = + ActivityScenario.launch( + Intent(Intent.ACTION_VIEW, Uri.parse(link)) + .setClass(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, relay.origin) + .putExtra(LaunchArguments.DEBUG_SESSION, richie) + ) + .onActivity { + models = ViewModelProvider(it)[CapDetailModels::class.java] + sessions = ViewModelProvider(it)[SessionHolder::class.java] + } + compose.waitForIdle() + } + + private fun await(signal: () -> Boolean) { + val resource = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signal() + } + compose.registerIdlingResource(resource) + try { + compose.waitForIdle() + } finally { + compose.unregisterIdlingResource(resource) + } + } + + private fun model(route: Route.Cap): CapDetailModel { + await { sessions.session != null } + lateinit var model: CapDetailModel + checkNotNull(scenario).onActivity { + model = models.model(route, checkNotNull(sessions.session)) + } + return model + } + + private fun player(route: Route.Cap): CapPlayer { + await { models.player(route)?.duration != null } + return checkNotNull(models.player(route)) + } + + @Test + fun playAndPause() { + open("cap://s/cap_stress") + val player = player(Route.Cap("cap_stress")) + + compose.onNode(hasContentDescription("Play")).performClick() + await { player.isPlaying } + await { !player.controls.visible } + compose.onNode(hasContentDescription("Video")).performClick() + compose.mainClock.advanceTimeBy(ViewConfiguration.getDoubleTapTimeout().toLong()) + compose.onNode(hasContentDescription("Pause")).performClick() + await { !player.isPlaying } + + compose.onNode(hasContentDescription("Play")).assertIsDisplayed() + } + + @Test + fun theDesignedPlaybackChromeIsVisible() { + open("cap://s/cap_stress") + player(Route.Cap("cap_stress")) + + compose.onNode(hasContentDescription("Play")).assertIsDisplayed() + compose.onNode(hasText("of 3:00")).assertIsDisplayed() + compose.onNode(hasContentDescription("Playback speed 1×")).assertIsDisplayed() + compose.onNode(hasContentDescription("Playback position")).assertIsDisplayed() + compose.onNode(hasText("Share")).assertIsDisplayed() + } + + @Test + fun aChosenSpeedIsKeptAfterTheAppIsOpenedAgain() { + val route = Route.Cap("cap_london") + open("cap://s/cap_london") + player(route) + + compose.onNode(hasContentDescription("Playback speed 1×")).performClick() + compose.onNode(hasText("1.5×")).performClick() + await { runBlocking { app.services.playback.speed() } == 1.5f } + open("cap://s/cap_london") + + assertEquals(1.5f, player(route).rate) + compose.onNode(hasContentDescription("Playback speed 1.5×")).assertIsDisplayed() + } + + @Test + fun aWrongPasswordSaysSoAndTheRightOneUnlocks() { + open("cap://s/cap_locked") + val model = model(Route.Cap("cap_locked")) + await { model.content == CapDetailModel.Content.Locked } + val field = compose.onNode(hasContentDescription("Password") and hasSetTextAction()) + + field.performTextInput("nope") + compose.onNode(hasText("Watch Cap")).performClick() + await { !model.isUnlocking } + compose + .onNode(hasContentDescription("Error: That password didn't work.")) + .assertIsDisplayed() + + field.performTextReplacement("letmein") + compose.onNode(hasText("Watch Cap")).performClick() + await { model.content is CapDetailModel.Content.Loaded } + + compose.onNode(hasText("Board update (password protected)")).assertIsDisplayed() + } + + private fun screenKeptOn(): Boolean { + compose.waitForIdle() + var on = false + checkNotNull(scenario).onActivity { on = it.window.decorView.keepsScreenOn() } + return on + } + + private fun View.keepsScreenOn(): Boolean = + keepScreenOn || + (this is ViewGroup && (0 until childCount).any { getChildAt(it).keepsScreenOn() }) + + @Test + fun theScreenStaysOnOnlyWhileAVideoPlays() { + open("cap://s/cap_stress") + val player = player(Route.Cap("cap_stress")) + assertFalse(screenKeptOn()) + + compose.onNode(hasContentDescription("Play")).performClick() + await { player.isPlaying } + assertTrue(screenKeptOn()) + + await { !player.controls.visible } + compose.onNode(hasContentDescription("Video")).performClick() + compose.mainClock.advanceTimeBy(ViewConfiguration.getDoubleTapTimeout().toLong()) + compose.onNode(hasContentDescription("Pause")).performClick() + await { !player.isPlaying } + assertFalse(screenKeptOn()) + + compose.onNode(hasContentDescription("Play")).performClick() + await { player.isPlaying } + assertTrue(screenKeptOn()) + compose.onNode(hasContentDescription("Back")).performClick() + await { models.player(Route.Cap("cap_stress")) == null } + + assertFalse(screenKeptOn()) + } + + @Test + fun aRefreshAfterTheVideoFailsPlaysItAgain() { + val route = Route.Cap("cap_stress") + open("cap://s/cap_stress") + val failed = player(route) + val model = model(route) + checkNotNull(scenario).onActivity { model.reportPlaybackFailure() } + compose.onNode(hasText("This video can't play right now.")).assertIsDisplayed() + + lateinit var refresh: Job + checkNotNull(scenario).onActivity { refresh = model.refresh() } + runBlocking { refresh.join() } + assertFalse(model.playbackFailed) + await { models.player(route).let { it != null && it !== failed && it.duration != null } } + + compose.onNode(hasContentDescription("Play")).performClick() + await { checkNotNull(models.player(route)).isPlaying } + compose.onNode(hasText("This video can't play right now.")).assertDoesNotExist() + } + + @Test + fun aShareLinkWithATimeOpensTheCapThere() { + open("cap://s/cap_stress?t=30") + val player = player(Route.Cap("cap_stress", startTime = 30.0)) + + await { player.currentTime >= 30.0 } + + assertTrue(player.currentTime < 40.0) + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapMenuTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapMenuTest.kt new file mode 100644 index 00000000000..7174252cb28 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapMenuTest.kt @@ -0,0 +1,337 @@ +package so.cap.mobile + +import android.content.ContentUris +import android.content.Intent +import android.net.Uri +import android.provider.MediaStore +import androidx.compose.ui.test.IdlingResource +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.lifecycleScope +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.mobile.app.LibraryModel +import so.cap.mobile.app.SessionHolder +import so.cap.mobile.features.cap.CapDetailModel +import so.cap.mobile.features.cap.CapDetailModels + +@RunWith(AndroidJUnit4::class) +class CapMenuTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val relay = + FixtureRelay( + InstrumentationRegistry.getArguments().getString("capFixtureUrl") + ?: "http://localhost:4310" + ) + private val richie = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie" + private val shownToasts = CopyOnWriteArrayList() + private var seenToasts = 0 + + private var scenario: ActivityScenario? = null + private var keyboard: KeyboardSettled? = null + private lateinit var models: CapDetailModels + private lateinit var sessions: SessionHolder + + @Before + fun forgetEverything() { + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + @After + fun closeTheApp() { + keyboard?.let(compose::unregisterIdlingResource) + scenario?.close() + relay.close() + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + private fun launch(intent: Intent) { + scenario = + ActivityScenario.launch( + intent + .setClass(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, relay.origin) + .putExtra(LaunchArguments.DEBUG_SESSION, richie) + ) + .onActivity { + models = ViewModelProvider(it)[CapDetailModels::class.java] + sessions = ViewModelProvider(it)[SessionHolder::class.java] + keyboard = KeyboardSettled(it).also(compose::registerIdlingResource) + } + await { sessions.session != null } + checkNotNull(scenario).onActivity { activity -> + val toasts = checkNotNull(sessions.session).toasts + activity.lifecycleScope.launch { + toasts.current.collect { toast -> if (toast != null) shownToasts += toast.message } + } + } + } + + private fun open(id: String): CapDetailModel { + launch(Intent(Intent.ACTION_VIEW, Uri.parse("cap://s/$id"))) + return loaded(Route.Cap(id)) + } + + private fun loaded(route: Route.Cap): CapDetailModel { + lateinit var model: CapDetailModel + checkNotNull(scenario).onActivity { + model = models.model(route, checkNotNull(sessions.session)) + } + await { model.content is CapDetailModel.Content.Loaded } + return model + } + + private fun await(signal: () -> Boolean) { + val resource = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signal() + } + compose.registerIdlingResource(resource) + try { + compose.waitForIdle() + } finally { + compose.unregisterIdlingResource(resource) + } + } + + private fun awaitToast(message: String) { + await { shownToasts.drop(seenToasts).contains(message) } + seenToasts = (seenToasts until shownToasts.size).first { shownToasts[it] == message } + 1 + } + + private fun shareSheetIsOpen(): Boolean = + compose.onAllNodes(hasText("Done")).fetchSemanticsNodes().isNotEmpty() + + private fun labelled(text: String) = hasText(text) + + private fun openShareSheet() { + compose.onNode(labelled("Share") and hasClickAction()).performClick() + compose.onNode(hasText("Done")).assertIsDisplayed() + } + + private fun choose(item: String) { + if (!shareSheetIsOpen()) openShareSheet() + compose.onNode(labelled(item) and hasClickAction()).performClick() + } + + private fun togglePassword() { + if (!shareSheetIsOpen()) openShareSheet() + compose.onNode(hasContentDescription("Password") and hasClickAction()).performClick() + } + + private fun body(request: String) = relay.bodies[request] + + private val passwordFooter = + "Viewers will need this password to watch. " + + "You and your organization can still open it in Cap." + + private val CapDetailModel.cap + get() = checkNotNull(detail).cap + + @Test + fun changingWhoCanViewSaysWhoCanView() { + val model = open("cap_link") + + choose("Anyone with the link") + awaitToast("Anyone with the link can view") + choose("Only people in your organization") + awaitToast("Only your organization's emails can view") + choose("Only you and your team") + awaitToast("Only you and your team can view") + choose("Only people in your organization") + awaitToast("Only your organization's emails can view") + + assertTrue(model.cap.isPublic) + compose.onNode(hasContentDescription("Public")).assertIsDisplayed() + } + + @Test + fun renamingTrimsTheTitleAndKeepsTheFirst255Characters() { + val model = open("cap_london") + val original = model.cap.title + val long = "R".repeat(300) + + choose("Rename") + compose.onNode(hasText("Rename Cap")).assertIsDisplayed() + compose + .onNode(hasContentDescription("Title") and hasSetTextAction()) + .performTextReplacement(" $long ") + compose.onNode(hasText("Save") and hasClickAction()).performClick() + awaitToast("Title updated") + + assertEquals( + """{"title":"${long.take(255)}"}""", + body("PATCH /api/mobile/caps/cap_london/title"), + ) + assertEquals(long.take(255), model.cap.title) + + choose("Rename") + compose + .onNode(hasContentDescription("Title") and hasSetTextAction()) + .performTextReplacement(original) + compose.onNode(hasText("Save") and hasClickAction()).performClick() + awaitToast("Title updated") + compose.onNode(hasText("Done") and hasClickAction()).performClick() + assertEquals(original, model.cap.title) + } + + @Test + fun aPasswordIsSetAndThenRemoved() { + val model = open("cap_london") + + togglePassword() + compose.onNode(hasText("Add password")).assertIsDisplayed() + compose.onNode(hasText(passwordFooter)).assertIsDisplayed() + compose + .onNode(hasContentDescription("Password") and hasSetTextAction()) + .performTextInput("hunter2") + compose.onNode(hasContentDescription("Save") and hasClickAction()).performClick() + awaitToast("Password set") + assertEquals( + """{"password":"hunter2"}""", + body("PATCH /api/mobile/caps/cap_london/password"), + ) + assertTrue(model.cap.isProtected) + compose.onNode(labelled("Change password")).assertIsDisplayed() + + togglePassword() + awaitToast("Password removed") + assertEquals( + """{"password":null}""", + body("PATCH /api/mobile/caps/cap_london/password"), + ) + } + + @Test + fun aPasswordSavedWhileTheScreenIsRecreatedClosesTheSheet() { + val hold = FixtureRelay.Hold() + relay.passwordHold = hold + val model = open("cap_london") + + togglePassword() + compose + .onNode(hasContentDescription("Password") and hasSetTextAction()) + .performTextInput("hunter2") + compose.onNode(hasContentDescription("Save") and hasClickAction()).performClick() + await { hold.isHolding } + checkNotNull(scenario).recreate() + compose.onNode(hasText(passwordFooter)).assertExists() + hold.release() + await { model.cap.isProtected && !model.management.savingPassword } + + compose.onNode(hasText(passwordFooter)).assertDoesNotExist() + } + + @Test + fun deletingClosesThePageAndRemovesTheCapFromTheList() { + launch(Intent(Intent.ACTION_MAIN)) + val session = checkNotNull(sessions.session) + await { + val key = session.currentLibraryKey ?: return@await false + session.library(key).status == LibraryModel.Status.Loaded + } + val title = relay.capTitles.first() + val id = session.library(checkNotNull(session.currentLibraryKey)).caps.first().id + + compose.onNode(hasText(title) and hasClickAction()).performClick() + loaded(Route.Cap(id)) + choose("Delete this Cap") + compose.onNode(hasText("Delete this Cap?")).assertIsDisplayed() + compose.onNode(hasText("Delete Cap")).performClick() + awaitToast("Cap deleted") + + compose.onNode(hasText("Share")).assertDoesNotExist() + compose.onNode(hasText(title) and hasClickAction()).assertDoesNotExist() + assertEquals(1, relay.requests.count { it == "DELETE /api/mobile/caps/$id" }) + } + + @Test + fun aTeamMemberWithDownloadPermissionKeepsDownload() { + open("cap_stress") + + openShareSheet() + + compose.onNode(hasText("Delete this Cap")).assertDoesNotExist() + compose.onNode(hasText("Download to this phone") and hasClickAction()).assertIsDisplayed() + } + + @Test + fun aSavedCapIsAddedToTheDevicesVideos() { + open("cap_london") + val resolver = app.contentResolver + val videos = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) + val where = + "${MediaStore.Video.Media.DISPLAY_NAME} = ? AND " + + "${MediaStore.Video.Media.RELATIVE_PATH} LIKE ?" + val arguments = arrayOf("cap_london.mp4", "Movies/Cap%") + fun saved(): List = + resolver + .query(videos, arrayOf(MediaStore.Video.Media._ID), where, arguments, null) + ?.use { cursor -> buildList { while (cursor.moveToNext()) add(cursor.getLong(0)) } } + .orEmpty() + saved().forEach { resolver.delete(ContentUris.withAppendedId(videos, it), null, null) } + + choose("Download to this phone") + awaitToast("Saved to your device") + + val added = saved() + assertEquals(1, added.size) + added.forEach { resolver.delete(ContentUris.withAppendedId(videos, it), null, null) } + } + + @Test + fun reportingSomeoneElsesCapSendsTheReason() { + open("cap_stress") + + openShareSheet() + compose.onNode(hasText("Rename")).assertDoesNotExist() + compose.onNode(hasText("Delete this Cap")).assertDoesNotExist() + compose.onNode(labelled("Report Cap") and hasClickAction()).performClick() + compose.onNode(hasText("Why are you reporting this Cap?")).assertIsDisplayed() + compose.onNode(hasText("Copyright infringement") and hasClickAction()).performClick() + awaitToast("Thanks. Cap Support will review this.") + + assertEquals("""{"reason":"copyright"}""", body("POST /api/mobile/caps/cap_stress/report")) + } + + @Test + fun blockingTheOwnerClosesThePage() { + open("cap_stress") + + choose("Block owner") + compose.onNode(hasText("Block Samantha Rivera-Oyelaran de la Cruz?")).assertIsDisplayed() + compose + .onNode(hasText("You won't see their Caps or comments in Cap for Android.")) + .assertIsDisplayed() + compose.onNode(hasText("Block") and hasClickAction()).performClick() + awaitToast("User blocked") + + assertEquals("""{"userId":"user_sam"}""", body("POST /api/mobile/user/blocks")) + compose.onNode(hasText("Share")).assertDoesNotExist() + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapSocialTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapSocialTest.kt new file mode 100644 index 00000000000..a10c062e106 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/CapSocialTest.kt @@ -0,0 +1,263 @@ +package so.cap.mobile + +import android.content.Intent +import android.net.Uri +import androidx.compose.ui.test.IdlingResource +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasScrollToNodeAction +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.longClick +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollToNode +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTouchInput +import androidx.lifecycle.ViewModelProvider +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.espresso.Espresso +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import java.util.UUID +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.mobile.app.SessionHolder +import so.cap.mobile.features.cap.CapDetailModel +import so.cap.mobile.features.cap.CapDetailModels + +@RunWith(AndroidJUnit4::class) +class CapSocialTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val relay = + FixtureRelay( + InstrumentationRegistry.getArguments().getString("capFixtureUrl") + ?: "http://localhost:4310" + ) + private val richie = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie" + + private var scenario: ActivityScenario? = null + private lateinit var models: CapDetailModels + private lateinit var sessions: SessionHolder + + @Before + fun forgetEverything() { + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + @After + fun closeTheApp() { + scenario?.close() + relay.close() + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + private fun open(id: String): CapDetailModel { + scenario = + ActivityScenario.launch( + Intent(Intent.ACTION_VIEW, Uri.parse("cap://s/$id")) + .setClass(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, relay.origin) + .putExtra(LaunchArguments.DEBUG_SESSION, richie) + ) + .onActivity { + models = ViewModelProvider(it)[CapDetailModels::class.java] + sessions = ViewModelProvider(it)[SessionHolder::class.java] + } + await { sessions.session != null } + lateinit var model: CapDetailModel + checkNotNull(scenario).onActivity { + model = models.model(Route.Cap(id), checkNotNull(sessions.session)) + } + await { model.detail != null } + return model + } + + private fun await(signal: () -> Boolean) { + val resource = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signal() + } + compose.registerIdlingResource(resource) + try { + compose.waitForIdle() + } finally { + compose.unregisterIdlingResource(resource) + } + } + + private fun reveal(matcher: SemanticsMatcher) { + compose.onNode(hasScrollToNodeAction()).performScrollToNode(matcher) + } + + private fun newestFirst() { + reveal(hasContentDescription("Sort comments, Oldest first")) + compose.onNode(hasContentDescription("Sort comments, Oldest first")).performClick() + compose.onNode(hasText("Newest first")).performClick() + } + + private fun send(text: String) { + compose.onNode(hasSetTextAction()).performTextInput(text) + Espresso.closeSoftKeyboard() + compose.onNode(hasContentDescription("Send comment")).performClick() + } + + @Test + fun aPostedCommentShowsAsSendingUntilTheServerHasIt() { + val hold = FixtureRelay.Hold() + relay.commentHold = hold + val model = open("cap_london") + newestFirst() + val text = "Posted from the device test ${UUID.randomUUID()}" + + send(text) + await { hold.isHolding } + reveal(hasText(text) and hasText("Sending…")) + compose.onNode(hasText(text) and hasText("Sending…")).assertIsDisplayed() + + hold.release() + await { model.pendingCommentIds.isEmpty() && !model.isSendingComment } + reveal(hasText(text) and hasText("Just now")) + compose.onNode(hasText(text) and hasText("Just now")).assertIsDisplayed() + assertTrue(relay.bodies.values.any { text in it }) + } + + @Test + fun aReplyJoinsTheThreadItAnswers() { + val model = open("cap_london") + val text = "Reply from the device test ${UUID.randomUUID()}" + + reveal(hasContentDescription("Reply to Ana Ortiz")) + compose.onNode(hasContentDescription("Reply to Ana Ortiz")).performClick() + compose.onNode(hasText("Replying to Ana Ortiz")).assertIsDisplayed() + compose.onNode(hasSetTextAction()).performTextInput(text) + Espresso.closeSoftKeyboard() + compose.onNode(hasContentDescription("Send reply")).performClick() + await { model.pendingCommentIds.isEmpty() && !model.isSendingComment } + + val thread = model.threads.single { it.id == "c3" } + assertTrue(thread.replies.any { it.content == text }) + assertTrue(relay.bodies.values.any { text in it && "\"parentCommentId\":\"c3\"" in it }) + val more = compose.onAllNodes(hasText("more repl", substring = true)).fetchSemanticsNodes() + if (more.isNotEmpty()) { + reveal(hasText("more repl", substring = true)) + compose.onNode(hasText("more repl", substring = true)).performClick() + } + reveal(hasText(text)) + compose.onNode(hasText(text)).assertIsDisplayed() + } + + @Test + fun aLinkToALateReplyShowsItAndKeepsItsThreadOpen() { + relay.extraReplies = mapOf("c3" to 8) + val model = open("cap_london") + await { model.threads.single { it.id == "c3" }.replies.any { it.id == "relay_reply_8" } } + + checkNotNull(scenario).onActivity { model.highlightedCommentId = "relay_reply_8" } + compose.mainClock.advanceTimeUntil(HIGHLIGHT_TIMEOUT_MILLIS) { + model.highlightedCommentId == null + } + + compose.onNode(hasText("Relay reply 8")).assertIsDisplayed() + } + + @Test + fun deletingYourCommentAsksFirst() { + val model = open("cap_london") + newestFirst() + val text = "Delete me ${UUID.randomUUID()}" + send(text) + await { model.pendingCommentIds.isEmpty() && !model.isSendingComment } + + reveal(hasText(text)) + compose.onNode(hasText(text)).performTouchInput { longClick() } + compose.onNode(hasText("Delete")).performClick() + compose.onNode(hasText("Delete this comment?")).assertIsDisplayed() + compose.onNode(hasText("Replies to it will be hidden too.")).assertIsDisplayed() + compose.onNode(hasText("Delete") and hasClickAction()).performClick() + await { model.threads.none { it.root.content == text } } + + compose.onNode(hasText(text)).assertDoesNotExist() + assertTrue(relay.requests.any { it.startsWith("DELETE /api/mobile/comments/") }) + } + + @Test + fun reactingSendsTheReactionAndShowsItAtOnce() { + val model = open("cap_london") + val before = model.reactionCounts.firstOrNull { it.emoji == "😮" }?.count ?: 0 + + reveal(hasContentDescription("React with 😮")) + compose.onNode(hasContentDescription("React with 😮")).performClick() + await { model.pendingCommentIds.isEmpty() } + + assertEquals(before + 1, model.reactionCounts.single { it.emoji == "😮" }.count) + assertTrue( + relay.requests.any { it.startsWith("POST /api/mobile/caps/cap_london/reactions") } + ) + assertTrue(relay.bodies.values.any { "😮" in it }) + } + + @Test + fun searchingTheTranscriptKeepsOnlyMatchingLines() { + val model = open("cap_london") + + reveal(hasText("Transcript") and hasClickAction()) + compose.onNode(hasText("Transcript") and hasClickAction()).performClick() + await { model.transcript is CapDetailModel.Transcript.Loaded } + reveal(hasText("The first thing you'll notice is the timeline.")) + compose.onNode(hasSetTextAction()).performTextInput("ZOOM handles") + Espresso.closeSoftKeyboard() + + reveal(hasText("Next up are the new zoom handles.")) + compose.onNode(hasText("Next up are the new zoom handles.")).assertIsDisplayed() + compose + .onNode(hasText("The first thing you'll notice is the timeline.")) + .assertDoesNotExist() + } + + @Test + fun tappingAChapterPlaysFromIt() { + open("cap_stress") + val route = Route.Cap("cap_stress") + await { models.player(route)?.duration != null } + val player = checkNotNull(models.player(route)) + + reveal(hasText("Summary") and hasClickAction()) + compose.onNode(hasText("Summary") and hasClickAction()).performClick() + reveal(hasContentDescription("Billing, at 0:48")) + compose.onNode(hasContentDescription("Billing, at 0:48")).performClick() + + await { player.currentTime >= 48.0 } + assertTrue(player.currentTime < 50.0) + } + + @Test + fun aFailedSendPutsTheDraftBack() { + relay.refusesComments = true + val model = open("cap_london") + val text = "Never sent ${UUID.randomUUID()}" + + send(text) + await { !model.isSendingComment } + + assertEquals(text, model.draft) + assertTrue(model.pendingCommentIds.isEmpty()) + compose.onNode(hasSetTextAction() and hasText(text)).assertIsDisplayed() + } +} + +private const val HIGHLIGHT_TIMEOUT_MILLIS = 10_000L diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/DesignSystemReviewTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/DesignSystemReviewTest.kt new file mode 100644 index 00000000000..e79242d3309 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/DesignSystemReviewTest.kt @@ -0,0 +1,176 @@ +package so.cap.mobile + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.click +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isSelected +import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe +import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import so.cap.mobile.designsystem.CapColorSwatch +import so.cap.mobile.designsystem.CapEditorToolItem +import so.cap.mobile.designsystem.CapScopeSegmentedControl +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapTickSlider + +class DesignSystemReviewTest { + @get:Rule val compose = createAndroidComposeRule() + + @Test + fun selectableControlsExposeTheirSelectedState() { + compose.setContent { + CapTheme { + Column { + CapScopeSegmentedControl( + options = listOf("Yours", "Team", "Shared"), + selectedIndex = 1, + onSelected = {}, + ) + CapColorSwatch("Blue", selected = true, onClick = {}) + CapEditorToolItem("Arrow", selected = true, onClick = {}) + } + } + } + + compose.onNode(hasText("Team") and isSelected()).assertIsSelected() + compose + .onNode( + hasText("Team") and SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab) + ) + .assertExists() + compose + .onNode( + hasText("Yours") and + SemanticsMatcher.expectValue(SemanticsProperties.Selected, false) + ) + .assertExists() + compose.onNode(hasContentDescription("Blue") and isSelected()).assertIsSelected() + compose.onNode(hasText("Arrow") and isSelected()).assertIsSelected() + } + + @Test + fun verticalSwipeOverATickSliderScrollsItsParentWithoutChangingTheValue() { + val sliderValue = mutableIntStateOf(6) + lateinit var scrollState: androidx.compose.foundation.ScrollState + compose.setContent { + scrollState = rememberScrollState() + CapTheme { + Column(Modifier.fillMaxSize().verticalScroll(scrollState)) { + Spacer(Modifier.height(320.dp)) + CapTickSlider( + label = "Width", + value = sliderValue.intValue, + range = 0..20, + onValueChange = { sliderValue.intValue = it }, + ) + Spacer(Modifier.height(1000.dp)) + } + } + } + + val slider = + compose.onNode(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)) + slider.performTouchInput { + swipe(center, center + Offset(0f, -320f), durationMillis = 300) + } + + compose.runOnIdle { + assertTrue("the parent scrolls", scrollState.value > 0) + assertEquals(6, sliderValue.intValue) + } + } + + @Test + fun tappingATickSliderSetsItsValue() { + val sliderValue = mutableIntStateOf(6) + compose.setContent { + CapTheme { + CapTickSlider( + label = "Width", + value = sliderValue.intValue, + range = 0..20, + onValueChange = { sliderValue.intValue = it }, + ) + } + } + + compose + .onNode(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)) + .performTouchInput { + click(Offset(visibleSize.width * 0.8f, visibleSize.height / 2f)) + } + + compose.runOnIdle { assertEquals(16, sliderValue.intValue) } + } + + @Test + fun draggingATickSliderHorizontallySetsItsValue() { + val sliderValue = mutableIntStateOf(6) + compose.setContent { + CapTheme { + CapTickSlider( + label = "Width", + value = sliderValue.intValue, + range = 0..20, + onValueChange = { sliderValue.intValue = it }, + ) + } + } + + compose + .onNode(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)) + .performTouchInput { + swipe(center, center + Offset(visibleSize.width * 0.3f, 0f), durationMillis = 300) + } + + compose.runOnIdle { assertTrue(sliderValue.intValue > 6) } + } + + @Test + fun annotationSwatchesStayInsideAThreeSixtyDpGallery() { + compose.setContent { + CapTheme(darkTheme = true) { + Box(Modifier.width(328.dp).testTag("samples")) { PanelSamples() } + } + } + + val panel = compose.onNodeWithTag("samples").fetchSemanticsNode().boundsInRoot + val density = + InstrumentationRegistry.getInstrumentation() + .targetContext + .resources + .displayMetrics + .density + val fullWidth = 44f * density - 1f + for (label in listOf("Blue", "Sky", "Yellow", "Orange", "Green", "White", "Black")) { + val node = compose.onNode(hasContentDescription(label)).fetchSemanticsNode() + val bounds = node.boundsInRoot + assertTrue("$label starts outside the panel", bounds.left >= panel.left - 0.5f) + assertTrue("$label ends outside the panel", bounds.right <= panel.right + 0.5f) + assertTrue("$label is squeezed to ${node.size.width}px", node.size.width >= fullWidth) + } + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FakeBrowserActivity.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FakeBrowserActivity.kt new file mode 100644 index 00000000000..0ece270292b --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FakeBrowserActivity.kt @@ -0,0 +1,5 @@ +package so.cap.mobile + +import android.app.Activity + +class FakeBrowserActivity : Activity() diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FixtureRelay.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FixtureRelay.kt new file mode 100644 index 00000000000..9c15cce7669 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/FixtureRelay.kt @@ -0,0 +1,314 @@ +package so.cap.mobile + +import java.io.Closeable +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import kotlin.concurrent.thread +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject + +class FixtureRelay(private val fixture: String) : Closeable { + class Hold { + private val gate = CountDownLatch(1) + + @Volatile + var arrived = false + private set + + val isHolding: Boolean + get() = arrived && gate.count > 0 + + fun release() = gate.countDown() + + internal fun await() { + arrived = true + gate.await() + } + } + + private class Reply( + val status: Int, + val type: String, + val length: Long, + val write: (OutputStream) -> Unit, + val close: () -> Unit = {}, + ) { + constructor( + status: Int, + type: String, + body: ByteArray, + ) : this(status, type, body.size.toLong(), { it.write(body) }) + } + + private val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")) + private val client = OkHttpClient() + + val requests = CopyOnWriteArrayList() + val bodies = ConcurrentHashMap() + + @Volatile var pageSize: Int? = null + + @Volatile var refusal: Hold? = null + + @Volatile var folderHold: Hold? = null + + @Volatile var createsFolders = false + + @Volatile var commentHold: Hold? = null + + @Volatile var passwordHold: Hold? = null + + @Volatile var refusesComments = false + + @Volatile var extraReplies: Map = emptyMap() + + @Volatile var listsFolders = true + + @Volatile var emptyFirstPage = false + + @Volatile var emptySpaceId: String? = null + + @Volatile var refusesLaterPages = false + + @Volatile + var capTitles: List = emptyList() + private set + + val origin: String + get() = "http://127.0.0.1:${socket.localPort}" + + init { + thread(isDaemon = true) { + while (true) { + val connection = + try { + socket.accept() + } catch (_: SocketException) { + return@thread + } + thread(isDaemon = true) { + try { + connection.use(::serve) + } catch (_: IOException) { + return@thread + } + } + } + } + } + + private fun InputStream.line(): String { + val line = StringBuilder() + while (true) { + val byte = read() + if (byte < 0 || byte == '\n'.code) return line.toString().trimEnd('\r') + line.append(byte.toChar()) + } + } + + private fun serve(connection: Socket) { + val input = connection.getInputStream().buffered() + val request = input.line().split(' ') + if (request.size < 2) return + val (method, target) = request + val headers = generateSequence { + input.line().takeIf { it.isNotEmpty() } + } + .associate { it.substringBefore(':').lowercase() to it.substringAfter(':').trim() } + val body = ByteArray(headers["content-length"]?.toIntOrNull() ?: 0) + var read = 0 + while (read < body.size) { + val count = input.read(body, read, body.size - read) + if (count < 0) break + read += count + } + requests += "$method $target" + if (body.isNotEmpty()) bodies["$method $target"] = String(body) + val reply = reply(method, target, headers, body) + val length = if (reply.length >= 0) "Content-Length: ${reply.length}\r\n" else "" + val head = + "HTTP/1.1 ${reply.status} \r\nContent-Type: ${reply.type}\r\n" + + "${length}Connection: close\r\n\r\n" + try { + val output = connection.getOutputStream() + output.write(head.toByteArray(Charsets.ISO_8859_1)) + reply.write(output) + output.flush() + } finally { + reply.close() + } + } + + private fun reply( + method: String, + target: String, + headers: Map, + body: ByteArray, + ): Reply { + val refused = refusal + if (refused != null && method == "PATCH" && target.endsWith("/sharing")) { + refused.await() + return Reply(500, "application/json", "{}".toByteArray()) + } + if (method == "POST" && target == "/api/mobile/folders") folderHold?.await() + if (method == "POST" && target.endsWith("/comments")) { + commentHold?.await() + if (refusesComments) return Reply(500, "application/json", "{}".toByteArray()) + } + if (createsFolders && method == "POST" && target == "/api/mobile/folders") { + val asked = JSONObject(String(body)) + val folder = + JSONObject() + .put("id", "folder_created") + .put("name", asked.getString("name")) + .put("color", asked.getString("color")) + .put("parentId", JSONObject.NULL) + .put("videoCount", 0) + return Reply(200, "application/json", folder.toString().toByteArray()) + } + if (method == "POST" && target == "/api/mobile/user/blocks") return success() + if (method == "POST" && target.matches(Regex("/api/mobile/caps/[A-Za-z0-9_-]+/report"))) { + return success() + } + if (method == "PATCH" && target.endsWith("/password")) { + passwordHold?.await() + val id = target.removePrefix("/api/mobile/caps/").removeSuffix("/password") + val detail = + Request.Builder() + .url("$fixture/api/mobile/caps/$id") + .header("authorization", headers["authorization"].orEmpty()) + .build() + val cap = + client.newCall(detail).execute().use { + JSONObject(it.body.string()).getJSONObject("cap") + } + cap.put("protected", !JSONObject(String(body)).isNull("password")) + return Reply( + 200, + "application/json", + cap.toString().replace(fixture, origin).toByteArray(), + ) + } + if (refusesLaterPages && isRootList(method, target) && pageOf(target) > 1) { + return Reply(500, "application/json", "{}".toByteArray()) + } + val forwarded = + Request.Builder() + .url(fixture + target) + .method(method, if (method == "GET") null else body.toRequestBody()) + for (name in listOf("authorization", "content-type", "user-agent", "x-cap-video-access")) { + headers[name]?.let { forwarded.header(name, it) } + } + val response = client.newCall(forwarded.build()).execute() + val type = response.header("Content-Type") ?: "application/octet-stream" + if (!type.startsWith("application/json")) { + return Reply( + response.code, + type, + response.body.contentLength(), + { response.body.byteStream().copyTo(it) }, + response::close, + ) + } + return response.use { + val text = response.body.string().replace(fixture, origin) + val isDetail = + method == "GET" && + target.startsWith("/api/mobile/caps/") && + target.substringBefore('?').count { it == '/' } == 4 + val body = + when { + isRootList(method, target) -> paged(text, target) + isDetail && extraReplies.isNotEmpty() -> withReplies(text) + else -> text + } + Reply(response.code, type, body.toByteArray()) + } + } + + private fun withReplies(detail: String): String { + val json = JSONObject(detail) + val comments = json.optJSONArray("comments") ?: return detail + val all = (0 until comments.length()).map(comments::getJSONObject) + for ((parentId, count) in extraReplies) { + val parent = all.firstOrNull { it.getString("id") == parentId } ?: continue + for (number in 1..count) { + val created = "2030-01-01T00:00:%02d.000Z".format(number) + comments.put( + JSONObject(parent.toString()) + .put("id", "relay_reply_$number") + .put("content", "Relay reply $number") + .put("timestamp", JSONObject.NULL) + .put("parentCommentId", parentId) + .put("createdAt", created) + .put("updatedAt", created) + ) + } + } + return json.toString() + } + + private fun success() = Reply(200, "application/json", """{"success":true}""".toByteArray()) + + private fun isRootList(method: String, target: String) = + method == "GET" && + target.substringBefore('?') == "/api/mobile/caps" && + "folderId=" !in target + + private fun pageOf(target: String) = + target + .substringAfter('?', "") + .split('&') + .firstOrNull { it.startsWith("page=") } + ?.substringAfter('=') + ?.toIntOrNull() ?: 1 + + private fun paged(list: String, target: String): String { + val json = JSONObject(list) + if (!listsFolders) json.put("folders", JSONArray()) + val caps = json.getJSONArray("caps") + val all = (0 until caps.length()).map(caps::getJSONObject) + capTitles = all.map { it.getString("title") } + val page = pageOf(target) + val emptySpace = emptySpaceId + if (emptySpace != null && "spaceId=$emptySpace" in target) { + json.put("folders", JSONArray()) + json.put("caps", JSONArray()) + json.put("page", page) + json.put("total", 0) + json.put("collectionTotal", 0) + json.put("hasMore", false) + return json.toString() + } + if (emptyFirstPage && page == 1) { + json.put("caps", JSONArray()) + json.put("hasMore", true) + return json.toString() + } + val size = pageSize ?: return json.toString() + val from = (page - 1) * size + json.put("caps", JSONArray(all.drop(from).take(size))) + json.put("page", page) + json.put("hasMore", from + size < all.size) + return json.toString() + } + + override fun close() { + refusal?.release() + folderHold?.release() + commentHold?.release() + passwordHold?.release() + socket.close() + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryImageServerTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryImageServerTest.kt new file mode 100644 index 00000000000..fd749d6a744 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryImageServerTest.kt @@ -0,0 +1,27 @@ +package so.cap.mobile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import java.net.Socket +import java.net.URI +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class GalleryImageServerTest { + @Test + fun keepsServingAfterClientsResetTheirConnections() { + GalleryImageServer().use { server -> + val port = URI(server.origin).port + repeat(20) { Socket("127.0.0.1", port).apply { setSoLinger(true, 0) }.close() } + Socket("127.0.0.1", port).use { socket -> + socket.soTimeout = 5_000 + socket + .getOutputStream() + .write("GET / HTTP/1.1\r\n\r\n".toByteArray(Charsets.ISO_8859_1)) + val status = socket.getInputStream().bufferedReader(Charsets.ISO_8859_1).readLine() + assertEquals("HTTP/1.1 200 OK", status) + } + } + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryTest.kt new file mode 100644 index 00000000000..1d7f300395d --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/GalleryTest.kt @@ -0,0 +1,123 @@ +package so.cap.mobile + +import android.content.Intent +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsNode +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.SemanticsNodeInteraction +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasScrollAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.text.TextLayoutResult +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlin.math.abs +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class GalleryTest { + @get:Rule val compose = createEmptyComposeRule() + + private val hasLabel = + SemanticsMatcher("has text or a content description") { node -> + SemanticsProperties.Text in node.config || + SemanticsProperties.ContentDescription in node.config + } + + @Test + fun everyComponentRendersInLight() = everyComponentRenders(theme = "light", fontScale = 1f) + + @Test fun everyComponentRendersInDark() = everyComponentRenders(theme = "dark", fontScale = 1f) + + @Test + fun everyComponentRendersAtFontScaleTwo() = + everyComponentRenders(theme = "light", fontScale = 2f) + + private fun everyComponentRenders(theme: String, fontScale: Float) { + val intent = + Intent(ApplicationProvider.getApplicationContext(), GalleryActivity::class.java) + .putExtra(GalleryActivity.EXTRA_THEME, theme) + .putExtra(GalleryActivity.EXTRA_FONT_SCALE, fontScale) + ActivityScenario.launch(intent).use { + for (section in GallerySection.entries) { + compose.onNodeWithTag(section.name).assertExists() + } + + val scrolled = compose.onAllNodes(hasLabel and hasAnyAncestor(hasScrollAction()), true) + val count = scrolled.fetchSemanticsNodes().size + assertTrue("the gallery shows its components", count > GallerySection.entries.size) + for (index in 0 until count) { + scrolled[index].performScrollTo().assertIsNotClipped() + } + + compose.onNode(hasText("Success"), true).performScrollTo().performClick() + compose.onNode(hasText("Link copied"), true).assertIsNotClipped() + } + } + + private fun SemanticsNodeInteraction.assertIsNotClipped() { + assertIsDisplayed() + val node = fetchSemanticsNode() + val name = node.describe() + val visible = node.boundsInRoot + assertTrue("$name is clipped horizontally", abs(visible.width - node.size.width) <= 1f) + assertTrue("$name is clipped vertically", abs(visible.height - node.size.height) <= 1f) + val layouts = mutableListOf() + node.config.getOrNull(SemanticsActions.GetTextLayoutResult)?.action?.invoke(layouts) + // This layout is measured at the node's widest allowed width and always wraps, so its + // didOverflowWidth is true for any label narrower than its row. Text that runs past its + // box without wrapping shows up here as a layout taller than the node. + for (layout in layouts) { + assertFalse("$name loses lines", layout.didOverflowHeight) + val truncated = (0 until layout.lineCount).any(layout::isLineEllipsized) + assertFalse("$name is truncated", truncated) + } + } + + private fun SemanticsNode.describe(): String { + val text = config.getOrNull(SemanticsProperties.Text)?.joinToString { it.text } + val description = config.getOrNull(SemanticsProperties.ContentDescription)?.joinToString() + return "\"${text ?: description}\"" + } + + @Test + fun componentsCarryAccessibilityLabels() { + val intent = + Intent(ApplicationProvider.getApplicationContext(), GalleryActivity::class.java) + ActivityScenario.launch(intent).use { + val labels = + compose + .onAllNodes( + SemanticsMatcher.keyIsDefined(SemanticsProperties.ContentDescription), + true, + ) + .fetchSemanticsNodes() + .flatMap { it.config[SemanticsProperties.ContentDescription] } + val expected = + listOf( + "Continue with Google, loading", + "Error: That code didn't work. Check it and try again.", + "1200 views", + "Duration 12:34", + "Duration 0:42", + "Loading Caps", + ) + assertTrue( + "missing accessibility labels from $labels", + labels.containsAll(expected), + ) + } + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/HomeLayoutTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/HomeLayoutTest.kt new file mode 100644 index 00000000000..d20e2695b74 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/HomeLayoutTest.kt @@ -0,0 +1,133 @@ +package so.cap.mobile + +import androidx.compose.foundation.layout.Column +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.unit.Density +import java.time.Instant +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import so.cap.kit.CapSummary +import so.cap.kit.MemberRole +import so.cap.kit.Organization +import so.cap.kit.Space +import so.cap.kit.SpaceKind +import so.cap.kit.SpacePrivacy +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.features.home.CapRow +import so.cap.mobile.features.home.ScopeBarContent + +class HomeLayoutTest { + @get:Rule val compose = createAndroidComposeRule() + + private val capOrganization = Organization("org_cap", "Cap", null, MemberRole.OWNER) + private val otherOrganization = Organization("org_other", "Other", null, MemberRole.MEMBER) + + private fun space(index: Int) = + Space( + id = "space_$index", + name = "Overflow space $index", + iconUrl = null, + kind = SpaceKind.SPACE, + privacy = SpacePrivacy.PUBLIC, + role = MemberRole.MEMBER, + canManage = true, + hasPassword = false, + ) + + @Test + fun theSelectedSpaceIsScrolledIntoView() { + val spaces = (1..8).map(::space) + compose.setContent { + CapTheme { + ScopeBarContent( + organizations = listOf(capOrganization, otherOrganization), + activeOrganization = capOrganization, + currentOrganizationId = capOrganization.id, + isSwitchingOrganization = false, + spaces = spaces, + selected = LibraryScope.Space("space_8"), + onSelect = {}, + onSwitchOrganization = {}, + ) + } + } + + compose.onNode(hasText("Overflow space 8")).assertIsDisplayed().assertIsSelected() + } + + @Test + fun scopeAndCapRowsGrowWithLargerText() { + val cap = + CapSummary( + id = "cap_large_text", + shareUrl = "https://cap.so/s/cap_large_text", + title = "A Cap with large text", + createdAt = Instant.parse("2026-10-29T14:00:00.000Z"), + updatedAt = Instant.parse("2026-10-29T14:00:00.000Z"), + ownerId = "user_richie", + ownerName = "Richie", + durationSeconds = 61.0, + thumbnailUrl = null, + thumbnailCacheKey = null, + folderId = null, + isPublic = true, + isProtected = false, + viewCount = 3, + commentCount = 1, + reactionCount = 0, + upload = null, + ownedByCurrentUser = true, + ) + compose.setContent { + val density = LocalDensity.current + CompositionLocalProvider( + LocalDensity provides Density(density.density, fontScale = 2f) + ) { + CapTheme { + Column { + ScopeBarContent( + organizations = listOf(capOrganization), + activeOrganization = capOrganization, + currentOrganizationId = capOrganization.id, + isSwitchingOrganization = false, + spaces = listOf(space(1)), + selected = LibraryScope.Personal, + onSelect = {}, + onSwitchOrganization = {}, + modifier = Modifier.testTag("scope-bar"), + ) + CapRow( + cap = cap, + userId = "user_richie", + onClick = {}, + onAction = {}, + modifier = Modifier.testTag("cap-row"), + ) + } + } + } + } + + val density = compose.activity.resources.displayMetrics.density + val scopeHeight = compose.onNodeWithTag("scope-bar").fetchSemanticsNode().size.height + val rowHeight = compose.onNodeWithTag("cap-row").fetchSemanticsNode().size.height + assertTrue( + "scope bar height $scopeHeight did not grow beyond 45dp", + scopeHeight > 45 * density + 1, + ) + assertTrue( + "cap row height $rowHeight did not grow beyond 80dp", + rowHeight > 80 * density + 1, + ) + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/InitialsTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/InitialsTest.kt new file mode 100644 index 00000000000..c0e9fbab701 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/InitialsTest.kt @@ -0,0 +1,19 @@ +package so.cap.mobile + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.mobile.designsystem.firstCharacter +import so.cap.mobile.designsystem.initials + +@RunWith(AndroidJUnit4::class) +class InitialsTest { + @Test + fun keepsAnEmojiSequenceWhole() { + val astronaut = "\uD83D\uDC69\u200D\uD83D\uDE80" + val flag = "\uD83C\uDDEC\uD83C\uDDE7" + assertEquals(astronaut + "A", initials("$astronaut Ada")) + assertEquals(flag, "$flag Team".firstCharacter()) + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/KeyboardSettled.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/KeyboardSettled.kt new file mode 100644 index 00000000000..e8841fe1231 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/KeyboardSettled.kt @@ -0,0 +1,86 @@ +package so.cap.mobile + +import android.app.Activity +import android.content.res.Configuration +import android.os.Build +import android.view.View +import android.view.inputmethod.InputMethodManager +import android.view.inspector.WindowInspector +import androidx.compose.ui.test.IdlingResource +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsAnimationCompat +import androidx.core.view.WindowInsetsCompat + +// The keyboard slides in and out on the system's clock, which the Compose test clock does not wait +// for, and it moves the layout under a pointer and under assertIsDisplayed. Busy while the keyboard +// is animating, and while it has been asked to show or hide and has not started yet. A focused +// field may never show one where a hardware keyboard is attached or no input method is enabled, so +// there only the animations count. +// +// A sheet or a dialog is a window of its own, and the focus of its field, the keyboard's insets +// and the keyboard's animation are reported to that window and not to the activity's. So every +// window of the app is watched: the keyboard has settled when the window that has focus shows it +// for its field, or when that window has no focused field and no window shows a keyboard. A field +// in a window that has lost focus to a sheet or a dialog does not count: the system has hidden its +// keyboard. While no window of the app has focus one is about to take it, and the keyboard can +// follow, so that is busy too: measured on API 37, a sheet's window is there for 0.26 to 0.53 s +// before it has focus. Before API 30 the keyboard's insets are worked out from a window's own +// frame, so a dialog that floats above the keyboard and pans never reports it: measured on API 29, +// the rename dialog's field has focus with the keyboard up and only the activity's window shows it. +// There a keyboard shown by any window of the app counts for the field. +internal class KeyboardSettled(activity: Activity) : IdlingResource { + private val ime = WindowInsetsCompat.Type.ime() + private val canShow = + activity.resources.configuration.keyboard == Configuration.KEYBOARD_NOKEYS && + activity + .getSystemService(InputMethodManager::class.java) + .enabledInputMethodList + .isNotEmpty() + private val animations = mutableMapOf>() + + init { + watch(activity.window.decorView) + } + + private fun watch(window: View) { + if (window in animations) return + val running = mutableSetOf() + animations[window] = running + ViewCompat.setWindowInsetsAnimationCallback( + window, + object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) { + override fun onPrepare(animation: WindowInsetsAnimationCompat) { + if (animation.typeMask and ime != 0) running += animation + } + + override fun onProgress( + insets: WindowInsetsCompat, + runningAnimations: List, + ) = insets + + override fun onEnd(animation: WindowInsetsAnimationCompat) { + running -= animation + } + }, + ) + } + + override val isIdleNow: Boolean + get() { + val windows = WindowInspector.getGlobalWindowViews() + animations.keys.retainAll(windows.toSet()) + windows.forEach(::watch) + if (animations.values.any { it.isNotEmpty() }) return false + if (!canShow) return true + val focused = windows.firstOrNull { it.hasWindowFocus() } ?: return false + val showing = windows.filter { + ViewCompat.getRootWindowInsets(it)?.isVisible(ime) == true + } + val editing = focused.findFocus()?.onCheckIsTextEditor() == true + return when { + !editing -> showing.isEmpty() + Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> focused in showing + else -> showing.isNotEmpty() + } + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/LibraryTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/LibraryTest.kt new file mode 100644 index 00000000000..a3c16c5e1e9 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/LibraryTest.kt @@ -0,0 +1,500 @@ +package so.cap.mobile + +import android.content.Intent +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.IdlingResource +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.hasAnySibling +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasScrollToIndexAction +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasStateDescription +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isHeading +import androidx.compose.ui.test.isSelectable +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.longClick +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performScrollToIndex +import androidx.compose.ui.test.performScrollToNode +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipeDown +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.lifecycleScope +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.kit.CapApiError +import so.cap.mobile.app.LibraryKey +import so.cap.mobile.app.LibraryModel +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.SessionHolder +import so.cap.mobile.features.cap.CapDetailModel +import so.cap.mobile.features.cap.CapDetailModels + +@RunWith(AndroidJUnit4::class) +class LibraryTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val relay = + FixtureRelay( + InstrumentationRegistry.getArguments().getString("capFixtureUrl") + ?: "http://localhost:4310" + ) + private val richie = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie" + private val nobody = "1f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie" + private val refused = CapApiError.Server(500).description + + private lateinit var scenario: ActivityScenario + private lateinit var sessions: SessionHolder + private lateinit var keyboard: KeyboardSettled + private var folder: LibraryKey? = null + private val shownToasts = CopyOnWriteArrayList() + private var seenToasts = 0 + + private val loaded = + object : IdlingResource { + override val isIdleNow: Boolean + get() { + val session = sessions.session ?: return false + if (session.bootstrap == null && session.bootstrapError == null) return false + if (session.isSwitchingOrganization) return false + val saving = session.folderDraft?.isSaving == true + if (saving && relay.folderHold?.isHolding != true) return false + val key = folder ?: session.currentLibraryKey ?: return true + val library = session.library(key) + return library.status != LibraryModel.Status.Idle && + library.status != LibraryModel.Status.Loading && + !library.isLoadingMore + } + } + + @Before + fun forgetEverything() { + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + @After + fun closeTheApp() { + compose.unregisterIdlingResource(loaded) + compose.unregisterIdlingResource(keyboard) + scenario.close() + relay.close() + app.services.vault.clear() + runBlocking { app.services.cache.removeAll() } + } + + private fun launch(session: String = richie) { + scenario = + ActivityScenario.launch( + Intent(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, relay.origin) + .putExtra(LaunchArguments.DEBUG_SESSION, session) + ) + compose.waitForIdle() + scenario.onActivity { + sessions = ViewModelProvider(it)[SessionHolder::class.java] + keyboard = KeyboardSettled(it) + } + compose.registerIdlingResource(loaded) + compose.registerIdlingResource(keyboard) + compose.waitForIdle() + scenario.onActivity { activity -> + val toasts = sessions.session?.toasts ?: return@onActivity + activity.lifecycleScope.launch { + toasts.current.collect { toast -> if (toast != null) shownToasts += toast.message } + } + } + } + + private fun await(signal: () -> Boolean) { + val resource = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signal() + } + compose.registerIdlingResource(resource) + try { + compose.waitForIdle() + } finally { + compose.unregisterIdlingResource(resource) + } + } + + private fun awaitToast(message: String) { + await { shownToasts.drop(seenToasts).contains(message) } + seenToasts = (seenToasts until shownToasts.size).first { shownToasts[it] == message } + 1 + } + + private val list = + hasScrollToIndexAction() and + SemanticsMatcher.keyIsDefined(SemanticsProperties.VerticalScrollAxisRange) + + private fun card(title: String) = hasText(title) and hasClickAction() + + private fun heading(title: String) = compose.onNode(hasText(title) and isHeading()) + + private fun chip(title: String) = compose.onNode(hasText(title) and isSelectable()) + + private fun sent(part: String) = relay.requests.any { part in it } + + private fun isPublic(title: String) = + compose + .onAllNodes(card(title) and hasStateDescription("Public")) + .fetchSemanticsNodes() + .isNotEmpty() + + private fun visibility(isPublic: Boolean) = if (isPublic) "Public" else "Private" + + private fun field() = compose.onNode(hasSetTextAction()) + + private fun button(label: String) = + compose.onNode(hasContentDescription(label) and hasClickAction()) + + private fun openFromTheAddMenu(entry: String) { + compose.onNode(hasContentDescription("Add")).performClick() + compose.onNode(hasText(entry)).performClick() + field().assertIsDisplayed().assertIsFocused() + } + + private fun pressAndHold(title: String) { + compose.onNode(card(title)).performTouchInput { longClick() } + } + + @Test + fun theListShowsTheFoldersAndTheCaps() { + launch() + + chip("My Caps").assertIsDisplayed() + compose.onNode(hasContentDescription("Launch folder, 4 Caps")).assertIsDisplayed() + heading("Caps").assertIsDisplayed() + compose.onNode(hasText(relay.capTitles.size.toString())).assertIsDisplayed() + compose.onNode(card(relay.capTitles.first())).assertIsDisplayed() + assertTrue(sent("GET /api/mobile/caps?")) + } + + @Test + fun scrollingTowardsTheEndLoadsTheNextPage() { + relay.pageSize = 14 + launch() + val titles = relay.capTitles + assertTrue(titles.size > 14) + assertFalse(sent("page=2")) + + compose.onNode(list).performScrollToIndex(3 + 13) + compose.waitForIdle() + assertTrue(sent("page=2")) + + compose.onNode(list).performScrollToNode(card(titles[10])) + compose.onNode(card(titles[10])).assertIsDisplayed() + compose.onNode(list).performScrollToNode(card(titles.last())) + compose.onNode(card(titles.last())).assertIsDisplayed() + assertFalse(sent("page=3")) + } + + @Test + fun aRefreshAtTheTopLoadsTheNextPageAgain() { + relay.pageSize = 3 + launch() + val secondPages = { relay.requests.count { "page=2&" in it && "folderId=" !in it } } + val before = secondPages() + + compose.onNode(list).performTouchInput { swipeDown() } + await { secondPages() > before } + } + + @Test + fun aFailedPageAfterAnEmptyFirstPageOffersARetry() { + relay.emptyFirstPage = true + relay.refusesLaterPages = true + launch() + + compose.onNode(hasText("Couldn't load more. Tap to retry.")).assertIsDisplayed() + compose.onNode(hasText("No Caps yet.")).assertDoesNotExist() + } + + @Test + fun choosingASpaceShowsItsCapsAndChoosingMyCapsComesBack() { + launch() + + chip("Design").performClick() + chip("Design").assertIsDisplayed() + chip("Design").assertIsSelected() + assertTrue(sent("spaceId=space_design")) + + chip("My Caps").performClick() + chip("My Caps").assertIsDisplayed() + chip("My Caps").assertIsSelected() + } + + @Test + fun anEmptySpaceStillShowsTheScopeBar() { + relay.emptySpaceId = "space_design" + launch() + + chip("Design").performClick() + chip("Design").assertIsDisplayed().assertIsSelected() + chip("My Caps").assertIsDisplayed() + + chip("My Caps").performClick() + compose.onNode(card(relay.capTitles.first())).assertIsDisplayed() + } + + @Test + fun aFolderOpensWithItsCapsAndBackReturnsToTheList() { + launch() + + compose.onNode(hasContentDescription("Launch folder, 4 Caps")).performClick() + folder = LibraryKey("org_cap", LibraryScope.Personal, "folder_launch") + heading("Launch").assertIsDisplayed() + assertTrue(sent("folderId=folder_launch")) + + folder = null + compose.onNode(hasContentDescription("Back")).performClick() + chip("My Caps").assertIsDisplayed() + } + + @Test + fun aChangeOfWhoCanViewShowsAtOnceAndIsUndoneWhenTheServerRefuses() { + val refusal = FixtureRelay.Hold() + relay.refusal = refusal + launch() + val title = relay.capTitles.first() + val before = isPublic(title) + + pressAndHold(title) + compose.onNode(hasText(if (before) "Make private" else "Make public")).performClick() + await { refusal.arrived } + compose.onNode(card(title) and hasStateDescription(visibility(!before))).assertIsDisplayed() + + refusal.release() + awaitToast(refused) + compose.onNode(card(title) and hasStateDescription(visibility(before))).assertIsDisplayed() + } + + @Test + fun aChangeOfWhoCanViewThatIsSavedStays() { + launch() + val title = relay.capTitles.first() + val before = isPublic(title) + val toasts = + mapOf( + true to "Anyone with the link can view", + false to "Only you and your team can view", + ) + + pressAndHold(title) + compose.onNode(hasText(if (before) "Make private" else "Make public")).performClick() + awaitToast(toasts.getValue(!before)) + compose.onNode(card(title) and hasStateDescription(visibility(!before))).assertIsDisplayed() + + pressAndHold(title) + compose.onNode(hasText(if (before) "Make public" else "Make private")).performClick() + awaitToast(toasts.getValue(before)) + compose.onNode(card(title) and hasStateDescription(visibility(before))).assertIsDisplayed() + } + + @Test + fun deleteAsksFirstAndRemovesTheCapOnceTheServerHasDeletedIt() { + launch() + val title = relay.capTitles.first() + val question = + "\u201C$title\u201D will be permanently deleted for everyone, " + + "including its link, comments and analytics." + + pressAndHold(title) + compose.onNode(hasText("Delete")).performClick() + compose.onNode(hasText("Delete this Cap?")).assertIsDisplayed() + compose.onNode(hasText(question)).assertIsDisplayed() + compose.onNode(hasText("Delete Cap")).assertIsDisplayed() + compose.onNode(hasText("Cancel")).performClick() + compose.onNode(hasText("Delete this Cap?")).assertDoesNotExist() + compose.onNode(card(title)).assertIsDisplayed() + assertFalse(sent("DELETE ")) + + pressAndHold(title) + compose.onNode(hasText("Delete")).performClick() + compose.onNode(hasText("Delete Cap")).performClick() + awaitToast("Cap deleted") + compose.onNode(card(title)).assertDoesNotExist() + assertEquals(1, relay.requests.count { it.startsWith("DELETE /api/mobile/caps/") }) + } + + @Test + fun theAddMenuListsWhatCanBeAddedAndOpensAPlaceholder() { + launch() + + compose.onNode(hasContentDescription("Add")).performClick() + for (entry in + listOf( + "Record", + "Upload from Photos", + "Upload from Files", + "Import from Loom", + "New folder", + "Open a Cap link", + )) { + compose + .onNode(hasText(entry) and hasClickAction() and !isSelectable()) + .assertIsDisplayed() + } + + compose.onNode(hasText("Import from Loom")).performClick() + compose.onNode(hasText("Import from Loom")).assertIsDisplayed() + compose.onNode(hasContentDescription("Back")).performClick() + chip("My Caps").assertIsDisplayed() + } + + @Test + fun aNewFolderIsNamedGivenAColourAndPutFirst() { + relay.createsFolders = true + launch() + + openFromTheAddMenu("New folder") + compose.onNode(hasText("New folder") and isHeading()).assertIsDisplayed() + button("Create").assertIsDisplayed().assertIsNotEnabled() + field().performTextInput("Launch plans") + compose + .onNode(hasContentDescription("Red")) + .performScrollTo() + .assertIsDisplayed() + .performClick() + .assertIsSelected() + button("Create").assertIsDisplayed().performClick() + + awaitToast("Folder created") + compose.onNode(hasContentDescription("Launch plans folder, 0 Caps")).assertIsDisplayed() + assertEquals( + """{"name":"Launch plans","color":"red"}""", + relay.bodies["POST /api/mobile/folders"], + ) + } + + @Test + fun aNewFolderShowsAtOnceInALibraryThatHadNone() { + relay.listsFolders = false + relay.createsFolders = true + launch() + compose.onNode(card(relay.capTitles.first())).assertIsDisplayed() + + openFromTheAddMenu("New folder") + field().performTextInput("Launch plans") + button("Create").assertIsDisplayed().performClick() + + awaitToast("Folder created") + compose.onNode(hasContentDescription("Launch plans folder, 0 Caps")).assertIsDisplayed() + } + + @Test + fun aFolderTheServerRefusesKeepsTheSheetAndSaysWhy() { + val hold = FixtureRelay.Hold() + relay.folderHold = hold + launch() + + openFromTheAddMenu("New folder") + field().performTextInput("Launch plans") + button("Create").assertIsDisplayed().performClick() + await { hold.arrived } + val saving = + SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo) and + hasAnySibling(hasContentDescription("Cancel")) + button("Create").assertDoesNotExist() + compose.onNode(saving).assertIsDisplayed() + heading("New folder").performTouchInput { + swipeDown(startY = centerY, endY = centerY + 300.dp.toPx()) + } + field().assertIsDisplayed().assertIsFocused() + compose.onNode(saving).assertIsDisplayed() + + hold.release() + compose + .onNode(hasContentDescription("Error: " + CapApiError.NotFound.description)) + .assertIsDisplayed() + assertTrue(sent("POST /api/mobile/folders")) + button("Create").assertIsDisplayed() + field().assertIsFocused() + button("Cancel").assertIsDisplayed().performClick() + chip("My Caps").assertIsDisplayed() + compose.onNode(hasSetTextAction()).assertDoesNotExist() + } + + @Test + fun sortingByNamePutsTheAlphabeticallyFirstCapAtTheTop() { + launch() + val alphabetic = relay.capTitles.first { it.startsWith("An extremely long") } + + compose.onNode(hasText("Newest")).performClick() + heading("Sort by").assertIsDisplayed() + chip("Name, A to Z").performClick() + + compose.onNode(hasText("Sort by")).assertDoesNotExist() + compose.onNode(hasText("Name, A to Z")).assertIsDisplayed() + compose.onNode(card(alphabetic)).assertIsDisplayed() + } + + @Test + fun aCapLinkOpensTheCapAndAnythingElseIsRefused() { + launch() + + openFromTheAddMenu("Open a Cap link") + button("Open").assertIsDisplayed().assertIsNotEnabled() + field().performTextInput("not a link") + button("Open").assertIsDisplayed().performClick() + compose + .onNode(hasContentDescription("Error: That doesn't look like a Cap link.")) + .assertIsDisplayed() + + field().performTextReplacement("https://cap.so/s/cap_london") + button("Open").assertIsDisplayed().performClick() + lateinit var cap: CapDetailModel + scenario.onActivity { + cap = + ViewModelProvider(it)[CapDetailModels::class.java].model( + Route.Cap("cap_london"), + checkNotNull(sessions.session), + ) + } + await { cap.content is CapDetailModel.Content.Loaded } + compose.onNode(hasText("Walkthrough: the new Cap 0.6.2 editor")).assertIsDisplayed() + compose.onNode(hasContentDescription("Back")).performClick() + chip("My Caps").assertIsDisplayed() + } + + @Test + fun anAccountWithNoCapsSaysSoAndOffersToAddAVideo() { + launch(nobody) + + compose.onNode(hasText("No Caps yet.")).assertIsDisplayed() + compose + .onNode( + hasText( + "Press the shutter. Your first Cap lands here with its link already copied." + ) + ) + .assertIsDisplayed() + button("Add").assertIsDisplayed() + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/MainShellTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/MainShellTest.kt new file mode 100644 index 00000000000..5efedda103b --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/MainShellTest.kt @@ -0,0 +1,117 @@ +package so.cap.mobile + +import android.content.Intent +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotSelected +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isHeading +import androidx.compose.ui.test.isSelectable +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.espresso.Espresso +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class MainShellTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val fixture = + InstrumentationRegistry.getArguments().getString("capFixtureUrl") ?: "http://localhost:4310" + private lateinit var scenario: ActivityScenario + + @Before + fun startSignedIn() { + scenario = + ActivityScenario.launch( + Intent(app, MainActivity::class.java) + .putExtra(LaunchArguments.API_BASE_URL, fixture) + .putExtra( + LaunchArguments.DEBUG_SESSION, + "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie", + ) + ) + } + + @After + fun signOut() { + scenario.close() + app.services.vault.clear() + } + + private fun tab(title: String) = compose.onNode(hasText(title) and isSelectable()) + + private fun pageTitle(title: String) = compose.onNode(hasText(title) and !isSelectable()) + + private fun libraryTitle() = compose.onNode(hasText("Caps") and isHeading() and !isSelectable()) + + @Test + fun theAppStartsOnCaps() { + tab("Caps").assertIsSelected() + libraryTitle().assertIsDisplayed() + tab("Record").assertIsNotSelected() + tab("Analytics").assertIsNotSelected() + tab("Settings").assertIsNotSelected() + } + + @Test + fun selectingATabShowsItsPage() { + tab("Analytics").performClick() + tab("Analytics").assertIsSelected() + pageTitle("Analytics").assertIsDisplayed() + + tab("Settings").performClick() + tab("Settings").assertIsSelected() + pageTitle("Settings").assertIsDisplayed() + + tab("Caps").performClick() + tab("Caps").assertIsSelected() + libraryTitle().assertIsDisplayed() + } + + @Test + fun recordOpensAFullScreenPageAndCloseReturnsToTheSameTab() { + tab("Settings").performClick() + + tab("Record").performClick() + compose.onNode(hasContentDescription("Close")).assertIsDisplayed() + pageTitle("Record").assertIsDisplayed() + tab("Settings").assertDoesNotExist() + + compose.onNode(hasContentDescription("Close")).performClick() + compose.onNode(hasContentDescription("Close")).assertDoesNotExist() + tab("Settings").assertIsSelected() + tab("Record").assertIsNotSelected() + } + + @Test + fun backClosesTheRecordPage() { + tab("Record").performClick() + compose.onNode(hasContentDescription("Close")).assertIsDisplayed() + + Espresso.pressBack() + + compose.onNode(hasContentDescription("Close")).assertDoesNotExist() + tab("Caps").assertIsSelected() + } + + @Test + fun backOnAnotherTabReturnsToCaps() { + tab("Analytics").performClick() + + Espresso.pressBack() + + tab("Caps").assertIsSelected() + libraryTitle().assertIsDisplayed() + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/SignInTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/SignInTest.kt new file mode 100644 index 00000000000..d7f7597c7a7 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/SignInTest.kt @@ -0,0 +1,378 @@ +package so.cap.mobile + +import android.content.Intent +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.IdlingResource +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.SemanticsNodeInteraction +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasContentDescription +import androidx.compose.ui.test.hasStateDescription +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isDialog +import androidx.compose.ui.test.isSelectable +import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performImeAction +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performTextInput +import androidx.core.net.toUri +import androidx.lifecycle.ViewModelProvider +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.espresso.Espresso +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.kit.AuthCallback +import so.cap.kit.CredentialSnapshot +import so.cap.mobile.app.AppModel +import so.cap.mobile.app.Phase +import so.cap.mobile.app.credentialStore +import so.cap.mobile.features.auth.SignInModel + +@RunWith(AndroidJUnit4::class) +class SignInTest { + @get:Rule val compose = createEmptyComposeRule() + + private val app = ApplicationProvider.getApplicationContext() + private val fixture = + InstrumentationRegistry.getArguments().getString("capFixtureUrl") ?: "http://localhost:4310" + private val key = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e" + private val richie = CredentialSnapshot(key, "user_richie") + private val callback = "cap://auth?api_key=$key&user_id=user_richie" + private val wrongCode = "That code didn't match. Check the email and enter it again." + + private lateinit var scenario: ActivityScenario + private lateinit var model: AppModel + private lateinit var keyboard: KeyboardSettled + + private val signIn: SignInModel? + get() = (model.phase.value as? Phase.SignedOut)?.signIn + + private val requests = + object : IdlingResource { + override val isIdleNow: Boolean + get() = !model.isSigningOut && signIn?.activity == null + } + + @Before + fun forgetTheSession() { + app.services.vault.clear() + } + + @After + fun closeTheApp() { + compose.unregisterIdlingResource(requests) + compose.unregisterIdlingResource(keyboard) + scenario.close() + app.services.vault.clear() + } + + private fun launch(session: String? = null, configure: Intent.() -> Unit = {}) { + val intent = + Intent(app, MainActivity::class.java).putExtra(LaunchArguments.API_BASE_URL, fixture) + if (session != null) intent.putExtra(LaunchArguments.DEBUG_SESSION, session) + intent.configure() + scenario = ActivityScenario.launch(intent) + compose.waitForIdle() + scenario.onActivity { + model = ViewModelProvider(it)[AppModel::class.java] + keyboard = KeyboardSettled(it) + } + compose.registerIdlingResource(requests) + compose.registerIdlingResource(keyboard) + } + + private val email = hasContentDescription("Email address") + private val code = hasContentDescription("Verification code") + + private val resendCountdown = + SemanticsMatcher("counts down to the next code") { node -> + node.config.getOrNull(SemanticsProperties.Text).orEmpty().any { + Regex("Nothing yet\\? Ask for a new code in 0:[0-9]{2}").matches(it.text) + } + } + + private val anyError = + SemanticsMatcher("is an error message") { node -> + node.config.getOrNull(SemanticsProperties.ContentDescription).orEmpty().any { + it.startsWith("Error:") + } + } + + private fun error(message: String) = compose.onNode(hasContentDescription("Error: $message")) + + private fun tab(title: String) = compose.onNode(hasText(title) and isSelectable()) + + private fun SemanticsNodeInteraction.scrollToAndClick() = + performScrollTo().assertIsDisplayed().performClick() + + private fun reachTheCodeStep() { + compose.onNode(hasText("Continue with email")).scrollToAndClick() + compose.onNode(email).performTextInput("richie@cap.so") + compose.onNode(hasText("Send code")).scrollToAndClick() + val signIn = checkNotNull(signIn) + val answered = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signIn.step is SignInModel.Step.Code || signIn.errorMessage != null + } + compose.registerIdlingResource(answered) + try { + compose.waitForIdle() + } finally { + compose.unregisterIdlingResource(answered) + } + assertNull("The code request failed", signIn.errorMessage) + compose.onNode(hasText("Enter the code")).assertIsDisplayed() + } + + @Test + fun signIn() { + launch() + compose.onNode(hasText("Stop recording. The link is already copied.")).assertIsDisplayed() + compose.onNode(hasText("Continue with email")).assertIsEnabled() + compose.onNode(hasText("Continue with Apple")).assertDoesNotExist() + compose.onNode(hasText("Continue with Google")).assertIsEnabled() + + reachTheCodeStep() + compose.onNode(hasText("Sent to richie@cap.so")).assertIsDisplayed() + compose.onNode(code and hasStateDescription("Empty")).assertIsDisplayed() + compose.onNode(hasText("Continue")).assertIsNotEnabled() + + compose.onNode(code).performTextInput("123456") + + tab("Caps").assertIsSelected() + assertEquals(richie, app.services.vault.credentials) + assertEquals(richie, credentialStore(app, app.services.environment).load()) + } + + @Test + fun systemBackFromEmailReturnsToTheSignInChoices() { + launch() + compose.onNode(hasText("Continue with email")).scrollToAndClick() + compose.onNode(hasText("What's your email?")).assertIsDisplayed() + + Espresso.pressBack() + + compose.onNode(hasText("Stop recording. The link is already copied.")).assertIsDisplayed() + compose.onNode(hasText("Continue with email")).assertIsDisplayed() + } + + @Test + fun anInvalidEmailShowsTheMessage() { + launch() + compose.onNode(hasText("Continue with email")).scrollToAndClick() + compose.onNode(email).performTextInput("richie@cap") + compose.onNode(hasText("Send code")).assertIsNotEnabled() + + compose.onNode(email).performImeAction() + + error("Enter a valid email address.").assertIsDisplayed() + compose.onNode(hasText("What's your email?")).assertIsDisplayed() + } + + @Test + fun aWrongCodeShowsTheMessageAndKeepsTheDigits() { + launch() + reachTheCodeStep() + + compose.onNode(code).performTextInput("000000") + + error(wrongCode).assertIsDisplayed() + compose.onNode(code and hasStateDescription("0 0 0 0 0 0")).assertIsDisplayed() + compose.onNode(hasText("Send a new code")).assertIsEnabled() + assertNull(app.services.vault.credentials) + } + + @Test + fun resendingAfterAWrongCodeShowsTheConfirmationAndClearsTheDigits() { + launch() + reachTheCodeStep() + compose.onNode(code).performTextInput("000000") + error(wrongCode).assertIsDisplayed() + + compose.onNode(hasText("Send a new code")).performClick() + + compose.onNode(hasText("New code sent. It lasts 10 minutes.")).assertIsDisplayed() + compose.onNode(code and hasStateDescription("Empty")).assertIsDisplayed() + } + + @Test + fun theCodeIsReadOutDigitByDigit() { + launch() + reachTheCodeStep() + + compose.onNode(code).performTextInput("12a3") + + compose.onNode(code and hasStateDescription("1 2 3")).assertIsDisplayed() + } + + @Test + fun resendCountsDown() { + launch() + reachTheCodeStep() + compose.onNode(resendCountdown).assertIsDisplayed() + val signIn = checkNotNull(signIn) + val ticked = + object : IdlingResource { + override val isIdleNow: Boolean + get() = signIn.resendRemaining < 30 + } + + compose.registerIdlingResource(ticked) + compose.onNode(resendCountdown).assertIsDisplayed() + compose.unregisterIdlingResource(ticked) + + assertTrue(signIn.resendRemaining in 1..29) + } + + @Test + fun differentEmailReturnsToTheEmailStepWithTheAddressKept() { + launch() + reachTheCodeStep() + + compose.onNode(hasContentDescription("Back")).performClick() + + compose.onNode(hasText("What's your email?")).assertIsDisplayed() + compose.onNode(email and hasText("richie@cap.so")).assertIsDisplayed() + } + + @Test + fun aRelaunchStaysSignedIn() { + launch() + reachTheCodeStep() + compose.onNode(code).performTextInput("123456") + tab("Caps").assertIsSelected() + compose.unregisterIdlingResource(requests) + compose.unregisterIdlingResource(keyboard) + scenario.close() + + launch() + + tab("Caps").assertIsSelected() + assertEquals(Phase.SignedIn(richie), model.phase.value) + } + + @Test + fun signingOutReturnsToSignIn() { + launch(session = "$key:user_richie") + tab("Settings").performClick() + val version = app.packageManager.getPackageInfo(app.packageName, 0) + compose + .onNode( + hasText("Version") and + hasText("${version.versionName} (${version.longVersionCode})") + ) + .assertIsDisplayed() + + compose.onNode(hasText("Sign out")).scrollToAndClick() + compose.onNode(hasText("Sign out of Cap on this device?")).assertIsDisplayed() + compose.onNode(hasText("Cancel")).performClick() + compose.onNode(hasText("Sign out of Cap on this device?")).assertDoesNotExist() + tab("Settings").assertIsSelected() + + compose.onNode(hasText("Sign out")).scrollToAndClick() + compose.onNode(hasText("Sign out") and hasAnyAncestor(isDialog())).performClick() + + compose.onNode(hasText("Stop recording. The link is already copied.")).assertIsDisplayed() + compose.onNode(anyError).assertDoesNotExist() + assertNull(app.services.vault.credentials) + assertNull(credentialStore(app, app.services.environment).load()) + } + + @Test + fun aSessionTheServerRejectsReturnsToSignInWithTheNotice() { + launch(session = "2f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e:user_richie") + val signedOut = + object : IdlingResource { + override val isIdleNow: Boolean + get() = model.phase.value is Phase.SignedOut + } + compose.registerIdlingResource(signedOut) + try { + error("Your session expired. Sign in again.").assertIsDisplayed() + } finally { + compose.unregisterIdlingResource(signedOut) + } + assertNull(app.services.vault.credentials) + } + + @Test + fun anAuthCallbackNobodyAskedForIsIgnored() { + launch() + + deliver(callback) + + compose.onNode(hasText("Stop recording. The link is already copied.")).assertIsDisplayed() + assertNull(app.services.vault.credentials) + } + + @Test + fun anAuthCallbackForASignInThisAppStartedSignsIn() { + launch() + lateinit var url: String + scenario.onActivity { url = checkNotNull(checkNotNull(signIn).startProvider("google")) } + + deliver("$callback&state=${AuthCallback.state(url)}") + + tab("Caps").assertIsSelected() + assertEquals(richie, app.services.vault.credentials) + } + + @Test + fun anAuthCallbackWithoutTheStateOfThePendingSignInIsRefused() { + launch() + + for (link in listOf(callback, "$callback&state=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) { + scenario.onActivity { checkNotNull(signIn).startProvider("google") } + deliver(link) + + compose + .onNode(hasText("Stop recording. The link is already copied.")) + .assertIsDisplayed() + assertNull(app.services.vault.credentials) + assertNull(credentialStore(app, app.services.environment).load()) + assertNull(signIn?.activity) + error( + "Google sign-in couldn't finish in this browser. Install or turn on Chrome, " + + "or sign in with your email." + ) + .assertIsDisplayed() + } + } + + @Test + fun aLaunchIntentCannotClaimAProviderSignInIsPending() { + launch { + action = Intent.ACTION_VIEW + data = callback.toUri() + putExtra("pendingProvider", "google") + putExtra("pendingProviderSince", System.currentTimeMillis()) + } + + compose.onNode(hasText("Stop recording. The link is already copied.")).assertIsDisplayed() + assertNull(signIn?.activity) + assertNull(app.services.vault.credentials) + } + + private fun deliver(url: String) { + val instrumentation = InstrumentationRegistry.getInstrumentation() + scenario.onActivity { + instrumentation.callActivityOnNewIntent(it, Intent(Intent.ACTION_VIEW, url.toUri())) + } + } +} diff --git a/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/app/CredentialVaultInstrumentedTest.kt b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/app/CredentialVaultInstrumentedTest.kt new file mode 100644 index 00000000000..075cc621091 --- /dev/null +++ b/apps/mobile-android/app/src/androidTest/kotlin/so/cap/mobile/app/CredentialVaultInstrumentedTest.kt @@ -0,0 +1,75 @@ +package so.cap.mobile.app + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import java.io.File +import java.security.KeyStore +import javax.crypto.KeyGenerator +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import so.cap.kit.CapEnvironment +import so.cap.kit.CredentialSnapshot + +@RunWith(AndroidJUnit4::class) +class CredentialVaultInstrumentedTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private val credentials = + CredentialSnapshot("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie") + private val file = File(context.noBackupFilesDir, "session") + + private fun store() = credentialStore(context, CapEnvironment.PRODUCTION) + + @After + fun removeTheSessionAndItsKey() { + store().delete() + KeyStore.getInstance("AndroidKeyStore").apply { load(null) }.deleteEntry(ALIAS) + } + + @Test + fun aKeyThatCanNoLongerBeUsedIsReplacedOnSave() { + val purposes = KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + val unusable = + KeyGenParameterSpec.Builder(ALIAS, purposes) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) + .build() + KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + .apply { init(unusable) } + .generateKey() + + CredentialVault(store()).replace(credentials) + + assertEquals(credentials, CredentialVault(store()).credentials) + } + + @Test + fun aSessionRoundTripsThroughTheKeystore() { + CredentialVault(store()).replace(credentials) + + assertEquals(credentials, CredentialVault(store()).credentials) + + val bytes = String(file.readBytes(), Charsets.ISO_8859_1) + assertFalse(bytes.contains(credentials.apiKey)) + assertFalse(bytes.contains(credentials.userId)) + + val keystore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + assertTrue(keystore.containsAlias(ALIAS)) + assertNull(keystore.getKey(ALIAS, null).encoded) + + assertTrue(CredentialVault(store()).clear(ifMatching = credentials)) + assertFalse(file.exists()) + assertNull(CredentialVault(store()).credentials) + } + + private companion object { + const val ALIAS = "so.cap.mobile.session" + } +} diff --git a/apps/mobile-android/app/src/debug/AndroidManifest.xml b/apps/mobile-android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000000..4d6bf7aa726 --- /dev/null +++ b/apps/mobile-android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,17 @@ + + + + + + + + + diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DebugCapApplication.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DebugCapApplication.kt new file mode 100644 index 00000000000..fe7e18b2718 --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DebugCapApplication.kt @@ -0,0 +1,45 @@ +package so.cap.mobile + +import android.app.Activity +import android.app.Application +import android.os.Bundle +import java.io.IOException +import so.cap.kit.CapEnvironment + +class DebugCapApplication : CapApplication(), Application.ActivityLifecycleCallbacks { + override fun onCreate() { + super.onCreate() + registerActivityLifecycleCallbacks(this) + } + + override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) { + if (activity !is MainActivity) return + val intent = activity.intent + intent + .getStringExtra(LaunchArguments.API_BASE_URL) + ?.let { CapEnvironment.parse(it, allowInsecureLocalhost = true) } + ?.let(::pointAt) + if (savedInstanceState != null) return + val session = + intent.getStringExtra(LaunchArguments.DEBUG_SESSION)?.let { + LaunchArguments.session(it, services.environment) + } ?: return + try { + services.vault.replace(session) + } catch (_: IOException) {} + } + + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} + + override fun onActivityStarted(activity: Activity) {} + + override fun onActivityResumed(activity: Activity) {} + + override fun onActivityPaused(activity: Activity) {} + + override fun onActivityStopped(activity: Activity) {} + + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} + + override fun onActivityDestroyed(activity: Activity) {} +} diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemSamples.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemSamples.kt new file mode 100644 index 00000000000..78e631c1167 --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemSamples.kt @@ -0,0 +1,216 @@ +package so.cap.mobile + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.dp +import so.cap.mobile.designsystem.CapAnnotationColors +import so.cap.mobile.designsystem.CapColorSwatch +import so.cap.mobile.designsystem.CapEditorToolItem +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapHairlineRow +import so.cap.mobile.designsystem.CapLargeNumericReadout +import so.cap.mobile.designsystem.CapNumericSize +import so.cap.mobile.designsystem.CapPanelScaffold +import so.cap.mobile.designsystem.CapPrimaryButton +import so.cap.mobile.designsystem.CapRadioRow +import so.cap.mobile.designsystem.CapScopeSegmentedControl +import so.cap.mobile.designsystem.CapSecondaryButton +import so.cap.mobile.designsystem.CapSheetScaffold +import so.cap.mobile.designsystem.CapSwitch +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapTickSlider +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.CapWallpaperColors +import so.cap.mobile.designsystem.ScreenTitleBlock + +@Composable +fun FoundationSamples() { + ScreenTitleBlock( + title = "Screen title", + description = "15/22 body copy in the secondary colour.", + ) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + CapLargeNumericReadout("0:42", size = CapNumericSize.Metric) + CapLargeNumericReadout( + "64%", + size = CapNumericSize.Notification, + color = CapTheme.colors.blue, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TokenChip("BG", MaterialTheme.colorScheme.background) + TokenChip("Text", MaterialTheme.colorScheme.onSurface) + TokenChip("Meta", CapTheme.colors.textSecondary) + TokenChip("Line", CapTheme.colors.hairline) + TokenChip("Fill", CapTheme.colors.quietFill) + TokenChip("Blue", CapTheme.colors.blue) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + CapColorSwatch("Sky", true, {}, brush = CapWallpaperColors.skySwatchBrush, size = 48) + CapColorSwatch("Dusk", false, {}, brush = CapWallpaperColors.duskSwatchBrush, size = 48) + CapColorSwatch("Paper", false, {}, color = CapWallpaperColors.paper, size = 48) + CapColorSwatch( + "Ink", + false, + {}, + color = CapWallpaperColors.ink, + size = 48, + borderColor = CapWallpaperColors.inkBorder, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon(painterResource(R.drawable.ic_cap_back), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_close), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_undo), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_redo), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_search), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_folder), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_mic), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_camera), null, Modifier.size(24.dp)) + Icon( + painterResource(R.drawable.ic_cap_check), + null, + Modifier.size(24.dp), + tint = CapTheme.colors.blue, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon(painterResource(R.drawable.ic_cap_chevron_right), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_chevron_down), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_camera_off), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_mic_off), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_play), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_pause), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_send), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_edit), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_copy), null, Modifier.size(24.dp)) + Icon(painterResource(R.drawable.ic_cap_share), null, Modifier.size(24.dp)) + } +} + +@Composable +private fun TokenChip(label: String, color: Color) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Box(Modifier.size(32.dp).background(color, RoundedCornerShape(CapTheme.controlRadius))) + Text(label, style = CapType.tinyLabel) + } +} + +@Composable +fun ControlSamples() { + var switchOn by remember { mutableStateOf(true) } + var radio by remember { mutableIntStateOf(0) } + var scope by remember { mutableIntStateOf(0) } + var width by remember { mutableIntStateOf(6) } + CapPrimaryButton("Primary action", onClick = {}, modifier = Modifier.fillMaxWidth()) + CapSecondaryButton("Secondary action", onClick = {}, modifier = Modifier.fillMaxWidth()) + CapScopeSegmentedControl( + options = listOf("Yours", "Team", "Shared"), + selectedIndex = scope, + onSelected = { scope = it }, + ) + CapHairlineRow(minHeight = 60.dp, bottomHairline = true) { + Text("Camera on", style = CapType.rowTitle) + CapSwitch(checked = switchOn, onCheckedChange = { switchOn = it }) + } + Column { + CapRadioRow( + title = "Northpine Studio", + subtitle = "Member", + selected = radio == 0, + onClick = { radio = 0 }, + ) + CapRadioRow( + title = "Rowan's Caps", + subtitle = "Personal", + selected = radio == 1, + onClick = { radio = 1 }, + ) + } + CapTickSlider( + label = "Width", + value = width, + range = 0..20, + onValueChange = { width = it }, + ) +} + +@Composable +fun PanelSamples() { + CapPanelScaffold(title = "Arrow", onDone = {}) { + FlowRow( + modifier = Modifier.padding(top = 6.dp, bottom = 20.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + CapColorSwatch("Blue", true, {}, color = CapAnnotationColors.blue) + CapColorSwatch("Sky", false, {}, color = CapAnnotationColors.sky) + CapColorSwatch("Yellow", false, {}, color = CapAnnotationColors.yellow) + CapColorSwatch("Orange", false, {}, color = CapAnnotationColors.orange) + CapColorSwatch("Green", false, {}, color = CapAnnotationColors.green) + CapColorSwatch("White", false, {}, color = CapAnnotationColors.white) + CapColorSwatch( + "Black", + false, + {}, + color = CapAnnotationColors.black, + borderColor = CapAnnotationColors.blackBorder, + ) + } + CapTickSlider(label = "Width", value = 6, range = 0..20, onValueChange = {}) + } + Row( + modifier = Modifier.fillMaxWidth().height(48.dp), + horizontalArrangement = Arrangement.spacedBy(26.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CapEditorToolItem("Arrow", selected = true, onClick = {}) + CapEditorToolItem("Box", selected = false, onClick = {}) + CapEditorToolItem("Circle", selected = false, onClick = {}) + CapEditorToolItem("Text", selected = false, onClick = {}) + } + CapSheetScaffold(title = "Share", onDone = {}) { + CapLargeNumericReadout("1080 × 2400", size = CapNumericSize.Option) + Text( + "Saved on this phone. Upload it and the link is copied.", + color = CapTheme.colors.textSecondary, + style = CapType.body, + ) + CapPrimaryButton( + "Upload to Cap and copy the link", + onClick = {}, + modifier = Modifier.fillMaxWidth().padding(top = 20.dp), + ) + } + Column { + CapHairline() + Box( + Modifier.fillMaxWidth() + .height(20.dp) + .background(Brush.verticalGradient(CapWallpaperColors.sky)) + ) + } +} diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemTestActivity.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemTestActivity.kt new file mode 100644 index 00000000000..71d844d8073 --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/DesignSystemTestActivity.kt @@ -0,0 +1,5 @@ +package so.cap.mobile + +import androidx.activity.ComponentActivity + +class DesignSystemTestActivity : ComponentActivity() diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryActivity.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryActivity.kt new file mode 100644 index 00000000000..31b60186fd8 --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryActivity.kt @@ -0,0 +1,341 @@ +package so.cap.mobile + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.LocalTextStyle +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import java.time.Instant +import so.cap.kit.CapApiError +import so.cap.kit.CapEnvironment +import so.cap.kit.CapSummary +import so.cap.kit.UploadPhase +import so.cap.kit.UploadProgress +import so.cap.mobile.app.ImageRequestInterceptor +import so.cap.mobile.app.Toast +import so.cap.mobile.app.ToastCenter +import so.cap.mobile.app.imageHttpClient +import so.cap.mobile.app.imageLoader +import so.cap.mobile.designsystem.Avatar +import so.cap.mobile.designsystem.CapPrimaryButton +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapThumbnail +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.ErrorText +import so.cap.mobile.designsystem.InkButton +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.designsystem.LocalImageLoader +import so.cap.mobile.designsystem.OrganizationIcon +import so.cap.mobile.designsystem.ProviderButton +import so.cap.mobile.designsystem.ScrimBadge +import so.cap.mobile.designsystem.SectionHeader +import so.cap.mobile.designsystem.SkeletonBlock +import so.cap.mobile.designsystem.SkeletonText +import so.cap.mobile.designsystem.StatLabel +import so.cap.mobile.designsystem.ToastHost +import so.cap.mobile.designsystem.TonalButton +import so.cap.mobile.designsystem.shimmering + +class GalleryActivity : ComponentActivity() { + private val imageServer = GalleryImageServer() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val section = + intent.getStringExtra(EXTRA_SECTION)?.let { name -> + GallerySection.entries.firstOrNull { it.name.equals(name, ignoreCase = true) } + } + val theme = intent.getStringExtra(EXTRA_THEME) + val fontScale = intent.getFloatExtra(EXTRA_FONT_SCALE, 0f) + val environment = + checkNotNull(CapEnvironment.parse(imageServer.origin, allowInsecureLocalhost = true)) + val images = + imageLoader( + this, + imageHttpClient(ImageRequestInterceptor(environment) { emptyMap() }), + (application as CapApplication).services.imageCache, + ) + setContent { + val darkTheme = + when (theme) { + "dark" -> true + "light" -> false + else -> isSystemInDarkTheme() + } + val density = LocalDensity.current + CompositionLocalProvider( + LocalDensity provides + if (fontScale > 0f) Density(density.density, fontScale) else density, + LocalImageLoader provides images, + LocalCapEnvironment provides environment, + ) { + CapTheme(darkTheme = darkTheme) { + Gallery(sections = section?.let(::listOf) ?: GallerySection.entries) + } + } + } + } + + override fun onDestroy() { + imageServer.close() + super.onDestroy() + } + + companion object { + const val EXTRA_SECTION = "section" + const val EXTRA_THEME = "theme" + const val EXTRA_FONT_SCALE = "fontScale" + } +} + +enum class GallerySection(val title: String, val content: @Composable (ToastCenter) -> Unit) { + Foundations("Design tokens, type and icons", { FoundationSamples() }), + Controls("Buttons and controls", { ControlSamples() }), + Panels("Panels, tools and sheets", { PanelSamples() }), + Buttons("Buttons", { ButtonSamples() }), + Text("Error text, section header and stat label", { TextSamples() }), + Badges("Badges", { BadgeSamples() }), + Toasts("Toasts", { ToastSamples(it) }), + Images("Avatar and organisation icon", { ImageSamples() }), + Thumbnails("Thumbnails", { ThumbnailSamples() }), + EmptyStates("Empty state", { EmptyStateSamples() }), + Skeletons("Skeleton", { SkeletonSamples() }), +} + +@Composable +private fun Gallery(sections: List) { + val scope = rememberCoroutineScope() + val toasts = remember(scope) { ToastCenter(scope) } + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column( + modifier = + Modifier.verticalScroll(rememberScrollState()) + .windowInsetsPadding(WindowInsets.safeDrawing) + .padding(CapTheme.spacing), + verticalArrangement = Arrangement.spacedBy(24.dp), + ) { + for (section in sections) { + Column( + modifier = Modifier.testTag(section.name), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(text = section.title, style = CapType.caption) + section.content(toasts) + } + } + } + Box(contentAlignment = Alignment.TopCenter) { ToastHost(toasts) } + } +} + +@Composable +private fun ButtonSamples() { + InkButton(onClick = {}) { + Icon(painterResource(R.drawable.ic_mail), contentDescription = null) + Text("Continue with email") + } + InkButton(onClick = {}, enabled = false) { Text("Verify and sign in") } + ProviderButton(title = "Continue with Google", isLoading = false, onClick = {}) { + Image( + painterResource(R.drawable.ic_google), + contentDescription = null, + modifier = Modifier.size(18.dp), + ) + } + ProviderButton(title = "Continue with Google", isLoading = true, onClick = {}) {} + TonalButton(onClick = {}) { Text("Try again") } +} + +@Composable +private fun TextSamples() { + ErrorText("That code didn't work. Check it and try again.") + SectionHeader(title = "Caps", trailing = "128") + CompositionLocalProvider( + LocalTextStyle provides CapType.footnote.copy(fontWeight = FontWeight.Medium), + LocalContentColor provides MaterialTheme.colorScheme.onSurfaceVariant, + ) { + StatLabel(value = 1200, icon = R.drawable.ic_gallery_visibility, noun = "views") + } +} + +@Composable +private fun BadgeSamples() { + FlowRow( + modifier = + Modifier.background(CapTheme.colors.blue, RoundedCornerShape(CapTheme.controlRadius)) + .padding(12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + ScrimBadge(text = "12:34") + ScrimBadge(text = "Protected", icon = R.drawable.ic_lock) + } +} + +@Composable +private fun ToastSamples(center: ToastCenter) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + TonalButton(onClick = { center.show("Link copied") }) { Text("Success") } + TonalButton(onClick = { center.show(CapApiError.Offline) }) { Text("Error") } + TonalButton( + onClick = { + center.show( + "Recording was too short", + icon = R.drawable.ic_gallery_visibility, + style = Toast.Style.Info, + ) + } + ) { + Text("Info") + } + } +} + +@Composable +private fun ImageSamples() { + val image = LocalCapEnvironment.current.url("avatar.png") + FlowRow( + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + itemVerticalAlignment = Alignment.CenterVertically, + ) { + Avatar(name = "Richie McIlroy", imageUrl = null) + Avatar(name = "", imageUrl = null) + Avatar(name = "Richie McIlroy", imageUrl = null, size = 56.dp) + Avatar(name = "Richie McIlroy", imageUrl = image, size = 56.dp) + OrganizationIcon(name = "Cap", iconUrl = null) + OrganizationIcon(name = "Cap", iconUrl = null, size = 56.dp) + OrganizationIcon(name = "Cap", iconUrl = image, size = 56.dp) + } +} + +@Composable +private fun ThumbnailSamples() { + val image = LocalCapEnvironment.current.url("thumbnail.png") + CapThumbnail(cap = sampleCap("loaded", image, durationSeconds = 754.0, isProtected = true)) + CapThumbnail(cap = sampleCap("placeholder", null, durationSeconds = 42.0)) + CapThumbnail( + cap = + sampleCap( + "uploading", + null, + upload = + UploadProgress( + uploaded = 42.0, + total = 100.0, + phase = UploadPhase.UPLOADING, + processingMessage = null, + processingError = null, + ), + ) + ) + CapThumbnail( + cap = + sampleCap( + "failed", + null, + upload = + UploadProgress( + phase = UploadPhase.ERROR, + processingMessage = null, + processingError = null, + ), + ) + ) +} + +@Composable +private fun EmptyStateSamples() { + EmptyState( + icon = R.drawable.ic_warning, + title = "Couldn't load Caps", + description = "You're offline. Check your connection and try again.", + ) { + CapPrimaryButton("Try again", onClick = {}) + } + EmptyState(icon = R.drawable.ic_smart_display, title = "No Caps yet") + EmptyState( + icon = R.drawable.ic_warning, + title = "Couldn't open this link", + description = + "https://cap.so/s/0123456789abcdefghjkmnpqrstvwxyz0123456789abcdefghjkmnpqrstvwxyz", + ) +} + +@Composable +private fun SkeletonSamples() { + Column( + modifier = Modifier.shimmering().semantics { contentDescription = "Loading Caps" }, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + SkeletonBlock(Modifier.fillMaxWidth().aspectRatio(16f / 9f)) + SkeletonText("A placeholder Cap title", CapType.headline) + SkeletonText("2 hours ago · 120 views", CapType.subheadline) + } +} + +private fun sampleCap( + id: String, + thumbnailUrl: String?, + durationSeconds: Double? = null, + isProtected: Boolean = false, + upload: UploadProgress? = null, +) = + CapSummary( + id = id, + shareUrl = "https://cap.so/s/$id", + title = "Walkthrough", + createdAt = Instant.EPOCH, + updatedAt = Instant.EPOCH, + ownerId = null, + durationSeconds = durationSeconds, + thumbnailUrl = thumbnailUrl, + thumbnailCacheKey = null, + folderId = null, + isPublic = true, + isProtected = isProtected, + upload = upload, + ownedByCurrentUser = true, + ) diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryImageServer.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryImageServer.kt new file mode 100644 index 00000000000..048d1f7dfe3 --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/GalleryImageServer.kt @@ -0,0 +1,73 @@ +package so.cap.mobile + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Shader +import androidx.core.graphics.createBitmap +import java.io.ByteArrayOutputStream +import java.io.Closeable +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketException +import kotlin.concurrent.thread + +class GalleryImageServer : Closeable { + private val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")) + private val image: ByteArray = run { + val bitmap = createBitmap(640, 360) + val paint = Paint() + paint.shader = + LinearGradient( + 0f, + 0f, + 640f, + 360f, + intArrayOf(0xFF1E3A8A.toInt(), 0xFF4785FF.toInt(), 0xFFFFCC00.toInt()), + null, + Shader.TileMode.CLAMP, + ) + Canvas(bitmap).drawPaint(paint) + ByteArrayOutputStream() + .also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + .toByteArray() + } + + val origin: String + get() = "http://127.0.0.1:${socket.localPort}" + + init { + thread(isDaemon = true) { + while (true) { + val connection = + try { + socket.accept() + } catch (_: SocketException) { + return@thread + } + try { + connection.use(::serve) + } catch (_: IOException) { + continue + } + } + } + } + + private fun serve(connection: Socket) { + val reader = connection.getInputStream().bufferedReader(Charsets.ISO_8859_1) + while (!reader.readLine().isNullOrEmpty()) continue + val head = + "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\n" + + "Content-Length: ${image.size}\r\nConnection: close\r\n\r\n" + val output = connection.getOutputStream() + output.write(head.toByteArray(Charsets.ISO_8859_1)) + output.write(image) + output.flush() + } + + override fun close() = socket.close() +} diff --git a/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/LaunchArguments.kt b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/LaunchArguments.kt new file mode 100644 index 00000000000..d265f5b9d0e --- /dev/null +++ b/apps/mobile-android/app/src/debug/kotlin/so/cap/mobile/LaunchArguments.kt @@ -0,0 +1,22 @@ +package so.cap.mobile + +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import so.cap.kit.ApiKeyValidator +import so.cap.kit.CapEnvironment +import so.cap.kit.CapId +import so.cap.kit.CredentialSnapshot + +object LaunchArguments { + const val API_BASE_URL = "capApiBaseUrl" + const val DEBUG_SESSION = "capDebugSession" + + fun session(argument: String, environment: CapEnvironment): CredentialSnapshot? { + val host = environment.baseUrl.toHttpUrlOrNull()?.host ?: return null + if (!CapEnvironment.isLocalDevelopmentHost(host)) return null + val parts = argument.split(':', limit = 2) + if (parts.size != 2) return null + val (apiKey, userId) = parts + if (!ApiKeyValidator.isPlausible(apiKey) || CapId.parse(userId) == null) return null + return CredentialSnapshot(apiKey, userId) + } +} diff --git a/apps/mobile-android/app/src/debug/res/drawable/ic_gallery_visibility.xml b/apps/mobile-android/app/src/debug/res/drawable/ic_gallery_visibility.xml new file mode 100644 index 00000000000..7bd0c4f9467 --- /dev/null +++ b/apps/mobile-android/app/src/debug/res/drawable/ic_gallery_visibility.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/debug/res/xml/network_security_config.xml b/apps/mobile-android/app/src/debug/res/xml/network_security_config.xml new file mode 100644 index 00000000000..6da0e74aee8 --- /dev/null +++ b/apps/mobile-android/app/src/debug/res/xml/network_security_config.xml @@ -0,0 +1,7 @@ + + + + localhost + 127.0.0.1 + + diff --git a/apps/mobile-android/app/src/main/AndroidManifest.xml b/apps/mobile-android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..9da78104b57 --- /dev/null +++ b/apps/mobile-android/app/src/main/AndroidManifest.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/mobile-android/app/src/main/assets/fonts/INTER_LICENSE.txt b/apps/mobile-android/app/src/main/assets/fonts/INTER_LICENSE.txt new file mode 100644 index 00000000000..9b2ca37b3ff --- /dev/null +++ b/apps/mobile-android/app/src/main/assets/fonts/INTER_LICENSE.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/CapApplication.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/CapApplication.kt new file mode 100644 index 00000000000..8598ad91990 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/CapApplication.kt @@ -0,0 +1,27 @@ +package so.cap.mobile + +import android.app.Application +import so.cap.kit.CapEnvironment +import so.cap.mobile.app.AppServices +import so.cap.mobile.app.PlaybackPreferences +import so.cap.mobile.app.imageDiskCache +import so.cap.mobile.features.cap.NowPlaying + +open class CapApplication : Application() { + private val imageCache by lazy { imageDiskCache(this) } + private val playback by lazy { + PlaybackPreferences(filesDir.resolve("datastore/playback.preferences_pb")) + } + val nowPlaying = NowPlaying() + private var provider = lazy { + AppServices(this, CapEnvironment.PRODUCTION, imageCache, playback) + } + + val services: AppServices + get() = provider.value + + protected fun pointAt(environment: CapEnvironment) { + if (provider.isInitialized() && services.environment == environment) return + provider = lazy { AppServices(this, environment, imageCache, playback) } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainActivity.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainActivity.kt new file mode 100644 index 00000000000..4986912af42 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainActivity.kt @@ -0,0 +1,242 @@ +package so.cap.mobile + +import android.content.ActivityNotFoundException +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.viewModels +import androidx.browser.auth.AuthTabIntent +import androidx.browser.customtabs.CustomTabsClient +import androidx.browser.customtabs.CustomTabsService +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.EaseInOut +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.core.net.toUri +import androidx.lifecycle.DEFAULT_ARGS_KEY +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.createSavedStateHandle +import androidx.lifecycle.viewmodel.MutableCreationExtras +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import so.cap.kit.AuthCallback +import so.cap.mobile.app.AppModel +import so.cap.mobile.app.AppVersion +import so.cap.mobile.app.Phase +import so.cap.mobile.app.SessionHolder +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.designsystem.LocalImageLoader +import so.cap.mobile.features.auth.SignInScreen +import so.cap.mobile.features.auth.authTabBrowser +import so.cap.mobile.features.cap.CapDetailModels +import so.cap.mobile.features.cap.LocalPictureInPicture +import so.cap.mobile.features.cap.PictureInPicture +import so.cap.mobile.features.cap.PictureInPictureContent +import so.cap.mobile.features.cap.PictureInPictureParamsEffect +import so.cap.mobile.features.settings.SettingsScreen + +class MainActivity : ComponentActivity() { + private val services + get() = (application as CapApplication).services + + private val model: AppModel by viewModels { + viewModelFactory { + initializer { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + AppModel( + services.vault, + services.api, + scope, + services.unauthorized, + services::removeLocalData, + MutableCreationExtras(this) + .apply { set(DEFAULT_ARGS_KEY, Bundle.EMPTY) } + .createSavedStateHandle(), + ) + } + } + } + + private val sessions: SessionHolder by viewModels { + viewModelFactory { + initializer { + val services = services + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + SessionHolder(model.phase, scope) { credentials, sessionScope -> + SessionModel(services.api, services.cache, credentials, sessionScope) + } + } + } + } + + private val capModels: CapDetailModels by viewModels { + viewModelFactory { + initializer { + CapDetailModels( + application, + services.api, + services.media, + services.playback, + (application as CapApplication).nowPlaying, + ) + } + } + } + + private lateinit var pictureInPicture: PictureInPicture + + private var browserClosed = false + + private val authTab = + AuthTabIntent.registerActivityResultLauncher(this) { result -> + val callback = result.resultUri?.takeIf { result.resultCode == AuthTabIntent.RESULT_OK } + when { + callback != null -> model.finishAuthTab(callback.toString()) + result.resultCode == AuthTabIntent.RESULT_CANCELED -> browserClosed = true + else -> signIn?.failProvider() + } + } + + private val signIn + get() = (model.phase.value as? Phase.SignedOut)?.signIn + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val pictureInPicture = PictureInPicture(this) + this.pictureInPicture = pictureInPicture + addOnPictureInPictureModeChangedListener { mode -> + pictureInPicture.modeChanged( + active = mode.isInPictureInPictureMode, + closed = lifecycle.currentState == Lifecycle.State.CREATED, + ) + } + if (savedInstanceState == null) intent?.dataString?.let(model::open) + setContent { + CompositionLocalProvider( + LocalImageLoader provides services.images, + LocalCapEnvironment provides services.environment, + LocalPictureInPicture provides pictureInPicture, + ) { + CapTheme { + PictureInPictureParamsEffect(pictureInPicture) + Box(Modifier.fillMaxSize()) { + Root(model, sessions, capModels, services.version, ::signInWith) + pictureInPicture.player?.let { PictureInPictureContent(it) } + } + } + } + } + } + + override fun onUserLeaveHint() { + super.onUserLeaveHint() + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) pictureInPicture.enterIfPlaying() + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + intent.dataString?.let(model::open) + } + + // A browser without Auth Tab returns through the cap://auth intent filter, and the platform + // delivers the closed tab's cancelled result before that intent. Waiting for onResume, which + // always follows onNewIntent, lets the callback be read while the sign-in is still pending. + override fun onResume() { + super.onResume() + if (browserClosed) { + browserClosed = false + signIn?.cancelProvider() + } + } + + private fun signInWith(provider: String) { + val signIn = signIn ?: return + val url = signIn.startProvider(provider)?.toUri() ?: return + val customTabs = Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION) + val customTabsBrowsers = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + packageManager.queryIntentServices( + customTabs, + PackageManager.ResolveInfoFlags.of(0), + ) + } else { + packageManager.queryIntentServices(customTabs, 0) + } + val browser = + authTabBrowser( + Intent(Intent.ACTION_VIEW, url).resolveActivity(packageManager)?.packageName, + customTabsBrowsers.map { it.serviceInfo.packageName }, + ) { + CustomTabsClient.isAuthTabSupported(this, it) + } + val tab = AuthTabIntent.Builder().setEphemeralBrowsingEnabled(true).build() + tab.intent.setPackage(browser) + try { + tab.launch(authTab, url, AuthCallback.SCHEME) + } catch (_: ActivityNotFoundException) { + signIn.failProvider() + } + } +} + +private const val PHASE_FADE_MILLIS = 300 + +@Composable +private fun Root( + model: AppModel, + sessions: SessionHolder, + capModels: CapDetailModels, + version: AppVersion, + onProvider: (String) -> Unit, +) { + val phase by model.phase.collectAsState() + AnimatedContent( + targetState = phase, + transitionSpec = { + fadeIn(tween(PHASE_FADE_MILLIS, easing = EaseInOut)) togetherWith + fadeOut(tween(PHASE_FADE_MILLIS, easing = EaseInOut)) + }, + contentKey = { (it as? Phase.SignedIn)?.credentials?.apiKey }, + ) { current -> + when (current) { + is Phase.SignedOut -> SignInScreen(current.signIn, current.notice, onProvider) + is Phase.SignedIn -> + sessions.session + ?.takeIf { it.credentials == current.credentials } + ?.let { session -> + MainShell( + session = session, + capModels = capModels, + shareLink = model.pendingShareLink, + onShareLinkOpened = { model.pendingShareLink = null }, + settings = { + SettingsScreen( + version, + model.isSigningOut, + onSignOut = { model.signOut() }, + ) + }, + ) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainShell.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainShell.kt new file mode 100644 index 00000000000..d0107972c08 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/MainShell.kt @@ -0,0 +1,326 @@ +package so.cap.mobile + +import androidx.activity.compose.BackHandler +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.NavigationBarItemDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import kotlinx.serialization.Serializable +import so.cap.kit.ShareTarget +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.ToastHost +import so.cap.mobile.features.cap.CapDetailModels +import so.cap.mobile.features.cap.CapDetailScreen +import so.cap.mobile.features.home.AddAction +import so.cap.mobile.features.home.FolderScreen +import so.cap.mobile.features.home.HomeScreen +import so.cap.mobile.features.home.OpenLinkSheet + +enum class AppTab(@StringRes val title: Int, @DrawableRes val icon: Int) { + Caps(R.string.tab_caps, R.drawable.ic_video_library), + Analytics(R.string.tab_analytics, R.drawable.ic_monitoring), + Settings(R.string.tab_settings, R.drawable.ic_settings), +} + +@Serializable +sealed interface Route : NavKey { + @Serializable data object Caps : Route + + @Serializable + data class Cap(val id: String, val startTime: Double? = null, val commentId: String? = null) : + Route + + @Serializable data class Folder(val id: String, val name: String, val spaceId: String?) : Route + + @Serializable data class Pending(val action: AddAction) : Route + + @Serializable data class CapEdit(val id: String, val title: String) : Route + + @Serializable data class CapAnalytics(val id: String, val title: String) : Route + + @Serializable data object Analytics : Route + + @Serializable data object Settings : Route +} + +@Composable +fun MainShell( + session: SessionModel, + capModels: CapDetailModels, + shareLink: ShareTarget?, + onShareLinkOpened: () -> Unit, + settings: @Composable () -> Unit, +) { + var tab by rememberSaveable { mutableStateOf(AppTab.Caps) } + var recorderOpen by rememberSaveable { mutableStateOf(false) } + val capsStack = rememberNavBackStack(Route.Caps) + val analyticsStack = rememberNavBackStack(Route.Analytics) + val settingsStack = rememberNavBackStack(Route.Settings) + val backStack = + when (tab) { + AppTab.Caps -> capsStack + AppTab.Analytics -> analyticsStack + AppTab.Settings -> settingsStack + } + + LaunchedEffect(capModels, capsStack) { + snapshotFlow { capsStack.filterIsInstance() }.collect(capModels::keep) + } + + LaunchedEffect(shareLink) { + val link = shareLink ?: return@LaunchedEffect + onShareLinkOpened() + tab = AppTab.Caps + capsStack.removeAll { it != Route.Caps } + capsStack.add(Route.Cap(link.id.rawValue, link.startTime, link.commentId)) + } + + var linkSheetOpen by rememberSaveable { mutableStateOf(false) } + val add: (AddAction) -> Unit = { action -> + when (action) { + AddAction.Record -> recorderOpen = true + AddAction.OpenLink -> linkSheetOpen = true + else -> capsStack.add(Route.Pending(action)) + } + } + if (linkSheetOpen) { + OpenLinkSheet( + onOpen = { id -> + linkSheetOpen = false + capsStack.add(Route.Cap(id.rawValue)) + }, + onCancel = { linkSheetOpen = false }, + ) + } + + BackHandler(enabled = tab != AppTab.Caps && backStack.size == 1) { tab = AppTab.Caps } + + Box(Modifier.fillMaxSize()) { + Scaffold( + modifier = if (recorderOpen) Modifier.clearAndSetSemantics {} else Modifier, + contentWindowInsets = WindowInsets(0), + bottomBar = { + NavigationBar { + TabItem(AppTab.Caps, selected = tab == AppTab.Caps) { tab = AppTab.Caps } + NavigationBarItem( + selected = false, + onClick = { recorderOpen = true }, + colors = tabColors(), + icon = { + Icon( + painterResource(R.drawable.ic_radio_button_checked), + contentDescription = null, + ) + }, + label = { Text(stringResource(R.string.tab_record)) }, + ) + TabItem(AppTab.Analytics, selected = tab == AppTab.Analytics) { + tab = AppTab.Analytics + } + TabItem(AppTab.Settings, selected = tab == AppTab.Settings) { + tab = AppTab.Settings + } + } + }, + ) { padding -> + NavDisplay( + backStack = backStack, + modifier = Modifier.padding(padding).consumeWindowInsets(padding), + onBack = { backStack.removeLastOrNull() }, + entryProvider = + entryProvider { + entry { + HomeScreen( + session = session, + onOpenFolder = { folder, scope -> + if (capsStack.lastOrNull() == Route.Caps) { + capsStack.add( + Route.Folder(folder.id, folder.name, scope.spaceId) + ) + } + }, + onOpenCap = { id -> + if (capsStack.lastOrNull() == Route.Caps) { + capsStack.add(Route.Cap(id.rawValue)) + } + }, + onAdd = add, + ) + } + entry { route -> + FolderScreen( + session = session, + folderId = route.id, + name = route.name, + scope = + route.spaceId?.let(LibraryScope::Space) + ?: LibraryScope.Personal, + onBack = { capsStack.removeLastOrNull() }, + onOpenCap = { id -> + if (capsStack.lastOrNull() == route) { + capsStack.add(Route.Cap(id.rawValue)) + } + }, + onAdd = add, + ) + } + entry { route -> + CapDetailScreen( + model = capModels.model(route, session), + player = capModels.player(route), + session = session, + onBack = { capsStack.removeLastOrNull() }, + onEdit = { cap -> capsStack.add(Route.CapEdit(cap.id, cap.title)) }, + onAnalytics = { cap -> + capsStack.add(Route.CapAnalytics(cap.id, cap.title)) + }, + ) + } + entry { route -> + BackPlaceholder( + title = stringResource(R.string.cap_action_edit), + body = route.title, + onBack = { capsStack.removeLastOrNull() }, + ) + } + entry { route -> + BackPlaceholder( + title = stringResource(R.string.cap_action_analytics), + body = route.title, + onBack = { capsStack.removeLastOrNull() }, + ) + } + entry { route -> + BackPlaceholder( + title = stringResource(route.action.label), + body = null, + onBack = { capsStack.removeLastOrNull() }, + ) + } + entry { PlaceholderPage(R.string.tab_analytics) } + entry { settings() } + }, + ) + } + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { + ToastHost(session.toasts) + } + AnimatedVisibility( + visible = recorderOpen, + enter = slideInVertically { it }, + exit = slideOutVertically { it }, + ) { + BackHandler { recorderOpen = false } + RecorderPlaceholder(onClose = { recorderOpen = false }) + } + } +} + +@Composable +private fun RowScope.TabItem( + tab: AppTab, + selected: Boolean, + onClick: () -> Unit, +) { + NavigationBarItem( + selected = selected, + onClick = onClick, + colors = tabColors(), + icon = { Icon(painterResource(tab.icon), contentDescription = null) }, + label = { Text(stringResource(tab.title)) }, + ) +} + +@Composable +private fun tabColors() = + NavigationBarItemDefaults.colors( + selectedIconColor = MaterialTheme.colorScheme.primary, + selectedTextColor = MaterialTheme.colorScheme.primary, + indicatorColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f), + ) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun PlaceholderPage(@StringRes title: Int) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Box { TopAppBar(title = { Text(stringResource(title)) }) } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun BackPlaceholder(title: String, body: String?, onBack: () -> Unit) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column { + TopAppBar( + title = { Text(title) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + painterResource(R.drawable.ic_arrow_back), + contentDescription = stringResource(R.string.navigate_back), + ) + } + }, + ) + if (body != null) Text(text = body, modifier = Modifier.padding(CapTheme.spacing)) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun RecorderPlaceholder(onClose: () -> Unit) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Box { + TopAppBar( + title = { Text(stringResource(R.string.tab_record)) }, + navigationIcon = { + IconButton(onClick = onClose) { + Icon( + painterResource(R.drawable.ic_close), + contentDescription = stringResource(R.string.recorder_close), + ) + } + }, + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppModel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppModel.kt new file mode 100644 index 00000000000..74dc76941fd --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppModel.kt @@ -0,0 +1,159 @@ +package so.cap.mobile.app + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import so.cap.kit.ApiKeySession +import so.cap.kit.CapApi +import so.cap.kit.CapApiException +import so.cap.kit.CredentialSnapshot +import so.cap.kit.DeepLink +import so.cap.kit.ShareTarget +import so.cap.mobile.features.auth.SignInModel + +sealed interface Phase { + class SignedOut(val signIn: SignInModel, val notice: String?) : Phase + + data class SignedIn(val credentials: CredentialSnapshot) : Phase +} + +class AppModel( + private val vault: CredentialVault, + private val api: CapApi, + private val scope: CoroutineScope, + unauthorized: Flow, + private val removeLocalData: suspend () -> Unit, + private val saved: SavedStateHandle, + private val now: () -> Long = System::currentTimeMillis, +) : ViewModel(scope) { + private val state = + MutableStateFlow( + vault.credentials?.let(Phase::SignedIn) + ?: signedOut(notice = null, pending = restoredProvider()) + ) + + val phase: StateFlow = state.asStateFlow() + + var isSigningOut: Boolean by mutableStateOf(false) + private set + + var pendingShareLink: ShareTarget? by mutableStateOf(null) + + init { + scope.launch { unauthorized.collect(::handleUnauthorized) } + } + + private fun signedOut(notice: String?, pending: SignInModel.Pending? = null): Phase = + Phase.SignedOut( + SignInModel( + api, + scope, + pending = pending, + onProviderPending = ::rememberProvider, + onSession = ::completeSignIn, + ), + notice, + ) + + private fun restoredProvider(): SignInModel.Pending? { + val provider = saved.get(PENDING_PROVIDER) + val state = saved.get(PENDING_STATE) + val age = saved.get(PENDING_SINCE)?.let { now() - it } + if ( + provider != null && + state != null && + age != null && + age in 0..PENDING_LIFETIME.inWholeMilliseconds + ) { + return SignInModel.Pending(provider, state) + } + rememberProvider(null) + return null + } + + private fun rememberProvider(pending: SignInModel.Pending?) { + if (pending == null) { + saved.remove(PENDING_PROVIDER) + saved.remove(PENDING_STATE) + saved.remove(PENDING_SINCE) + return + } + saved[PENDING_PROVIDER] = pending.provider + saved[PENDING_STATE] = pending.state + saved[PENDING_SINCE] = now() + } + + private fun handleUnauthorized(snapshot: CredentialSnapshot) { + if (!vault.clear(ifMatching = snapshot)) return + finishSignOut(notice = SESSION_EXPIRED) + } + + private fun finishSignOut(notice: String?) { + state.value = signedOut(notice) + scope.launch { removeLocalData() } + } + + fun signOut(): Job? { + if (isSigningOut || state.value !is Phase.SignedIn) return null + isSigningOut = true + return scope.launch { + try { + withTimeoutOrNull(REVOKE_TIMEOUT) { + try { + api.revokeSession() + } catch (_: CapApiException) {} + } + } finally { + vault.clear() + isSigningOut = false + finishSignOut(notice = null) + } + } + } + + fun open(url: String): Job? { + when (val link = DeepLink.parse(url)) { + is DeepLink.Share -> pendingShareLink = link.target + is DeepLink.AuthCallback -> return finishProvider(url, fromAuthTab = false) + DeepLink.StopScreenRecording, + null -> {} + } + return null + } + + fun finishAuthTab(url: String): Job? = finishProvider(url, fromAuthTab = true) + + private fun finishProvider(url: String, fromAuthTab: Boolean): Job? { + if (DeepLink.parse(url) !is DeepLink.AuthCallback) return null + return (state.value as? Phase.SignedOut)?.signIn?.finishProvider(url, fromAuthTab) + } + + suspend fun completeSignIn(session: ApiKeySession) { + val credentials = CredentialSnapshot(session.apiKey, session.userId) + withContext(Dispatchers.IO) { vault.replace(credentials) } + state.value = Phase.SignedIn(credentials) + } + + private companion object { + val REVOKE_TIMEOUT = 4.seconds + val PENDING_LIFETIME = 10.minutes + const val PENDING_PROVIDER = "pendingProvider" + const val PENDING_SINCE = "pendingProviderSince" + const val PENDING_STATE = "pendingProviderState" + const val SESSION_EXPIRED = "Your session expired. Sign in again." + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppServices.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppServices.kt new file mode 100644 index 00000000000..55fd3af08e9 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/AppServices.kt @@ -0,0 +1,66 @@ +package so.cap.mobile.app + +import android.content.Context +import coil3.ImageLoader +import coil3.disk.DiskCache +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import so.cap.kit.CapApi +import so.cap.kit.CapEnvironment +import so.cap.kit.CredentialSnapshot +import so.cap.kit.SnapshotCache + +class AppVersion(val name: String, val build: Long) + +class AppServices( + context: Context, + val environment: CapEnvironment, + val imageCache: DiskCache, + val playback: PlaybackPreferences, +) { + val version: AppVersion = + context.packageManager.getPackageInfo(context.packageName, 0).let { + AppVersion(it.versionName ?: "1.0", it.longVersionCode) + } + + val vault = CredentialVault(credentialStore(context, environment)) + + private val rejectedSessions = + Channel(capacity = 4, onBufferOverflow = BufferOverflow.DROP_OLDEST) + + val unauthorized: Flow = rejectedSessions.receiveAsFlow() + + val api = + CapApi( + environment = environment, + userAgent = "Cap-Android/${version.name} (${version.build})", + credentials = { vault.credentials }, + onUnauthorized = { rejectedSessions.trySend(it) }, + ) + + val media: OkHttpClient by lazy { + mediaHttpClient(MediaRequestInterceptor(environment, api::mediaHeaders)) + } + + val cache = SnapshotCache(context.cacheDir.resolve("snapshots")) + + val images: ImageLoader = + imageLoader( + context, + imageHttpClient(ImageRequestInterceptor(environment, headers = api::mediaHeaders)), + imageCache, + ) + + suspend fun removeLocalData() { + cache.removeAll() + withContext(Dispatchers.IO) { + images.memoryCache?.clear() + imageCache.clear() + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CapEdits.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CapEdits.kt new file mode 100644 index 00000000000..47626b98b58 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CapEdits.kt @@ -0,0 +1,68 @@ +package so.cap.mobile.app + +import so.cap.kit.CapSummary + +class CapEdits { + private class Visibility(var server: Boolean) { + val pending = sortedMapOf() + var saved = 0 + } + + private val visibility = mutableMapOf() + private val settled = mutableMapOf>() + private val deleted = mutableSetOf() + + var stamp = 0 + private set + + fun shown(caps: List, asked: Int): List = + caps + .filter { it.id !in deleted } + .map { cap -> + val pending = visibility[cap.id]?.pending + val isPublic = + if (pending != null) { + pending[pending.lastKey()] + } else { + settled[cap.id]?.takeIf { it.first > asked }?.second + } + if (isPublic == null) cap else cap.copy(isPublic = isPublic) + } + + fun beginVisibility(cap: CapSummary, wanted: Boolean): Int { + stamp += 1 + visibility.getOrPut(cap.id) { Visibility(cap.isPublic) }.pending[stamp] = wanted + return stamp + } + + fun visibilitySaved(id: String, token: Int, isPublic: Boolean): Boolean { + val state = finish(id, token) ?: return false + state.saved = token + state.server = isPublic + stamp += 1 + settled[id] = stamp to isPublic + return state.pending.isEmpty() || state.pending.lastKey() < token + } + + fun visibilityFailed(id: String, token: Int, server: Boolean? = null): Boolean? { + val state = finish(id, token) ?: return null + if (server != null) state.server = server + if (state.pending.isEmpty()) return state.server + val newest = state.pending.lastKey() + return state.pending[newest].takeIf { newest < token } + } + + private fun finish(id: String, token: Int): Visibility? { + val state = visibility[id] ?: return null + state.pending.remove(token) + if (state.pending.isEmpty()) visibility.remove(id) + return state.takeIf { token > it.saved } + } + + fun latestVisibility(id: String): Boolean? = + visibility[id]?.pending?.let { it[it.lastKey()] } ?: settled[id]?.second + + fun deleted(id: String) { + deleted += id + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CredentialVault.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CredentialVault.kt new file mode 100644 index 00000000000..d937ea34a1d --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/CredentialVault.kt @@ -0,0 +1,146 @@ +package so.cap.mobile.app + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.io.File +import java.io.IOException +import java.security.GeneralSecurityException +import java.security.KeyStore +import java.security.ProviderException +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import so.cap.kit.ApiKeyValidator +import so.cap.kit.CapEnvironment +import so.cap.kit.CapId +import so.cap.kit.CredentialSnapshot + +class CredentialStore( + private val file: File, + private val origin: String, + private val key: (fresh: Boolean) -> SecretKey, +) { + @Serializable private class Payload(val apiKey: String, val userId: String, val origin: String) + + fun load(): CredentialSnapshot? { + val payload = + try { + val sealed = file.readBytes() + if (sealed.size <= NONCE_BYTES) return null + val cipher = Cipher.getInstance(TRANSFORMATION) + val nonce = GCMParameterSpec(TAG_BITS, sealed, 0, NONCE_BYTES) + cipher.init(Cipher.DECRYPT_MODE, key(false), nonce) + val opened = cipher.doFinal(sealed, NONCE_BYTES, sealed.size - NONCE_BYTES) + Json.decodeFromString(opened.decodeToString()) + } catch (_: IOException) { + return null + } catch (_: GeneralSecurityException) { + return null + } catch (_: ProviderException) { + return null + } catch (_: IllegalArgumentException) { + return null + } + if ( + payload.origin != origin || + !ApiKeyValidator.isPlausible(payload.apiKey) || + CapId.parse(payload.userId) == null + ) { + return null + } + return CredentialSnapshot(payload.apiKey, payload.userId) + } + + fun save(credentials: CredentialSnapshot) { + val payload = Payload(credentials.apiKey, credentials.userId, origin) + val plain = Json.encodeToString(payload).encodeToByteArray() + val sealed = + try { + try { + seal(plain, fresh = false) + } catch (_: GeneralSecurityException) { + seal(plain, fresh = true) + } catch (_: ProviderException) { + seal(plain, fresh = true) + } + } catch (error: GeneralSecurityException) { + throw IOException(error) + } catch (error: ProviderException) { + throw IOException(error) + } + val pending = File(file.path + ".pending") + pending.writeBytes(sealed) + if (!pending.renameTo(file)) { + pending.delete() + throw IOException("Could not replace the saved session") + } + } + + fun delete() { + file.delete() + } + + private fun seal(plain: ByteArray, fresh: Boolean): ByteArray { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, key(fresh)) + return cipher.iv + cipher.doFinal(plain) + } + + private companion object { + const val TRANSFORMATION = "AES/GCM/NoPadding" + const val NONCE_BYTES = 12 + const val TAG_BITS = 128 + } +} + +class CredentialVault(private val store: CredentialStore) { + private var current: CredentialSnapshot? = store.load() + + val credentials: CredentialSnapshot? + @Synchronized get() = current + + @Synchronized + fun replace(credentials: CredentialSnapshot) { + store.save(credentials) + current = credentials + } + + @Synchronized + fun clear(ifMatching: CredentialSnapshot? = null): Boolean { + if (ifMatching != null && current != ifMatching) return false + current = null + store.delete() + return true + } +} + +fun credentialStore(context: Context, environment: CapEnvironment): CredentialStore = + CredentialStore(File(context.noBackupFilesDir, "session"), environment.baseUrl, ::keystoreKey) + +private const val KEYSTORE = "AndroidKeyStore" +private const val KEY_ALIAS = "so.cap.mobile.session" + +private fun keystoreKey(fresh: Boolean): SecretKey { + val keystore = KeyStore.getInstance(KEYSTORE).apply { load(null) } + if (fresh) { + keystore.deleteEntry(KEY_ALIAS) + } else { + (keystore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { + return it + } + } + val purposes = KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + val spec = + KeyGenParameterSpec.Builder(KEY_ALIAS, purposes) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE) + .apply { init(spec) } + .generateKey() +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/FolderDraft.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/FolderDraft.kt new file mode 100644 index 00000000000..c0c8fbd8897 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/FolderDraft.kt @@ -0,0 +1,30 @@ +package so.cap.mobile.app + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import so.cap.kit.FolderColor + +class FolderDraft(val scope: LibraryScope) { + val name = TextFieldState() + + var color: FolderColor by mutableStateOf(FolderColor.NORMAL) + + var isSaving: Boolean by mutableStateOf(false) + internal set + + var error: String? by mutableStateOf(null) + internal set + + companion object { + const val NAME_LIMIT = 100 + + fun keptLength(name: CharSequence): Int = + when { + name.length <= NAME_LIMIT -> name.length + name[NAME_LIMIT - 1].isHighSurrogate() -> NAME_LIMIT - 1 + else -> NAME_LIMIT + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ImagePipeline.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ImagePipeline.kt new file mode 100644 index 00000000000..1ee49a16e98 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ImagePipeline.kt @@ -0,0 +1,94 @@ +package so.cap.mobile.app + +import android.content.Context +import coil3.ImageLoader +import coil3.disk.DiskCache +import coil3.memory.MemoryCache +import coil3.network.okhttp.OkHttpNetworkFetcherFactory +import java.io.IOException +import java.util.concurrent.TimeUnit +import okhttp3.Dispatcher +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Response +import okhttp3.ResponseBody.Companion.asResponseBody +import okio.Buffer +import okio.ForwardingSource +import okio.Path.Companion.toOkioPath +import okio.buffer +import so.cap.kit.CapEnvironment + +class ImageRequestInterceptor( + private val environment: CapEnvironment, + private val maxDownloadBytes: Long = MAX_DOWNLOAD_BYTES, + private val headers: (String) -> Map, +) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val sameOrigin = environment.isSameOrigin(request.url.toString()) + if (!sameOrigin && !request.isHttps) { + throw IOException("Refused an image request to an insecure host") + } + val builder = request.newBuilder().header("Accept", "image/*") + if (sameOrigin) { + headers(request.url.toString()).forEach(builder::header) + } else { + PRIVATE_HEADERS.forEach(builder::removeHeader) + } + return chain.proceed(builder.build()) + } + + fun limited(response: Response): Response { + val body = response.body + if (body.contentLength() > maxDownloadBytes) { + response.close() + throw IOException("Image is larger than $maxDownloadBytes bytes") + } + val limited = + object : ForwardingSource(body.source()) { + private var received = 0L + + override fun read(sink: Buffer, byteCount: Long): Long { + val read = super.read(sink, byteCount) + if (read > 0) received += read + if (received > maxDownloadBytes) { + throw IOException("Image is larger than $maxDownloadBytes bytes") + } + return read + } + } + return response + .newBuilder() + .body(limited.buffer().asResponseBody(body.contentType(), body.contentLength())) + .build() + } + + companion object { + const val MAX_DOWNLOAD_BYTES = 25L * 1024 * 1024 + val PRIVATE_HEADERS = listOf("Authorization", "X-Cap-Video-Access") + } +} + +fun imageHttpClient(interceptor: ImageRequestInterceptor): OkHttpClient = + OkHttpClient.Builder() + .connectTimeout(20, TimeUnit.SECONDS) + .readTimeout(20, TimeUnit.SECONDS) + .dispatcher(Dispatcher().apply { maxRequestsPerHost = 8 }) + // The size limit is applied out here because a network interceptor sees a gzip body + // before OkHttp expands it, so a small compressed body could carry a huge image past it. + .addInterceptor { chain -> interceptor.limited(chain.proceed(chain.request())) } + .addNetworkInterceptor(interceptor) + .build() + +fun imageDiskCache(context: Context): DiskCache = + DiskCache.Builder() + .directory(context.cacheDir.resolve("so.cap.mobile.images").toOkioPath()) + .maxSizeBytes(150L * 1024 * 1024) + .build() + +fun imageLoader(context: Context, client: OkHttpClient, diskCache: DiskCache): ImageLoader = + ImageLoader.Builder(context) + .components { add(OkHttpNetworkFetcherFactory(callFactory = { client })) } + .memoryCache { MemoryCache.Builder().maxSizeBytes(96L * 1024 * 1024).build() } + .diskCache(diskCache) + .build() diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/LibraryModel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/LibraryModel.kt new file mode 100644 index 00000000000..2879d67444d --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/LibraryModel.kt @@ -0,0 +1,345 @@ +package so.cap.mobile.app + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeMark +import kotlin.time.TimeSource +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapApiException +import so.cap.kit.CapSummary +import so.cap.kit.CapsPage +import so.cap.kit.Folder +import so.cap.kit.SnapshotCache +import so.cap.kit.UploadPhase + +sealed interface LibraryScope { + data object Personal : LibraryScope + + data class Space(val id: String) : LibraryScope + + val spaceId: String? + get() = (this as? Space)?.id +} + +enum class LibrarySort { + NEWEST, + OLDEST, + MOST_VIEWED, + LONGEST, + NAME, +} + +data class LibraryKey( + val organizationId: String, + val scope: LibraryScope, + val folderId: String?, +) { + val cacheKey: String + get() = + listOf("caps", organizationId, scope.spaceId ?: "personal", folderId ?: "root") + .joinToString("-") +} + +class LibraryModel( + val key: LibraryKey, + private val api: CapApi, + private val cache: SnapshotCache, + private val userId: String, + private val toasts: ToastCenter, + parent: CoroutineScope, + private val timeSource: TimeSource, + private val edits: CapEdits = CapEdits(), + private val awaitOrganization: suspend () -> Unit = {}, +) { + sealed interface Status { + data object Idle : Status + + data object Loading : Status + + data object Loaded : Status + + data class Failed(val error: CapApiError) : Status + } + + var caps: List by mutableStateOf(emptyList()) + private set + + var folders: List by mutableStateOf(emptyList()) + private set + + var folderInsertionStamp: Int by mutableIntStateOf(0) + private set + + var status: Status by mutableStateOf(Status.Idle) + private set + + var total: Int by mutableIntStateOf(0) + private set + + var hasMore: Boolean by mutableStateOf(false) + private set + + var isLoadingMore: Boolean by mutableStateOf(false) + private set + + var loadMoreError: CapApiError? by mutableStateOf(null) + private set + + var sort: LibrarySort by mutableStateOf(LibrarySort.NEWEST) + private set + + var showingOfflineCache: Boolean by mutableStateOf(false) + private set + + private val scope = CoroutineScope(parent.coroutineContext + Job(parent.coroutineContext[Job])) + private var generation = 0 + private var page = 1 + private var lastRefresh: TimeMark? = null + private var poll: Job? = null + private var paused = false + private var snapshot: Pair? = null + private var refreshOwed = false + private var added = emptyList>() + + internal val isPolling: Boolean + get() = poll?.isActive == true + + val isEmpty: Boolean + get() = caps.isEmpty() && folders.isEmpty() + + val availableSorts: List + get() = if (hasMore) listOf(LibrarySort.NEWEST) else LibrarySort.entries + + fun selectSort(next: LibrarySort): Boolean { + if (next !in availableSorts) return false + sort = next + caps = sortedCaps(caps) + return true + } + + private fun sortedCaps(list: List): List = + when (sort) { + LibrarySort.NEWEST -> list.sortedWith(compareByDescending { it.createdAt }) + LibrarySort.OLDEST -> list.sortedWith(compareBy { it.createdAt }) + LibrarySort.MOST_VIEWED -> + list.sortedWith( + compareByDescending { it.viewCount } + .thenByDescending { it.createdAt } + ) + LibrarySort.LONGEST -> + list.sortedWith( + compareByDescending { it.durationSeconds ?: -1.0 } + .thenByDescending { it.createdAt } + ) + LibrarySort.NAME -> + list.sortedWith( + compareBy { it.title.lowercase() }.thenByDescending { it.createdAt } + ) + } + + fun loadIfNeeded(): Job { + paused = false + return scope.launch { + if (status == Status.Idle && caps.isEmpty()) { + val cached = cache.read(CapsPage.serializer(), userId, key.cacheKey) + if (cached != null && caps.isEmpty()) { + snapshot = cached to edits.stamp + apply(cached, edits.stamp) + status = Status.Loaded + } + } + val refreshedRecently = lastRefresh?.let { it.elapsedNow() < REFRESH_AFTER } ?: false + if (!refreshedRecently) load() else schedulePolling() + } + } + + fun pausePolling() { + paused = true + poll?.cancel() + } + + fun refresh(): Job = scope.launch { load() } + + private suspend fun load(): Boolean { + awaitOrganization() + generation += 1 + val current = generation + val asked = edits.stamp + if (isEmpty) status = Status.Loading + try { + val first = api.listCaps(key.folderId, key.scope.spaceId, page = 1, limit = PAGE_SIZE) + awaitOrganization() + if (current != generation) return true + refreshOwed = false + apply(first, asked) + showingOfflineCache = false + status = Status.Loaded + lastRefresh = timeSource.markNow() + loadMoreError = null + snapshot = first to asked + saveSnapshot() + schedulePolling() + if (caps.isEmpty()) loadMore()?.join() + return true + } catch (failure: CapApiException) { + if (current != generation) return true + showingOfflineCache = + failure.error == CapApiError.Offline && snapshot != null && caps.isNotEmpty() + if (isEmpty) status = Status.Failed(failure.error) else toasts.show(failure.error) + return false + } + } + + fun loadMoreIfNeeded(after: CapSummary): Job? { + val index = caps.indexOfFirst { it.id == after.id } + if (index < 0 || index < caps.size - LOAD_MORE_WITHIN || loadMoreError != null) return null + return loadMore() + } + + fun retryLoadMore(): Job? { + loadMoreError = null + return loadMore() + } + + private fun loadMore(): Job? { + if (!hasMore || isLoadingMore) return null + isLoadingMore = true + val current = generation + val asked = edits.stamp + return scope.launch { + try { + do { + awaitOrganization() + val next = + api.listCaps(key.folderId, key.scope.spaceId, page + 1, limit = PAGE_SIZE) + awaitOrganization() + if (current != generation) return@launch + val known = caps.mapTo(mutableSetOf()) { it.id } + val added = edits.shown(next.caps.filter { it.id !in known }, asked) + caps = sortedCaps(caps + added) + hasMore = next.hasMore && next.page > page + page = next.page + total = next.total + } while (added.isEmpty() && hasMore) + schedulePolling() + } catch (failure: CapApiException) { + if (current == generation) loadMoreError = failure.error + } finally { + isLoadingMore = false + } + } + } + + private fun apply(first: CapsPage, asked: Int) { + if (first.hasMore) sort = LibrarySort.NEWEST + caps = sortedCaps(edits.shown(first.caps, asked)) + if (key.folderId == null) { + added = added.filter { it.first == generation } + val listed = first.folders.mapTo(mutableSetOf()) { it.id } + folders = added.map { it.second }.filter { it.id !in listed } + first.folders + } + page = first.page + hasMore = first.hasMore + total = first.total - (first.caps.size - caps.size) + } + + internal suspend fun saveSnapshot() { + val (first, asked) = snapshot ?: return + val shown = edits.shown(first.caps, asked) + cache.write( + CapsPage.serializer(), + first.copy(caps = shown, total = first.total - (first.caps.size - shown.size)), + userId, + key.cacheKey, + ) + } + + internal fun insert(folder: Folder) { + if (folders.any { it.id == folder.id }) return + added = listOf(generation to folder) + added + folders = listOf(folder) + folders + folderInsertionStamp += 1 + } + + internal fun update(id: String, change: (CapSummary) -> CapSummary) { + caps = sortedCaps(caps.map { if (it.id == id) change(it) else it }) + } + + internal fun remove(id: String) { + if (caps.none { it.id == id }) return + caps = caps.filter { it.id != id } + total -= 1 + } + + private fun processingIds(): List = + caps.filter { it.isProcessing && it.isOwned(userId) }.map { it.id } + + private fun schedulePolling() { + poll?.cancel() + if (paused || processingIds().isEmpty()) return + poll = + scope.launch(start = CoroutineStart.UNDISPATCHED) { + pollWithBackoff(POLL_FIRST, POLL_LONGEST, ::pollOnce) + } + } + + internal suspend fun pollOnce(): Boolean { + val ids = processingIds() + if (ids.isEmpty()) return !refreshOwed || load() + val statuses = + try { + api.capStatuses(ids).associateBy { it.id } + } catch (failure: CapApiException) { + return failure.error == CapApiError.Unauthorized + } + var finished = false + caps = + sortedCaps( + caps.map { cap -> + val status = statuses[cap.id] ?: return@map cap + if (status.upload == null || status.upload?.phase == UploadPhase.COMPLETE) { + finished = true + } + cap.copy(upload = status.upload) + } + ) + if (finished) refreshOwed = true + return refreshOwed && load() + } + + fun cancel() { + scope.cancel() + } + + companion object { + const val PAGE_SIZE = 30 + const val LOAD_MORE_WITHIN = 6 + val REFRESH_AFTER = 20.seconds + val POLL_FIRST = 3.seconds + val POLL_LONGEST = 15.seconds + } +} + +internal suspend fun pollWithBackoff( + first: Duration, + longest: Duration, + once: suspend () -> Boolean, +) { + var wait = first + while (true) { + delay(wait) + if (once()) return + wait = (wait * 1.5).coerceAtMost(longest) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/MediaHttp.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/MediaHttp.kt new file mode 100644 index 00000000000..726c1e00965 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/MediaHttp.kt @@ -0,0 +1,50 @@ +package so.cap.mobile.app + +import java.io.IOException +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runInterruptible +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import so.cap.kit.CapEnvironment + +class MediaRequestInterceptor( + private val environment: CapEnvironment, + private val headers: (String) -> Map, +) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val sameOrigin = environment.isSameOrigin(request.url.toString()) + if (!sameOrigin && !request.isHttps) { + throw IOException("Refused a media request to an insecure host") + } + val builder = request.newBuilder() + if (sameOrigin) { + headers(request.url.toString()).forEach(builder::header) + } else { + ImageRequestInterceptor.PRIVATE_HEADERS.forEach(builder::removeHeader) + } + return chain.proceed(builder.build()) + } +} + +fun mediaHttpClient(interceptor: MediaRequestInterceptor): OkHttpClient = + OkHttpClient.Builder() + .connectTimeout(20, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .addNetworkInterceptor(interceptor) + .build() + +suspend fun OkHttpClient.text(url: String, maxBytes: Long = 4L * 1024 * 1024): String = + runInterruptible(Dispatchers.IO) { + val request = + Request.Builder().url(url).header("Accept", "text/vtt, text/plain, */*").build() + newCall(request).execute().use { response -> + if (!response.isSuccessful) throw IOException("HTTP ${response.code}") + val source = response.body.source() + if (source.request(maxBytes + 1)) throw IOException("Response is too large") + source.buffer.readUtf8() + } + } diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/PlaybackPreferences.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/PlaybackPreferences.kt new file mode 100644 index 00000000000..9d7f3e9744e --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/PlaybackPreferences.kt @@ -0,0 +1,47 @@ +package so.cap.mobile.app + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.doublePreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.emptyPreferences +import java.io.File +import java.io.IOException +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.first +import so.cap.kit.CapViewer + +class PlaybackPreferences(file: File) { + private val store: DataStore = + PreferenceDataStoreFactory.create(produceFile = { file }) + + private suspend fun current(): Preferences = + store.data + .catch { failure -> + if (failure is IOException) emit(emptyPreferences()) else throw failure + } + .first() + + suspend fun speed(): Float = current()[SPEED]?.let(CapViewer::nearestSpeed) ?: 1f + + suspend fun setSpeed(value: Float) { + try { + store.edit { it[SPEED] = value.toDouble() } + } catch (_: IOException) {} + } + + suspend fun captionsEnabled(): Boolean = current()[CAPTIONS] ?: true + + suspend fun setCaptionsEnabled(value: Boolean) { + try { + store.edit { it[CAPTIONS] = value } + } catch (_: IOException) {} + } + + private companion object { + val SPEED = doublePreferencesKey("playback.speed") + val CAPTIONS = booleanPreferencesKey("captions.enabled") + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/SessionModel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/SessionModel.kt new file mode 100644 index 00000000000..c54c2d0a780 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/SessionModel.kt @@ -0,0 +1,423 @@ +package so.cap.mobile.app + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import kotlin.time.TimeSource +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.builtins.serializer +import so.cap.kit.Bootstrap +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapApiException +import so.cap.kit.CapId +import so.cap.kit.CapSummary +import so.cap.kit.CredentialSnapshot +import so.cap.kit.LinkAccess +import so.cap.kit.Organization +import so.cap.kit.PlanStatus +import so.cap.kit.SnapshotCache +import so.cap.kit.Space +import so.cap.mobile.R + +class SessionModel( + private val api: CapApi, + private val cache: SnapshotCache, + val credentials: CredentialSnapshot, + val scope: CoroutineScope, + private val timeSource: TimeSource = TimeSource.Monotonic, +) { + val toasts = ToastCenter(scope) + + var bootstrap: Bootstrap? by mutableStateOf(null) + private set + + var bootstrapError: CapApiError? by mutableStateOf(null) + private set + + var plan: PlanStatus? by mutableStateOf(null) + private set + + var libraryScope: LibraryScope by mutableStateOf(LibraryScope.Personal) + private set + + var isSwitchingOrganization: Boolean by mutableStateOf(false) + private set + + private var started = false + private var bootstrapRefresh: Job? = null + private var bootstrapGeneration = 0 + private var switching: Job? = null + private var scopeRestoredFor: String? = null + private val libraries = mutableMapOf() + private val edits = CapEdits() + private val deleting = mutableSetOf() + private val visibilityWrites = mutableMapOf() + + val organizationId: String? + get() = bootstrap?.let { it.activeOrganizationId ?: it.user.activeOrganizationId } + + val isPro: Boolean + get() = plan?.upgraded ?: false + + val spaces: List + get() = bootstrap?.spaces.orEmpty() + + val selectedSpace: Space? + get() = libraryScope.spaceId?.let { id -> spaces.firstOrNull { it.id == id } } + + val showsScopeBar: Boolean + get() = spaces.isNotEmpty() || (bootstrap?.organizations?.size ?: 0) > 1 + + val currentLibraryKey: LibraryKey? + get() = organizationId?.let { LibraryKey(it, libraryScope, folderId = null) } + + fun library(key: LibraryKey): LibraryModel = + libraries.getOrPut(key) { + LibraryModel(key, api, cache, credentials.userId, toasts, scope, timeSource, edits) { + switching?.join() + } + } + + fun start(): Job? { + if (started) return null + started = true + return scope.launch { + val cached = cache.read(Bootstrap.serializer(), credentials.userId, BOOTSTRAP_KEY) + if (cached != null && bootstrap == null) apply(cached, bootstrapGeneration) + joinAll(refreshBootstrap(), refreshPlan()) + } + } + + fun onEnd(block: () -> Unit) { + scope.launch(start = CoroutineStart.UNDISPATCHED) { + try { + awaitCancellation() + } finally { + block() + } + } + } + + fun refreshBootstrap(): Job { + bootstrapRefresh + ?.takeIf { it.isActive } + ?.let { + return it + } + val generation = bootstrapGeneration + val refresh = scope.launch { + val fresh = + try { + api.bootstrap() + } catch (failure: CapApiException) { + if (generation == bootstrapGeneration) bootstrapError = failure.error + return@launch + } + if (!apply(fresh, generation)) return@launch + bootstrapError = null + cache.write(Bootstrap.serializer(), fresh, credentials.userId, BOOTSTRAP_KEY) + } + bootstrapRefresh = refresh + return refresh + } + + fun refreshPlan(): Job = scope.launch { + try { + plan = api.plan() + } catch (_: CapApiException) {} + } + + // The remembered scope is read before anything changes, so that the bootstrap, the dropped + // libraries and the scope change together and no library is made for a scope about to change. + private suspend fun apply(fresh: Bootstrap, generation: Int): Boolean { + val organization = fresh.activeOrganizationId ?: fresh.user.activeOrganizationId + val remembered = + if (organization == scopeRestoredFor) { + null + } else { + cache.read(String.serializer(), credentials.userId, scopeKey(organization)) + } + if (generation != bootstrapGeneration) return false + if (organizationId != organization) { + libraries.values.forEach { it.cancel() } + libraries.clear() + } + bootstrap = fresh + val known = fresh.spaces.mapTo(mutableSetOf()) { it.id } + if (remembered != null && remembered in known) { + libraryScope = LibraryScope.Space(remembered) + } else if (libraryScope.spaceId?.let { it !in known } == true) { + libraryScope = LibraryScope.Personal + } + scopeRestoredFor = organization + return true + } + + fun select(selected: LibraryScope): Job? { + libraryScope = selected + val organization = organizationId ?: return null + return scope.launch { + val spaceId = selected.spaceId + if (spaceId == null) { + cache.remove(credentials.userId, scopeKey(organization)) + } else { + cache.write( + String.serializer(), + spaceId, + credentials.userId, + scopeKey(organization), + ) + } + } + } + + fun switchOrganization(organization: Organization): Job? { + if (organization.id == organizationId || isSwitchingOrganization) return null + isSwitchingOrganization = true + val switch = scope.launch { + try { + val fresh = api.setActiveOrganization(organization.id) + bootstrapGeneration += 1 + apply(fresh, bootstrapGeneration) + bootstrapError = null + toasts.show("Switched to ${organization.name}", icon = R.drawable.ic_domain) + cache.write(Bootstrap.serializer(), fresh, credentials.userId, BOOTSTRAP_KEY) + } catch (failure: CapApiException) { + toasts.show(failure.error) + } finally { + isSwitchingOrganization = false + } + } + switching = switch + return switch + } + + var folderDraft: FolderDraft? by mutableStateOf(null) + private set + + val canCreateFolder: Boolean + get() = + !isSwitchingOrganization && + (libraryScope == LibraryScope.Personal || selectedSpace?.canManage == true) + + fun beginFolder() { + if (canCreateFolder) folderDraft = FolderDraft(libraryScope) + } + + fun cancelFolder() { + folderDraft = null + } + + fun saveFolder(): Job? { + val draft = folderDraft ?: return null + val organization = organizationId ?: return null + val name = draft.name.text.trim().toString() + if (name.isEmpty() || draft.isSaving || isSwitchingOrganization) return null + draft.isSaving = true + draft.error = null + return scope.launch { + try { + val folder = api.createFolder(name, draft.color, draft.scope.spaceId) + libraries[LibraryKey(organization, draft.scope, folderId = null)]?.insert(folder) + toasts.show("Folder created", R.drawable.ic_folder) + if (folderDraft === draft) folderDraft = null + } catch (failure: CapApiException) { + draft.error = failure.error.description + } finally { + draft.isSaving = false + } + } + } + + fun setPublic( + cap: CapSummary, + isPublic: Boolean, + linkAccess: LinkAccess? = null, + ): Deferred? { + val id = CapId.parse(cap.id) ?: return null + val token = edits.beginVisibility(cap, isPublic) + libraries.values.forEach { library -> + library.update(cap.id) { + it.copy(isPublic = isPublic, linkAccess = linkAccess ?: it.linkAccess) + } + } + val writes = visibilityWrites.getOrPut(cap.id) { Mutex() } + return scope.async(start = CoroutineStart.UNDISPATCHED) { + writes.withLock { + var publishedFirst = false + try { + val updated = + if (linkAccess != null && isPublic && !cap.isPublic) { + api.updateSharing(id, isPublic) + publishedFirst = true + api.updateSharing(id, isPublic, linkAccess) + } else { + api.updateSharing(id, isPublic, linkAccess) + } + if (!edits.visibilitySaved(cap.id, token, updated.isPublic)) { + return@withLock SharingResult.Superseded(edits.latestVisibility(cap.id)) + } + libraries.values.toList().forEach { library -> + library.update(cap.id) { + it.copy( + isPublic = updated.isPublic, + linkAccess = updated.linkAccess, + linkRestricted = updated.linkRestricted, + ) + } + library.saveSnapshot() + } + val restricted = updated.isPublic && updated.linkRestricted == true + if (linkAccess != null) { + if (restricted) { + toasts.show( + "Only your organization's emails can view", + R.drawable.ic_domain, + ) + } else if (updated.isPublic) { + toasts.show("Anyone with the link can view", R.drawable.ic_public) + } + } else if (restricted) { + toasts.show( + "Only your organization's emails can view", + R.drawable.ic_public, + ) + } else if (isPublic) { + toasts.show("Anyone with the link can view", R.drawable.ic_public) + } else { + toasts.show("Only you and your team can view", R.drawable.ic_lock) + } + SharingResult.Saved(updated) + } catch (failure: CapApiException) { + var actual: CapSummary? = null + var actualVisibility: Boolean? = null + if (publishedFirst) { + try { + actual = api.updateSharing(id, isPublic = false) + actualVisibility = false + } catch (_: CapApiException) { + actual = + try { + api.cap(id).cap + } catch (_: CapApiException) { + null + } + actualVisibility = actual?.isPublic ?: true + } + } + val shown = + edits.visibilityFailed(cap.id, token, actualVisibility) + ?: return@withLock SharingResult.Superseded( + edits.latestVisibility(cap.id) + ) + val shownAccess = actual?.linkAccess ?: cap.linkAccess + val shownRestricted = actual?.linkRestricted ?: cap.linkRestricted + libraries.values.toList().forEach { library -> + library.update(cap.id) { + it.copy( + isPublic = shown, + linkAccess = shownAccess, + linkRestricted = shownRestricted, + ) + } + library.saveSnapshot() + } + toasts.show(failure.error) + SharingResult.Refused(shown, shownAccess, shownRestricted) + } + } + } + } + + fun capChanged(id: String, change: (CapSummary) -> CapSummary) { + libraries.values.forEach { library -> library.update(id, change) } + } + + fun delete(cap: CapSummary): Deferred? { + val id = CapId.parse(cap.id) ?: return null + if (!deleting.add(cap.id)) return null + return scope.async { + try { + api.deleteCap(id) + edits.deleted(cap.id) + libraries.values.toList().forEach { + it.remove(cap.id) + it.saveSnapshot() + } + toasts.show("Cap deleted", R.drawable.ic_delete) + true + } catch (failure: CapApiException) { + toasts.show(failure.error) + false + } finally { + deleting.remove(cap.id) + } + } + } + + fun ownerBlocked(capId: String) { + edits.deleted(capId) + libraries.values.forEach { library -> + library.remove(capId) + library.refresh() + } + } + + private fun scopeKey(organizationId: String) = "scope-$organizationId" + + private companion object { + const val BOOTSTRAP_KEY = "bootstrap" + } +} + +class SessionHolder( + phase: StateFlow, + scope: CoroutineScope, + private val create: (CredentialSnapshot, CoroutineScope) -> SessionModel, +) : ViewModel(scope) { + var session: SessionModel? by mutableStateOf(null) + private set + + private var sessionScope: CoroutineScope? = null + + init { + scope.launch { + phase.collect { current -> + val credentials = (current as? Phase.SignedIn)?.credentials + sessionScope?.cancel() + sessionScope = null + session = null + if (credentials == null) return@collect + val child = CoroutineScope(coroutineContext + SupervisorJob(coroutineContext[Job])) + sessionScope = child + session = create(credentials, child).also { it.start() } + } + } + } +} + +sealed interface SharingResult { + data class Saved(val cap: CapSummary) : SharingResult + + data class Refused( + val isPublic: Boolean, + val linkAccess: LinkAccess?, + val linkRestricted: Boolean?, + ) : SharingResult + + data class Superseded(val isPublic: Boolean?) : SharingResult +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ToastCenter.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ToastCenter.kt new file mode 100644 index 00000000000..e4ca5e4b678 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/ToastCenter.kt @@ -0,0 +1,63 @@ +package so.cap.mobile.app + +import androidx.annotation.DrawableRes +import java.util.UUID +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import so.cap.kit.CapApiError +import so.cap.mobile.R + +data class Toast( + val id: UUID, + val message: String, + @DrawableRes val icon: Int, + val style: Style, +) { + enum class Style { + Info, + Success, + Error, + } +} + +class ToastCenter(private val scope: CoroutineScope) { + private val state = MutableStateFlow(null) + private var dismissJob: Job? = null + + val current: StateFlow = state.asStateFlow() + + fun show( + message: String, + @DrawableRes icon: Int = R.drawable.ic_check_circle, + style: Toast.Style = Toast.Style.Success, + ) { + val toast = Toast(UUID.randomUUID(), message, icon, style) + state.value = toast + dismissJob?.cancel() + dismissJob = scope.launch { + delay(if (style == Toast.Style.Error) ERROR_DURATION else DEFAULT_DURATION) + dismiss(toast.id) + } + } + + fun show(error: CapApiError) { + if (error == CapApiError.Cancelled) return + show(error.description, icon = R.drawable.ic_warning, style = Toast.Style.Error) + } + + fun dismiss(id: UUID) { + state.update { if (it?.id == id) null else it } + } + + companion object { + val DEFAULT_DURATION = 2400.milliseconds + val ERROR_DURATION = 4000.milliseconds + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Avatar.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Avatar.kt new file mode 100644 index 00000000000..cda2361c4e2 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Avatar.kt @@ -0,0 +1,97 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import java.text.BreakIterator +import kotlin.math.roundToInt +import so.cap.kit.SafeUrl +import so.cap.mobile.R + +@Composable +fun Avatar(name: String, imageUrl: String?, modifier: Modifier = Modifier, size: Dp = 36.dp) { + val environment = LocalCapEnvironment.current + val density = LocalDensity.current + val request = + SafeUrl.media(imageUrl, environment)?.let { url -> + RemoteImageRequest( + url = url, + maxPixelSize = with(density) { size.toPx() }.roundToInt(), + ) + } + val initials = initials(name) + val blue = CapTheme.colors.blue + RemoteImage( + request = request, + modifier = + modifier + .size(size) + .clip(CircleShape) + .border( + 0.5.dp, + MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f), + CircleShape, + ) + .clearAndSetSemantics {}, + ) { + Box( + modifier = + Modifier.background( + Brush.verticalGradient(listOf(lerp(blue, Color.White, 0.18f), blue)) + ), + contentAlignment = Alignment.Center, + ) { + if (initials.isEmpty()) { + Icon( + painter = painterResource(R.drawable.ic_person), + contentDescription = null, + modifier = Modifier.size(size * 0.55f), + tint = Color.White.copy(alpha = 0.9f), + ) + } else { + Text( + text = initials, + color = Color.White, + style = + TextStyle( + fontSize = with(density) { (size * 0.4f).toSp() }, + fontWeight = FontWeight.SemiBold, + ), + ) + } + } + } +} + +internal fun initials(name: String): String = + name + .split(Regex("\\s+")) + .filter { it.isNotEmpty() } + .take(2) + .joinToString("") { it.firstCharacter().uppercase() } + +internal fun String.firstCharacter(): String { + val characters = BreakIterator.getCharacterInstance() + characters.setText(this) + val end = characters.next() + return if (end == BreakIterator.DONE) "" else substring(0, end) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Badges.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Badges.kt new file mode 100644 index 00000000000..d293c5b6f74 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Badges.kt @@ -0,0 +1,43 @@ +package so.cap.mobile.designsystem + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +@Composable +fun ScrimBadge(text: String, modifier: Modifier = Modifier, @DrawableRes icon: Int? = null) { + val style = CapType.caption.copy(fontWeight = FontWeight.SemiBold).monospacedDigit() + val iconSize = with(LocalDensity.current) { style.fontSize.toDp() } + Row( + modifier = + modifier + .background(Color.Black.copy(alpha = 0.55f), CircleShape) + .padding(horizontal = 8.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (icon != null) { + Icon( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.size(iconSize), + tint = Color.White, + ) + } + Text(text = text, color = Color.White, style = style) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Buttons.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Buttons.kt new file mode 100644 index 00000000000..b87bd779361 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Buttons.kt @@ -0,0 +1,205 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import so.cap.mobile.R + +@Composable +fun CapPrimaryButton( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, +) { + CapPrimaryButton(onClick = onClick, modifier = modifier, enabled = enabled) { Text(text) } +} + +@Composable +fun CapPrimaryButton( + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + height: Dp = 56.dp, + content: @Composable RowScope.() -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val pressed by interactionSource.collectIsPressedAsState() + val scale by + animateFloatAsState( + targetValue = if (pressed) CapMotion.PRESSED_SCALE else 1f, + animationSpec = CapMotion.press(), + ) + val ink = MaterialTheme.colorScheme.onSurface + val paper = MaterialTheme.colorScheme.surface + Button( + onClick = onClick, + modifier = + modifier.defaultMinSize(minHeight = height).graphicsLayer { + scaleX = scale + scaleY = scale + }, + enabled = enabled, + shape = RoundedCornerShape(CapTheme.controlRadius), + colors = + ButtonDefaults.buttonColors( + containerColor = ink, + contentColor = paper, + disabledContainerColor = CapTheme.colors.quietFill, + disabledContentColor = CapTheme.colors.textSecondary, + ), + contentPadding = PaddingValues(horizontal = 16.dp), + interactionSource = interactionSource, + ) { + ProvideTextStyle(CapType.rowTitle) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + content = content, + ) + } + } +} + +@Composable +fun CapSecondaryButton( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, +) { + CapSecondaryButton(onClick = onClick, modifier = modifier, enabled = enabled) { Text(text) } +} + +@Composable +fun CapSecondaryButton( + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + height: Dp = 56.dp, + content: @Composable RowScope.() -> Unit, +) { + val outline = MaterialTheme.colorScheme.outline + OutlinedButton( + onClick = onClick, + modifier = modifier.defaultMinSize(minHeight = height), + enabled = enabled, + shape = RoundedCornerShape(CapTheme.controlRadius), + colors = + ButtonDefaults.outlinedButtonColors( + contentColor = MaterialTheme.colorScheme.onSurface, + disabledContentColor = CapTheme.colors.textSecondary, + ), + border = + BorderStroke(CapTheme.hairline, if (enabled) outline else CapTheme.colors.hairline), + contentPadding = PaddingValues(horizontal = 16.dp), + ) { + ProvideTextStyle(CapType.rowTitle) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + content = content, + ) + } + } +} + +@Composable +fun InkButton( + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + content: @Composable RowScope.() -> Unit, +) { + CapPrimaryButton( + onClick = onClick, + modifier = modifier.fillMaxWidth(), + enabled = enabled, + height = 52.dp, + content = content, + ) +} + +@Composable +fun TonalButton( + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + content: @Composable RowScope.() -> Unit, +) { + CapSecondaryButton( + onClick = onClick, + modifier = modifier, + enabled = enabled, + height = 48.dp, + content = content, + ) +} + +@Composable +fun ProviderButton( + title: String, + isLoading: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable () -> Unit, +) { + val loadingLabel = stringResource(R.string.button_loading_label, title) + TonalButton( + onClick = onClick, + modifier = modifier.fillMaxWidth().defaultMinSize(minHeight = 56.dp), + enabled = enabled, + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isLoading) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp).clearAndSetSemantics {}, + color = LocalContentColor.current, + strokeWidth = 2.dp, + ) + } else { + icon() + } + Text( + text = title, + modifier = + if (isLoading) Modifier.semantics { contentDescription = loadingLabel } + else Modifier, + style = CapType.rowTitle, + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/CapThumbnail.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/CapThumbnail.kt new file mode 100644 index 00000000000..bbd9992d1bc --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/CapThumbnail.kt @@ -0,0 +1,160 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.math.ceil +import so.cap.kit.CapFormat +import so.cap.kit.CapSummary +import so.cap.kit.SafeUrl +import so.cap.kit.UploadPhase +import so.cap.kit.UploadProgress +import so.cap.mobile.R + +@Composable +fun CapThumbnail( + cap: CapSummary, + modifier: Modifier = Modifier, + cornerRadius: Dp = CapTheme.thumbnailRadius, + showsBadges: Boolean = true, +) { + val environment = LocalCapEnvironment.current + val upload = cap.upload + val duration = CapFormat.duration(cap.durationSeconds) + val showsUploadOverlay = + upload != null && (cap.isProcessing || upload.phase == UploadPhase.ERROR) + BoxWithConstraints( + modifier = + modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(RoundedCornerShape(cornerRadius)) + ) { + val widthPx = with(LocalDensity.current) { maxWidth.toPx() } + val request = + SafeUrl.media(cap.thumbnailUrl, environment)?.let { url -> + RemoteImageRequest( + url = url, + cacheKey = + cap.thumbnailCacheKey + ?: "cap-thumbnail:${cap.id}:${cap.updatedAt.toEpochMilli()}", + maxPixelSize = thumbnailBucket(widthPx), + ) + } + RemoteImage(request = request, modifier = Modifier.fillMaxSize()) { + ThumbnailPlaceholder(isProcessing = showsUploadOverlay) + } + if (showsBadges && duration != null && !cap.isProcessing) { + val label = stringResource(R.string.thumbnail_duration_label, duration) + ScrimBadge( + text = duration, + modifier = + Modifier.align(Alignment.BottomEnd).padding(8.dp).semantics { + contentDescription = label + }, + ) + } + if (showsBadges && cap.isProtected) { + ScrimBadge( + text = stringResource(R.string.thumbnail_protected), + modifier = Modifier.align(Alignment.TopStart).padding(8.dp), + icon = R.drawable.ic_lock, + ) + } + if (upload != null && showsUploadOverlay) { + UploadProgressOverlay(progress = upload) + } + } +} + +internal fun thumbnailBucket(widthPx: Float): Int = maxOf(320, ceil(widthPx / 160f).toInt() * 160) + +@Composable +fun ThumbnailPlaceholder(modifier: Modifier = Modifier, isProcessing: Boolean = false) { + Box( + modifier = + modifier.background( + Brush.linearGradient( + listOf( + CapTheme.colors.blueSoft.copy(alpha = 0.55f), + CapTheme.colors.blue.copy(alpha = 0.25f), + ) + ) + ), + contentAlignment = Alignment.Center, + ) { + if (!isProcessing) { + Icon( + painter = painterResource(R.drawable.ic_smart_display), + contentDescription = null, + modifier = Modifier.size(34.dp), + tint = Color.White.copy(alpha = 0.85f), + ) + } + } +} + +@Composable +fun UploadProgressOverlay(progress: UploadProgress, modifier: Modifier = Modifier) { + Box( + modifier = + modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f)).semantics( + mergeDescendants = true + ) {}, + contentAlignment = Alignment.Center, + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (progress.phase == UploadPhase.ERROR) { + Icon( + painter = painterResource(R.drawable.ic_warning), + contentDescription = null, + modifier = Modifier.size(28.dp), + tint = CapTheme.colors.caution, + ) + } else { + CircularProgressIndicator( + progress = { progress.fractionCompleted.toFloat() }, + modifier = Modifier.size(36.dp), + color = Color.White, + trackColor = Color.White.copy(alpha = 0.3f), + ) + } + Text( + text = progress.statusText, + modifier = Modifier.padding(horizontal = 12.dp), + color = Color.White, + textAlign = TextAlign.Center, + overflow = TextOverflow.Ellipsis, + maxLines = 2, + style = CapType.footnote.copy(fontWeight = FontWeight.SemiBold), + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Color.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Color.kt new file mode 100644 index 00000000000..ae9ee7c6c87 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Color.kt @@ -0,0 +1,235 @@ +package so.cap.mobile.designsystem + +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color + +object CapColorTokens { + val BackgroundLight = Color(0xFFFCFCFC) + val BackgroundDark = Color(0xFF111111) + val TextLight = Color(0xFF202020) + val TextDark = Color(0xFFEEEEEE) + val SecondaryTextLight = Color(0xFF646464) + val SecondaryTextDark = Color(0xFFB4B4B4) + val HairlineLight = Color(0xFFE0E0E0) + val HairlineDark = Color(0xFF2A2A2A) + val QuietFillLight = Color(0xFFE8E8E8) + val QuietFillDark = Color(0xFF2A2A2A) + val DialFaceLight = Color(0xFFF0F0F0) + val DialFaceDark = Color(0xFF191919) + val DialRimLight = Color(0xFFD9D9D9) + val DialRimDark = Color(0xFF3A3A3A) + val DialKnurlLight = Color(0xFFBBBBBB) + val DialKnurlDark = Color(0xFF606060) + val DialRing2Dark = Color(0xFF222222) + val SwitchOffLight = Color(0xFF8D8D8D) + val InactiveDark = Color(0xFF6E6E6E) + val Blue = Color(0xFF4785FF) + val BlueSoft = Color(0xFFADC9FF) + val RecordRed = Color(0xFFF74A3A) + val Green = Color(0xFF30A46C) + val Yellow = Color(0xFFFFD60A) + val Orange = Color(0xFFFF8A00) + val Sky = Color(0xFF2EB4FF) + val SkyTop = Color(0xFF0090FF) + val SkyBottom = Color(0xFFC5EAFF) + val Ink = Color(0xFF1B1B1B) + val White = Color(0xFFFFFFFF) +} + +object CapWallpaperColors { + val sky = listOf(CapColorTokens.SkyTop, CapColorTokens.Sky, CapColorTokens.SkyBottom) + val skySwatch = listOf(CapColorTokens.SkyTop, CapColorTokens.SkyBottom) + val duskSwatch = listOf(Color(0xFF2E3A6E), Color(0xFFF2A07B)) + val paper = Color(0xFFF0EEE8) + val ink = CapColorTokens.Ink + val inkBorder = Color(0xFF3A3A3A) + val mint = Color(0xFFBFE8D5) + val sand = Color(0xFFE7D9C4) + + val skyBrush = Brush.verticalGradient(sky) + val skySwatchBrush = Brush.verticalGradient(skySwatch) + val duskSwatchBrush = Brush.verticalGradient(duskSwatch) +} + +object CapAnnotationColors { + val blue = CapColorTokens.Blue + val sky = CapColorTokens.Sky + val yellow = CapColorTokens.Yellow + val orange = CapColorTokens.Orange + val green = CapColorTokens.Green + val white = CapColorTokens.White + val black = CapColorTokens.BackgroundDark + val blackBorder = Color(0xFF606060) + val all = listOf(blue, sky, yellow, orange, green, white, black) +} + +@Immutable +data class CapColors( + val background: Color, + val text: Color, + val textSecondary: Color, + val hairline: Color, + val quietFill: Color, + val dialFace: Color, + val dialRim: Color, + val dialKnurl: Color, + val dialRing1: Color, + val dialRing2: Color, + val mutedControl: Color, + val fineLine: Color, + val switchOffTrack: Color, + val editorBackground: Color, + val editorText: Color, + val editorTextSecondary: Color, + val editorHairline: Color, + val blue: Color, + val blueSoft: Color, + val record: Color, + val success: Color, + val warning: Color, + val caution: Color, + val purple: Color, +) + +internal val LightCapColors = + CapColors( + background = CapColorTokens.BackgroundLight, + text = CapColorTokens.TextLight, + textSecondary = CapColorTokens.SecondaryTextLight, + hairline = CapColorTokens.HairlineLight, + quietFill = CapColorTokens.QuietFillLight, + dialFace = CapColorTokens.DialFaceLight, + dialRim = CapColorTokens.DialRimLight, + dialKnurl = CapColorTokens.DialKnurlLight, + dialRing1 = CapColorTokens.HairlineLight, + dialRing2 = CapColorTokens.QuietFillLight, + mutedControl = CapColorTokens.DialKnurlLight, + fineLine = CapColorTokens.White.copy(alpha = 0.18f), + switchOffTrack = CapColorTokens.SwitchOffLight, + editorBackground = CapColorTokens.BackgroundDark, + editorText = CapColorTokens.TextDark, + editorTextSecondary = CapColorTokens.SecondaryTextDark, + editorHairline = CapColorTokens.HairlineDark, + blue = CapColorTokens.Blue, + blueSoft = CapColorTokens.BlueSoft, + record = CapColorTokens.RecordRed, + success = CapColorTokens.Green, + warning = CapColorTokens.Orange, + caution = CapColorTokens.Yellow, + purple = Color(0xFFAF52DE), + ) + +internal val DarkCapColors = + CapColors( + background = CapColorTokens.BackgroundDark, + text = CapColorTokens.TextDark, + textSecondary = CapColorTokens.SecondaryTextDark, + hairline = CapColorTokens.HairlineDark, + quietFill = CapColorTokens.QuietFillDark, + dialFace = CapColorTokens.DialFaceDark, + dialRim = CapColorTokens.DialRimDark, + dialKnurl = CapColorTokens.DialKnurlDark, + dialRing1 = CapColorTokens.HairlineDark, + dialRing2 = CapColorTokens.DialRing2Dark, + mutedControl = CapColorTokens.DialKnurlDark, + fineLine = Color.Black.copy(alpha = 0.16f), + switchOffTrack = CapColorTokens.InactiveDark, + editorBackground = CapColorTokens.BackgroundDark, + editorText = CapColorTokens.TextDark, + editorTextSecondary = CapColorTokens.SecondaryTextDark, + editorHairline = CapColorTokens.HairlineDark, + blue = CapColorTokens.Blue, + blueSoft = CapColorTokens.BlueSoft, + record = CapColorTokens.RecordRed, + success = CapColorTokens.Green, + warning = CapColorTokens.Orange, + caution = CapColorTokens.Yellow, + purple = Color(0xFFBF5AF2), + ) + +internal val LocalCapColors = staticCompositionLocalOf { LightCapColors } + +internal val LightColorScheme: ColorScheme = + lightColorScheme( + primary = CapColorTokens.Blue, + onPrimary = CapColorTokens.BackgroundDark, + primaryContainer = CapColorTokens.BlueSoft, + onPrimaryContainer = CapColorTokens.TextLight, + inversePrimary = CapColorTokens.Blue, + secondary = CapColorTokens.Blue, + onSecondary = CapColorTokens.BackgroundDark, + secondaryContainer = CapColorTokens.QuietFillLight, + onSecondaryContainer = CapColorTokens.TextLight, + tertiary = CapColorTokens.Blue, + onTertiary = CapColorTokens.BackgroundDark, + tertiaryContainer = CapColorTokens.BlueSoft, + onTertiaryContainer = CapColorTokens.TextLight, + background = CapColorTokens.BackgroundLight, + onBackground = CapColorTokens.TextLight, + surface = CapColorTokens.BackgroundLight, + onSurface = CapColorTokens.TextLight, + surfaceVariant = CapColorTokens.QuietFillLight, + onSurfaceVariant = CapColorTokens.SecondaryTextLight, + surfaceTint = CapColorTokens.Blue, + inverseSurface = CapColorTokens.TextLight, + inverseOnSurface = CapColorTokens.BackgroundLight, + error = Color(0xFFD70015), + onError = CapColorTokens.White, + errorContainer = Color(0xFFFFDAD6), + onErrorContainer = Color(0xFF410002), + outline = CapColorTokens.DialKnurlLight, + outlineVariant = CapColorTokens.HairlineLight, + scrim = Color.Black, + surfaceBright = CapColorTokens.BackgroundLight, + surfaceDim = CapColorTokens.QuietFillLight, + surfaceContainerLowest = CapColorTokens.BackgroundLight, + surfaceContainerLow = CapColorTokens.BackgroundLight, + surfaceContainer = CapColorTokens.QuietFillLight, + surfaceContainerHigh = CapColorTokens.QuietFillLight, + surfaceContainerHighest = CapColorTokens.HairlineLight, + ) + +internal val DarkColorScheme: ColorScheme = + darkColorScheme( + primary = CapColorTokens.Blue, + onPrimary = CapColorTokens.BackgroundDark, + primaryContainer = CapColorTokens.BlueSoft, + onPrimaryContainer = CapColorTokens.TextLight, + inversePrimary = CapColorTokens.Blue, + secondary = CapColorTokens.Blue, + onSecondary = CapColorTokens.BackgroundDark, + secondaryContainer = CapColorTokens.QuietFillDark, + onSecondaryContainer = CapColorTokens.TextDark, + tertiary = CapColorTokens.Blue, + onTertiary = CapColorTokens.BackgroundDark, + tertiaryContainer = CapColorTokens.BlueSoft, + onTertiaryContainer = CapColorTokens.TextLight, + background = CapColorTokens.BackgroundDark, + onBackground = CapColorTokens.TextDark, + surface = CapColorTokens.BackgroundDark, + onSurface = CapColorTokens.TextDark, + surfaceVariant = CapColorTokens.QuietFillDark, + onSurfaceVariant = CapColorTokens.SecondaryTextDark, + surfaceTint = CapColorTokens.Blue, + inverseSurface = CapColorTokens.TextDark, + inverseOnSurface = CapColorTokens.BackgroundDark, + error = Color(0xFFFF6B60), + onError = Color(0xFF410002), + errorContainer = Color(0xFF93000A), + onErrorContainer = Color(0xFFFFDAD6), + outline = CapColorTokens.DialKnurlDark, + outlineVariant = CapColorTokens.HairlineDark, + scrim = Color.Black, + surfaceBright = CapColorTokens.QuietFillDark, + surfaceDim = CapColorTokens.BackgroundDark, + surfaceContainerLowest = CapColorTokens.BackgroundDark, + surfaceContainerLow = CapColorTokens.DialFaceDark, + surfaceContainer = CapColorTokens.QuietFillDark, + surfaceContainerHigh = CapColorTokens.QuietFillDark, + surfaceContainerHighest = CapColorTokens.DialRimDark, + ) diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Controls.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Controls.kt new file mode 100644 index 00000000000..ad9d1051ae9 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Controls.kt @@ -0,0 +1,254 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.setProgress +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.dp +import kotlin.math.roundToInt + +@Composable +fun CapSwitch( + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + contentDescription: String? = null, +) { + val trackColor by + animateColorAsState( + if (checked) CapTheme.colors.blue else CapTheme.colors.switchOffTrack, + animationSpec = CapMotion.colour(), + ) + val knobTravel by + animateDpAsState(if (checked) 18.dp else 0.dp, animationSpec = CapMotion.colour()) + Box( + modifier = + modifier + .size(CapTheme.touchTarget) + .toggleable( + value = checked, + enabled = enabled, + role = Role.Switch, + onValueChange = onCheckedChange, + ) + .semantics { + if (contentDescription != null) this.contentDescription = contentDescription + }, + contentAlignment = Alignment.Center, + ) { + Box( + modifier = + Modifier.size(width = 44.dp, height = 26.dp) + .background(trackColor, CircleShape) + .padding(3.dp) + ) { + Box( + modifier = + Modifier.align(Alignment.CenterStart) + .offset { androidx.compose.ui.unit.IntOffset(knobTravel.roundToPx(), 0) } + .size(20.dp) + .background(Color.White, CircleShape) + ) + } + } +} + +@Composable +fun CapTickSlider( + label: String, + value: Int, + range: IntRange, + onValueChange: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + val currentOnValueChange by rememberUpdatedState(onValueChange) + Column(modifier) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Bottom, + ) { + Text(text = label, color = CapTheme.colors.textSecondary, style = CapType.body) + Text( + text = value.toString(), + color = MaterialTheme.colorScheme.onSurface, + style = CapType.sliderValue, + ) + } + Box( + modifier = + Modifier.fillMaxWidth() + .height(CapTheme.touchTarget) + .semantics { + progressBarRangeInfo = + ProgressBarRangeInfo( + value.toFloat(), + range.first.toFloat()..range.last.toFloat(), + ) + stateDescription = value.toString() + setProgress { target -> + onValueChange(target.roundToInt().coerceIn(range.first, range.last)) + true + } + } + .pointerInput(range) { + detectTapGestures { offset -> + currentOnValueChange(tickSliderValue(offset.x, size.width, range)) + } + } + .pointerInput(range) { + detectHorizontalDragGestures { change, _ -> + currentOnValueChange( + tickSliderValue(change.position.x, size.width, range) + ) + change.consume() + } + }, + contentAlignment = Alignment.BottomStart, + ) { + CapTickStrip( + fraction = + ((value - range.first).toFloat() / (range.last - range.first).coerceAtLeast(1)) + .coerceIn(0f, 1f), + modifier = Modifier.fillMaxWidth(), + ) + } + } +} + +private fun tickSliderValue(x: Float, width: Int, range: IntRange): Int { + if (width <= 0) return range.first + val fraction = (x / width).coerceIn(0f, 1f) + val span = range.last - range.first + return (range.first + span * fraction).roundToInt() +} + +@Composable +private fun CapTickStrip(fraction: Float, modifier: Modifier = Modifier) { + val tickColor = CapTheme.colors.mutedControl + val indexColor = CapTheme.colors.blue + val tickSpacing = 8.dp + val tickWidth = 1.dp + val indexWidth = 2.dp + Canvas(modifier.height(22.dp)) { + val spacing = tickSpacing.toPx() + val width = tickWidth.toPx() + var x = 0f + while (x <= size.width) { + drawLine( + color = tickColor, + start = Offset(x, size.height - 10.dp.toPx()), + end = Offset(x, size.height), + strokeWidth = width, + ) + x += spacing + } + val lineWidth = indexWidth.toPx() + val centre = (size.width * fraction).coerceIn(lineWidth / 2, size.width - lineWidth / 2) + drawRoundRect( + color = indexColor, + topLeft = Offset(centre - lineWidth / 2, 0f), + size = Size(lineWidth, size.height), + cornerRadius = CornerRadius(lineWidth / 2), + ) + } +} + +enum class CapNumericSize(val textStyle: TextStyle) { + Huge(CapType.hugeNumeric), + Count(CapType.libraryCount), + Option(CapType.bigOption), + Metric(CapType.largeMetric), + Notification(CapType.notificationNumeric), +} + +@Composable +fun CapLargeNumericReadout( + value: String, + modifier: Modifier = Modifier, + size: CapNumericSize = CapNumericSize.Huge, + color: Color = Color.Unspecified, +) { + Text(text = value, modifier = modifier, color = color, style = size.textStyle) +} + +@Composable +fun CapColorSwatch( + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, + color: Color = Color.Unspecified, + brush: Brush? = null, + size: Int = 40, + borderColor: Color = Color.Unspecified, +) { + val shape: Shape = RoundedCornerShape(CapTheme.controlRadius) + val outer = size.dp + 4.dp + Box( + modifier = + modifier + .size(outer) + .selectable(selected = selected, onClick = onClick, role = Role.RadioButton) + .semantics { contentDescription = label }, + contentAlignment = Alignment.Center, + ) { + Box( + modifier = + Modifier.size(size.dp) + .then( + if (selected) Modifier.border(2.dp, CapTheme.colors.editorText, shape) + else Modifier + ) + .padding(2.dp) + .then( + if (borderColor != Color.Unspecified) + Modifier.border(1.dp, borderColor, shape) + else Modifier + ) + .then( + if (brush != null) Modifier.background(brush, shape) + else Modifier.background(color, shape) + ) + ) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/EmptyState.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/EmptyState.kt new file mode 100644 index 00000000000..42c6c8e56e0 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/EmptyState.kt @@ -0,0 +1,65 @@ +package so.cap.mobile.designsystem + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp + +@Composable +fun EmptyState( + @DrawableRes icon: Int, + title: String, + modifier: Modifier = Modifier, + description: String? = null, + actions: (@Composable () -> Unit)? = null, +) { + Column( + modifier = modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.padding(bottom = 8.dp).size(52.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = title, + modifier = Modifier.semantics { heading() }, + textAlign = TextAlign.Center, + style = CapType.title2.copy(fontWeight = FontWeight.Bold), + ) + if (description != null) { + Text( + text = description, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + style = CapType.subheadline, + ) + } + if (actions != null) { + Column( + modifier = Modifier.padding(top = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + actions() + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/ErrorText.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/ErrorText.kt new file mode 100644 index 00000000000..5c6633c6046 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/ErrorText.kt @@ -0,0 +1,36 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.unit.dp +import so.cap.mobile.R + +@Composable +fun ErrorText(message: String, modifier: Modifier = Modifier) { + val label = stringResource(R.string.error_text_label, message) + val iconSize = with(LocalDensity.current) { CapType.footnote.lineHeight.toDp() } + Row( + modifier = modifier.fillMaxWidth().clearAndSetSemantics { contentDescription = label }, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Icon( + painter = painterResource(R.drawable.ic_error), + contentDescription = null, + modifier = Modifier.size(iconSize), + tint = MaterialTheme.colorScheme.error, + ) + Text(text = message, color = MaterialTheme.colorScheme.error, style = CapType.footnote) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/InAppBrowser.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/InAppBrowser.kt new file mode 100644 index 00000000000..b777c9bacfb --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/InAppBrowser.kt @@ -0,0 +1,12 @@ +package so.cap.mobile.designsystem + +import android.content.ActivityNotFoundException +import android.content.Context +import androidx.browser.customtabs.CustomTabsIntent +import androidx.core.net.toUri + +fun openInAppBrowser(context: Context, url: String) { + try { + CustomTabsIntent.Builder().build().launchUrl(context, url.toUri()) + } catch (_: ActivityNotFoundException) {} +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/OrganizationIcon.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/OrganizationIcon.kt new file mode 100644 index 00000000000..117c971b680 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/OrganizationIcon.kt @@ -0,0 +1,59 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.math.roundToInt +import so.cap.kit.SafeUrl + +@Composable +fun OrganizationIcon( + name: String, + iconUrl: String?, + modifier: Modifier = Modifier, + size: Dp = 28.dp, +) { + val environment = LocalCapEnvironment.current + val density = LocalDensity.current + val request = + SafeUrl.media(iconUrl, environment)?.let { url -> + RemoteImageRequest( + url = url, + maxPixelSize = with(density) { size.toPx() }.roundToInt(), + ) + } + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + RemoteImage( + request = request, + modifier = + modifier.size(size).clip(RoundedCornerShape(size * 0.28f)).clearAndSetSemantics {}, + ) { + Box( + modifier = Modifier.background(secondary.copy(alpha = 0.18f)), + contentAlignment = Alignment.Center, + ) { + Text( + text = name.firstCharacter().uppercase(), + color = secondary, + style = + TextStyle( + fontSize = with(density) { (size * 0.48f).toSp() }, + fontWeight = FontWeight.SemiBold, + ), + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Panels.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Panels.kt new file mode 100644 index 00000000000..c1210804c56 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Panels.kt @@ -0,0 +1,125 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +@Composable +fun CapPanelScaffold( + title: String, + onDone: () -> Unit, + modifier: Modifier = Modifier, + doneLabel: String = "Done", + content: @Composable ColumnScope.() -> Unit, +) { + Column(modifier) { + Row( + modifier = Modifier.fillMaxWidth().height(48.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = title, + color = MaterialTheme.colorScheme.onSurface, + style = CapType.panelTitle, + ) + CapTextAction(text = doneLabel, onClick = onDone) + } + content() + } +} + +@Composable +fun CapEditorToolItem( + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + Box( + modifier = + modifier + .defaultMinSize(minWidth = CapTheme.touchTarget) + .height(CapTheme.touchTarget) + .selectable(selected = selected, onClick = onClick, role = Role.Tab), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + color = + if (selected) MaterialTheme.colorScheme.onSurface + else CapTheme.colors.textSecondary, + style = + CapType.body.copy( + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium + ), + ) + } +} + +@Composable +fun CapSheetScaffold( + title: String, + onDone: () -> Unit, + modifier: Modifier = Modifier, + doneLabel: String = "Done", + content: @Composable ColumnScope.() -> Unit, +) { + Surface( + modifier = modifier, + shape = + RoundedCornerShape( + topStart = CapTheme.sheetRadius, + topEnd = CapTheme.sheetRadius, + ), + color = MaterialTheme.colorScheme.surface, + ) { + Column(Modifier.padding(start = 24.dp, top = 24.dp, end = 24.dp, bottom = 20.dp)) { + Row( + modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = title, + color = MaterialTheme.colorScheme.onSurface, + style = CapType.detailTitle, + ) + CapTextAction(text = doneLabel, onClick = onDone) + } + content() + } + } +} + +@Composable +fun CapTextAction(text: String, onClick: () -> Unit, modifier: Modifier = Modifier) { + Box( + modifier = + modifier + .defaultMinSize(minWidth = CapTheme.touchTarget) + .height(CapTheme.touchTarget) + .clickable(onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Text(text = text, color = MaterialTheme.colorScheme.onSurface, style = CapType.bodyStrong) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/RemoteImage.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/RemoteImage.kt new file mode 100644 index 00000000000..a344e91c93a --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/RemoteImage.kt @@ -0,0 +1,63 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import coil3.ImageLoader +import coil3.compose.AsyncImage +import coil3.request.ImageRequest +import coil3.request.crossfade +import coil3.size.Scale +import so.cap.kit.CapEnvironment + +val LocalImageLoader = staticCompositionLocalOf { null } + +val LocalCapEnvironment = staticCompositionLocalOf { CapEnvironment.PRODUCTION } + +data class RemoteImageRequest(val url: String, val cacheKey: String = url, val maxPixelSize: Int) { + val storageKey: String + get() = "$cacheKey@$maxPixelSize" +} + +@Composable +fun RemoteImage( + request: RemoteImageRequest?, + modifier: Modifier = Modifier, + placeholder: @Composable () -> Unit, +) { + val loader = LocalImageLoader.current + val context = LocalContext.current + var loadedKey by remember { mutableStateOf(null) } + Box(modifier = modifier, propagateMinConstraints = true) { + if (request == null || loader == null || loadedKey != request.storageKey) { + placeholder() + } + if (request != null && loader != null) { + AsyncImage( + model = + remember(request, context) { + ImageRequest.Builder(context) + .data(request.url) + .memoryCacheKey(request.storageKey) + .diskCacheKey(request.storageKey) + .size(request.maxPixelSize) + .scale(Scale.FIT) + .crossfade(CapMotion.IMAGE_FADE_MILLIS) + .build() + }, + contentDescription = null, + imageLoader = loader, + modifier = Modifier.matchParentSize(), + onSuccess = { loadedKey = request.storageKey }, + contentScale = ContentScale.Crop, + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Rows.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Rows.kt new file mode 100644 index 00000000000..a598f6aabf2 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Rows.kt @@ -0,0 +1,180 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.selection.selectable +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import so.cap.mobile.R + +@Composable +fun CapHairline(modifier: Modifier = Modifier) { + Box(modifier.fillMaxWidth().height(CapTheme.hairline).background(CapTheme.colors.hairline)) +} + +@Composable +fun ScreenTitleBlock( + title: String, + modifier: Modifier = Modifier, + description: String? = null, +) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = title, + color = MaterialTheme.colorScheme.onBackground, + style = CapType.screenTitle, + ) + if (description != null) { + Text(text = description, color = CapTheme.colors.textSecondary, style = CapType.body) + } + } +} + +@Composable +fun CapHairlineRow( + modifier: Modifier = Modifier, + minHeight: Dp = 60.dp, + topHairline: Boolean = true, + bottomHairline: Boolean = false, + contentPadding: PaddingValues = PaddingValues(0.dp), + horizontalArrangement: Arrangement.Horizontal = Arrangement.SpaceBetween, + content: @Composable RowScope.() -> Unit, +) { + Column(modifier) { + if (topHairline) CapHairline() + Row( + modifier = + Modifier.fillMaxWidth() + .defaultMinSize(minHeight = minHeight) + .padding(contentPadding), + horizontalArrangement = horizontalArrangement, + verticalAlignment = Alignment.CenterVertically, + content = content, + ) + if (bottomHairline) CapHairline() + } +} + +@Composable +fun CapRadioRow( + title: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, + subtitle: String? = null, + bottomHairline: Boolean = true, +) { + Row( + modifier = + modifier + .fillMaxWidth() + .defaultMinSize(minHeight = if (subtitle == null) 48.dp else 76.dp) + .selectable(selected = selected, onClick = onClick, role = Role.RadioButton), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + text = title, + color = + if (selected || subtitle != null) MaterialTheme.colorScheme.onSurface + else CapTheme.colors.textSecondary, + style = if (subtitle == null) CapType.rowTitle else CapType.panelTitle, + ) + if (subtitle != null) { + Text( + text = subtitle, + color = CapTheme.colors.textSecondary, + style = CapType.metadata, + ) + } + } + if (selected) { + Icon( + painter = painterResource(R.drawable.ic_cap_check), + contentDescription = null, + modifier = Modifier.size(if (subtitle == null) 20.dp else 22.dp), + tint = CapTheme.colors.blue, + ) + } + } + if (bottomHairline) CapHairline() +} + +@Composable +fun CapScopeSegmentedControl( + options: List, + selectedIndex: Int, + onSelected: (Int) -> Unit, + modifier: Modifier = Modifier, + trailing: @Composable () -> Unit = {}, +) { + Box(modifier.fillMaxWidth().height(45.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Row(horizontalArrangement = Arrangement.spacedBy(22.dp)) { + val underline = MaterialTheme.colorScheme.onSurface + options.forEachIndexed { index, label -> + val selected = index == selectedIndex + Text( + text = label, + modifier = + Modifier.defaultMinSize(minWidth = CapTheme.touchTarget) + .height(CapTheme.touchTarget) + .selectable( + selected = selected, + onClick = { onSelected(index) }, + role = Role.Tab, + ) + .drawBehind { + if (selected) { + drawRect( + color = underline, + topLeft = Offset(0f, size.height - 2.dp.toPx()), + size = Size(size.width, 2.dp.toPx()), + ) + } + } + .wrapContentSize(Alignment.Center), + color = + if (selected) MaterialTheme.colorScheme.onSurface + else CapTheme.colors.textSecondary, + style = + CapType.body.copy( + fontWeight = + if (selected) FontWeight.SemiBold else FontWeight.Medium + ), + ) + } + } + trailing() + } + CapHairline(Modifier.align(Alignment.BottomCenter)) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/SectionHeader.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/SectionHeader.kt new file mode 100644 index 00000000000..c298a06f7b2 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/SectionHeader.kt @@ -0,0 +1,35 @@ +package so.cap.mobile.designsystem + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +@Composable +fun SectionHeader(title: String, modifier: Modifier = Modifier, trailing: String? = null) { + Row( + modifier = modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = title, + modifier = Modifier.weight(1f).alignByBaseline().semantics { heading() }, + style = CapType.title3.copy(fontWeight = FontWeight.SemiBold), + ) + if (trailing != null) { + Text( + text = trailing, + modifier = Modifier.alignByBaseline(), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.subheadline.monospacedDigit(), + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Skeleton.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Skeleton.kt new file mode 100644 index 00000000000..3e407f99d09 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Skeleton.kt @@ -0,0 +1,76 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.MotionDurationScale +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.text.TextStyle + +private const val SKELETON_FILL_ALPHA = 0.12f + +@Composable +fun Modifier.shimmering(): Modifier { + val durationScale = rememberCoroutineScope().coroutineContext[MotionDurationScale] + if (durationScale?.scaleFactor == 0f) return this + val alpha by + rememberInfiniteTransition() + .animateFloat( + initialValue = 1f, + targetValue = CapMotion.SHIMMER_DIM_ALPHA, + animationSpec = CapMotion.shimmer, + ) + return graphicsLayer { this.alpha = alpha } +} + +@Composable +fun SkeletonBlock( + modifier: Modifier = Modifier, + shape: Shape = RoundedCornerShape(CapTheme.thumbnailRadius), +) { + Box( + modifier.background( + MaterialTheme.colorScheme.onSurface.copy(alpha = SKELETON_FILL_ALPHA), + shape, + ) + ) +} + +@Composable +fun SkeletonText(text: String, style: TextStyle, modifier: Modifier = Modifier) { + val fill = MaterialTheme.colorScheme.onSurface.copy(alpha = SKELETON_FILL_ALPHA) + Text( + text = text, + modifier = + modifier + .drawBehind { + val inset = size.height * 0.15f + val barHeight = size.height - inset * 2 + drawRoundRect( + color = fill, + topLeft = Offset(0f, inset), + size = Size(size.width, barHeight), + cornerRadius = CornerRadius(barHeight / 4), + ) + } + .clearAndSetSemantics {}, + color = Color.Transparent, + maxLines = 1, + style = style, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/StatLabel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/StatLabel.kt new file mode 100644 index 00000000000..b29805103af --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/StatLabel.kt @@ -0,0 +1,44 @@ +package so.cap.mobile.designsystem + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.mobile.R + +@Composable +fun StatLabel( + value: Int, + @DrawableRes icon: Int, + noun: String, + modifier: Modifier = Modifier, +) { + val label = stringResource(R.string.stat_label, value, noun) + val style = LocalTextStyle.current.monospacedDigit() + val iconSize = with(LocalDensity.current) { style.fontSize.toDp() } + Row( + modifier = modifier.clearAndSetSemantics { contentDescription = label }, + horizontalArrangement = Arrangement.spacedBy(3.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.size(iconSize), + ) + Text(text = CapFormat.count(value), style = style) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Theme.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Theme.kt new file mode 100644 index 00000000000..f36278c3add --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Theme.kt @@ -0,0 +1,132 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.core.CubicBezierEasing +import androidx.compose.animation.core.Easing +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.InfiniteRepeatableSpec +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Shapes +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.dropShadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.shadow.Shadow +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp + +object CapTheme { + val spacing = 16.dp + val pageMargin = 24.dp + val touchTarget = 44.dp + val hairline = 1.dp + val cardRadius = 12.dp + val thumbnailRadius = 12.dp + val controlRadius = 12.dp + val sheetRadius = 12.dp + val pillRadius = 999.dp + val tinyRadius = 3.dp + val sampleRadius = 9.dp + val framedSampleRadius = 15.dp + val systemCardRadius = 28.dp + + val colors: CapColors + @Composable @ReadOnlyComposable get() = LocalCapColors.current +} + +object CapEasing { + val emphasized: Easing = CubicBezierEasing(0.16f, 1f, 0.3f, 1f) + val springLike: Easing = CubicBezierEasing(0.34f, 1.56f, 0.64f, 1f) + val linear: Easing = LinearEasing +} + +object CapMotion { + const val PRESSED_SCALE = 0.98f + const val SHIMMER_DIM_ALPHA = 0.55f + const val IMAGE_FADE_MILLIS = 200 + const val TICK_MILLIS = 160 + const val COLOR_MILLIS = 200 + const val MEDIUM_MILLIS = 300 + const val PANEL_MILLIS = 500 + + val shimmer: InfiniteRepeatableSpec = + infiniteRepeatable(tween(PANEL_MILLIS, easing = CapEasing.emphasized), RepeatMode.Reverse) + + fun tick(): FiniteAnimationSpec = tween(TICK_MILLIS, easing = CapEasing.linear) + + fun colour(): FiniteAnimationSpec = tween(COLOR_MILLIS, easing = CapEasing.linear) + + fun panel(): FiniteAnimationSpec = tween(PANEL_MILLIS, easing = CapEasing.emphasized) + + fun morph(): FiniteAnimationSpec = tween(PANEL_MILLIS, easing = CapEasing.springLike) + + fun medium(): FiniteAnimationSpec = tween(MEDIUM_MILLIS, easing = CapEasing.emphasized) + + fun press(): FiniteAnimationSpec = tick() + + fun focus(): FiniteAnimationSpec = colour() + + fun signInStep(): FiniteAnimationSpec = medium() + + fun toastEnter(): FiniteAnimationSpec = + tween(MEDIUM_MILLIS, easing = CapEasing.springLike) + + fun toastExit(): FiniteAnimationSpec = tween(TICK_MILLIS, easing = CapEasing.linear) +} + +object CapElevation { + val floatingLarge = + Shadow( + radius = 32.dp, + color = Color.Black, + offset = DpOffset(0.dp, 12.dp), + alpha = 0.30f, + ) + val floatingSmall = + Shadow( + radius = 8.dp, + color = Color.Black, + offset = DpOffset(0.dp, 2.dp), + alpha = 0.20f, + ) +} + +fun Modifier.capFloatingShadow(shape: Shape): Modifier = + dropShadow(shape, CapElevation.floatingLarge).dropShadow(shape, CapElevation.floatingSmall) + +private val CapShapes = + Shapes( + small = RoundedCornerShape(CapTheme.controlRadius), + medium = RoundedCornerShape(CapTheme.thumbnailRadius), + large = RoundedCornerShape(CapTheme.cardRadius), + ) + +@Composable +fun Modifier.capCardBackground(): Modifier = + background( + MaterialTheme.colorScheme.surfaceContainer, + RoundedCornerShape(CapTheme.cardRadius), + ) + +@Composable +fun CapTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { + CompositionLocalProvider( + LocalCapColors provides if (darkTheme) DarkCapColors else LightCapColors + ) { + MaterialTheme( + colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme, + typography = CapMaterialTypography, + shapes = CapShapes, + content = content, + ) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Toast.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Toast.kt new file mode 100644 index 00000000000..5b3c224ee43 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Toast.kt @@ -0,0 +1,123 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.node.Ref +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.app.Toast +import so.cap.mobile.app.ToastCenter + +private val ToastShape = RoundedCornerShape(26.dp) + +@Composable +fun ToastHost(center: ToastCenter, modifier: Modifier = Modifier) { + val current by center.current.collectAsState() + val last = remember { Ref() } + val toast = current ?: last.value + last.value = toast + + val haptics = LocalHapticFeedback.current + LaunchedEffect(current?.id) { + val shown = current ?: return@LaunchedEffect + haptics.performHapticFeedback( + if (shown.style == Toast.Style.Error) HapticFeedbackType.Reject + else HapticFeedbackType.Confirm + ) + } + + AnimatedVisibility( + visible = current != null, + modifier = + modifier + .windowInsetsPadding( + WindowInsets.safeDrawing.only( + WindowInsetsSides.Top + WindowInsetsSides.Horizontal + ) + ) + .padding(start = 24.dp, top = 6.dp, end = 24.dp), + enter = slideInVertically(CapMotion.toastEnter()) { -it } + fadeIn(CapMotion.toastEnter()), + exit = slideOutVertically(CapMotion.toastExit()) { -it } + fadeOut(CapMotion.toastExit()), + ) { + if (toast != null) { + ToastSurface(toast = toast, onDismiss = { center.dismiss(toast.id) }) + } + } +} + +@Composable +private fun ToastSurface(toast: Toast, onDismiss: () -> Unit) { + val iconSize = with(LocalDensity.current) { CapType.body.lineHeight.toDp() } + Surface( + modifier = + Modifier.clip(ToastShape) + .clickable( + onClickLabel = stringResource(R.string.toast_dismiss), + onClick = onDismiss, + ) + .semantics { liveRegion = LiveRegionMode.Polite }, + shape = ToastShape, + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shadowElevation = 6.dp, + ) { + Row( + modifier = Modifier.padding(horizontal = 18.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + painter = painterResource(toast.icon), + contentDescription = null, + modifier = Modifier.size(iconSize), + tint = + when (toast.style) { + Toast.Style.Info -> MaterialTheme.colorScheme.primary + Toast.Style.Success -> CapTheme.colors.success + Toast.Style.Error -> CapTheme.colors.warning + }, + ) + Text( + text = toast.message, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + style = CapType.subheadline.copy(fontWeight = FontWeight.Medium), + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Type.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Type.kt new file mode 100644 index 00000000000..143b3290b57 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/designsystem/Type.kt @@ -0,0 +1,86 @@ +package so.cap.mobile.designsystem + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import so.cap.mobile.R + +val CapFontFamily = + FontFamily( + Font(R.font.inter_regular, FontWeight.Normal), + Font(R.font.inter_medium, FontWeight.Medium), + Font(R.font.inter_semibold, FontWeight.SemiBold), + ) + +object CapType { + val hugeNumeric = capTextStyle(152, 152, FontWeight.SemiBold, (-0.045f).em, numeric = true) + val libraryCount = capTextStyle(96, 96, FontWeight.SemiBold, (-0.045f).em, numeric = true) + val bigOption = capTextStyle(48, 56, FontWeight.SemiBold, (-0.04f).em, numeric = true) + val pickerNumber = capTextStyle(44, 48, FontWeight.SemiBold, (-0.04f).em, numeric = true) + val largeMetric = capTextStyle(40, 44, FontWeight.SemiBold, numeric = true) + val notificationNumeric = capTextStyle(32, 36, FontWeight.SemiBold, (-0.03f).em, numeric = true) + val screenTitle = capTextStyle(28, 34, FontWeight.SemiBold, (-0.02f).em) + val sliderValue = capTextStyle(28, 32, FontWeight.SemiBold, (-0.03f).em, numeric = true) + val detailTitle = capTextStyle(22, 28, FontWeight.SemiBold, (-0.015f).em) + val panelTitle = capTextStyle(17, 24, FontWeight.SemiBold) + val rowTitle = capTextStyle(16, 22, FontWeight.SemiBold) + val body = capTextStyle(15, 22, FontWeight.Normal) + val bodyStrong = capTextStyle(15, 22, FontWeight.SemiBold) + val metadata = capTextStyle(14, 20, FontWeight.Normal) + val metadataStrong = capTextStyle(14, 20, FontWeight.SemiBold) + val small = capTextStyle(13, 18, FontWeight.Normal) + val smallStrong = capTextStyle(13, 18, FontWeight.SemiBold) + val tinyLabel = capTextStyle(12, 16, FontWeight.SemiBold) + + val largeTitle = screenTitle + val title = screenTitle + val title2 = detailTitle + val title3 = panelTitle + val headline = rowTitle + val subheadline = body + val footnote = small + val caption = tinyLabel + val caption2 = tinyLabel +} + +private fun capTextStyle( + size: Int, + lineHeight: Int, + weight: FontWeight, + tracking: TextUnit = TextUnit.Unspecified, + numeric: Boolean = false, +) = + TextStyle( + fontFamily = CapFontFamily, + fontSize = size.sp, + lineHeight = lineHeight.sp, + fontWeight = weight, + letterSpacing = tracking, + fontFeatureSettings = if (numeric) "tnum" else null, + ) + +fun TextStyle.monospacedDigit(): TextStyle = copy(fontFeatureSettings = "tnum") + +internal val CapMaterialTypography = + Typography( + displayLarge = CapType.hugeNumeric, + displayMedium = CapType.libraryCount, + displaySmall = CapType.bigOption, + headlineLarge = CapType.largeMetric, + headlineMedium = CapType.screenTitle, + headlineSmall = CapType.detailTitle, + titleLarge = CapType.detailTitle, + titleMedium = CapType.panelTitle, + titleSmall = CapType.rowTitle, + bodyLarge = CapType.body, + bodyMedium = CapType.metadata, + bodySmall = CapType.small, + labelLarge = CapType.bodyStrong, + labelMedium = CapType.metadataStrong, + labelSmall = CapType.tinyLabel, + ) diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/AuthBrowser.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/AuthBrowser.kt new file mode 100644 index 00000000000..4171bd28e16 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/AuthBrowser.kt @@ -0,0 +1,17 @@ +package so.cap.mobile.features.auth + +private val CHROME_CHANNELS = + listOf("com.android.chrome", "com.chrome.beta", "com.chrome.dev", "com.chrome.canary") + +fun authTabBrowser( + defaultBrowser: String?, + customTabsBrowsers: List, + supportsAuthTab: (String) -> Boolean, +): String? { + if (defaultBrowser != null && supportsAuthTab(defaultBrowser)) return defaultBrowser + return customTabsBrowsers + .sortedBy { browser -> + CHROME_CHANNELS.indexOf(browser).takeIf { it >= 0 } ?: CHROME_CHANNELS.size + } + .firstOrNull(supportsAuthTab) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/CodeField.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/CodeField.kt new file mode 100644 index 00000000000..039a6fec74b --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/CodeField.kt @@ -0,0 +1,174 @@ +package so.cap.mobile.features.auth + +import androidx.compose.foundation.background +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.InputTransformation +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.selection.LocalTextSelectionColors +import androidx.compose.foundation.text.selection.TextSelectionColors +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.autofill.ContentType +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.contentType +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import so.cap.kit.VerificationCode +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.monospacedDigit + +@Composable +fun OneTimeCodeField( + state: TextFieldState, + enabled: Boolean, + modifier: Modifier = Modifier, + wrong: Boolean = false, + onEdited: () -> Unit = {}, +) { + val label = stringResource(R.string.sign_in_code_label) + val empty = stringResource(R.string.sign_in_code_empty) + val code = state.text.toString() + val spoken = if (code.isEmpty()) empty else code.toList().joinToString(" ") + val interactions = remember { MutableInteractionSource() } + val focused by interactions.collectIsFocusedAsState() + val hidden = TextSelectionColors(Color.Transparent, Color.Transparent) + val transformation = + remember(onEdited) { + InputTransformation { + onEdited() + val typed = asCharSequence().toString() + val sanitized = VerificationCode.sanitize(typed) + if (sanitized != typed) replace(0, length, sanitized) + } + } + CompositionLocalProvider(LocalTextSelectionColors provides hidden) { + BasicTextField( + state = state, + modifier = + modifier.fillMaxWidth().semantics { + contentDescription = label + stateDescription = spoken + contentType = ContentType.SmsOtpCode + }, + enabled = enabled, + inputTransformation = transformation, + textStyle = CapType.body.copy(color = Color.Transparent), + keyboardOptions = + KeyboardOptions( + autoCorrectEnabled = false, + keyboardType = KeyboardType.NumberPassword, + imeAction = ImeAction.Done, + ), + lineLimits = TextFieldLineLimits.SingleLine, + interactionSource = interactions, + cursorBrush = SolidColor(Color.Transparent), + decorator = { field -> + Box { + field() + Row( + modifier = Modifier.fillMaxWidth().clearAndSetSemantics {}, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + repeat(VerificationCode.LENGTH) { index -> + CodeSlot( + digit = code.getOrNull(index)?.toString().orEmpty(), + current = + code.length < VerificationCode.LENGTH && index == code.length, + focused = focused, + wrong = wrong, + modifier = Modifier.weight(1f), + ) + } + } + } + }, + ) + } +} + +@Composable +private fun CodeSlot( + digit: String, + current: Boolean, + focused: Boolean, + wrong: Boolean, + modifier: Modifier, +) { + val density = LocalDensity.current + val fontScale = if (density.fontScale > 1.15f) 1.15f / density.fontScale else 1f + val digitStyle = + CapType.body + .copy( + fontSize = (56f * fontScale).sp, + lineHeight = (64f * fontScale).sp, + fontWeight = FontWeight.SemiBold, + letterSpacing = (-0.03f).em, + ) + .monospacedDigit() + Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) { + Box(modifier = Modifier.fillMaxWidth().height(64.dp), contentAlignment = Alignment.Center) { + if (digit.isNotEmpty()) { + Text( + text = digit, + color = + if (wrong) CapTheme.colors.textSecondary + else MaterialTheme.colorScheme.onSurface, + style = digitStyle, + ) + } + if (focused && current) { + Box( + modifier = + Modifier.width(2.dp) + .height(46.dp) + .background( + CapTheme.colors.blue, + androidx.compose.foundation.shape.CircleShape, + ) + ) + } + } + Box( + modifier = + Modifier.fillMaxWidth() + .height(2.dp) + .background( + when { + current -> CapTheme.colors.blue + digit.isNotEmpty() -> MaterialTheme.colorScheme.onSurface + else -> CapTheme.colors.dialRim + } + ) + ) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInHero.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInHero.kt new file mode 100644 index 00000000000..1b2328de2d7 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInHero.kt @@ -0,0 +1,184 @@ +package so.cap.mobile.features.auth + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.blur +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapColorTokens + +private const val DESIGN_WIDTH = 412f +private const val DESIGN_HEIGHT = 610f + +@Composable +fun SignInHero(modifier: Modifier = Modifier) { + BoxWithConstraints(modifier.clearAndSetSemantics {}) { + val sx = maxWidth.value / DESIGN_WIDTH + val sy = maxHeight.value / DESIGN_HEIGHT + val background = MaterialTheme.colorScheme.background + Canvas(Modifier.fillMaxSize()) { + drawRect( + Brush.verticalGradient( + colorStops = + arrayOf( + 0f to CapColorTokens.SkyTop, + 0.40f to CapColorTokens.Sky, + 0.78f to CapColorTokens.SkyBottom, + 1f to background, + ) + ) + ) + val stroke = 1.dp.toPx() + val centre = + Offset(size.width * (206f / DESIGN_WIDTH), size.height * (236f / DESIGN_HEIGHT)) + val ringScale = size.width / (DESIGN_WIDTH * density) + drawCircle( + Color.White.copy(alpha = 0.60f), + 92f * density * ringScale, + centre, + style = Stroke(stroke), + ) + drawCircle( + Color.White.copy(alpha = 0.45f), + 150f * density * ringScale, + centre, + style = Stroke(stroke), + ) + drawCircle( + Color.White.copy(alpha = 0.32f), + 232f * density * ringScale, + centre, + style = Stroke(stroke), + ) + drawCircle( + Color.White.copy(alpha = 0.22f), + 340f * density * ringScale, + centre, + style = Stroke(stroke), + ) + } + + Cloud( + left = maxWidth * (26f / DESIGN_WIDTH), + top = maxHeight * (84f / DESIGN_HEIGHT), + width = maxWidth * (150f / DESIGN_WIDTH), + height = maxHeight * (56f / DESIGN_HEIGHT), + blur = 8.dp * sx, + ) { + CloudPart(0f, 22f, 150f, 34f, sx, sy, Color.White, pill = true) + CloudPart(34f, 0f, 62f, 56f, sx, sy, Color.White) + } + Cloud( + left = maxWidth * (248f / DESIGN_WIDTH), + top = maxHeight * (268f / DESIGN_HEIGHT), + width = maxWidth * (250f / DESIGN_WIDTH), + height = maxHeight * (124f / DESIGN_HEIGHT), + blur = 9.dp * sx, + ) { + CloudPart(10f, 70f, 230f, 54f, sx, sy, Color(0xFFE6F4FF), pill = true) + CloudPart(20f, 44f, 84f, 80f, sx, sy, Color.White) + CloudPart(78f, 0f, 120f, 120f, sx, sy, Color.White) + } + Cloud( + left = maxWidth * (-104f / DESIGN_WIDTH), + top = maxHeight * (338f / DESIGN_HEIGHT), + width = maxWidth * (380f / DESIGN_WIDTH), + height = maxHeight * (190f / DESIGN_HEIGHT), + blur = 10.dp * sx, + ) { + CloudPart(20f, 104f, 340f, 86f, sx, sy, Color(0xFFE6F4FF), pill = true) + CloudPart(44f, 62f, 130f, 128f, sx, sy, Color.White) + CloudPart(132f, 8f, 172f, 172f, sx, sy, Color.White) + CloudPart(252f, 74f, 108f, 108f, sx, sy, Color.White) + } + Cloud( + left = maxWidth * (-60f / DESIGN_WIDTH), + top = maxHeight * (486f / DESIGN_HEIGHT), + width = maxWidth * (532f / DESIGN_WIDTH), + height = maxHeight * (170f / DESIGN_HEIGHT), + blur = 14.dp * sx, + ) { + CloudPart( + 0f, + 60f, + 532f, + 110f, + sx, + sy, + MaterialTheme.colorScheme.background, + rectangle = true, + ) + CloudPart(10f, 24f, 150f, 130f, sx, sy, Color.White) + CloudPart(120f, 40f, 170f, 130f, sx, sy, Color.White) + CloudPart(250f, 10f, 160f, 150f, sx, sy, Color.White) + CloudPart(380f, 36f, 140f, 130f, sx, sy, Color.White) + } + + Image( + painter = painterResource(R.drawable.cap_logo_large), + contentDescription = null, + modifier = + Modifier.offset( + x = maxWidth * (158f / DESIGN_WIDTH), + y = maxHeight * (188f / DESIGN_HEIGHT), + ) + .size(96.dp * sx), + ) + } +} + +@Composable +private fun Cloud( + left: Dp, + top: Dp, + width: Dp, + height: Dp, + blur: Dp, + content: @Composable () -> Unit, +) { + Box(Modifier.offset(left, top).size(width, height).blur(blur)) { content() } +} + +@Composable +private fun CloudPart( + x: Float, + y: Float, + width: Float, + height: Float, + sx: Float, + sy: Float, + color: Color, + pill: Boolean = false, + rectangle: Boolean = false, +) { + val shape: Shape = + when { + rectangle -> RoundedCornerShape(0.dp) + pill -> RoundedCornerShape(percent = 50) + else -> CircleShape + } + Box( + Modifier.offset(x.dp * sx, y.dp * sy) + .size(width.dp * sx, height.dp * sy) + .background(color, shape) + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInModel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInModel.kt new file mode 100644 index 00000000000..e8b53e045d4 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInModel.kt @@ -0,0 +1,321 @@ +package so.cap.mobile.features.auth + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.clearText +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import java.io.IOException +import java.util.Locale +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import so.cap.kit.ApiKeySession +import so.cap.kit.AuthCallback +import so.cap.kit.AuthCallbackError +import so.cap.kit.AuthConfig +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapApiException +import so.cap.kit.EmailValidator +import so.cap.kit.VerificationCode + +class SignInModel( + private val api: CapApi, + private val scope: CoroutineScope, + private val timeSource: TimeSource = TimeSource.Monotonic, + pending: Pending? = null, + private val onProviderPending: (Pending?) -> Unit = {}, + private val onSession: suspend (ApiKeySession) -> Unit, +) { + sealed interface Step { + data object Start : Step + + data object Email : Step + + data class Code(val email: String) : Step + } + + enum class CodeNotice { + Resent + } + + sealed interface Activity { + data object Email : Activity + + data object Verifying : Activity + + data object Resending : Activity + + data class Provider(val name: String) : Activity + } + + data class Pending(val provider: String, val state: String) + + var step: Step by mutableStateOf(Step.Start) + private set + + val email = TextFieldState() + val code = TextFieldState() + + var activity: Activity? by mutableStateOf(pending?.provider?.let(Activity::Provider)) + private set + + var errorMessage: String? by mutableStateOf(null) + private set + + var config: AuthConfig by mutableStateOf(AuthConfig.FALLBACK) + private set + + var resendRemaining: Int by mutableIntStateOf(0) + private set + + var codeNotice: CodeNotice? by mutableStateOf(null) + private set + + private var rejectedCode: String? by mutableStateOf(null) + private var cooldown: Job? = null + + private var pendingState: String? = pending?.state + + val canSubmitEmail: Boolean + get() = EmailValidator.isValid(email.text.toString()) && activity == null + + val canVerify: Boolean + get() = + VerificationCode.isComplete(code.text.toString()) && + activity == null && + code.text.toString() != rejectedCode + + val isWrongCodeError: Boolean + get() = errorMessage == WRONG_CODE + + fun showEmail() { + if (activity != null) return + step = Step.Email + errorMessage = null + codeNotice = null + rejectedCode = null + } + + fun showSignInOptions() { + if (activity != null) return + step = Step.Start + errorMessage = null + codeNotice = null + rejectedCode = null + } + + fun noteCodeEdited() { + rejectedCode = null + codeNotice = null + } + + fun loadConfig(): Job = scope.launch { + try { + config = api.authConfig() + } catch (_: CapApiException) {} + } + + fun sendCode(): Job? { + if (activity != null) return null + val typed = email.text.toString() + if (!EmailValidator.isValid(typed)) { + errorMessage = INVALID_EMAIL + return null + } + val normalized = EmailValidator.normalize(typed) + return run(Activity.Email, Context.REQUEST) { + api.requestEmailCode(normalized) + code.clearText() + rejectedCode = null + codeNotice = null + startCooldown() + step = Step.Code(normalized) + } + } + + fun resend(): Job? { + val current = step as? Step.Code ?: return null + if (activity != null || resendRemaining > 0) return null + return run(Activity.Resending, Context.REQUEST) { + api.requestEmailCode(current.email) + code.clearText() + rejectedCode = null + codeNotice = CodeNotice.Resent + startCooldown() + } + } + + fun verify(): Job? { + val current = step as? Step.Code ?: return null + if (!canVerify) return null + val typed = code.text.toString() + return run( + Activity.Verifying, + Context.VERIFY, + onFailure = { error -> + if ( + error == CapApiError.Forbidden || + error == CapApiError.BadRequest || + error == CapApiError.NotFound + ) { + rejectedCode = typed + } else { + code.clearText() + } + codeNotice = null + stopCooldown() + }, + ) { + val session = api.verifyEmailCode(current.email, typed) + try { + onSession(session) + } catch (_: IOException) { + errorMessage = SESSION_NOT_SAVED + } + } + } + + fun useDifferentEmail() { + step = Step.Email + code.clearText() + rejectedCode = null + codeNotice = null + errorMessage = null + } + + fun startProvider(provider: String): String? { + if (activity != null) return null + val state = AuthCallback.newState() + activity = Activity.Provider(provider) + pendingState = state + onProviderPending(Pending(provider, state)) + errorMessage = null + return api.sessionRequestUrl(provider, state) + } + + fun finishProvider(callbackUrl: String, fromAuthTab: Boolean): Job? { + val provider = activity as? Activity.Provider ?: return null + val expected = pendingState + if (!fromAuthTab && (expected == null || AuthCallback.state(callbackUrl) != expected)) { + activity = null + pendingState = null + onProviderPending(null) + errorMessage = + provider.name.replaceFirstChar { it.titlecase(Locale.ROOT) } + + BROWSER_COULD_NOT_FINISH + return null + } + pendingState = null + onProviderPending(null) + val session = + try { + AuthCallback.session(callbackUrl) + } catch (error: AuthCallbackError) { + activity = null + errorMessage = error.message + return null + } + activity = Activity.Verifying + return scope.launch { + try { + onSession(session) + } catch (_: IOException) { + errorMessage = SESSION_NOT_SAVED + } finally { + activity = null + } + } + } + + fun cancelProvider() { + if (activity !is Activity.Provider) return + activity = null + pendingState = null + onProviderPending(null) + } + + fun failProvider() { + if (activity !is Activity.Provider) return + activity = null + pendingState = null + onProviderPending(null) + errorMessage = COULD_NOT_START + } + + private enum class Context { + REQUEST, + VERIFY, + } + + private fun message(error: CapApiError, context: Context): String = + when (error) { + CapApiError.RateLimited -> TOO_MANY_ATTEMPTS + CapApiError.Forbidden -> if (context == Context.VERIFY) WRONG_CODE else NO_CODE_SIGN_IN + CapApiError.BadRequest -> if (context == Context.VERIFY) WRONG_CODE else INVALID_EMAIL + CapApiError.NotFound -> if (context == Context.VERIFY) WRONG_CODE else error.description + else -> error.description + } + + private fun run( + activity: Activity, + context: Context, + onFailure: (CapApiError) -> Unit = {}, + request: suspend () -> Unit, + ): Job { + this.activity = activity + errorMessage = null + return scope.launch { + try { + request() + } catch (error: CapApiException) { + onFailure(error.error) + errorMessage = message(error.error, context) + } finally { + this@SignInModel.activity = null + } + } + } + + private fun startCooldown() { + cooldown?.cancel() + val available = timeSource.markNow() + RESEND_COOLDOWN + cooldown = + scope.launch(start = CoroutineStart.UNDISPATCHED) { + while (true) { + val left = -available.elapsedNow() + if (!left.isPositive()) break + val seconds = ((left.inWholeMilliseconds + 999) / 1000).toInt() + resendRemaining = seconds + delay(maxOf(left - (seconds - 1).seconds, 1.milliseconds)) + } + resendRemaining = 0 + } + } + + private fun stopCooldown() { + cooldown?.cancel() + resendRemaining = 0 + } + + private companion object { + val RESEND_COOLDOWN = 30.seconds + const val INVALID_EMAIL = "Enter a valid email address." + const val TOO_MANY_ATTEMPTS = "Too many attempts. Wait a few minutes and try again." + const val WRONG_CODE = "That code didn't match. Check the email and enter it again." + const val NO_CODE_SIGN_IN = + "This email can't sign in with a code. Try another sign in option." + const val COULD_NOT_START = "Sign in couldn't start. Check your connection and try again." + const val SESSION_NOT_SAVED = "Cap couldn't save your session securely. Try again." + const val BROWSER_COULD_NOT_FINISH = + " sign-in couldn't finish in this browser. Install or turn on Chrome, " + + "or sign in with your email." + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInScreen.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInScreen.kt new file mode 100644 index 00000000000..398fa17e231 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/auth/SignInScreen.kt @@ -0,0 +1,554 @@ +package so.cap.mobile.features.auth + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedContentTransitionScope.SlideDirection +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.autofill.ContentType +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.contentType +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import java.util.Locale +import so.cap.kit.VerificationCode +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapMotion +import so.cap.mobile.designsystem.CapPrimaryButton +import so.cap.mobile.designsystem.CapSecondaryButton +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.designsystem.openInAppBrowser + +private const val GOOGLE = "google" +private const val START_HEIGHT = 915f +private const val START_HERO_HEIGHT = 610f +private val body16 = CapType.rowTitle.copy(fontWeight = FontWeight.Normal, lineHeight = 24.sp) + +@Composable +fun SignInScreen(model: SignInModel, notice: String?, onProvider: (String) -> Unit) { + LaunchedEffect(model) { model.loadConfig() } + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + BoxWithConstraints(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)) { + AnimatedContent( + targetState = model.step, + modifier = Modifier.fillMaxSize(), + transitionSpec = { + val direction = + if (targetState is SignInModel.Step.Start) SlideDirection.End + else SlideDirection.Start + slideIntoContainer(direction, CapMotion.signInStep()) + + fadeIn(CapMotion.signInStep()) togetherWith + slideOutOfContainer(direction, CapMotion.signInStep()) + + fadeOut(CapMotion.signInStep()) + }, + contentKey = { + when (it) { + SignInModel.Step.Start -> 0 + SignInModel.Step.Email -> 1 + is SignInModel.Step.Code -> 2 + } + }, + ) { step -> + when (step) { + SignInModel.Step.Start -> StartStep(model, notice, onProvider, maxHeight) + SignInModel.Step.Email -> EmailStep(model, onProvider) + is SignInModel.Step.Code -> CodeStep(model, step.email) + } + } + } + } +} + +@Composable +private fun StartStep( + model: SignInModel, + notice: String?, + onProvider: (String) -> Unit, + viewport: Dp, +) { + StartLayout(viewport, Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { + SignInHero() + AuthHeader( + title = stringResource(R.string.sign_in_title), + subtitle = stringResource(R.string.sign_in_subtitle), + ) + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + val message = model.errorMessage ?: notice + if (message != null) AuthStatusMessage(message, error = true) + if (model.config.googleAuthAvailable) { + CapPrimaryButton( + onClick = { onProvider(GOOGLE) }, + modifier = Modifier.fillMaxWidth(), + enabled = model.activity == null, + height = 56.dp, + ) { + if (model.activity == SignInModel.Activity.Provider(GOOGLE)) ButtonSpinner() + Text(stringResource(R.string.sign_in_google)) + } + } + CapSecondaryButton( + onClick = model::showEmail, + modifier = Modifier.fillMaxWidth(), + enabled = model.activity == null, + height = 56.dp, + ) { + Text(stringResource(R.string.sign_in_continue_email)) + } + } + Legal() + } +} + +@Composable +private fun StartLayout(viewport: Dp, modifier: Modifier, content: @Composable () -> Unit) { + Layout(content, modifier) { measurables, constraints -> + val width = constraints.maxWidth + val margin = 24.dp.roundToPx() + val contentWidth = minOf(width - margin * 2, 364.dp.roundToPx()).coerceAtLeast(1) + val left = (width - contentWidth) / 2 + val viewportPx = viewport.roundToPx() + val heroHeight = (viewportPx * (START_HERO_HEIGHT / START_HEIGHT)).toInt() + val hero = measurables[0].measure(Constraints.fixed(width, heroHeight)) + val header = measurables[1].measure(Constraints.fixedWidth(contentWidth)) + val actions = measurables[2].measure(Constraints.fixedWidth(contentWidth)) + val legal = measurables[3].measure(Constraints.fixedWidth(contentWidth)) + val headerY = (viewportPx * (604f / START_HEIGHT)).toInt() + val actionGap = 10.dp.roundToPx() + val legalGap = 4.dp.roundToPx() + val bottom = 32.dp.roundToPx() + val actionsY = + maxOf( + (viewportPx * (722f / START_HEIGHT)).toInt(), + headerY + header.height + actionGap, + ) + val legalY = actionsY + actions.height + legalGap + val height = maxOf(viewportPx, legalY + legal.height + bottom) + layout(width, height) { + hero.place(0, 0) + header.place(left, headerY) + actions.place(left, actionsY) + legal.place(left, legalY) + } + } +} + +@Composable +private fun EmailStep(model: SignInModel, onProvider: (String) -> Unit) { + AuthStepScaffold(onBack = model::showSignInOptions, backEnabled = model.activity == null) { + Spacer(Modifier.height(36.dp)) + AuthHeader( + title = stringResource(R.string.sign_in_email_title), + subtitle = stringResource(R.string.sign_in_email_subtitle), + ) + Spacer(Modifier.height(26.dp)) + EmailForm(model) + Spacer(Modifier.height(42.dp)) + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + val focus = LocalFocusManager.current + CapPrimaryButton( + onClick = { + focus.clearFocus() + model.sendCode() + }, + modifier = Modifier.fillMaxWidth(), + enabled = model.canSubmitEmail, + height = 56.dp, + ) { + if (model.activity == SignInModel.Activity.Email) ButtonSpinner() + Text(stringResource(R.string.sign_in_send_code)) + } + if (model.config.googleAuthAvailable) { + AuthTextAction( + text = stringResource(R.string.sign_in_use_google), + onClick = { onProvider(GOOGLE) }, + enabled = model.activity == null, + ) + } + } + model.errorMessage?.let { + Spacer(Modifier.height(16.dp)) + AuthStatusMessage(it, error = true) + } + } +} + +@Composable +private fun EmailForm(model: SignInModel) { + val view = remember { BringIntoViewRequester() } + var focused by remember { mutableStateOf(false) } + val keyboard = WindowInsets.ime.getBottom(LocalDensity.current) + LaunchedEffect(focused, keyboard) { if (focused) view.bringIntoView() } + Column( + modifier = Modifier.bringIntoViewRequester(view).onFocusChanged { focused = it.hasFocus } + ) { + Text( + text = stringResource(R.string.sign_in_email_field_label), + color = CapTheme.colors.textSecondary, + style = CapType.small, + ) + Spacer(Modifier.height(4.dp)) + EmailField(state = model.email, onSubmit = { model.sendCode() }) + } +} + +@Composable +private fun EmailField(state: TextFieldState, onSubmit: () -> Unit) { + val label = stringResource(R.string.sign_in_email_label) + val interactions = remember { MutableInteractionSource() } + val ink = MaterialTheme.colorScheme.onSurface + BasicTextField( + state = state, + modifier = + Modifier.fillMaxWidth().semantics { + contentDescription = label + contentType = ContentType.Username + ContentType.EmailAddress + }, + textStyle = + CapType.detailTitle.copy( + color = ink, + fontSize = 22.sp, + lineHeight = 30.sp, + letterSpacing = (-0.01f).em, + ), + keyboardOptions = + KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Email, + imeAction = ImeAction.Go, + ), + onKeyboardAction = { onSubmit() }, + lineLimits = TextFieldLineLimits.SingleLine, + interactionSource = interactions, + cursorBrush = SolidColor(CapTheme.colors.blue), + decorator = { field -> + Column { + Box(Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 10.dp)) { + if (state.text.isEmpty()) { + Text( + text = stringResource(R.string.sign_in_email_placeholder), + color = CapTheme.colors.textSecondary, + style = CapType.detailTitle.copy(fontSize = 22.sp, lineHeight = 30.sp), + ) + } + field() + } + Box(Modifier.fillMaxWidth().height(2.dp).background(ink)) + } + }, + ) +} + +@Composable +private fun CodeStep(model: SignInModel, email: String) { + val codeFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { codeFocus.requestFocus() } + LaunchedEffect(model) { + snapshotFlow { model.code.text.toString() } + .collect { if (VerificationCode.isComplete(it)) model.verify() } + } + AuthStepScaffold(onBack = model::useDifferentEmail, backEnabled = model.activity == null) { + Spacer(Modifier.height(36.dp)) + AuthHeader( + title = stringResource(R.string.sign_in_code_title), + subtitle = stringResource(R.string.sign_in_code_sent_to, email), + ) + Spacer(Modifier.height(36.dp)) + OneTimeCodeField( + state = model.code, + enabled = model.activity != SignInModel.Activity.Verifying, + wrong = model.isWrongCodeError, + onEdited = model::noteCodeEdited, + modifier = Modifier.focusRequester(codeFocus), + ) + Spacer(Modifier.height(28.dp)) + Box(Modifier.fillMaxWidth().heightIn(min = 90.dp)) { CodeStatus(model) } + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + CapPrimaryButton( + onClick = { model.verify() }, + modifier = Modifier.fillMaxWidth(), + enabled = model.canVerify, + height = 56.dp, + ) { + if (model.activity == SignInModel.Activity.Verifying) ButtonSpinner() + Text(stringResource(R.string.sign_in_continue)) + } + if (model.isWrongCodeError || model.resendRemaining == 0) { + CapSecondaryButton( + onClick = { model.resend() }, + modifier = Modifier.fillMaxWidth(), + enabled = model.activity == null && model.resendRemaining == 0, + height = 56.dp, + ) { + Text(stringResource(R.string.sign_in_send_new_code)) + } + } + val context = LocalContext.current + AuthTextAction( + text = stringResource(R.string.sign_in_open_email_app), + onClick = { openEmailApp(context) }, + ) + } + } +} + +@Composable +private fun CodeStatus(model: SignInModel) { + when { + model.errorMessage != null -> AuthStatusMessage(model.errorMessage.orEmpty(), error = true) + model.codeNotice == SignInModel.CodeNotice.Resent -> + AuthStatusMessage(stringResource(R.string.sign_in_resent)) + model.resendRemaining > 0 -> { + val seconds = model.resendRemaining + val time = String.format(Locale.US, "%d:%02d", seconds / 60, seconds % 60) + val text = stringResource(R.string.sign_in_resend_countdown, time) + val start = text.indexOf(time) + val annotated = buildAnnotatedString { + append(text) + if (start >= 0) { + addStyle( + SpanStyle( + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.SemiBold, + fontFeatureSettings = "tnum", + ), + start, + start + time.length, + ) + } + } + Text(text = annotated, color = CapTheme.colors.textSecondary, style = body16) + } + } +} + +@Composable +private fun AuthStepScaffold( + onBack: () -> Unit, + backEnabled: Boolean, + content: @Composable () -> Unit, +) { + BackHandler(enabled = backEnabled, onBack = onBack) + Column(Modifier.fillMaxSize()) { + Row( + modifier = + Modifier.fillMaxWidth() + .padding(start = 12.dp, end = 12.dp, top = 14.dp) + .height(44.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = + Modifier.size(44.dp) + .clickable(enabled = backEnabled, onClick = onBack) + .semantics { role = Role.Button }, + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(R.drawable.ic_cap_back), + contentDescription = stringResource(R.string.sign_in_back), + tint = + MaterialTheme.colorScheme.onSurface.copy( + alpha = if (backEnabled) 1f else 0.38f + ), + ) + } + Image( + painter = painterResource(R.drawable.ic_cap_glyph), + contentDescription = null, + modifier = Modifier.size(28.dp), + ) + Spacer(Modifier.size(44.dp)) + } + Column( + modifier = + Modifier.fillMaxWidth() + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 24.dp), + content = { content() }, + ) + } +} + +@Composable +private fun AuthHeader(title: String, subtitle: String) { + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = title, + modifier = Modifier.semantics { heading() }, + color = MaterialTheme.colorScheme.onSurface, + style = CapType.screenTitle, + ) + Text(text = subtitle, color = CapTheme.colors.textSecondary, style = body16) + } +} + +@Composable +private fun AuthTextAction(text: String, onClick: () -> Unit, enabled: Boolean = true) { + Box( + modifier = + Modifier.fillMaxWidth() + .height(48.dp) + .clickable(enabled = enabled, onClick = onClick) + .semantics { role = Role.Button }, + contentAlignment = Alignment.Center, + ) { + Text( + text = text, + color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (enabled) 1f else 0.38f), + style = CapType.body.copy(fontWeight = FontWeight.SemiBold), + textAlign = TextAlign.Center, + ) + } +} + +@Composable +private fun AuthStatusMessage(message: String, error: Boolean = false) { + val label = stringResource(R.string.error_text_label, message) + val view = remember { BringIntoViewRequester() } + val keyboard = WindowInsets.ime.getBottom(LocalDensity.current) + LaunchedEffect(message, error, keyboard) { if (error) view.bringIntoView() } + Text( + text = message, + modifier = + Modifier.fillMaxWidth() + .bringIntoViewRequester(view) + .then( + if (error) Modifier.clearAndSetSemantics { contentDescription = label } + else Modifier + ), + color = MaterialTheme.colorScheme.onSurface, + style = body16.copy(fontWeight = FontWeight.Medium), + ) +} + +@Composable +private fun ButtonSpinner() { + CircularProgressIndicator( + modifier = Modifier.size(20.dp).clearAndSetSemantics {}, + color = LocalContentColor.current, + strokeWidth = 2.dp, + ) +} + +@Composable +private fun Legal() { + val context = LocalContext.current + val environment = LocalCapEnvironment.current + val terms = stringResource(R.string.sign_in_terms) + val privacy = stringResource(R.string.sign_in_privacy) + val text = stringResource(R.string.sign_in_legal, terms, privacy) + val linkStyles = + TextLinkStyles( + SpanStyle( + color = MaterialTheme.colorScheme.onSurface, + textDecoration = TextDecoration.Underline, + ) + ) + val links = listOf(terms to environment.termsUrl, privacy to environment.privacyUrl) + val annotated = buildAnnotatedString { + append(text) + for ((label, url) in links) { + val start = text.indexOf(label) + if (start < 0) continue + addLink( + LinkAnnotation.Url(url, linkStyles) { openInAppBrowser(context, url) }, + start, + start + label.length, + ) + } + } + Text( + text = annotated, + modifier = Modifier.fillMaxWidth(), + color = CapTheme.colors.textSecondary, + style = CapType.small, + textAlign = TextAlign.Center, + ) +} + +private fun openEmailApp(context: Context) { + val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_EMAIL) + try { + context.startActivity(intent) + } catch (_: ActivityNotFoundException) {} +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/BlockDialog.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/BlockDialog.kt new file mode 100644 index 00000000000..c7b993813c2 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/BlockDialog.kt @@ -0,0 +1,38 @@ +package so.cap.mobile.features.cap + +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import so.cap.mobile.R + +@Composable +internal fun BlockDialog(ownerName: String, onBlock: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + stringResource( + R.string.cap_block_title, + ownerName.ifEmpty { stringResource(R.string.cap_block_someone) }, + ) + ) + }, + text = { Text(stringResource(R.string.cap_block_message)) }, + confirmButton = { + TextButton( + onClick = onBlock, + colors = + ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), + ) { + Text(stringResource(R.string.cap_block_confirm)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } + }, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModel.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModel.kt new file mode 100644 index 00000000000..2704f287249 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModel.kt @@ -0,0 +1,713 @@ +package so.cap.mobile.features.cap + +import androidx.annotation.StringRes +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import java.io.IOException +import java.time.Instant +import java.util.UUID +import kotlin.random.Random +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeMark +import kotlin.time.TimeSource +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import so.cap.kit.CapAccessStatus +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapApiException +import so.cap.kit.CapComment +import so.cap.kit.CapDetail +import so.cap.kit.CapId +import so.cap.kit.CapSummary +import so.cap.kit.CapViewer +import so.cap.kit.CommentAuthor +import so.cap.kit.CommentKind +import so.cap.kit.CommentThread +import so.cap.kit.CommentThreads +import so.cap.kit.PlaybackKind +import so.cap.kit.SafeUrl +import so.cap.kit.ShareTarget +import so.cap.kit.TimelineMarker +import so.cap.kit.TranscriptCue +import so.cap.kit.TranscriptionStatus +import so.cap.kit.WebVtt +import so.cap.mobile.R +import so.cap.mobile.app.SessionModel +import so.cap.mobile.app.text + +class CapDetailModel( + val target: ShareTarget, + private val api: CapApi, + private val media: OkHttpClient, + private val session: SessionModel, + private val scope: CoroutineScope, + private val edits: CommentEdits = CommentEdits(), +) { + init { + edits.pages += this + scope.coroutineContext[Job]?.invokeOnCompletion { edits.pages -= this } + } + + sealed interface Content { + data object Loading : Content + + data class Loaded(val detail: CapDetail) : Content + + data object Locked : Content + + data object Restricted : Content + + data class Unavailable(val error: CapApiError) : Content + } + + sealed interface Transcript { + data object Idle : Transcript + + data object Loading : Transcript + + data class Loaded(val cues: List) : Transcript + + data class Unavailable(@StringRes val message: Int) : Transcript + } + + enum class Section(@StringRes val title: Int) { + Comments(R.string.cap_section_comments), + Summary(R.string.cap_section_summary), + Transcript(R.string.cap_section_transcript), + } + + data class ReactionBurst(val id: Long, val emoji: String, val lane: Double) + + data class ReactionCount(val emoji: String, val count: Int, val firstTime: Double?) + + enum class CommentOrder(@StringRes val title: Int) { + Oldest(R.string.comments_order_oldest), + Newest(R.string.comments_order_newest), + Video(R.string.comments_order_video), + } + + val id: CapId + get() = target.id + + var content: Content by mutableStateOf(Content.Loading) + private set + + var mediaUrl: String? by mutableStateOf(null) + private set + + var mediaKind by mutableStateOf(PlaybackKind.MP4) + private set + + var playbackAttempt by mutableIntStateOf(0) + private set + + var playbackFailed by mutableStateOf(false) + private set + + var transcript: Transcript by mutableStateOf(Transcript.Idle) + private set + + var isUnlocking by mutableStateOf(false) + private set + + var unlockError: CapApiError? by mutableStateOf(null) + private set + + var section by mutableStateOf(Section.Comments) + + var commentOrder by mutableStateOf(CommentOrder.Oldest) + + val threads: List by derivedStateOf { + CommentThreads.build(detail?.comments.orEmpty()) + } + + val threadedCommentCount: Int by derivedStateOf { threads.sumOf { 1 + it.replies.size } } + + var draft by mutableStateOf("") + + var composerTimestamp: Double? by mutableStateOf(null) + + var replyingTo: CapComment? by mutableStateOf(null) + private set + + var highlightedCommentId: String? by mutableStateOf(target.commentId) + + var isSendingComment by mutableStateOf(false) + private set + + var pendingCommentIds by mutableStateOf(emptySet()) + private set + + var bursts by mutableStateOf(emptyList()) + private set + + val reactionCounts: List by derivedStateOf { + detail + ?.comments + .orEmpty() + .filter { it.type == CommentKind.EMOJI } + .groupBy { it.content } + .map { (emoji, reactions) -> + ReactionCount( + emoji, + reactions.size, + reactions.mapNotNull { it.timestamp }.minOrNull(), + ) + } + .sortedWith(compareByDescending { it.count }.thenBy { it.emoji }) + } + + private var burstCount = 0L + private var lastBurst: TimeMark? = null + + internal var poll: Job? = null + private set + + private var trackedView = false + private var hasPlayback = false + private var transcriptUrl: String? = null + private var loading: Job? = null + + val detail: CapDetail? + get() = (content as? Content.Loaded)?.detail + + val management: CapManagement by lazy { + CapManagement(this, api, media, session, session.scope) + } + + internal fun capUpdated(change: (CapSummary) -> CapSummary) { + if (!scope.isActive) return + val current = detail ?: return + edits.recordCapEdit() + content = Content.Loaded(current.copy(cap = change(current.cap))) + } + + val isOwner: Boolean + get() = detail?.cap?.isOwned(session.credentials.userId) == true + + private val viewer: CapViewer + get() = detail?.viewer ?: CapViewer() + + val commentsEnabled: Boolean + get() = !viewer.settings.disableComments + + val reactionsEnabled: Boolean + get() = !viewer.settings.disableReactions + + val isScreenshot: Boolean + get() = viewer.isScreenshot + + val transcriptEnabled: Boolean + get() = !viewer.settings.disableTranscript && !viewer.isScreenshot + + val summaryEnabled: Boolean + get() = + !(viewer.settings.disableSummary && viewer.settings.disableChapters) && + !viewer.isScreenshot + + val isGeneratingSummary: Boolean + get() = detail?.isWaiting == true + + var sectionRevealRequests by mutableIntStateOf(0) + private set + + val sections: List
+ get() = buildList { + if (commentsEnabled) add(Section.Comments) + if (summaryEnabled) add(Section.Summary) + if (transcriptEnabled) add(Section.Transcript) + } + + fun requestSectionReveal() { + sectionRevealRequests += 1 + } + + fun loadTranscript(): Job = scope.launch { loadTranscriptIfNeeded() } + + val currentSection: Section? + get() = sections.let { available -> + section.takeIf { it in available } ?: available.firstOrNull() + } + + val orderedThreads: List + get() = + when (commentOrder) { + CommentOrder.Oldest -> threads + CommentOrder.Newest -> threads.asReversed() + CommentOrder.Video -> + threads.sortedWith( + compareBy( + { it.root.timestamp ?: Double.POSITIVE_INFINITY }, + { it.root.createdAt }, + ) + ) + } + + val captions: List? + get() { + if (detail?.viewer?.settings?.disableCaptions != false) return null + return (transcript as? Transcript.Loaded)?.cues + } + + fun load(): Job { + loading + ?.takeIf { it.isActive } + ?.let { + return it + } + return scope.launch { performLoad() }.also { loading = it } + } + + private suspend fun performLoad() { + if (content is Content.Loaded) return + content = Content.Loading + val asked = edits.count + val fresh = + try { + api.cap(id) + } catch (failure: CapApiException) { + content = + if (failure.error == CapApiError.Forbidden) accessContent() + else Content.Unavailable(failure.error) + return + } + apply(fresh, asked) + attachPlaybackIfNeeded(fresh) + } + + private suspend fun accessContent(): Content { + val status = + try { + api.capAccess(id) + } catch (_: CapApiException) { + null + } + return if (status == CapAccessStatus.PASSWORD_REQUIRED) Content.Locked + else Content.Restricted + } + + private fun apply(fresh: CapDetail, asked: Int) { + show(fresh, asked) + startPollingIfNeeded(fresh) + } + + private fun show(fresh: CapDetail, asked: Int) { + val deleted = edits.deleted + val served = fresh.comments.mapTo(HashSet()) { it.id } + val pending = detail?.comments.orEmpty().filter { it.id in pendingCommentIds } + val createdSince = edits.createdSince(asked, served) + val comments = + (fresh.comments + createdSince + pending).filter { + it.id !in deleted && it.parentCommentId !in deleted + } + val local = detail?.cap + val stale = local != null && edits.capEditedAt > asked + val cap = if (stale) fresh.cap.keepingEdits(local) else fresh.cap + content = Content.Loaded(fresh.copy(cap = cap, comments = comments)) + if (cap.isOwned(session.credentials.userId)) + session.capChanged(cap.id) { if (stale) fresh.cap.keepingEdits(it) else fresh.cap } + } + + private fun startPollingIfNeeded(detail: CapDetail) { + if (!detail.isWaiting) { + poll?.cancel() + poll = null + return + } + if (poll != null) return + poll = + scope.launch(start = CoroutineStart.UNDISPATCHED) { + var wait = POLL_FIRST + repeat(POLL_ATTEMPTS) { + delay(wait) + wait = (wait * 2).coerceAtMost(POLL_LONGEST) + val asked = edits.count + val fresh = + try { + api.cap(id) + } catch (_: CapApiException) { + return@repeat + } + val attached = mediaUrl != null + show(fresh, asked) + attachPlaybackIfNeeded(fresh) + if ( + fresh.transcriptionStatus == TranscriptionStatus.COMPLETE && + transcript is Transcript.Unavailable + ) { + if (attached && transcriptUrl == null) refetchTranscriptUrl() + transcript = Transcript.Idle + loadTranscriptIfNeeded() + } + if (!fresh.isWaiting) { + poll = null + return@launch + } + } + poll = null + } + } + + private val CapDetail.isWaiting: Boolean + get() = + cap.isProcessing || + transcriptionStatus == TranscriptionStatus.PROCESSING || + viewer.isGeneratingAi + + private suspend fun attachPlaybackIfNeeded(detail: CapDetail) { + if (mediaUrl != null || detail.viewer.isScreenshot || detail.viewer.overShareLimit) return + try { + val playback = api.playback(id) + hasPlayback = true + transcriptUrl = playback.transcriptUrl + val url = SafeUrl.media(playback.url, api.environment) + if (url == null) { + playbackFailed = true + } else { + mediaKind = playback.kind + mediaUrl = url + playbackFailed = false + playbackAttempt += 1 + } + } catch (_: CapApiException) { + playbackFailed = !detail.cap.isProcessing + } + loadTranscriptIfNeeded() + } + + suspend fun loadTranscriptIfNeeded() { + val detail = detail + if (transcript != Transcript.Idle || detail == null) return + if (detail.viewer.overShareLimit) { + transcript = + Transcript.Unavailable( + if (isOwner) R.string.cap_over_share_limit_owner + else R.string.cap_over_share_limit + ) + return + } + when (detail.transcriptionStatus) { + TranscriptionStatus.PROCESSING -> + transcript = Transcript.Unavailable(R.string.transcript_processing) + TranscriptionStatus.NO_AUDIO -> + transcript = Transcript.Unavailable(R.string.transcript_no_audio) + TranscriptionStatus.ERROR -> + transcript = Transcript.Unavailable(R.string.transcript_error) + TranscriptionStatus.SKIPPED, + TranscriptionStatus.COMPLETE, + null -> {} + } + if (transcript != Transcript.Idle) return + val url = SafeUrl.media(transcriptUrl, api.environment) + if (url == null) { + if (hasPlayback || detail.viewer.isScreenshot) { + transcript = Transcript.Unavailable(R.string.transcript_missing) + } + return + } + transcript = Transcript.Loading + transcript = + try { + val cues = withContext(Dispatchers.Default) { WebVtt.parse(media.text(url)) } + if (cues.isEmpty()) Transcript.Unavailable(R.string.transcript_empty) + else Transcript.Loaded(cues) + } catch (_: IOException) { + Transcript.Unavailable(R.string.transcript_failed) + } + } + + fun feedbackTimestamp(playbackTime: Double): Double? = playbackTime.takeIf { + !viewer.isScreenshot && it > MIN_FEEDBACK_TIME + } + + fun beginComposing(playbackTime: Double) { + if (composerTimestamp == null) composerTimestamp = feedbackTimestamp(playbackTime) + } + + fun startReply(comment: CapComment) { + replyingTo = comment + } + + fun cancelReply() { + replyingTo = null + } + + fun sendComment(): Job? { + val detail = detail ?: return null + val text = draft.trim().clippedToComment() + if (!commentsEnabled || text.isEmpty() || isSendingComment) return null + isSendingComment = true + val parent = replyingTo + val timestamp = if (parent == null) composerTimestamp else null + val placeholder = localComment(CommentKind.TEXT, text, timestamp, parent?.id) + content = Content.Loaded(detail.copy(comments = detail.comments + placeholder)) + pendingCommentIds = pendingCommentIds + placeholder.id + draft = "" + replyingTo = null + composerTimestamp = null + return session.scope.launch { + try { + val created = api.createComment(id, text, timestamp, parent?.id) + edits.recordCreated(created) + edits.pages.toList().forEach { it.replaceLocal(placeholder.id, created) } + if (scope.isActive) highlightedCommentId = created.id + } catch (failure: CapApiException) { + if (scope.isActive) { + removeLocal(placeholder.id) + if (draft.isEmpty() && replyingTo == null) { + draft = text + replyingTo = parent + composerTimestamp = timestamp + } + } + session.toasts.show(failure.error) + } finally { + isSendingComment = false + } + } + } + + fun react(emoji: String, playbackTime: Double): Job? { + val detail = detail ?: return null + if (!reactionsEnabled) return null + burst(emoji) + val placeholder = + localComment(CommentKind.EMOJI, emoji, feedbackTimestamp(playbackTime), null) + content = Content.Loaded(detail.copy(comments = detail.comments + placeholder)) + pendingCommentIds = pendingCommentIds + placeholder.id + return session.scope.launch { + try { + val created = api.createReaction(id, emoji, placeholder.timestamp) + edits.recordCreated(created) + edits.pages.toList().forEach { it.replaceLocal(placeholder.id, created) } + } catch (failure: CapApiException) { + if (scope.isActive) removeLocal(placeholder.id) + session.toasts.show(failure.error) + } + } + } + + fun burst(emoji: String) { + val last = lastBurst + if (last != null && last.elapsedNow() <= BURST_GAP) return + lastBurst = TimeSource.Monotonic.markNow() + val added = + ReactionBurst(burstCount++, emoji, Random.nextDouble(BURST_LANE_START, BURST_LANE_END)) + bursts = (bursts + added).takeLast(MAX_BURSTS) + } + + fun finishBurst(id: Long) { + bursts = bursts.filter { it.id != id } + } + + fun reactionsPassed(previous: Double, current: Double, playing: Boolean) { + val detail = detail ?: return + val step = current - previous + if (!playing || step <= 0 || step >= MAX_BURST_STEP || !reactionsEnabled) return + detail.comments + .asSequence() + .filter { comment -> + val time = comment.timestamp + comment.type == CommentKind.EMOJI && + time != null && + time > previous && + time <= current + } + .take(MAX_BURSTS_PER_STEP) + .forEach { burst(it.content) } + } + + fun markerSelected(marker: TimelineMarker) { + if (!commentsEnabled) return + val first = + detail?.comments?.firstOrNull { + it.type == CommentKind.TEXT && it.id in marker.commentIds + } ?: return + section = Section.Comments + highlightedCommentId = first.id + } + + fun isMine(comment: CapComment): Boolean = comment.author.id == session.credentials.userId + + fun deleteComment(comment: CapComment): Job? { + if (detail == null) return null + return session.scope.launch { + try { + api.deleteComment(comment.id) + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + return@launch + } + edits.recordDeleted(comment.id) + edits.pages.toList().forEach { it.removeDeleted(comment.id) } + session.toasts.show("Comment deleted", R.drawable.ic_delete) + } + } + + private fun localComment( + kind: CommentKind, + text: String, + timestamp: Double?, + parentId: String?, + ): CapComment { + val user = session.bootstrap?.user + val now = Instant.now() + return CapComment( + id = "local-${UUID.randomUUID()}", + videoId = id.rawValue, + type = kind, + content = text, + timestamp = timestamp, + parentCommentId = parentId, + createdAt = now, + updatedAt = now, + author = CommentAuthor(session.credentials.userId, user?.displayName, user?.imageUrl), + ) + } + + private fun replaceLocal(localId: String, comment: CapComment) { + if (comment.id in edits.deleted || comment.parentCommentId in edits.deleted) { + removeLocal(localId) + return + } + pendingCommentIds = pendingCommentIds - localId + val detail = detail ?: return + val others = detail.comments.filter { it.id != comment.id } + val index = others.indexOfFirst { it.id == localId } + val comments = + if (index < 0) others + comment else others.toMutableList().also { it[index] = comment } + content = Content.Loaded(detail.copy(comments = comments)) + } + + private fun removeDeleted(commentId: String) { + val detail = detail ?: return + content = + Content.Loaded( + detail.copy( + comments = + detail.comments.filter { + it.id != commentId && it.parentCommentId != commentId + } + ) + ) + } + + private fun removeLocal(localId: String) { + pendingCommentIds = pendingCommentIds - localId + val detail = detail ?: return + content = + Content.Loaded(detail.copy(comments = detail.comments.filter { it.id != localId })) + } + + fun unlock(password: String): Job? { + val trimmed = password.trim() + if (isUnlocking || trimmed.isEmpty()) return null + isUnlocking = true + unlockError = null + return scope.launch { + try { + api.unlockCap(id, trimmed.take(CapManagement.MAX_PASSWORD)) + content = Content.Loading + performLoad() + } catch (failure: CapApiException) { + unlockError = failure.error + } finally { + isUnlocking = false + } + } + } + + fun playbackStarted(): Job? { + if (trackedView || isOwner) return null + trackedView = true + return scope.launch { + try { + api.trackView(id, viewSession) + } catch (_: CapApiException) {} + } + } + + fun reportPlaybackFailure() { + playbackFailed = true + } + + fun retry(): Job { + content = Content.Loading + return load() + } + + fun refresh(): Job = scope.launch { + val asked = edits.count + val fresh = + try { + api.cap(id) + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + return@launch + } + if (playbackFailed) mediaUrl = null + val attached = mediaUrl != null + apply(fresh, asked) + attachPlaybackIfNeeded(fresh) + if ( + attached && + transcriptUrl == null && + fresh.transcriptionStatus == TranscriptionStatus.COMPLETE + ) { + refetchTranscriptUrl() + } + if (transcript is Transcript.Unavailable) transcript = Transcript.Idle + loadTranscriptIfNeeded() + } + + private suspend fun refetchTranscriptUrl() { + try { + transcriptUrl = api.playback(id).transcriptUrl + } catch (_: CapApiException) {} + } + + private companion object { + const val MIN_FEEDBACK_TIME = 0.5 + const val MAX_BURSTS = 12 + const val MAX_BURSTS_PER_STEP = 3 + const val MAX_BURST_STEP = 1.5 + const val BURST_LANE_START = 0.15 + const val BURST_LANE_END = 0.85 + val BURST_GAP = 80.milliseconds + const val POLL_ATTEMPTS = 34 + val POLL_FIRST = 6.seconds + val POLL_LONGEST = 30.seconds + val viewSession: String by lazy { + val alphabet = ('a'..'z') + ('A'..'Z') + ('0'..'9') + String(CharArray(24) { alphabet.random() }) + } + } +} + +internal const val MAX_COMMENT = 2000 + +internal fun String.clippedToComment(): String { + if (length <= MAX_COMMENT) return this + return take(if (this[MAX_COMMENT - 1].isHighSurrogate()) MAX_COMMENT - 1 else MAX_COMMENT) +} + +private fun CapSummary.keepingEdits(edited: CapSummary): CapSummary = + copy( + title = edited.title, + isPublic = edited.isPublic, + isProtected = edited.isProtected, + linkAccess = edited.linkAccess, + linkRestricted = edited.linkRestricted, + ) diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModels.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModels.kt new file mode 100644 index 00000000000..8af35b9eb9b --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailModels.kt @@ -0,0 +1,119 @@ +package so.cap.mobile.features.cap + +import android.app.Application +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.lifecycle.ViewModel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import so.cap.kit.CapApi +import so.cap.kit.CapId +import so.cap.kit.ShareTarget +import so.cap.mobile.Route +import so.cap.mobile.app.PlaybackPreferences +import so.cap.mobile.app.SessionModel + +class CapDetailModels( + private val application: Application, + private val api: CapApi, + private val media: OkHttpClient, + private val preferences: PlaybackPreferences, + private val nowPlaying: NowPlaying, +) : ViewModel() { + private class Entry(val model: CapDetailModel, val scope: CoroutineScope) { + var player: CapPlayer? by mutableStateOf(null) + } + + private var session: SessionModel? = null + private val entries = mutableMapOf() + private val commentEdits = mutableMapOf() + + fun model(route: Route.Cap, session: SessionModel): CapDetailModel { + if (session !== this.session) { + keep(emptyList()) + commentEdits.clear() + this.session = session + session.onEnd { + if (this.session !== session) return@onEnd + keep(emptyList()) + commentEdits.clear() + this.session = null + } + } + entries[route]?.let { + return it.model + } + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + val target = + ShareTarget(checkNotNull(CapId.parse(route.id)), route.startTime, route.commentId) + val edits = commentEdits.getOrPut(route.id) { CommentEdits() } + val model = CapDetailModel(target, api, media, session, scope, edits) + val entry = Entry(model, scope) + entries[route] = entry + scope.launch { + snapshotFlow { model.playbackAttempt } + .filter { it > 0 } + .collectLatest { + val url = model.mediaUrl ?: return@collectLatest + val failed = entry.player + entry.player = null + failed?.let { old -> + nowPlaying.detach(old) + old.release() + } + val speed = preferences.speed() + val captions = preferences.captionsEnabled() + val cap = model.detail?.cap + val player = + CapPlayer( + application, + media, + url, + model.mediaKind, + speed, + captions, + preferences, + title = cap?.title ?: "Cap", + artist = cap?.ownerName?.ifEmpty { null }, + knownDuration = cap?.durationSeconds, + pendingStart = + failed?.currentTime?.takeIf { it > 0 } ?: target.startTime, + onFailed = model::reportPlaybackFailure, + ) + entry.player = player + nowPlaying.attach(application, player) + snapshotFlow { player.isPlaying }.first { it } + model.playbackStarted() + } + } + return model + } + + fun player(route: Route.Cap): CapPlayer? = entries[route]?.player + + fun keep(routes: Collection) { + val gone = entries.keys - routes.toSet() + gone.forEach { route -> + entries.remove(route)?.let { entry -> + entry.scope.cancel() + entry.player?.let { player -> + nowPlaying.detach(player) + player.release() + } + } + } + } + + override fun onCleared() { + keep(emptyList()) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailScreen.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailScreen.kt new file mode 100644 index 00000000000..56559a10dad --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapDetailScreen.kt @@ -0,0 +1,719 @@ +package so.cap.mobile.features.cap + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import androidx.annotation.DrawableRes +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.isImeVisible +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.net.toUri +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import so.cap.kit.CapApiError +import so.cap.kit.CapDetail +import so.cap.kit.CapFormat +import so.cap.kit.CapSummary +import so.cap.mobile.R +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.CapScopeSegmentedControl +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapThumbnail +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.InkButton +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.designsystem.SkeletonBlock +import so.cap.mobile.designsystem.SkeletonText +import so.cap.mobile.designsystem.monospacedDigit +import so.cap.mobile.designsystem.shimmering +import so.cap.mobile.features.cap.CapDetailModel.Content +import so.cap.mobile.features.cap.CapDetailModel.Section + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CapDetailScreen( + model: CapDetailModel, + player: CapPlayer?, + session: SessionModel, + onBack: () -> Unit, + onEdit: (CapSummary) -> Unit, + onAnalytics: (CapSummary) -> Unit, +) { + LaunchedEffect(model) { model.load() } + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column { + DetailTopBar(model, onBack) { + (model.content as? Content.Loaded)?.let { + CapMoreActions( + model, + player, + it.detail, + session, + onClose = onBack, + onEdit = onEdit, + onAnalytics = onAnalytics, + ) + } + } + when (val content = model.content) { + Content.Loading -> LoadingContent() + is Content.Loaded -> LoadedContent(model, player, content.detail, session) + Content.Locked -> PasswordGate(model) + Content.Restricted -> + AccessContent( + model, + R.drawable.ic_lock, + R.string.cap_restricted_title, + R.string.cap_restricted_message, + ) + is Content.Unavailable -> + if (content.error == CapApiError.NotFound) { + AccessContent( + model, + R.drawable.ic_videocam_off, + R.string.cap_not_found_title, + R.string.cap_not_found_message, + ) + } else { + EmptyState( + icon = R.drawable.ic_wifi_off, + title = stringResource(R.string.cap_load_failed), + modifier = Modifier.padding(top = 40.dp), + description = content.error.description, + actions = { + InkButton(onClick = { model.retry() }) { + Text(stringResource(R.string.home_try_again)) + } + }, + ) + } + } + } + } +} + +@Composable +private fun DetailTopBar( + model: CapDetailModel, + onBack: () -> Unit, + actions: @Composable () -> Unit = {}, +) { + val context = LocalContext.current + Row( + modifier = + Modifier.fillMaxWidth() + .safeDrawingPadding() + .height(CapTheme.touchTarget) + .padding(start = 12.dp, end = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack, modifier = Modifier.size(CapTheme.touchTarget)) { + Icon( + painterResource(R.drawable.ic_cap_back), + contentDescription = stringResource(R.string.navigate_back), + tint = MaterialTheme.colorScheme.onSurface, + ) + } + Spacer(Modifier.weight(1f)) + actions() + } +} + +@Composable +private fun LoadingContent() { + val label = stringResource(R.string.cap_loading) + Column( + modifier = + Modifier.fillMaxWidth() + .padding(CapTheme.spacing) + .clearAndSetSemantics { contentDescription = label } + .shimmering(), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + SkeletonBlock(Modifier.fillMaxWidth().aspectRatio(16f / 9f)) + SkeletonText( + "Loading this Cap title", + CapType.title2.copy(fontWeight = FontWeight.Bold), + ) + SkeletonText("Owner name · 2 days ago", CapType.body) + } +} + +@Composable +private fun AccessContent( + model: CapDetailModel, + @DrawableRes icon: Int, + title: Int, + message: Int, +) { + val context = LocalContext.current + val url = LocalCapEnvironment.current.shareUrl(model.id) + EmptyState( + icon = icon, + title = stringResource(title), + modifier = Modifier.padding(top = 40.dp), + description = stringResource(message), + actions = { + InkButton(onClick = { openInBrowser(context, url) }) { + Text(stringResource(R.string.cap_open_in_browser)) + } + }, + ) +} + +internal fun openInBrowser(context: Context, url: String) { + try { + context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri())) + } catch (_: ActivityNotFoundException) {} +} + +@OptIn( + ExperimentalMaterial3Api::class, + ExperimentalFoundationApi::class, + ExperimentalLayoutApi::class, +) +@Composable +private fun LoadedContent( + model: CapDetailModel, + player: CapPlayer?, + detail: CapDetail, + session: SessionModel, +) { + val owned = detail.cap.isOwned(session.credentials.userId) + val scope = rememberCoroutineScope() + var isRefreshing by remember { mutableStateOf(false) } + val current = model.currentSection + val list = rememberLazyListState() + val sectionsIndex = if (model.reactionsEnabled) 2 else 1 + val sectionStart = sectionsIndex + if (model.sections.size > 1) 1 else 0 + LaunchedEffect(player) { + if (player == null) return@LaunchedEffect + var previous = player.currentTime + snapshotFlow { player.currentTime } + .collect { now -> + model.reactionsPassed(previous, now, player.isPlaying) + previous = now + } + } + var transcriptQuery by rememberSaveable(current) { mutableStateOf("") } + LaunchedEffect(current) { if (current == Section.Transcript) model.loadTranscript() } + LaunchedEffect(model.sectionRevealRequests) { + if (model.sectionRevealRequests == 0) return@LaunchedEffect + delay(REVEAL_DELAY) + list.animateScrollToItem(sectionsIndex) + } + val highlighted = model.highlightedCommentId + var revealedCommentId by remember { mutableStateOf(null) } + LaunchedEffect(highlighted) { + revealedCommentId = null + val id = highlighted ?: return@LaunchedEffect + if (model.commentsEnabled) model.section = Section.Comments + commentItemOffset(model, id)?.let { offset -> + list.animateScrollToItem( + sectionStart + offset, + -list.layoutInfo.viewportSize.height / 3, + ) + } + revealedCommentId = id + delay(HIGHLIGHT_DURATION) + model.highlightedCommentId = null + } + BoxWithConstraints(Modifier.fillMaxSize()) { + val fullHeight = maxHeight + BoxWithConstraints(Modifier.fillMaxSize().imePadding()) { + val layout = + if (player?.isPictureInPicture == true) CapPageLayout.Stacked + else capPageLayout(maxWidth, fullHeight, maxHeight, WindowInsets.isImeVisible) + val width = maxWidth + val height = maxHeight + val showsVideo = layout != CapPageLayout.VideoAside + LaunchedEffect(showsVideo) { + if (showsVideo) return@LaunchedEffect + val reply = model.replyingTo?.id + if (reply == null && list.firstVisibleItemIndex > 0) return@LaunchedEffect + val target = + reply?.let { commentItemOffset(model, it) }?.plus(sectionStart) ?: sectionsIndex + list.animateScrollToItem(target) + } + val chapters = + if (detail.viewer.settings.disableChapters) emptyList() else detail.chapters + if ( + player != null && + player.isFullscreen && + !player.isPictureInPicture && + !model.playbackFailed + ) { + FullscreenPlayer(player, detail.cap.title, chapters, model.captions) { + BurstLayer(model, player.videoAspect) + } + } + val stage: @Composable ColumnScope.() -> Unit = { + val showsTimeline = + showsVideo && + player != null && + !model.playbackFailed && + !detail.viewer.isScreenshot && + !detail.viewer.overShareLimit && + (player.duration ?: 0.0) > 0 + val stageHeight = + capPlayerStageHeight( + width, + height, + showsTimeline, + reservesDetailHeight = layout != CapPageLayout.SideBySide, + minimumHeight = + if (layout == CapPageLayout.SideBySide) { + MINIMUM_SCROLLING_STAGE_HEIGHT + } else { + 0.dp + }, + ) + AnimatedVisibility(showsVideo) { + PlayerStage( + model, + player, + detail, + Modifier.fillMaxWidth(), + stageHeight, + ) + } + if (player != null && showsTimeline) { + MarkerLayer( + comments = detail.comments, + duration = player.duration ?: 0.0, + onSelect = { marker -> + player.seek(marker.time) + model.markerSelected(marker) + }, + modifier = + Modifier.padding(horizontal = CapTheme.spacing).padding(top = 6.dp), + ) + PlaybackChrome(player, chapters) + } + } + val feed: @Composable (Modifier) -> Unit = { modifier -> + Column(modifier) { + PullToRefreshBox( + isRefreshing = isRefreshing, + onRefresh = { + scope.launch { + isRefreshing = true + try { + model.refresh().join() + } finally { + isRefreshing = false + } + } + }, + modifier = Modifier.fillMaxWidth().weight(1f), + ) { + LazyColumn( + modifier = Modifier.fillMaxSize(), + state = list, + contentPadding = PaddingValues(top = 14.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + item(key = HEADER_KEY) { + Box(Modifier.padding(horizontal = CapTheme.spacing)) { + CapHeader(detail, owned) + } + } + if (model.reactionsEnabled) { + item(key = REACTIONS_KEY) { + ReactionBar( + model, + player, + Modifier.padding(horizontal = CapTheme.spacing), + ) + } + } + val sections = model.sections + if (sections.size > 1 && current != null) { + stickyHeader(key = SECTIONS_KEY) { + SectionPicker(model, sections, current) + } + } + when (current) { + Section.Comments -> + commentsSection(model, player, revealedCommentId) + Section.Summary -> summarySection(model, player) + Section.Transcript -> + transcriptSection( + model, + player, + session.toasts, + transcriptQuery, + ) { + transcriptQuery = it + } + null -> {} + } + } + } + if (current == Section.Comments && model.commentsEnabled) { + CommentComposer( + model, + player, + ownerName = if (owned) null else detail.cap.ownerName, + ) + } + } + } + if (layout == CapPageLayout.SideBySide) { + Row(Modifier.fillMaxSize()) { + Column( + Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()), + content = stage, + ) + feed(Modifier.weight(1f)) + } + } else { + Column(Modifier.fillMaxSize()) { + stage() + feed(Modifier.fillMaxWidth().weight(1f)) + } + } + } + } +} + +@Composable +private fun PlaybackChrome(player: CapPlayer, chapters: List) { + Column(Modifier.fillMaxWidth().padding(top = 8.dp)) { + Row( + modifier = Modifier.fillMaxWidth().height(48.dp).padding(start = 12.dp, end = 24.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = player::togglePlay, modifier = Modifier.size(44.dp)) { + Icon( + painterResource( + when { + player.hasEnded -> R.drawable.ic_replay + player.isPlaying -> R.drawable.ic_cap_pause + else -> R.drawable.ic_cap_play + } + ), + contentDescription = + stringResource( + when { + player.hasEnded -> R.string.player_replay + player.isPlaying -> R.string.player_pause + else -> R.string.player_play + } + ), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(26.dp), + ) + } + Text( + text = CapFormat.timestamp(player.scrubTime ?: player.currentTime), + color = MaterialTheme.colorScheme.onSurface, + style = CapType.largeMetric, + ) + player.duration?.let { duration -> + Text( + text = + stringResource(R.string.player_duration_of, CapFormat.timestamp(duration)), + modifier = Modifier.padding(start = 8.dp).weight(1f), + color = CapTheme.colors.textSecondary, + style = CapType.body.monospacedDigit(), + maxLines = 1, + ) + } ?: Spacer(Modifier.weight(1f)) + SpeedMenu( + player, + enabled = true, + contentColor = MaterialTheme.colorScheme.onSurface, + textStyle = + CapType.detailTitle.copy( + fontSize = 24.sp, + lineHeight = 28.sp, + fontWeight = FontWeight.SemiBold, + ), + ) + } + PlayerTimeline( + player = player, + chapters = chapters, + modifier = Modifier.padding(horizontal = CapTheme.pageMargin), + ) + } +} + +internal enum class CapPageLayout { + Stacked, + VideoAside, + SideBySide, +} + +internal fun capPageLayout( + width: Dp, + fullHeight: Dp, + height: Dp, + keyboardOpen: Boolean, +): CapPageLayout { + if (width > fullHeight) return CapPageLayout.SideBySide + if (!keyboardOpen) return CapPageLayout.Stacked + val video = (width * STAGE_HEIGHT_RATIO).coerceAtMost(360.dp) + val room = if (width < SMALL_PHONE_WIDTH) 260.dp else 220.dp + return if (height >= video + room) CapPageLayout.Stacked else CapPageLayout.VideoAside +} + +private val HIGHLIGHT_DURATION = 3.seconds +private val REVEAL_DELAY = 350.milliseconds +private val SMALL_PHONE_WIDTH = 390.dp + +@Composable +private fun SectionPicker(model: CapDetailModel, sections: List
, current: Section) { + val count = model.threadedCommentCount + CapScopeSegmentedControl( + options = + sections.map { item -> + if (item == Section.Comments && count > 0) { + stringResource(R.string.cap_section_comments_count, CapFormat.count(count)) + } else { + stringResource(item.title) + } + }, + selectedIndex = sections.indexOf(current).coerceAtLeast(0), + onSelected = { model.section = sections[it] }, + modifier = + Modifier.fillMaxWidth() + .background(MaterialTheme.colorScheme.background) + .padding(horizontal = CapTheme.pageMargin), + ) +} + +private const val HEADER_KEY = "header" +private const val REACTIONS_KEY = "reactions" +private const val STAGE_ASPECT = 16f / 9f +private const val SECTIONS_KEY = "sections" + +@Composable +private fun PlayerStage( + model: CapDetailModel, + player: CapPlayer?, + detail: CapDetail, + modifier: Modifier = Modifier, + heightLimit: Dp = 360.dp, +) { + BoxWithConstraints(modifier.fillMaxWidth().background(CapTheme.colors.dialFace)) { + val stageHeight = (maxWidth * STAGE_HEIGHT_RATIO).coerceAtMost(heightLimit) + Box( + modifier = Modifier.fillMaxWidth().height(stageHeight), + contentAlignment = Alignment.Center, + ) { + val playing = !detail.viewer.isScreenshot && !detail.viewer.overShareLimit + if (playing && player != null && !model.playbackFailed) { + if (!player.isFullscreen && !player.isPictureInPicture) + CapPlayerSurface( + player, + captions = model.captions, + surfaceColor = Color.Transparent, + compactInlineControls = true, + ) { + BurstLayer(model, player.videoAspect) + } + return@Box + } + CapThumbnail( + cap = detail.cap, + modifier = Modifier.fillMaxSize(), + cornerRadius = 0.dp, + showsBadges = false, + ) + when { + detail.viewer.isScreenshot -> {} + detail.viewer.overShareLimit -> + StageNotice( + R.drawable.ic_link, + stringResource( + if (detail.cap.isOwned(detail.cap.ownerId ?: "")) { + R.string.cap_over_share_limit_owner + } else { + R.string.cap_over_share_limit + } + ), + ) + detail.cap.upload != null -> {} + model.playbackFailed -> + StageNotice( + R.drawable.ic_play_disabled, + stringResource(R.string.cap_playback_failed), + ) + else -> CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) + } + BurstLayer(model, STAGE_ASPECT) + } + } +} + +private val STAGE_HEIGHT_RATIO = 360f / 412f + +internal fun capPlayerStageHeight( + width: Dp, + availableHeight: Dp, + showsPlaybackChrome: Boolean, + reservesDetailHeight: Boolean = true, + minimumHeight: Dp = 0.dp, +): Dp { + val designed = (width * STAGE_HEIGHT_RATIO).coerceAtMost(360.dp) + val reserved = + (if (reservesDetailHeight) MINIMUM_DETAIL_HEIGHT else 0.dp) + + if (showsPlaybackChrome) PLAYBACK_CHROME_HEIGHT else 0.dp + return minOf(designed, (availableHeight - reserved).coerceAtLeast(minimumHeight)) +} + +private val MINIMUM_DETAIL_HEIGHT = 96.dp +private val MINIMUM_SCROLLING_STAGE_HEIGHT = 120.dp +private val PLAYBACK_CHROME_HEIGHT = 92.dp + +@Composable +internal fun StageNotice(@DrawableRes icon: Int, text: String) { + Column( + modifier = + Modifier.padding(16.dp) + .clip(RoundedCornerShape(18.dp)) + .background(Color.Black.copy(alpha = 0.55f)) + .padding(16.dp) + .semantics(mergeDescendants = true) {}, + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + painterResource(icon), + contentDescription = null, + tint = Color.White, + modifier = Modifier.size(28.dp), + ) + Text( + text = text, + color = Color.White, + textAlign = TextAlign.Center, + style = CapType.footnote.copy(fontWeight = FontWeight.SemiBold), + ) + } +} + +@Composable +private fun CapHeader(detail: CapDetail, owned: Boolean) { + val cap = detail.cap + val secondary = CapTheme.colors.textSecondary + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + SelectionContainer(Modifier.weight(1f)) { + Text( + text = cap.title.ifEmpty { stringResource(R.string.cap_untitled) }, + color = MaterialTheme.colorScheme.onSurface, + style = CapType.detailTitle, + ) + } + if (owned) { + Icon( + painter = + painterResource( + if (cap.isPublic) R.drawable.ic_public else R.drawable.ic_lock + ), + contentDescription = + stringResource( + if (cap.isPublic) R.string.cap_public else R.string.cap_private + ), + tint = secondary, + modifier = Modifier.size(16.dp), + ) + } + } + Text( + text = + stringResource( + if (detail.viewer.isScreenshot) R.string.cap_kind_screenshot + else R.string.cap_kind_instant + ) + + ", " + + CapFormat.relative(cap.createdAt) + + ", " + + pluralStringResource( + R.plurals.cap_view_count, + cap.viewCount, + CapFormat.count(cap.viewCount), + ), + color = secondary, + style = CapType.metadata, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val upload = cap.upload + if (upload != null && cap.isProcessing) { + Text( + text = upload.statusText, + color = secondary, + style = CapType.small, + modifier = Modifier.padding(top = 8.dp), + ) + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapManagement.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapManagement.kt new file mode 100644 index 00000000000..3e5ad1779f5 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapManagement.kt @@ -0,0 +1,207 @@ +package so.cap.mobile.features.cap + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import java.io.IOException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import so.cap.kit.CapApi +import so.cap.kit.CapApiException +import so.cap.kit.ContentReportReason +import so.cap.kit.LinkAccess +import so.cap.kit.SafeUrl +import so.cap.mobile.R +import so.cap.mobile.app.SessionModel +import so.cap.mobile.app.SharingResult +import so.cap.mobile.app.Toast + +class CapManagement( + private val model: CapDetailModel, + private val api: CapApi, + private val media: OkHttpClient, + private val session: SessionModel, + private val scope: CoroutineScope, +) { + var updatingSharing by mutableStateOf(false) + private set + + var isSaving by mutableStateOf(false) + private set + + var isGone by mutableStateOf(false) + private set + + var savingPassword by mutableStateOf(false) + private set + + var passwordSaved by mutableStateOf(false) + private set + + fun setPublic(isPublic: Boolean): Job? = updateSharing(isPublic, linkAccess = null) + + fun setLinkAccess(linkAccess: LinkAccess): Job? = + if (model.detail?.cap?.isPublic == true) updateSharing(isPublic = true, linkAccess) + else null + + fun setAudience(isPublic: Boolean, linkAccess: LinkAccess? = null): Job? = + updateSharing(isPublic, linkAccess) + + private fun updateSharing(isPublic: Boolean, linkAccess: LinkAccess?): Job? { + val cap = model.detail?.cap ?: return null + if (updatingSharing || (linkAccess != null && !isPublic)) return null + val saving = session.setPublic(cap, isPublic, linkAccess) ?: return null + updatingSharing = true + model.capUpdated { it.copy(isPublic = isPublic, linkAccess = linkAccess ?: it.linkAccess) } + return scope.launch { + try { + when (val result = saving.await()) { + is SharingResult.Saved -> + model.capUpdated { + it.copy( + isPublic = result.cap.isPublic, + linkAccess = result.cap.linkAccess, + linkRestricted = result.cap.linkRestricted, + ) + } + is SharingResult.Refused -> + model.capUpdated { + it.copy( + isPublic = result.isPublic, + linkAccess = result.linkAccess, + linkRestricted = result.linkRestricted, + ) + } + is SharingResult.Superseded -> + result.isPublic?.let { isPublic -> + model.capUpdated { it.copy(isPublic = isPublic) } + } + } + } finally { + updatingSharing = false + } + } + } + + fun rename(title: String): Job? { + val cap = model.detail?.cap ?: return null + val trimmed = title.trim() + if (trimmed.isEmpty() || trimmed == cap.title) return null + return scope.launch { + try { + val updated = api.updateTitle(model.id, trimmed.take(MAX_TITLE)) + model.capUpdated { it.copy(title = updated.title) } + session.capChanged(updated.id) { it.copy(title = updated.title) } + session.toasts.show("Title updated", R.drawable.ic_edit) + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + } + } + } + + fun setPassword(password: String?): Deferred? { + if (model.detail == null || savingPassword) return null + if (password != null && password.length > MAX_PASSWORD) return null + savingPassword = true + return scope.async { + try { + val updated = api.updatePassword(model.id, password) + model.capUpdated { it.copy(isProtected = updated.isProtected) } + session.capChanged(updated.id) { it.copy(isProtected = updated.isProtected) } + if (password == null) { + session.toasts.show("Password removed", R.drawable.ic_lock_open) + } else { + session.toasts.show("Password set", R.drawable.ic_lock) + } + passwordSaved = true + true + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + false + } finally { + savingPassword = false + } + } + } + + fun forgetPasswordSaved() { + passwordSaved = false + } + + fun report(reason: ContentReportReason): Job = scope.launch { + try { + api.reportCap(model.id, reason) + session.toasts.show("Thanks. Cap Support will review this.", R.drawable.ic_flag) + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + } + } + + fun delete(): Deferred? { + val deleting = session.delete(model.detail?.cap ?: return null) ?: return null + return scope.async { deleting.await().also { if (it) isGone = true } } + } + + fun blockOwner(): Deferred? { + val ownerId = model.detail?.cap?.ownerId ?: return null + return scope.async { + try { + api.blockUser(ownerId) + session.ownerBlocked(model.id.rawValue) + session.toasts.show("User blocked", R.drawable.ic_back_hand) + isGone = true + true + } catch (failure: CapApiException) { + session.toasts.show(failure.error) + false + } + } + } + + fun saveToDevice(videos: DeviceVideos): Job? { + if (isSaving) return null + isSaving = true + session.toasts.show("Saving to your device…", R.drawable.ic_download, Toast.Style.Info) + return scope.launch { + val saved = + try { + val link = api.download(model.id) + val url = + SafeUrl.web(link.url) + ?: SafeUrl.media(link.url, api.environment) + ?: throw IOException("Refused the download address") + val file = media.downloadVideo(url, link.fileName, videos.scratch) + try { + videos.add(file, videoDisplayName(link.fileName)) + } finally { + file.delete() + } + true + } catch (_: CapApiException) { + false + } catch (_: IOException) { + false + } finally { + isSaving = false + } + if (saved) { + session.toasts.show("Saved to your device", R.drawable.ic_check_circle) + } else { + session.toasts.show( + "The video couldn't be saved. Try again.", + R.drawable.ic_warning, + Toast.Style.Error, + ) + } + } + } + + internal companion object { + private const val MAX_TITLE = 255 + const val MAX_PASSWORD = 512 + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapPlayer.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapPlayer.kt new file mode 100644 index 00000000000..37f2779abf7 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CapPlayer.kt @@ -0,0 +1,288 @@ +package so.cap.mobile.features.cap + +import android.content.Context +import androidx.annotation.OptIn +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableDoubleStateOf +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.MediaMetadata +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.VideoSize +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.okhttp.OkHttpDataSource +import androidx.media3.exoplayer.DefaultRenderersFactory +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.mediacodec.MediaCodecSelector +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import so.cap.kit.PlaybackKind +import so.cap.mobile.app.PlaybackPreferences + +@OptIn(UnstableApi::class) +class CapPlayer( + context: Context, + client: OkHttpClient, + url: String, + kind: PlaybackKind, + speed: Float, + captions: Boolean, + private val preferences: PlaybackPreferences, + title: String, + artist: String?, + knownDuration: Double?, + private var pendingStart: Double?, + private val onFailed: () -> Unit, +) { + private val failedDecoders = FailedDecoderTracker() + + private val mediaCodecSelector = + MediaCodecSelector { mimeType, requiresSecureDecoder, requiresTunnelingDecoder -> + failedDecoders.filter( + MediaCodecSelector.DEFAULT.getDecoderInfos( + mimeType, + requiresSecureDecoder, + requiresTunnelingDecoder, + ) + ) + } + + val player: ExoPlayer = + ExoPlayer.Builder( + context, + DefaultRenderersFactory(context).setMediaCodecSelector(mediaCodecSelector), + ) + .setMediaSourceFactory(DefaultMediaSourceFactory(OkHttpDataSource.Factory(client))) + .setSeekBackIncrementMs(SKIP_MILLIS) + .setSeekForwardIncrementMs(SKIP_MILLIS) + .setHandleAudioBecomingNoisy(true) + .build() + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var ticker: Job? = null + + private var presentations = 0 + + var isFullscreen by mutableStateOf(false) + + var isPictureInPicture by mutableStateOf(false) + + val controls = ControlsState(scope) + + var currentTime by mutableDoubleStateOf(0.0) + private set + + var duration: Double? by mutableStateOf(knownDuration?.takeIf { it > 0 }) + private set + + var isPlaying by mutableStateOf(false) + private set + + var isBuffering by mutableStateOf(false) + private set + + var hasEnded by mutableStateOf(false) + private set + + var videoAspect by mutableFloatStateOf(16f / 9f) + private set + + var rate by mutableFloatStateOf(speed) + private set + + var captionsEnabled by mutableStateOf(captions) + private set + + var scrubTime: Double? by mutableStateOf(null) + private set + + var isScrubbing by mutableStateOf(false) + private set + + private var wasPlayingBeforeScrub = false + + init { + player.addListener( + object : Player.Listener { + override fun onPlaybackStateChanged(playbackState: Int) { + isBuffering = playbackState == Player.STATE_BUFFERING && player.playWhenReady + when (playbackState) { + Player.STATE_READY -> ready() + Player.STATE_ENDED -> { + hasEnded = true + controls.show(autoHide = false) + } + Player.STATE_IDLE, + Player.STATE_BUFFERING -> {} + } + } + + override fun onIsPlayingChanged(playing: Boolean) { + isPlaying = playing + updateTime() + controls.playingChanged(playing) + ticker?.cancel() + if (!playing) return + hasEnded = false + ticker = scope.launch { + while (isActive) { + delay(TICK_MILLIS) + updateTime() + } + } + } + + override fun onPlayerError(error: PlaybackException) { + if ( + error.errorCode == PlaybackException.ERROR_CODE_DECODING_FAILED && + failedDecoders.excludeFailedDecoder(error) + ) { + val at = player.currentPosition + player.prepare() + player.seekTo(at) + return + } + onFailed() + } + + override fun onVideoSizeChanged(videoSize: VideoSize) { + if (videoSize.width <= 0 || videoSize.height <= 0) return + videoAspect = + (videoSize.width * videoSize.pixelWidthHeightRatio / videoSize.height) + .coerceIn(MIN_ASPECT, MAX_ASPECT) + } + } + ) + player.setPlaybackSpeed(speed) + player.setMediaItem( + MediaItem.Builder() + .setUri(url) + .setMimeType(kind.mimeType) + .setMediaMetadata(MediaMetadata.Builder().setTitle(title).setArtist(artist).build()) + .build() + ) + player.prepare() + } + + private fun ready() { + player.duration.takeIf { it != C.TIME_UNSET && it > 0 }?.let { duration = it / 1000.0 } + val start = pendingStart ?: return + pendingStart = null + seek(start, play = presentations > 0) + } + + private fun updateTime() { + if (isScrubbing) return + currentTime = player.currentPosition / 1000.0 + } + + fun seek(seconds: Double, play: Boolean = true) { + val target = seconds.coerceIn(0.0, duration ?: seconds.coerceAtLeast(0.0)) + currentTime = target + hasEnded = false + player.seekTo((target * 1000).toLong()) + if (play) player.play() + } + + fun presented() { + presentations += 1 + } + + fun dismissed() { + presentations -= 1 + scope.launch(Dispatchers.Main) { + if (presentations == 0 && !isFullscreen && !isPictureInPicture) player.pause() + } + } + + fun togglePlay() { + if (isPlaying || (isBuffering && player.playWhenReady)) { + player.pause() + } else { + if (hasEnded) seek(0.0, play = false) + player.play() + } + controls.show() + } + + fun skip(seconds: Double) { + seek(currentTime + seconds, play = isPlaying) + controls.show() + } + + fun changeRate(value: Float) { + rate = value + player.setPlaybackSpeed(value) + scope.launch { preferences.setSpeed(value) } + controls.show() + } + + fun toggleCaptions() { + val enabled = !captionsEnabled + captionsEnabled = enabled + scope.launch { preferences.setCaptionsEnabled(enabled) } + controls.show() + } + + fun beginScrub(): Boolean { + if (isScrubbing) return false + wasPlayingBeforeScrub = isPlaying + isScrubbing = true + controls.isScrubbing = true + scrubTime = currentTime + player.setScrubbingModeEnabled(true) + player.pause() + controls.show(autoHide = false) + return true + } + + fun updateScrub(seconds: Double) { + if (!isScrubbing) return + val target = seconds.coerceIn(0.0, duration ?: seconds.coerceAtLeast(0.0)) + scrubTime = target + player.seekTo((target * 1000).toLong()) + } + + fun endScrub() { + val target = scrubTime ?: return + if (!isScrubbing) return + isScrubbing = false + controls.isScrubbing = false + scrubTime = null + player.setScrubbingModeEnabled(false) + seek(target, play = wasPlayingBeforeScrub) + controls.scheduleHide() + } + + fun release() { + scope.cancel() + player.release() + } + + private companion object { + const val SKIP_MILLIS = 10_000L + const val TICK_MILLIS = 250L + const val MIN_ASPECT = 0.3f + const val MAX_ASPECT = 3f + } +} + +internal val PlaybackKind.mimeType: String? + get() = + when (this) { + PlaybackKind.MP4 -> null + PlaybackKind.HLS -> MimeTypes.APPLICATION_M3U8 + } diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Captions.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Captions.kt new file mode 100644 index 00000000000..341da841d19 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Captions.kt @@ -0,0 +1,82 @@ +package so.cap.mobile.features.cap + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.max +import androidx.compose.ui.unit.min +import so.cap.kit.TranscriptCue + +@Composable +internal fun CaptionOverlay(player: CapPlayer, cues: List, raised: Boolean) { + val caption by + remember(player, cues) { + derivedStateOf { + val time = player.currentTime + TranscriptCue.active(cues, time)?.caption(time)?.ifEmpty { null } + } + } + BoxWithConstraints(Modifier.fillMaxSize().clearAndSetSemantics {}) { + val videoHeight = videoHeight(maxWidth, maxHeight, player.videoAspect) + val videoBottom = maxHeight - (maxHeight - videoHeight) / 2 + val lift = if (raised) videoHeight * 0.18f else max(8.dp, videoHeight * 0.05f) + val gap by animateDpAsState(maxHeight - videoBottom + lift, tween(200)) + val fontSize = (maxWidth * 0.04f).coerceIn(15.dp, 24.dp) + val density = LocalDensity.current + AnimatedContent( + targetState = caption.takeIf { player.captionsEnabled }, + modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = gap), + transitionSpec = { fadeIn(tween(150)) togetherWith fadeOut(tween(150)) }, + contentKey = { it != null }, + label = "caption", + ) { shown -> + if (shown == null) return@AnimatedContent + Text( + shown, + modifier = + Modifier.widthIn(max = min(maxWidth * 0.92f, 620.dp)) + .background( + Color.Black.copy(alpha = 0.62f), + RoundedCornerShape(fontSize * 0.35f), + ) + .padding(horizontal = fontSize * 0.55f, vertical = fontSize * 0.25f), + color = Color.White, + fontSize = with(density) { fontSize.toSp() }, + lineHeight = with(density) { (fontSize * 1.2f + 2.dp).toSp() }, + fontWeight = FontWeight.Medium, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +private fun videoHeight(width: Dp, height: Dp, aspect: Float): Dp { + if (width <= 0.dp || height <= 0.dp || aspect <= 0f) return height + return if (width / height > aspect) height else width / aspect +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentEdits.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentEdits.kt new file mode 100644 index 00000000000..707d5c49f0e --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentEdits.kt @@ -0,0 +1,37 @@ +package so.cap.mobile.features.cap + +import so.cap.kit.CapComment + +class CommentEdits { + var count = 0 + private set + + var deleted = emptySet() + private set + + private var created = emptyList>() + + internal val pages = mutableSetOf() + + fun createdSince(asked: Int, served: Set): List = + created + .filter { (edit, comment) -> edit > asked && comment.id !in served } + .map { it.second } + + fun recordCreated(comment: CapComment) { + count += 1 + created = created + (count to comment) + } + + var capEditedAt = 0 + private set + + fun recordCapEdit() { + count += 1 + capEditedAt = count + } + + fun recordDeleted(id: String) { + deleted = deleted + id + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentsSection.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentsSection.kt new file mode 100644 index 00000000000..71d4230e60b --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/CommentsSection.kt @@ -0,0 +1,509 @@ +package so.cap.mobile.features.cap + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.util.Patterns +import androidx.annotation.StringRes +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.kit.CapComment +import so.cap.kit.CapFormat +import so.cap.kit.CommentThread +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.monospacedDigit + +internal fun LazyListScope.commentsSection( + model: CapDetailModel, + player: CapPlayer?, + revealedCommentId: String?, +) { + if (model.showsReactionCounts) { + item(key = REACTION_COUNTS_KEY) { + ReactionCounts(model, player, Modifier.padding(horizontal = CapTheme.spacing)) + } + } + val threads = model.orderedThreads + if (threads.isEmpty()) { + item(key = COMMENTS_EMPTY_KEY) { + EmptyState( + icon = R.drawable.ic_forum, + title = stringResource(R.string.comments_empty_title), + modifier = Modifier.padding(vertical = 12.dp), + description = stringResource(R.string.comments_empty_message), + ) + } + return + } + item(key = COMMENTS_HEADER_KEY) { + CommentsHeader(model, Modifier.padding(horizontal = CapTheme.spacing)) + } + items(threads, key = { it.id }) { thread -> + ThreadView( + thread, + model, + player, + revealedCommentId, + Modifier.padding(horizontal = CapTheme.spacing), + ) + } +} + +@Composable +private fun CommentsHeader(model: CapDetailModel, modifier: Modifier) { + var sorting by remember { mutableStateOf(false) } + val order = stringResource(model.commentOrder.title) + val sortLabel = stringResource(R.string.comments_sort_label, order) + Row( + modifier.fillMaxWidth().height(32.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Spacer(Modifier.weight(1f)) + Box { + TextButton( + onClick = { sorting = true }, + modifier = Modifier.semantics { contentDescription = sortLabel }, + ) { + Text(order, style = CapType.footnote.copy(fontWeight = FontWeight.Medium)) + Icon( + painterResource(R.drawable.ic_cap_chevron_down), + contentDescription = null, + modifier = Modifier.size(14.dp), + ) + } + DropdownMenu(expanded = sorting, onDismissRequest = { sorting = false }) { + for (option in CapDetailModel.CommentOrder.entries) { + DropdownMenuItem( + text = { Text(stringResource(option.title)) }, + onClick = { + model.commentOrder = option + sorting = false + }, + trailingIcon = + if (option == model.commentOrder) { + { Icon(painterResource(R.drawable.ic_cap_check), null) } + } else { + null + }, + ) + } + } + } + } +} + +@Composable +private fun ThreadView( + thread: CommentThread, + model: CapDetailModel, + player: CapPlayer?, + revealedCommentId: String?, + modifier: Modifier, +) { + Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) { + CommentRow(thread.root, model, player, isReply = false, revealedCommentId) + if (thread.replies.isEmpty()) return@Column + var expanded by rememberSaveable { mutableStateOf(false) } + val highlightsAReply = thread.replies.any { it.id == model.highlightedCommentId } + LaunchedEffect(highlightsAReply) { if (highlightsAReply) expanded = true } + val showAll = expanded || thread.replies.size <= COLLAPSED_REPLIES + 1 || highlightsAReply + val visible = if (showAll) thread.replies else thread.replies.take(COLLAPSED_REPLIES) + val line = MaterialTheme.colorScheme.outlineVariant + Column( + Modifier.padding(start = 12.dp).drawBehind { + val inset = 6.dp.toPx() + if (size.height <= inset * 2) return@drawBehind + drawRoundRect( + color = line, + topLeft = Offset(4.dp.toPx(), inset), + size = Size(2.dp.toPx(), size.height - inset * 2), + cornerRadius = CornerRadius(1.dp.toPx()), + ) + }, + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + for (reply in visible) { + CommentRow(reply, model, player, isReply = true, revealedCommentId) + } + if (!showAll) { + val hidden = thread.replies.size - visible.size + TextButton( + onClick = { expanded = true }, + modifier = Modifier.padding(start = 10.dp), + ) { + Icon( + painterResource(R.drawable.ic_expand_more), + contentDescription = null, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + pluralStringResource(R.plurals.comment_show_more, hidden, hidden), + style = CapType.footnote.copy(fontWeight = FontWeight.SemiBold), + ) + } + } + } + } +} + +@Composable +private fun CommentRow( + comment: CapComment, + model: CapDetailModel, + player: CapPlayer?, + isReply: Boolean, + revealedCommentId: String?, +) { + val context = LocalContext.current + val reveal = remember { BringIntoViewRequester() } + val isRevealed = revealedCommentId == comment.id + LaunchedEffect(isRevealed) { if (isRevealed) reveal.bringIntoView() } + val haptics = LocalHapticFeedback.current + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + val accent = MaterialTheme.colorScheme.primary + val authorName = + comment.author.name?.trim()?.ifEmpty { null } ?: stringResource(R.string.comment_anonymous) + val timestamp = comment.timestamp + val nowPlaying by + remember(comment.id, timestamp, player) { + derivedStateOf { + player != null && + timestamp != null && + player.currentTime >= timestamp && + player.currentTime < timestamp + NOW_PLAYING_SECONDS + } + } + val isPending = comment.id in model.pendingCommentIds + val isHighlighted = model.highlightedCommentId == comment.id + val tint by + animateColorAsState( + when { + isHighlighted -> accent.copy(alpha = 0.14f) + nowPlaying -> accent.copy(alpha = 0.07f) + else -> Color.Transparent + }, + tween(if (isHighlighted || nowPlaying) 250 else 400), + ) + val canReply = model.commentsEnabled && !isPending + val replyLabel = stringResource(R.string.comment_reply) + val replyToLabel = stringResource(R.string.comment_reply_to, authorName) + var menu by remember { mutableStateOf(false) } + var confirmingDelete by remember { mutableStateOf(false) } + val isMine = model.isMine(comment) + val deleteLabel = stringResource(R.string.comment_delete) + val copyLabel = stringResource(R.string.comment_copy) + val playLabel = timestamp?.let { + stringResource(R.string.comment_play_from, CapFormat.timestamp(it)) + } + val copy = { copyPlainText(context, R.string.comment_clip_label, comment.content) } + val play = { if (timestamp != null) player?.seek(timestamp) } + Box(Modifier.bringIntoViewRequester(reveal).alpha(if (isPending) PENDING_ALPHA else 1f)) { + Row( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(tint) + .pointerInput(comment.id, isPending) { + if (isPending) return@pointerInput + detectTapGestures( + onLongPress = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + menu = true + } + ) + } + .semantics(mergeDescendants = true) { + if (isPending) return@semantics + customActions = buildList { + if (canReply) { + add( + CustomAccessibilityAction(replyLabel) { + model.startReply(comment) + true + } + ) + } + add(CustomAccessibilityAction(copyLabel) { copy().let { true } }) + if (playLabel != null) { + add(CustomAccessibilityAction(playLabel) { play().let { true } }) + } + if (isMine) { + add( + CustomAccessibilityAction(deleteLabel) { + confirmingDelete = true + true + } + ) + } + } + } + .padding(10.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (timestamp != null && !isReply) { + TimestampChip(timestamp, nowPlaying, onClick = play) + } else { + Spacer(Modifier.width(40.dp)) + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Row( + Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + authorName, + modifier = Modifier.weight(1f, fill = false), + style = CapType.subheadline.copy(fontWeight = FontWeight.SemiBold), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + if (isPending) stringResource(R.string.comment_sending) + else CapFormat.relative(comment.createdAt), + color = secondary, + style = CapType.caption, + maxLines = 1, + ) + } + } + LinkifiedText(comment.content, style = CapType.body.copy(color = secondary)) + if (canReply) { + Text( + replyLabel, + modifier = + Modifier.clickable(role = Role.Button) { model.startReply(comment) } + .clearAndSetSemantics { + contentDescription = replyToLabel + role = Role.Button + }, + color = secondary, + style = CapType.footnote.copy(fontWeight = FontWeight.SemiBold), + ) + } + } + } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + text = { Text(copyLabel) }, + leadingIcon = { Icon(painterResource(R.drawable.ic_content_copy), null) }, + onClick = { + menu = false + copy() + }, + ) + if (model.commentsEnabled) { + DropdownMenuItem( + text = { Text(replyLabel) }, + leadingIcon = { Icon(painterResource(R.drawable.ic_reply), null) }, + onClick = { + menu = false + model.startReply(comment) + }, + ) + } + if (playLabel != null) { + DropdownMenuItem( + text = { Text(playLabel) }, + leadingIcon = { Icon(painterResource(R.drawable.ic_play_arrow), null) }, + onClick = { + menu = false + play() + }, + ) + } + if (isMine) { + val destructive = MaterialTheme.colorScheme.error + DropdownMenuItem( + text = { Text(deleteLabel, color = destructive) }, + leadingIcon = { + Icon(painterResource(R.drawable.ic_delete), null, tint = destructive) + }, + onClick = { + menu = false + confirmingDelete = true + }, + ) + } + } + } + if (confirmingDelete) { + AlertDialog( + onDismissRequest = { confirmingDelete = false }, + title = { Text(stringResource(R.string.comment_delete_title)) }, + text = + if (isReply) { + null + } else { + { Text(stringResource(R.string.comment_delete_message)) } + }, + confirmButton = { + TextButton( + onClick = { + confirmingDelete = false + model.deleteComment(comment) + } + ) { + Text(deleteLabel, color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { + TextButton(onClick = { confirmingDelete = false }) { + Text(stringResource(R.string.action_cancel)) + } + }, + ) + } +} + +@Composable +private fun TimestampChip(time: Double, isActive: Boolean, onClick: () -> Unit) { + val label = stringResource(R.string.comment_play_from, CapFormat.timestamp(time)) + Text( + CapFormat.timestamp(time), + modifier = + Modifier.width(40.dp) + .clip(RoundedCornerShape(6.dp)) + .clickable(role = Role.Button, onClick = onClick) + .clearAndSetSemantics { + contentDescription = label + role = Role.Button + } + .padding(vertical = 3.dp), + color = if (isActive) MaterialTheme.colorScheme.primary else CapTheme.colors.textSecondary, + style = CapType.caption.copy(fontWeight = FontWeight.SemiBold).monospacedDigit(), + ) +} + +@Composable +internal fun LinkifiedText(text: String, style: TextStyle, modifier: Modifier = Modifier) { + val accent = MaterialTheme.colorScheme.primary + val linked = + remember(text, accent) { + linkified( + text, + TextLinkStyles( + SpanStyle(color = accent, textDecoration = TextDecoration.Underline) + ), + ) + } + Text(linked, modifier = modifier, style = style) +} + +private fun linkified(text: String, styles: TextLinkStyles): AnnotatedString = + buildAnnotatedString { + append(text) + if (text.length >= MAX_LINKIFIED_LENGTH) return@buildAnnotatedString + val matcher = Patterns.WEB_URL.matcher(text) + var found = 0 + while (found < MAX_LINKS && matcher.find()) { + found += 1 + val match = matcher.group() + val scheme = match.substringBefore("://", "").lowercase() + val url = + when (scheme) { + "http", + "https" -> match + "" -> "http://$match" + else -> continue + } + addLink(LinkAnnotation.Url(url, styles), matcher.start(), matcher.end()) + } + } + +internal fun copyPlainText(context: Context, @StringRes label: Int, text: String) { + context + .getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText(context.getString(label), text)) +} + +private const val REACTION_COUNTS_KEY = "reaction-counts" +private const val COMMENTS_EMPTY_KEY = "comments-empty" +private const val COMMENTS_HEADER_KEY = "comments-header" +private const val NOW_PLAYING_SECONDS = 4.0 +private const val PENDING_ALPHA = 0.55f +private const val COLLAPSED_REPLIES = 2 + +internal fun commentItemOffset(model: CapDetailModel, commentId: String): Int? { + val index = + model.orderedThreads.indexOfFirst { thread -> + thread.id == commentId || thread.replies.any { it.id == commentId } + } + return if (index < 0) null else index + 1 + if (model.showsReactionCounts) 1 else 0 +} + +private val CapDetailModel.showsReactionCounts: Boolean + get() = reactionsEnabled && reactionCounts.isNotEmpty() + +private const val MAX_LINKS = 50 +private const val MAX_LINKIFIED_LENGTH = 20_000 diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Composer.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Composer.kt new file mode 100644 index 00000000000..2fae8dfcc9d --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Composer.kt @@ -0,0 +1,245 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.monospacedDigit + +@Composable +internal fun CommentComposer( + model: CapDetailModel, + player: CapPlayer?, + ownerName: String?, + modifier: Modifier = Modifier, +) { + val focusManager = LocalFocusManager.current + val focus = remember { FocusRequester() } + var focused by remember { mutableStateOf(false) } + val canSend = model.draft.isNotBlank() && !model.isSendingComment + val reply = model.replyingTo + val fallback = stringResource(R.string.composer_reply_fallback) + val placeholder = + when { + reply != null -> + stringResource(R.string.composer_reply, reply.author.name.firstWord() ?: fallback) + else -> + stringResource( + R.string.composer_comment_at, + CapFormat.timestamp(model.feedbackTimestamp(player?.currentTime ?: 0.0) ?: 0.0), + ) + } + val pins = reply == null && !model.isScreenshot + LaunchedEffect(reply?.id) { if (reply != null) focus.requestFocus() } + Column( + modifier.fillMaxWidth().padding(bottom = 4.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + so.cap.mobile.designsystem.CapHairline() + if (reply != null) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 20.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + Icon( + painterResource(R.drawable.ic_reply), + contentDescription = null, + tint = secondary, + modifier = Modifier.size(14.dp), + ) + Text( + stringResource(R.string.composer_replying_to, reply.author.name ?: fallback), + modifier = Modifier.weight(1f), + color = secondary, + style = CapType.footnote.copy(fontWeight = FontWeight.Medium), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + IconButton(onClick = model::cancelReply, modifier = Modifier.size(32.dp)) { + Icon( + painterResource(R.drawable.ic_cancel), + contentDescription = stringResource(R.string.composer_cancel_reply), + tint = secondary, + modifier = Modifier.size(18.dp), + ) + } + } + } + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + TextField( + value = model.draft, + onValueChange = { model.draft = it.clippedToComment() }, + modifier = + Modifier.weight(1f).focusRequester(focus).onFocusChanged { state -> + if (state.isFocused && !focused) { + model.beginComposing(player?.currentTime ?: 0.0) + player?.player?.pause() + } + focused = state.isFocused + }, + placeholder = { Text(placeholder) }, + leadingIcon = + if (pins) { + { TimestampToggle(model, player, focused) } + } else { + null + }, + shape = RoundedCornerShape(0.dp), + colors = + TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + ), + minLines = 1, + maxLines = 5, + ) + IconButton( + onClick = { + focusManager.clearFocus() + model.sendComment() + }, + enabled = canSend, + modifier = Modifier.padding(bottom = 6.dp).size(44.dp), + ) { + if (model.isSendingComment) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp).clearAndSetSemantics {}, + strokeWidth = 2.dp, + ) + } else { + Icon( + painterResource(R.drawable.ic_cap_send), + contentDescription = + stringResource( + if (reply == null) R.string.composer_send + else R.string.composer_send_reply + ), + ) + } + } + } + } +} + +private fun String?.firstWord(): String? = this?.split(' ')?.firstOrNull { it.isNotEmpty() } + +@Composable +private fun TimestampToggle(model: CapDetailModel, player: CapPlayer?, focused: Boolean) { + var open by remember { mutableStateOf(false) } + val accent = MaterialTheme.colorScheme.primary + val feedback = model.feedbackTimestamp(player?.currentTime ?: 0.0) + val pinned = model.composerTimestamp + val shown = pinned ?: if (focused) null else feedback + val label = + pinned?.let { stringResource(R.string.composer_pinned_to, CapFormat.timestamp(it)) } + ?: stringResource(R.string.composer_not_pinned) + Box(Modifier.padding(start = 8.dp)) { + Box( + Modifier.defaultMinSize(minWidth = 28.dp, minHeight = 28.dp) + .clip(CircleShape) + .then( + if (shown != null) Modifier.background(accent.copy(alpha = 0.14f)) else Modifier + ) + .clickable(role = Role.Button) { open = true } + .clearAndSetSemantics { + contentDescription = label + role = Role.Button + }, + contentAlignment = Alignment.Center, + ) { + if (shown != null) { + Text( + CapFormat.timestamp(shown), + modifier = Modifier.padding(horizontal = 8.dp), + color = accent, + style = + CapType.caption.copy(fontWeight = FontWeight.SemiBold).monospacedDigit(), + ) + } else { + Icon( + painterResource(R.drawable.ic_schedule), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp), + ) + } + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + if (feedback != null) { + DropdownMenuItem( + text = { + Text( + stringResource(R.string.composer_pin_to, CapFormat.timestamp(feedback)) + ) + }, + leadingIcon = { Icon(painterResource(R.drawable.ic_schedule), null) }, + onClick = { + model.composerTimestamp = feedback + open = false + }, + ) + } + if (pinned != null) { + DropdownMenuItem( + text = { Text(stringResource(R.string.composer_unpin)) }, + leadingIcon = { Icon(painterResource(R.drawable.ic_close), null) }, + onClick = { + model.composerTimestamp = null + open = false + }, + ) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/FailedDecoderTracker.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/FailedDecoderTracker.kt new file mode 100644 index 00000000000..d570275e064 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/FailedDecoderTracker.kt @@ -0,0 +1,28 @@ +package so.cap.mobile.features.cap + +import androidx.annotation.OptIn +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.mediacodec.MediaCodecDecoderException +import androidx.media3.exoplayer.mediacodec.MediaCodecInfo +import java.util.concurrent.CopyOnWriteArraySet + +@OptIn(UnstableApi::class) +internal class FailedDecoderTracker { + private val excludedNames = CopyOnWriteArraySet() + + fun filter(decoderInfos: List): List = + if (excludedNames.isEmpty()) decoderInfos + else decoderInfos.filterNot { it.name in excludedNames } + + fun excludeFailedDecoder(error: Throwable): Boolean { + var cause: Throwable? = error + while (cause != null) { + if (cause is MediaCodecDecoderException) { + val codecInfo = cause.codecInfo ?: return false + return excludedNames.add(codecInfo.name) + } + cause = cause.cause + } + return false + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MediaSession.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MediaSession.kt new file mode 100644 index 00000000000..f92854bd18b --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MediaSession.kt @@ -0,0 +1,90 @@ +package so.cap.mobile.features.cap + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.media3.session.MediaSession +import androidx.media3.session.MediaSessionService +import so.cap.mobile.CapApplication +import so.cap.mobile.MainActivity + +class NowPlaying { + var player: CapPlayer? = null + private set + + internal var onChange: ((CapPlayer?) -> Unit)? = null + + fun attach(context: Context, player: CapPlayer) { + this.player = player + val change = onChange + if (change != null) { + change(player) + } else { + context.startService(Intent(context, PlaybackService::class.java)) + } + } + + fun detach(player: CapPlayer) { + if (this.player !== player) return + this.player = null + onChange?.invoke(null) + } +} + +class PlaybackService : MediaSessionService() { + private var session: MediaSession? = null + private val change: (CapPlayer?) -> Unit = ::show + + private val nowPlaying: NowPlaying + get() = (application as CapApplication).nowPlaying + + override fun onCreate() { + super.onCreate() + nowPlaying.onChange = change + show(nowPlaying.player) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val result = super.onStartCommand(intent, flags, startId) + nowPlaying.onChange = change + show(nowPlaying.player) + return result + } + + private fun show(player: CapPlayer?) { + val current = session + when { + player == null -> { + release() + stopSelf() + } + current != null -> current.player = player.player + else -> { + val activity = + PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + val created = + MediaSession.Builder(this, player.player).setSessionActivity(activity).build() + session = created + addSession(created) + } + } + } + + override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session + + private fun release() { + if (nowPlaying.onChange === change) nowPlaying.onChange = null + session?.release() + session = null + } + + override fun onDestroy() { + release() + super.onDestroy() + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MoreMenu.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MoreMenu.kt new file mode 100644 index 00000000000..6ee7d8c9d80 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MoreMenu.kt @@ -0,0 +1,377 @@ +package so.cap.mobile.features.cap + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.os.Build +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.kit.CapDetail +import so.cap.kit.CapFormat +import so.cap.kit.CapSummary +import so.cap.kit.LinkAccess +import so.cap.kit.SafeUrl +import so.cap.mobile.R +import so.cap.mobile.app.SessionModel +import so.cap.mobile.app.ToastCenter +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapHairlineRow +import so.cap.mobile.designsystem.CapPrimaryButton +import so.cap.mobile.designsystem.CapRadioRow +import so.cap.mobile.designsystem.CapSwitch +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.features.home.DeleteCapDialog +import so.cap.mobile.features.home.copyCapLink +import so.cap.mobile.features.home.shareCap + +@Composable +internal fun CapMoreActions( + model: CapDetailModel, + player: CapPlayer?, + detail: CapDetail, + session: SessionModel, + onClose: () -> Unit, + onEdit: (CapSummary) -> Unit, + onAnalytics: (CapSummary) -> Unit, +) { + val management = model.management + var sheetOpen by rememberSaveable { mutableStateOf(false) } + val isGone = management.isGone + LaunchedEffect(isGone) { if (isGone) onClose() } + Box( + modifier = + Modifier.defaultMinSize(minWidth = CapTheme.touchTarget) + .height(CapTheme.touchTarget) + .clickable(role = Role.Button) { sheetOpen = true } + .padding(horizontal = 12.dp) + .semantics(mergeDescendants = true) { role = Role.Button }, + contentAlignment = Alignment.Center, + ) { + Text( + stringResource(R.string.cap_action_share), + color = MaterialTheme.colorScheme.onSurface, + style = CapType.bodyStrong, + ) + } + if (sheetOpen) { + CapShareSheet( + model, + player, + detail, + session, + onEdit, + onAnalytics, + onDismiss = { sheetOpen = false }, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun CapShareSheet( + model: CapDetailModel, + player: CapPlayer?, + detail: CapDetail, + session: SessionModel, + onEdit: (CapSummary) -> Unit, + onAnalytics: (CapSummary) -> Unit, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + val environment = LocalCapEnvironment.current + val cap = detail.cap + val webUrl = SafeUrl.web(cap.shareUrl) + val owned = cap.isOwned(session.credentials.userId) + val management = model.management + val videos = remember(context) { DeviceVideos(context.applicationContext) } + var dialog by rememberSaveable { mutableStateOf(null) } + when (dialog) { + MoreDialog.Rename -> + RenameDialog( + title = cap.title, + onSave = { title -> + dialog = null + management.rename(title) + }, + onDismiss = { dialog = null }, + ) + MoreDialog.Password -> { + LaunchedEffect(management.passwordSaved) { + if (management.passwordSaved) { + management.forgetPasswordSaved() + dialog = null + } + } + PasswordSheet( + isProtected = cap.isProtected, + isSaving = management.savingPassword, + onSave = { management.setPassword(it) }, + onDismiss = { dialog = null }, + ) + } + MoreDialog.Delete -> + DeleteCapDialog( + cap = cap, + onConfirm = { + dialog = null + management.delete() + }, + onDismiss = { dialog = null }, + ) + MoreDialog.Report -> + ReportDialog( + onReport = { reason -> + dialog = null + management.report(reason) + }, + onDismiss = { dialog = null }, + ) + MoreDialog.Block -> + BlockDialog( + ownerName = cap.ownerName, + onBlock = { + dialog = null + management.blockOwner() + }, + onDismiss = { dialog = null }, + ) + null -> {} + } + ModalBottomSheet( + onDismissRequest = onDismiss, + scrimColor = Color(0x80111111), + dragHandle = null, + ) { + Column( + Modifier.fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(start = 24.dp, end = 24.dp, bottom = 20.dp) + ) { + Row( + Modifier.fillMaxWidth().height(48.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.cap_action_share), + modifier = Modifier.weight(1f), + style = CapType.detailTitle, + ) + Text( + stringResource(R.string.cap_done), + modifier = + Modifier.defaultMinSize(minWidth = CapTheme.touchTarget) + .height(CapTheme.touchTarget) + .clickable(role = Role.Button, onClick = onDismiss) + .padding(horizontal = 8.dp) + .semantics(mergeDescendants = true) { role = Role.Button }, + color = MaterialTheme.colorScheme.onSurface, + style = CapType.bodyStrong, + ) + } + CapHairlineRow(minHeight = 60.dp, bottomHairline = true) { + Text( + cap.shareUrl, + modifier = Modifier.weight(1f).padding(end = 16.dp), + style = CapType.bodyStrong, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + CapPrimaryButton( + onClick = { copyCapLink(context, cap, session.toasts) }, + height = 44.dp, + ) { + Text(stringResource(R.string.cap_action_copy_link)) + } + } + SheetRow(stringResource(R.string.cap_action_share_link)) { shareCap(context, cap) } + if (owned) { + Text( + stringResource(R.string.cap_share_who_can_watch), + modifier = Modifier.padding(top = 18.dp, bottom = 4.dp), + color = CapTheme.colors.textSecondary, + style = CapType.small, + ) + val restricted = + cap.linkAccess == LinkAccess.RESTRICTED || cap.linkRestricted == true + CapRadioRow( + stringResource(R.string.cap_audience_anyone), + selected = cap.isPublic && !restricted, + onClick = { + management.setAudience(isPublic = true, LinkAccess.ANYONE) + }, + ) + CapRadioRow( + stringResource(R.string.cap_audience_organization), + selected = cap.isPublic && restricted, + onClick = { + management.setAudience(isPublic = true, LinkAccess.RESTRICTED) + }, + ) + CapRadioRow( + stringResource(R.string.cap_audience_private), + selected = !cap.isPublic, + onClick = { management.setPublic(false) }, + bottomHairline = false, + ) + CapHairlineRow(minHeight = 60.dp, topHairline = false, bottomHairline = true) { + Text( + stringResource(R.string.cap_password_sheet_title), + modifier = Modifier.weight(1f), + style = CapType.body, + ) + CapSwitch( + checked = cap.isProtected, + enabled = !management.savingPassword, + contentDescription = stringResource(R.string.cap_password_sheet_title), + onCheckedChange = { protect -> + if (protect) { + management.forgetPasswordSaved() + dialog = MoreDialog.Password + } else { + management.setPassword(null) + } + }, + ) + } + if (cap.isProtected) { + SheetRow(stringResource(R.string.cap_action_change_password)) { + management.forgetPasswordSaved() + dialog = MoreDialog.Password + } + } + SheetRow(stringResource(R.string.cap_action_rename)) { dialog = MoreDialog.Rename } + if (detail.viewer.canDownload && !detail.viewer.isScreenshot) { + SheetRow( + stringResource(R.string.cap_action_download_to_phone), + enabled = !management.isSaving && !cap.isProcessing, + ) { + management.saveToDevice(videos) + } + } + SheetRow(stringResource(R.string.cap_action_edit), enabled = !cap.isProcessing) { + onEdit(cap) + } + SheetRow(stringResource(R.string.cap_action_analytics)) { onAnalytics(cap) } + SheetRow(stringResource(R.string.cap_action_delete_this_cap), destructive = true) { + dialog = MoreDialog.Delete + } + } + if (!owned && detail.viewer.canDownload && !detail.viewer.isScreenshot) { + SheetRow( + stringResource(R.string.cap_action_download_to_phone), + enabled = !management.isSaving && !cap.isProcessing, + ) { + management.saveToDevice(videos) + } + } + val time = player?.currentTime?.takeIf { it > 0.5 && !detail.viewer.isScreenshot } + if (time != null) { + SheetRow( + stringResource(R.string.cap_action_copy_link_at, CapFormat.timestamp(time)) + ) { + copyCapLinkAt( + context, + environment.shareUrl(model.id, time), + time, + session.toasts, + ) + } + } + if (webUrl != null) { + SheetRow(stringResource(R.string.cap_open_in_browser)) { + openInBrowser(context, webUrl) + } + } + if (!owned) { + CapHairline(Modifier.padding(vertical = 8.dp)) + SheetRow(stringResource(R.string.cap_action_report)) { dialog = MoreDialog.Report } + if (cap.ownerId != null) { + SheetRow(stringResource(R.string.cap_action_block_owner), destructive = true) { + dialog = MoreDialog.Block + } + } + } + } + } +} + +@Composable +private fun SheetRow( + text: String, + enabled: Boolean = true, + destructive: Boolean = false, + onClick: () -> Unit, +) { + Row( + Modifier.fillMaxWidth() + .height(52.dp) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + .semantics(mergeDescendants = true) { role = Role.Button }, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text, + color = + when { + !enabled -> CapTheme.colors.textSecondary + destructive -> MaterialTheme.colorScheme.error + else -> MaterialTheme.colorScheme.onSurface + }, + style = CapType.body, + ) + } + CapHairline() +} + +private enum class MoreDialog { + Rename, + Password, + Delete, + Report, + Block, +} + +private fun copyCapLinkAt(context: Context, url: String, seconds: Double, toasts: ToastCenter) { + val label = context.getString(R.string.cap_link_clip_label) + context + .getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText(label, url)) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + toasts.show( + context.getString(R.string.cap_link_at_copied, CapFormat.timestamp(seconds)), + R.drawable.ic_link, + ) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordGate.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordGate.kt new file mode 100644 index 00000000000..933fea72ac3 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordGate.kt @@ -0,0 +1,192 @@ +package so.cap.mobile.features.cap + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicSecureTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.autofill.ContentType +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.contentType +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import so.cap.kit.CapApiError +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapMotion +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.ErrorText +import so.cap.mobile.designsystem.InkButton + +@Composable +internal fun PasswordGate(model: CapDetailModel) { + val password = rememberTextFieldState() + val focus = remember { FocusRequester() } + val canSubmit = password.text.isNotBlank() && !model.isUnlocking + LaunchedEffect(Unit) { focus.requestFocus() } + Column( + modifier = + Modifier.fillMaxWidth() + .verticalScroll(rememberScrollState()) + .imePadding() + .padding(24.dp) + .padding(top = 40.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Column( + modifier = Modifier.widthIn(max = 440.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(20.dp), + ) { + Box( + Modifier.size(76.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, CircleShape) + .clearAndSetSemantics {}, + contentAlignment = Alignment.Center, + ) { + Icon( + painterResource(R.drawable.ic_lock), + contentDescription = null, + modifier = Modifier.size(30.dp), + tint = MaterialTheme.colorScheme.primary, + ) + } + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + stringResource(R.string.cap_password_title), + modifier = Modifier.fillMaxWidth(), + style = CapType.title2.copy(fontWeight = FontWeight.Bold), + textAlign = TextAlign.Center, + ) + Text( + stringResource(R.string.cap_password_message), + modifier = Modifier.fillMaxWidth(), + style = CapType.body, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + PasswordField( + password = password, + label = stringResource(R.string.cap_password_label), + contentType = ContentType.Password, + imeAction = ImeAction.Go, + modifier = Modifier.focusRequester(focus), + onSubmit = { model.unlock(password.text.toString()) }, + ) + model.unlockError?.let { ErrorText(unlockMessage(it)) } + InkButton( + onClick = { model.unlock(password.text.toString()) }, + enabled = canSubmit, + ) { + if (model.isUnlocking) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp).clearAndSetSemantics {}, + color = LocalContentColor.current, + strokeWidth = 2.dp, + ) + } + Text(stringResource(R.string.cap_password_watch)) + } + } + } + } +} + +@Composable +private fun unlockMessage(error: CapApiError): String = + when (error) { + CapApiError.Forbidden -> stringResource(R.string.cap_password_wrong) + CapApiError.BadRequest -> stringResource(R.string.cap_password_too_many) + else -> error.description + } + +@Composable +internal fun PasswordField( + password: TextFieldState, + label: String, + contentType: ContentType, + imeAction: ImeAction, + modifier: Modifier, + onSubmit: () -> Unit, +) { + val interactions = remember { MutableInteractionSource() } + val focused by interactions.collectIsFocusedAsState() + val ink = MaterialTheme.colorScheme.onSurface + val ring by + animateColorAsState( + targetValue = if (focused) ink.copy(alpha = 0.25f) else Color.Transparent, + animationSpec = CapMotion.focus(), + ) + BasicSecureTextField( + state = password, + modifier = + modifier.fillMaxWidth().semantics { + contentDescription = label + this.contentType = contentType + }, + textStyle = CapType.body.copy(color = ink), + keyboardOptions = + KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction), + onKeyboardAction = { onSubmit() }, + interactionSource = interactions, + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + decorator = { field -> + Box( + modifier = + Modifier.defaultMinSize(minHeight = 52.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, CircleShape) + .border(1.dp, ring, CircleShape) + .padding(horizontal = 18.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (password.text.isEmpty()) { + Text( + text = label, + color = MaterialTheme.colorScheme.outline, + style = CapType.body, + ) + } + field() + } + }, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordSheet.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordSheet.kt new file mode 100644 index 00000000000..16d7efb69ef --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PasswordSheet.kt @@ -0,0 +1,125 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.ModalBottomSheetProperties +import androidx.compose.material3.SheetValue +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.autofill.ContentType +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.features.home.SheetHeader +import so.cap.mobile.features.home.rememberSheetFocus + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun PasswordSheet( + isProtected: Boolean, + isSaving: Boolean, + onSave: (String?) -> Unit, + onDismiss: () -> Unit, +) { + val password = rememberTextFieldState() + val tooLong = password.text.trim().length > CapManagement.MAX_PASSWORD + val save: (String?) -> Unit = { value -> + if (!isSaving) onSave(value?.trim()?.ifEmpty { null }) + } + val sheetState = + rememberBottomSheetState( + SheetValue.Hidden, + setOf(SheetValue.Hidden, SheetValue.Expanded), + confirmValueChange = { it != SheetValue.Hidden || !isSaving }, + ) + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + properties = ModalBottomSheetProperties(shouldDismissOnBackPress = !isSaving), + ) { + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = CapTheme.spacing)) { + SheetHeader( + title = + stringResource( + if (isProtected) R.string.cap_password_sheet_title + else R.string.cap_action_add_password + ), + confirmLabel = stringResource(R.string.action_save), + confirmIcon = R.drawable.ic_check, + confirmEnabled = password.text.isNotBlank() && !tooLong, + isWorking = isSaving, + onCancel = onDismiss, + onConfirm = { save(password.text.toString()) }, + ) + Column( + modifier = + Modifier.weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + .padding(top = 16.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + val focus = rememberSheetFocus() + PasswordField( + password = password, + label = + stringResource( + if (isProtected) R.string.cap_password_new + else R.string.cap_password_label + ), + contentType = ContentType.NewPassword, + imeAction = ImeAction.Done, + modifier = Modifier.focusRequester(focus), + onSubmit = { + if (password.text.isNotBlank() && !tooLong) save(password.text.toString()) + }, + ) + if (tooLong) { + Text( + text = + pluralStringResource( + R.plurals.cap_password_too_long, + CapManagement.MAX_PASSWORD, + CapManagement.MAX_PASSWORD, + ), + color = MaterialTheme.colorScheme.error, + style = CapType.footnote, + ) + } + Text( + text = stringResource(R.string.cap_password_footer), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.footnote, + ) + if (isProtected) { + TextButton( + onClick = { save(null) }, + enabled = !isSaving, + colors = + ButtonDefaults.textButtonColors( + contentColor = MaterialTheme.colorScheme.error + ), + ) { + Text(stringResource(R.string.cap_password_remove)) + } + } + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PictureInPicture.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PictureInPicture.kt new file mode 100644 index 00000000000..774b5e6e379 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PictureInPicture.kt @@ -0,0 +1,128 @@ +package so.cap.mobile.features.cap + +import android.app.Activity +import android.app.PictureInPictureParams +import android.content.pm.PackageManager +import android.graphics.Rect +import android.os.Build +import android.util.Rational +import androidx.annotation.OptIn +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.compose.PlayerSurface + +class PictureInPicture(private val activity: Activity) { + val isSupported: Boolean = + activity.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) + + var candidate: CapPlayer? by mutableStateOf(null) + private set + + var player: CapPlayer? by mutableStateOf(null) + private set + + var sourceRect: Rect? by mutableStateOf(null) + private set + + fun shown(player: CapPlayer) { + candidate = player + } + + fun hidden(player: CapPlayer) { + if (candidate !== player) return + candidate = null + sourceRect = null + } + + fun placed(player: CapPlayer, bounds: Rect) { + if (candidate === player && sourceRect != bounds) sourceRect = bounds + } + + fun enter(): Boolean { + val player = candidate ?: return false + if (!isSupported) return false + return try { + activity.enterPictureInPictureMode(params(player)) + } catch (_: IllegalStateException) { + false + } + } + + fun enterIfPlaying() { + if (candidate?.isPlaying == true) enter() + } + + fun modeChanged(active: Boolean, closed: Boolean) { + val current = if (active) candidate else player + current?.isPictureInPicture = active + player = if (active) current else null + if (!active && closed) current?.player?.pause() + } + + fun update() { + if (!isSupported || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return + val player = candidate + val builder = PictureInPictureParams.Builder() + if (player != null) builder.setAspectRatio(rational(player.videoAspect)) + builder.setSourceRectHint(sourceRect) + builder.setAutoEnterEnabled(player?.isPlaying == true) + activity.setPictureInPictureParams(builder.build()) + } + + private fun params(player: CapPlayer): PictureInPictureParams = + PictureInPictureParams.Builder() + .setAspectRatio(rational(player.videoAspect)) + .setSourceRectHint(sourceRect) + .build() + + private fun rational(aspect: Float): Rational = + Rational((aspect.coerceIn(MIN_ASPECT, MAX_ASPECT) * 1000).toInt(), 1000) + + private companion object { + const val MIN_ASPECT = 0.42f + const val MAX_ASPECT = 2.39f + } +} + +val LocalPictureInPicture = staticCompositionLocalOf { null } + +@Composable +fun PictureInPictureParamsEffect(pictureInPicture: PictureInPicture) { + LaunchedEffect(pictureInPicture) { + snapshotFlow { + val player = pictureInPicture.candidate + listOf(player, player?.isPlaying, player?.videoAspect, pictureInPicture.sourceRect) + } + .collect { pictureInPicture.update() } + } +} + +@OptIn(UnstableApi::class) +@Composable +fun PictureInPictureContent(player: CapPlayer) { + DisposableEffect(player) { + player.presented() + onDispose { player.dismissed() } + } + Box(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) { + PlayerSurface( + player = player.player, + modifier = Modifier.aspectRatio(player.videoAspect).clearAndSetSemantics {}, + ) + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PlayerControls.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PlayerControls.kt new file mode 100644 index 00000000000..7967524702d --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/PlayerControls.kt @@ -0,0 +1,594 @@ +package so.cap.mobile.features.cap + +import android.content.Context +import android.content.pm.ActivityInfo +import android.graphics.Rect +import android.view.accessibility.AccessibilityManager +import androidx.activity.compose.LocalActivity +import androidx.annotation.DrawableRes +import androidx.annotation.OptIn +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.gestures.detectVerticalDragGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.hideFromAccessibility +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.window.DialogWindowProvider +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.compose.PlayerSurface +import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.util.Locale +import kotlin.math.roundToInt +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import so.cap.kit.CapViewer +import so.cap.kit.Chapter +import so.cap.kit.TranscriptCue +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.monospacedDigit + +class ControlsState(private val scope: CoroutineScope) { + var visible by mutableStateOf(true) + private set + + var isPlaying = false + private set + + var isScrubbing = false + + private var hide: Job? = null + + fun show(autoHide: Boolean = true) { + visible = true + if (autoHide) scheduleHide() else hide?.cancel() + } + + fun toggle() { + if (visible && isPlaying) { + hide?.cancel() + visible = false + } else { + show() + } + } + + fun playingChanged(playing: Boolean) { + isPlaying = playing + if (playing) scheduleHide() else if (!isScrubbing) show(autoHide = false) + } + + fun scheduleHide() { + hide?.cancel() + if (!isPlaying) return + hide = scope.launch { + delay(HIDE_AFTER) + if (isPlaying && !isScrubbing) visible = false + } + } + + companion object { + val HIDE_AFTER = 3.seconds + } +} + +@OptIn(UnstableApi::class) +@Composable +fun CapPlayerSurface( + player: CapPlayer, + modifier: Modifier = Modifier, + isFullscreen: Boolean = false, + title: String? = null, + chapters: List = emptyList(), + captions: List? = null, + surfaceColor: Color = Color.Black, + compactInlineControls: Boolean = false, + overlay: @Composable () -> Unit = {}, +) { + val pictureInPicture = LocalPictureInPicture.current + DisposableEffect(player, isFullscreen, pictureInPicture) { + player.presented() + pictureInPicture?.shown(player) + onDispose { + pictureInPicture?.hidden(player) + player.dismissed() + } + } + val view = LocalView.current + val playing = player.isPlaying + DisposableEffect(view, playing) { + view.keepScreenOn = playing + onDispose { view.keepScreenOn = false } + } + val label = stringResource(R.string.player_label) + Box( + modifier + .fillMaxSize() + .background(surfaceColor) + .semantics { contentDescription = label } + .onGloballyPositioned { coordinates -> + if (isFullscreen) return@onGloballyPositioned + val bounds = coordinates.boundsInWindow() + pictureInPicture?.placed( + player, + Rect( + bounds.left.roundToInt(), + bounds.top.roundToInt(), + bounds.right.roundToInt(), + bounds.bottom.roundToInt(), + ), + ) + }, + contentAlignment = Alignment.Center, + ) { + PlayerSurface( + player = player.player, + modifier = Modifier.aspectRatio(player.videoAspect).clearAndSetSemantics {}, + ) + if (captions != null) { + val raised = isFullscreen && (player.controls.visible || !player.isPlaying) + CaptionOverlay(player, captions, raised) + } + overlay() + GestureLayer(player) + PlayerControls( + player, + isFullscreen, + title, + chapters, + captionsAvailable = captions != null, + compactInlineControls, + ) + } +} + +@Composable +fun FullscreenPlayer( + player: CapPlayer, + title: String?, + chapters: List, + captions: List?, + overlay: @Composable () -> Unit, +) { + val activity = LocalActivity.current + val density = LocalDensity.current + var dragOffset by remember { mutableFloatStateOf(0f) } + val shownOffset by animateFloatAsState(dragOffset, tween(if (dragOffset == 0f) 250 else 0)) + Dialog( + onDismissRequest = { player.isFullscreen = false }, + properties = + DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false), + ) { + val window = (LocalView.current.parent as? DialogWindowProvider)?.window + DisposableEffect(window, activity) { + val previous = activity?.requestedOrientation + if (player.videoAspect > LANDSCAPE_ASPECT) { + activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + } + val insets = window?.let { WindowCompat.getInsetsController(it, it.decorView) } + insets?.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + insets?.hide(WindowInsetsCompat.Type.systemBars()) + player.controls.show() + onDispose { + if (previous != null) activity.requestedOrientation = previous + } + } + CapPlayerSurface( + player = player, + modifier = + Modifier.graphicsLayer { translationY = shownOffset } + .pointerInput(player) { + val dismissAt = with(density) { DISMISS_DRAG.toPx() } + detectVerticalDragGestures( + onDragEnd = { + if (dragOffset > dismissAt) player.isFullscreen = false + dragOffset = 0f + }, + onDragCancel = { dragOffset = 0f }, + ) { change, amount -> + dragOffset = (dragOffset + amount).coerceAtLeast(0f) + change.consume() + } + }, + isFullscreen = true, + title = title, + chapters = chapters, + captions = captions, + overlay = overlay, + ) + } +} + +@Composable +private fun GestureLayer(player: CapPlayer) { + var feedback by remember { mutableStateOf?>(null) } + BoxWithConstraints( + Modifier.fillMaxSize() + .semantics { hideFromAccessibility() } + .pointerInput(player) { + detectTapGestures( + onTap = { player.controls.toggle() }, + onDoubleTap = { offset -> + val forward = offset.x > size.width / 2 + player.skip(if (forward) SKIP_SECONDS else -SKIP_SECONDS) + feedback = forward to System.nanoTime() + }, + ) + } + ) { + val shown = feedback + LaunchedEffect(shown) { + if (shown == null) return@LaunchedEffect + delay(FEEDBACK_SHOWN) + feedback = null + } + AnimatedVisibility( + visible = shown != null, + modifier = + Modifier.align( + if (shown?.first == false) Alignment.CenterStart else Alignment.CenterEnd + ) + .padding(horizontal = maxWidth * 0.12f), + enter = fadeIn(tween(200)) + scaleIn(initialScale = 0.8f), + exit = fadeOut(tween(200)), + ) { + Icon( + painterResource( + if (shown?.first == false) R.drawable.ic_replay_10 else R.drawable.ic_forward_10 + ), + contentDescription = null, + tint = Color.White, + modifier = + Modifier.background(Color.Black.copy(alpha = 0.35f), CircleShape) + .padding(18.dp) + .size(30.dp), + ) + } + } +} + +@Composable +private fun PlayerControls( + player: CapPlayer, + isFullscreen: Boolean, + title: String?, + chapters: List, + captionsAvailable: Boolean, + compactInlineControls: Boolean = false, +) { + val controls = player.controls + val visible = controls.visible || !player.isPlaying || rememberTouchExploration() + val alpha by animateFloatAsState(if (visible) 1f else 0f, tween(200)) + if (alpha == 0f) return + Box( + Modifier.fillMaxSize() + .alpha(alpha) + .background( + Brush.verticalGradient( + listOf( + Color.Black.copy(alpha = 0.45f), + Color.Transparent, + Color.Transparent, + Color.Black.copy(alpha = if (isFullscreen) 0.55f else 0.25f), + ) + ) + ) + .then(if (visible) Modifier else Modifier.clearAndSetSemantics {}), + contentAlignment = Alignment.Center, + ) { + if (player.isBuffering && !controls.isScrubbing) { + CircularProgressIndicator(color = Color.White) + } else if (!compactInlineControls || isFullscreen) { + Row( + horizontalArrangement = Arrangement.spacedBy(28.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ControlButton( + R.drawable.ic_replay_10, + stringResource(R.string.player_back), + SKIP_BUTTON, + enabled = visible, + ) { + player.skip(-SKIP_SECONDS) + } + ControlButton( + when { + player.hasEnded -> R.drawable.ic_replay + player.isPlaying -> R.drawable.ic_pause + else -> R.drawable.ic_play_arrow + }, + stringResource( + when { + player.hasEnded -> R.string.player_replay + player.isPlaying -> R.string.player_pause + else -> R.string.player_play + } + ), + PLAY_BUTTON, + enabled = visible, + onClick = player::togglePlay, + ) + ControlButton( + R.drawable.ic_forward_10, + stringResource(R.string.player_forward), + SKIP_BUTTON, + enabled = visible, + ) { + player.skip(SKIP_SECONDS) + } + } + } + Row( + Modifier.align(Alignment.TopStart) + .fillMaxWidth() + .then(if (isFullscreen) Modifier.safeDrawingPadding() else Modifier) + .padding(horizontal = if (isFullscreen) 20.dp else 8.dp) + .padding(top = if (isFullscreen) 12.dp else 6.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isFullscreen) { + TopBarButton( + R.drawable.ic_close, + stringResource(R.string.player_close_fullscreen), + enabled = visible, + ) { + player.isFullscreen = false + } + if (title != null) { + Text( + title, + modifier = Modifier.weight(1f, fill = false), + color = Color.White, + style = CapType.headline, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + Spacer(Modifier.weight(1f)) + if (captionsAvailable) { + TopBarButton( + if (player.captionsEnabled) R.drawable.ic_closed_caption + else R.drawable.ic_closed_caption_disabled, + stringResource( + if (player.captionsEnabled) R.string.player_hide_captions + else R.string.player_show_captions + ), + enabled = visible, + onClick = player::toggleCaptions, + ) + } + if (!compactInlineControls || isFullscreen) SpeedMenu(player, enabled = visible) + val pictureInPicture = LocalPictureInPicture.current + if (!isFullscreen && pictureInPicture?.isSupported == true) { + TopBarButton( + R.drawable.ic_picture_in_picture_alt, + stringResource(R.string.player_picture_in_picture), + enabled = visible, + ) { + pictureInPicture.enter() + } + } + if (!isFullscreen) { + TopBarButton( + R.drawable.ic_fullscreen, + stringResource(R.string.player_fullscreen), + enabled = visible, + ) { + player.isFullscreen = true + } + } + } + if (isFullscreen) { + PlayerTimeline( + player = player, + chapters = chapters, + modifier = + Modifier.align(Alignment.BottomCenter) + .safeDrawingPadding() + .padding(horizontal = 20.dp) + .padding(bottom = 12.dp), + style = TimelineStyle.Overlay, + ) + } + } +} + +@Composable +internal fun TopBarButton( + @DrawableRes icon: Int, + label: String, + enabled: Boolean, + onClick: () -> Unit, +) { + IconButton( + onClick = onClick, + enabled = enabled, + modifier = Modifier.size(40.dp), + colors = + IconButtonDefaults.iconButtonColors( + contentColor = Color.White, + disabledContentColor = Color.White, + ), + ) { + Icon(painterResource(icon), contentDescription = label, modifier = Modifier.size(22.dp)) + } +} + +@Composable +internal fun SpeedMenu( + player: CapPlayer, + enabled: Boolean, + contentColor: Color = Color.White, + textStyle: androidx.compose.ui.text.TextStyle = + CapType.subheadline.copy(fontWeight = FontWeight.SemiBold).monospacedDigit(), +) { + var open by remember { mutableStateOf(false) } + val name = speedName(player.rate) + val label = stringResource(R.string.player_speed_label, name) + Box { + TextButton( + onClick = { open = true }, + enabled = enabled, + modifier = + Modifier.defaultMinSize(40.dp, 40.dp).semantics { contentDescription = label }, + colors = + ButtonDefaults.textButtonColors( + contentColor = contentColor, + disabledContentColor = contentColor, + ), + ) { + Text( + name, + modifier = Modifier.clearAndSetSemantics {}, + style = textStyle, + ) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + for (speed in CapViewer.PLAYBACK_SPEEDS) { + val selected = speed == player.rate + DropdownMenuItem( + text = { Text(speedName(speed)) }, + onClick = { + open = false + player.changeRate(speed) + }, + modifier = Modifier.semantics { this.selected = selected }, + trailingIcon = + if (selected) { + { + Icon( + painterResource(R.drawable.ic_check), + contentDescription = null, + ) + } + } else { + null + }, + ) + } + } + } +} + +internal fun speedName(rate: Float, locale: Locale = Locale.getDefault()): String = + DecimalFormat("0.##", DecimalFormatSymbols(locale)).format(rate.toDouble()) + "×" + +@Composable +private fun ControlButton( + @DrawableRes icon: Int, + label: String, + size: Dp, + enabled: Boolean, + onClick: () -> Unit, +) { + IconButton( + onClick = onClick, + enabled = enabled, + modifier = Modifier.size(size), + colors = + IconButtonDefaults.iconButtonColors( + containerColor = Color.Black.copy(alpha = 0.3f), + contentColor = Color.White, + disabledContainerColor = Color.Black.copy(alpha = 0.3f), + disabledContentColor = Color.White, + ), + ) { + Icon( + painterResource(icon), + contentDescription = label, + modifier = Modifier.size(size * 0.5f), + ) + } +} + +@Composable +internal fun rememberTouchExploration(): Boolean { + val context = LocalContext.current + val manager = + remember(context) { + context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager + } + var enabled by remember(manager) { mutableStateOf(manager.isTouchExplorationEnabled) } + DisposableEffect(manager) { + val listener = AccessibilityManager.TouchExplorationStateChangeListener { enabled = it } + manager.addTouchExplorationStateChangeListener(listener) + onDispose { manager.removeTouchExplorationStateChangeListener(listener) } + } + return enabled +} + +private const val SKIP_SECONDS = 10.0 +private const val LANDSCAPE_ASPECT = 1.05f +private val DISMISS_DRAG = 120.dp +private val FEEDBACK_SHOWN = 650.milliseconds +private val PLAY_BUTTON = 66.dp +private val SKIP_BUTTON = 46.dp diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Reactions.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Reactions.kt new file mode 100644 index 00000000000..9c2032b2a2d --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Reactions.kt @@ -0,0 +1,158 @@ +package so.cap.mobile.features.cap + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.min +import kotlinx.coroutines.delay +import so.cap.kit.CapFormat +import so.cap.kit.Reactions +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.monospacedDigit + +@Composable +internal fun ReactionBar(model: CapDetailModel, player: CapPlayer?, modifier: Modifier = Modifier) { + val haptics = LocalHapticFeedback.current + val density = LocalDensity.current + Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + for (emoji in Reactions.emojis) { + val label = stringResource(R.string.reaction_label, emoji) + Box( + Modifier.weight(1f) + .heightIn(min = 44.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .clickable(role = Role.Button) { + haptics.performHapticFeedback(HapticFeedbackType.ContextClick) + model.react(emoji, player?.currentTime ?: 0.0) + } + .semantics { contentDescription = label }, + contentAlignment = Alignment.Center, + ) { + Text( + emoji, + fontSize = with(density) { min(22.dp * fontScale, 30.dp).toSp() }, + modifier = Modifier.clearAndSetSemantics {}, + ) + } + } + } +} + +@Composable +internal fun ReactionCounts( + model: CapDetailModel, + player: CapPlayer?, + modifier: Modifier = Modifier, +) { + Row( + modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (item in model.reactionCounts) { + val label = + pluralStringResource(R.plurals.reaction_count, item.count, item.count, item.emoji) + Text( + "${item.emoji} ${CapFormat.count(item.count)}", + modifier = + Modifier.clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHighest) + .clickable(role = Role.Button) { item.firstTime?.let { player?.seek(it) } } + .clearAndSetSemantics { + contentDescription = label + role = Role.Button + } + .padding(horizontal = 12.dp, vertical = 6.dp), + style = CapType.subheadline.copy(fontWeight = FontWeight.Medium).monospacedDigit(), + ) + } + } +} + +@Composable +internal fun BurstLayer(model: CapDetailModel, aspect: Float) { + Box( + Modifier.fillMaxSize().clearAndSetSemantics {}, + contentAlignment = Alignment.Center, + ) { + BoxWithConstraints(Modifier.aspectRatio(aspect)) { + for (burst in model.bursts) { + key(burst.id) { + BurstView(burst, maxWidth, maxHeight) { model.finishBurst(burst.id) } + } + } + } + } +} + +@Composable +private fun BurstView( + burst: CapDetailModel.ReactionBurst, + width: Dp, + height: Dp, + onFinish: () -> Unit, +) { + val density = LocalDensity.current + val progress = remember { Animatable(0f) } + LaunchedEffect(burst.id) { + progress.animateTo(1f, tween(BURST_MILLIS, easing = FastOutSlowInEasing)) + delay(BURST_TAIL_MILLIS) + onFinish() + } + val size = min(height * 0.22f, 44.dp) + Text( + burst.emoji, + fontSize = with(density) { size.toSp() }, + modifier = + Modifier.graphicsLayer { + val shown = progress.value + val scale = 0.5f + 0.65f * shown + scaleX = scale + scaleY = scale + alpha = 1f - shown + translationX = (width * burst.lane.toFloat()).toPx() - size.toPx() / 2 + translationY = (height * (0.78f - 0.66f * shown)).toPx() - size.toPx() / 2 + }, + ) +} + +private const val BURST_MILLIS = 1500 +private const val BURST_TAIL_MILLIS = 50L diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/RenameDialog.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/RenameDialog.kt new file mode 100644 index 00000000000..4c13879a822 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/RenameDialog.kt @@ -0,0 +1,46 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import so.cap.mobile.R +import so.cap.mobile.features.home.SheetField +import so.cap.mobile.features.home.rememberSheetFocus + +@Composable +internal fun RenameDialog(title: String, onSave: (String) -> Unit, onDismiss: () -> Unit) { + val state = rememberTextFieldState(title) + val save = { onSave(state.text.toString()) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.cap_rename_title)) }, + text = { + val focus = rememberSheetFocus() + SheetField( + state = state, + label = stringResource(R.string.cap_rename_field), + keyboardOptions = + KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Done, + ), + onSubmit = save, + modifier = Modifier.focusRequester(focus), + ) + }, + confirmButton = { + TextButton(onClick = save) { Text(stringResource(R.string.action_save)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } + }, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/ReportDialog.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/ReportDialog.kt new file mode 100644 index 00000000000..df8c012f4cf --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/ReportDialog.kt @@ -0,0 +1,45 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import so.cap.kit.ContentReportReason +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapType + +@Composable +internal fun ReportDialog(onReport: (ContentReportReason) -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.cap_report_title)) }, + text = { + Column { + ContentReportReason.entries.forEach { reason -> + Box( + modifier = + Modifier.fillMaxWidth() + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = { onReport(reason) }), + contentAlignment = Alignment.CenterStart, + ) { + Text(reason.title, style = CapType.body) + } + } + } + }, + confirmButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } + }, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SaveToDevice.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SaveToDevice.kt new file mode 100644 index 00000000000..1262fc2ca1b --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SaveToDevice.kt @@ -0,0 +1,82 @@ +package so.cap.mobile.features.cap + +import android.content.ContentValues +import android.content.Context +import android.os.Environment +import android.provider.MediaStore +import java.io.File +import java.io.IOException +import java.util.UUID +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runInterruptible +import okhttp3.OkHttpClient +import okhttp3.Request + +class DeviceVideos(private val context: Context) { + val scratch: File + get() = context.cacheDir + + suspend fun add(file: File, displayName: String) = + runInterruptible(Dispatchers.IO) { + val resolver = context.contentResolver + val pending = + ContentValues().apply { + put(MediaStore.Video.Media.DISPLAY_NAME, displayName) + put(MediaStore.Video.Media.MIME_TYPE, videoMimeType(file.name)) + put( + MediaStore.Video.Media.RELATIVE_PATH, + "${Environment.DIRECTORY_MOVIES}/Cap", + ) + put(MediaStore.Video.Media.IS_PENDING, 1) + } + val collection = + MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) + val uri = + resolver.insert(collection, pending) + ?: throw IOException("The video library refused the video") + try { + val output = + resolver.openOutputStream(uri) + ?: throw IOException("The video library gave no place to write") + output.use { file.inputStream().use { input -> input.copyTo(it) } } + val done = ContentValues().apply { put(MediaStore.Video.Media.IS_PENDING, 0) } + resolver.update(uri, done, null, null) + } catch (failure: IOException) { + resolver.delete(uri, null, null) + throw failure + } + } +} + +internal suspend fun OkHttpClient.downloadVideo( + url: String, + fileName: String, + directory: File, +): File { + val file = File(directory, "${UUID.randomUUID()}.${videoExtension(fileName)}") + try { + runInterruptible(Dispatchers.IO) { + newCall(Request.Builder().url(url).build()).execute().use { response -> + if (!response.isSuccessful) throw IOException("HTTP ${response.code}") + file.outputStream().use { response.body.byteStream().copyTo(it) } + } + } + return file + } catch (failure: Throwable) { + file.delete() + throw failure + } +} + +internal fun videoExtension(fileName: String): String = + fileName.substringAfterLast('.', "").lowercase().takeIf { it in VIDEO_EXTENSIONS } ?: "mp4" + +internal fun videoDisplayName(fileName: String): String { + val base = File(fileName).nameWithoutExtension.trim().ifEmpty { "Cap" } + return "$base.${videoExtension(fileName)}" +} + +private fun videoMimeType(fileName: String): String = + if (videoExtension(fileName) == "mov") "video/quicktime" else "video/mp4" + +private val VIDEO_EXTENSIONS = setOf("mp4", "mov", "m4v") diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SummarySection.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SummarySection.kt new file mode 100644 index 00000000000..44dd3364150 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/SummarySection.kt @@ -0,0 +1,208 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.kit.Chapter +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.capCardBackground +import so.cap.mobile.designsystem.monospacedDigit + +internal fun LazyListScope.summarySection(model: CapDetailModel, player: CapPlayer?) { + val detail = model.detail ?: return + val settings = detail.viewer.settings + val summary = detail.summary?.trim()?.takeUnless { settings.disableSummary || it.isEmpty() } + val chapters = if (settings.disableChapters) emptyList() else detail.chapters + if (summary != null) { + item(key = SUMMARY_KEY) { + Column( + Modifier.padding(horizontal = CapTheme.spacing) + .fillMaxWidth() + .capCardBackground() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(stringResource(R.string.summary_title), style = CapType.headline) + SelectionContainer { + Text( + summaryText(summary), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.body, + ) + } + } + } + } + if (chapters.isNotEmpty()) { + item(key = CHAPTERS_KEY) { + Text( + stringResource(R.string.summary_chapters), + modifier = + Modifier.padding(horizontal = CapTheme.spacing) + .padding(top = if (summary != null) 12.dp else 0.dp, bottom = 6.dp), + style = CapType.headline, + ) + } + itemsIndexed(chapters, key = { index, _ -> "chapter-$index" }) { index, chapter -> + ChapterRow( + index, + chapter, + chapters, + player, + Modifier.padding(horizontal = CapTheme.spacing), + ) + } + } + if (summary == null && chapters.isEmpty()) { + item(key = SUMMARY_EMPTY_KEY) { + val generating = model.isGeneratingSummary + EmptyState( + icon = if (generating) R.drawable.ic_hourglass else R.drawable.ic_subject, + title = + stringResource( + if (generating) R.string.summary_generating else R.string.summary_none + ), + description = + stringResource( + if (generating) { + R.string.summary_generating_hint + } else { + R.string.summary_none_hint + } + ), + actions = + if (generating) { + { CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) } + } else { + null + }, + ) + } + } +} + +internal fun activeChapter(chapters: List, time: Double): Int? = + chapters.indexOfLast { time >= it.start && time > 0 }.takeIf { it >= 0 } + +private val emphasis = Regex("""\*\*(.+?)\*\*|\*(.+?)\*""") + +internal fun summaryText(markdown: String): AnnotatedString = buildAnnotatedString { + var at = 0 + for (match in emphasis.findAll(markdown)) { + append(markdown, at, match.range.first) + val (bold, italic) = match.destructured + if (bold.isNotEmpty()) { + withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { append(bold) } + } else { + withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { append(italic) } + } + at = match.range.last + 1 + } + append(markdown, at, markdown.length) +} + +@Composable +private fun ChapterRow( + index: Int, + chapter: Chapter, + chapters: List, + player: CapPlayer?, + modifier: Modifier, +) { + val isActive by + remember(index, chapters, player) { + derivedStateOf { + player != null && activeChapter(chapters, player.currentTime) == index + } + } + val accent = MaterialTheme.colorScheme.primary + val stamp = CapFormat.timestamp(chapter.start) + val label = stringResource(R.string.summary_chapter_label, chapter.title, stamp) + val play = stringResource(R.string.summary_chapter_play) + val seek = { player?.seek(chapter.start) } + Row( + modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(if (isActive) accent.copy(alpha = 0.1f) else Color.Transparent) + .clickable { seek() } + .clearAndSetSemantics { + contentDescription = label + role = Role.Button + selected = isActive + onClick(play) { + seek() + true + } + } + .padding(horizontal = 12.dp, vertical = 10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stamp, + modifier = Modifier.widthIn(min = 52.dp), + color = accent, + style = CapType.subheadline.copy(fontWeight = FontWeight.SemiBold).monospacedDigit(), + ) + Text( + chapter.title, + modifier = Modifier.weight(1f), + color = MaterialTheme.colorScheme.onSurface, + style = CapType.subheadline, + ) + if (isActive) { + Icon( + painterResource(R.drawable.ic_graphic_eq), + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = accent, + ) + } + } +} + +private const val SUMMARY_KEY = "summary" +private const val CHAPTERS_KEY = "chapters" +private const val SUMMARY_EMPTY_KEY = "summary-empty" diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Timeline.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Timeline.kt new file mode 100644 index 00000000000..3629607c44a --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/Timeline.kt @@ -0,0 +1,264 @@ +package so.cap.mobile.features.cap + +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.hideFromAccessibility +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.setProgress +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.kit.Chapter +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.monospacedDigit + +enum class TimelineStyle { + Inline, + Overlay, +} + +internal fun chapterGaps(chapters: List, duration: Double): List = + if (duration <= 0) emptyList() + else chapters.drop(1).filter { it.start > 0 && it.start < duration }.map { it.start / duration } + +internal fun chapterAt(chapters: List, time: Double): String? = + chapters.lastOrNull { it.start <= time }?.title + +@Composable +fun PlayerTimeline( + player: CapPlayer, + chapters: List, + modifier: Modifier = Modifier, + style: TimelineStyle = TimelineStyle.Inline, +) { + val light = style == TimelineStyle.Overlay + val duration = player.duration ?: 0.0 + val time = player.scrubTime ?: player.currentTime + val progress = if (duration > 0) (time / duration).coerceIn(0.0, 1.0).toFloat() else 0f + val dragging = player.isScrubbing + val haptics = LocalHapticFeedback.current + val accent = MaterialTheme.colorScheme.primary + val trackHeight by animateDpAsState(if (dragging) 8.dp else 5.dp, tween(150)) + val thumb by animateDpAsState(if (dragging) 18.dp else 12.dp, tween(150)) + val positionLabel = stringResource(R.string.player_position) + val positionValue = + stringResource( + R.string.player_position_value, + CapFormat.timestamp(time), + CapFormat.timestamp(duration), + ) + Column(modifier, verticalArrangement = Arrangement.spacedBy(2.dp)) { + BoxWithConstraints( + Modifier.fillMaxWidth() + .height(if (light) 28.dp else 36.dp) + .semantics { + contentDescription = positionLabel + stateDescription = positionValue + progressBarRangeInfo = + ProgressBarRangeInfo( + time.toFloat(), + 0f..duration.toFloat().coerceAtLeast(0f), + ) + setProgress { target -> + player.skip(if (target >= time) SKIP_SECONDS else -SKIP_SECONDS) + true + } + } + .pointerInput(player) { + awaitEachGesture { + val down = awaitFirstDown() + val total = player.duration ?: return@awaitEachGesture + if (total <= 0 || size.width <= 0) return@awaitEachGesture + fun fraction(x: Float) = (x / size.width).coerceIn(0f, 1f) * total + if (!player.beginScrub()) return@awaitEachGesture + haptics.performHapticFeedback(HapticFeedbackType.SegmentTick) + player.updateScrub(fraction(down.position.x)) + down.consume() + while (true) { + val change = awaitPointerEvent().changes.first() + if (!change.pressed) break + player.updateScrub(fraction(change.position.x)) + change.consume() + } + player.endScrub() + haptics.performHapticFeedback(HapticFeedbackType.SegmentTick) + } + }, + contentAlignment = Alignment.CenterStart, + ) { + val width = maxWidth + if (light) { + Box( + Modifier.fillMaxWidth() + .height(trackHeight) + .background(Color.White.copy(alpha = 0.3f), CircleShape) + ) + Box( + Modifier.width(maxOf(5.dp, width * progress)) + .height(trackHeight) + .background(accent, CircleShape) + ) + for (position in chapterGaps(chapters, duration)) { + Box( + Modifier.offset(x = width * position.toFloat() - 1.dp) + .width(2.dp) + .height(trackHeight) + .background(Color.Black.copy(alpha = 0.5f)) + ) + } + Box( + Modifier.offset { + val x = + (width * progress - thumb / 2).coerceIn( + 0.dp, + (width - thumb).coerceAtLeast(0.dp), + ) + IntOffset(x.roundToPx(), 0) + } + .size(thumb) + .shadow(3.dp, CircleShape) + .background(Color.White, CircleShape) + .border(2.dp, accent, CircleShape) + ) + } else { + val inactive = CapTheme.colors.dialKnurl + val active = MaterialTheme.colorScheme.onSurface + val chapterGap = MaterialTheme.colorScheme.background + Canvas( + Modifier.fillMaxWidth().height(36.dp).semantics { hideFromAccessibility() } + ) { + val spacing = 7.dp.toPx() + val tickWidth = 1.dp.toPx() + val tickHeight = 12.dp.toPx() + val baseline = size.height + val progressX = size.width * progress + var x = 0f + while (x <= size.width) { + drawLine( + color = if (x <= progressX) active else inactive, + start = Offset(x, baseline - tickHeight), + end = Offset(x, baseline), + strokeWidth = tickWidth, + ) + x += spacing + } + for (position in chapterGaps(chapters, duration)) { + val gapX = size.width * position.toFloat() + drawRect( + color = chapterGap, + topLeft = Offset(gapX - 1.dp.toPx(), baseline - tickHeight), + size = Size(2.dp.toPx(), tickHeight), + ) + } + val indexWidth = 2.dp.toPx() + val centre = progressX.coerceIn(indexWidth / 2, size.width - indexWidth / 2) + drawRoundRect( + color = active, + topLeft = Offset(centre - indexWidth / 2, baseline - 22.dp.toPx()), + size = Size(indexWidth, 22.dp.toPx()), + cornerRadius = CornerRadius(indexWidth / 2), + ) + } + } + val scrub = player.scrubTime + if (dragging && scrub != null) { + Column( + Modifier.offset( + x = + (width * progress - 45.dp).coerceIn( + 0.dp, + (width - 110.dp).coerceAtLeast(0.dp), + ), + y = (-34).dp, + ) + .widthIn(max = 180.dp) + .background( + MaterialTheme.colorScheme.surfaceContainerHigh, + RoundedCornerShape(50), + ) + .padding(horizontal = 10.dp, vertical = 5.dp) + .semantics { hideFromAccessibility() }, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + CapFormat.timestamp(scrub), + style = + CapType.subheadline + .copy(fontWeight = FontWeight.SemiBold) + .monospacedDigit(), + ) + chapterAt(chapters, scrub)?.let { + Text( + it, + style = CapType.caption2, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + if (light) { + Row(Modifier.fillMaxWidth().semantics { hideFromAccessibility() }) { + val color = Color.White.copy(alpha = 0.85f) + val labelStyle = + CapType.caption2.copy(fontWeight = FontWeight.Medium).monospacedDigit() + Text(CapFormat.timestamp(time), color = color, style = labelStyle) + Spacer(Modifier.weight(1f)) + player.duration?.let { + Text( + "-" + CapFormat.timestamp((it - time).coerceAtLeast(0.0)), + color = color, + style = labelStyle, + ) + } + } + } + } +} + +private const val SKIP_SECONDS = 10.0 diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TimelineMarkers.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TimelineMarkers.kt new file mode 100644 index 00000000000..f114570e91f --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TimelineMarkers.kt @@ -0,0 +1,143 @@ +package so.cap.mobile.features.cap + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.role +import androidx.compose.ui.unit.dp +import kotlin.math.abs +import kotlin.math.max +import so.cap.kit.CapComment +import so.cap.kit.CapFormat +import so.cap.kit.TimelineMarker +import so.cap.kit.TimelineMarkers +import so.cap.mobile.R + +@Composable +internal fun MarkerLayer( + comments: List, + duration: Double, + onSelect: (TimelineMarker) -> Unit, + modifier: Modifier = Modifier, +) { + BoxWithConstraints(modifier.fillMaxWidth().height(LAYER_HEIGHT.dp)) { + val width = maxWidth.value + val coarse = + remember(comments, duration, width) { + TimelineMarkers.build(comments, duration, max(6, (width / 30).toInt())) + } + val sparse = coarse.sumOf { it.count } <= max(6, (width / 34).toInt()) + val badges = if (sparse) coarse else markerPeaks(coarse, width, PEAK_BADGES) + for (marker in badges) { + val x = + (width * marker.position.toFloat() - BADGE_SIZE / 2).coerceIn( + 0f, + max(width - BADGE_SIZE, 0f), + ) + MarkerBadge( + marker, + showsCount = sparse, + modifier = Modifier.align(Alignment.CenterStart).offset(x = x.dp), + onClick = { onSelect(marker) }, + ) + } + } +} + +internal fun markerPeaks( + markers: List, + width: Float, + limit: Int, +): List { + val chosen = mutableListOf() + val byWeight = + markers.sortedWith(compareByDescending { it.count }.thenBy { it.time }) + for (marker in byWeight) { + if (chosen.size >= limit) break + val x = width * marker.position + if (chosen.all { abs(width * it.position - x) > BADGE_SIZE + PEAK_GAP }) chosen += marker + } + return chosen.sortedBy { it.time } +} + +@Composable +private fun MarkerBadge( + marker: TimelineMarker, + showsCount: Boolean, + modifier: Modifier, + onClick: () -> Unit, +) { + val label = markerLabel(marker) + val accent = MaterialTheme.colorScheme.primary + Box( + modifier + .size(BADGE_SIZE.dp) + .clip(CircleShape) + .clickable(role = Role.Button, onClick = onClick) + .clearAndSetSemantics { + contentDescription = label + role = Role.Button + }, + contentAlignment = Alignment.Center, + ) { + Box( + Modifier.size(8.dp) + .clip(CircleShape) + .then( + if (marker.textCount > 0) { + Modifier.background(accent, CircleShape) + } else { + Modifier.border(1.5.dp, accent, CircleShape) + } + ) + ) + } +} + +@Composable +private fun markerLabel(marker: TimelineMarker): String { + val comments = + marker.textCount + .takeIf { it > 0 } + ?.let { + pluralStringResource(R.plurals.marker_comments, it, it) + } + val reactions = + marker.reactionCount + .takeIf { it > 0 } + ?.let { + pluralStringResource(R.plurals.marker_reactions, it, it) + } + val parts = + if (comments != null && reactions != null) { + stringResource(R.string.marker_and, comments, reactions) + } else { + comments ?: reactions.orEmpty() + } + return stringResource(R.string.marker_label, parts, CapFormat.timestamp(marker.time)) +} + +private const val LAYER_HEIGHT = 30 +private const val BADGE_SIZE = 34f +private const val PEAK_GAP = 6f +private const val PEAK_BADGES = 3 +private val REACTION_ORANGE = Color(0xFFFF9500) diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TranscriptSection.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TranscriptSection.kt new file mode 100644 index 00000000000..c024089d0ae --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/TranscriptSection.kt @@ -0,0 +1,305 @@ +package so.cap.mobile.features.cap + +import android.content.Context +import android.content.Intent +import android.os.Build +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import java.text.Normalizer +import java.util.Locale +import so.cap.kit.CapFormat +import so.cap.kit.TranscriptCue +import so.cap.kit.TranscriptExport +import so.cap.mobile.R +import so.cap.mobile.app.ToastCenter +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.monospacedDigit +import so.cap.mobile.features.cap.CapDetailModel.Transcript + +internal fun LazyListScope.transcriptSection( + model: CapDetailModel, + player: CapPlayer?, + toasts: ToastCenter, + query: String, + onQuery: (String) -> Unit, +) { + when (val transcript = model.transcript) { + Transcript.Idle, + Transcript.Loading -> + item(key = TRANSCRIPT_LOADING_KEY) { + Column( + Modifier.fillMaxWidth().heightIn(min = 160.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), + ) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) + Text( + stringResource(R.string.transcript_loading), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.footnote, + ) + } + } + is Transcript.Unavailable -> + item(key = TRANSCRIPT_NONE_KEY) { + EmptyState( + icon = R.drawable.ic_closed_caption, + title = stringResource(R.string.transcript_none), + description = stringResource(transcript.message), + ) + } + is Transcript.Loaded -> { + val cues = transcript.cues + item(key = TRANSCRIPT_SEARCH_KEY) { + TranscriptSearch( + model, + cues, + toasts, + query, + onQuery, + Modifier.padding(horizontal = CapTheme.spacing), + ) + } + val trimmed = query.trim() + val visible = filterCues(cues, trimmed) + if (visible.isEmpty()) { + item(key = TRANSCRIPT_NO_RESULTS_KEY) { + EmptyState( + icon = R.drawable.ic_search, + title = stringResource(R.string.transcript_no_results, trimmed), + description = stringResource(R.string.transcript_no_results_hint), + ) + } + } else { + items(visible, key = { "cue-${it.id}" }) { cue -> + TranscriptRow( + cue, + cues, + player, + Modifier.padding(horizontal = CapTheme.spacing), + ) + } + } + } + } +} + +internal fun filterCues(cues: List, query: String): List { + if (query.isEmpty()) return cues + val folded = query.folded() + return cues.filter { folded in it.text.folded() } +} + +private val marks = Regex("\\p{Mn}+") + +private fun String.folded(): String = + Normalizer.normalize(this, Normalizer.Form.NFD).replace(marks, "").lowercase(Locale.ROOT) + +@Composable +private fun TranscriptSearch( + model: CapDetailModel, + cues: List, + toasts: ToastCenter, + query: String, + onQuery: (String) -> Unit, + modifier: Modifier, +) { + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + val label = stringResource(R.string.transcript_search) + Row( + modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + TextField( + value = query, + onValueChange = onQuery, + modifier = + Modifier.weight(1f) + .semantics { contentDescription = label } + .onFocusChanged { if (it.isFocused) model.requestSectionReveal() }, + placeholder = { Text(label) }, + leadingIcon = { + Icon( + painterResource(R.drawable.ic_cap_search), + contentDescription = null, + tint = secondary, + ) + }, + trailingIcon = + if (query.isNotEmpty()) { + { + IconButton(onClick = { onQuery("") }) { + Icon( + painterResource(R.drawable.ic_cancel), + contentDescription = stringResource(R.string.transcript_clear), + tint = secondary, + ) + } + } + } else { + null + }, + singleLine = true, + textStyle = CapType.bodyStrong, + shape = RoundedCornerShape(0.dp), + colors = + TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = MaterialTheme.colorScheme.onSurface, + unfocusedIndicatorColor = CapTheme.colors.hairline, + disabledIndicatorColor = Color.Transparent, + ), + ) + val matches = filterCues(cues, query.trim()).size + if (query.isNotBlank()) { + Text( + "$matches/${cues.size}", + color = secondary, + style = CapType.metadata.monospacedDigit(), + ) + } + TranscriptOptions(model.detail?.cap?.title, cues, toasts) + } +} + +@Composable +private fun TranscriptOptions(title: String?, cues: List, toasts: ToastCenter) { + val context = LocalContext.current + var isOpen by remember { mutableStateOf(false) } + val subject = title ?: stringResource(R.string.cap_section_transcript) + Box { + IconButton(onClick = { isOpen = true }) { + Icon( + painterResource(R.drawable.ic_more_horiz), + contentDescription = stringResource(R.string.transcript_options), + tint = MaterialTheme.colorScheme.onSurface, + ) + } + DropdownMenu(expanded = isOpen, onDismissRequest = { isOpen = false }) { + @Composable + fun option(label: Int, @DrawableRes icon: Int, action: () -> Unit) = + DropdownMenuItem( + text = { Text(stringResource(label)) }, + onClick = { + isOpen = false + action() + }, + leadingIcon = { Icon(painterResource(icon), contentDescription = null) }, + ) + option(R.string.transcript_copy, R.drawable.ic_content_copy) { + copyTranscript(context, TranscriptExport.plainText(cues), toasts) + } + option(R.string.transcript_copy_timestamps, R.drawable.ic_schedule) { + copyTranscript(context, TranscriptExport.timestamped(cues), toasts) + } + option(R.string.transcript_share, R.drawable.ic_share) { + val send = + Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, TranscriptExport.plainText(cues)) + .putExtra(Intent.EXTRA_SUBJECT, subject) + .putExtra(Intent.EXTRA_TITLE, subject) + context.startActivity(Intent.createChooser(send, null)) + } + } + } +} + +private fun copyTranscript(context: Context, text: String, toasts: ToastCenter) { + copyPlainText(context, R.string.cap_section_transcript, text) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + toasts.show(context.getString(R.string.transcript_copied), R.drawable.ic_content_copy) + } +} + +@Composable +private fun TranscriptRow( + cue: TranscriptCue, + cues: List, + player: CapPlayer?, + modifier: Modifier, +) { + val isActive by + remember(cue, cues, player) { + derivedStateOf { + player != null && TranscriptCue.active(cues, player.currentTime)?.id == cue.id + } + } + val accent = MaterialTheme.colorScheme.primary + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + val stamp = CapFormat.timestamp(cue.start) + Box(modifier) { + Row( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(if (isActive) accent.copy(alpha = 0.1f) else Color.Transparent) + .clickable(onClickLabel = stringResource(R.string.transcript_play_from, stamp)) { + player?.seek(cue.start) + } + .padding(horizontal = 10.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + stamp, + modifier = Modifier.width(40.dp).alignByBaseline(), + color = if (isActive) accent else secondary, + style = CapType.caption.copy(fontWeight = FontWeight.SemiBold).monospacedDigit(), + ) + Text( + cue.text, + modifier = Modifier.weight(1f).alignByBaseline(), + color = if (isActive) MaterialTheme.colorScheme.onSurface else secondary, + style = CapType.body, + ) + } + } +} + +private const val TRANSCRIPT_LOADING_KEY = "transcript-loading" +private const val TRANSCRIPT_NONE_KEY = "transcript-none" +private const val TRANSCRIPT_SEARCH_KEY = "transcript-search" +private const val TRANSCRIPT_NO_RESULTS_KEY = "transcript-no-results" diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/AddMenu.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/AddMenu.kt new file mode 100644 index 00000000000..5714ed81857 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/AddMenu.kt @@ -0,0 +1,85 @@ +package so.cap.mobile.features.home + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.designsystem.InkButton + +enum class AddAction(@StringRes val label: Int, @DrawableRes val icon: Int) { + Record(R.string.add_record, R.drawable.ic_radio_button_checked), + UploadPhotos(R.string.add_upload_photos, R.drawable.ic_photo_library), + UploadFiles(R.string.add_upload_files, R.drawable.ic_upload_file), + ImportLoom(R.string.add_import_loom, R.drawable.ic_download), + NewFolder(R.string.add_new_folder, R.drawable.ic_create_new_folder), + OpenLink(R.string.add_open_link, R.drawable.ic_link), +} + +@Composable +fun AddMenu( + showsNewFolder: Boolean, + onAction: (AddAction) -> Unit, + modifier: Modifier = Modifier, + prominent: Boolean = false, +) { + var expanded by remember { mutableStateOf(false) } + val label = stringResource(R.string.add_label) + Box(modifier) { + if (prominent) { + InkButton( + onClick = { expanded = true }, + modifier = Modifier.semantics { contentDescription = label }, + ) { + Icon(painterResource(R.drawable.ic_add), contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.add_prominent)) + } + } else { + IconButton(onClick = { expanded = true }) { + Icon(painterResource(R.drawable.ic_add), contentDescription = label) + } + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + AddAction.entries + .filter { showsNewFolder || it != AddAction.NewFolder } + .forEach { action -> + if ( + action == AddAction.UploadPhotos || + action == AddAction.NewFolder || + action == AddAction.OpenLink + ) { + HorizontalDivider() + } + DropdownMenuItem( + text = { Text(stringResource(action.label)) }, + onClick = { + expanded = false + onAction(action) + }, + leadingIcon = { + Icon(painterResource(action.icon), contentDescription = null) + }, + ) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapActions.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapActions.kt new file mode 100644 index 00000000000..7cae0ef4dcf --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapActions.kt @@ -0,0 +1,203 @@ +package so.cap.mobile.features.home + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.os.Build +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Box +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.MenuDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.unit.DpOffset +import so.cap.kit.CapSummary +import so.cap.kit.SafeUrl +import so.cap.mobile.R +import so.cap.mobile.app.ToastCenter + +enum class CapAction(@StringRes val label: Int, @DrawableRes val icon: Int) { + CopyLink(R.string.cap_action_copy_link, R.drawable.ic_link), + Share(R.string.cap_action_share, R.drawable.ic_share), + MakePrivate(R.string.cap_action_make_private, R.drawable.ic_lock), + MakePublic(R.string.cap_action_make_public, R.drawable.ic_public), + Delete(R.string.cap_action_delete, R.drawable.ic_delete); + + companion object { + fun available(cap: CapSummary, owned: Boolean): List = buildList { + add(CopyLink) + if (SafeUrl.web(cap.shareUrl) != null) add(Share) + if (owned) { + add(if (cap.isPublic) MakePrivate else MakePublic) + add(Delete) + } + } + } +} + +@Composable +fun CapMenu( + actions: List, + expanded: Boolean, + offset: DpOffset, + onDismiss: () -> Unit, + onAction: (CapAction) -> Unit, +) { + DropdownMenu(expanded = expanded, onDismissRequest = onDismiss, offset = offset) { + actions.forEach { action -> + if (action != CapAction.CopyLink && action != CapAction.Share) HorizontalDivider() + val color = + if (action == CapAction.Delete) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurface + } + DropdownMenuItem( + text = { Text(stringResource(action.label)) }, + onClick = { + onDismiss() + onAction(action) + }, + leadingIcon = { Icon(painterResource(action.icon), contentDescription = null) }, + colors = MenuDefaults.itemColors(textColor = color, leadingIconColor = color), + ) + } + } +} + +@Composable +fun CapPressable( + cap: CapSummary, + owned: Boolean, + onClick: () -> Unit, + onAction: (CapAction) -> Unit, + modifier: Modifier = Modifier, + content: @Composable () -> Unit, +) { + val actions = CapAction.available(cap, owned) + val actionLabels = actions.map { stringResource(it.label) } + val visibility = stringResource(if (cap.isPublic) R.string.cap_public else R.string.cap_private) + val haptics = LocalHapticFeedback.current + val density = LocalDensity.current + var pressedAt by remember { mutableStateOf(Offset.Zero) } + var height by remember { mutableIntStateOf(0) } + var menuOffset by remember { mutableStateOf(null) } + CapMenu( + actions = actions, + expanded = menuOffset != null, + offset = menuOffset ?: DpOffset.Zero, + onDismiss = { menuOffset = null }, + onAction = onAction, + ) + Box( + modifier = + modifier + .onSizeChanged { height = it.height } + .pointerInput(Unit) { + awaitEachGesture { + pressedAt = awaitFirstDown(requireUnconsumed = false).position + } + } + .combinedClickable( + onClickLabel = stringResource(R.string.cap_open_action), + onLongClickLabel = stringResource(R.string.cap_actions_action), + role = Role.Button, + onLongClick = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + menuOffset = + with(density) { + DpOffset(pressedAt.x.toDp(), (pressedAt.y - height).toDp()) + } + }, + onClick = onClick, + ) + .semantics { + stateDescription = visibility + customActions = + actions.zip(actionLabels) { action, label -> + CustomAccessibilityAction(label) { + onAction(action) + true + } + } + } + ) { + content() + } +} + +@Composable +fun DeleteCapDialog(cap: CapSummary, onConfirm: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.cap_delete_title)) }, + text = { Text(stringResource(R.string.cap_delete_message, cap.title)) }, + confirmButton = { + TextButton( + onClick = onConfirm, + colors = + ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), + ) { + Text(stringResource(R.string.cap_delete_confirm)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } + }, + ) +} + +// Android 13 and later show their own confirmation when an app copies, so the toast is for the +// versions that show nothing. +fun copyCapLink(context: Context, cap: CapSummary, toasts: ToastCenter) { + val url = SafeUrl.web(cap.shareUrl) ?: return + val label = context.getString(R.string.cap_link_clip_label) + context + .getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText(label, url)) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + toasts.show(context.getString(R.string.cap_link_copied), R.drawable.ic_link) + } +} + +fun shareCap(context: Context, cap: CapSummary) { + val url = SafeUrl.web(cap.shareUrl) ?: return + val send = + Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, url) + .putExtra(Intent.EXTRA_SUBJECT, cap.title) + .putExtra(Intent.EXTRA_TITLE, cap.title) + context.startActivity(Intent.createChooser(send, null)) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapCard.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapCard.kt new file mode 100644 index 00000000000..332d2555740 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapCard.kt @@ -0,0 +1,213 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.LocalTextStyle +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.kit.CapSummary +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapThumbnail +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.StatLabel + +private const val THUMBNAIL_SHADOW_ALPHA = 0.3f + +@Composable +fun CapCard( + cap: CapSummary, + userId: String, + onClick: () -> Unit, + onAction: (CapAction) -> Unit, + modifier: Modifier = Modifier, +) { + val owned = cap.isOwned(userId) + val secondary = MaterialTheme.colorScheme.onSurfaceVariant + val actions = CapAction.available(cap, owned) + val actionLabels = actions.map { stringResource(it.label) } + val haptics = LocalHapticFeedback.current + val density = LocalDensity.current + var pressedAt by remember { mutableStateOf(Offset.Zero) } + var height by remember { mutableIntStateOf(0) } + var menuOffset by remember { mutableStateOf(null) } + CapMenu( + actions = actions, + expanded = menuOffset != null, + offset = menuOffset ?: DpOffset.Zero, + onDismiss = { menuOffset = null }, + onAction = onAction, + ) + Column( + modifier = + modifier + .fillMaxWidth() + .onSizeChanged { height = it.height } + .pointerInput(Unit) { + awaitEachGesture { + pressedAt = awaitFirstDown(requireUnconsumed = false).position + } + } + .combinedClickable( + onClickLabel = stringResource(R.string.cap_open_action), + onLongClickLabel = stringResource(R.string.cap_actions_action), + role = Role.Button, + onLongClick = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + menuOffset = + with(density) { + DpOffset(pressedAt.x.toDp(), (pressedAt.y - height).toDp()) + } + }, + onClick = onClick, + ) + .semantics { + customActions = + actions.zip(actionLabels) { action, label -> + CustomAccessibilityAction(label) { + onAction(action) + true + } + } + }, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + CapThumbnail( + cap = cap, + modifier = + Modifier.shadow( + elevation = 6.dp, + shape = RoundedCornerShape(CapTheme.thumbnailRadius), + ambientColor = Color.Black.copy(alpha = THUMBNAIL_SHADOW_ALPHA), + spotColor = Color.Black.copy(alpha = THUMBNAIL_SHADOW_ALPHA), + ), + ) + Row( + modifier = Modifier.padding(horizontal = 2.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + text = cap.title.ifEmpty { stringResource(R.string.cap_untitled) }, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + style = CapType.headline, + ) + CompositionLocalProvider( + LocalContentColor provides secondary, + LocalTextStyle provides CapType.subheadline, + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (!owned && cap.ownerName.isNotEmpty()) { + Text( + text = cap.ownerName, + modifier = Modifier.weight(1f, fill = false), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text("·") + } + Text( + text = CapFormat.relative(cap.createdAt), + modifier = if (owned) Modifier.weight(1f, fill = false) else Modifier, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (owned) { + val size = + with(LocalDensity.current) { CapType.subheadline.fontSize.toDp() } + Icon( + painter = + painterResource( + if (cap.isPublic) R.drawable.ic_public + else R.drawable.ic_lock + ), + contentDescription = + stringResource( + if (cap.isPublic) R.string.cap_public + else R.string.cap_private + ), + modifier = Modifier.size(size), + ) + } + } + } + } + CompositionLocalProvider( + LocalContentColor provides secondary, + LocalTextStyle provides CapType.footnote.copy(fontWeight = FontWeight.Medium), + ) { + Row( + modifier = Modifier.padding(top = 2.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (owned) { + StatLabel( + cap.viewCount, + R.drawable.ic_visibility, + stringResource(R.string.stat_views), + ) + } + if (cap.commentCount > 0) { + StatLabel( + cap.commentCount, + R.drawable.ic_chat_bubble, + stringResource(R.string.stat_comments), + ) + } + if (cap.reactionCount > 0) { + StatLabel( + cap.reactionCount, + R.drawable.ic_mood, + stringResource(R.string.stat_reactions), + ) + } + } + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapRow.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapRow.kt new file mode 100644 index 00000000000..8336b2da167 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/CapRow.kt @@ -0,0 +1,181 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.kit.CapSummary +import so.cap.kit.SafeUrl +import so.cap.kit.UploadPhase +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.LocalCapEnvironment +import so.cap.mobile.designsystem.RemoteImage +import so.cap.mobile.designsystem.RemoteImageRequest +import so.cap.mobile.designsystem.ThumbnailPlaceholder +import so.cap.mobile.designsystem.monospacedDigit +import so.cap.mobile.designsystem.thumbnailBucket + +@Composable +fun CapRow( + cap: CapSummary, + userId: String, + onClick: () -> Unit, + onAction: (CapAction) -> Unit, + modifier: Modifier = Modifier, + isSelected: Boolean = false, + bottomHairline: Boolean = true, +) { + val owned = cap.isOwned(userId) + val highlight = + if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.10f) else Color.Transparent + CapPressable( + cap = cap, + owned = owned, + onClick = onClick, + onAction = onAction, + modifier = + modifier.fillMaxWidth().background(highlight).semantics { selected = isSelected }, + ) { + Box(Modifier.fillMaxWidth().defaultMinSize(minHeight = 80.dp)) { + Row( + modifier = + Modifier.fillMaxWidth() + .align(Alignment.Center) + .padding(horizontal = CapTheme.pageMargin, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + LibraryRowThumbnail(cap) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(3.dp), + ) { + Text( + text = cap.title.ifEmpty { stringResource(R.string.cap_untitled) }, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.rowTitle, + ) + Text( + text = metadata(cap, owned), + color = + if (cap.isProcessing) CapTheme.colors.blue + else CapTheme.colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.metadata, + ) + } + trailing(cap)?.let { label -> + Text( + text = label, + color = + if (cap.isProcessing) CapTheme.colors.blue + else MaterialTheme.colorScheme.onSurface, + maxLines = 1, + style = CapType.detailTitle.monospacedDigit(), + ) + } + } + val upload = cap.upload + if (upload != null && cap.isProcessing) { + Box( + Modifier.align(Alignment.BottomStart) + .fillMaxWidth(upload.fractionCompleted.toFloat().coerceIn(0f, 1f)) + .height(2.dp) + .background(CapTheme.colors.blue) + ) + } + if (bottomHairline) { + Box(Modifier.align(Alignment.BottomCenter)) { + CapHairline(Modifier.padding(start = CapTheme.pageMargin + 64.dp)) + } + } + } + } +} + +@Composable +private fun LibraryRowThumbnail(cap: CapSummary) { + Box(Modifier.size(48.dp).clip(RoundedCornerShape(CapTheme.thumbnailRadius))) { + val environment = LocalCapEnvironment.current + val density = LocalDensity.current + val request = + SafeUrl.media(cap.thumbnailUrl, environment)?.let { url -> + RemoteImageRequest( + url = url, + cacheKey = + cap.thumbnailCacheKey + ?: "cap-thumbnail:${cap.id}:${cap.updatedAt.toEpochMilli()}", + maxPixelSize = thumbnailBucket(with(density) { 48.dp.toPx() }), + ) + } + RemoteImage(request = request, modifier = Modifier.fillMaxSize()) { + ThumbnailPlaceholder(isProcessing = cap.isProcessing) + } + if (cap.isProtected) { + Icon( + painter = painterResource(R.drawable.ic_lock), + contentDescription = stringResource(R.string.thumbnail_protected), + modifier = + Modifier.align(Alignment.BottomEnd) + .padding(4.dp) + .size(12.dp) + .background(Color.Black.copy(alpha = 0.45f), RoundedCornerShape(6.dp)) + .padding(2.dp), + tint = Color.White, + ) + } + } +} + +private fun metadata(cap: CapSummary, owned: Boolean): String { + val upload = cap.upload + if (upload != null && upload.phase == UploadPhase.ERROR) { + return upload.processingError ?: upload.statusText + } + if (cap.isProcessing && upload != null) return upload.statusText.lowercase() + return buildList { + if (!owned && cap.ownerName.isNotEmpty()) add(cap.ownerName) + add(CapFormat.relative(cap.createdAt)) + if (owned) add("${CapFormat.count(cap.viewCount)} views") + } + .joinToString(", ") +} + +private fun trailing(cap: CapSummary): String? { + val upload = cap.upload + if (upload != null && cap.isProcessing) { + return CapFormat.percentage(upload.fractionCompleted) + } + return CapFormat.duration(cap.durationSeconds) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderScreen.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderScreen.kt new file mode 100644 index 00000000000..3e516ba49b3 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderScreen.kt @@ -0,0 +1,74 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import so.cap.kit.CapId +import so.cap.mobile.R +import so.cap.mobile.app.LibraryKey +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.SessionModel + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FolderScreen( + session: SessionModel, + folderId: String, + name: String, + scope: LibraryScope, + onBack: () -> Unit, + onOpenCap: (CapId) -> Unit, + onAdd: (AddAction) -> Unit, +) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column { + TopAppBar( + title = { + Text( + text = name, + modifier = Modifier.semantics { heading() }, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + painterResource(R.drawable.ic_arrow_back), + contentDescription = stringResource(R.string.navigate_back), + ) + } + }, + actions = { + if (scope == LibraryScope.Personal) { + AddMenu(showsNewFolder = false, onAction = onAdd) + } + }, + ) + val organizationId = session.organizationId + if (organizationId != null) { + LibraryContent( + session = session, + library = session.library(LibraryKey(organizationId, scope, folderId)), + onOpenFolder = {}, + onOpenCap = onOpenCap, + onAdd = onAdd, + showsLibraryChrome = false, + ) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderStrip.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderStrip.kt new file mode 100644 index 00000000000..3da69cbc1a9 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/FolderStrip.kt @@ -0,0 +1,153 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import so.cap.kit.CapFormat +import so.cap.kit.Folder +import so.cap.kit.FolderColor +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType + +@Composable +fun FolderColor.tint(): Color = + when (this) { + FolderColor.NORMAL -> MaterialTheme.colorScheme.primary + FolderColor.BLUE -> CapTheme.colors.blue + FolderColor.RED -> MaterialTheme.colorScheme.error + FolderColor.YELLOW -> CapTheme.colors.caution + } + +@Composable +fun FolderStrip( + folders: List, + onOpen: (Folder) -> Unit, + modifier: Modifier = Modifier, +) { + LazyRow( + modifier = modifier, + contentPadding = PaddingValues(horizontal = CapTheme.spacing, vertical = 2.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + items(folders, key = { it.id }) { folder -> + val count = + pluralStringResource( + R.plurals.folder_cap_count, + folder.videoCount, + folder.videoCount, + ) + val label = stringResource(R.string.folder_label, folder.name, count) + val shape = RoundedCornerShape(FOLDER_RADIUS) + Row( + modifier = + Modifier.clip(shape) + .background(MaterialTheme.colorScheme.surfaceContainer, shape) + .clickable(role = Role.Button, onClick = { onOpen(folder) }) + .widthIn(min = 132.dp, max = 240.dp) + .padding(horizontal = 14.dp, vertical = 10.dp) + .clearAndSetSemantics { contentDescription = label }, + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + painter = painterResource(R.drawable.ic_folder), + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = folder.color.tint(), + ) + Column(verticalArrangement = Arrangement.spacedBy(1.dp)) { + Text( + text = folder.name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.subheadline.copy(fontWeight = FontWeight.SemiBold), + ) + Text( + text = count, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + style = CapType.caption, + ) + } + } + } + } +} + +@Composable +fun LibraryFolderRow( + folder: Folder, + onOpen: (Folder) -> Unit, + modifier: Modifier = Modifier, + bottomHairline: Boolean = true, +) { + val count = + pluralStringResource(R.plurals.folder_cap_count, folder.videoCount, folder.videoCount) + val label = stringResource(R.string.folder_label, folder.name, count) + Column(modifier.fillMaxWidth()) { + Row( + modifier = + Modifier.fillMaxWidth() + .height(52.dp) + .clickable(role = Role.Button, onClick = { onOpen(folder) }) + .padding(horizontal = CapTheme.pageMargin) + .clearAndSetSemantics { contentDescription = label }, + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + painter = painterResource(R.drawable.ic_cap_folder), + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onSurface, + ) + Text( + text = folder.name, + modifier = Modifier.weight(1f), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.rowTitle.copy(fontWeight = FontWeight.Medium), + ) + Text( + text = CapFormat.count(folder.videoCount), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + style = CapType.detailTitle, + ) + } + if (bottomHairline) CapHairline(Modifier.padding(start = CapTheme.pageMargin + 36.dp)) + } +} + +private val FOLDER_RADIUS = 16.dp diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/HomeScreen.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/HomeScreen.kt new file mode 100644 index 00000000000..821db0696bc --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/HomeScreen.kt @@ -0,0 +1,72 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.key +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import so.cap.kit.CapId +import so.cap.kit.Folder +import so.cap.mobile.R +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.InkButton + +@Composable +fun HomeScreen( + session: SessionModel, + onOpenFolder: (Folder, LibraryScope) -> Unit, + onOpenCap: (CapId) -> Unit, + onAdd: (AddAction) -> Unit, +) { + val add: (AddAction) -> Unit = { action -> + if (action == AddAction.NewFolder) session.beginFolder() else onAdd(action) + } + session.folderDraft?.let { draft -> + NewFolderSheet( + draft = draft, + onSave = { session.saveFolder() }, + onCancel = session::cancelFolder, + ) + } + Surface( + modifier = Modifier.fillMaxSize().statusBarsPadding(), + color = MaterialTheme.colorScheme.background, + ) { + val libraryKey = session.currentLibraryKey + val error = session.bootstrapError + if (libraryKey != null) { + key(libraryKey) { + LibraryContent( + session = session, + library = session.library(libraryKey), + onOpenFolder = { onOpenFolder(it, libraryKey.scope) }, + onOpenCap = onOpenCap, + onAdd = add, + ) + } + } else if (error != null) { + Box(Modifier.fillMaxSize(), Alignment.Center) { + EmptyState( + icon = R.drawable.ic_wifi_off, + title = stringResource(R.string.home_bootstrap_failed), + description = error.description, + actions = { + InkButton(onClick = { session.refreshBootstrap() }) { + Text(stringResource(R.string.home_try_again)) + } + }, + ) + } + } else { + LibrarySkeleton() + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryContent.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryContent.kt new file mode 100644 index 00000000000..7e7c9971412 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryContent.kt @@ -0,0 +1,417 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleStartEffect +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch +import so.cap.kit.CapFormat +import so.cap.kit.CapId +import so.cap.kit.Folder +import so.cap.mobile.R +import so.cap.mobile.app.LibraryModel +import so.cap.mobile.app.LibrarySort +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapRadioRow +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.EmptyState +import so.cap.mobile.designsystem.InkButton +import so.cap.mobile.designsystem.SkeletonBlock +import so.cap.mobile.designsystem.SkeletonText +import so.cap.mobile.designsystem.shimmering + +@Composable +fun LibraryContent( + session: SessionModel, + library: LibraryModel, + onOpenFolder: (Folder) -> Unit, + onOpenCap: (CapId) -> Unit, + onAdd: (AddAction) -> Unit, + modifier: Modifier = Modifier, + showsLibraryChrome: Boolean = true, +) { + LifecycleStartEffect(library) { + library.loadIfNeeded() + onStopOrDispose { library.pausePolling() } + } + val caps = library.caps + val rows = remember(caps) { caps.mapNotNull { cap -> CapId.parse(cap.id)?.let { it to cap } } } + val status = library.status + val scope = rememberCoroutineScope() + val context = LocalContext.current + var isRefreshing by remember { mutableStateOf(false) } + var pendingDeleteId by rememberSaveable { mutableStateOf(null) } + val listState = rememberLazyListState() + val folderInsertionStamp = library.folderInsertionStamp + LaunchedEffect(folderInsertionStamp) { + if (folderInsertionStamp > 0) listState.scrollToItem(0) + } + val folders = library.folders + val showsFolders = library.key.folderId == null && folders.isNotEmpty() + val loadedEmpty = + status == LibraryModel.Status.Loaded && library.isEmpty && library.loadMoreError == null + val showsDesignedEmpty = loadedEmpty && showsLibraryChrome && library.key.folderId == null + caps + .firstOrNull { it.id == pendingDeleteId } + ?.let { cap -> + DeleteCapDialog( + cap = cap, + onConfirm = { + pendingDeleteId = null + session.delete(cap) + }, + onDismiss = { pendingDeleteId = null }, + ) + } + Column(modifier.fillMaxSize()) { + if (showsLibraryChrome) { + LibraryHeader(session, library, onAdd, showsDetails = !showsDesignedEmpty) + } + PullToRefreshBox( + isRefreshing = isRefreshing, + onRefresh = { + scope.launch { + isRefreshing = true + try { + joinAll(library.refresh(), session.refreshBootstrap()) + } finally { + isRefreshing = false + } + } + }, + modifier = Modifier.weight(1f).fillMaxWidth(), + ) { + when { + showsDesignedEmpty -> { + LibraryEmptyState(Modifier.fillMaxSize()) + } + loadedEmpty -> { + Box(Modifier.fillMaxSize(), Alignment.Center) { + EmptyState( + icon = R.drawable.ic_video_library, + title = stringResource(R.string.home_folder_empty_title), + modifier = Modifier.padding(horizontal = CapTheme.pageMargin), + description = stringResource(R.string.home_empty_space), + ) + } + } + else -> { + LazyColumn( + modifier = Modifier.fillMaxSize(), + state = listState, + contentPadding = PaddingValues(bottom = 24.dp), + ) { + if (library.showingOfflineCache) { + item(key = "offline", contentType = "offline") { + Text( + text = + pluralStringResource( + R.plurals.library_offline_saved_caps, + caps.size, + caps.size, + ), + modifier = + Modifier.fillMaxWidth() + .padding( + horizontal = CapTheme.pageMargin, + vertical = 8.dp, + ), + color = CapTheme.colors.textSecondary, + style = CapType.small, + ) + } + } + if (showsFolders) { + items( + folders, + key = { "folder:${it.id}" }, + contentType = { "folder" }, + ) { folder -> + LibraryFolderRow(folder = folder, onOpen = onOpenFolder) + } + } + items(rows, key = { (id) -> "cap:$id" }, contentType = { "cap" }) { + (id, cap) -> + CapRow( + cap = cap, + userId = session.credentials.userId, + onClick = { onOpenCap(id) }, + onAction = { action -> + when (action) { + CapAction.CopyLink -> + copyCapLink(context, cap, session.toasts) + CapAction.Share -> shareCap(context, cap) + CapAction.MakePrivate -> + session.setPublic(cap, isPublic = false) + CapAction.MakePublic -> + session.setPublic(cap, isPublic = true) + CapAction.Delete -> pendingDeleteId = cap.id + } + }, + ) + LaunchedEffect(cap.id, caps, library.isLoadingMore) { + library.loadMoreIfNeeded(cap) + } + } + if (library.isLoadingMore) { + item(key = "footer", contentType = "loading") { + Box(Modifier.fillMaxWidth().padding(16.dp), Alignment.Center) { + CircularProgressIndicator( + Modifier.size(24.dp), + strokeWidth = 2.dp, + ) + } + } + } else if (library.loadMoreError != null) { + item(key = "footer", contentType = "retry") { + TextButton( + onClick = { library.retryLoadMore() }, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = stringResource(R.string.home_load_more_failed), + style = CapType.small, + ) + } + } + } + } + } + } + if (library.isEmpty && status == LibraryModel.Status.Loading) { + LibrarySkeleton() + } else if (library.isEmpty && status is LibraryModel.Status.Failed) { + EmptyState( + icon = R.drawable.ic_warning, + title = stringResource(R.string.home_load_failed), + modifier = Modifier.align(Alignment.Center), + description = status.error.description, + actions = { + InkButton(onClick = { library.refresh() }) { + Text(stringResource(R.string.home_try_again)) + } + }, + ) + } + } + } +} + +@Composable +private fun LibraryHeader( + session: SessionModel, + library: LibraryModel, + onAdd: (AddAction) -> Unit, + showsDetails: Boolean = true, +) { + var sortOpen by rememberSaveable { mutableStateOf(false) } + Column { + Row( + modifier = + Modifier.fillMaxWidth().height(CapTheme.touchTarget).padding(horizontal = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Spacer(Modifier.weight(1f)) + AddMenu( + showsNewFolder = library.key.folderId == null && session.canCreateFolder, + onAction = onAdd, + ) + } + if (showsDetails) { + Row( + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = CapTheme.pageMargin) + .height(104.dp), + verticalAlignment = Alignment.Bottom, + ) { + if (library.isEmpty && library.status == LibraryModel.Status.Loading) { + SkeletonBlock(Modifier.width(168.dp).height(72.dp).shimmering()) + } else { + Text( + text = CapFormat.count(library.total), + color = MaterialTheme.colorScheme.onBackground, + maxLines = 1, + style = CapType.libraryCount, + ) + } + Text( + text = stringResource(R.string.library_caps_label), + modifier = + Modifier.padding(start = 10.dp, bottom = 10.dp).semantics { heading() }, + color = MaterialTheme.colorScheme.onBackground, + style = CapType.panelTitle, + ) + } + } + Box(Modifier.padding(horizontal = CapTheme.pageMargin)) { + ScopeBar( + session = session, + trailing = { + val sorts = library.availableSorts + if (sorts.size > 1 && library.caps.isNotEmpty()) { + SortControl( + sort = library.sort, + onClick = { sortOpen = true }, + ) + } + }, + ) + } + } + if (sortOpen) { + SortSheet( + library = library, + onDismiss = { sortOpen = false }, + ) + } +} + +@Composable +private fun SortControl(sort: LibrarySort, onClick: () -> Unit) { + Row( + modifier = + Modifier.defaultMinSize(minHeight = CapTheme.touchTarget) + .clickable(role = Role.Button, onClick = onClick) + .padding(top = 12.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(sort.label), + color = MaterialTheme.colorScheme.onSurface, + style = CapType.body.copy(fontWeight = FontWeight.SemiBold), + ) + Icon( + painter = painterResource(R.drawable.ic_cap_chevron_down), + contentDescription = stringResource(R.string.library_sort_action), + modifier = Modifier.padding(start = 4.dp).size(12.dp), + tint = MaterialTheme.colorScheme.onSurface, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun SortSheet(library: LibraryModel, onDismiss: () -> Unit) { + ModalBottomSheet( + onDismissRequest = onDismiss, + shape = RoundedCornerShape(topStart = CapTheme.sheetRadius, topEnd = CapTheme.sheetRadius), + containerColor = MaterialTheme.colorScheme.surface, + dragHandle = null, + ) { + Column( + modifier = + Modifier.fillMaxWidth() + .selectableGroup() + .padding(horizontal = CapTheme.pageMargin) + .padding(top = 22.dp, bottom = 28.dp) + ) { + Text( + text = stringResource(R.string.library_sort_title), + modifier = Modifier.padding(bottom = 8.dp).semantics { heading() }, + color = CapTheme.colors.textSecondary, + style = CapType.small, + ) + library.availableSorts.forEachIndexed { index, option -> + CapRadioRow( + title = stringResource(option.label), + selected = library.sort == option, + onClick = { + if (library.selectSort(option)) onDismiss() + }, + modifier = Modifier.height(54.dp), + bottomHairline = index != library.availableSorts.lastIndex, + ) + } + } + } +} + +private val LibrarySort.label: Int + get() = + when (this) { + LibrarySort.NEWEST -> R.string.library_sort_newest + LibrarySort.OLDEST -> R.string.library_sort_oldest + LibrarySort.MOST_VIEWED -> R.string.library_sort_most_viewed + LibrarySort.LONGEST -> R.string.library_sort_longest + LibrarySort.NAME -> R.string.library_sort_name + } + +@Composable +fun LibrarySkeleton(modifier: Modifier = Modifier) { + val label = stringResource(R.string.home_loading) + Column( + modifier = + modifier.fillMaxSize().clipToBounds().shimmering().clearAndSetSemantics { + contentDescription = label + } + ) { + repeat(SKELETON_ROWS) { + Row( + modifier = + Modifier.fillMaxWidth().height(80.dp).padding(horizontal = CapTheme.pageMargin), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + SkeletonBlock(Modifier.size(48.dp)) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) { + SkeletonText("A placeholder Cap title", CapType.rowTitle) + SkeletonText("2 hours ago, 120 views", CapType.metadata) + } + SkeletonText("0:42", CapType.detailTitle) + } + CapHairline(Modifier.padding(start = CapTheme.pageMargin + 64.dp)) + } + } +} + +private const val SKELETON_ROWS = 6 diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryEmptyState.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryEmptyState.kt new file mode 100644 index 00000000000..1944628b446 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryEmptyState.kt @@ -0,0 +1,108 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapColorTokens +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType + +@Composable +fun LibraryEmptyState(modifier: Modifier = Modifier) { + val background = MaterialTheme.colorScheme.background + Column( + modifier = + modifier.fillMaxSize().verticalScroll(rememberScrollState()).background(background) + ) { + Box( + Modifier.fillMaxWidth() + .height(EMPTY_HERO_HEIGHT) + .background( + Brush.verticalGradient( + 0f to CapColorTokens.SkyTop, + 0.40f to CapColorTokens.Sky, + 0.78f to CapColorTokens.SkyBottom, + 1f to background, + ) + ) + ) { + val stroke = with(LocalDensity.current) { 1.dp.toPx() } + Canvas(Modifier.fillMaxSize()) { + val scale = size.minDimension / 560f + val center = Offset(size.width * 0.5f, size.height * 1.50f) + listOf(430f, 560f, 700f).forEachIndexed { index, radius -> + drawCircle( + color = Color.White.copy(alpha = 0.28f - index * 0.04f), + radius = radius * scale, + center = center, + style = Stroke(width = stroke), + ) + } + val cloud = + Brush.radialGradient( + 0f to Color.White.copy(alpha = 0.58f), + 0.68f to Color.White.copy(alpha = 0.28f), + 1f to Color.White.copy(alpha = 0f), + ) + drawOval( + brush = cloud, + topLeft = Offset(size.width * 0.03f, size.height * 0.38f), + size = + androidx.compose.ui.geometry.Size(size.width * 0.48f, size.height * 0.18f), + ) + drawOval( + brush = cloud, + topLeft = Offset(size.width * 0.56f, size.height * 0.48f), + size = + androidx.compose.ui.geometry.Size(size.width * 0.43f, size.height * 0.16f), + ) + drawOval( + brush = cloud, + topLeft = Offset(size.width * 0.28f, size.height * 0.28f), + size = + androidx.compose.ui.geometry.Size(size.width * 0.36f, size.height * 0.13f), + ) + } + } + Column( + modifier = + Modifier.fillMaxWidth().padding(horizontal = CapTheme.pageMargin, vertical = 22.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.home_empty_title), + color = MaterialTheme.colorScheme.onBackground, + style = CapType.screenTitle, + ) + Text( + text = stringResource(R.string.home_empty_personal), + modifier = Modifier.padding(top = 8.dp), + color = CapTheme.colors.textSecondary, + style = CapType.body, + textAlign = androidx.compose.ui.text.style.TextAlign.Center, + ) + } + } +} + +private val EMPTY_HERO_HEIGHT = 560.dp diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/NewFolderSheet.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/NewFolderSheet.kt new file mode 100644 index 00000000000..fea7698e2dc --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/NewFolderSheet.kt @@ -0,0 +1,146 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.InputTransformation +import androidx.compose.foundation.text.input.delete +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.ModalBottomSheetProperties +import androidx.compose.material3.SheetValue +import androidx.compose.material3.Text +import androidx.compose.material3.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.dp +import so.cap.kit.FolderColor +import so.cap.mobile.R +import so.cap.mobile.app.FolderDraft +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType + +private const val SELECTED_RING_ALPHA = 0.4f + +private val nameLimit = InputTransformation { + val kept = FolderDraft.keptLength(asCharSequence()) + if (kept < length) delete(kept, length) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun NewFolderSheet(draft: FolderDraft, onSave: () -> Unit, onCancel: () -> Unit) { + val sheetState = + rememberBottomSheetState( + SheetValue.Hidden, + setOf(SheetValue.Hidden, SheetValue.Expanded), + confirmValueChange = { it != SheetValue.Hidden || !draft.isSaving }, + ) + ModalBottomSheet( + onDismissRequest = onCancel, + sheetState = sheetState, + properties = ModalBottomSheetProperties(shouldDismissOnBackPress = !draft.isSaving), + ) { + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = CapTheme.spacing)) { + SheetHeader( + title = stringResource(R.string.folder_new_title), + confirmLabel = stringResource(R.string.folder_create), + confirmIcon = R.drawable.ic_check, + confirmEnabled = draft.name.text.isNotBlank(), + isWorking = draft.isSaving, + onCancel = onCancel, + onConfirm = onSave, + ) + Column( + modifier = + Modifier.weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + .padding(top = 16.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + val focus = rememberSheetFocus() + SheetField( + state = draft.name, + label = stringResource(R.string.folder_name_label), + keyboardOptions = + KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Done, + ), + onSubmit = onSave, + modifier = Modifier.focusRequester(focus), + inputTransformation = nameLimit, + ) + Text( + text = stringResource(R.string.folder_color_label), + modifier = Modifier.semantics { heading() }, + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.footnote, + ) + Row( + modifier = Modifier.fillMaxWidth().selectableGroup(), + horizontalArrangement = + Arrangement.spacedBy(18.dp, Alignment.CenterHorizontally), + ) { + FolderColor.entries.forEach { option -> + val selected = draft.color == option + val ring = + if (selected) { + MaterialTheme.colorScheme.onSurface.copy( + alpha = SELECTED_RING_ALPHA + ) + } else { + Color.Transparent + } + Box( + modifier = + Modifier.size(48.dp) + .clip(CircleShape) + .border(2.dp, ring, CircleShape) + .selectable( + selected = selected, + role = Role.RadioButton, + onClick = { draft.color = option }, + ) + .semantics { contentDescription = option.displayName }, + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(R.drawable.ic_folder), + contentDescription = null, + modifier = Modifier.size(28.dp), + tint = option.tint(), + ) + } + } + } + draft.error?.let { SheetError(it) } + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/OpenLinkSheet.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/OpenLinkSheet.kt new file mode 100644 index 00000000000..7bb580eab4c --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/OpenLinkSheet.kt @@ -0,0 +1,119 @@ +package so.cap.mobile.features.home + +import android.content.ClipboardManager +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SheetValue +import androidx.compose.material3.Text +import androidx.compose.material3.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import so.cap.kit.CapId +import so.cap.kit.ShareLinkParser +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.TonalButton + +private const val PASTE_LIMIT = 2048 + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun OpenLinkSheet(onOpen: (CapId) -> Unit, onCancel: () -> Unit) { + val context = LocalContext.current + val link = rememberTextFieldState() + var notALink by rememberSaveable { mutableStateOf(false) } + val open = { + val id = ShareLinkParser.capIdFromUserInput(link.text.toString()) + if (id == null) notALink = true else onOpen(id) + } + ModalBottomSheet( + onDismissRequest = onCancel, + sheetState = + rememberBottomSheetState( + SheetValue.Hidden, + setOf(SheetValue.Hidden, SheetValue.Expanded), + ), + ) { + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = CapTheme.spacing)) { + SheetHeader( + title = stringResource(R.string.add_open_link), + confirmLabel = stringResource(R.string.link_open), + confirmIcon = R.drawable.ic_arrow_forward, + confirmEnabled = link.text.isNotBlank(), + isWorking = false, + onCancel = onCancel, + onConfirm = open, + ) + Column( + modifier = + Modifier.weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + .padding(top = 16.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + val focus = rememberSheetFocus() + SheetField( + state = link, + label = stringResource(R.string.link_placeholder), + keyboardOptions = + KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Go, + ), + onSubmit = open, + modifier = Modifier.focusRequester(focus), + ) + TonalButton( + onClick = { + val clip = + context.getSystemService(ClipboardManager::class.java).primaryClip + val item = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0) + val pasted = item?.text ?: item?.uri?.toString() + if (pasted != null) { + link.setTextAndPlaceCursorAtEnd(pasted.take(PASTE_LIMIT).toString()) + open() + } + } + ) { + Icon(painterResource(R.drawable.ic_content_paste), contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.link_paste)) + } + Text( + text = stringResource(R.string.link_footer), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.footnote, + ) + if (notALink) SheetError(stringResource(R.string.link_error)) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/ScopeBar.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/ScopeBar.kt new file mode 100644 index 00000000000..c412831d0e9 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/ScopeBar.kt @@ -0,0 +1,251 @@ +package so.cap.mobile.features.home + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.selection.selectable +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.flow.first +import so.cap.kit.Organization +import so.cap.kit.Space +import so.cap.mobile.R +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.SessionModel +import so.cap.mobile.designsystem.CapHairline +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType + +@Composable +fun ScopeBar( + session: SessionModel, + modifier: Modifier = Modifier, + trailing: @Composable () -> Unit = {}, +) { + ScopeBarContent( + organizations = session.bootstrap?.organizations.orEmpty(), + activeOrganization = session.bootstrap?.activeOrganization, + currentOrganizationId = session.organizationId, + isSwitchingOrganization = session.isSwitchingOrganization, + spaces = session.spaces, + selected = session.libraryScope, + onSelect = { session.select(it) }, + onSwitchOrganization = { session.switchOrganization(it) }, + modifier = modifier, + trailing = trailing, + ) +} + +@Composable +internal fun ScopeBarContent( + organizations: List, + activeOrganization: Organization?, + currentOrganizationId: String?, + isSwitchingOrganization: Boolean, + spaces: List, + selected: LibraryScope, + onSelect: (LibraryScope) -> Unit, + onSwitchOrganization: (Organization) -> Unit, + modifier: Modifier = Modifier, + trailing: @Composable () -> Unit = {}, +) { + val showsOrganizations = organizations.size > 1 + val state = rememberLazyListState() + LaunchedEffect(selected, spaces, showsOrganizations) { + val personal = if (showsOrganizations) 1 else 0 + val target = + selected.spaceId + ?.let { id -> spaces.indexOfFirst { it.id == id } } + ?.takeIf { it >= 0 } + ?.let { personal + 1 + it } ?: personal + val layout = snapshotFlow { state.layoutInfo }.first { it.visibleItemsInfo.isNotEmpty() } + if (layout.visibleItemsInfo.none { it.index == target }) { + state.scrollToItem(target) + snapshotFlow { state.layoutInfo } + .first { info -> info.visibleItemsInfo.any { it.index == target } } + } + val width = + state.layoutInfo.visibleItemsInfo.firstOrNull { it.index == target }?.size + ?: return@LaunchedEffect + val centred = + (state.layoutInfo.viewportSize.width - width) / 2 - + state.layoutInfo.beforeContentPadding + state.animateScrollToItem(target, scrollOffset = -centred) + } + Box(modifier.fillMaxWidth().defaultMinSize(minHeight = 45.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + LazyRow( + modifier = Modifier.weight(1f).padding(end = 12.dp), + state = state, + verticalAlignment = Alignment.CenterVertically, + ) { + if (organizations.size > 1) { + item(key = "organization") { + OrganizationScopeItem( + organizations = organizations, + activeOrganization = activeOrganization, + currentOrganizationId = currentOrganizationId, + isSwitchingOrganization = isSwitchingOrganization, + onSwitchOrganization = onSwitchOrganization, + ) + } + } + item(key = "personal") { + ScopeItem( + title = stringResource(R.string.home_title_personal), + isSelected = selected == LibraryScope.Personal, + onClick = { onSelect(LibraryScope.Personal) }, + ) + } + items(spaces, key = { "space:${it.id}" }) { space -> + val scope = LibraryScope.Space(space.id) + ScopeItem( + title = space.name, + isSelected = selected == scope, + onClick = { onSelect(scope) }, + ) + } + } + trailing() + } + CapHairline(Modifier.align(Alignment.BottomCenter)) + } +} + +@Composable +private fun ScopeItem(title: String, isSelected: Boolean, onClick: () -> Unit) { + val underline = MaterialTheme.colorScheme.onSurface + Text( + text = title, + modifier = + Modifier.padding(end = 22.dp) + .defaultMinSize(minHeight = CapTheme.touchTarget) + .selectable(selected = isSelected, onClick = onClick, role = Role.Tab) + .drawBehind { + if (isSelected) { + drawRect( + color = underline, + topLeft = Offset(0f, size.height - 2.dp.toPx()), + size = Size(size.width, 2.dp.toPx()), + ) + } + } + .padding(top = 12.dp, bottom = 10.dp), + color = + if (isSelected) MaterialTheme.colorScheme.onSurface else CapTheme.colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = + CapType.body.copy( + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium + ), + ) +} + +@Composable +private fun OrganizationScopeItem( + organizations: List, + activeOrganization: Organization?, + currentOrganizationId: String?, + isSwitchingOrganization: Boolean, + onSwitchOrganization: (Organization) -> Unit, +) { + var isOpen by remember { mutableStateOf(false) } + val label = stringResource(R.string.organization_chip_label, activeOrganization?.name.orEmpty()) + Box(Modifier.padding(end = 22.dp)) { + Row( + modifier = + Modifier.defaultMinSize(minHeight = CapTheme.touchTarget) + .clickable( + onClickLabel = stringResource(R.string.organization_switch_action), + role = Role.DropdownList, + onClick = { isOpen = true }, + ) + .clearAndSetSemantics { contentDescription = label } + .padding(top = 12.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isSwitchingOrganization) { + CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp) + } else { + Text( + text = + activeOrganization?.name ?: stringResource(R.string.organization_fallback), + color = CapTheme.colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.body.copy(fontWeight = FontWeight.Medium), + ) + Icon( + painter = painterResource(R.drawable.ic_cap_chevron_down), + contentDescription = null, + modifier = Modifier.padding(start = 4.dp).size(12.dp), + tint = CapTheme.colors.textSecondary, + ) + } + } + DropdownMenu(expanded = isOpen, onDismissRequest = { isOpen = false }) { + Text( + text = stringResource(R.string.organization_switch_title), + modifier = + Modifier.padding(horizontal = 12.dp, vertical = 8.dp).semantics { heading() }, + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.small, + ) + organizations.forEach { organization -> + DropdownMenuItem( + text = { Text(organization.name) }, + onClick = { + isOpen = false + onSwitchOrganization(organization) + }, + trailingIcon = + if (organization.id == currentOrganizationId) { + { + Icon( + painterResource(R.drawable.ic_cap_check), + contentDescription = + stringResource(R.string.organization_current), + ) + } + } else { + null + }, + ) + } + } + } +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/Sheets.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/Sheets.kt new file mode 100644 index 00000000000..0e0e8a62c31 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/Sheets.kt @@ -0,0 +1,169 @@ +package so.cap.mobile.features.home + +import android.view.ViewTreeObserver +import android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE +import android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.InputTransformation +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogWindowProvider +import so.cap.mobile.R +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.ErrorText + +// Material gives the sheet's window adjust=nothing from API 30, and the system hides the keyboard +// each time such a window takes focus. That hide reaches the app late and can land after the field +// has asked for the keyboard, so the sheet opens focused with no keyboard: about one opening in +// four on API 37. Material sets the mode again on every recomposition, so the window is told to +// leave the keyboard as it is at the moment it takes focus, just before the system reads the mode. +@Composable +fun rememberSheetFocus(): FocusRequester { + val focus = remember { FocusRequester() } + val view = LocalView.current + DisposableEffect(view) { + val window = (view.parent as? DialogWindowProvider)?.window + val keepKeyboard = ViewTreeObserver.OnWindowFocusChangeListener { focused -> + if (focused && window != null) { + window.setSoftInputMode( + window.attributes.softInputMode and + SOFT_INPUT_MASK_STATE.inv() or + SOFT_INPUT_STATE_UNCHANGED + ) + } + } + view.viewTreeObserver.addOnWindowFocusChangeListener(keepKeyboard) + onDispose { view.viewTreeObserver.removeOnWindowFocusChangeListener(keepKeyboard) } + } + LaunchedEffect(focus) { focus.requestFocus() } + return focus +} + +@Composable +fun SheetError(message: String) { + val place = remember { BringIntoViewRequester() } + LaunchedEffect(message) { place.bringIntoView() } + ErrorText(message, Modifier.bringIntoViewRequester(place)) +} + +@Composable +fun SheetHeader( + title: String, + confirmLabel: String, + @DrawableRes confirmIcon: Int, + confirmEnabled: Boolean, + isWorking: Boolean, + onCancel: () -> Unit, + onConfirm: () -> Unit, + modifier: Modifier = Modifier, +) { + Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = onCancel) { + Icon( + painterResource(R.drawable.ic_close), + contentDescription = stringResource(R.string.action_cancel), + ) + } + Text( + text = title, + modifier = Modifier.weight(1f).semantics { heading() }, + textAlign = TextAlign.Center, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CapType.headline, + ) + if (isWorking) { + Box(Modifier.size(48.dp), Alignment.Center) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) + } + } else { + IconButton(onClick = onConfirm, enabled = confirmEnabled) { + Icon(painterResource(confirmIcon), contentDescription = confirmLabel) + } + } + } +} + +@Composable +fun SheetField( + state: TextFieldState, + label: String, + keyboardOptions: KeyboardOptions, + onSubmit: () -> Unit, + modifier: Modifier = Modifier, + inputTransformation: InputTransformation? = null, +) { + val interactions = remember { MutableInteractionSource() } + val focused by interactions.collectIsFocusedAsState() + val ink = MaterialTheme.colorScheme.onSurface + val ring = if (focused) MaterialTheme.colorScheme.primary else Color.Transparent + BasicTextField( + state = state, + modifier = modifier.fillMaxWidth().semantics { contentDescription = label }, + inputTransformation = inputTransformation, + textStyle = CapType.body.copy(color = ink), + keyboardOptions = keyboardOptions, + onKeyboardAction = { onSubmit() }, + lineLimits = TextFieldLineLimits.SingleLine, + interactionSource = interactions, + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + decorator = { field -> + Box( + modifier = + Modifier.defaultMinSize(minHeight = 52.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, CircleShape) + .border(1.dp, ring, CircleShape) + .padding(horizontal = 18.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (state.text.isEmpty()) { + Text( + text = label, + color = MaterialTheme.colorScheme.outline, + style = CapType.body, + ) + } + field() + } + }, + ) +} diff --git a/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/settings/SettingsScreen.kt b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/settings/SettingsScreen.kt new file mode 100644 index 00000000000..76e1d8d1d73 --- /dev/null +++ b/apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/settings/SettingsScreen.kt @@ -0,0 +1,146 @@ +package so.cap.mobile.features.settings + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import so.cap.mobile.R +import so.cap.mobile.app.AppVersion +import so.cap.mobile.designsystem.CapTheme +import so.cap.mobile.designsystem.CapType +import so.cap.mobile.designsystem.capCardBackground +import so.cap.mobile.designsystem.monospacedDigit + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen(version: AppVersion, signingOut: Boolean, onSignOut: () -> Unit) { + var confirming by rememberSaveable { mutableStateOf(false) } + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column { + TopAppBar(title = { Text(stringResource(R.string.tab_settings)) }) + Column( + modifier = + Modifier.verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(20.dp), + ) { + SettingsRow( + icon = R.drawable.ic_info, + label = stringResource(R.string.settings_version), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.semantics(mergeDescendants = true) {}, + ) { + Text( + text = + stringResource( + R.string.settings_version_value, + version.name, + version.build, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = CapType.body.monospacedDigit(), + ) + } + SettingsRow( + icon = R.drawable.ic_logout, + label = stringResource(R.string.settings_sign_out), + color = MaterialTheme.colorScheme.error, + modifier = + Modifier.clickable(enabled = !signingOut, role = Role.Button) { + confirming = true + }, + ) { + if (signingOut) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp).clearAndSetSemantics {}, + color = MaterialTheme.colorScheme.onSurfaceVariant, + strokeWidth = 2.dp, + ) + } + } + } + } + } + if (confirming) { + AlertDialog( + onDismissRequest = { confirming = false }, + title = { Text(stringResource(R.string.settings_sign_out_title)) }, + confirmButton = { + TextButton( + onClick = { + confirming = false + onSignOut() + } + ) { + Text( + text = stringResource(R.string.settings_sign_out), + color = MaterialTheme.colorScheme.error, + ) + } + }, + dismissButton = { + TextButton(onClick = { confirming = false }) { + Text(stringResource(R.string.settings_cancel)) + } + }, + ) + } +} + +@Composable +private fun SettingsRow( + @DrawableRes icon: Int, + label: String, + color: Color, + modifier: Modifier, + trailing: @Composable () -> Unit, +) { + Row( + modifier = + Modifier.fillMaxWidth() + .defaultMinSize(minHeight = 52.dp) + .clip(RoundedCornerShape(CapTheme.cardRadius)) + .capCardBackground() + .then(modifier) + .padding(horizontal = 16.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.spacedBy(14.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(painter = painterResource(icon), contentDescription = null, tint = color) + Text(text = label, modifier = Modifier.weight(1f), color = color, style = CapType.body) + trailing() + } +} diff --git a/apps/mobile-android/app/src/main/res/drawable-nodpi/cap_logo_large.webp b/apps/mobile-android/app/src/main/res/drawable-nodpi/cap_logo_large.webp new file mode 100644 index 00000000000..d44b04e9169 Binary files /dev/null and b/apps/mobile-android/app/src/main/res/drawable-nodpi/cap_logo_large.webp differ diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_add.xml b/apps/mobile-android/app/src/main/res/drawable/ic_add.xml new file mode 100644 index 00000000000..2a553652d6a --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_add.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_arrow_back.xml b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_back.xml new file mode 100644 index 00000000000..70aee9c3ee8 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_back.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_arrow_forward.xml b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_forward.xml new file mode 100644 index 00000000000..884df0af2ba --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_forward.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_arrow_upward.xml b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_upward.xml new file mode 100644 index 00000000000..e3d94b652c3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_arrow_upward.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_back_hand.xml b/apps/mobile-android/app/src/main/res/drawable/ic_back_hand.xml new file mode 100644 index 00000000000..19cd8c637f0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_back_hand.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cancel.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cancel.xml new file mode 100644 index 00000000000..4be22ac20f3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cancel.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_back.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_back.xml new file mode 100644 index 00000000000..a3eb06cc0b8 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_back.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera.xml new file mode 100644 index 00000000000..14c60cd34e1 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera_off.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera_off.xml new file mode 100644 index 00000000000..fdc4e45d46d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_camera_off.xml @@ -0,0 +1,27 @@ + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_check.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_check.xml new file mode 100644 index 00000000000..d7acfad397a --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_check.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_down.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_down.xml new file mode 100644 index 00000000000..afc20fd3873 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_down.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_right.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_right.xml new file mode 100644 index 00000000000..2ae42adc339 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_chevron_right.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_close.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_close.xml new file mode 100644 index 00000000000..ab4c2f5e0fe --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_close.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_copy.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_copy.xml new file mode 100644 index 00000000000..143eacdea76 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_copy.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_edit.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_edit.xml new file mode 100644 index 00000000000..f6fa7533809 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_edit.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_folder.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_folder.xml new file mode 100644 index 00000000000..a5f8d3aaf4e --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_folder.xml @@ -0,0 +1,13 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_glyph.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_glyph.xml new file mode 100644 index 00000000000..d307a8ad7f6 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_glyph.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic.xml new file mode 100644 index 00000000000..5672cfdd4ce --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic.xml @@ -0,0 +1,27 @@ + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic_off.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic_off.xml new file mode 100644 index 00000000000..0b9b0ccacfe --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_mic_off.xml @@ -0,0 +1,34 @@ + + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_pause.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_pause.xml new file mode 100644 index 00000000000..69917a8b3bf --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_pause.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_play.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_play.xml new file mode 100644 index 00000000000..771f377dfc2 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_play.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_redo.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_redo.xml new file mode 100644 index 00000000000..6b747f69ebe --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_redo.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_search.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_search.xml new file mode 100644 index 00000000000..fc6e5a7d746 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_search.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_send.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_send.xml new file mode 100644 index 00000000000..316a59f25c3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_send.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_share.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_share.xml new file mode 100644 index 00000000000..8a945ecb71b --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_share.xml @@ -0,0 +1,27 @@ + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_cap_undo.xml b/apps/mobile-android/app/src/main/res/drawable/ic_cap_undo.xml new file mode 100644 index 00000000000..8792d3973e7 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_cap_undo.xml @@ -0,0 +1,20 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_chat_bubble.xml b/apps/mobile-android/app/src/main/res/drawable/ic_chat_bubble.xml new file mode 100644 index 00000000000..58ca5f7a194 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_chat_bubble.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_check.xml b/apps/mobile-android/app/src/main/res/drawable/ic_check.xml new file mode 100644 index 00000000000..6e017632fbd --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_check.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_check_circle.xml b/apps/mobile-android/app/src/main/res/drawable/ic_check_circle.xml new file mode 100644 index 00000000000..ee299568af0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_check_circle.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_close.xml b/apps/mobile-android/app/src/main/res/drawable/ic_close.xml new file mode 100644 index 00000000000..719b1172b99 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_close.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption.xml b/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption.xml new file mode 100644 index 00000000000..7203a75a8f7 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption_disabled.xml b/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption_disabled.xml new file mode 100644 index 00000000000..725903f112d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_closed_caption_disabled.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_content_copy.xml b/apps/mobile-android/app/src/main/res/drawable/ic_content_copy.xml new file mode 100644 index 00000000000..58c27b642c5 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_content_copy.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_content_cut.xml b/apps/mobile-android/app/src/main/res/drawable/ic_content_cut.xml new file mode 100644 index 00000000000..932eadce2aa --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_content_cut.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_content_paste.xml b/apps/mobile-android/app/src/main/res/drawable/ic_content_paste.xml new file mode 100644 index 00000000000..8c5772d91df --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_content_paste.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_create_new_folder.xml b/apps/mobile-android/app/src/main/res/drawable/ic_create_new_folder.xml new file mode 100644 index 00000000000..ba01b79e92b --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_create_new_folder.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_delete.xml b/apps/mobile-android/app/src/main/res/drawable/ic_delete.xml new file mode 100644 index 00000000000..c9f748feff0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_delete.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_domain.xml b/apps/mobile-android/app/src/main/res/drawable/ic_domain.xml new file mode 100644 index 00000000000..5a6ecb29d7d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_domain.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_download.xml b/apps/mobile-android/app/src/main/res/drawable/ic_download.xml new file mode 100644 index 00000000000..8f7a037d55f --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_download.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_edit.xml b/apps/mobile-android/app/src/main/res/drawable/ic_edit.xml new file mode 100644 index 00000000000..baaa94ff239 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_edit.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_error.xml b/apps/mobile-android/app/src/main/res/drawable/ic_error.xml new file mode 100644 index 00000000000..ec5a8eedab9 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_error.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_expand_more.xml b/apps/mobile-android/app/src/main/res/drawable/ic_expand_more.xml new file mode 100644 index 00000000000..261bf3ff238 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_expand_more.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_flag.xml b/apps/mobile-android/app/src/main/res/drawable/ic_flag.xml new file mode 100644 index 00000000000..ce32239a801 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_flag.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_folder.xml b/apps/mobile-android/app/src/main/res/drawable/ic_folder.xml new file mode 100644 index 00000000000..e437a94d3ad --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_folder.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_forum.xml b/apps/mobile-android/app/src/main/res/drawable/ic_forum.xml new file mode 100644 index 00000000000..f6f00d81c0c --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_forum.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_forward_10.xml b/apps/mobile-android/app/src/main/res/drawable/ic_forward_10.xml new file mode 100644 index 00000000000..2e7aa7f42b3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_forward_10.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_fullscreen.xml b/apps/mobile-android/app/src/main/res/drawable/ic_fullscreen.xml new file mode 100644 index 00000000000..1b908fcbfa8 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_fullscreen.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_google.xml b/apps/mobile-android/app/src/main/res/drawable/ic_google.xml new file mode 100644 index 00000000000..c1c433a4103 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_google.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_graphic_eq.xml b/apps/mobile-android/app/src/main/res/drawable/ic_graphic_eq.xml new file mode 100644 index 00000000000..1c01d21960b --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_graphic_eq.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_hourglass.xml b/apps/mobile-android/app/src/main/res/drawable/ic_hourglass.xml new file mode 100644 index 00000000000..c6363f6c0bd --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_hourglass.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_info.xml b/apps/mobile-android/app/src/main/res/drawable/ic_info.xml new file mode 100644 index 00000000000..d762fe686ee --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_info.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_launcher_foreground.xml b/apps/mobile-android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 00000000000..15515ef552f --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/apps/mobile-android/app/src/main/res/drawable/ic_launcher_monochrome.xml new file mode 100644 index 00000000000..161715ef69d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_link.xml b/apps/mobile-android/app/src/main/res/drawable/ic_link.xml new file mode 100644 index 00000000000..978e5498c81 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_link.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_lock.xml b/apps/mobile-android/app/src/main/res/drawable/ic_lock.xml new file mode 100644 index 00000000000..4dbfc0adf21 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_lock.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_lock_open.xml b/apps/mobile-android/app/src/main/res/drawable/ic_lock_open.xml new file mode 100644 index 00000000000..a930f226313 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_lock_open.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_logout.xml b/apps/mobile-android/app/src/main/res/drawable/ic_logout.xml new file mode 100644 index 00000000000..e141e3a7e29 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_logout.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_mail.xml b/apps/mobile-android/app/src/main/res/drawable/ic_mail.xml new file mode 100644 index 00000000000..fe392ce73f6 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_mail.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_monitoring.xml b/apps/mobile-android/app/src/main/res/drawable/ic_monitoring.xml new file mode 100644 index 00000000000..0df788421fa --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_monitoring.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_mood.xml b/apps/mobile-android/app/src/main/res/drawable/ic_mood.xml new file mode 100644 index 00000000000..0af95f9f332 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_mood.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_more_horiz.xml b/apps/mobile-android/app/src/main/res/drawable/ic_more_horiz.xml new file mode 100644 index 00000000000..f193d677cda --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_more_horiz.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_open_in_new.xml b/apps/mobile-android/app/src/main/res/drawable/ic_open_in_new.xml new file mode 100644 index 00000000000..6a3faa0c8e3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_open_in_new.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_pause.xml b/apps/mobile-android/app/src/main/res/drawable/ic_pause.xml new file mode 100644 index 00000000000..9edbb8d86a5 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_pause.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_person.xml b/apps/mobile-android/app/src/main/res/drawable/ic_person.xml new file mode 100644 index 00000000000..7cff986cf77 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_person.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_photo_library.xml b/apps/mobile-android/app/src/main/res/drawable/ic_photo_library.xml new file mode 100644 index 00000000000..c4444dbcac0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_photo_library.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_picture_in_picture_alt.xml b/apps/mobile-android/app/src/main/res/drawable/ic_picture_in_picture_alt.xml new file mode 100644 index 00000000000..b62443e0728 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_picture_in_picture_alt.xml @@ -0,0 +1,10 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_play_arrow.xml b/apps/mobile-android/app/src/main/res/drawable/ic_play_arrow.xml new file mode 100644 index 00000000000..f6425fc4403 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_play_arrow.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_play_disabled.xml b/apps/mobile-android/app/src/main/res/drawable/ic_play_disabled.xml new file mode 100644 index 00000000000..6fe92c317fc --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_play_disabled.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_public.xml b/apps/mobile-android/app/src/main/res/drawable/ic_public.xml new file mode 100644 index 00000000000..95d83981995 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_public.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_radio_button_checked.xml b/apps/mobile-android/app/src/main/res/drawable/ic_radio_button_checked.xml new file mode 100644 index 00000000000..3d09d4e8b20 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_radio_button_checked.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_replay.xml b/apps/mobile-android/app/src/main/res/drawable/ic_replay.xml new file mode 100644 index 00000000000..42e8c58bf77 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_replay.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_replay_10.xml b/apps/mobile-android/app/src/main/res/drawable/ic_replay_10.xml new file mode 100644 index 00000000000..374e6c3c59b --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_replay_10.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_reply.xml b/apps/mobile-android/app/src/main/res/drawable/ic_reply.xml new file mode 100644 index 00000000000..5ca2311ed51 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_reply.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_schedule.xml b/apps/mobile-android/app/src/main/res/drawable/ic_schedule.xml new file mode 100644 index 00000000000..895da501b84 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_schedule.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_search.xml b/apps/mobile-android/app/src/main/res/drawable/ic_search.xml new file mode 100644 index 00000000000..5eab28e62a0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_search.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_settings.xml b/apps/mobile-android/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 00000000000..68537f671bd --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_share.xml b/apps/mobile-android/app/src/main/res/drawable/ic_share.xml new file mode 100644 index 00000000000..fdfc65b664d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_share.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_smart_display.xml b/apps/mobile-android/app/src/main/res/drawable/ic_smart_display.xml new file mode 100644 index 00000000000..e66b7cfa7b3 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_smart_display.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_subject.xml b/apps/mobile-android/app/src/main/res/drawable/ic_subject.xml new file mode 100644 index 00000000000..80d9e43f98f --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_subject.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_upload_file.xml b/apps/mobile-android/app/src/main/res/drawable/ic_upload_file.xml new file mode 100644 index 00000000000..7afec137f14 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_upload_file.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_video_library.xml b/apps/mobile-android/app/src/main/res/drawable/ic_video_library.xml new file mode 100644 index 00000000000..0ad4e985e74 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_video_library.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_videocam_off.xml b/apps/mobile-android/app/src/main/res/drawable/ic_videocam_off.xml new file mode 100644 index 00000000000..e8e06f94003 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_videocam_off.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_visibility.xml b/apps/mobile-android/app/src/main/res/drawable/ic_visibility.xml new file mode 100644 index 00000000000..7bd0c4f9467 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_visibility.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_warning.xml b/apps/mobile-android/app/src/main/res/drawable/ic_warning.xml new file mode 100644 index 00000000000..485b988fb3d --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_warning.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/drawable/ic_wifi_off.xml b/apps/mobile-android/app/src/main/res/drawable/ic_wifi_off.xml new file mode 100644 index 00000000000..33eb20436ce --- /dev/null +++ b/apps/mobile-android/app/src/main/res/drawable/ic_wifi_off.xml @@ -0,0 +1,9 @@ + + + diff --git a/apps/mobile-android/app/src/main/res/font/inter_medium.ttf b/apps/mobile-android/app/src/main/res/font/inter_medium.ttf new file mode 100644 index 00000000000..458cd0601d2 Binary files /dev/null and b/apps/mobile-android/app/src/main/res/font/inter_medium.ttf differ diff --git a/apps/mobile-android/app/src/main/res/font/inter_regular.ttf b/apps/mobile-android/app/src/main/res/font/inter_regular.ttf new file mode 100644 index 00000000000..b7aaca8de1f Binary files /dev/null and b/apps/mobile-android/app/src/main/res/font/inter_regular.ttf differ diff --git a/apps/mobile-android/app/src/main/res/font/inter_semibold.ttf b/apps/mobile-android/app/src/main/res/font/inter_semibold.ttf new file mode 100644 index 00000000000..47f8ab1d681 Binary files /dev/null and b/apps/mobile-android/app/src/main/res/font/inter_semibold.ttf differ diff --git a/apps/mobile-android/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/apps/mobile-android/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 00000000000..c78bee3b538 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/apps/mobile-android/app/src/main/res/values-night/colors.xml b/apps/mobile-android/app/src/main/res/values-night/colors.xml new file mode 100644 index 00000000000..88fa75c7db7 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values-night/colors.xml @@ -0,0 +1,4 @@ + + + #111111 + diff --git a/apps/mobile-android/app/src/main/res/values-night/themes.xml b/apps/mobile-android/app/src/main/res/values-night/themes.xml new file mode 100644 index 00000000000..a64b682912c --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/values/colors.xml b/apps/mobile-android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000000..9aedb4270fc --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + + #FFFFFF + #FCFCFC + diff --git a/apps/mobile-android/app/src/main/res/values/strings.xml b/apps/mobile-android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000000..577cc9dc2d7 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values/strings.xml @@ -0,0 +1,226 @@ + + + Cancel + Import from Loom + Add + New folder + Open a Cap link + Add a video + Record + Upload from Files + Upload from Photos + Cap + %1$s, loading + Copy link + Delete + Make private + Make public + Share + Instant + Screenshot + of %1$s + show actions + Delete Cap + “%1$s” will be permanently deleted for everyone, including its link, comments and analytics. + Delete this Cap? + Cap link + Link copied + Couldn\'t load this Cap + Loading Cap + It may have been deleted, or the link may be wrong. + Cap not found + open this Cap + Open in browser + This Cap is over its free plan limit. + This Cap is over your plan\'s monthly share limit. + Password + Enter the password the owner shared with you to watch it. + This Cap is password protected + Too many attempts. Wait a few minutes and try again. + Watch Cap + That password didn\'t work. + This video can\'t play right now. + Private + Public + This Cap is private, limited to certain email addresses, or shared with an organization you\'re not in. + You don\'t have access + Comments + Comments %1$s + Summary + Transcript + Untitled + + %s view + %s views + + Anonymous + Comment + Copy text + Delete + Replies to it will be hidden too. + Delete this comment? + Play from %1$s + Reply + Reply to %1$s + Sending… + + Show %1$d more reply + Show %1$d more replies + + Comments are pinned to the moment you\'re watching, so everyone can jump straight to it. + Be the first to comment + Newest first + Oldest first + Video order + Sort comments, %1$s + Comment at %1$s + Cancel reply + Not pinned to a time + Pin to %1$s + Pinned to %1$s + Reply to %1$s… + comment + Replying to %1$s + Send comment + Send reply + Don\'t pin to a time + Error: %1$s + + %d Cap + %d Caps + + Color + Create + %1$s folder, %2$s + Folder name + New folder + Couldn\'t load Cap + Press the shutter. Your first Cap lands here with its link already copied. + Caps shared to this space will appear here. + No Caps yet. + This folder is empty + Couldn\'t load Caps + Couldn\'t load more. Tap to retry. + Loading Caps + My Caps + Try again + Caps + Sort Caps + Sort by + Newest + Oldest + Most viewed + Longest + Name, A to Z + That doesn\'t look like a Cap link. + Paste a Cap share link to watch it here. + Open + Paste + https://cap.so/s/… + %1$s and %2$s + + %1$d comment + %1$d comments + + %1$s at %2$s + + %1$d reaction + %1$d reactions + + Back + + Offline. Showing the %1$d Cap saved on this phone. Uploads carry on when you\'re back. + Offline. Showing the %1$d Caps saved on this phone. Uploads carry on when you\'re back. + + Organization, %1$s + Current + Organization + switch organization + Switch organization + Back 10 seconds + Close full screen + Forward 10 seconds + Full screen + Hide captions + Video + Pause + Picture in Picture + Play + Playback position + %1$s of %2$s + Replay + Show captions + Playback speed %1$s + + %1$d %2$s reaction + %1$d %2$s reactions + + React with %1$s + Close + Cancel + Sign out + Sign out of Cap on this device? + Version + %1$s (%2$d) + Back + Empty + Verification code + Sent to %1$s + Enter the code + Continue + Continue with email + Email + Email address + you@company.com + We\'ll send a six-digit code. No password to remember. + What\'s your email? + Continue with Google + By continuing you agree to the %1$s and %2$s. + Open your email app + Privacy Policy + Nothing yet? Ask for a new code in %1$s + New code sent. It lasts 10 minutes. + Send code + Send a new code + Open source screen recording, now in your pocket. + Terms + Stop recording. The link is already copied. + Use Google instead + comments + %1$d %2$s + reactions + views + %1$s, at %2$s + play from this chapter + Chapters + Generating summary + The summary and chapters appear here when they\'re ready. + No summary yet + Summaries and chapters appear for Caps with spoken audio. + Summary + Analytics + Caps + Record + Settings + Duration %1$s + Protected + Dismiss + Clear search + Transcript copied + Copy text + Copy with timestamps + The transcript is empty. + This Cap couldn\'t be transcribed. + The transcript couldn\'t be loaded. + Loading transcript + There\'s no transcript for this Cap. + No audio track was detected in this Cap. + No Results for “%1$s” + Check the spelling or try a new search. + No transcript + Transcript options + play from %1$s + The transcript is still being generated. + Search transcript + Share transcript + diff --git a/apps/mobile-android/app/src/main/res/values/strings_cap_management.xml b/apps/mobile-android/app/src/main/res/values/strings_cap_management.xml new file mode 100644 index 00000000000..cb819682928 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values/strings_cap_management.xml @@ -0,0 +1,36 @@ + + + Save + Add password + Analytics + Block owner + Change password + Copy link at %1$s + Edit + Rename + Report Cap + Block + You won\'t see their Caps or comments in Cap for Android. + this user + Block %1$s? + Link at %1$s copied + Viewers will need this password to watch. You and your organization can still open it in Cap. + New password + + Passwords can be up to %1$d character. + Passwords can be up to %1$d characters. + + Remove password + Password + Title + Rename Cap + Why are you reporting this Cap? + Anyone with the link + Only people in your organization + Only you and your team + Who can watch + Share link + Download to this phone + Delete this Cap + Done + diff --git a/apps/mobile-android/app/src/main/res/values/themes.xml b/apps/mobile-android/app/src/main/res/values/themes.xml new file mode 100644 index 00000000000..e827b9d8bd8 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/apps/mobile-android/app/src/main/res/values/upper_layer_resources.xml b/apps/mobile-android/app/src/main/res/values/upper_layer_resources.xml new file mode 100644 index 00000000000..52228f2cbe0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/values/upper_layer_resources.xml @@ -0,0 +1,3 @@ + + diff --git a/apps/mobile-android/app/src/main/res/xml/data_extraction_rules.xml b/apps/mobile-android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000000..224515d8b15 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/apps/mobile-android/app/src/main/res/xml/full_backup_content.xml b/apps/mobile-android/app/src/main/res/xml/full_backup_content.xml new file mode 100644 index 00000000000..ce0b32432a0 --- /dev/null +++ b/apps/mobile-android/app/src/main/res/xml/full_backup_content.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/BackupRulesTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/BackupRulesTest.kt new file mode 100644 index 00000000000..3a776a59167 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/BackupRulesTest.kt @@ -0,0 +1,58 @@ +package so.cap.mobile + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +class BackupRulesTest { + private val android = "http://schemas.android.com/apk/res/android" + + private fun parse(path: String): Element = + DocumentBuilderFactory.newInstance() + .apply { isNamespaceAware = true } + .newDocumentBuilder() + .parse(File(path)) + .documentElement + + private fun children(element: Element, name: String): List { + val nodes = element.getElementsByTagName(name) + return (0 until nodes.length).map { nodes.item(it) as Element } + } + + private fun excludesTheWholeDataDirectory(section: Element): Boolean = + children(section, "include").isEmpty() && + children(section, "exclude").any { + it.getAttribute("domain") == "root" && it.getAttribute("path") == "." + } + + @Test + fun cloudBackupAndDeviceTransferBothLeaveOutTheDataDirectory() { + val rules = parse("src/main/res/xml/data_extraction_rules.xml") + + assertTrue(excludesTheWholeDataDirectory(children(rules, "cloud-backup").single())) + assertTrue(excludesTheWholeDataDirectory(children(rules, "device-transfer").single())) + } + + @Test + fun theOlderBackupRulesLeaveOutTheDataDirectory() { + assertTrue(excludesTheWholeDataDirectory(parse("src/main/res/xml/full_backup_content.xml"))) + } + + @Test + fun theManifestSwitchesBackupOffAndNamesBothRuleFiles() { + val application = children(parse("src/main/AndroidManifest.xml"), "application").single() + + assertEquals("false", application.getAttributeNS(android, "allowBackup")) + assertEquals( + "@xml/data_extraction_rules", + application.getAttributeNS(android, "dataExtractionRules"), + ) + assertEquals( + "@xml/full_backup_content", + application.getAttributeNS(android, "fullBackupContent"), + ) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ApiServer.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ApiServer.kt new file mode 100644 index 00000000000..b4c5eeed838 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ApiServer.kt @@ -0,0 +1,82 @@ +package so.cap.mobile.app + +import com.sun.net.httpserver.HttpServer +import java.io.Closeable +import java.net.InetAddress +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executors +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.runBlocking +import so.cap.kit.CapEnvironment + +class HeldReply(private val reply: Reply) { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + + fun answer(): Reply { + arrived.complete(Unit) + runBlocking { release.await() } + return reply + } +} + +// Answers each request on its own thread, so a test can hold one reply back while a later +// request is answered. LoopbackServer serves one connection at a time. +class ApiServer(handler: (RecordedRequest) -> Reply) : Closeable { + val requests = CopyOnWriteArrayList() + + private val executor = Executors.newCachedThreadPool() + private val server = + HttpServer.create(InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 50) + + val environment: CapEnvironment + get() = + checkNotNull( + CapEnvironment.parse( + "http://127.0.0.1:${server.address.port}", + allowInsecureLocalhost = true, + ) + ) + + init { + server.executor = executor + server.createContext("/") { exchange -> + exchange.use { + val request = + RecordedRequest( + method = exchange.requestMethod, + path = exchange.requestURI.toString(), + headers = + exchange.requestHeaders.entries.associate { + it.key.lowercase() to it.value.first() + }, + body = exchange.requestBody.readBytes().decodeToString(), + ) + requests += request + val reply = handler(request) + reply.headers.forEach { (name, value) -> exchange.responseHeaders.add(name, value) } + exchange.sendResponseHeaders( + reply.status, + if (reply.body.isEmpty()) -1 else reply.body.size.toLong(), + ) + exchange.responseBody.write(reply.body) + } + } + server.start() + } + + fun count(method: String, path: String): Int = requests.count { + it.method == method && it.path.substringBefore('?') == path + } + + override fun close() { + server.stop(0) + executor.shutdownNow() + } + + companion object { + fun json(body: String, status: Int = 200) = + Reply(status, mapOf("Content-Type" to "application/json"), body.toByteArray()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/AppModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/AppModelTest.kt new file mode 100644 index 00000000000..24db0e1bdca --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/AppModelTest.kt @@ -0,0 +1,492 @@ +package so.cap.mobile.app + +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import androidx.lifecycle.SavedStateHandle +import java.io.File +import java.io.IOException +import javax.crypto.KeyGenerator +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.ApiKeySession +import so.cap.kit.AuthCallback +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapApiException +import so.cap.kit.CapEnvironment +import so.cap.kit.CredentialSnapshot +import so.cap.mobile.features.auth.SignInModel + +class AppModelTest { + @get:Rule val folder = TemporaryFolder() + + private val session = ApiKeySession("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie") + private val credentials = CredentialSnapshot(session.apiKey, session.userId) + private val callback = "cap://auth?api_key=${session.apiKey}&user_id=${session.userId}" + private val clock = ModelClock() + + private var server: LoopbackServer? = null + + @After + fun stopTheServer() { + server?.close() + } + + private fun serve(handler: (RecordedRequest) -> Reply): CapEnvironment { + val started = LoopbackServer.http(handler) + server = started + return checkNotNull(CapEnvironment.parse(started.origin, allowInsecureLocalhost = true)) + } + + private fun json(body: String, status: Int = 200) = + Reply(status, mapOf("Content-Type" to "application/json"), body.toByteArray()) + + private val rejectedSessions = Channel(capacity = 4) + private var removals = 0 + private val removed = CompletableDeferred() + + private fun api(vault: CredentialVault, environment: CapEnvironment) = + CapApi( + environment, + "Cap-Android/test", + credentials = { vault.credentials }, + onUnauthorized = { rejectedSessions.trySend(it) }, + ) + + private val saved = SavedStateHandle() + private var wallClock = 1_800_000_000_000L + + private fun model( + vault: CredentialVault, + api: CapApi = api(vault, CapEnvironment.PRODUCTION), + ) = + AppModel( + vault, + api, + clock.scope, + rejectedSessions.receiveAsFlow(), + removeLocalData = { + removals += 1 + removed.complete(Unit) + }, + saved = saved, + now = { wallClock }, + ) + + private fun signIn(model: AppModel) = (model.phase.value as Phase.SignedOut).signIn + + private fun model(vault: CredentialVault, environment: CapEnvironment) = + model(vault, api(vault, environment)) + + private fun emailSignIn(request: RecordedRequest): Reply = + if (request.path.endsWith("/verify")) { + json("""{"type":"api_key","apiKey":"${session.apiKey}","userId":"${session.userId}"}""") + } else { + json("""{"success":true}""") + } + + private suspend fun typeTheCode(model: AppModel): SignInModel { + val signIn = (model.phase.value as Phase.SignedOut).signIn + signIn.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + checkNotNull(signIn.sendCode()).join() + signIn.code.setTextAndPlaceCursorAtEnd("123456") + checkNotNull(signIn.verify()).join() + return signIn + } + + @Test + fun startsSignedOutWithNoSavedSession() { + val model = model(SessionFiles(folder.root).vault()) + + assertNull((model.phase.value as Phase.SignedOut).notice) + } + + @Test + fun startsSignedInWithTheSavedSession() { + val files = SessionFiles(folder.root) + files.store().save(credentials) + + val model = model(files.vault()) + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + } + + @Test + fun completingSignInSavesTheSessionAndSignsIn() { + val files = SessionFiles(folder.root) + val model = model(files.vault()) + + runBlocking { model.completeSignIn(session) } + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(Phase.SignedIn(credentials), model(files.vault()).phase.value) + } + + @Test + fun theSessionIsSavedAwayFromTheCallingThread() { + val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + val keyThreads = mutableListOf() + val store = + CredentialStore(File(folder.root, "session"), "https://cap.so") { + synchronized(keyThreads) { keyThreads += Thread.currentThread() } + key + } + val model = model(CredentialVault(store)) + + runBlocking { model.completeSignIn(session) } + + val saver = synchronized(keyThreads) { keyThreads.last() } + assertTrue(saver != Thread.currentThread()) + assertTrue(saver.name, saver.name.startsWith("DefaultDispatcher-worker")) + assertEquals(Phase.SignedIn(credentials), model.phase.value) + } + + @Test + fun aSessionThatCannotBeSavedLeavesTheAppSignedOut() { + val files = SessionFiles(File(folder.root, "missing")) + val vault = files.vault() + val model = model(vault) + + assertThrows(IOException::class.java) { runBlocking { model.completeSignIn(session) } } + + assertTrue(model.phase.value is Phase.SignedOut) + assertNull(vault.credentials) + } + + @Test + fun anEmailCodeSignsTheAppInAndSavesTheSession() = runBlocking { + val files = SessionFiles(folder.root) + val model = model(files.vault(), serve(::emailSignIn)) + + typeTheCode(model) + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + } + + @Test + fun anEmailCodeWhoseSessionCannotBeSavedStaysSignedOutWithTheMessage() = runBlocking { + val vault = SessionFiles(File(folder.root, "missing")).vault() + val model = model(vault, serve(::emailSignIn)) + + val signIn = typeTheCode(model) + + assertTrue(model.phase.value is Phase.SignedOut) + assertEquals("Cap couldn't save your session securely. Try again.", signIn.errorMessage) + assertNull(vault.credentials) + } + + @Test + fun anAuthCallbackSignsInWhileAProviderSignInIsPending() = runBlocking { + val files = SessionFiles(folder.root) + val model = model(files.vault()) + val url = checkNotNull(signIn(model).startProvider("google")) + + checkNotNull(model.open("$callback&state=${AuthCallback.state(url)}")).join() + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + } + + @Test + fun anAuthTabResultIsTrustedButALinkNeedsTheState() = runBlocking { + val files = SessionFiles(folder.root) + val model = model(files.vault()) + for (link in listOf(callback, "$callback&state=wrong-state-0123456789")) { + signIn(model).startProvider("google") + assertNull(model.open(link)) + assertNull(signIn(model).activity) + assertEquals( + "Google sign-in couldn't finish in this browser. Install or turn on Chrome, " + + "or sign in with your email.", + signIn(model).errorMessage, + ) + } + assertNull(files.store().load()) + + signIn(model).startProvider("google") + checkNotNull(model.finishAuthTab(callback)).join() + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + assertTrue(saved.keys().isEmpty()) + } + + @Test + fun aSavedProviderWithoutAStateIsNotRestored() { + saved["pendingProvider"] = "google" + saved["pendingProviderSince"] = wallClock + + val model = model(SessionFiles(folder.root).vault()) + model.open(callback) + + assertNull(signIn(model).activity) + assertTrue(model.phase.value is Phase.SignedOut) + assertTrue(saved.keys().isEmpty()) + } + + @Test + fun aProviderSignInSurvivesTheProcessBeingRecreated() = runBlocking { + val files = SessionFiles(folder.root) + val url = checkNotNull(signIn(model(files.vault())).startProvider("google")) + wallClock += 9.minutes.inWholeMilliseconds + + val recreated = model(files.vault()) + assertEquals(SignInModel.Activity.Provider("google"), signIn(recreated).activity) + checkNotNull(recreated.open("$callback&state=${AuthCallback.state(url)}")).join() + + assertEquals(Phase.SignedIn(credentials), recreated.phase.value) + assertEquals(credentials, files.store().load()) + assertTrue(saved.keys().isEmpty()) + } + + @Test + fun aProviderSignInOlderThanTenMinutesIsNotRestored() { + val files = SessionFiles(folder.root) + val url = checkNotNull(signIn(model(files.vault())).startProvider("google")) + wallClock += 10.minutes.inWholeMilliseconds + 1 + + val recreated = model(files.vault()) + recreated.open("$callback&state=${AuthCallback.state(url)}") + + assertNull(signIn(recreated).activity) + assertTrue(recreated.phase.value is Phase.SignedOut) + assertNull(files.store().load()) + assertTrue(saved.keys().isEmpty()) + } + + @Test + fun aProviderSignInStampedInTheFutureIsNotRestored() { + val files = SessionFiles(folder.root) + signIn(model(files.vault())).startProvider("google") + wallClock -= 1 + + val recreated = model(files.vault()) + + assertNull(signIn(recreated).activity) + assertTrue(saved.keys().isEmpty()) + } + + @Test + fun theSavedProviderIsClearedWhenTheSignInEnds() { + val model = model(SessionFiles(folder.root).vault()) + val signIn = signIn(model) + + val url = checkNotNull(signIn.startProvider("google")) + assertEquals("google", saved.get("pendingProvider")) + assertEquals(AuthCallback.state(url), saved.get("pendingProviderState")) + assertEquals(wallClock, saved.get("pendingProviderSince")) + signIn.cancelProvider() + assertTrue(saved.keys().isEmpty()) + + signIn.startProvider("apple") + signIn.failProvider() + assertTrue(saved.keys().isEmpty()) + + signIn.startProvider("google") + model.finishAuthTab("cap://auth?error_description=Access%20denied") + assertTrue(saved.keys().isEmpty()) + assertNull(model(SessionFiles(folder.root).vault()).let(::signIn).activity) + } + + @Test + fun anAuthCallbackNobodyAskedForIsIgnored() { + val files = SessionFiles(folder.root) + val model = model(files.vault()) + + model.open(callback) + + assertTrue(model.phase.value is Phase.SignedOut) + assertNull(files.store().load()) + } + + @Test + fun anAuthCallbackWhileSignedInDoesNotReplaceTheSession() { + val files = SessionFiles(folder.root) + files.store().save(credentials) + val model = model(files.vault()) + + model.open("cap://auth?api_key=1f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e&user_id=user_empty") + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + } + + @Test + fun aLinkThatIsNotAnAuthCallbackDoesNotEndAPendingSignIn() { + val model = model(SessionFiles(folder.root).vault()) + val signIn = (model.phase.value as Phase.SignedOut).signIn + signIn.startProvider("google") + + model.open("cap://s/abc123?api_key=${session.apiKey}&user_id=${session.userId}") + model.open("https://cap.so/auth?api_key=${session.apiKey}&user_id=${session.userId}") + + assertEquals(SignInModel.Activity.Provider("google"), signIn.activity) + assertTrue(model.phase.value is Phase.SignedOut) + } + + @Test + fun aShareLinkWaitsToBeOpenedWithItsTimeAndComment() { + val model = model(SessionFiles(folder.root).vault()) + + model.open("cap://s/abc123?t=30&comment=cmt_1") + + val link = checkNotNull(model.pendingShareLink) + assertEquals("abc123", link.id.rawValue) + assertEquals(30.0, checkNotNull(link.startTime), 0.0) + assertEquals("cmt_1", link.commentId) + } + + @Test + fun anAuthCallbackIsNotAShareLink() { + val model = model(SessionFiles(folder.root).vault()) + + model.open("cap://auth?api_key=${session.apiKey}&user_id=${session.userId}") + + assertNull(model.pendingShareLink) + } + + @Test + fun aSessionTheServerRejectsSignsOutWithTheNotice() = runBlocking { + val files = SessionFiles(folder.root) + files.store().save(credentials) + val vault = files.vault() + val api = api(vault, serve { json("{}", status = 401) }) + val model = model(vault, api) + + val failure = runCatching { api.bootstrap() }.exceptionOrNull() + + assertEquals(CapApiError.Unauthorized, (failure as CapApiException).error) + val phase = model.phase.value as Phase.SignedOut + assertEquals("Your session expired. Sign in again.", phase.notice) + assertEquals( + "Bearer ${session.apiKey}", + checkNotNull(server).requests.single().headers["authorization"], + ) + assertNull(vault.credentials) + assertNull(files.store().load()) + assertEquals(1, removals) + } + + @Test + fun aRejectionOfAnEarlierSessionLeavesTheCurrentOneAlone() { + val files = SessionFiles(folder.root) + files.store().save(credentials) + val model = model(files.vault()) + + rejectedSessions.trySend( + CredentialSnapshot("1f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_empty") + ) + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + assertEquals(0, removals) + } + + @Test + fun signingInAgainAfterARejectedSessionWorks() { + val files = SessionFiles(folder.root) + files.store().save(credentials) + val model = model(files.vault()) + rejectedSessions.trySend(credentials) + assertTrue(model.phase.value is Phase.SignedOut) + + runBlocking { model.completeSignIn(session) } + + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + } + + private fun signedIn(handler: (RecordedRequest) -> Reply): Pair { + val files = SessionFiles(folder.root) + files.store().save(credentials) + return model(files.vault(), serve(handler)) to files + } + + @Test + fun signingOutRevokesTheSessionAndForgetsIt() = runBlocking { + val (model, files) = signedIn { json("""{"success":true}""") } + + checkNotNull(model.signOut()).join() + removed.await() + + val request = checkNotNull(server).requests.single() + assertEquals("POST", request.method) + assertEquals("/api/mobile/session/revoke", request.path) + assertEquals("Bearer ${session.apiKey}", request.headers["authorization"]) + assertNull((model.phase.value as Phase.SignedOut).notice) + assertNull(files.store().load()) + assertFalse(model.isSigningOut) + assertEquals(1, removals) + } + + @Test + fun signingOutDoesNotDependOnTheServer() = runBlocking { + val (model, files) = signedIn { json("{}", status = 500) } + + checkNotNull(model.signOut()).join() + + assertTrue(model.phase.value is Phase.SignedOut) + assertNull(files.store().load()) + } + + @Test + fun signingOutOfASessionTheServerAlreadyRejectedShowsNoNotice() = runBlocking { + val (model, files) = signedIn { json("{}", status = 401) } + + checkNotNull(model.signOut()).join() + + assertNull((model.phase.value as Phase.SignedOut).notice) + assertNull(files.store().load()) + } + + @Test + fun aRevokeTheServerNeverAnswersIsGivenFourSeconds() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val (model, files) = + signedIn { + arrived.complete(Unit) + runBlocking { release.await() } + json("""{"success":true}""") + } + + val signingOut = checkNotNull(model.signOut()) + arrived.await() + assertTrue(model.isSigningOut) + assertNull(model.signOut()) + clock.advance(3999.milliseconds) + assertEquals(Phase.SignedIn(credentials), model.phase.value) + assertEquals(credentials, files.store().load()) + + clock.advance(1.milliseconds) + signingOut.join() + release.complete(Unit) + + assertTrue(model.phase.value is Phase.SignedOut) + assertNull(files.store().load()) + assertFalse(model.isSigningOut) + } + + @Test + fun signingOutWhileSignedOutDoesNothing() { + val model = model(SessionFiles(folder.root).vault(), serve { json("{}") }) + + assertNull(model.signOut()) + + assertTrue(checkNotNull(server).requests.isEmpty()) + assertEquals(0, removals) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CapActionsTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CapActionsTest.kt new file mode 100644 index 00000000000..864e0f546dc --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CapActionsTest.kt @@ -0,0 +1,701 @@ +package so.cap.mobile.app + +import androidx.compose.runtime.snapshots.Snapshot +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.builtins.serializer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapsPage +import so.cap.kit.SnapshotCache +import so.cap.mobile.app.ApiServer.Companion.json + +class CapActionsTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private val cache by lazy { SnapshotCache(folder.root) } + private val root = LibraryKey("org_cap", LibraryScope.Personal, folderId = null) + private val launch = root.copy(folderId = "folder_launch") + private val refused = CapApiError.Server(500).description + private var server: ApiServer? = null + + @After + fun stopTheServer() { + server?.close() + } + + private fun page(vararg ids: String) = json(Samples.page(ids.map { Samples.cap(it) })) + + private fun session(handler: (RecordedRequest) -> Reply?): SessionModel { + val started = ApiServer { request -> + handler(request) + ?: when (request.path.substringBefore('?')) { + "/api/mobile/bootstrap" -> json(Samples.bootstrap()) + "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + "/api/mobile/caps" -> page("a", "b", "c") + else -> json("{}", status = 404) + } + } + server = started + val api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + return SessionModel(api, cache, Samples.richie, clock.scope) + } + + private suspend fun SessionModel.loaded(key: LibraryKey = root): LibraryModel { + start()?.join() + return library(key).also { it.loadIfNeeded().join() } + } + + private fun sharing(id: String) = "/api/mobile/caps/$id/sharing" + + private fun isSharing(request: RecordedRequest) = request.path == sharing("b") + + private fun isDelete(request: RecordedRequest) = + request.method == "DELETE" && request.path == "/api/mobile/caps/b" + + private fun isList(request: RecordedRequest) = + request.method == "GET" && request.path.startsWith("/api/mobile/caps?") + + private fun count(matches: (RecordedRequest) -> Boolean) = + checkNotNull(server).requests.count(matches) + + private fun saved(isPublic: Boolean) = json(Samples.cap("b", isPublic = isPublic)) + + private fun LibraryModel.cap(id: String) = caps.first { it.id == id } + + private suspend fun savedPage() = + cache.read(CapsPage.serializer(), Samples.richie.userId, root.cacheKey) + + private suspend fun savedIds() = savedPage()?.caps?.map { it.id } + + private val LibraryModel.ids + get() = caps.map { it.id } + + private val LibraryModel.bIsPublic + get() = cap("b").isPublic + + private val SessionModel.toast + get() = toasts.current.value?.message + + @Test + fun makingACapPrivateShowsAtOnceAndThenShowsTheServersCap() = runBlocking { + val held = HeldReply(json(Samples.cap("b", isPublic = false, title = "From the server"))) + val session = session { if (isSharing(it)) held.answer() else null } + val library = session.loaded() + + val change = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + held.arrived.await() + assertEquals(listOf(true, false, true), library.caps.map { it.isPublic }) + assertEquals("Cap b", library.cap("b").title) + assertNull(session.toast) + + held.release.complete(Unit) + change.join() + val request = checkNotNull(server).requests.single(::isSharing) + assertEquals("PATCH", request.method) + assertEquals("""{"public":false}""", request.body) + assertEquals(listOf(true, false, true), library.caps.map { it.isPublic }) + assertEquals("Cap b", library.cap("b").title) + assertEquals("Only you and your team can view", session.toast) + } + + @Test + fun makingACapPublicSaysWhoCanView() = runBlocking { + var reply = Samples.cap("b") + val session = session { request -> + when { + isSharing(request) -> json(reply) + isList(request) -> json(Samples.page(listOf(Samples.cap("b", isPublic = false)))) + else -> null + } + } + val library = session.loaded() + + checkNotNull(session.setPublic(library.cap("b"), isPublic = true)).join() + assertEquals("""{"public":true}""", checkNotNull(server).requests.last().body) + assertEquals(true, library.bIsPublic) + assertEquals("Anyone with the link can view", session.toast) + + val restricted = ""","linkAccess":"restricted","linkRestricted":true}""" + reply = Samples.cap("b").dropLast(1) + restricted + checkNotNull(session.setPublic(library.cap("b"), isPublic = true)).join() + assertEquals("Only your organization's emails can view", session.toast) + + reply = Samples.cap("b", isPublic = false).dropLast(1) + restricted + checkNotNull(session.setPublic(library.cap("b"), isPublic = false)).join() + assertEquals("Only you and your team can view", session.toast) + } + + @Test + fun aChangeTheServerRefusesIsUndoneAndNothingElseMoves() = runBlocking { + val session = session { if (isSharing(it)) json("{}", status = 500) else null } + val library = session.loaded() + val before = library.caps + + checkNotNull(session.setPublic(library.cap("b"), isPublic = false)).join() + + assertEquals(before, library.caps) + assertEquals(3, library.total) + assertEquals(refused, session.toast) + } + + @Test + fun aChangeShowsInEveryLibraryThatHoldsTheCap() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + val session = session { if (isSharing(it)) held.answer() else null } + val library = session.loaded() + val inFolder = session.loaded(launch) + + val change = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + held.arrived.await() + assertEquals(listOf(false, false), listOf(library.bIsPublic, inFolder.bIsPublic)) + + held.release.complete(Unit) + change.join() + assertEquals(listOf(true, true), listOf(library.bIsPublic, inFolder.bIsPublic)) + } + + @Test + fun aPageThatArrivesWhileAChangeIsPendingKeepsTheChange() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + var listed = true + val session = session { request -> + when { + isSharing(request) -> held.answer() + isList(request) -> json(Samples.page(listOf(Samples.cap("b", isPublic = listed)))) + else -> null + } + } + val library = session.loaded() + listed = false + library.refresh().join() + + val change = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + held.arrived.await() + library.refresh().join() + assertEquals(true, library.bIsPublic) + + listed = true + library.refresh().join() + listed = false + library.refresh().join() + held.release.complete(Unit) + change.join() + assertEquals(false, library.bIsPublic) + } + + @Test + fun anOlderAnswerDoesNotOverwriteANewerOne() = runBlocking { + val first = HeldReply(saved(isPublic = false)) + val second = HeldReply(saved(isPublic = true)) + val session = session { request -> + if (!isSharing(request)) { + null + } else if (request.body.contains("false")) { + first.answer() + } else { + second.answer() + } + } + val library = session.loaded() + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + first.arrived.await() + val newer = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + library.refresh().join() + assertEquals(true, library.bIsPublic) + + first.release.complete(Unit) + older.join() + assertEquals(true, library.bIsPublic) + assertNull(session.toast) + + second.arrived.await() + second.release.complete(Unit) + newer.join() + assertEquals(true, library.bIsPublic) + assertEquals("Anyone with the link can view", session.toast) + } + + @Test + fun changesOfWhoCanViewReachTheServerInTheOrderTheyWereMade() = runBlocking { + val first = HeldReply(saved(isPublic = true)) + val second = HeldReply(saved(isPublic = false)) + val answered = CopyOnWriteArrayList() + val session = session { request -> + if (!isSharing(request)) { + null + } else { + val reply = if (request.body.contains("true")) first.answer() else second.answer() + answered += request.body + reply + } + } + val library = session.loaded() + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + first.arrived.await() + val newer = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + second.release.complete(Unit) + library.refresh().join() + first.release.complete(Unit) + older.join() + newer.join() + + assertEquals(listOf("""{"public":true}""", """{"public":false}"""), answered) + assertEquals(false, library.bIsPublic) + assertEquals("Only you and your team can view", session.toast) + } + + @Test + fun anOlderAnswerIsNotShownWhileANewerChangeIsPending() = runBlocking { + val second = HeldReply(json("{}", status = 500)) + val session = session { request -> + if (!isSharing(request)) { + null + } else if (request.body.contains("false")) { + saved(isPublic = false) + } else { + second.answer() + } + } + val library = session.loaded() + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + val newer = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + second.arrived.await() + older.join() + assertEquals(true, library.bIsPublic) + assertNull(session.toast) + + second.release.complete(Unit) + newer.join() + assertEquals(false, library.bIsPublic) + assertEquals(refused, session.toast) + } + + @Test + fun anOlderFailureDoesNotUndoANewerChange() = runBlocking { + val first = HeldReply(json("{}", status = 500)) + var changes = 0 + val session = session { request -> + if (!isSharing(request)) { + null + } else { + changes += 1 + if (changes == 1) first.answer() else saved(isPublic = changes == 2) + } + } + val library = session.loaded() + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + first.arrived.await() + val middle = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + val newest = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + first.release.complete(Unit) + older.join() + middle.join() + newest.join() + + assertEquals(false, library.bIsPublic) + assertEquals("Only you and your team can view", session.toast) + } + + @Test + fun anOlderAnswerIsShownOnceTheNewerChangeHasFailed() = runBlocking { + val first = HeldReply(json(Samples.cap("b", isPublic = false, title = "From the server"))) + val failure = HeldReply(json("{}", status = 500)) + val session = session { request -> + if (!isSharing(request)) { + null + } else if (request.body.contains("false")) { + first.answer() + } else { + failure.answer() + } + } + val library = session.loaded() + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + first.arrived.await() + val newer = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + assertEquals(true, library.bIsPublic) + + first.release.complete(Unit) + older.join() + assertEquals(true, library.bIsPublic) + assertNull(session.toast) + + failure.release.complete(Unit) + newer.join() + assertEquals(false, library.bIsPublic) + assertEquals("Cap b", library.cap("b").title) + assertEquals(refused, session.toast) + } + + @Test + fun anOlderFailureIsNotShownWhileANewerChangeIsPending() = runBlocking { + val second = HeldReply(json("{}", status = 500)) + val session = session { request -> + if (!isSharing(request)) { + null + } else if (request.body.contains("false")) { + json("{}", status = 500) + } else { + second.answer() + } + } + val library = session.loaded() + val before = library.caps + + val older = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + val newer = checkNotNull(session.setPublic(library.cap("b"), isPublic = true)) + second.arrived.await() + older.join() + assertNull(session.toast) + + second.release.complete(Unit) + newer.join() + assertEquals(before, library.caps) + assertEquals(refused, session.toast) + } + + @Test + fun aPageRequestedBeforeAChangeDoesNotUndoIt() = runBlocking { + val held = HeldReply(page("a", "b", "c")) + var lists = 0 + val session = session { request -> + when { + isSharing(request) -> saved(isPublic = false) + isList(request) -> { + lists += 1 + if (lists == 2) held.answer() else null + } + else -> null + } + } + val library = session.loaded() + + val refresh = library.refresh() + held.arrived.await() + checkNotNull(session.setPublic(library.cap("b"), isPublic = false)).join() + held.release.complete(Unit) + refresh.join() + assertEquals(listOf(true, false, true), library.caps.map { it.isPublic }) + + library.refresh().join() + assertEquals(listOf(true, true, true), library.caps.map { it.isPublic }) + } + + @Test + fun aPageRequestedWhileAChangeIsBeingSavedDoesNotUndoIt() = runBlocking { + val change = HeldReply(saved(isPublic = false)) + val list = HeldReply(page("a", "b", "c")) + var lists = 0 + val session = session { request -> + when { + isSharing(request) -> change.answer() + isList(request) -> { + lists += 1 + if (lists == 2) list.answer() else null + } + else -> null + } + } + val library = session.loaded() + + val changing = checkNotNull(session.setPublic(library.cap("b"), isPublic = false)) + change.arrived.await() + val refresh = library.refresh() + list.arrived.await() + change.release.complete(Unit) + changing.join() + list.release.complete(Unit) + refresh.join() + + assertEquals(listOf(true, false, true), library.caps.map { it.isPublic }) + } + + @Test + fun aCapWithAnIdThatIsNotACapIdIsLeftAlone() = runBlocking { + val session = session { null } + val library = session.loaded() + val odd = library.cap("b").copy(id = "not a cap") + + assertNull(session.setPublic(odd, isPublic = false)) + assertNull(session.delete(odd)) + assertEquals( + 1, + checkNotNull(server).requests.count { it.path.startsWith("/api/mobile/caps") }, + ) + } + + @Test + fun aCapIsRemovedOnlyOnceTheServerHasDeletedIt() = runBlocking { + val held = HeldReply(json("""{"success":true}""")) + val session = session { if (isDelete(it)) held.answer() else null } + val library = session.loaded() + + val delete = checkNotNull(session.delete(library.cap("b"))) + held.arrived.await() + assertEquals(listOf("a", "b", "c"), library.ids) + assertEquals(3, library.total) + assertNull(session.toast) + assertNull(session.delete(library.cap("b"))) + + held.release.complete(Unit) + delete.join() + assertEquals(listOf("a", "c"), library.ids) + assertEquals(2, library.total) + assertEquals("Cap deleted", session.toast) + assertEquals(1, count(::isDelete)) + } + + @Test + fun aDeletedCapIsGoneFromThePageSavedForTheNextLaunch() = runBlocking { + val held = HeldReply(page("a", "b", "c")) + val session = session { request -> + when { + isDelete(request) -> json("""{"success":true}""") + isList(request) && count(::isList) > 1 -> held.answer() + else -> null + } + } + val library = session.loaded() + assertEquals(listOf("a", "b", "c"), savedIds()) + + val refresh = library.refresh() + held.arrived.await() + checkNotNull(session.delete(library.cap("b"))).join() + assertEquals(listOf("a", "c"), savedIds()) + + held.release.complete(Unit) + refresh.join() + assertEquals(listOf("a", "c"), library.ids) + assertEquals(listOf("a", "c"), savedIds()) + assertEquals(2, savedPage()?.total) + } + + @Test + fun aLibraryOpenedWhileTheSavedPagesAreWrittenDoesNotBreakTheDelete() = runBlocking { + val held = HeldReply(json("""{"success":true}""")) + val session = session { if (isDelete(it)) held.answer() else null } + val library = session.loaded() + val inFolder = session.library(launch).also { it.loadIfNeeded().join() } + val hold = holdTheCache() + + val delete = checkNotNull(session.delete(library.cap("b"))) + held.arrived.await() + val removed = CompletableDeferred() + val observer = Snapshot.registerGlobalWriteObserver { removed.complete(Unit) } + held.release.complete(Unit) + removed.await() + observer.dispose() + session.library(launch.copy(folderId = "folder_other")) + hold.release() + delete.join() + + assertEquals(listOf("a", "c"), library.ids) + assertEquals(listOf("a", "c"), inFolder.ids) + assertEquals(listOf("a", "c"), savedIds()) + assertEquals( + listOf("a", "c"), + cache.read(CapsPage.serializer(), Samples.richie.userId, launch.cacheKey)?.caps?.map { + it.id + }, + ) + assertEquals("Cap deleted", session.toast) + } + + private suspend fun holdTheCache(): HeldCache { + cache.write(String.serializer(), "", Samples.richie.userId, "hold") + val file = folder.root.walk().single { it.name == "hold.json" } + check(file.delete()) + check(ProcessBuilder("mkfifo", file.path).start().waitFor() == 0) + val reading = + clock.scope.launch { cache.read(String.serializer(), Samples.richie.userId, "hold") } + return HeldCache(file, reading) + } + + private class HeldCache(private val file: File, private val reading: Job) { + suspend fun release() { + file.writeText("\"\"") + reading.join() + } + } + + @Test + fun aChangeOfWhoCanViewIsSavedForTheNextLaunch() = runBlocking { + val held = HeldReply(page("a", "b", "c")) + val session = session { request -> + when { + isSharing(request) && request.body.contains("false") -> saved(isPublic = false) + isSharing(request) -> json("{}", status = 500) + isList(request) && count(::isList) > 1 -> held.answer() + else -> null + } + } + val library = session.loaded() + + val refresh = library.refresh() + held.arrived.await() + checkNotNull(session.setPublic(library.cap("b"), isPublic = false)).join() + assertEquals(false, savedPage()?.caps?.first { it.id == "b" }?.isPublic) + + held.release.complete(Unit) + refresh.join() + assertEquals(false, library.bIsPublic) + assertEquals(false, savedPage()?.caps?.first { it.id == "b" }?.isPublic) + + checkNotNull(session.setPublic(library.cap("b"), isPublic = true)).join() + assertEquals(false, library.bIsPublic) + assertEquals(false, savedPage()?.caps?.first { it.id == "b" }?.isPublic) + } + + @Test + fun aDeleteTheServerRefusesLeavesTheCapAndCanBeTriedAgain() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + val session = session { if (isDelete(it)) held.answer() else null } + val library = session.loaded() + val before = library.caps + + val delete = checkNotNull(session.delete(library.cap("b"))) + held.arrived.await() + library.refresh().join() + assertEquals(before, library.caps) + held.release.complete(Unit) + delete.join() + + assertEquals(before, library.caps) + assertEquals(3, library.total) + assertEquals(refused, session.toast) + checkNotNull(session.delete(library.cap("b"))).join() + assertEquals(2, count(::isDelete)) + } + + @Test + fun aDeleteAnswersWhetherTheServerDeletedTheCap() = runBlocking { + var reply = json("{}", status = 500) + val session = session { if (isDelete(it)) reply else null } + val library = session.loaded() + + assertEquals(false, checkNotNull(session.delete(library.cap("b"))).await()) + reply = json("""{"success":true}""") + assertEquals(true, checkNotNull(session.delete(library.cap("b"))).await()) + } + + @Test + fun aLaterPageRequestedBeforeAChangeDoesNotUndoIt() = runBlocking { + val held = HeldReply(json(Samples.page(listOf(Samples.cap("b")), page = 2, total = 2))) + val session = session { request -> + when { + isSharing(request) -> saved(isPublic = false) + isList(request) && request.path.contains("folderId") -> page("b") + isList(request) && request.path.contains("page=2") -> held.answer() + isList(request) -> + json(Samples.page(listOf(Samples.cap("a")), total = 2, hasMore = true)) + else -> null + } + } + val library = session.loaded() + val inFolder = session.loaded(launch) + + val more = checkNotNull(library.loadMoreIfNeeded(library.caps.last())) + held.arrived.await() + checkNotNull(session.setPublic(inFolder.cap("b"), isPublic = false)).join() + held.release.complete(Unit) + more.join() + + assertEquals(listOf(true, false), library.caps.map { it.isPublic }) + } + + @Test + fun aDeletedCapLeavesEveryLibraryThatHoldsIt() = runBlocking { + val session = session { request -> + when { + isDelete(request) -> json("""{"success":true}""") + isList(request) && request.path.contains("spaceId") -> page("a", "c") + else -> null + } + } + val library = session.loaded() + val inFolder = session.loaded(launch) + val inSpace = session.loaded(root.copy(scope = LibraryScope.Space("space_design"))) + + checkNotNull(session.delete(library.cap("b"))).join() + + assertEquals(listOf("a", "c"), library.ids) + assertEquals(listOf("a", "c"), inFolder.ids) + assertEquals(listOf("a", "c"), inSpace.ids) + assertEquals(listOf(2, 2, 2), listOf(library.total, inFolder.total, inSpace.total)) + } + + @Test + fun aPageRequestedBeforeADeleteDoesNotBringTheCapBack() = runBlocking { + val held = HeldReply(page("a", "b", "c")) + var lists = 0 + val session = session { request -> + when { + isDelete(request) -> json("""{"success":true}""") + isList(request) -> { + lists += 1 + if (lists == 2) held.answer() else null + } + else -> null + } + } + val library = session.loaded() + + val refresh = library.refresh() + held.arrived.await() + checkNotNull(session.delete(library.cap("b"))).join() + held.release.complete(Unit) + refresh.join() + + assertEquals(listOf("a", "c"), library.ids) + assertEquals(2, library.total) + } + + @Test + fun aLaterPageLeavesOutADeletedCap() = runBlocking { + val session = session { request -> + when { + isDelete(request) -> json("""{"success":true}""") + isList(request) && request.path.contains("page=2") -> + json( + Samples.page( + listOf(Samples.cap("b"), Samples.cap("d")), + page = 2, + total = 4, + ) + ) + isList(request) -> + json( + Samples.page( + listOf(Samples.cap("a"), Samples.cap("c")), + total = 4, + hasMore = true, + ) + ) + else -> null + } + } + val library = session.loaded() + checkNotNull(session.delete(Samples.decodedCap("b"))).join() + + checkNotNull(library.loadMoreIfNeeded(library.caps.last())).join() + + assertEquals(listOf("a", "c", "d"), library.ids) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CredentialVaultTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CredentialVaultTest.kt new file mode 100644 index 00000000000..4c66481ed36 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/CredentialVaultTest.kt @@ -0,0 +1,172 @@ +package so.cap.mobile.app + +import java.io.File +import java.io.IOException +import java.security.InvalidKeyException +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CredentialSnapshot + +class CredentialVaultTest { + @get:Rule val folder = TemporaryFolder() + + private val key = newKey() + private val credentials = + CredentialSnapshot("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie") + + private val file: File + get() = File(folder.root, "session") + + private fun newKey(): SecretKey = + KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + + private fun store(origin: String = "https://cap.so", key: SecretKey = this.key) = + CredentialStore(file, origin) { key } + + private fun contains(haystack: ByteArray, needle: String): Boolean = + String(haystack, Charsets.ISO_8859_1).contains(needle) + + @Test + fun clearOnlyRemovesMatchingCredentials() { + val store = store() + store.save(credentials) + val vault = CredentialVault(store) + val newer = CredentialSnapshot("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "user_123") + vault.replace(newer) + + assertFalse(vault.clear(ifMatching = credentials)) + assertEquals(newer, vault.credentials) + assertEquals(newer, store.load()) + + assertTrue(vault.clear(ifMatching = newer)) + assertNull(vault.credentials) + assertNull(store.load()) + assertFalse(file.exists()) + } + + @Test + fun aMissingSessionStaysSignedOut() { + val vault = CredentialVault(store()) + assertNull(vault.credentials) + + store().save(credentials) + + assertNull(vault.credentials) + } + + @Test + fun aSavedSessionIsReadByANewVault() { + CredentialVault(store()).replace(credentials) + + assertEquals(credentials, CredentialVault(store()).credentials) + } + + @Test + fun clearWithNothingToMatchAlwaysClears() { + val vault = CredentialVault(store()) + vault.replace(credentials) + + assertTrue(vault.clear()) + + assertNull(vault.credentials) + assertNull(store().load()) + } + + @Test + fun theFileOnDiskHoldsNeitherTheKeyNorTheUser() { + store().save(credentials) + + val bytes = file.readBytes() + assertFalse(contains(bytes, credentials.apiKey)) + assertFalse(contains(bytes, credentials.userId)) + assertFalse(contains(bytes, "apiKey")) + assertEquals(listOf("session"), folder.root.list()?.toList()) + } + + @Test + fun savingTheSameSessionTwiceWritesDifferentBytes() { + store().save(credentials) + val first = file.readBytes() + store().save(credentials) + + assertNotEquals(first.toList(), file.readBytes().toList()) + assertEquals(credentials, store().load()) + } + + @Test + fun aSessionSavedForAnotherServerIsNotRead() { + store(origin = "https://cap.so").save(credentials) + + assertNull(store(origin = "http://localhost:4310").load()) + assertEquals(credentials, store(origin = "https://cap.so").load()) + } + + @Test + fun aChangedFileReadsAsNoSession() { + store().save(credentials) + val bytes = file.readBytes() + bytes[bytes.lastIndex] = (bytes.last().toInt() xor 1).toByte() + file.writeBytes(bytes) + + assertNull(store().load()) + } + + @Test + fun aFileSealedWithAnotherKeyReadsAsNoSession() { + store(key = newKey()).save(credentials) + + assertNull(store().load()) + } + + @Test + fun aFileTooShortToHoldASessionReadsAsNoSession() { + file.writeBytes(ByteArray(12)) + + assertNull(store().load()) + } + + @Test + fun anImplausibleSavedSessionIsNotRead() { + store().save(CredentialSnapshot("short", "user_richie")) + assertNull(store().load()) + + store().save(CredentialSnapshot(credentials.apiKey, "not a user id")) + assertNull(store().load()) + } + + @Test + fun aKeyThatCanNoLongerBeUsedIsReplacedOnSave() { + var replaced = false + val store = + CredentialStore(file, "https://cap.so") { fresh -> + if (fresh) replaced = true + if (!replaced) throw InvalidKeyException("This key can no longer be used") + key + } + + CredentialVault(store).replace(credentials) + + assertTrue(replaced) + assertEquals(credentials, CredentialVault(store).credentials) + } + + @Test + fun aSaveThatFailsWithAFreshKeyIsAnError() { + val store = + CredentialStore(file, "https://cap.so") { + throw InvalidKeyException("This key can no longer be used") + } + + assertThrows(IOException::class.java) { store.save(credentials) } + assertFalse(file.exists()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ImageRequestInterceptorTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ImageRequestInterceptorTest.kt new file mode 100644 index 00000000000..c2216c951ad --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ImageRequestInterceptorTest.kt @@ -0,0 +1,248 @@ +package so.cap.mobile.app + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.util.zip.GZIPOutputStream +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapEnvironment +import so.cap.kit.CapId +import so.cap.kit.CredentialSnapshot + +class ImageRequestInterceptorTest { + @get:Rule val temporaryFolder = TemporaryFolder() + + private val image = ByteArray(64) { it.toByte() } + private val signedIn = CredentialSnapshot("cap-api-key", "user_richie") + private val servers = mutableListOf() + private lateinit var certificate: LoopbackCertificate + + @Before + fun createCertificate() { + certificate = LoopbackCertificate(temporaryFolder.root) + } + + @After + fun closeServers() { + servers.forEach(LoopbackServer::close) + } + + private fun http(handler: (RecordedRequest) -> Reply = { Reply(body = image) }) = + LoopbackServer.http(handler).also(servers::add) + + private fun https(handler: (RecordedRequest) -> Reply = { Reply(body = image) }) = + LoopbackServer.https(certificate, handler).also(servers::add) + + private fun environment(cap: LoopbackServer) = + checkNotNull(CapEnvironment.parse(cap.origin, allowInsecureLocalhost = true)) + + private fun api(cap: LoopbackServer) = + CapApi(environment(cap), "Cap-Android/test", credentials = { signedIn }) + + private fun client( + cap: LoopbackServer, + maxDownloadBytes: Long = ImageRequestInterceptor.MAX_DOWNLOAD_BYTES, + api: CapApi = api(cap), + ): OkHttpClient { + return imageHttpClient( + ImageRequestInterceptor(environment(cap), maxDownloadBytes, api::mediaHeaders) + ) + .newBuilder() + .sslSocketFactory(certificate.context.socketFactory, certificate.trustManager) + .build() + } + + private fun get(client: OkHttpClient, url: String, videoAccess: String? = null): ByteArray { + val request = Request.Builder().url(url) + if (videoAccess != null) request.header("X-Cap-Video-Access", videoAccess) + return client.newCall(request.build()).execute().use { response -> + assertEquals(200, response.code) + response.body.bytes() + } + } + + @Test + fun aRequestToTheCapOriginCarriesTheBearerHeaderAndAsksForImages() { + val cap = http() + + val body = get(client(cap), "${cap.origin}/api/mobile/caps/abc/thumbnail") + + assertTrue(image.contentEquals(body)) + val request = cap.requests.single() + assertEquals("/api/mobile/caps/abc/thumbnail", request.path) + assertEquals("Bearer cap-api-key", request.headers["authorization"]) + assertEquals("image/*", request.headers["accept"]) + } + + @Test + fun aThumbnailOfAnUnlockedCapCarriesItsVideoAccessToken() = runBlocking { + val cap = http { request -> + if (request.path.endsWith("/unlock")) { + Reply( + headers = mapOf("Content-Type" to "application/json"), + body = + """{"accessToken":"unlocked-token","expiresAt":"2099-01-01T00:00:00Z"}""" + .toByteArray(), + ) + } else { + Reply(body = image) + } + } + val api = api(cap) + api.unlockCap(checkNotNull(CapId.parse("cap_locked")), "secret") + + get(client(cap, api = api), "${cap.origin}/api/mobile/caps/cap_locked/thumbnail") + + val request = cap.requests.last() + assertEquals("Bearer cap-api-key", request.headers["authorization"]) + assertEquals("unlocked-token", request.headers["x-cap-video-access"]) + } + + @Test + fun aRequestToANonCapHostCarriesNoAuthorizationHeader() { + val cap = http() + val storage = https() + + get(client(cap), "${storage.origin}/avatar.png", videoAccess = "unlocked") + + val request = storage.requests.single() + assertFalse("authorization" in request.headers) + assertFalse("x-cap-video-access" in request.headers) + assertEquals("image/*", request.headers["accept"]) + assertTrue(cap.requests.isEmpty()) + } + + @Test + fun bothAuthHeadersAreStrippedOnACrossOriginRedirect() { + val storage = https() + val cap = http { + Reply(status = 302, headers = mapOf("Location" to "${storage.origin}/signed.jpg")) + } + + val body = + get( + client(cap), + "${cap.origin}/api/mobile/caps/abc/thumbnail", + videoAccess = "unlocked", + ) + + assertTrue(image.contentEquals(body)) + val first = cap.requests.single() + assertEquals("Bearer cap-api-key", first.headers["authorization"]) + assertEquals("unlocked", first.headers["x-cap-video-access"]) + val redirected = storage.requests.single() + assertEquals("/signed.jpg", redirected.path) + assertFalse("authorization" in redirected.headers) + assertFalse("x-cap-video-access" in redirected.headers) + } + + @Test + fun aSameOriginRedirectKeepsBothAuthHeaders() { + val cap = http { request -> + if (request.path == "/first") { + Reply(status = 302, headers = mapOf("Location" to "/second")) + } else { + Reply(body = image) + } + } + + get(client(cap), "${cap.origin}/first", videoAccess = "unlocked") + + assertEquals(listOf("/first", "/second"), cap.requests.map { it.path }) + val second = cap.requests.last() + assertEquals("Bearer cap-api-key", second.headers["authorization"]) + assertEquals("unlocked", second.headers["x-cap-video-access"]) + } + + @Test + fun aRedirectToAnInsecureHostIsRefused() { + val insecure = http() + val cap = http { + Reply(status = 302, headers = mapOf("Location" to "${insecure.origin}/image.jpg")) + } + + assertThrows(IOException::class.java) { get(client(cap), "${cap.origin}/thumbnail") } + + assertEquals(1, cap.requests.size) + assertTrue(insecure.requests.isEmpty()) + } + + @Test + fun anInsecureRequestToANonCapHostIsRefused() { + val cap = http() + val insecure = http() + + assertThrows(IOException::class.java) { get(client(cap), "${insecure.origin}/image.jpg") } + + assertTrue(insecure.requests.isEmpty()) + } + + @Test + fun aDeclaredLengthOverTheLimitFails() { + val cap = http() + + assertThrows(IOException::class.java) { + get(client(cap, maxDownloadBytes = 63), "${cap.origin}/thumbnail") + } + } + + @Test + fun aStreamedBodyOverTheLimitFails() { + val cap = http { Reply(body = image, declaresLength = false) } + + assertThrows(IOException::class.java) { + get(client(cap, maxDownloadBytes = 63), "${cap.origin}/thumbnail") + } + } + + @Test + fun aBodyAtTheLimitLoads() { + val cap = http { Reply(body = image, declaresLength = false) } + + val body = get(client(cap, maxDownloadBytes = 64), "${cap.origin}/thumbnail") + + assertTrue(image.contentEquals(body)) + assertNull(cap.requests.single().headers["x-cap-video-access"]) + } + + @Test + fun aCompressedBodyThatExpandsOverTheLimitFails() { + val compressed = gzip(ByteArray(4096)) + val cap = http { Reply(headers = mapOf("Content-Encoding" to "gzip"), body = compressed) } + + assertTrue(compressed.size < 64) + assertThrows(IOException::class.java) { + get(client(cap, maxDownloadBytes = 64), "${cap.origin}/thumbnail") + } + } + + @Test + fun aCompressedBodyIsMeasuredExpanded() { + val compressed = gzip(image) + val cap = http { Reply(headers = mapOf("Content-Encoding" to "gzip"), body = compressed) } + + val body = get(client(cap, maxDownloadBytes = 64), "${cap.origin}/thumbnail") + + assertTrue(compressed.size > 64) + assertTrue(image.contentEquals(body)) + assertEquals("gzip", cap.requests.single().headers["accept-encoding"]) + } + + private fun gzip(bytes: ByteArray): ByteArray { + val output = ByteArrayOutputStream() + GZIPOutputStream(output).use { it.write(bytes) } + return output.toByteArray() + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LibraryModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LibraryModelTest.kt new file mode 100644 index 00000000000..358ec62d453 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LibraryModelTest.kt @@ -0,0 +1,1074 @@ +package so.cap.mobile.app + +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapJson +import so.cap.kit.CapsPage +import so.cap.kit.SnapshotCache +import so.cap.kit.UploadPhase +import so.cap.mobile.app.ApiServer.Companion.json +import so.cap.mobile.app.LibraryModel.Status + +class LibraryModelTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private val cache by lazy { SnapshotCache(folder.root) } + private val toasts = ToastCenter(clock.scope) + private val root = LibraryKey("org_cap", LibraryScope.Personal, folderId = null) + private var server: ApiServer? = null + + @After + fun stopTheServer() { + server?.close() + } + + private fun model(key: LibraryKey = root, handler: (RecordedRequest) -> Reply): LibraryModel { + val started = ApiServer(handler) + server = started + val api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + return LibraryModel( + key, + api, + cache, + Samples.richie.userId, + toasts, + clock.scope, + clock.scheduler.timeSource, + ) + } + + private fun page(vararg ids: String, folders: List = emptyList()) = + json(Samples.page(ids.map { Samples.cap(it) }, folders)) + + private suspend fun remember(vararg ids: String, key: LibraryKey = root) = + cache.write( + CapsPage.serializer(), + CapJson.json.decodeFromString( + CapsPage.serializer(), + Samples.page(ids.map { Samples.cap(it) }), + ), + Samples.richie.userId, + key.cacheKey, + ) + + private suspend fun saved(key: LibraryKey = root) = + cache.read(CapsPage.serializer(), Samples.richie.userId, key.cacheKey)?.caps?.map { it.id } + + private val LibraryModel.ids + get() = caps.map { it.id } + + private fun listRequests() = checkNotNull(server).count("GET", "/api/mobile/caps") + + private class Held(private val reply: Reply) { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + + fun answer(): Reply { + arrived.complete(Unit) + runBlocking { release.await() } + return reply + } + } + + @Test + fun theFirstLoadShowsLoadingAndThenTheFirstPage() = runBlocking { + val held = Held(page("a", "b", folders = listOf(Samples.folder("f1")))) + val model = model { held.answer() } + assertEquals(Status.Idle, model.status) + + val load = model.loadIfNeeded() + held.arrived.await() + assertEquals(Status.Loading, model.status) + assertTrue(model.isEmpty) + + held.release.complete(Unit) + load.join() + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("a", "b"), model.ids) + assertEquals(listOf("f1"), model.folders.map { it.id }) + assertEquals(2, model.total) + val request = checkNotNull(server).requests.single() + assertEquals("GET", request.method) + assertEquals("/api/mobile/caps?page=1&limit=30", request.path) + } + + @Test + fun theRequestNamesTheSpaceAndTheFolder() = runBlocking { + val key = LibraryKey("org_cap", LibraryScope.Space("space_design"), "folder_launch") + val model = model(key) { page("a") } + + model.loadIfNeeded().join() + + assertEquals( + "/api/mobile/caps?folderId=folder_launch&spaceId=space_design&page=1&limit=30", + checkNotNull(server).requests.single().path, + ) + } + + @Test + fun aLibraryInsideAFolderKeepsNoFolders() = runBlocking { + val key = LibraryKey("org_cap", LibraryScope.Personal, "folder_launch") + val model = model(key) { page("a", folders = listOf(Samples.folder("f1"))) } + + model.loadIfNeeded().join() + + assertEquals(listOf("a"), model.ids) + assertTrue(model.folders.isEmpty()) + } + + @Test + fun sortsOnlyWhenTheWholeCollectionIsLoaded() = runBlocking { + val model = model { + if (listRequests() == 1) { + json( + Samples.page( + listOf( + Samples.cap("z"), + Samples.cap("a"), + Samples.cap("m"), + ), + hasMore = true, + ) + ) + } else { + page("z", "a", "m") + } + } + model.loadIfNeeded().join() + + assertEquals(listOf(LibrarySort.NEWEST), model.availableSorts) + assertEquals(false, model.selectSort(LibrarySort.NAME)) + + model.loadMoreIfNeeded(model.caps.last())?.join() + assertEquals(LibrarySort.entries, model.availableSorts) + assertEquals(true, model.selectSort(LibrarySort.NAME)) + assertEquals(listOf("a", "m", "z"), model.ids) + } + + @Test + fun refreshingAnIncompleteCollectionReturnsToNewestOrder() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + pageOf(31..45, page = 2, total = 45, hasMore = false) + } + } + model.loadIfNeeded().join() + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + assertEquals(true, model.selectSort(LibrarySort.OLDEST)) + + model.refresh().join() + + assertEquals(LibrarySort.NEWEST, model.sort) + assertEquals(ids(1..30), model.ids) + } + + @Test + fun offlineSavedCapsAreOnlyClaimedWhenASnapshotExists() = runBlocking { + val model = model { page("a") } + model.loadIfNeeded().join() + assertEquals(false, model.showingOfflineCache) + + checkNotNull(server).close() + model.refresh().join() + + assertEquals(true, model.showingOfflineCache) + } + + @Test + fun theCacheKeyNamesTheOrganisationTheScopeAndTheFolder() { + assertEquals("caps-org_cap-personal-root", root.cacheKey) + assertEquals( + "caps-org_cap-space_design-folder_launch", + LibraryKey("org_cap", LibraryScope.Space("space_design"), "folder_launch").cacheKey, + ) + } + + @Test + fun theCachedPageIsShownBeforeTheServerAnswers() = runBlocking { + remember("cached") + val held = Held(page("fresh")) + val model = model { held.answer() } + + val load = model.loadIfNeeded() + held.arrived.await() + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("cached"), model.ids) + + held.release.complete(Unit) + load.join() + assertEquals(listOf("fresh"), model.ids) + } + + @Test + fun theCacheOfAnotherLibraryIsNotShown() = runBlocking { + remember("cached", key = LibraryKey("org_cap", LibraryScope.Personal, "folder_launch")) + val held = Held(page("fresh")) + val model = model { held.answer() } + + val load = model.loadIfNeeded() + held.arrived.await() + assertTrue(model.isEmpty) + assertEquals(Status.Loading, model.status) + + held.release.complete(Unit) + load.join() + } + + @Test + fun theFirstPageIsSavedForTheNextLaunch() = runBlocking { + val model = model { page("a", "b") } + + model.loadIfNeeded().join() + + assertEquals(listOf("a", "b"), saved()) + } + + @Test + fun aReplyToAnEarlierRefreshIsDiscarded() = runBlocking { + val earlier = Held(page("old")) + val model = model { if (listRequests() == 1) earlier.answer() else page("new") } + + val first = model.refresh() + earlier.arrived.await() + model.refresh().join() + assertEquals(listOf("new"), model.ids) + + earlier.release.complete(Unit) + first.join() + assertEquals(listOf("new"), model.ids) + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("new"), saved()) + } + + @Test + fun aFailureOfAnEarlierRefreshIsDiscarded() = runBlocking { + val earlier = Held(json("{}", status = 500)) + val model = model { if (listRequests() == 1) earlier.answer() else page() } + + val first = model.refresh() + earlier.arrived.await() + model.refresh().join() + assertEquals(Status.Loaded, model.status) + + earlier.release.complete(Unit) + first.join() + assertEquals(Status.Loaded, model.status) + assertNull(toasts.current.value) + } + + @Test + fun aFirstLoadThatFailsIsAnErrorAndCanBeTriedAgain() = runBlocking { + var status = 500 + val model = model { json(Samples.page(listOf(Samples.cap("a"))), status) } + + model.loadIfNeeded().join() + assertEquals(Status.Failed(CapApiError.Server(500)), model.status) + assertNull(toasts.current.value) + + status = 200 + model.refresh().join() + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("a"), model.ids) + } + + @Test + fun aRefreshThatFailsKeepsTheListAndShowsAToast() = runBlocking { + var status = 200 + val model = model { json(Samples.page(listOf(Samples.cap("a"))), status) } + model.loadIfNeeded().join() + + status = 500 + model.refresh().join() + + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("a"), model.ids) + val toast = checkNotNull(toasts.current.value) + assertEquals("Cap is having trouble right now. Try again shortly.", toast.message) + assertEquals(Toast.Style.Error, toast.style) + } + + @Test + fun theCachedListStaysWhenTheServerCannotBeReached() = runBlocking { + remember("cached") + val model = model { page("fresh") } + checkNotNull(server).close() + + model.loadIfNeeded().join() + + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("cached"), model.ids) + assertEquals(true, model.showingOfflineCache) + assertEquals( + "You're offline. Check your connection and try again.", + toasts.current.value?.message, + ) + } + + @Test + fun withNoCacheAnUnreachableServerIsAnError() = runBlocking { + val model = model { page("fresh") } + checkNotNull(server).close() + + model.loadIfNeeded().join() + + assertEquals(Status.Failed(CapApiError.Offline), model.status) + } + + @Test + fun aLibraryRefreshedInTheLastTwentySecondsIsNotLoadedAgain() = runBlocking { + val model = model { page("a") } + model.loadIfNeeded().join() + + clock.advance(20.seconds - 1.milliseconds) + model.loadIfNeeded().join() + assertEquals(1, listRequests()) + + clock.advance(1.milliseconds) + model.loadIfNeeded().join() + assertEquals(2, listRequests()) + } + + @Test + fun aLibraryWhoseLastRefreshFailedIsLoadedAgainStraightAway() = runBlocking { + var status = 200 + val model = model { json(Samples.page(listOf(Samples.cap("a"))), status) } + model.loadIfNeeded().join() + clock.advance(20.seconds) + status = 500 + model.loadIfNeeded().join() + assertEquals(2, listRequests()) + + status = 200 + model.loadIfNeeded().join() + + assertEquals(3, listRequests()) + } + + @Test + fun refreshingAnEmptyLibraryShowsLoadingAgain() = runBlocking { + val later = Held(page("a")) + val model = model { if (listRequests() == 1) page() else later.answer() } + model.loadIfNeeded().join() + assertEquals(Status.Loaded, model.status) + + val refresh = model.refresh() + later.arrived.await() + assertEquals(Status.Loading, model.status) + + later.release.complete(Unit) + refresh.join() + assertEquals(Status.Loaded, model.status) + } + + @Test + fun refreshingAListOnScreenKeepsItLoaded() = runBlocking { + val later = Held(page("b")) + val model = model { if (listRequests() == 1) page("a") else later.answer() } + model.loadIfNeeded().join() + + val refresh = model.refresh() + later.arrived.await() + assertEquals(Status.Loaded, model.status) + assertEquals(listOf("a"), model.ids) + + later.release.complete(Unit) + refresh.join() + assertEquals(listOf("b"), model.ids) + } + + private fun ids(range: IntRange) = range.map { "c$it" } + + private fun pageOf( + range: IntRange, + page: Int, + total: Int, + hasMore: Boolean, + extra: List = emptyList(), + ) = + json( + Samples.page( + (extra + ids(range)).map { Samples.cap(it) }, + emptyList(), + page, + total, + hasMore, + ) + ) + + private fun pageNumber(request: RecordedRequest) = + request.path.substringAfter("page=").substringBefore('&').toInt() + + @Test + fun reachingTheLastSixCapsLoadsTheNextPage() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + pageOf(31..45, page = 2, total = 45, hasMore = false) + } + } + model.loadIfNeeded().join() + assertTrue(model.hasMore) + + assertNull(model.loadMoreIfNeeded(model.caps[23])) + assertEquals(1, listRequests()) + + checkNotNull(model.loadMoreIfNeeded(model.caps[24])).join() + + assertEquals("/api/mobile/caps?page=2&limit=30", checkNotNull(server).requests.last().path) + assertEquals(ids(1..45), model.ids) + assertEquals(45, model.total) + assertEquals(false, model.hasMore) + assertEquals(false, model.isLoadingMore) + assertNull(model.loadMoreIfNeeded(model.caps.last())) + assertEquals(2, listRequests()) + assertEquals(ids(1..30), saved()) + } + + @Test + fun aCapThatIsNotInTheListLoadsNothing() = runBlocking { + val model = model { pageOf(1..30, page = 1, total = 45, hasMore = true) } + model.loadIfNeeded().join() + val stranger = model.caps.last().copy(id = "stranger") + + assertNull(model.loadMoreIfNeeded(stranger)) + assertEquals(1, listRequests()) + } + + @Test + fun onlyOnePageIsRequestedAtATime() = runBlocking { + val held = Held(pageOf(31..45, page = 2, total = 45, hasMore = false)) + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + held.answer() + } + } + model.loadIfNeeded().join() + + val more = checkNotNull(model.loadMoreIfNeeded(model.caps.last())) + held.arrived.await() + assertTrue(model.isLoadingMore) + assertNull(model.loadMoreIfNeeded(model.caps.last())) + + held.release.complete(Unit) + more.join() + assertEquals(2, listRequests()) + assertEquals(false, model.isLoadingMore) + } + + @Test + fun capsAlreadyInTheListAreNotAddedTwice() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 32, hasMore = true) + } else { + pageOf(31..32, page = 2, total = 33, hasMore = false, extra = listOf("c29", "c30")) + } + } + model.loadIfNeeded().join() + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertEquals(ids(1..32), model.ids) + assertEquals(33, model.total) + } + + @Test + fun aRefreshStartsThePagingAgain() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 90, hasMore = true) + } else { + pageOf(31..60, page = 2, total = 90, hasMore = true) + } + } + model.loadIfNeeded().join() + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + model.refresh().join() + assertEquals(ids(1..30), model.ids) + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertEquals(listOf(1, 2, 1, 2), checkNotNull(server).requests.map(::pageNumber)) + assertEquals(ids(1..60), model.ids) + } + + @Test + fun anEmptyPageWithMoreToComeLoadsTheNextOne() = runBlocking { + val model = model { request -> + when (pageNumber(request)) { + 1 -> pageOf(1..30, page = 1, total = 90, hasMore = true) + 2 -> pageOf(IntRange.EMPTY, page = 2, total = 90, hasMore = true) + else -> pageOf(61..90, page = 3, total = 90, hasMore = false) + } + } + model.loadIfNeeded().join() + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertEquals(listOf(1, 2, 3), checkNotNull(server).requests.map(::pageNumber)) + assertEquals(ids(1..30) + ids(61..90), model.ids) + assertEquals(false, model.hasMore) + } + + @Test + fun anEmptyFirstPageWithMoreToComeLoadsTheNextOne() = runBlocking { + val model = model { request -> + when (pageNumber(request)) { + 1 -> pageOf(IntRange.EMPTY, page = 1, total = 60, hasMore = true) + else -> pageOf(31..60, page = 2, total = 60, hasMore = false) + } + } + + model.loadIfNeeded().join() + + assertEquals(listOf(1, 2), checkNotNull(server).requests.map(::pageNumber)) + assertEquals(ids(31..60), model.ids) + assertEquals(false, model.hasMore) + assertEquals(false, model.isLoadingMore) + } + + @Test + fun anEmptyPageThatDoesNotMoveOnEndsThePaging() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + pageOf(IntRange.EMPTY, page = 2, total = 45, hasMore = true) + } + } + model.loadIfNeeded().join() + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertEquals(listOf(1, 2, 3), checkNotNull(server).requests.map(::pageNumber)) + assertEquals(false, model.hasMore) + assertEquals(ids(1..30), model.ids) + } + + @Test + fun theNextRequestFollowsTheServersPageNumber() = runBlocking { + val model = model { request -> + when (val number = pageNumber(request)) { + 1 -> pageOf(1..30, page = 1, total = 90, hasMore = true) + else -> + pageOf( + (number - 1) * 30 + 1..number * 30, + page = number, + total = 90, + hasMore = number < 3, + ) + } + } + model.loadIfNeeded().join() + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + assertTrue(model.hasMore) + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertEquals(listOf(1, 2, 3), checkNotNull(server).requests.map(::pageNumber)) + assertEquals(ids(1..90), model.ids) + assertEquals(false, model.hasMore) + } + + @Test + fun aPageThatFailsOffersARetryAndStopsLoadingOnItsOwn() = runBlocking { + var status = 500 + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + json( + Samples.page(ids(31..45).map { Samples.cap(it) }, page = 2, total = 45), + status, + ) + } + } + model.loadIfNeeded().join() + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + assertEquals(CapApiError.Server(500), model.loadMoreError) + assertEquals(false, model.isLoadingMore) + assertEquals(ids(1..30), model.ids) + assertNull(toasts.current.value) + assertNull(model.loadMoreIfNeeded(model.caps.last())) + assertEquals(2, listRequests()) + + status = 200 + checkNotNull(model.retryLoadMore()).join() + assertNull(model.loadMoreError) + assertEquals(ids(1..45), model.ids) + assertEquals(3, listRequests()) + } + + @Test + fun aRetryThatFailsOffersTheRetryAgain() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + json("{}", status = 500) + } + } + model.loadIfNeeded().join() + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + val retry = checkNotNull(model.retryLoadMore()) + retry.join() + + assertEquals(CapApiError.Server(500), model.loadMoreError) + } + + @Test + fun aRefreshClearsAFailedPage() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } else { + json("{}", status = 500) + } + } + model.loadIfNeeded().join() + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + model.refresh().join() + + assertNull(model.loadMoreError) + } + + @Test + fun aPageRequestedBeforeARefreshIsDiscarded() = runBlocking { + val held = Held(pageOf(31..45, page = 2, total = 45, hasMore = false)) + val model = model { request -> + when { + pageNumber(request) == 2 && listRequests() == 2 -> held.answer() + pageNumber(request) == 2 -> pageOf(61..62, page = 2, total = 32, hasMore = false) + listRequests() == 1 -> pageOf(1..30, page = 1, total = 45, hasMore = true) + else -> pageOf(101..130, page = 1, total = 32, hasMore = true) + } + } + model.loadIfNeeded().join() + + val more = checkNotNull(model.loadMoreIfNeeded(model.caps.last())) + held.arrived.await() + model.refresh().join() + held.release.complete(Unit) + more.join() + + assertEquals(ids(101..130), model.ids) + assertEquals(32, model.total) + assertTrue(model.hasMore) + assertEquals(false, model.isLoadingMore) + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + assertEquals(2, pageNumber(checkNotNull(server).requests.last())) + assertEquals(ids(101..130) + ids(61..62), model.ids) + } + + @Test + fun aPageFailureFromBeforeARefreshIsDiscarded() = runBlocking { + val held = Held(json("{}", status = 500)) + val model = model { request -> + if (pageNumber(request) == 2) { + held.answer() + } else { + pageOf(1..30, page = 1, total = 45, hasMore = true) + } + } + model.loadIfNeeded().join() + + val more = checkNotNull(model.loadMoreIfNeeded(model.caps.last())) + held.arrived.await() + model.refresh().join() + held.release.complete(Unit) + more.join() + + assertNull(model.loadMoreError) + assertEquals(false, model.isLoadingMore) + } + + private fun isStatuses(request: RecordedRequest) = + request.method == "POST" && request.path == "/api/mobile/caps/statuses" + + private fun statusRequests() = checkNotNull(server).count("POST", "/api/mobile/caps/statuses") + + private fun processingPage(vararg ids: String) = + json(Samples.page(ids.map { Samples.cap(it, upload = Samples.processing(10)) })) + + private val LibraryModel.progress + get() = caps.map { it.upload?.processingProgress } + + @Test + fun theWaitBetweenPollsGrowsFromThreeSecondsToFifteen() { + val start = clock.scheduler.timeSource.markNow() + val polled = mutableListOf() + val job = + clock.scope.launch { + pollWithBackoff(LibraryModel.POLL_FIRST, LibraryModel.POLL_LONGEST) { + polled += start.elapsedNow().inWholeMilliseconds + polled.size == 7 + } + } + + clock.advance(2999.milliseconds) + assertTrue(polled.isEmpty()) + clock.advance(1.milliseconds) + assertEquals(listOf(3000L), polled) + clock.advance(5.minutes) + + assertEquals(listOf(3000L, 7500L, 14250L, 24375L, 39375L, 54375L, 69375L), polled) + assertTrue(job.isCompleted) + } + + @Test + fun aListWithAnOwnProcessingCapIsPolledAfterThreeSeconds() = runBlocking { + val asked = CompletableDeferred() + val model = model { request -> + if (isStatuses(request)) { + asked.complete(request) + json(Samples.statuses("a" to Samples.processing(40))) + } else { + json( + Samples.page( + listOf( + Samples.cap("a", upload = Samples.processing(10)), + Samples.cap("b", owned = false, upload = Samples.processing(10)), + Samples.cap("c"), + Samples.cap("d", upload = Samples.upload("error")), + Samples.cap("e", upload = Samples.upload("complete")), + ) + ) + ) + } + } + model.loadIfNeeded().join() + assertTrue(model.isPolling) + + clock.advance(LibraryModel.POLL_FIRST) + + assertEquals("""{"ids":["a"]}""", asked.await().body) + } + + @Test + fun aListWithNothingOfTheUsersProcessingIsNotPolled() = runBlocking { + val model = model { + json( + Samples.page( + listOf( + Samples.cap("b", owned = false, upload = Samples.processing(10)), + Samples.cap("c"), + Samples.cap("d", upload = Samples.upload("error")), + Samples.cap("e", upload = Samples.upload("complete")), + ) + ) + ) + } + + model.loadIfNeeded().join() + + assertEquals(false, model.isPolling) + assertTrue(model.pollOnce()) + assertEquals(0, statusRequests()) + } + + @Test + fun aPollUpdatesTheProgressAndGoesOn() = runBlocking { + val model = model { request -> + if (isStatuses(request)) { + json(Samples.statuses("a" to Samples.processing(40))) + } else { + processingPage("a", "b") + } + } + model.loadIfNeeded().join() + + assertEquals(false, model.pollOnce()) + + assertEquals(listOf(40.0, 10.0), model.progress) + assertEquals(1, listRequests()) + assertTrue(model.isPolling) + } + + @Test + fun aCapThatHasNoUploadLeftRefreshesTheListAndEndsThePolling() = runBlocking { + val model = model { request -> + when { + isStatuses(request) -> json(Samples.statuses("a" to null)) + listRequests() == 1 -> processingPage("a") + else -> page("a", "new") + } + } + model.loadIfNeeded().join() + + assertTrue(model.pollOnce()) + + assertEquals(listOf("a", "new"), model.ids) + assertEquals(listOf(null, null), model.progress) + assertEquals(false, model.isPolling) + } + + @Test + fun theOtherCapsAreStillPolledWhenTheRefreshAfterAFinishedCapFails() = runBlocking { + val model = model { request -> + when { + isStatuses(request) && request.body.contains("\"a\"") -> + json(Samples.statuses("a" to null, "b" to Samples.processing(40))) + isStatuses(request) -> json(Samples.statuses("b" to Samples.processing(70))) + listRequests() == 1 -> processingPage("a", "b") + else -> json("{}", status = 500) + } + } + model.loadIfNeeded().join() + + assertEquals(false, model.pollOnce()) + assertEquals(listOf(null, 40.0), model.progress) + assertEquals(false, model.pollOnce()) + + assertEquals(listOf(null, 70.0), model.progress) + assertEquals(1, checkNotNull(server).requests.count { it.body == """{"ids":["b"]}""" }) + assertEquals(3, listRequests()) + } + + @Test + fun theRefreshAfterTheLastFinishedCapIsTriedAgainUntilItArrives() = runBlocking { + val model = model { request -> + when { + isStatuses(request) -> json(Samples.statuses("a" to null)) + listRequests() == 1 -> processingPage("a") + listRequests() == 2 -> json("{}", status = 500) + else -> json(Samples.page(listOf(Samples.cap("a", title = "Ready")))) + } + } + model.loadIfNeeded().join() + + assertEquals(false, model.pollOnce()) + assertEquals("Cap a", model.caps.single().title) + assertTrue(model.pollOnce()) + + assertEquals(3, listRequests()) + assertEquals(1, statusRequests()) + assertEquals("Ready", model.caps.single().title) + assertTrue(model.pollOnce()) + assertEquals(3, listRequests()) + } + + @Test + fun aCapWhoseUploadIsCompleteRefreshesTheList() = runBlocking { + val model = model { request -> + when { + isStatuses(request) -> json(Samples.statuses("a" to Samples.upload("complete"))) + else -> processingPage("a") + } + } + model.loadIfNeeded().join() + + assertTrue(model.pollOnce()) + + assertEquals(2, listRequests()) + assertTrue(model.isPolling) + } + + @Test + fun aCapThatFailsToProcessIsNotAskedAboutAgain() = runBlocking { + val model = model { request -> + if (isStatuses(request)) { + json(Samples.statuses("a" to Samples.upload("error"))) + } else { + processingPage("a") + } + } + model.loadIfNeeded().join() + + assertEquals(false, model.pollOnce()) + assertEquals(UploadPhase.ERROR, model.caps.single().upload?.phase) + assertTrue(model.pollOnce()) + + assertEquals(1, statusRequests()) + assertEquals(1, listRequests()) + } + + @Test + fun aPollThatFailsIsTriedAgain() = runBlocking { + val model = model { request -> + if (isStatuses(request)) json("{}", status = 500) else processingPage("a") + } + model.loadIfNeeded().join() + + assertEquals(false, model.pollOnce()) + + assertEquals(listOf(10.0), model.progress) + assertNull(toasts.current.value) + assertEquals(1, listRequests()) + } + + @Test + fun aPollThatIsRefusedEndsThePolling() = runBlocking { + val model = model { request -> + if (isStatuses(request)) json("{}", status = 401) else processingPage("a") + } + model.loadIfNeeded().join() + + assertTrue(model.pollOnce()) + + assertEquals(1, listRequests()) + } + + @Test + fun aStatusForACapThatLeftTheListIsIgnored() = runBlocking { + val held = Held(json(Samples.statuses("a" to null))) + val model = model { request -> + when { + isStatuses(request) -> held.answer() + listRequests() == 1 -> processingPage("a") + else -> page("b") + } + } + model.loadIfNeeded().join() + + val poll = async { model.pollOnce() } + held.arrived.await() + model.refresh().join() + held.release.complete(Unit) + + assertEquals(false, poll.await()) + assertEquals(listOf("b"), model.ids) + assertEquals(2, listRequests()) + } + + @Test + fun aRefreshWithNothingProcessingEndsThePolling() = runBlocking { + val model = model { if (listRequests() == 1) processingPage("a") else page("a") } + model.loadIfNeeded().join() + assertTrue(model.isPolling) + + model.refresh().join() + + assertEquals(false, model.isPolling) + } + + @Test + fun aRefreshStartsTheWaitAgain() = runBlocking { + val asked = CompletableDeferred() + val model = model { request -> + if (isStatuses(request)) { + asked.complete(Unit) + json(Samples.statuses("a" to Samples.processing(40))) + } else { + processingPage("a") + } + } + model.loadIfNeeded().join() + clock.advance(2.seconds) + model.refresh().join() + assertTrue(model.isPolling) + + clock.advance(LibraryModel.POLL_FIRST - 100.milliseconds) + assertEquals(0, statusRequests()) + clock.advance(100.milliseconds) + asked.await() + + assertEquals(1, statusRequests()) + } + + @Test + fun aLaterPageWithAProcessingCapStartsThePolling() = runBlocking { + val model = model { request -> + if (pageNumber(request) == 1) { + pageOf(1..30, page = 1, total = 31, hasMore = true) + } else { + json( + Samples.page( + listOf(Samples.cap("late", upload = Samples.processing(10))), + page = 2, + total = 31, + ) + ) + } + } + model.loadIfNeeded().join() + assertEquals(false, model.isPolling) + + checkNotNull(model.loadMoreIfNeeded(model.caps.last())).join() + + assertTrue(model.isPolling) + } + + @Test + fun aPausedLibraryStopsPollingUntilItIsShownAgain() = runBlocking { + val model = model { processingPage("a") } + model.loadIfNeeded().join() + + model.pausePolling() + assertEquals(false, model.isPolling) + + model.loadIfNeeded().join() + assertTrue(model.isPolling) + assertEquals(1, listRequests()) + } + + @Test + fun aListThatArrivesAfterThePauseDoesNotStartPolling() = runBlocking { + val held = Held(processingPage("a")) + val model = model { request -> + if (isStatuses(request)) json(Samples.statuses("a" to Samples.processing(40))) + else held.answer() + } + val load = model.loadIfNeeded() + held.arrived.await() + + model.pausePolling() + held.release.complete(Unit) + load.join() + assertEquals(listOf("a"), model.ids) + assertEquals(false, model.isPolling) + + clock.advance(1.minutes) + assertEquals(0, statusRequests()) + } + + @Test + fun aCancelledLibraryStopsPolling() = runBlocking { + val model = model { processingPage("a") } + model.loadIfNeeded().join() + + model.cancel() + + assertEquals(false, model.isPolling) + } + + @Test + fun aCancelledLibraryIgnoresItsReply() = runBlocking { + val held = Held(page("a")) + val model = model { held.answer() } + + val load = model.loadIfNeeded() + held.arrived.await() + model.cancel() + held.release.complete(Unit) + load.join() + + assertTrue(model.isEmpty) + assertNull(saved()) + assertTrue(clock.scope.isActive) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LoopbackServer.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LoopbackServer.kt new file mode 100644 index 00000000000..c96952152dc --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/LoopbackServer.kt @@ -0,0 +1,150 @@ +package so.cap.mobile.app + +import java.io.Closeable +import java.io.File +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketException +import java.security.KeyStore +import java.util.concurrent.CopyOnWriteArrayList +import javax.net.ssl.KeyManagerFactory +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager +import kotlin.concurrent.thread + +class RecordedRequest( + val method: String, + val path: String, + val headers: Map, + val body: String, +) + +class Reply( + val status: Int = 200, + val headers: Map = emptyMap(), + val body: ByteArray = ByteArray(0), + val declaresLength: Boolean = true, +) + +class LoopbackServer +private constructor( + private val socket: ServerSocket, + private val scheme: String, + private val handler: (RecordedRequest) -> Reply, +) : Closeable { + val requests = CopyOnWriteArrayList() + val origin: String + get() = "$scheme://127.0.0.1:${socket.localPort}" + + init { + thread(isDaemon = true) { + while (true) { + val connection = + try { + socket.accept() + } catch (_: SocketException) { + return@thread + } + connection.use(::serve) + } + } + } + + private fun serve(connection: Socket) { + val reader = connection.getInputStream().bufferedReader(Charsets.ISO_8859_1) + val requestLine = reader.readLine() ?: return + val headers = mutableMapOf() + while (true) { + val line = reader.readLine() + if (line.isNullOrEmpty()) break + headers[line.substringBefore(':').trim().lowercase()] = line.substringAfter(':').trim() + } + val body = CharArray(headers["content-length"]?.toInt() ?: 0) + var filled = 0 + while (filled < body.size) { + val count = reader.read(body, filled, body.size - filled) + if (count < 0) break + filled += count + } + val (method, path) = requestLine.split(' ') + val request = RecordedRequest(method, path, headers, String(body, 0, filled)) + requests += request + val reply = handler(request) + val head = buildString { + append("HTTP/1.1 ${reply.status} Reply\r\n") + reply.headers.forEach { (name, value) -> append("$name: $value\r\n") } + if (reply.declaresLength) append("Content-Length: ${reply.body.size}\r\n") + append("Connection: close\r\n\r\n") + } + val output = connection.getOutputStream() + output.write(head.toByteArray(Charsets.ISO_8859_1)) + output.write(reply.body) + output.flush() + } + + override fun close() = socket.close() + + companion object { + private val loopback: InetAddress = InetAddress.getByName("127.0.0.1") + + fun http(handler: (RecordedRequest) -> Reply): LoopbackServer = + LoopbackServer(ServerSocket(0, 50, loopback), "http", handler) + + fun https( + certificate: LoopbackCertificate, + handler: (RecordedRequest) -> Reply, + ): LoopbackServer = + LoopbackServer( + certificate.context.serverSocketFactory.createServerSocket(0, 50, loopback), + "https", + handler, + ) + } +} + +class LoopbackCertificate(directory: File) { + val context: SSLContext + val trustManager: X509TrustManager + + init { + val file = File(directory, "loopback.p12") + val password = "loopback" + val keytool = File(System.getProperty("java.home"), "bin/keytool").path + val exit = + ProcessBuilder( + keytool, + "-genkeypair", + "-alias", + "loopback", + "-keyalg", + "EC", + "-validity", + "1", + "-dname", + "CN=127.0.0.1", + "-ext", + "san=ip:127.0.0.1", + "-storetype", + "PKCS12", + "-keystore", + file.path, + "-storepass", + password, + ) + .redirectErrorStream(true) + .start() + .waitFor() + check(exit == 0) { "keytool failed with exit code $exit" } + val store = KeyStore.getInstance("PKCS12") + file.inputStream().use { store.load(it, password.toCharArray()) } + val keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) + keys.init(store, password.toCharArray()) + val trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + trust.init(store) + trustManager = trust.trustManagers.filterIsInstance().single() + context = SSLContext.getInstance("TLS") + context.init(keys.keyManagers, trust.trustManagers, null) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/MediaRequestInterceptorTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/MediaRequestInterceptorTest.kt new file mode 100644 index 00000000000..ba69eb97506 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/MediaRequestInterceptorTest.kt @@ -0,0 +1,170 @@ +package so.cap.mobile.app + +import java.io.IOException +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapEnvironment + +class MediaRequestInterceptorTest { + @get:Rule val temporaryFolder = TemporaryFolder() + + private val video = ByteArray(32) { it.toByte() } + private val servers = mutableListOf() + private lateinit var certificate: LoopbackCertificate + + @Before + fun createCertificate() { + certificate = LoopbackCertificate(temporaryFolder.root) + } + + @After + fun closeServers() { + servers.forEach(LoopbackServer::close) + } + + private fun http(handler: (RecordedRequest) -> Reply = { Reply(body = video) }) = + LoopbackServer.http(handler).also(servers::add) + + private fun https(handler: (RecordedRequest) -> Reply = { Reply(body = video) }) = + LoopbackServer.https(certificate, handler).also(servers::add) + + private fun client( + cap: LoopbackServer, + headers: (String) -> Map = { + mapOf("Authorization" to "Bearer cap-api-key") + }, + ): OkHttpClient { + val environment = + checkNotNull(CapEnvironment.parse(cap.origin, allowInsecureLocalhost = true)) + return mediaHttpClient(MediaRequestInterceptor(environment, headers)) + .newBuilder() + .sslSocketFactory(certificate.context.socketFactory, certificate.trustManager) + .build() + } + + private fun get(client: OkHttpClient, url: String): ByteArray = + client + .newCall(Request.Builder().url(url).header("X-Cap-Video-Access", "unlocked").build()) + .execute() + .use { response -> + assertEquals(200, response.code) + response.body.bytes() + } + + @Test + fun videoFromTheCapOriginCarriesTheBearerHeader() { + val cap = http() + + val body = get(client(cap), "${cap.origin}/media/demo.mp4") + + assertTrue(video.contentEquals(body)) + assertEquals("Bearer cap-api-key", cap.requests.single().headers["authorization"]) + } + + @Test + fun videoFromAStorageHostCarriesNoAuthHeaders() { + val cap = http() + val storage = https() + + get(client(cap), "${storage.origin}/video.mp4") + + val request = storage.requests.single() + assertFalse("authorization" in request.headers) + assertFalse("x-cap-video-access" in request.headers) + assertTrue(cap.requests.isEmpty()) + } + + @Test + fun aRedirectToAStorageHostDropsTheAuthHeaders() { + val storage = https() + val cap = http { + Reply(status = 302, headers = mapOf("Location" to "${storage.origin}/signed.mp4")) + } + + val body = get(client(cap), "${cap.origin}/api/mobile/caps/abc/video") + + assertTrue(video.contentEquals(body)) + assertEquals("Bearer cap-api-key", cap.requests.single().headers["authorization"]) + val redirected = storage.requests.single() + assertEquals("/signed.mp4", redirected.path) + assertFalse("authorization" in redirected.headers) + assertFalse("x-cap-video-access" in redirected.headers) + } + + @Test + fun aPlaylistFromTheCapOriginCarriesItsHeadersAndItsSegmentsOnStorageDoNot() { + val storage = https() + val cap = http { Reply(body = "#EXTM3U\n${storage.origin}/segment_1.m4s\n".toByteArray()) } + val asked = mutableListOf() + val client = + client(cap) { url -> + asked += url + mapOf("Authorization" to "Bearer cap-api-key", "X-Cap-Video-Access" to "sealed") + } + val playlist = "${cap.origin}/api/playlist?videoId=cap_1&videoType=segments-video" + + client.newCall(Request.Builder().url(playlist).build()).execute().close() + client + .newCall(Request.Builder().url("${storage.origin}/segment_1.m4s").build()) + .execute() + .close() + + assertEquals(listOf(playlist), asked) + val headers = cap.requests.single().headers + assertEquals("Bearer cap-api-key", headers["authorization"]) + assertEquals("sealed", headers["x-cap-video-access"]) + val segment = storage.requests.single().headers + assertFalse("authorization" in segment) + assertFalse("x-cap-video-access" in segment) + } + + @Test + fun aRangeRequestKeepsItsRangeAndOnlyTheCapOriginGetsTheKey() { + val cap = http() + + client(cap) + .newCall( + Request.Builder() + .url("${cap.origin}/media/long.mp4") + .header("Range", "bytes=10-") + .build() + ) + .execute() + .close() + + val request = cap.requests.single() + assertEquals("bytes=10-", request.headers["range"]) + assertEquals("Bearer cap-api-key", request.headers["authorization"]) + } + + @Test + fun videoFromAnInsecureForeignHostIsRefused() { + val cap = http() + val insecure = http() + + assertThrows(IOException::class.java) { get(client(cap), "${insecure.origin}/video.mp4") } + + assertTrue(insecure.requests.isEmpty()) + } + + @Test + fun aRedirectToAnInsecureForeignHostIsRefused() { + val insecure = http() + val cap = http { + Reply(status = 302, headers = mapOf("Location" to "${insecure.origin}/video.mp4")) + } + + assertThrows(IOException::class.java) { get(client(cap), "${cap.origin}/video") } + + assertTrue(insecure.requests.isEmpty()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ModelClock.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ModelClock.kt new file mode 100644 index 00000000000..f5b6316106f --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ModelClock.kt @@ -0,0 +1,21 @@ +package so.cap.mobile.app + +import kotlin.time.Duration +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestCoroutineScheduler +import kotlinx.coroutines.test.UnconfinedTestDispatcher + +// Time for a model under test only moves when the test moves it. Inside runTest, virtual time +// runs ahead on its own whenever the test is waiting for the loopback server, which would let a +// countdown or a timeout finish before the reply it is racing has arrived. +@OptIn(ExperimentalCoroutinesApi::class) +class ModelClock { + val scheduler = TestCoroutineScheduler() + val scope = CoroutineScope(UnconfinedTestDispatcher(scheduler)) + + fun advance(duration: Duration) { + scheduler.advanceTimeBy(duration) + scheduler.runCurrent() + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/NewFolderTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/NewFolderTest.kt new file mode 100644 index 00000000000..8ff8398491a --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/NewFolderTest.kt @@ -0,0 +1,305 @@ +package so.cap.mobile.app + +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.FolderColor +import so.cap.kit.SnapshotCache +import so.cap.mobile.app.ApiServer.Companion.json + +class NewFolderTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private val cache by lazy { SnapshotCache(folder.root) } + private val root = LibraryKey("org_cap", LibraryScope.Personal, folderId = null) + private val design = LibraryScope.Space("space_design") + private val created = json(Samples.folder("new", "Launch")) + private var bootstrap = Samples.bootstrap() + private var listed = listOf("old") + private var pages: () -> Reply = ::page + private var switching: () -> Reply = { + json(Samples.bootstrap(activeOrganizationId = "org_acme")) + } + private var server: ApiServer? = null + + @After + fun stopTheServer() { + server?.close() + } + + private fun session(folders: (RecordedRequest) -> Reply): SessionModel { + val started = ApiServer { request -> + when (request.path.substringBefore('?')) { + "/api/mobile/bootstrap" -> json(bootstrap) + "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + "/api/mobile/caps" -> pages() + "/api/mobile/folders" -> folders(request) + "/api/mobile/user/active-organization" -> switching() + else -> json("{}", status = 404) + } + } + server = started + val api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + return SessionModel(api, cache, Samples.richie, clock.scope) + } + + private fun page() = + json(Samples.page(emptyList(), folders = listed.map { Samples.folder(it) })) + + private suspend fun SessionModel.loaded(key: LibraryKey = root): LibraryModel { + start()?.join() + return library(key).also { it.loadIfNeeded().join() } + } + + private fun SessionModel.draft(name: String): FolderDraft { + beginFolder() + return checkNotNull(folderDraft).also { it.name.setTextAndPlaceCursorAtEnd(name) } + } + + private val posts + get() = checkNotNull(server).requests.filter { it.path == "/api/mobile/folders" } + + private val LibraryModel.folderIds + get() = folders.map { it.id } + + private val SessionModel.toast + get() = toasts.current.value?.message + + @Test + fun aFolderCanBeAddedToTheUsersOwnCapsAndToASpaceTheyManage() = runBlocking { + val session = session { created } + session.start()?.join() + assertTrue(session.canCreateFolder) + + session.select(design)?.join() + assertTrue(session.canCreateFolder) + session.beginFolder() + assertEquals(design, session.folderDraft?.scope) + } + + @Test + fun noFolderIsMadeWhileTheOrganizationIsChanging() = runBlocking { + val held = HeldReply(json(Samples.bootstrap(activeOrganizationId = "org_acme"))) + switching = held::answer + val session = session { created } + session.start()?.join() + val draft = session.draft("Launch") + val acme = checkNotNull(session.bootstrap).organizations.first { it.id == "org_acme" } + + val switch = checkNotNull(session.switchOrganization(acme)) + held.arrived.await() + assertFalse(session.canCreateFolder) + assertNull(session.saveFolder()) + session.cancelFolder() + session.beginFolder() + assertNull(session.folderDraft) + + held.release.complete(Unit) + switch.join() + assertTrue(posts.isEmpty()) + assertFalse(draft.isSaving) + assertTrue(session.canCreateFolder) + } + + @Test + fun aFolderCannotBeAddedToASpaceSomeoneElseManages() = runBlocking { + bootstrap = bootstrap.replace(""""canManage":true""", """"canManage":false""") + val session = session { created } + session.start()?.join() + session.select(design)?.join() + + assertFalse(session.canCreateFolder) + session.beginFolder() + assertNull(session.folderDraft) + } + + @Test + fun aNameIsCutAtAHundredCharactersWithoutSplittingAnEmoji() { + val emoji = "\uD83D\uDE00" + + assertEquals(3, FolderDraft.keptLength("abc")) + assertEquals(100, FolderDraft.keptLength("x".repeat(100))) + assertEquals(100, FolderDraft.keptLength("x".repeat(120))) + assertEquals(100, FolderDraft.keptLength("x".repeat(98) + emoji)) + assertEquals(99, FolderDraft.keptLength("x".repeat(99) + emoji)) + assertEquals(100, FolderDraft.keptLength("x".repeat(98) + emoji + "x")) + } + + @Test + fun savingSendsTheTrimmedNameAndTheColourAndPutsTheFolderFirst() = runBlocking { + val held = HeldReply(created) + val session = session { held.answer() } + val library = session.loaded() + val draft = session.draft(" Launch \n") + draft.color = FolderColor.RED + + val save = checkNotNull(session.saveFolder()) + held.arrived.await() + assertTrue(draft.isSaving) + assertNull(session.saveFolder()) + assertEquals(listOf("old"), library.folderIds) + + held.release.complete(Unit) + save.join() + assertEquals("POST", posts.single().method) + assertEquals("""{"name":"Launch","color":"red"}""", posts.single().body) + assertEquals(listOf("new", "old"), library.folderIds) + assertEquals("Folder created", session.toast) + assertNull(session.folderDraft) + assertFalse(draft.isSaving) + } + + @Test + fun aFolderInASpaceNamesTheSpaceAndGoesToThatSpacesLibrary() = runBlocking { + val session = session { created } + val own = session.loaded() + session.select(design)?.join() + val shared = session.loaded(root.copy(scope = design)) + session.draft("Launch") + session.select(LibraryScope.Personal)?.join() + + checkNotNull(session.saveFolder()).join() + + assertEquals( + """{"name":"Launch","color":"normal","spaceId":"space_design"}""", + posts.single().body, + ) + assertEquals(listOf("old"), own.folderIds) + assertEquals(listOf("new", "old"), shared.folderIds) + } + + @Test + fun aNameThatIsOnlySpacesIsNotSent() = runBlocking { + val session = session { created } + session.loaded() + session.draft(" \n ") + + assertNull(session.saveFolder()) + assertEquals(0, posts.size) + assertNotNull(session.folderDraft) + } + + @Test + fun aFolderTheServerRefusesKeepsTheDraftAndSaysWhy() = runBlocking { + var refuse = true + val second = HeldReply(created) + val session = session { + if (refuse) json("{}", status = 500) else second.answer() + } + val library = session.loaded() + val draft = session.draft("Launch") + + checkNotNull(session.saveFolder()).join() + assertEquals(CapApiError.Server(500).description, draft.error) + assertSame(draft, session.folderDraft) + assertFalse(draft.isSaving) + assertNull(session.toast) + assertEquals(listOf("old"), library.folderIds) + + refuse = false + val again = checkNotNull(session.saveFolder()) + second.arrived.await() + assertNull(draft.error) + second.release.complete(Unit) + again.join() + assertEquals(listOf("new", "old"), library.folderIds) + } + + @Test + fun aSaveThatIsCancelledStillAddsTheFolderAndLeavesANewerDraftAlone() = runBlocking { + val held = HeldReply(created) + val session = session { held.answer() } + val library = session.loaded() + session.draft("Launch") + + val save = checkNotNull(session.saveFolder()) + held.arrived.await() + session.cancelFolder() + assertNull(session.folderDraft) + val newer = session.draft("Another") + held.release.complete(Unit) + save.join() + + assertEquals(listOf("new", "old"), library.folderIds) + assertEquals("Folder created", session.toast) + assertSame(newer, session.folderDraft) + } + + @Test + fun aPageRequestedBeforeTheFolderWasCreatedKeepsIt() = runBlocking { + val page = HeldReply(page()) + var lists = 0 + pages = { + lists += 1 + if (lists == 2) page.answer() else page() + } + val session = session { created } + val library = session.loaded() + + val refresh = library.refresh() + page.arrived.await() + session.draft("Launch") + checkNotNull(session.saveFolder()).join() + page.release.complete(Unit) + refresh.join() + assertEquals(listOf("new", "old"), library.folderIds) + + library.refresh().join() + assertEquals(listOf("old"), library.folderIds) + } + + @Test + fun aPageRequestedBeforeThatAlreadyListsTheFolderShowsItOnce() = runBlocking { + listed = listOf("old", "new") + val page = HeldReply(page()) + listed = listOf("old") + var lists = 0 + pages = { + lists += 1 + if (lists == 2) page.answer() else page() + } + val session = session { created } + val library = session.loaded() + + val refresh = library.refresh() + page.arrived.await() + session.draft("Launch") + checkNotNull(session.saveFolder()).join() + page.release.complete(Unit) + refresh.join() + + assertEquals(listOf("old", "new"), library.folderIds) + } + + @Test + fun aFolderThePageAlreadyListsIsNotAddedTwice() = runBlocking { + val held = HeldReply(created) + val session = session { held.answer() } + val library = session.loaded() + session.draft("Launch") + + val save = checkNotNull(session.saveFolder()) + held.arrived.await() + listed = listOf("new", "old") + library.refresh().join() + held.release.complete(Unit) + save.join() + assertEquals(listOf("new", "old"), library.folderIds) + + val page = library.refresh() + page.join() + assertEquals(listOf("new", "old"), library.folderIds) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/PlaybackPreferencesTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/PlaybackPreferencesTest.kt new file mode 100644 index 00000000000..ccf908a668d --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/PlaybackPreferencesTest.kt @@ -0,0 +1,55 @@ +package so.cap.mobile.app + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class PlaybackPreferencesTest { + @get:Rule val folder = TemporaryFolder() + + private val file by lazy { folder.root.resolve("datastore/playback.preferences_pb") } + + @Test + fun theSpeedStartsAtNormal() = runBlocking { + assertEquals(1f, PlaybackPreferences(file).speed()) + } + + @Test + fun aChosenSpeedIsRemembered() = runBlocking { + val preferences = PlaybackPreferences(file) + + preferences.setSpeed(1.75f) + + assertEquals(1.75f, preferences.speed()) + assertEquals(true, file.exists()) + } + + @Test + fun aStoredSpeedSnapsToTheNearestOffered() = runBlocking { + val preferences = PlaybackPreferences(file) + + preferences.setSpeed(1.3f) + + assertEquals(1.2f, preferences.speed()) + } + + @Test + fun anUnreadableFileReadsAsNormalSpeed() = runBlocking { + file.parentFile?.mkdirs() + file.writeText("not a preferences file") + + assertEquals(1f, PlaybackPreferences(file).speed()) + } + + @Test + fun captionsStartOnAndRememberBeingTurnedOff() = runBlocking { + val preferences = PlaybackPreferences(file) + assertEquals(true, preferences.captionsEnabled()) + + preferences.setCaptionsEnabled(false) + + assertEquals(false, preferences.captionsEnabled()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/Samples.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/Samples.kt new file mode 100644 index 00000000000..ecf586676a9 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/Samples.kt @@ -0,0 +1,76 @@ +package so.cap.mobile.app + +import so.cap.kit.CapJson +import so.cap.kit.CapSummary +import so.cap.kit.CredentialSnapshot + +object Samples { + val richie = CredentialSnapshot("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie") + + fun bootstrap( + activeOrganizationId: String? = "org_cap", + userName: String = "Richie", + organizations: List> = + listOf("org_cap" to "Cap", "org_acme" to "Acme Studio"), + spaces: List> = listOf("space_design" to "Design"), + ): String { + val active = activeOrganizationId?.let { "\"$it\"" } + val organizationList = + organizations.joinToString(",") { (id, name) -> + """{"id":"$id","name":"$name","iconUrl":null,"role":"owner"}""" + } + val spaceList = + spaces.joinToString(",") { (id, name) -> + """{"id":"$id","name":"$name","iconUrl":null,"kind":"space","privacy":"Public",""" + + """"role":"member","canManage":true,"hasPassword":false}""" + } + return """{"user":{"id":"user_richie","name":"$userName","lastName":"McIlroy",""" + + """"email":"richie@cap.so","imageUrl":null,"activeOrganizationId":"org_cap"},""" + + """"organizations":[$organizationList],"activeOrganizationId":$active,""" + + """"rootFolders":[],"spaces":[$spaceList]}""" + } + + fun cap( + id: String, + isPublic: Boolean = true, + owned: Boolean = true, + upload: String? = null, + title: String = "Cap $id", + ): String = + """{"id":"$id","shareUrl":"https://cap.so/s/$id","title":"$title",""" + + """"createdAt":"2026-10-29T14:00:00.000Z","updatedAt":"2026-10-29T14:00:00.000Z",""" + + """"ownerId":"${if (owned) "user_richie" else "user_sam"}","ownerName":"Owner",""" + + """"durationSeconds":61,"thumbnailUrl":null,"thumbnailCacheKey":null,""" + + """"folderId":null,"public":$isPublic,"protected":false,"viewCount":3,""" + + """"commentCount":1,"reactionCount":0,"upload":$upload,"ownedByCurrentUser":$owned}""" + + fun decodedCap(id: String): CapSummary = + CapJson.json.decodeFromString(CapSummary.serializer(), cap(id)) + + fun processing(progress: Int): String = upload("processing", progress) + + fun upload(phase: String, progress: Int = 0): String = + """{"uploaded":0,"total":0,"phase":"$phase","processingProgress":$progress,""" + + """"processingMessage":"Processing video","processingError":null}""" + + fun statuses(vararg uploads: Pair): String = + uploads.joinToString(",", """{"caps":[""", "]}") { (id, upload) -> + """{"id":"$id","upload":$upload}""" + } + + fun folder(id: String, name: String = "Folder $id", videoCount: Int = 2): String = + """{"id":"$id","name":"$name","color":"blue","parentId":null,"videoCount":$videoCount}""" + + fun page( + caps: List, + folders: List = emptyList(), + page: Int = 1, + total: Int = caps.size, + hasMore: Boolean = false, + ): String = + """{"folders":[${folders.joinToString(",")}],"caps":[${caps.joinToString(",")}],""" + + """"page":$page,"limit":30,"total":$total,"collectionTotal":$total,"hasMore":$hasMore}""" + + fun plan(upgraded: Boolean): String = + """{"upgraded":$upgraded,"stripeSubscriptionStatus":null}""" +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionFiles.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionFiles.kt new file mode 100644 index 00000000000..6ce58312977 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionFiles.kt @@ -0,0 +1,15 @@ +package so.cap.mobile.app + +import java.io.File +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +class SessionFiles(private val directory: File, private val origin: String = "https://cap.so") { + private val key: SecretKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + + val file = File(directory, "session") + + fun store() = CredentialStore(file, origin) { key } + + fun vault() = CredentialVault(store()) +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionModelTest.kt new file mode 100644 index 00000000000..6a623c13b70 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/SessionModelTest.kt @@ -0,0 +1,828 @@ +package so.cap.mobile.app + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.builtins.serializer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.Bootstrap +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapJson +import so.cap.kit.CapsPage +import so.cap.kit.CredentialSnapshot +import so.cap.kit.MemberRole +import so.cap.kit.Organization +import so.cap.kit.SnapshotCache +import so.cap.mobile.app.ApiServer.Companion.json +import so.cap.mobile.features.auth.SignInModel + +class SessionModelTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private val cache by lazy { SnapshotCache(folder.root) } + private var server: ApiServer? = null + + @After + fun stopTheServer() { + server?.close() + } + + private fun serve(handler: (RecordedRequest) -> Reply): CapApi { + val started = ApiServer(handler) + server = started + return CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + } + + private fun model( + scope: CoroutineScope = clock.scope, + handler: (RecordedRequest) -> Reply, + ) = SessionModel(serve(handler), cache, Samples.richie, scope) + + private fun answers(bootstrap: Reply, plan: Reply = json(Samples.plan(upgraded = true))) = + { request: RecordedRequest -> + if (request.path == "/api/desktop/plan") plan else bootstrap + } + + private fun decoded(bootstrap: String): Bootstrap = + CapJson.json.decodeFromString(Bootstrap.serializer(), bootstrap) + + private suspend fun remember(bootstrap: String, userId: String = Samples.richie.userId) = + cache.write(Bootstrap.serializer(), decoded(bootstrap), userId, "bootstrap") + + private fun bootstrapRequests() = checkNotNull(server).count("GET", "/api/mobile/bootstrap") + + @Test + fun startLoadsTheBootstrapAndThePlan() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap()))) + + checkNotNull(model.start()).join() + + assertEquals(decoded(Samples.bootstrap()), model.bootstrap) + assertNull(model.bootstrapError) + assertEquals("org_cap", model.organizationId) + assertTrue(model.isPro) + val requests = checkNotNull(server).requests + assertEquals( + setOf("/api/mobile/bootstrap", "/api/desktop/plan"), + requests.map { it.path }.toSet(), + ) + assertTrue(requests.all { it.method == "GET" }) + assertTrue( + requests.all { it.headers["authorization"] == "Bearer ${Samples.richie.apiKey}" } + ) + } + + @Test + fun theCachedBootstrapIsShownBeforeTheServerAnswers() = runBlocking { + remember(Samples.bootstrap(userName = "Cached")) + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = + answers(json(Samples.bootstrap(userName = "Fresh"))).let { answer -> + { request -> + if (request.path == "/api/mobile/bootstrap") { + arrived.complete(Unit) + runBlocking { release.await() } + } + answer(request) + } + } + ) + + val start = checkNotNull(model.start()) + arrived.await() + assertEquals("Cached", model.bootstrap?.user?.name) + + release.complete(Unit) + start.join() + assertEquals("Fresh", model.bootstrap?.user?.name) + } + + @Test + fun thePlanIsRequestedWhileTheBootstrapIsStillLoading() = runBlocking { + val planArrived = CompletableDeferred() + val model = + model( + handler = { request -> + if (request.path == "/api/desktop/plan") { + planArrived.complete(Unit) + json(Samples.plan(upgraded = true)) + } else { + runBlocking { planArrived.await() } + json(Samples.bootstrap()) + } + } + ) + + checkNotNull(model.start()).join() + + assertNotNull(model.bootstrap) + assertTrue(model.isPro) + } + + @Test + fun aFreshBootstrapIsSavedForTheNextLaunch() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap(userName = "Fresh")))) + + checkNotNull(model.start()).join() + + val saved = cache.read(Bootstrap.serializer(), Samples.richie.userId, "bootstrap") + assertEquals("Fresh", saved?.user?.name) + } + + @Test + fun anotherUsersCachedBootstrapIsNotShown() = runBlocking { + remember(Samples.bootstrap(userName = "Someone else"), userId = "user_sam") + val model = model(handler = answers(json("{}", status = 500))) + + checkNotNull(model.start()).join() + + assertNull(model.bootstrap) + } + + @Test + fun aFailedRefreshKeepsTheBootstrapAndRecordsTheError() = runBlocking { + remember(Samples.bootstrap(userName = "Cached")) + var status = 500 + val model = + model( + handler = { request -> + answers(json(Samples.bootstrap(userName = "Fresh"), status))(request) + } + ) + + checkNotNull(model.start()).join() + assertEquals("Cached", model.bootstrap?.user?.name) + assertEquals(CapApiError.Server(500), model.bootstrapError) + + status = 200 + model.refreshBootstrap().join() + assertEquals("Fresh", model.bootstrap?.user?.name) + assertNull(model.bootstrapError) + } + + @Test + fun aRefreshWhileOneIsInFlightSendsNoSecondRequest() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = { + arrived.complete(Unit) + runBlocking { release.await() } + json(Samples.bootstrap()) + } + ) + + val first = model.refreshBootstrap() + arrived.await() + val second = model.refreshBootstrap() + release.complete(Unit) + first.join() + second.join() + + assertEquals(1, bootstrapRequests()) + + model.refreshBootstrap().join() + assertEquals(2, bootstrapRequests()) + } + + @Test + fun endingTheSessionRunsWhatWaitsForTheEnd() { + val model = model(handler = answers(json(Samples.bootstrap()))) + var ended = 0 + model.onEnd { ended += 1 } + assertEquals(0, ended) + + clock.scope.cancel() + + assertEquals(1, ended) + } + + @Test + fun whatWaitsForASessionThatHasEndedRunsAtOnce() { + val model = model(handler = answers(json(Samples.bootstrap()))) + clock.scope.cancel() + var ended = 0 + + model.onEnd { ended += 1 } + + assertEquals(1, ended) + } + + @Test + fun startRunsOnce() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap()))) + + checkNotNull(model.start()).join() + assertNull(model.start()) + + assertEquals(1, bootstrapRequests()) + } + + @Test + fun theOrganizationFallsBackToTheUsersWhenTheBootstrapNamesNone() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap(activeOrganizationId = null)))) + assertNull(model.organizationId) + + checkNotNull(model.start()).join() + + assertEquals("org_cap", model.organizationId) + } + + @Test + fun aPlanThatCannotBeLoadedIsNotPro() = runBlocking { + val model = + model(handler = answers(json(Samples.bootstrap()), plan = json("{}", status = 500))) + + checkNotNull(model.start()).join() + + assertNull(model.plan) + assertFalse(model.isPro) + } + + @Test + fun aFreePlanIsNotPro() = runBlocking { + val model = + model( + handler = + answers(json(Samples.bootstrap()), plan = json(Samples.plan(upgraded = false))) + ) + + checkNotNull(model.start()).join() + + assertEquals(false, model.plan?.upgraded) + assertFalse(model.isPro) + } + + @Test + fun aReplyThatArrivesAfterTheSessionEndedChangesNothing() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = { + arrived.complete(Unit) + runBlocking { release.await() } + json(Samples.bootstrap()) + } + ) + + val refresh = model.refreshBootstrap() + arrived.await() + clock.scope.cancel() + release.complete(Unit) + refresh.join() + + assertNull(model.bootstrap) + assertNull(model.bootstrapError) + assertNull(cache.read(Bootstrap.serializer(), Samples.richie.userId, "bootstrap")) + } + + @Test + fun thereIsNoLibraryUntilTheOrganisationIsKnown() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap()))) + assertNull(model.currentLibraryKey) + + checkNotNull(model.start()).join() + + assertEquals( + LibraryKey("org_cap", LibraryScope.Personal, folderId = null), + model.currentLibraryKey, + ) + } + + @Test + fun aLibraryIsKeptPerKey() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap()))) + checkNotNull(model.start()).join() + val key = checkNotNull(model.currentLibraryKey) + + assertSame(model.library(key), model.library(key)) + assertNotSame(model.library(key), model.library(key.copy(folderId = "folder_launch"))) + assertEquals(key, model.library(key).key) + } + + @Test + fun aBootstrapForTheSameOrganisationKeepsTheLibraries() = runBlocking { + val model = model(handler = answers(json(Samples.bootstrap()))) + checkNotNull(model.start()).join() + val key = checkNotNull(model.currentLibraryKey) + val library = model.library(key) + + model.refreshBootstrap().join() + + assertSame(library, model.library(key)) + } + + @Test + fun aBootstrapForAnotherOrganisationDropsAndStopsTheLibraries() = runBlocking { + var organization = "org_cap" + val listArrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = { request -> + when (request.path.substringBefore('?')) { + "/api/mobile/caps" -> { + listArrived.complete(Unit) + runBlocking { release.await() } + json(Samples.page(listOf(Samples.cap("a")))) + } + "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + else -> json(Samples.bootstrap(activeOrganizationId = organization)) + } + } + ) + checkNotNull(model.start()).join() + val key = checkNotNull(model.currentLibraryKey) + val library = model.library(key) + val load = library.loadIfNeeded() + listArrived.await() + + organization = "org_acme" + model.refreshBootstrap().join() + release.complete(Unit) + load.join() + + assertEquals("org_acme", model.currentLibraryKey?.organizationId) + assertNotSame(library, model.library(key)) + assertTrue(library.caps.isEmpty()) + } + + private val design = LibraryScope.Space("space_design") + private val acme = + Organization("org_acme", "Acme Studio", iconUrl = null, role = MemberRole.MEMBER) + private val switchPath = "/api/mobile/user/active-organization" + + private fun organisations( + requests: (RecordedRequest) -> Reply? = { null } + ): (RecordedRequest) -> Reply { + var active = "org_cap" + return { request -> + requests(request) + ?: when (request.path.substringBefore('?')) { + switchPath -> { + active = request.body.substringAfter(""":"""").substringBefore('"') + json(bootstrapOf(active)) + } + "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + "/api/mobile/caps" -> json(Samples.page(listOf(Samples.cap("a")))) + else -> json(bootstrapOf(active)) + } + } + } + + private fun bootstrapOf(organization: String) = + Samples.bootstrap( + activeOrganizationId = organization, + spaces = + if (organization == "org_cap") { + listOf("space_design" to "Design") + } else { + listOf("space_sales" to "Sales") + }, + ) + + private suspend fun rememberedScope(organization: String) = + cache.read(String.serializer(), Samples.richie.userId, "scope-$organization") + + @Test + fun theLibraryStartsOnTheUsersOwnCaps() = runBlocking { + val model = model(handler = organisations()) + + checkNotNull(model.start()).join() + + assertEquals(LibraryScope.Personal, model.libraryScope) + assertNull(model.selectedSpace) + assertEquals( + LibraryKey("org_cap", LibraryScope.Personal, folderId = null), + model.currentLibraryKey, + ) + } + + @Test + fun theScopeBarIsShownForSpacesOrSeveralOrganisations() { + fun shows(organizations: Int, spaces: Int): Boolean = runBlocking { + val bootstrap = + Samples.bootstrap( + organizations = + listOf("org_cap" to "Cap", "org_acme" to "Acme Studio").take(organizations), + spaces = listOf("space_design" to "Design").take(spaces), + ) + server?.close() + val model = model(handler = answers(json(bootstrap))) + assertEquals(false, model.showsScopeBar) + checkNotNull(model.start()).join() + model.showsScopeBar + } + + assertEquals(false, shows(organizations = 1, spaces = 0)) + assertTrue(shows(organizations = 1, spaces = 1)) + assertTrue(shows(organizations = 2, spaces = 0)) + } + + @Test + fun selectingASpaceShowsItsLibraryAndIsRememberedForTheNextLaunch() = runBlocking { + val model = model(handler = organisations()) + checkNotNull(model.start()).join() + + checkNotNull(model.select(design)).join() + + assertEquals(design, model.libraryScope) + assertEquals("Design", model.selectedSpace?.name) + assertEquals(LibraryKey("org_cap", design, folderId = null), model.currentLibraryKey) + assertEquals("space_design", rememberedScope("org_cap")) + + val api = + CapApi( + checkNotNull(server).environment, + "Cap-Android/test", + credentials = { Samples.richie }, + ) + val relaunched = SessionModel(api, cache, Samples.richie, clock.scope) + checkNotNull(relaunched.start()).join() + assertEquals(design, relaunched.libraryScope) + } + + @Test + fun theRememberedSpaceIsShownWithTheCachedBootstrap() = runBlocking { + remember(bootstrapOf("org_cap")) + cache.write(String.serializer(), "space_design", Samples.richie.userId, "scope-org_cap") + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = + organisations { request -> + if (request.path == "/api/mobile/bootstrap") { + arrived.complete(Unit) + runBlocking { release.await() } + } + null + } + ) + + val start = checkNotNull(model.start()) + arrived.await() + assertEquals(design, model.libraryScope) + + release.complete(Unit) + start.join() + } + + @Test + fun selectingTheUsersOwnCapsForgetsTheSpace() = runBlocking { + val model = model(handler = organisations()) + checkNotNull(model.start()).join() + checkNotNull(model.select(design)).join() + + checkNotNull(model.select(LibraryScope.Personal)).join() + + assertEquals(LibraryScope.Personal, model.libraryScope) + assertNull(rememberedScope("org_cap")) + } + + @Test + fun aRememberedSpaceThatIsGoneFallsBackToTheUsersOwnCaps() = runBlocking { + cache.write(String.serializer(), "space_gone", Samples.richie.userId, "scope-org_cap") + val model = model(handler = organisations()) + + checkNotNull(model.start()).join() + + assertEquals(LibraryScope.Personal, model.libraryScope) + } + + @Test + fun aSelectedSpaceThatLeavesTheBootstrapFallsBackToTheUsersOwnCaps() = runBlocking { + var spaces = listOf("space_design" to "Design") + val model = + model( + handler = + organisations { request -> + if (request.path == "/api/mobile/bootstrap") { + json(Samples.bootstrap(spaces = spaces)) + } else { + null + } + } + ) + checkNotNull(model.start()).join() + checkNotNull(model.select(design)).join() + + spaces = emptyList() + model.refreshBootstrap().join() + + assertEquals(LibraryScope.Personal, model.libraryScope) + } + + @Test + fun theRememberedSpaceIsReadOncePerOrganisation() = runBlocking { + val model = model(handler = organisations()) + checkNotNull(model.start()).join() + cache.write(String.serializer(), "space_design", Samples.richie.userId, "scope-org_cap") + + model.refreshBootstrap().join() + + assertEquals(LibraryScope.Personal, model.libraryScope) + } + + @Test + fun switchingOrganisationReplacesTheBootstrapAndDropsTheLibraries() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = + organisations { request -> + if (request.path == switchPath) { + arrived.complete(Unit) + runBlocking { release.await() } + } + null + } + ) + checkNotNull(model.start()).join() + checkNotNull(model.select(design)).join() + val key = checkNotNull(model.currentLibraryKey) + val library = model.library(key) + library.loadIfNeeded().join() + + val switch = checkNotNull(model.switchOrganization(acme)) + arrived.await() + assertTrue(model.isSwitchingOrganization) + assertNull(model.switchOrganization(acme)) + assertEquals("org_cap", model.organizationId) + + release.complete(Unit) + switch.join() + + val request = checkNotNull(server).requests.single { it.path == switchPath } + assertEquals("PATCH", request.method) + assertEquals("""{"organizationId":"org_acme"}""", request.body) + assertEquals(false, model.isSwitchingOrganization) + assertEquals("org_acme", model.organizationId) + assertEquals(LibraryScope.Personal, model.libraryScope) + assertEquals(listOf("space_sales"), model.spaces.map { it.id }) + assertNotSame(library, model.library(key)) + assertEquals(false, library.refresh().isActive) + assertEquals("Switched to Acme Studio", model.toasts.current.value?.message) + assertEquals( + "org_acme", + cache + .read(Bootstrap.serializer(), Samples.richie.userId, "bootstrap") + ?.activeOrganizationId, + ) + } + + @Test + fun aLibraryListsNothingWhileTheOrganisationIsChanging() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + var serverSwitched = false + val model = + model( + handler = + organisations { request -> + when { + request.path == switchPath -> { + serverSwitched = true + arrived.complete(Unit) + runBlocking { release.await() } + null + } + request.path.startsWith("/api/mobile/caps") -> + json( + Samples.page( + if (serverSwitched) listOf(Samples.cap("acme")) + else emptyList() + ) + ) + else -> null + } + } + ) + checkNotNull(model.start()).join() + val key = checkNotNull(model.currentLibraryKey) + val library = model.library(key) + library.loadIfNeeded().join() + assertEquals(LibraryModel.Status.Loaded, library.status) + + val switch = checkNotNull(model.switchOrganization(acme)) + arrived.await() + val refresh = library.refresh() + assertEquals(LibraryModel.Status.Loaded, library.status) + release.complete(Unit) + switch.join() + refresh.join() + + assertTrue(library.caps.isEmpty()) + assertEquals( + emptyList(), + cache.read(CapsPage.serializer(), Samples.richie.userId, key.cacheKey)?.caps?.map { + it.id + }, + ) + } + + @Test + fun theScopeIsRememberedPerOrganisation() = runBlocking { + val cap = Organization("org_cap", "Cap", iconUrl = null, role = MemberRole.OWNER) + val model = model(handler = organisations()) + checkNotNull(model.start()).join() + checkNotNull(model.select(design)).join() + checkNotNull(model.switchOrganization(acme)).join() + checkNotNull(model.select(LibraryScope.Space("space_sales"))).join() + + checkNotNull(model.switchOrganization(cap)).join() + assertEquals(design, model.libraryScope) + + checkNotNull(model.switchOrganization(acme)).join() + assertEquals(LibraryScope.Space("space_sales"), model.libraryScope) + } + + @Test + fun switchingToTheCurrentOrganisationDoesNothing() = runBlocking { + val model = model(handler = organisations()) + checkNotNull(model.start()).join() + + assertNull(model.switchOrganization(acme.copy(id = "org_cap"))) + + assertEquals(0, checkNotNull(server).count("PATCH", switchPath)) + } + + @Test + fun aSwitchThatFailsKeepsTheOrganisationAndSaysWhy() = runBlocking { + val model = + model( + handler = + organisations { request -> + if (request.path == switchPath) json("{}", status = 500) else null + } + ) + checkNotNull(model.start()).join() + checkNotNull(model.select(design)).join() + val key = checkNotNull(model.currentLibraryKey) + val library = model.library(key) + + checkNotNull(model.switchOrganization(acme)).join() + + assertEquals("org_cap", model.organizationId) + assertEquals(design, model.libraryScope) + assertSame(library, model.library(key)) + assertEquals(false, model.isSwitchingOrganization) + assertEquals(CapApiError.Server(500).description, model.toasts.current.value?.message) + assertNull(model.bootstrapError) + } + + private suspend fun switchedWhileRefreshing(late: Reply): SessionModel { + var hold = false + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = + model( + handler = + organisations { request -> + if (hold && request.path == "/api/mobile/bootstrap") { + arrived.complete(Unit) + runBlocking { release.await() } + late + } else { + null + } + } + ) + checkNotNull(model.start()).join() + hold = true + val refresh = model.refreshBootstrap() + arrived.await() + checkNotNull(model.switchOrganization(acme)).join() + release.complete(Unit) + refresh.join() + return model + } + + @Test + fun aBootstrapRequestedBeforeASwitchIsDiscarded() = runBlocking { + val model = switchedWhileRefreshing(late = json(bootstrapOf("org_cap"))) + + assertEquals("org_acme", model.organizationId) + assertEquals(listOf("space_sales"), model.spaces.map { it.id }) + } + + @Test + fun aBootstrapFailureFromBeforeASwitchIsNotRecorded() = runBlocking { + val model = switchedWhileRefreshing(late = json("{}", status = 500)) + + assertNull(model.bootstrapError) + } + + private fun holder(phase: MutableStateFlow, scopes: MutableList) = + SessionHolder(phase, clock.scope) { credentials, scope -> + scopes += scope + SessionModel( + serve(answers(json(Samples.bootstrap()))), + cache, + credentials, + scope, + ) + } + + private fun signedOut() = + Phase.SignedOut( + SignInModel(serve { json("{}") }, clock.scope, onSession = {}), + notice = null, + ) + + @Test + fun thereIsNoSessionWhileSignedOut() { + val holder = holder(MutableStateFlow(signedOut()), mutableListOf()) + + assertNull(holder.session) + } + + @Test + fun signingInStartsASessionForThoseCredentials() { + val phase = MutableStateFlow(signedOut()) + val holder = holder(phase, mutableListOf()) + + phase.value = Phase.SignedIn(Samples.richie) + + assertEquals(Samples.richie, holder.session?.credentials) + assertNull(holder.session?.start()) + } + + @Test + fun aSavedSessionIsStartedStraightAway() { + val holder = holder(MutableStateFlow(Phase.SignedIn(Samples.richie)), mutableListOf()) + + assertEquals(Samples.richie, holder.session?.credentials) + } + + @Test + fun signingOutEndsTheSessionAndItsWork() { + val phase = MutableStateFlow(Phase.SignedIn(Samples.richie)) + val scopes = mutableListOf() + val holder = holder(phase, scopes) + + phase.value = signedOut() + + assertNull(holder.session) + assertFalse(scopes.single().isActive) + assertTrue(clock.scope.isActive) + } + + @Test + fun theSessionEndsWithItsHolder() { + val scopes = mutableListOf() + holder(MutableStateFlow(Phase.SignedIn(Samples.richie)), scopes) + + clock.scope.cancel() + + assertFalse(scopes.single().isActive) + } + + @Test + fun signingInAsSomeoneElseReplacesTheSession() { + val phase = MutableStateFlow(Phase.SignedIn(Samples.richie)) + val scopes = mutableListOf() + val holder = holder(phase, scopes) + val first = holder.session + val other = CredentialSnapshot("1f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_empty") + + phase.value = Phase.SignedIn(other) + + assertNotSame(first, holder.session) + assertEquals(other, holder.session?.credentials) + assertFalse(scopes[0].isActive) + assertTrue(scopes[1].isActive) + } + + @Test + fun theSameCredentialsKeepTheSession() { + val phase = MutableStateFlow(Phase.SignedIn(Samples.richie)) + val holder = holder(phase, mutableListOf()) + val first = holder.session + + phase.value = Phase.SignedIn(Samples.richie.copy()) + + assertSame(first, holder.session) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ToastCenterTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ToastCenterTest.kt new file mode 100644 index 00000000000..ed95229b0e1 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/app/ToastCenterTest.kt @@ -0,0 +1,116 @@ +package so.cap.mobile.app + +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import so.cap.kit.CapApiError +import so.cap.mobile.R + +@OptIn(ExperimentalCoroutinesApi::class) +class ToastCenterTest { + @Test + fun showDefaultsToASuccessToastWithACheckmark() = runTest { + val center = ToastCenter(backgroundScope) + + center.show("Link copied") + + val toast = center.current.value + assertEquals("Link copied", toast?.message) + assertEquals(Toast.Style.Success, toast?.style) + assertEquals(R.drawable.ic_check_circle, toast?.icon) + } + + @Test + fun aToastDismissesItselfAfterTwoPointFourSeconds() = runTest { + val center = ToastCenter(backgroundScope) + center.show("Link copied") + + advanceTimeBy(2399.milliseconds) + runCurrent() + assertEquals("Link copied", center.current.value?.message) + + advanceTimeBy(1.milliseconds) + runCurrent() + assertNull(center.current.value) + } + + @Test + fun anErrorToastStaysForFourSeconds() = runTest { + val center = ToastCenter(backgroundScope) + center.show("Something went wrong.", style = Toast.Style.Error) + + advanceTimeBy(3999.milliseconds) + runCurrent() + assertEquals("Something went wrong.", center.current.value?.message) + + advanceTimeBy(1.milliseconds) + runCurrent() + assertNull(center.current.value) + } + + @Test + fun anApiErrorShowsItsDescriptionAsAnErrorToast() = runTest { + val center = ToastCenter(backgroundScope) + + center.show(CapApiError.Offline) + + val toast = center.current.value + assertEquals("You're offline. Check your connection and try again.", toast?.message) + assertEquals(Toast.Style.Error, toast?.style) + assertEquals(R.drawable.ic_warning, toast?.icon) + } + + @Test + fun aCancelledApiErrorShowsNothing() = runTest { + val center = ToastCenter(backgroundScope) + + center.show(CapApiError.Cancelled) + + assertNull(center.current.value) + } + + @Test + fun aNewToastReplacesTheCurrentOneAndRestartsTheTimer() = runTest { + val center = ToastCenter(backgroundScope) + center.show("First") + advanceTimeBy(2000.milliseconds) + + center.show("Second") + assertEquals("Second", center.current.value?.message) + + advanceTimeBy(2399.milliseconds) + runCurrent() + assertEquals("Second", center.current.value?.message) + + advanceTimeBy(1.milliseconds) + runCurrent() + assertNull(center.current.value) + } + + @Test + fun dismissClearsTheCurrentToast() = runTest { + val center = ToastCenter(backgroundScope) + center.show("Link copied") + + center.dismiss(checkNotNull(center.current.value).id) + + assertNull(center.current.value) + } + + @Test + fun dismissIgnoresAToastThatWasAlreadyReplaced() = runTest { + val center = ToastCenter(backgroundScope) + center.show("First") + val first = checkNotNull(center.current.value).id + center.show("Second") + + center.dismiss(first) + + assertEquals("Second", center.current.value?.message) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/CapThumbnailTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/CapThumbnailTest.kt new file mode 100644 index 00000000000..c2051d2bfc8 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/CapThumbnailTest.kt @@ -0,0 +1,20 @@ +package so.cap.mobile.designsystem + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CapThumbnailTest { + @Test + fun thumbnailBucketRoundsTheWidthUpToTheNext160Pixels() { + assertEquals(960, thumbnailBucket(960f)) + assertEquals(1120, thumbnailBucket(961f)) + assertEquals(1120, thumbnailBucket(1080f)) + } + + @Test + fun thumbnailBucketIsNeverBelow320Pixels() { + assertEquals(320, thumbnailBucket(0f)) + assertEquals(320, thumbnailBucket(116f)) + assertEquals(480, thumbnailBucket(321f)) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/ColorContrastTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/ColorContrastTest.kt new file mode 100644 index 00000000000..b17f14dedee --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/ColorContrastTest.kt @@ -0,0 +1,34 @@ +package so.cap.mobile.designsystem + +import androidx.compose.material3.ColorScheme +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import org.junit.Assert.assertTrue +import org.junit.Test + +class ColorContrastTest { + @Test fun errorTextReadsOnTheSurfaceInLight() = assertErrorTextReads(LightColorScheme) + + @Test fun errorTextReadsOnTheSurfaceInDark() = assertErrorTextReads(DarkColorScheme) + + @Test fun accentTextReadsOnAccentColoursInLight() = assertAccentTextReads(LightColorScheme) + + @Test fun accentTextReadsOnAccentColoursInDark() = assertAccentTextReads(DarkColorScheme) + + private fun assertErrorTextReads(scheme: ColorScheme) { + assertContrast(scheme.error, scheme.surface, "error on surface") + } + + private fun assertAccentTextReads(scheme: ColorScheme) { + assertContrast(scheme.onPrimary, scheme.primary, "onPrimary on primary") + assertContrast(scheme.onSecondary, scheme.secondary, "onSecondary on secondary") + assertContrast(scheme.onTertiary, scheme.tertiary, "onTertiary on tertiary") + } + + private fun assertContrast(foreground: Color, background: Color, label: String) { + val text = foreground.luminance() + val surface = background.luminance() + val contrast = (maxOf(text, surface) + 0.05f) / (minOf(text, surface) + 0.05f) + assertTrue("$label has a contrast of $contrast to 1", contrast >= 4.5f) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/DesignTokensTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/DesignTokensTest.kt new file mode 100644 index 00000000000..264179bcd88 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/DesignTokensTest.kt @@ -0,0 +1,100 @@ +package so.cap.mobile.designsystem + +import androidx.compose.animation.core.TweenSpec +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.sp +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class DesignTokensTest { + @Test + fun coreLightAndDarkColoursMatchTheDesign() { + assertEquals(Color(0xFFFCFCFC), LightCapColors.background) + assertEquals(Color(0xFF111111), DarkCapColors.background) + assertEquals(Color(0xFF202020), LightCapColors.text) + assertEquals(Color(0xFFEEEEEE), DarkCapColors.text) + assertEquals(Color(0xFF646464), LightCapColors.textSecondary) + assertEquals(Color(0xFFB4B4B4), DarkCapColors.textSecondary) + assertEquals(Color(0xFFE0E0E0), LightCapColors.hairline) + assertEquals(Color(0xFF2A2A2A), DarkCapColors.hairline) + assertEquals(Color(0xFFE8E8E8), LightCapColors.quietFill) + assertEquals(Color(0xFF2A2A2A), DarkCapColors.quietFill) + assertEquals(Color(0xFF4785FF), LightCapColors.blue) + assertEquals(Color(0xFF4785FF), DarkCapColors.blue) + } + + @Test + fun editorAndAccentColoursMatchTheDesign() { + assertEquals(Color(0xFF111111), LightCapColors.editorBackground) + assertEquals(Color(0xFFEEEEEE), LightCapColors.editorText) + assertEquals(Color(0xFFADC9FF), LightCapColors.blueSoft) + assertEquals(Color(0xFFF74A3A), LightCapColors.record) + assertEquals(Color(0xFF30A46C), CapAnnotationColors.green) + assertEquals(Color(0xFFFFD60A), CapAnnotationColors.yellow) + assertEquals(Color(0xFFFF8A00), CapAnnotationColors.orange) + assertEquals(Color(0xFF2EB4FF), CapAnnotationColors.sky) + assertEquals( + listOf(Color(0xFF0090FF), Color(0xFF2EB4FF), Color(0xFFC5EAFF)), + CapWallpaperColors.sky, + ) + } + + @Test + fun typeScaleMatchesTheDesign() { + assertType(CapType.hugeNumeric, 152, 152) + assertType(CapType.libraryCount, 96, 96) + assertType(CapType.bigOption, 48, 56) + assertType(CapType.pickerNumber, 44, 48) + assertType(CapType.largeMetric, 40, 44) + assertType(CapType.notificationNumeric, 32, 36) + assertType(CapType.screenTitle, 28, 34) + assertType(CapType.detailTitle, 22, 28) + assertType(CapType.panelTitle, 17, 24) + assertType(CapType.rowTitle, 16, 22) + assertType(CapType.body, 15, 22) + assertType(CapType.metadata, 14, 20) + assertType(CapType.small, 13, 18) + assertType(CapType.tinyLabel, 12, 16) + assertSame(CapFontFamily, CapType.body.fontFamily) + assertEquals("tnum", CapType.hugeNumeric.fontFeatureSettings) + } + + @Test + fun legacyTypeNamesMapOntoTheDesignScale() { + assertSame(CapType.screenTitle, CapType.largeTitle) + assertSame(CapType.screenTitle, CapType.title) + assertSame(CapType.detailTitle, CapType.title2) + assertSame(CapType.panelTitle, CapType.title3) + assertSame(CapType.rowTitle, CapType.headline) + assertSame(CapType.body, CapType.subheadline) + assertSame(CapType.small, CapType.footnote) + assertSame(CapType.tinyLabel, CapType.caption) + } + + @Test + fun motionUsesTheDesignDurationsAndEasings() { + assertTween(CapMotion.tick(), 160) + assertTween(CapMotion.colour(), 200) + assertTween(CapMotion.medium(), 300) + assertTween(CapMotion.panel(), 500) + assertTween(CapMotion.morph(), 500) + val emphasized = CapEasing.emphasized.transform(0.5f) + val springLike = CapEasing.springLike.transform(0.5f) + assertTrue(emphasized > 0.5f) + assertTrue(springLike > 1f) + } + + private fun assertType(style: androidx.compose.ui.text.TextStyle, size: Int, lineHeight: Int) { + assertEquals(size.sp, style.fontSize) + assertEquals(lineHeight.sp, style.lineHeight) + } + + private fun assertTween( + spec: androidx.compose.animation.core.FiniteAnimationSpec<*>, + millis: Int, + ) { + assertEquals(millis, (spec as TweenSpec).durationMillis) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/InitialsTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/InitialsTest.kt new file mode 100644 index 00000000000..134df3bd22c --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/designsystem/InitialsTest.kt @@ -0,0 +1,32 @@ +package so.cap.mobile.designsystem + +import org.junit.Assert.assertEquals +import org.junit.Test + +class InitialsTest { + @Test + fun takesTheFirstLetterOfTheFirstTwoWords() { + assertEquals("RM", initials("Richie McIlroy")) + assertEquals("RM", initials(" richie mcilroy junior ")) + assertEquals("R", initials("richie")) + assertEquals("", initials(" ")) + } + + @Test + fun keepsACharacterOutsideTheBasicPlaneWhole() { + assertEquals("\uD842\uDFB7\u592A", initials("\uD842\uDFB7\u91CE \u592A\u90CE")) + assertEquals("\uD83D\uDE00S", initials("\uD83D\uDE00 smile")) + assertEquals("\uD842\uDFB7", "\uD842\uDFB7\u91CE\u5BB6".firstCharacter()) + } + + @Test + fun keepsALetterWithItsCombiningMark() { + assertEquals("E\u0301", initials("e\u0301mile")) + assertEquals("e\u0301", "e\u0301mile".firstCharacter()) + } + + @Test + fun hasNoFirstCharacterInAnEmptyName() { + assertEquals("", "".firstCharacter()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/AuthBrowserTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/AuthBrowserTest.kt new file mode 100644 index 00000000000..dc3a1b1b459 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/AuthBrowserTest.kt @@ -0,0 +1,60 @@ +package so.cap.mobile.features.auth + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class AuthBrowserTest { + private val firefox = "org.mozilla.firefox" + private val hyperOs = "com.mi.globalbrowser" + private val samsung = "com.sec.android.app.sbrowser" + private val chrome = "com.android.chrome" + private val chromeBeta = "com.chrome.beta" + + @Test + fun aDefaultBrowserWithAuthTabIsUsed() { + val supported = setOf(samsung, chrome) + + assertEquals(samsung, authTabBrowser(samsung, listOf(chrome, samsung), supported::contains)) + } + + @Test + fun chromeIsChosenWhenTheDefaultBrowserHasNoAuthTab() { + val supported = setOf(samsung, chromeBeta, chrome) + + assertEquals( + chrome, + authTabBrowser( + hyperOs, + listOf(hyperOs, samsung, chromeBeta, chrome), + supported::contains, + ), + ) + } + + @Test + fun anotherChromeChannelComesBeforeOtherBrowsers() { + val supported = setOf(samsung, chromeBeta) + + assertEquals( + chromeBeta, + authTabBrowser(hyperOs, listOf(samsung, chrome, chromeBeta), supported::contains), + ) + } + + @Test + fun anyBrowserWithAuthTabIsUsedWhenNoChromeHasIt() { + val supported = setOf(samsung) + + assertEquals( + samsung, + authTabBrowser(hyperOs, listOf(firefox, chrome, samsung), supported::contains), + ) + } + + @Test + fun noBrowserIsChosenWhenNoneSupportsAuthTab() { + assertNull(authTabBrowser(hyperOs, listOf(hyperOs, firefox, chrome)) { false }) + assertNull(authTabBrowser(null, emptyList()) { true }) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/SignInModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/SignInModelTest.kt new file mode 100644 index 00000000000..ecb242fe78d --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/auth/SignInModelTest.kt @@ -0,0 +1,715 @@ +package so.cap.mobile.features.auth + +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import java.io.IOException +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import so.cap.kit.ApiKeySession +import so.cap.kit.AuthCallback +import so.cap.kit.AuthConfig +import so.cap.kit.CapApi +import so.cap.kit.CapEnvironment +import so.cap.mobile.app.LoopbackServer +import so.cap.mobile.app.ModelClock +import so.cap.mobile.app.RecordedRequest +import so.cap.mobile.app.Reply + +class SignInModelTest { + private val clock = ModelClock() + private var server: LoopbackServer? = null + private val sessions = mutableListOf() + private var saveFailure: IOException? = null + private val pending = mutableListOf() + private var restored: SignInModel.Pending? = null + private var saving: CompletableDeferred? = null + private val callback = + "cap://auth?api_key=0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e&user_id=user_richie" + private val googleCouldNotFinish = + "Google sign-in couldn't finish in this browser. Install or turn on Chrome, " + + "or sign in with your email." + private val session = + """{"type":"api_key","apiKey":"0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e","userId":"user_richie"}""" + + @After + fun stopTheServer() { + server?.close() + } + + private fun json(body: String, status: Int = 200) = + Reply(status, mapOf("Content-Type" to "application/json"), body.toByteArray()) + + private fun model(handler: (RecordedRequest) -> Reply): SignInModel { + val started = LoopbackServer.http(handler) + server = started + val environment = + checkNotNull(CapEnvironment.parse(started.origin, allowInsecureLocalhost = true)) + return SignInModel( + api = CapApi(environment, "Cap-Android/test", credentials = { null }), + scope = clock.scope, + timeSource = clock.scheduler.timeSource, + pending = restored, + onProviderPending = { pending += it }, + onSession = { session -> + saving?.await() + saveFailure?.let { throw it } + sessions += session + }, + ) + } + + private fun codeFlow(verify: Reply): (RecordedRequest) -> Reply = { request -> + if (request.path.endsWith("/verify")) verify else json("""{"success":true}""") + } + + private suspend fun SignInModel.reachTheCodeStep() { + email.setTextAndPlaceCursorAtEnd("richie@cap.so") + checkNotNull(sendCode()).join() + } + + private val requests: List + get() = checkNotNull(server).requests + + @Test + fun anInvalidEmailIsRefusedWithoutARequest() { + val model = model { json("""{"success":true}""") } + model.showEmail() + model.email.setTextAndPlaceCursorAtEnd("richie@cap") + + assertFalse(model.canSubmitEmail) + assertNull(model.sendCode()) + + assertEquals("Enter a valid email address.", model.errorMessage) + assertEquals(SignInModel.Step.Email, model.step) + assertTrue(requests.isEmpty()) + } + + @Test + fun sendingACodeNormalisesTheEmailAndMovesToTheCodeStep() = runBlocking { + val model = model { json("""{"success":true}""") } + model.showEmail() + model.email.setTextAndPlaceCursorAtEnd(" Richie@Cap.so ") + + assertTrue(model.canSubmitEmail) + checkNotNull(model.sendCode()).join() + + val request = requests.single() + assertEquals("POST", request.method) + assertEquals("/api/mobile/session/email/request", request.path) + assertEquals("""{"email":"richie@cap.so"}""", request.body) + assertNull(request.headers["authorization"]) + assertEquals(SignInModel.Step.Code("richie@cap.so"), model.step) + assertNull(model.errorMessage) + assertNull(model.activity) + } + + @Test + fun aSecondSendWhileTheFirstIsInFlightDoesNothing() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = model { + arrived.complete(Unit) + runBlocking { release.await() } + json("""{"success":true}""") + } + model.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + + val first = checkNotNull(model.sendCode()) + arrived.await() + assertEquals(SignInModel.Activity.Email, model.activity) + assertFalse(model.canSubmitEmail) + assertNull(model.sendCode()) + assertNull(model.errorMessage) + + release.complete(Unit) + first.join() + assertEquals(1, requests.size) + assertEquals(SignInModel.Step.Code("richie@cap.so"), model.step) + } + + @Test + fun aFailedSendStaysOnTheEmailStepWithTheError() = runBlocking { + val model = model { json("{}", status = 500) } + model.showEmail() + model.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + + checkNotNull(model.sendCode()).join() + + assertEquals(SignInModel.Step.Email, model.step) + assertEquals("Cap is having trouble right now. Try again shortly.", model.errorMessage) + assertNull(model.activity) + } + + @Test + fun differentEmailReturnsToTheEmailStepAndKeepsTheAddress() = runBlocking { + val model = model { json("""{"success":true}""") } + model.showEmail() + model.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + checkNotNull(model.sendCode()).join() + + model.useDifferentEmail() + + assertEquals(SignInModel.Step.Email, model.step) + assertEquals("richie@cap.so", model.email.text.toString()) + assertNull(model.errorMessage) + } + + @Test + fun differentEmailClearsATypedCode() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + model.code.setTextAndPlaceCursorAtEnd("123") + + model.useDifferentEmail() + + assertEquals("", model.code.text.toString()) + } + + @Test + fun sendingACodeStartsAThirtySecondCountdown() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + + assertEquals(30, model.resendRemaining) + clock.advance(1.seconds) + assertEquals(29, model.resendRemaining) + clock.advance(500.milliseconds) + assertEquals(29, model.resendRemaining) + clock.advance(28.seconds) + assertEquals(1, model.resendRemaining) + clock.advance(499.milliseconds) + assertEquals(1, model.resendRemaining) + clock.advance(1.milliseconds) + assertEquals(0, model.resendRemaining) + } + + @Test + fun resendIsRefusedUntilTheCountdownEnds() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + + clock.advance(29.seconds) + assertNull(model.resend()) + assertEquals(1, requests.size) + + clock.advance(1.seconds) + model.code.setTextAndPlaceCursorAtEnd("12") + checkNotNull(model.resend()).join() + + assertEquals(2, requests.size) + assertEquals("""{"email":"richie@cap.so"}""", requests.last().body) + assertEquals("", model.code.text.toString()) + assertEquals(30, model.resendRemaining) + assertNull(model.activity) + } + + @Test + fun resendDoesNothingBeforeACodeWasSent() { + val model = model(codeFlow(json(session))) + + assertNull(model.resend()) + assertTrue(requests.isEmpty()) + } + + @Test + fun aResentCodeShowsAConfirmationUntilTheCodeIsEdited() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + clock.advance(30.seconds) + + checkNotNull(model.resend()).join() + + assertEquals(SignInModel.CodeNotice.Resent, model.codeNotice) + + model.noteCodeEdited() + + assertNull(model.codeNotice) + } + + @Test + fun aFailedResendKeepsTheCodeStepAndShowsTheError() = runBlocking { + var failing = false + val model = model { + if (failing) json("{}", status = 500) else json("""{"success":true}""") + } + model.reachTheCodeStep() + clock.advance(30.seconds) + failing = true + + checkNotNull(model.resend()).join() + + assertEquals(SignInModel.Step.Code("richie@cap.so"), model.step) + assertNotNull(model.errorMessage) + assertEquals(0, model.resendRemaining) + } + + @Test + fun verifyNeedsAllSixDigits() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + model.code.setTextAndPlaceCursorAtEnd("12345") + + assertFalse(model.canVerify) + assertNull(model.verify()) + + assertEquals(1, requests.size) + assertTrue(sessions.isEmpty()) + } + + @Test + fun aCorrectCodeHandsOverTheSession() = runBlocking { + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + model.code.setTextAndPlaceCursorAtEnd("123456") + + assertTrue(model.canVerify) + checkNotNull(model.verify()).join() + + val request = requests.last() + assertEquals("POST", request.method) + assertEquals("/api/mobile/session/email/verify", request.path) + assertEquals("""{"email":"richie@cap.so","code":"123456"}""", request.body) + assertEquals( + listOf(ApiKeySession("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie")), + sessions, + ) + assertNull(model.errorMessage) + assertNull(model.activity) + } + + @Test + fun aWrongCodeKeepsTheDigitsAndRejectsOnlyThatAttempt() = runBlocking { + val model = model(codeFlow(json("{}", status = 403))) + model.reachTheCodeStep() + assertEquals(30, model.resendRemaining) + model.code.setTextAndPlaceCursorAtEnd("654321") + + checkNotNull(model.verify()).join() + + assertTrue(sessions.isEmpty()) + assertEquals("654321", model.code.text.toString()) + assertFalse(model.canVerify) + assertEquals(0, model.resendRemaining) + assertEquals( + "That code didn't match. Check the email and enter it again.", + model.errorMessage, + ) + assertTrue(model.isWrongCodeError) + assertEquals(SignInModel.Step.Code("richie@cap.so"), model.step) + + model.code.setTextAndPlaceCursorAtEnd("65432") + model.noteCodeEdited() + model.code.setTextAndPlaceCursorAtEnd("654321") + assertTrue(model.canVerify) + + checkNotNull(model.resend()).join() + assertEquals(30, model.resendRemaining) + } + + @Test + fun aSessionThatCannotBeSavedShowsItsOwnMessage() = runBlocking { + saveFailure = IOException("disk full") + val model = model(codeFlow(json(session))) + model.reachTheCodeStep() + model.code.setTextAndPlaceCursorAtEnd("123456") + + checkNotNull(model.verify()).join() + + assertEquals("Cap couldn't save your session securely. Try again.", model.errorMessage) + assertEquals("123456", model.code.text.toString()) + assertNull(model.activity) + } + + @Test + fun bothProvidersAreOfferedUntilTheServerSaysOtherwise() = runBlocking { + val model = model { + json( + """{"appleAuthAvailable":false,"googleAuthAvailable":true,"workosAuthAvailable":false}""" + ) + } + assertEquals(AuthConfig.FALLBACK, model.config) + + model.loadConfig().join() + + val request = requests.single() + assertEquals("GET", request.method) + assertEquals("/api/mobile/session/config", request.path) + assertEquals( + AuthConfig( + appleAuthAvailable = false, + googleAuthAvailable = true, + workosAuthAvailable = false, + ), + model.config, + ) + } + + @Test + fun aConfigThatCannotBeLoadedKeepsBothProviders() = runBlocking { + val model = model { json("{}", status = 500) } + + model.loadConfig().join() + + assertEquals(AuthConfig.FALLBACK, model.config) + assertNull(model.errorMessage) + } + + @Test + fun startingAProviderSignInGivesTheAddressToOpen() { + val model = model { json("{}") } + + val url = checkNotNull(model.startProvider("google")) + + assertEquals( + "${checkNotNull(server).origin}/api/mobile/session/request" + + "?redirectUri=cap%3A%2F%2Fauth&provider=google&state=${AuthCallback.state(url)}", + url, + ) + assertEquals(SignInModel.Activity.Provider("google"), model.activity) + assertNull(model.startProvider("apple")) + assertEquals(SignInModel.Activity.Provider("google"), model.activity) + assertTrue(requests.isEmpty()) + } + + @Test + fun aProviderSignInIsRefusedWhileACodeIsBeingSent() = runBlocking { + val arrived = CompletableDeferred() + val release = CompletableDeferred() + val model = model { + arrived.complete(Unit) + runBlocking { release.await() } + json("""{"success":true}""") + } + model.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + val sending = checkNotNull(model.sendCode()) + arrived.await() + + assertNull(model.startProvider("google")) + assertEquals(SignInModel.Activity.Email, model.activity) + + release.complete(Unit) + sending.join() + } + + @Test + fun aCallbackWithASessionHandsItOver() { + val model = model { json("{}") } + model.startProvider("google") + + model.finishProvider(callback, fromAuthTab = true) + + assertEquals( + listOf(ApiKeySession("0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", "user_richie")), + sessions, + ) + assertNull(model.activity) + assertNull(model.errorMessage) + } + + @Test + fun aRestoredProviderSignInAcceptsItsCallback() { + restored = SignInModel.Pending("google", "restored-state-0123456789") + val model = model { json("{}") } + + assertEquals(SignInModel.Activity.Provider("google"), model.activity) + model.finishProvider("$callback&state=restored-state-0123456789", fromAuthTab = false) + + assertEquals(1, sessions.size) + assertNull(model.activity) + assertEquals(listOf(null), pending) + } + + @Test + fun aLinkIsAcceptedOnlyWithTheStateOfThePendingSignIn() { + val model = model { json("{}") } + val refused = + listOf( + callback, + "$callback&state=wrong-state-0123456789", + "cap://auth?error_description=Access%20denied", + ) + + for (link in refused) { + model.startProvider("google") + assertNull(model.finishProvider(link, fromAuthTab = false)) + assertNull(model.activity) + assertEquals(googleCouldNotFinish, model.errorMessage) + } + assertTrue(sessions.isEmpty()) + + val state = checkNotNull(AuthCallback.state(checkNotNull(model.startProvider("google")))) + model.finishProvider("$callback&state=$state", fromAuthTab = false) + + assertEquals(1, sessions.size) + assertNull(model.activity) + assertNull(model.finishProvider("$callback&state=$state", fromAuthTab = false)) + assertEquals(1, sessions.size) + } + + @Test + fun aRefusedLinkEndsTheSignInAndNamesTheProvider() { + val model = model { json("{}") } + model.startProvider("apple") + + assertNull(model.finishProvider(callback, fromAuthTab = false)) + + assertNull(model.activity) + assertEquals( + "Apple sign-in couldn't finish in this browser. Install or turn on Chrome, " + + "or sign in with your email.", + model.errorMessage, + ) + assertEquals("apple", pending.first()?.provider) + assertNull(pending.last()) + assertNull(model.finishProvider(callback, fromAuthTab = true)) + assertTrue(sessions.isEmpty()) + } + + @Test + fun aLinkWithNoProviderSignInPendingSaysNothing() { + val model = model { json("{}") } + + assertNull(model.finishProvider(callback, fromAuthTab = false)) + assertNull(model.finishProvider("$callback&state=wrong-state-0123456789", false)) + + assertNull(model.activity) + assertNull(model.errorMessage) + assertTrue(pending.isEmpty()) + } + + @Test + fun eachProviderSignInSendsAFreshStateAndReportsIt() { + val model = model { json("{}") } + val first = checkNotNull(AuthCallback.state(checkNotNull(model.startProvider("google")))) + model.cancelProvider() + val second = checkNotNull(AuthCallback.state(checkNotNull(model.startProvider("google")))) + + assertNotEquals(first, second) + assertTrue(second, Regex("[A-Za-z0-9_-]{32}").matches(second)) + assertEquals( + listOf( + SignInModel.Pending("google", first), + null, + SignInModel.Pending("google", second), + ), + pending, + ) + } + + @Test + fun thePendingProviderIsReportedUntilTheSignInEnds() { + val model = model { json("{}") } + + model.startProvider("google") + model.cancelProvider() + model.startProvider("apple") + model.failProvider() + model.startProvider("google") + model.finishProvider("cap://auth?error_description=Access%20denied", fromAuthTab = true) + model.cancelProvider() + model.failProvider() + + assertEquals( + listOf("google", null, "apple", null, "google", null), + pending.map { it?.provider }, + ) + } + + @Test + fun aCallbackWithNoProviderSignInPendingIsIgnored() { + val model = model { json("{}") } + + model.finishProvider(callback, fromAuthTab = true) + model.finishProvider("cap://auth?error_description=Access%20denied", fromAuthTab = true) + + assertTrue(sessions.isEmpty()) + assertNull(model.errorMessage) + } + + @Test + fun aCallbackIsAcceptedOnlyOncePerSignIn() { + val model = model { json("{}") } + model.startProvider("google") + + model.finishProvider(callback, fromAuthTab = true) + model.finishProvider(callback, fromAuthTab = true) + + assertEquals(1, sessions.size) + } + + @Test + fun aProviderSignInStaysBusyWhileItsSessionIsSaved() = runBlocking { + val release = CompletableDeferred() + saving = release + val model = model { json("{}") } + model.startProvider("google") + + val finishing = checkNotNull(model.finishProvider(callback, fromAuthTab = true)) + assertEquals(SignInModel.Activity.Verifying, model.activity) + assertNull(model.finishProvider(callback, fromAuthTab = true)) + model.cancelProvider() + assertNull(model.startProvider("apple")) + assertEquals(SignInModel.Activity.Verifying, model.activity) + + release.complete(Unit) + finishing.join() + + assertEquals(1, sessions.size) + assertNull(model.activity) + assertNull(model.errorMessage) + } + + @Test + fun aCallbackAfterTheBrowserWasClosedIsIgnored() { + val model = model { json("{}") } + model.startProvider("apple") + + model.cancelProvider() + assertNull(model.activity) + assertNull(model.errorMessage) + model.finishProvider(callback, fromAuthTab = true) + + assertTrue(sessions.isEmpty()) + } + + @Test + fun aCallbackCarryingAProviderErrorShowsIt() { + val model = model { json("{}") } + model.startProvider("google") + + model.finishProvider("cap://auth?error_description=Access%20denied", fromAuthTab = true) + + assertEquals("Access denied", model.errorMessage) + assertNull(model.activity) + assertTrue(sessions.isEmpty()) + } + + @Test + fun aCallbackWithoutAPlausibleSessionShowsTheMessage() { + val model = model { json("{}") } + model.startProvider("google") + + model.finishProvider("cap://auth?api_key=nope&user_id=user_richie", fromAuthTab = true) + + assertEquals("Sign in did not return a Cap session. Try again.", model.errorMessage) + assertNull(model.activity) + assertTrue(sessions.isEmpty()) + } + + @Test + fun aProviderSessionThatCannotBeSavedShowsItsOwnMessage() { + saveFailure = IOException("disk full") + val model = model { json("{}") } + model.startProvider("google") + + model.finishProvider(callback, fromAuthTab = true) + + assertEquals("Cap couldn't save your session securely. Try again.", model.errorMessage) + assertNull(model.activity) + } + + @Test + fun aBrowserThatCannotBeOpenedShowsTheMessage() { + val model = model { json("{}") } + model.startProvider("google") + + model.failProvider() + + assertEquals( + "Sign in couldn't start. Check your connection and try again.", + model.errorMessage, + ) + assertNull(model.activity) + } + + @Test + fun aBrowserFailureWithNoProviderSignInPendingSaysNothing() { + val model = model { json("{}") } + + model.failProvider() + + assertNull(model.errorMessage) + } + + private fun messageAfterSending(status: Int): String? = runBlocking { + val model = model { json("{}", status) } + model.email.setTextAndPlaceCursorAtEnd("richie@cap.so") + checkNotNull(model.sendCode()).join() + model.errorMessage + } + + private fun messageAfterVerifying(status: Int): String? = runBlocking { + val model = model(codeFlow(json("{}", status))) + model.reachTheCodeStep() + model.code.setTextAndPlaceCursorAtEnd("654321") + checkNotNull(model.verify()).join() + model.errorMessage + } + + private val wrongCode = "That code didn't match. Check the email and enter it again." + + @Test + fun aRateLimitHasItsOwnMessageOnBothSteps() { + val message = "Too many attempts. Wait a few minutes and try again." + + assertEquals(message, messageAfterSending(429)) + assertEquals(message, messageAfterVerifying(429)) + } + + @Test + fun aRefusedCodeSaysTheCodeDidNotWork() { + assertEquals(wrongCode, messageAfterVerifying(403)) + assertEquals(wrongCode, messageAfterVerifying(404)) + assertEquals(wrongCode, messageAfterVerifying(400)) + } + + @Test + fun anEmailThatCannotUseACodeIsToldToTryAnotherOption() { + assertEquals( + "This email can't sign in with a code. Try another sign in option.", + messageAfterSending(403), + ) + } + + @Test + fun anEmailTheServerRejectsIsCalledInvalid() { + assertEquals("Enter a valid email address.", messageAfterSending(400)) + } + + @Test + fun otherFailuresKeepTheGeneralMessages() { + assertEquals( + "This couldn't be found. It may have been deleted or moved.", + messageAfterSending(404), + ) + assertEquals( + "Cap is having trouble right now. Try again shortly.", + messageAfterVerifying(503), + ) + } + + @Test + fun aFailedResendUsesTheRequestMessages() = runBlocking { + var status = 200 + val model = model { json("""{"success":true}""", status) } + model.reachTheCodeStep() + clock.advance(30.seconds) + status = 403 + + checkNotNull(model.resend()).join() + + assertEquals( + "This email can't sign in with a code. Try another sign in option.", + model.errorMessage, + ) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapDetailModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapDetailModelTest.kt new file mode 100644 index 00000000000..2d8227082ca --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapDetailModelTest.kt @@ -0,0 +1,718 @@ +package so.cap.mobile.features.cap + +import androidx.media3.common.MimeTypes +import java.util.concurrent.atomic.AtomicInteger +import kotlin.coroutines.CoroutineContext +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellableContinuation +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Delay +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.InternalCoroutinesApi +import kotlinx.coroutines.Runnable +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import okhttp3.OkHttpClient +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapId +import so.cap.kit.PlaybackKind +import so.cap.kit.ShareTarget +import so.cap.kit.SnapshotCache +import so.cap.mobile.R +import so.cap.mobile.app.ApiServer +import so.cap.mobile.app.ApiServer.Companion.json +import so.cap.mobile.app.LibraryKey +import so.cap.mobile.app.LibraryScope +import so.cap.mobile.app.ModelClock +import so.cap.mobile.app.RecordedRequest +import so.cap.mobile.app.Reply +import so.cap.mobile.app.Samples +import so.cap.mobile.app.SessionModel +import so.cap.mobile.features.cap.CapDetailModel.Content +import so.cap.mobile.features.cap.CapDetailModel.Transcript + +class CapDetailModelTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private var server: ApiServer? = null + private lateinit var session: SessionModel + + @After + fun stopTheServer() { + server?.close() + } + + private fun model( + target: ShareTarget = ShareTarget(checkNotNull(CapId.parse("cap_a"))), + scope: CoroutineScope = clock.scope, + handler: (RecordedRequest) -> Reply, + ): CapDetailModel { + val started = ApiServer(handler) + server = started + val api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + session = SessionModel(api, SnapshotCache(folder.root), Samples.richie, clock.scope) + return CapDetailModel(target, api, OkHttpClient(), session, scope) + } + + private fun requests(method: String, path: String) = checkNotNull(server).count(method, path) + + @Test + fun loadingShowsTheCap() = runBlocking { + val model = model { json(detail(Samples.cap("cap_a", title = "Walkthrough"))) } + + model.load().join() + + assertEquals("Walkthrough", model.detail?.cap?.title) + assertEquals(1, requests("GET", "/api/mobile/caps/cap_a")) + } + + @Test + fun aForbiddenCapWithAPasswordIsLocked() = runBlocking { + val model = model { request -> + if (request.path.endsWith("/access")) json("""{"status":"password_required"}""") + else json("{}", status = 403) + } + + model.load().join() + + assertSame(Content.Locked, model.content) + assertEquals(1, requests("GET", "/api/mobile/caps/cap_a/access")) + } + + @Test + fun aForbiddenCapWithoutAPasswordIsRestricted() = runBlocking { + val model = model { request -> + if (request.path.endsWith("/access")) json("""{"status":"restricted"}""") + else json("{}", status = 403) + } + + model.load().join() + + assertSame(Content.Restricted, model.content) + } + + @Test + fun aFailedAccessCheckReadsAsRestricted() = runBlocking { + val model = model { request -> + json("{}", status = if (request.path.endsWith("/access")) 500 else 403) + } + + model.load().join() + + assertSame(Content.Restricted, model.content) + } + + @Test + fun aMissingCapIsUnavailableWithoutAnAccessCheck() = runBlocking { + val model = model { json("{}", status = 404) } + + model.load().join() + + assertEquals(Content.Unavailable(CapApiError.NotFound), model.content) + assertEquals(0, requests("GET", "/api/mobile/caps/cap_a/access")) + } + + @Test + fun tryAgainLoadsAgainAfterAFailure() = runBlocking { + var failing = true + val model = model { + if (failing) json("{}", status = 500) else json(detail(Samples.cap("cap_a"))) + } + model.load().join() + assertEquals(Content.Unavailable(CapApiError.Server(500)), model.content) + + failing = false + model.retry().join() + + assertEquals("cap_a", model.detail?.cap?.id) + assertEquals(2, requests("GET", "/api/mobile/caps/cap_a")) + } + + @Test + fun aLoadedCapIsNotFetchedAgainByLoad() = runBlocking { + val model = model { json(detail(Samples.cap("cap_a"))) } + + model.load().join() + model.load().join() + + assertEquals(1, requests("GET", "/api/mobile/caps/cap_a")) + } + + @Test + fun loadingAnOwnedCapUpdatesItsLibraryCard() = runBlocking { + val model = model { request -> + if (request.path.startsWith("/api/mobile/caps?")) { + json(Samples.page(listOf(Samples.cap("cap_a", title = "Old title")))) + } else { + json(detail(Samples.cap("cap_a", title = "New title"))) + } + } + val library = session.library(LibraryKey("org_cap", LibraryScope.Personal, null)) + library.refresh().join() + + model.load().join() + + assertEquals(listOf("New title"), library.caps.map { it.title }) + } + + @Test + fun aCapSomeoneElseOwnsLeavesTheLibraryAlone() = runBlocking { + val model = model { request -> + if (request.path.startsWith("/api/mobile/caps?")) { + json(Samples.page(listOf(Samples.cap("cap_a", title = "Old title")))) + } else { + json(detail(Samples.cap("cap_a", owned = false, title = "New title"))) + } + } + val library = session.library(LibraryKey("org_cap", LibraryScope.Personal, null)) + library.refresh().join() + + model.load().join() + + assertEquals(listOf("Old title"), library.caps.map { it.title }) + } + + @Test + fun refreshingShowsAFailureAsAToastAndKeepsTheCap() = runBlocking { + var failing = false + val model = model { + if (failing) json("{}", status = 500) else json(detail(Samples.cap("cap_a"))) + } + model.load().join() + + failing = true + model.refresh().join() + + assertEquals("cap_a", model.detail?.cap?.id) + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + private fun locked(unlock: (String) -> Reply): (RecordedRequest) -> Reply = { request -> + val granted = request.headers["x-cap-video-access"] == "sealed" + when { + request.path.endsWith("/unlock") -> unlock(request.body) + request.path.endsWith("/access") -> + json("""{"status":"${if (granted) "granted" else "password_required"}"}""") + request.path.endsWith("/playback") -> json("{}", status = 403) + granted -> json(detail(Samples.cap("cap_a", title = "Board update"))) + else -> json("{}", status = 403) + } + } + + private val sealed = json("""{"accessToken":"sealed","expiresAt":"2099-01-01T00:00:00.000Z"}""") + + @Test + fun aProcessingCapIsFetchedAgainUntilItIsReady() = runBlocking { + val fetches = AtomicInteger() + val delays = DelayLog(clock) + val model = + model(scope = CoroutineScope(delays)) { request -> + when { + request.path.endsWith("/playback") -> json("{}", status = 403) + fetches.getAndIncrement() < 2 -> + json(detail(Samples.cap("cap_a", upload = Samples.processing(40)))) + else -> json(detail(Samples.cap("cap_a", title = "Ready"))) + } + } + model.load().join() + val poll = checkNotNull(model.poll) + assertEquals(6_000L, delays.next()) + + clock.advance(6.seconds - 1.milliseconds) + assertEquals(1, requests("GET", "/api/mobile/caps/cap_a")) + clock.advance(1.milliseconds) + assertEquals(12_000L, delays.next()) + assertSame(poll, model.poll) + clock.advance(12.seconds) + poll.join() + + assertEquals("Ready", model.detail?.cap?.title) + assertNull(model.poll) + assertEquals(3, requests("GET", "/api/mobile/caps/cap_a")) + } + + @Test + fun aCapThatStaysProcessingIsPolledLessOftenAndThenLeftAlone() = runBlocking { + val delays = DelayLog(clock) + val model = + model( + scope = CoroutineScope(delays), + handler = serving(Samples.cap("cap_a", upload = Samples.processing(40))), + ) + model.load().join() + val poll = checkNotNull(model.poll) + + val waits = List(34) { delays.next().also { clock.advance(it.milliseconds) } } + poll.join() + + assertEquals(listOf(6_000L, 12_000L, 24_000L) + List(31) { 30_000L }, waits) + assertEquals(35, requests("GET", "/api/mobile/caps/cap_a")) + assertNull(model.poll) + } + + @Test + fun failedPollFetchesAlsoBackOff() = runBlocking { + val fetches = AtomicInteger() + val delays = DelayLog(clock) + val model = + model(scope = CoroutineScope(delays)) { request -> + when { + request.path.endsWith("/playback") -> json("{}", status = 403) + else -> + when (val fetch = fetches.getAndIncrement()) { + in 1..2 -> json("{}", status = 500) + 3 -> json(detail(Samples.cap("cap_a", title = "Ready"))) + else -> + json(detail(Samples.cap("cap_a", upload = Samples.processing(40)))) + } + } + } + model.load().join() + val poll = checkNotNull(model.poll) + + assertEquals(6_000L, delays.next()) + clock.advance(6.seconds) + assertEquals(12_000L, delays.next()) + clock.advance(12.seconds) + assertEquals(24_000L, delays.next()) + clock.advance(24.seconds) + poll.join() + + assertEquals("Ready", model.detail?.cap?.title) + assertNull(model.poll) + assertEquals(4, requests("GET", "/api/mobile/caps/cap_a")) + } + + @Test + fun aCapWhoseTranscriptIsBeingWrittenIsPolledAndThenCaptioned() = runBlocking { + val fetches = AtomicInteger() + val model = + model( + handler = { request -> + if ( + request.path.startsWith("/api/mobile/caps/cap_a?") || + request.path == "/api/mobile/caps/cap_a" + ) { + val status = + if (fetches.getAndIncrement() == 0) "PROCESSING" else "COMPLETE" + json(detail(Samples.cap("cap_a"), transcriptionStatus = status)) + } else { + val written = fetches.get() > 1 + serving(transcript = if (written) ({ vtt() }) else null)(request) + } + } + ) + model.load().join() + assertEquals(Transcript.Unavailable(R.string.transcript_processing), model.transcript) + val video = checkNotNull(model.mediaUrl) + + val poll = checkNotNull(model.poll) + clock.advance(6.seconds) + poll.join() + + assertEquals(listOf("Hello there"), model.captions?.map { it.text }) + assertSame(video, model.mediaUrl) + assertEquals(2, requests("GET", "/api/mobile/caps/cap_a/playback")) + assertNull(model.poll) + } + + @Test + fun aTranscriptLinkThatFailsToArriveIsFetchedAgainOnRefresh() = runBlocking { + val fetches = AtomicInteger() + val playbacks = AtomicInteger() + val model = + model( + handler = { request -> + if ( + request.path.startsWith("/api/mobile/caps/cap_a?") || + request.path == "/api/mobile/caps/cap_a" + ) { + val status = + if (fetches.getAndIncrement() == 0) "PROCESSING" else "COMPLETE" + json(detail(Samples.cap("cap_a"), transcriptionStatus = status)) + } else if (request.path.endsWith("/playback")) { + when (playbacks.getAndIncrement()) { + 0 -> serving()(request) + 1 -> json("{}", status = 500) + else -> serving(transcript = { vtt() })(request) + } + } else { + serving(transcript = { vtt() })(request) + } + } + ) + model.load().join() + val video = checkNotNull(model.mediaUrl) + val poll = checkNotNull(model.poll) + clock.advance(6.seconds) + poll.join() + assertEquals(Transcript.Unavailable(R.string.transcript_missing), model.transcript) + + model.refresh().join() + + assertEquals(listOf("Hello there"), model.captions?.map { it.text }) + assertSame(video, model.mediaUrl) + assertEquals(3, requests("GET", "/api/mobile/caps/cap_a/playback")) + } + + @Test + fun playingSomeoneElsesCapCountsOneView() = runBlocking { + val model = model(handler = serving(cap = Samples.cap("cap_a", owned = false))) + model.load().join() + + checkNotNull(model.playbackStarted()).join() + + assertNull(model.playbackStarted()) + val views = + checkNotNull(server).requests.filter { it.path == "/api/mobile/caps/cap_a/views" } + assertEquals(1, views.size) + assertEquals("POST", views.single().method) + assertTrue(Regex("""\{"sessionId":"[A-Za-z0-9]{24}"\}""").matches(views.single().body)) + } + + @Test + fun playingYourOwnCapCountsNoView() = runBlocking { + val model = model(handler = serving()) + model.load().join() + + assertNull(model.playbackStarted()) + assertEquals(0, requests("POST", "/api/mobile/caps/cap_a/views")) + } + + @Test + fun aReadyCapIsNotPolled() = runBlocking { + val model = model(handler = serving()) + + model.load().join() + + assertNull(model.poll) + } + + @Test + fun theRightPasswordOpensTheCapWithItsAccessToken() = runBlocking { + val model = + model(handler = locked { body -> if ("letmein" in body) sealed else json("{}", 403) }) + model.load().join() + assertSame(Content.Locked, model.content) + + checkNotNull(model.unlock(" letmein \n")).join() + + assertEquals("Board update", model.detail?.cap?.title) + assertNull(model.unlockError) + assertFalse(model.isUnlocking) + val unlock = checkNotNull(server).requests.single { it.path.endsWith("/unlock") } + assertEquals("""{"password":"letmein"}""", unlock.body) + } + + @Test + fun aWrongPasswordKeepsTheGateAndSaysWhy() = runBlocking { + val model = model(handler = locked { json("{}", status = 403) }) + model.load().join() + + checkNotNull(model.unlock("nope")).join() + + assertSame(Content.Locked, model.content) + assertEquals(CapApiError.Forbidden, model.unlockError) + assertFalse(model.isUnlocking) + } + + @Test + fun tooManyAttemptsAreReportedAsSuch() = runBlocking { + val model = model(handler = locked { json("{}", status = 400) }) + model.load().join() + + checkNotNull(model.unlock("nope")).join() + + assertEquals(CapApiError.BadRequest, model.unlockError) + } + + @Test + fun aBlankPasswordIsNotSent() = runBlocking { + val model = model(handler = locked { sealed }) + model.load().join() + + assertNull(model.unlock(" ")) + assertEquals(0, requests("POST", "/api/mobile/caps/cap_a/unlock")) + } + + private fun serving( + cap: String = Samples.cap("cap_a"), + viewer: String = "{}", + playbackUrl: (String) -> String? = { "${it}/media/demo.mp4" }, + kind: String = "mp4", + transcriptionStatus: String? = null, + transcript: (() -> Reply)? = null, + ): (RecordedRequest) -> Reply = { request -> + val base = checkNotNull(server).environment.baseUrl + when { + request.path.endsWith("/playback") -> + playbackUrl(base)?.let { url -> + val vtt = transcript?.let { "\"$base/media/demo.vtt\"" } ?: "null" + json("""{"kind":"$kind","url":"${url}","transcriptUrl":$vtt}""") + } ?: json("{}", status = 403) + request.path == "/media/demo.vtt" -> checkNotNull(transcript)() + else -> json(detail(cap, viewer, transcriptionStatus)) + } + } + + private fun vtt(status: Int = 200) = + Reply( + status, + mapOf("Content-Type" to "text/vtt"), + "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nHello there\n".toByteArray(), + ) + + @Test + fun aFinishedTranscriptBecomesTheCaptions() = runBlocking { + val model = + model(handler = serving(transcriptionStatus = "COMPLETE", transcript = { vtt() })) + + model.load().join() + + assertEquals(listOf("Hello there"), model.captions?.map { it.text }) + } + + @Test + fun captionsTurnedOffByTheOwnerStayHidden() = runBlocking { + val model = + model( + handler = + serving( + viewer = """{"settings":{"disableCaptions":true}}""", + transcript = { vtt() }, + ) + ) + + model.load().join() + + assertTrue(model.transcript is Transcript.Loaded) + assertNull(model.captions) + } + + @Test + fun aTranscriptStillBeingGeneratedIsNotFetched() = runBlocking { + val model = + model(handler = serving(transcriptionStatus = "PROCESSING", transcript = { vtt() })) + + model.load().join() + + assertEquals(Transcript.Unavailable(R.string.transcript_processing), model.transcript) + assertEquals(0, requests("GET", "/media/demo.vtt")) + assertNull(model.captions) + } + + @Test + fun aCapWithoutATranscriptSaysSo() = runBlocking { + val model = model(handler = serving()) + + model.load().join() + + assertEquals(Transcript.Unavailable(R.string.transcript_missing), model.transcript) + } + + @Test + fun aCapOverItsShareLimitSaysSoInsteadOfLoadingItsTranscript() = runBlocking { + val over = """{"overShareLimit":true}""" + val someoneElses = + model(handler = serving(Samples.cap("cap_a", owned = false), viewer = over)) + someoneElses.load().join() + someoneElses.loadTranscript().join() + assertEquals(Transcript.Unavailable(R.string.cap_over_share_limit), someoneElses.transcript) + server?.close() + + val yours = model(handler = serving(viewer = over)) + yours.load().join() + yours.loadTranscript().join() + assertEquals(Transcript.Unavailable(R.string.cap_over_share_limit_owner), yours.transcript) + } + + @Test + fun refreshingRetriesATranscriptThatFailedToLoad() = runBlocking { + val attempts = AtomicInteger() + val model = + model( + handler = + serving(transcript = { vtt(if (attempts.getAndIncrement() == 0) 500 else 200) }) + ) + model.load().join() + assertEquals(Transcript.Unavailable(R.string.transcript_failed), model.transcript) + + model.refresh().join() + + assertEquals(1, model.captions?.size) + } + + @Test + fun aLoadedCapAttachesItsVideoFromTheCapOrigin() = runBlocking { + val model = model(handler = serving()) + + model.load().join() + + assertEquals("${checkNotNull(server).environment.baseUrl}/media/demo.mp4", model.mediaUrl) + assertFalse(model.playbackFailed) + } + + @Test + fun aSegmentedCapAttachesAsHls() = runBlocking { + val playlist = { base: String -> + "${base}/api/playlist?videoId=cap_a&videoType=segments-master" + } + val model = model(handler = serving(playbackUrl = playlist, kind = "hls")) + + model.load().join() + + assertEquals(playlist(checkNotNull(server).environment.baseUrl), model.mediaUrl) + assertEquals(PlaybackKind.HLS, model.mediaKind) + assertEquals(MimeTypes.APPLICATION_M3U8, model.mediaKind.mimeType) + } + + @Test + fun aProgressiveVideoKeepsItsMimeTypeFromTheFile() = runBlocking { + val model = model(handler = serving()) + + model.load().join() + + assertEquals(PlaybackKind.MP4, model.mediaKind) + assertNull(model.mediaKind.mimeType) + } + + @Test + fun aVideoOnAnHttpsStorageHostAttaches() = runBlocking { + val model = model(handler = serving(playbackUrl = { "https://storage.example/v.mp4" })) + + model.load().join() + + assertEquals("https://storage.example/v.mp4", model.mediaUrl) + } + + @Test + fun aVideoOnAnInsecureForeignHostIsRefused() = runBlocking { + val model = model(handler = serving(playbackUrl = { "http://storage.example/v.mp4" })) + + model.load().join() + + assertNull(model.mediaUrl) + assertTrue(model.playbackFailed) + } + + @Test + fun aScreenshotOrACapOverItsLimitAsksForNoVideo() = runBlocking { + for (viewer in listOf("""{"isScreenshot":true}""", """{"overShareLimit":true}""")) { + val model = model(handler = serving(viewer = viewer)) + + model.load().join() + + assertNull(model.mediaUrl) + assertFalse(model.playbackFailed) + assertEquals(0, requests("GET", "/api/mobile/caps/cap_a/playback")) + server?.close() + } + } + + @Test + fun aRefusedVideoFailsOnlyOnceTheCapHasFinishedProcessing() = runBlocking { + val processing = + model( + handler = + serving( + Samples.cap("cap_a", upload = Samples.processing(40)), + playbackUrl = { null }, + ) + ) + processing.load().join() + assertFalse(processing.playbackFailed) + server?.close() + + val ready = model(handler = serving(playbackUrl = { null })) + ready.load().join() + assertTrue(ready.playbackFailed) + } + + @Test + fun aVideoThatAttachesOnRefreshClearsTheFailure() = runBlocking { + var refused = true + val model = + model(handler = serving(playbackUrl = { if (refused) null else "$it/media/demo.mp4" })) + model.load().join() + assertTrue(model.playbackFailed) + + refused = false + model.refresh().join() + + assertEquals("${checkNotNull(server).environment.baseUrl}/media/demo.mp4", model.mediaUrl) + assertFalse(model.playbackFailed) + } + + @Test + fun aRefreshAfterThePlayerFailsAttachesTheVideoAgain() = runBlocking { + val model = model(handler = serving()) + model.load().join() + model.reportPlaybackFailure() + + model.refresh().join() + + assertEquals(2, requests("GET", "/api/mobile/caps/cap_a/playback")) + assertEquals("${checkNotNull(server).environment.baseUrl}/media/demo.mp4", model.mediaUrl) + assertFalse(model.playbackFailed) + } + + @Test + fun refreshingAttachesTheVideoOnce() = runBlocking { + val model = model(handler = serving()) + model.load().join() + + model.refresh().join() + + assertEquals(1, requests("GET", "/api/mobile/caps/cap_a/playback")) + } + + companion object { + fun detail( + cap: String, + viewer: String = "{}", + transcriptionStatus: String? = null, + chapters: String = "[]", + comments: String = "[]", + ): String = + """{"cap":$cap,"summary":null,"chapters":$chapters,""" + + """"transcriptionStatus":${transcriptionStatus?.let { "\"$it\"" }},""" + + """"comments":$comments,"shareUrl":"https://cap.so/s/cap_a","viewer":$viewer}""" + } +} + +@OptIn(InternalCoroutinesApi::class, ExperimentalCoroutinesApi::class) +private class DelayLog(clock: ModelClock) : CoroutineDispatcher(), Delay { + private val inner = UnconfinedTestDispatcher(clock.scheduler) + private val scheduled = Channel(Channel.UNLIMITED) + + suspend fun next(): Long = scheduled.receive() + + override fun isDispatchNeeded(context: CoroutineContext): Boolean = + inner.isDispatchNeeded(context) + + override fun dispatch(context: CoroutineContext, block: Runnable) { + inner.dispatch(context, block) + } + + override fun scheduleResumeAfterDelay( + timeMillis: Long, + continuation: CancellableContinuation, + ) { + inner.scheduleResumeAfterDelay(timeMillis, continuation) + scheduled.trySend(timeMillis) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapManagementTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapManagementTest.kt new file mode 100644 index 00000000000..aeb52cb9c3c --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapManagementTest.kt @@ -0,0 +1,764 @@ +package so.cap.mobile.features.cap + +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapId +import so.cap.kit.ContentReportReason +import so.cap.kit.LinkAccess +import so.cap.kit.ShareTarget +import so.cap.kit.SnapshotCache +import so.cap.mobile.app.ApiServer +import so.cap.mobile.app.ApiServer.Companion.json +import so.cap.mobile.app.HeldReply +import so.cap.mobile.app.LibraryModel +import so.cap.mobile.app.ModelClock +import so.cap.mobile.app.RecordedRequest +import so.cap.mobile.app.Reply +import so.cap.mobile.app.Samples +import so.cap.mobile.app.SessionModel +import so.cap.mobile.features.cap.CapDetailModelTest.Companion.detail + +class CapManagementTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private var server: ApiServer? = null + private lateinit var session: SessionModel + + @After + fun stopTheServer() { + server?.close() + } + + private suspend fun loaded( + cap: String = Samples.cap("cap_a"), + capScope: CoroutineScope = clock.scope, + handler: (RecordedRequest) -> Reply?, + ): CapDetailModel { + val started = ApiServer { request -> + handler(request) + ?: if (request.method == "GET" && request.path == "/api/mobile/caps/cap_a") { + json(detail(cap)) + } else { + json("{}", status = 404) + } + } + server = started + val api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + session = SessionModel(api, SnapshotCache(folder.root), Samples.richie, clock.scope) + val model = + CapDetailModel( + ShareTarget(checkNotNull(CapId.parse("cap_a"))), + api, + OkHttpClient(), + session, + capScope, + ) + model.load().join() + return model + } + + private fun sent(method: String, path: String) = + checkNotNull(server).requests.filter { it.method == method && it.path == path } + + private val toast + get() = session.toasts.current.value?.message + + private val CapDetailModel.cap + get() = checkNotNull(detail).cap + + private fun withLink(cap: String, access: String, restricted: Boolean) = + cap.dropLast(1) + ""","linkAccess":"$access","linkRestricted":$restricted}""" + + @Test + fun makingACapPrivateShowsAtOnceAndSaysWhoCanView() = runBlocking { + val held = + HeldReply(json(Samples.cap("cap_a", isPublic = false, title = "From the server"))) + val model = loaded { if (it.path.endsWith("/sharing")) held.answer() else null } + + val change = checkNotNull(model.management.setPublic(false)) + held.arrived.await() + assertFalse(model.cap.isPublic) + assertTrue(model.management.updatingSharing) + + held.release.complete(Unit) + change.join() + assertEquals( + """{"public":false}""", + sent("PATCH", "/api/mobile/caps/cap_a/sharing").single().body, + ) + assertEquals("Cap cap_a", model.cap.title) + assertFalse(model.management.updatingSharing) + assertEquals("Only you and your team can view", toast) + } + + @Test + fun makingACapPublicSaysAnyoneCanView() = runBlocking { + val model = + loaded(Samples.cap("cap_a", isPublic = false)) { + if (it.path.endsWith("/sharing")) json(Samples.cap("cap_a")) else null + } + + model.management.setPublic(true)?.join() + + assertTrue(model.cap.isPublic) + assertEquals("Anyone with the link can view", toast) + } + + @Test + fun aRefusedSharingChangeKeepsARenameThatLandedMeanwhile() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + val model = + loaded(Samples.cap("cap_a", title = "Walkthrough")) { + when { + it.path.endsWith("/sharing") -> held.answer() + it.path.endsWith("/title") -> json(Samples.cap("cap_a", title = "Renamed")) + else -> null + } + } + + val change = checkNotNull(model.management.setPublic(false)) + held.arrived.await() + checkNotNull(model.management.rename("Renamed")).join() + assertEquals("Renamed", model.cap.title) + + held.release.complete(Unit) + change.join() + assertEquals("Renamed", model.cap.title) + assertTrue(model.cap.isPublic) + } + + @Test + fun aDeletedCapClosesItsPageEvenWhenNobodyWaitsForTheReply() = runBlocking { + val held = HeldReply(json("""{"success":true}""")) + val model = loaded { + if (it.method == "DELETE" && it.path == "/api/mobile/caps/cap_a") held.answer() + else null + } + + val deleting = checkNotNull(model.management.delete()) + held.arrived.await() + assertFalse(model.management.isGone) + + held.release.complete(Unit) + assertTrue(deleting.await()) + assertTrue(model.management.isGone) + assertEquals("Cap deleted", toast) + } + + @Test + fun aRefusedDeleteKeepsThePageOpen() = runBlocking { + val model = loaded { if (it.method == "DELETE") json("{}", status = 500) else null } + + assertFalse(checkNotNull(model.management.delete()).await()) + assertFalse(model.management.isGone) + } + + private suspend fun libraryOf(): LibraryModel { + session.start()?.join() + val library = session.library(checkNotNull(session.currentLibraryKey)) + library.loadIfNeeded().join() + return library + } + + private fun libraryRoutes(request: RecordedRequest, vararg caps: String): Reply? = + when { + request.path.startsWith("/api/mobile/caps?") -> json(Samples.page(caps.toList())) + request.path == "/api/mobile/bootstrap" -> json(Samples.bootstrap()) + request.path == "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + else -> null + } + + @Test + fun aRenameFinishesInTheLibraryAfterThePageIsGone() = runBlocking { + val capScope = CoroutineScope(clock.scope.coroutineContext + SupervisorJob()) + val held = HeldReply(json(Samples.cap("cap_a", title = "Renamed"))) + val walkthrough = Samples.cap("cap_a", title = "Walkthrough") + val model = + loaded(walkthrough, capScope) { + if (it.path.endsWith("/title")) held.answer() else libraryRoutes(it, walkthrough) + } + val library = libraryOf() + + val renaming = checkNotNull(model.management.rename("Renamed")) + held.arrived.await() + capScope.cancel() + held.release.complete(Unit) + renaming.join() + + assertEquals(listOf("Renamed"), library.caps.map { it.title }) + assertEquals("Title updated", toast) + } + + @Test + fun aBlockFinishesInTheLibraryAfterThePageIsGone() = runBlocking { + val capScope = CoroutineScope(clock.scope.coroutineContext + SupervisorJob()) + val held = HeldReply(json("""{"success":true}""")) + val someoneElses = Samples.cap("cap_a", owned = false) + val model = + loaded(someoneElses, capScope) { + if (it.path == "/api/mobile/user/blocks") { + held.answer() + } else { + libraryRoutes(it, someoneElses) + } + } + val library = libraryOf() + + val blocking = checkNotNull(model.management.blockOwner()) + held.arrived.await() + capScope.cancel() + held.release.complete(Unit) + blocking.join() + + assertEquals(emptyList(), library.caps.map { it.id }) + assertEquals("User blocked", toast) + } + + @Test + fun aSharingReplyOvertakenFromTheLibraryShowsTheNewerChoice() = runBlocking { + val held = HeldReply(json(Samples.cap("cap_a", isPublic = false))) + val sharing = AtomicInteger() + val model = loaded { + when { + !it.path.endsWith("/sharing") -> libraryRoutes(it, Samples.cap("cap_a")) + sharing.getAndIncrement() == 0 -> held.answer() + else -> json(Samples.cap("cap_a", isPublic = true)) + } + } + val library = libraryOf() + + val detailChange = checkNotNull(model.management.setPublic(false)) + held.arrived.await() + val libraryChange = checkNotNull(session.setPublic(library.caps.single(), isPublic = true)) + held.release.complete(Unit) + detailChange.join() + libraryChange.join() + + assertTrue(model.cap.isPublic) + assertTrue(library.caps.single().isPublic) + } + + @Test + fun aDetailReadThatStartedBeforeARenameKeepsTheNewTitle() = runBlocking { + val walkthrough = Samples.cap("cap_a", title = "Walkthrough") + val held = HeldReply(json(detail(walkthrough))) + val reads = AtomicInteger() + val model = + loaded(walkthrough) { + when { + it.path.endsWith("/title") -> json(Samples.cap("cap_a", title = "Roadmap")) + it.method == "GET" && + it.path == "/api/mobile/caps/cap_a" && + reads.getAndIncrement() == 1 -> held.answer() + else -> libraryRoutes(it, walkthrough) + } + } + val library = libraryOf() + + val refresh = model.refresh() + held.arrived.await() + checkNotNull(model.management.rename("Roadmap")).join() + held.release.complete(Unit) + refresh.join() + + assertEquals("Roadmap", model.cap.title) + assertEquals("Roadmap", library.caps.single().title) + } + + @Test + fun aDetailReadThatStartedBeforeARenameStillShowsTheCapFinished() = runBlocking { + val processing = + Samples.cap("cap_a", title = "Walkthrough", upload = Samples.processing(40)) + val finished = + Samples.cap("cap_a", title = "Walkthrough", upload = Samples.upload("complete")) + val held = HeldReply(json(detail(finished))) + val reads = AtomicInteger() + val model = + loaded(processing) { + when { + it.path.endsWith("/title") -> + json( + Samples.cap("cap_a", title = "Roadmap", upload = Samples.processing(40)) + ) + it.method == "GET" && + it.path == "/api/mobile/caps/cap_a" && + reads.getAndIncrement() == 1 -> held.answer() + else -> libraryRoutes(it, processing) + } + } + val library = libraryOf() + + val refresh = model.refresh() + held.arrived.await() + checkNotNull(model.management.rename("Roadmap")).join() + held.release.complete(Unit) + refresh.join() + + assertEquals("Roadmap", model.cap.title) + assertFalse(model.cap.isProcessing) + assertEquals("Roadmap", library.caps.single().title) + assertFalse(library.caps.single().isProcessing) + } + + @Test + fun aDetailReadThatStartedBeforeARenameKeepsALaterSharingChangeInTheLibrary() = runBlocking { + val walkthrough = Samples.cap("cap_a", title = "Walkthrough") + val held = HeldReply(json(detail(walkthrough))) + val reads = AtomicInteger() + val model = + loaded(walkthrough) { + when { + it.path.endsWith("/title") -> json(Samples.cap("cap_a", title = "Roadmap")) + it.path.endsWith("/sharing") -> + json(Samples.cap("cap_a", title = "Roadmap", isPublic = false)) + it.method == "GET" && + it.path == "/api/mobile/caps/cap_a" && + reads.getAndIncrement() == 1 -> held.answer() + else -> libraryRoutes(it, walkthrough) + } + } + val library = libraryOf() + + val refresh = model.refresh() + held.arrived.await() + checkNotNull(model.management.rename("Roadmap")).join() + checkNotNull(session.setPublic(library.caps.single(), isPublic = false)).join() + held.release.complete(Unit) + refresh.join() + + assertEquals("Roadmap", model.cap.title) + assertEquals("Roadmap", library.caps.single().title) + assertFalse(library.caps.single().isPublic) + } + + @Test + fun aSharingReplyThatLandsAfterARenameKeepsTheNewTitle() = runBlocking { + val held = HeldReply(json(Samples.cap("cap_a", title = "Walkthrough", isPublic = false))) + val walkthrough = Samples.cap("cap_a", title = "Walkthrough") + val model = + loaded(walkthrough) { + when { + it.path.endsWith("/sharing") -> held.answer() + it.path.endsWith("/title") -> json(Samples.cap("cap_a", title = "Roadmap")) + else -> libraryRoutes(it, walkthrough) + } + } + val library = libraryOf() + + val sharing = checkNotNull(model.management.setPublic(false)) + held.arrived.await() + checkNotNull(model.management.rename("Roadmap")).join() + held.release.complete(Unit) + sharing.join() + + assertEquals("Roadmap", model.cap.title) + assertFalse(model.cap.isPublic) + assertEquals(listOf("Roadmap"), library.caps.map { it.title }) + assertFalse(library.caps.single().isPublic) + } + + @Test + fun aRenameReplyThatLandsAfterASharingChangeKeepsTheNewSharing() = runBlocking { + val held = HeldReply(json(Samples.cap("cap_a", title = "Roadmap", isPublic = true))) + val walkthrough = Samples.cap("cap_a", title = "Walkthrough") + val model = + loaded(walkthrough) { + when { + it.path.endsWith("/title") -> held.answer() + it.path.endsWith("/sharing") -> json(Samples.cap("cap_a", isPublic = false)) + else -> libraryRoutes(it, walkthrough) + } + } + val library = libraryOf() + + val renaming = checkNotNull(model.management.rename("Roadmap")) + held.arrived.await() + checkNotNull(model.management.setPublic(false)).join() + held.release.complete(Unit) + renaming.join() + + assertEquals("Roadmap", model.cap.title) + assertFalse(model.cap.isPublic) + assertEquals(listOf("Roadmap"), library.caps.map { it.title }) + assertFalse(library.caps.single().isPublic) + } + + @Test + fun aRefusedChangeIsUndoneAndSaysWhy() = runBlocking { + val model = loaded { if (it.path.endsWith("/sharing")) json("{}", status = 500) else null } + + model.management.setPublic(false)?.join() + + assertTrue(model.cap.isPublic) + assertEquals(CapApiError.Server(500).description, toast) + } + + @Test + fun aSecondChangeWaitsForTheFirstToFinish() = runBlocking { + val held = HeldReply(json(Samples.cap("cap_a", isPublic = false))) + val model = loaded { if (it.path.endsWith("/sharing")) held.answer() else null } + + val first = checkNotNull(model.management.setPublic(false)) + held.arrived.await() + assertNull(model.management.setPublic(true)) + + held.release.complete(Unit) + first.join() + assertEquals(1, sent("PATCH", "/api/mobile/caps/cap_a/sharing").size) + } + + @Test + fun limitingTheLinkToTheOrganizationSaysSo() = runBlocking { + val model = + loaded(withLink(Samples.cap("cap_a"), "anyone", restricted = false)) { + if (it.path.endsWith("/sharing")) { + json(withLink(Samples.cap("cap_a"), "restricted", restricted = true)) + } else { + null + } + } + + model.management.setLinkAccess(LinkAccess.RESTRICTED)?.join() + + assertEquals( + """{"public":true,"linkAccess":"restricted"}""", + sent("PATCH", "/api/mobile/caps/cap_a/sharing").single().body, + ) + assertEquals(LinkAccess.RESTRICTED, model.cap.linkAccess) + assertEquals("Only your organization's emails can view", toast) + } + + @Test + fun restrictingAPrivateCapPublishesItBeforeChoosingTheAudience() = runBlocking { + val writes = AtomicInteger() + val model = + loaded(Samples.cap("cap_a", isPublic = false)) { + if (it.path.endsWith("/sharing")) { + val write = writes.getAndIncrement() + if (write == 0 && it.body.contains("linkAccess")) { + json("{}", status = 409) + } else if (write == 0) { + json(Samples.cap("cap_a")) + } else { + json(withLink(Samples.cap("cap_a"), "restricted", restricted = true)) + } + } else { + null + } + } + + model.management.setAudience(isPublic = true, LinkAccess.RESTRICTED)?.join() + + assertEquals( + listOf("""{"public":true}""", """{"public":true,"linkAccess":"restricted"}"""), + sent("PATCH", "/api/mobile/caps/cap_a/sharing").map { it.body }, + ) + assertEquals(LinkAccess.RESTRICTED, model.cap.linkAccess) + assertEquals("Only your organization's emails can view", toast) + } + + @Test + fun aRefusedAudienceChoiceIsMadePrivateAgain() = runBlocking { + val writes = AtomicInteger() + val model = + loaded(Samples.cap("cap_a", isPublic = false)) { + if (it.path.endsWith("/sharing")) { + when (writes.getAndIncrement()) { + 0 -> json(Samples.cap("cap_a")) + 1 -> json("{}", status = 403) + else -> json(Samples.cap("cap_a", isPublic = false)) + } + } else { + null + } + } + + model.management.setAudience(isPublic = true, LinkAccess.ANYONE)?.join() + + assertEquals( + listOf( + """{"public":true}""", + """{"public":true,"linkAccess":"anyone"}""", + """{"public":false}""", + ), + sent("PATCH", "/api/mobile/caps/cap_a/sharing").map { it.body }, + ) + assertFalse(model.cap.isPublic) + } + + @Test + fun aFailedAudienceUndoShowsTheAccessStillOnTheServer() = runBlocking { + val writes = AtomicInteger() + val reads = AtomicInteger() + val model = + loaded(Samples.cap("cap_a", isPublic = false)) { + when { + it.path.endsWith("/sharing") -> + when (writes.getAndIncrement()) { + 0 -> json(Samples.cap("cap_a")) + 1 -> json("{}", status = 403) + else -> json("{}", status = 500) + } + it.method == "GET" && + it.path == "/api/mobile/caps/cap_a" && + reads.getAndIncrement() > 0 -> json(detail(Samples.cap("cap_a"))) + else -> null + } + } + + model.management.setAudience(isPublic = true, LinkAccess.ANYONE)?.join() + + assertTrue(model.cap.isPublic) + } + + @Test + fun openingTheLinkToAnyoneSaysSo() = runBlocking { + val model = + loaded(withLink(Samples.cap("cap_a"), "restricted", restricted = true)) { + if (it.path.endsWith("/sharing")) { + json(withLink(Samples.cap("cap_a"), "anyone", restricted = false)) + } else { + null + } + } + + model.management.setLinkAccess(LinkAccess.ANYONE)?.join() + + assertEquals(LinkAccess.ANYONE, model.cap.linkAccess) + assertEquals("Anyone with the link can view", toast) + } + + @Test + fun aRefusedLinkChangeKeepsTheOldAccess() = runBlocking { + val model = + loaded(withLink(Samples.cap("cap_a"), "anyone", restricted = false)) { + if (it.path.endsWith("/sharing")) json("{}", status = 409) else null + } + + model.management.setLinkAccess(LinkAccess.RESTRICTED)?.join() + + assertEquals(LinkAccess.ANYONE, model.cap.linkAccess) + assertEquals(CapApiError.Conflict.description, toast) + } + + @Test + fun aPrivateCapHasNoLinkAccessToChange() = runBlocking { + val model = loaded(Samples.cap("cap_a", isPublic = false)) { null } + + assertNull(model.management.setLinkAccess(LinkAccess.RESTRICTED)) + assertEquals(0, sent("PATCH", "/api/mobile/caps/cap_a/sharing").size) + } + + @Test + fun renamingTrimsTheTitleAndKeepsTheFirst255Characters() = runBlocking { + val long = "a".repeat(300) + val model = loaded { + if (it.path.endsWith("/title")) { + json(Samples.cap("cap_a", title = long.take(255))) + } else { + null + } + } + + model.management.rename(" $long ")?.join() + + assertEquals( + """{"title":"${long.take(255)}"}""", + sent("PATCH", "/api/mobile/caps/cap_a/title").single().body, + ) + assertEquals(long.take(255), model.cap.title) + assertEquals("Title updated", toast) + } + + @Test + fun aBlankOrUnchangedTitleIsNotSent() = runBlocking { + val model = loaded(Samples.cap("cap_a", title = "Walkthrough")) { null } + + assertNull(model.management.rename(" ")) + assertNull(model.management.rename(" Walkthrough ")) + assertEquals(0, sent("PATCH", "/api/mobile/caps/cap_a/title").size) + } + + @Test + fun aRefusedRenameKeepsTheTitleAndSaysWhy() = runBlocking { + val model = + loaded(Samples.cap("cap_a", title = "Walkthrough")) { + if (it.path.endsWith("/title")) json("{}", status = 500) else null + } + + model.management.rename("Roadmap")?.join() + + assertEquals("Walkthrough", model.cap.title) + assertEquals(CapApiError.Server(500).description, toast) + } + + private fun isProtected(cap: String) = + cap.replace(""""protected":false""", """"protected":true""") + + @Test + fun settingAPasswordProtectsTheCap() = runBlocking { + val model = loaded { + if (it.path.endsWith("/password")) json(isProtected(Samples.cap("cap_a"))) else null + } + + val saved = checkNotNull(model.management.setPassword("letmein")).await() + + assertTrue(saved) + assertEquals( + """{"password":"letmein"}""", + sent("PATCH", "/api/mobile/caps/cap_a/password").single().body, + ) + assertTrue(model.cap.isProtected) + assertEquals("Password set", toast) + assertTrue(model.management.passwordSaved) + } + + @Test + fun removingThePasswordSendsNull() = runBlocking { + val model = + loaded(isProtected(Samples.cap("cap_a"))) { + if (it.path.endsWith("/password")) json(Samples.cap("cap_a")) else null + } + + val saved = checkNotNull(model.management.setPassword(null)).await() + + assertTrue(saved) + assertEquals( + """{"password":null}""", + sent("PATCH", "/api/mobile/caps/cap_a/password").single().body, + ) + assertFalse(model.cap.isProtected) + assertEquals("Password removed", toast) + } + + @Test + fun aPasswordBeingSavedIsSavedOnceAndShowsAsSaving() = runBlocking { + val held = HeldReply(json(isProtected(Samples.cap("cap_a")))) + val model = loaded { if (it.path.endsWith("/password")) held.answer() else null } + + val saving = checkNotNull(model.management.setPassword("letmein")) + held.arrived.await() + assertTrue(model.management.savingPassword) + assertNull(model.management.setPassword("letmein")) + + held.release.complete(Unit) + assertTrue(saving.await()) + assertFalse(model.management.savingPassword) + assertEquals(1, sent("PATCH", "/api/mobile/caps/cap_a/password").size) + } + + @Test + fun aPasswordTooLongToUnlockIsNotSent() = runBlocking { + val model = loaded { + if (it.path.endsWith("/password")) json(isProtected(Samples.cap("cap_a"))) else null + } + + assertNull(model.management.setPassword("p".repeat(CapManagement.MAX_PASSWORD + 1))) + assertTrue( + checkNotNull(model.management.setPassword("p".repeat(CapManagement.MAX_PASSWORD))) + .await() + ) + + assertEquals(1, sent("PATCH", "/api/mobile/caps/cap_a/password").size) + } + + @Test + fun aRefusedPasswordKeepsTheSheetOpenAndSaysWhy() = runBlocking { + val model = loaded { + if (it.path.endsWith("/password")) json("{}", status = 400) else null + } + + val saved = checkNotNull(model.management.setPassword("letmein")).await() + + assertFalse(saved) + assertFalse(model.cap.isProtected) + assertEquals(CapApiError.BadRequest.description, toast) + assertFalse(model.management.passwordSaved) + } + + @Test + fun reportingSendsTheReasonAndThanksTheViewer() = runBlocking { + val model = + loaded(Samples.cap("cap_a", owned = false)) { + if (it.path.endsWith("/report")) json("""{"success":true}""") else null + } + + model.management.report(ContentReportReason.COPYRIGHT).join() + + assertEquals( + """{"reason":"copyright"}""", + sent("POST", "/api/mobile/caps/cap_a/report").single().body, + ) + assertEquals("Thanks. Cap Support will review this.", toast) + } + + @Test + fun aRefusedReportSaysWhy() = runBlocking { + val model = + loaded(Samples.cap("cap_a", owned = false)) { + if (it.path.endsWith("/report")) json("{}", status = 429) else null + } + + model.management.report(ContentReportReason.OTHER).join() + + assertEquals(CapApiError.RateLimited.description, toast) + } + + @Test + fun blockingTheOwnerSendsTheirIdAndHidesTheCap() = runBlocking { + val model = + loaded(Samples.cap("cap_a", owned = false)) { + when { + it.path == "/api/mobile/user/blocks" -> json("""{"success":true}""") + it.path.startsWith("/api/mobile/caps?") -> + json(Samples.page(listOf(Samples.cap("cap_a", owned = false)))) + it.path == "/api/mobile/bootstrap" -> json(Samples.bootstrap()) + it.path == "/api/desktop/plan" -> json(Samples.plan(upgraded = true)) + else -> null + } + } + session.start()?.join() + val library = session.library(checkNotNull(session.currentLibraryKey)) + library.loadIfNeeded().join() + assertEquals(listOf("cap_a"), library.caps.map { it.id }) + + val blocked = checkNotNull(model.management.blockOwner()).await() + + assertTrue(blocked) + assertTrue(model.management.isGone) + assertEquals( + """{"userId":"user_sam"}""", + sent("POST", "/api/mobile/user/blocks").single().body, + ) + assertEquals("User blocked", toast) + assertEquals(emptyList(), library.caps.map { it.id }) + } + + @Test + fun aRefusedBlockKeepsThePageOpen() = runBlocking { + val model = + loaded(Samples.cap("cap_a", owned = false)) { + if (it.path == "/api/mobile/user/blocks") json("{}", status = 500) else null + } + + val blocked = checkNotNull(model.management.blockOwner()).await() + + assertFalse(blocked) + assertEquals(CapApiError.Server(500).description, toast) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapPageLayoutTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapPageLayoutTest.kt new file mode 100644 index 00000000000..cda88807a4d --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CapPageLayoutTest.kt @@ -0,0 +1,47 @@ +package so.cap.mobile.features.cap + +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertEquals +import org.junit.Test + +class CapPageLayoutTest { + @Test + fun aLandscapePhoneSitsTheVideoBesideTheList() { + assertEquals( + CapPageLayout.SideBySide, + capPageLayout(860.dp, 330.dp, 330.dp, keyboardOpen = false), + ) + } + + @Test + fun aShortWindowKeepsTheVideoWhileTheKeyboardIsDown() { + assertEquals( + CapPageLayout.Stacked, + capPageLayout(360.dp, 380.dp, 380.dp, keyboardOpen = false), + ) + } + + @Test + fun theKeyboardOnASmallPhoneMovesTheVideoAside() { + assertEquals( + CapPageLayout.VideoAside, + capPageLayout(360.dp, 640.dp, 300.dp, keyboardOpen = true), + ) + } + + @Test + fun aLargerPhoneKeepsTheVideoWithTheKeyboardUp() { + assertEquals( + CapPageLayout.Stacked, + capPageLayout(412.dp, 800.dp, 650.dp, keyboardOpen = true), + ) + } + + @Test + fun theKeyboardNeverTurnsAPortraitPageSideways() { + assertEquals( + CapPageLayout.VideoAside, + capPageLayout(412.dp, 800.dp, 340.dp, keyboardOpen = true), + ) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CommentsModelTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CommentsModelTest.kt new file mode 100644 index 00000000000..b6ff0c92a95 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/CommentsModelTest.kt @@ -0,0 +1,814 @@ +package so.cap.mobile.features.cap + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.kit.CapApi +import so.cap.kit.CapApiError +import so.cap.kit.CapId +import so.cap.kit.ShareTarget +import so.cap.kit.SnapshotCache +import so.cap.kit.TimelineMarkers +import so.cap.mobile.app.ApiServer +import so.cap.mobile.app.ApiServer.Companion.json +import so.cap.mobile.app.HeldReply +import so.cap.mobile.app.ModelClock +import so.cap.mobile.app.RecordedRequest +import so.cap.mobile.app.Reply +import so.cap.mobile.app.Samples +import so.cap.mobile.app.SessionModel +import so.cap.mobile.features.cap.CapDetailModel.CommentOrder +import so.cap.mobile.features.cap.CapDetailModel.Section +import so.cap.mobile.features.cap.CapDetailModelTest.Companion.detail + +class CommentsModelTest { + @get:Rule val folder = TemporaryFolder() + + private val clock = ModelClock() + private var server: ApiServer? = null + private lateinit var session: SessionModel + private lateinit var api: CapApi + + @After + fun stopTheServer() { + server?.close() + } + + private fun model( + target: ShareTarget = ShareTarget(checkNotNull(CapId.parse("cap_a"))), + page: CoroutineScope = clock.scope, + edits: CommentEdits = CommentEdits(), + handler: (RecordedRequest) -> Reply, + ): CapDetailModel { + val started = ApiServer(handler) + server = started + api = CapApi(started.environment, "Cap-Android/test", credentials = { Samples.richie }) + session = SessionModel(api, SnapshotCache(folder.root), Samples.richie, clock.scope) + return CapDetailModel(target, api, OkHttpClient(), session, page, edits) + } + + private fun reopened(edits: CommentEdits): CapDetailModel { + val target = ShareTarget(checkNotNull(CapId.parse("cap_a"))) + return CapDetailModel(target, api, OkHttpClient(), session, clock.scope, edits) + } + + private fun serving( + comments: List = emptyList(), + viewer: String = "{}", + post: (RecordedRequest) -> Reply = { json("{}", status = 500) }, + ): (RecordedRequest) -> Reply = { request -> + when { + request.method == "POST" -> post(request) + request.path.endsWith("/playback") -> json("{}", status = 404) + else -> + json( + detail( + Samples.cap("cap_a"), + viewer = viewer, + comments = comments.joinToString(",", "[", "]"), + ) + ) + } + } + + @Test + fun commentsSortOldestNewestOrByTheirMoment() = runBlocking { + val model = + model( + handler = + serving( + listOf( + comment("early", minute = 1, at = 40.0), + comment("middle", minute = 2), + comment("late", minute = 3, at = 5.0), + comment("reply", minute = 4, parent = "early"), + ) + ) + ) + model.load().join() + + assertEquals(4, model.threadedCommentCount) + assertEquals(listOf("early", "middle", "late"), model.orderedThreads.map { it.id }) + model.commentOrder = CommentOrder.Newest + assertEquals(listOf("late", "middle", "early"), model.orderedThreads.map { it.id }) + model.commentOrder = CommentOrder.Video + assertEquals(listOf("late", "early", "middle"), model.orderedThreads.map { it.id }) + } + + @Test + fun commentsTurnedOffByTheOwnerLeaveNoCommentsSection() = runBlocking { + val open = model(handler = serving(emptyList())) + open.load().join() + assertTrue(Section.Comments in open.sections) + server?.close() + + val closed = + model( + handler = serving(emptyList(), viewer = """{"settings":{"disableComments":true}}""") + ) + closed.load().join() + assertTrue(Section.Comments !in closed.sections) + } + + private fun posts() = checkNotNull(server).requests.filter { it.method == "POST" } + + @Test + fun aSentCommentShowsAsSendingUntilTheServerHasIt() = runBlocking { + val held = + HeldReply(json(comment("c_new", content = "Hello", at = 12.5, author = "user_richie"))) + val model = model(handler = serving(post = { held.answer() })) + model.load().join() + model.draft = " Hello \n" + model.composerTimestamp = 12.5 + + val send = checkNotNull(model.sendComment()) + held.arrived.await() + val local = model.threads.single().root + assertTrue(local.id.startsWith("local-")) + assertEquals("Hello", local.content) + assertEquals("user_richie", local.author.id) + assertEquals(setOf(local.id), model.pendingCommentIds) + assertTrue(model.isSendingComment) + assertEquals("", model.draft) + assertNull(model.composerTimestamp) + assertNull(model.sendComment()) + + held.release.complete(Unit) + send.join() + assertEquals(listOf("c_new"), model.threads.map { it.id }) + assertTrue(model.pendingCommentIds.isEmpty()) + assertFalse(model.isSendingComment) + assertEquals("/api/mobile/caps/cap_a/comments", posts().single().path) + assertEquals("""{"content":"Hello","timestamp":12.5}""", posts().single().body) + } + + @Test + fun aFailedSendPutsTheDraftAndItsMomentBack() = runBlocking { + val model = model(handler = serving()) + model.load().join() + model.draft = "Hello" + model.composerTimestamp = 12.5 + + checkNotNull(model.sendComment()).join() + + assertEquals("Hello", model.draft) + assertEquals(12.5, checkNotNull(model.composerTimestamp), 0.0) + assertTrue(model.threads.isEmpty()) + assertTrue(model.pendingCommentIds.isEmpty()) + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + @Test + fun aFailedSendKeepsWhatWasTypedWhileItWasSending() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + val model = model(handler = serving(listOf(comment("c1")), post = { held.answer() })) + model.load().join() + model.draft = "First" + model.composerTimestamp = 12.5 + + val send = checkNotNull(model.sendComment()) + held.arrived.await() + val parent = model.threads.first { it.id == "c1" }.root + model.startReply(parent) + model.draft = "Second" + held.release.complete(Unit) + send.join() + + assertEquals("Second", model.draft) + assertEquals(parent, model.replyingTo) + assertNull(model.composerTimestamp) + assertEquals(listOf("c1"), model.threads.map { it.id }) + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + @Test + fun aRefreshThatAlreadyHasTheSentCommentShowsItOnce() = runBlocking { + val sent = comment("c_new", content = "Hello", author = "user_richie") + val served = CopyOnWriteArrayList() + val held = HeldReply(json(sent)) + val model = + model( + handler = { request -> + if (request.method == "POST") held.answer() else serving(served)(request) + } + ) + model.load().join() + model.draft = "Hello" + + val send = checkNotNull(model.sendComment()) + held.arrived.await() + served += sent + model.refresh().join() + held.release.complete(Unit) + send.join() + + assertEquals(listOf("c_new"), checkNotNull(model.detail).comments.map { it.id }) + assertTrue(model.pendingCommentIds.isEmpty()) + } + + @Test + fun aBlankDraftIsNotSentAndALongOneIsCut() = runBlocking { + val model = model(handler = serving(post = { json(comment("c_new")) })) + model.load().join() + model.draft = " \n " + assertNull(model.sendComment()) + + model.draft = "x".repeat(2100) + checkNotNull(model.sendComment()).join() + assertEquals( + """{"content":"${"x".repeat(2000)}","timestamp":null}""", + posts().single().body, + ) + } + + @Test + fun cuttingALongCommentNeverSplitsAnEmoji() = runBlocking { + val model = model(handler = serving(post = { json(comment("c_new")) })) + model.load().join() + model.draft = "x".repeat(1999) + "\uD83D\uDE00" + + checkNotNull(model.sendComment()).join() + + assertEquals( + """{"content":"${"x".repeat(1999)}","timestamp":null}""", + posts().single().body, + ) + } + + @Test + fun composingPinsTheMomentOnceAndNeverTheVeryStart() = runBlocking { + val model = model(handler = serving()) + model.load().join() + + model.beginComposing(0.3) + assertNull(model.composerTimestamp) + model.beginComposing(10.0) + assertEquals(10.0, checkNotNull(model.composerTimestamp), 0.0) + model.beginComposing(20.0) + assertEquals(10.0, checkNotNull(model.composerTimestamp), 0.0) + assertNull(model.feedbackTimestamp(0.5)) + } + + @Test + fun aScreenshotIsNeverPinnedToAMoment() = runBlocking { + val model = model(handler = serving(viewer = """{"isScreenshot":true}""")) + model.load().join() + + model.beginComposing(10.0) + + assertNull(model.composerTimestamp) + } + + @Test + fun aReplyNamesItsParentHasNoMomentAndHighlightsTheReply() = runBlocking { + val model = + model( + handler = + serving( + listOf(comment("c1", at = 30.0)), + post = { json(comment("c_new", content = "Thanks", parent = "c1")) }, + ) + ) + model.load().join() + model.startReply(model.threads.single().root) + model.composerTimestamp = 12.5 + model.draft = "Thanks" + + checkNotNull(model.sendComment()).join() + + assertEquals( + """{"content":"Thanks","timestamp":null,"parentCommentId":"c1"}""", + posts().single().body, + ) + assertEquals(listOf("c_new"), model.threads.single().replies.map { it.id }) + assertEquals("c_new", model.highlightedCommentId) + assertNull(model.replyingTo) + assertNull(model.composerTimestamp) + } + + @Test + fun aFailedReplyStillAnswersTheSameComment() = runBlocking { + val model = model(handler = serving(listOf(comment("c1")))) + model.load().join() + val parent = model.threads.single().root + model.startReply(parent) + model.draft = "Thanks" + + checkNotNull(model.sendComment()).join() + + assertEquals(parent, model.replyingTo) + assertEquals("Thanks", model.draft) + assertTrue(model.threads.single().replies.isEmpty()) + } + + @Test + fun cancellingAReplyMakesTheNextCommentTopLevel() = runBlocking { + val model = model(handler = serving(listOf(comment("c1")))) + model.load().join() + model.startReply(model.threads.single().root) + + model.cancelReply() + + assertNull(model.replyingTo) + } + + @Test + fun aLinkToACommentHighlightsIt() = runBlocking { + val model = + model(target = ShareTarget(checkNotNull(CapId.parse("cap_a")), commentId = "c1")) { + json("{}", status = 404) + } + + assertEquals("c1", model.highlightedCommentId) + } + + @Test + fun deletingACommentTakesItsRepliesWithIt() = runBlocking { + val model = model { request -> + if (request.method == "DELETE") json("""{"success":true}""") + else + serving( + listOf( + comment("c1", author = "user_richie"), + comment("c1r", parent = "c1", minute = 1), + comment("c2", minute = 2), + ) + )(request) + } + model.load().join() + + checkNotNull(model.deleteComment(model.threads.first().root)).join() + + assertEquals(listOf("c2"), model.detail?.comments?.map { it.id }) + assertEquals(1, checkNotNull(server).count("DELETE", "/api/mobile/comments/c1")) + assertEquals("Comment deleted", session.toasts.current.value?.message) + } + + @Test + fun aRefreshFromBeforeADeleteDoesNotBringTheCommentBack() = runBlocking { + val comments = listOf(comment("c1", author = "user_richie"), comment("c2", minute = 2)) + val stale = + HeldReply( + json(detail(Samples.cap("cap_a"), comments = comments.joinToString(",", "[", "]"))) + ) + val holding = AtomicBoolean(false) + val model = model { request -> + when { + request.method == "DELETE" -> json("""{"success":true}""") + holding.get() && request.path == "/api/mobile/caps/cap_a" -> stale.answer() + else -> serving(comments)(request) + } + } + model.load().join() + holding.set(true) + + val refresh = model.refresh() + stale.arrived.await() + checkNotNull(model.deleteComment(model.threads.first().root)).join() + stale.release.complete(Unit) + refresh.join() + + assertEquals(listOf("c2"), model.detail?.comments?.map { it.id }) + } + + @Test + fun aRefreshFromBeforeASendKeepsTheSentComment() = runBlocking { + val stale = HeldReply(json(detail(Samples.cap("cap_a"), comments = "[]"))) + val holding = AtomicBoolean(false) + val model = model { request -> + when { + request.method == "POST" -> + json(comment("c_new", content = "Hello", author = "user_richie")) + holding.get() && request.path == "/api/mobile/caps/cap_a" -> stale.answer() + else -> serving()(request) + } + } + model.load().join() + holding.set(true) + + val refresh = model.refresh() + stale.arrived.await() + model.draft = "Hello" + checkNotNull(model.sendComment()).join() + stale.release.complete(Unit) + refresh.join() + + assertEquals(listOf("c_new"), model.detail?.comments?.map { it.id }) + } + + @Test + fun aRefreshWhileACommentSendsKeepsItsPlaceholder() = runBlocking { + val held = HeldReply(json(comment("c_new", content = "Hello", author = "user_richie"))) + val model = model(handler = serving(post = { held.answer() })) + model.load().join() + model.draft = "Hello" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + + model.refresh().join() + assertEquals(model.pendingCommentIds, model.threads.map { it.id }.toSet()) + assertEquals(1, model.pendingCommentIds.size) + + held.release.complete(Unit) + send.join() + assertEquals(listOf("c_new"), model.threads.map { it.id }) + } + + private fun leavablePage() = CoroutineScope(clock.scope.coroutineContext + SupervisorJob()) + + @Test + fun aCommentSentJustBeforeLeavingTheCapStillSends() = runBlocking { + val held = HeldReply(json(comment("c_new", content = "Hello", author = "user_richie"))) + val page = leavablePage() + val model = model(page = page, handler = serving(post = { held.answer() })) + model.load().join() + model.draft = "Hello" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + + page.cancel() + held.release.complete(Unit) + send.join() + + assertFalse(send.isCancelled) + assertEquals(1, posts().size) + assertNull(session.toasts.current.value) + } + + @Test + fun aRefusedCommentSentJustBeforeLeavingTheCapStillSaysSo() = runBlocking { + val held = HeldReply(json("{}", status = 500)) + val page = leavablePage() + val model = model(page = page, handler = serving(post = { held.answer() })) + model.load().join() + model.draft = "Hello" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + + page.cancel() + held.release.complete(Unit) + send.join() + + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + @Test + fun aReactionJustBeforeLeavingTheCapStillSends() = runBlocking { + val held = HeldReply(json(comment("r_new", type = "emoji", content = "😂", at = 20.0))) + val page = leavablePage() + val model = model(page = page, handler = serving(post = { held.answer() })) + model.load().join() + val react = checkNotNull(model.react("😂", 20.0)) + held.arrived.await() + + page.cancel() + held.release.complete(Unit) + react.join() + + assertFalse(react.isCancelled) + assertNull(session.toasts.current.value) + } + + @Test + fun aDeleteJustBeforeLeavingTheCapStillFinishes() = runBlocking { + val held = HeldReply(json("""{"success":true}""")) + val page = leavablePage() + val model = + model(page = page) { request -> + if (request.method == "DELETE") held.answer() + else serving(listOf(comment("c1", author = "user_richie")))(request) + } + model.load().join() + val delete = checkNotNull(model.deleteComment(model.threads.single().root)) + held.arrived.await() + + page.cancel() + held.release.complete(Unit) + delete.join() + + assertFalse(delete.isCancelled) + assertEquals("Comment deleted", session.toasts.current.value?.message) + } + + @Test + fun aCommentSentBeforeReopeningTheCapShowsOnTheReopenedPage() = runBlocking { + val held = HeldReply(json(comment("c_new", content = "Hello", author = "user_richie"))) + val edits = CommentEdits() + val page = leavablePage() + val model = model(page = page, edits = edits, handler = serving(post = { held.answer() })) + model.load().join() + model.draft = "Hello" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + page.cancel() + + val reopened = reopened(edits) + reopened.load().join() + assertTrue(reopened.threads.isEmpty()) + held.release.complete(Unit) + send.join() + + assertEquals(listOf("c_new"), reopened.detail?.comments?.map { it.id }) + } + + @Test + fun aDeleteFinishingAfterReopeningTheCapRemovesTheCommentThere() = runBlocking { + val held = HeldReply(json("""{"success":true}""")) + val edits = CommentEdits() + val page = leavablePage() + val comments = listOf(comment("c1", author = "user_richie"), comment("c2", minute = 2)) + val model = + model(page = page, edits = edits) { request -> + if (request.method == "DELETE") held.answer() else serving(comments)(request) + } + model.load().join() + val delete = checkNotNull(model.deleteComment(model.threads.first().root)) + held.arrived.await() + page.cancel() + + val reopened = reopened(edits) + reopened.load().join() + held.release.complete(Unit) + delete.join() + + assertEquals(listOf("c2"), reopened.detail?.comments?.map { it.id }) + } + + @Test + fun aCommentDeletedOnTheReopenedPageStaysGoneWhenItsSendAnswers() = runBlocking { + val held = HeldReply(json(comment("c_new", content = "Hello", author = "user_richie"))) + val edits = CommentEdits() + val page = leavablePage() + val saved = listOf(comment("c_new", content = "Hello", author = "user_richie")) + val model = + model(page = page, edits = edits) { request -> + when (request.method) { + "POST" -> held.answer() + "DELETE" -> json("""{"success":true}""") + else -> serving(saved)(request) + } + } + model.load().join() + model.draft = "Hello" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + page.cancel() + + val reopened = reopened(edits) + reopened.load().join() + checkNotNull(reopened.deleteComment(reopened.threads.single().root)).join() + held.release.complete(Unit) + send.join() + + assertTrue(checkNotNull(reopened.detail).comments.isEmpty()) + } + + @Test + fun aReplyAnsweringAfterItsParentIsDeletedStaysHidden() = runBlocking { + val held = HeldReply(json(comment("c_reply", content = "Thanks", parent = "c1"))) + val model = model { request -> + when (request.method) { + "POST" -> held.answer() + "DELETE" -> json("""{"success":true}""") + else -> serving(listOf(comment("c1", author = "user_richie")))(request) + } + } + model.load().join() + val parent = model.threads.single().root + model.startReply(parent) + model.draft = "Thanks" + val send = checkNotNull(model.sendComment()) + held.arrived.await() + + checkNotNull(model.deleteComment(parent)).join() + held.release.complete(Unit) + send.join() + + assertTrue(checkNotNull(model.detail).comments.isEmpty()) + assertTrue(model.pendingCommentIds.isEmpty()) + } + + @Test + fun aFailedDeleteKeepsTheComment() = runBlocking { + val model = model { request -> + if (request.method == "DELETE") json("{}", status = 500) + else serving(listOf(comment("c1", author = "user_richie")))(request) + } + model.load().join() + + checkNotNull(model.deleteComment(model.threads.single().root)).join() + + assertEquals(listOf("c1"), model.threads.map { it.id }) + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + @Test + fun onlyYourOwnCommentsAreYoursToDelete() = runBlocking { + val model = + model( + handler = + serving(listOf(comment("mine", author = "user_richie"), comment("theirs"))) + ) + model.load().join() + + assertEquals(listOf(true, false), model.threads.map { model.isMine(it.root) }) + } + + @Test + fun aReactionShowsAtOnceAtTheMomentAndBursts() = runBlocking { + val held = HeldReply(json(comment("r_new", type = "emoji", content = "😂", at = 20.0))) + val model = model(handler = serving(post = { held.answer() })) + model.load().join() + + val react = checkNotNull(model.react("😂", 20.0)) + held.arrived.await() + val local = checkNotNull(model.detail).comments.single() + assertEquals(setOf(local.id), model.pendingCommentIds) + assertEquals(listOf("😂"), model.bursts.map { it.emoji }) + assertEquals(listOf(CapDetailModel.ReactionCount("😂", 1, 20.0)), model.reactionCounts) + + held.release.complete(Unit) + react.join() + assertEquals(listOf("r_new"), checkNotNull(model.detail).comments.map { it.id }) + assertTrue(model.pendingCommentIds.isEmpty()) + assertEquals("/api/mobile/caps/cap_a/reactions", posts().single().path) + assertEquals("""{"content":"😂","timestamp":20.0}""", posts().single().body) + } + + @Test + fun aRefusedReactionIsTakenBack() = runBlocking { + val model = model(handler = serving()) + model.load().join() + + checkNotNull(model.react("👍", 0.2)).join() + + assertTrue(checkNotNull(model.detail).comments.isEmpty()) + assertEquals("""{"content":"👍","timestamp":null}""", posts().single().body) + assertEquals(CapApiError.Server(500).description, session.toasts.current.value?.message) + } + + @Test + fun reactionsTurnedOffSendNothing() = runBlocking { + val model = model(handler = serving(viewer = """{"settings":{"disableReactions":true}}""")) + model.load().join() + + assertNull(model.react("👍", 10.0)) + model.reactionsPassed(9.0, 9.5, playing = true) + + assertTrue(model.bursts.isEmpty()) + assertTrue(posts().isEmpty()) + } + + @Test + fun reactionsBurstAsPlaybackPassesThemButNotOnAJumpOrWhilePaused() = runBlocking { + val model = + model( + handler = serving(listOf(comment("r1", type = "emoji", content = "🙌", at = 10.2))) + ) + model.load().join() + + model.reactionsPassed(9.0, 12.0, playing = true) + model.reactionsPassed(10.0, 10.25, playing = false) + assertTrue(model.bursts.isEmpty()) + + model.reactionsPassed(10.0, 10.25, playing = true) + assertEquals(listOf("🙌"), model.bursts.map { it.emoji }) + + model.finishBurst(model.bursts.single().id) + assertTrue(model.bursts.isEmpty()) + } + + @Test + fun reactionCountsGoByCountThenEmojiFromTheirFirstMoment() = runBlocking { + val model = + model( + handler = + serving( + listOf( + comment("a", type = "emoji", content = "👍", at = 30.0), + comment("b", type = "emoji", content = "😂", at = 50.0), + comment("c", type = "emoji", content = "😂", at = 12.0), + comment("d", type = "emoji", content = "🙌"), + ) + ) + ) + model.load().join() + + assertEquals( + listOf( + CapDetailModel.ReactionCount("😂", 2, 12.0), + CapDetailModel.ReactionCount("👍", 1, 30.0), + CapDetailModel.ReactionCount("🙌", 1, null), + ), + model.reactionCounts, + ) + } + + @Test + fun choosingAMarkerHighlightsItsFirstComment() = runBlocking { + val model = + model( + handler = + serving( + listOf( + comment("r1", type = "emoji", content = "🙌", at = 10.0), + comment("c1", at = 11.0), + ) + ) + ) + model.load().join() + val markers = TimelineMarkers.build(checkNotNull(model.detail).comments, 60.0, 6) + + model.markerSelected(markers.single()) + + assertEquals("c1", model.highlightedCommentId) + assertEquals(Section.Comments, model.section) + } + + @Test + fun aMarkerOfOnlyReactionsHighlightsNothing() = runBlocking { + val model = + model( + handler = serving(listOf(comment("r1", type = "emoji", content = "🙌", at = 10.0))) + ) + model.load().join() + + model.markerSelected( + TimelineMarkers.build(checkNotNull(model.detail).comments, 60.0, 6).single() + ) + + assertNull(model.highlightedCommentId) + } + + @Test + fun theTranscriptSectionFollowsTheOwnersSettings() = runBlocking { + val open = model(handler = serving()) + open.load().join() + assertEquals(listOf(Section.Comments, Section.Summary, Section.Transcript), open.sections) + server?.close() + + val off = model(handler = serving(viewer = """{"settings":{"disableTranscript":true}}""")) + off.load().join() + assertEquals(listOf(Section.Comments, Section.Summary), off.sections) + server?.close() + + val screenshot = model(handler = serving(viewer = """{"isScreenshot":true}""")) + screenshot.load().join() + assertEquals(listOf(Section.Comments), screenshot.sections) + } + + @Test + fun theSummarySectionHidesOnlyWhenSummaryAndChaptersAreBothOff() = runBlocking { + val chaptersOnly = + model(handler = serving(viewer = """{"settings":{"disableSummary":true}}""")) + chaptersOnly.load().join() + assertTrue(Section.Summary in chaptersOnly.sections) + server?.close() + + val off = + model( + handler = + serving( + viewer = """{"settings":{"disableSummary":true,"disableChapters":true}}""" + ) + ) + off.load().join() + assertEquals(listOf(Section.Comments, Section.Transcript), off.sections) + server?.close() + + val generating = + model(handler = serving(viewer = """{"aiGenerationStatus":"PROCESSING"}""")) + generating.load().join() + assertTrue(generating.isGeneratingSummary) + } + + companion object { + fun comment( + id: String, + type: String = "text", + content: String = "Comment $id", + at: Double? = null, + parent: String? = null, + author: String = "user_sam", + minute: Int = 0, + ): String { + val created = "2026-10-29T14:%02d:00.000Z".format(minute) + return """{"id":"$id","videoId":"cap_a","type":"$type","content":"$content",""" + + """"timestamp":$at,"parentCommentId":${parent?.let { "\"$it\"" }},""" + + """"createdAt":"$created","updatedAt":"$created",""" + + """"author":{"id":"$author","name":"Sam","imageUrl":null}}""" + } + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/ControlsStateTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/ControlsStateTest.kt new file mode 100644 index 00000000000..570c033ba7b --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/ControlsStateTest.kt @@ -0,0 +1,84 @@ +package so.cap.mobile.features.cap + +import kotlin.time.Duration.Companion.milliseconds +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import so.cap.mobile.app.ModelClock + +class ControlsStateTest { + private val clock = ModelClock() + private val controls = ControlsState(clock.scope) + + @Test + fun theControlsHideThreeSecondsAfterPlaybackStarts() { + controls.playingChanged(true) + + clock.advance(ControlsState.HIDE_AFTER - 1.milliseconds) + assertTrue(controls.visible) + clock.advance(1.milliseconds) + assertFalse(controls.visible) + } + + @Test + fun theControlsStayWhilePaused() { + controls.show() + + clock.advance(ControlsState.HIDE_AFTER * 2) + + assertTrue(controls.visible) + } + + @Test + fun pausingShowsTheControlsAndKeepsThem() { + controls.playingChanged(true) + clock.advance(ControlsState.HIDE_AFTER) + assertFalse(controls.visible) + + controls.playingChanged(false) + clock.advance(ControlsState.HIDE_AFTER * 2) + + assertTrue(controls.visible) + } + + @Test + fun aTapHidesTheControlsAtOnceDuringPlaybackAndATapShowsThemAgain() { + controls.playingChanged(true) + + controls.toggle() + assertFalse(controls.visible) + + controls.toggle() + assertTrue(controls.visible) + clock.advance(ControlsState.HIDE_AFTER) + assertFalse(controls.visible) + } + + @Test + fun aTapWhilePausedLeavesTheControlsUp() { + controls.toggle() + + assertTrue(controls.visible) + } + + @Test + fun usingAControlRestartsTheCountdown() { + controls.playingChanged(true) + clock.advance(ControlsState.HIDE_AFTER - 500.milliseconds) + + controls.show() + clock.advance(ControlsState.HIDE_AFTER - 1.milliseconds) + + assertTrue(controls.visible) + } + + @Test + fun theControlsStayUpWhileScrubbing() { + controls.playingChanged(true) + controls.isScrubbing = true + + clock.advance(ControlsState.HIDE_AFTER * 2) + + assertTrue(controls.visible) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/FailedDecoderTrackerTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/FailedDecoderTrackerTest.kt new file mode 100644 index 00000000000..c07fc50c0a7 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/FailedDecoderTrackerTest.kt @@ -0,0 +1,76 @@ +package so.cap.mobile.features.cap + +import androidx.annotation.OptIn +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.mediacodec.MediaCodecInfo +import androidx.media3.exoplayer.video.MediaCodecVideoDecoderException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(UnstableApi::class) +class FailedDecoderTrackerTest { + private fun decoder(name: String, software: Boolean = false) = + MediaCodecInfo.newInstance( + name, + "video/avc", + "video/avc", + null, + !software, + software, + !software, + false, + false, + ) + + @Test + fun decodersAreUnchangedBeforeAFailure() { + val tracker = FailedDecoderTracker() + val decoders = + listOf( + decoder("c2.hardware.avc.decoder"), + decoder("c2.android.avc.decoder", software = true), + ) + + assertEquals( + listOf("c2.hardware.avc.decoder", "c2.android.avc.decoder"), + tracker.filter(decoders).map { it.name }, + ) + } + + @Test + fun unrelatedErrorsDoNotExcludeADecoder() { + val tracker = FailedDecoderTracker() + + assertFalse(tracker.excludeFailedDecoder(RuntimeException("network error"))) + } + + @Test + fun aDecoderErrorAnywhereInTheCauseChainIsExcluded() { + val tracker = FailedDecoderTracker() + val failed = decoder("c2.hardware.avc.decoder") + val software = decoder("c2.android.avc.decoder", software = true) + val decoderError = + MediaCodecVideoDecoderException(IllegalStateException("codec"), failed, null) + val playbackError = RuntimeException("playback", decoderError) + + assertTrue(tracker.excludeFailedDecoder(playbackError)) + + assertEquals( + listOf("c2.android.avc.decoder"), + tracker.filter(listOf(failed, software)).map { it.name }, + ) + } + + @Test + fun theSameDecoderIsOnlyExcludedOnce() { + val tracker = FailedDecoderTracker() + val failed = decoder("c2.hardware.avc.decoder") + val decoderError = + MediaCodecVideoDecoderException(IllegalStateException("codec"), failed, null) + + assertTrue(tracker.excludeFailedDecoder(decoderError)) + assertFalse(tracker.excludeFailedDecoder(decoderError)) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/MarkerPeaksTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/MarkerPeaksTest.kt new file mode 100644 index 00000000000..857ba11a862 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/MarkerPeaksTest.kt @@ -0,0 +1,33 @@ +package so.cap.mobile.features.cap + +import org.junit.Assert.assertEquals +import org.junit.Test +import so.cap.kit.TimelineMarker + +class MarkerPeaksTest { + private fun marker(id: String, position: Double, count: Int) = + TimelineMarker(id, position * 100, position, listOf(id), emptyList(), emptyList(), count, 0) + + @Test + fun peaksAreTheBusiestMomentsFarEnoughApartInTimeOrder() { + val markers = + listOf( + marker("a", 0.10, 4), + marker("b", 0.12, 9), + marker("c", 0.50, 2), + marker("d", 0.80, 9), + marker("e", 0.90, 1), + ) + + assertEquals(listOf("b", "c", "d"), markerPeaks(markers, 300f, 3).map { it.id }) + assertEquals(listOf("b", "d"), markerPeaks(markers, 300f, 2).map { it.id }) + assertEquals(listOf("b"), markerPeaks(markers, 30f, 3).map { it.id }) + } + + @Test + fun equalPeaksPreferTheEarlierMoment() { + val markers = listOf(marker("late", 0.6, 3), marker("early", 0.59, 3)) + + assertEquals(listOf("early"), markerPeaks(markers, 300f, 3).map { it.id }) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/PlayerStageHeightTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/PlayerStageHeightTest.kt new file mode 100644 index 00000000000..674bc82fd22 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/PlayerStageHeightTest.kt @@ -0,0 +1,50 @@ +package so.cap.mobile.features.cap + +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertEquals +import org.junit.Test + +class PlayerStageHeightTest { + @Test + fun aPortraitPhoneKeepsTheDesignedStageHeight() { + assertEquals(360.dp, capPlayerStageHeight(412.dp, 870.dp, showsPlaybackChrome = true)) + } + + @Test + fun aShortWindowLeavesRoomForThePlaybackControlsAndTitle() { + assertEquals(98.dp, capPlayerStageHeight(860.dp, 286.dp, showsPlaybackChrome = true)) + } + + @Test + fun aWindowTooShortForTheStageStillKeepsTheControlsInReach() { + assertEquals(0.dp, capPlayerStageHeight(860.dp, 150.dp, showsPlaybackChrome = true)) + } + + @Test + fun aScrollingColumnDoesNotReserveDetailHeightBelowThePlayer() { + assertEquals( + 194.dp, + capPlayerStageHeight( + 860.dp, + 286.dp, + showsPlaybackChrome = true, + reservesDetailHeight = false, + minimumHeight = 120.dp, + ), + ) + } + + @Test + fun aScrollingColumnKeepsAUsableStageWhenTheWindowIsShorterStill() { + assertEquals( + 120.dp, + capPlayerStageHeight( + 860.dp, + 150.dp, + showsPlaybackChrome = true, + reservesDetailHeight = false, + minimumHeight = 120.dp, + ), + ) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SaveToDeviceTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SaveToDeviceTest.kt new file mode 100644 index 00000000000..736da90b43d --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SaveToDeviceTest.kt @@ -0,0 +1,101 @@ +package so.cap.mobile.features.cap + +import java.io.IOException +import java.util.concurrent.LinkedBlockingQueue +import kotlin.coroutines.CoroutineContext +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import so.cap.mobile.app.ApiServer +import so.cap.mobile.app.Reply + +class SaveToDeviceTest { + @get:Rule val folder = TemporaryFolder() + + private var server: ApiServer? = null + private val video = ByteArray(64 * 1024) { (it % 251).toByte() } + + @After + fun stopTheServer() { + server?.close() + } + + private fun serving(status: Int = 200): String { + val started = ApiServer { Reply(status, mapOf("Content-Type" to "video/mp4"), video) } + server = started + return started.environment.url("media/demo.mp4") + } + + @Test + fun aDownloadedVideoIsWrittenWithItsExtension() = runBlocking { + val url = serving() + + val file = OkHttpClient().downloadVideo(url, "Board update.MOV", folder.root) + + assertEquals("mov", file.extension) + assertArrayEquals(video, file.readBytes()) + } + + @Test + fun aFileNameWithoutAVideoExtensionIsSavedAsMp4() { + assertEquals("mp4", videoExtension("cap_london")) + assertEquals("mp4", videoExtension("notes.txt")) + assertEquals("m4v", videoExtension("clip.m4v")) + assertEquals("Board update.mov", videoDisplayName("Board update.MOV")) + assertEquals("cap_london.mp4", videoDisplayName("cap_london")) + assertEquals("Cap.mp4", videoDisplayName(" .mp4")) + } + + private class QueuedDispatcher : CoroutineDispatcher() { + val tasks = LinkedBlockingQueue() + + override fun dispatch(context: CoroutineContext, block: Runnable) { + tasks.put(block) + } + } + + @Test + fun aDownloadCancelledAfterItsBodyIsWrittenLeavesNoFile() { + val url = serving() + val caller = QueuedDispatcher() + val download = + CoroutineScope(caller).launch { + OkHttpClient().downloadVideo(url, "cap_london.mp4", folder.root) + } + caller.tasks.take().run() + val written = caller.tasks.take() + + download.cancel() + written.run() + while (caller.tasks.isNotEmpty()) caller.tasks.take().run() + + assertTrue(download.isCancelled) + assertTrue(download.isCompleted) + assertTrue(folder.root.listFiles().orEmpty().isEmpty()) + } + + @Test + fun aRefusedDownloadLeavesNoFile() = runBlocking { + val url = serving(status = 404) + + val failure = + try { + OkHttpClient().downloadVideo(url, "cap_london.mp4", folder.root) + null + } catch (refused: IOException) { + refused + } + + assertEquals("HTTP 404", failure?.message) + assertTrue(folder.root.listFiles().orEmpty().isEmpty()) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SpeedNameTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SpeedNameTest.kt new file mode 100644 index 00000000000..a6b717d584b --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SpeedNameTest.kt @@ -0,0 +1,21 @@ +package so.cap.mobile.features.cap + +import java.util.Locale +import org.junit.Assert.assertEquals +import org.junit.Test +import so.cap.kit.CapViewer + +class SpeedNameTest { + @Test + fun speedsReadWithUpToTwoDecimalPlaces() { + assertEquals( + listOf("0.5×", "0.75×", "1×", "1.2×", "1.5×", "1.75×", "2×"), + CapViewer.PLAYBACK_SPEEDS.map { speedName(it, Locale.US) }, + ) + } + + @Test + fun speedsUseTheLocaleDecimalSeparator() { + assertEquals("1,75×", speedName(1.75f, Locale.GERMANY)) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SummaryTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SummaryTest.kt new file mode 100644 index 00000000000..867365199fb --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/SummaryTest.kt @@ -0,0 +1,35 @@ +package so.cap.mobile.features.cap + +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import so.cap.kit.Chapter + +class SummaryTest { + private val chapters = + listOf(Chapter("Intro", 0.0), Chapter("Snapping", 38.0), Chapter("Zoom", 96.0)) + + @Test + fun theActiveChapterIsTheLastOneStartedOnceSomethingHasPlayed() { + assertNull(activeChapter(chapters, 0.0)) + assertEquals(0, activeChapter(chapters, 0.1)) + assertEquals(0, activeChapter(chapters, 37.9)) + assertEquals(1, activeChapter(chapters, 38.0)) + assertEquals(2, activeChapter(chapters, 500.0)) + assertNull(activeChapter(emptyList(), 10.0)) + assertNull(activeChapter(listOf(Chapter("Late", 20.0)), 10.0)) + } + + @Test + fun summariesRenderBoldAndItalicMarkdown() { + val text = summaryText("**Overview.** Richie shows *new* zoom handles.") + assertEquals("Overview. Richie shows new zoom handles.", text.text) + val bold = text.spanStyles.single { it.item.fontWeight == FontWeight.SemiBold } + assertEquals("Overview.", text.text.substring(bold.start, bold.end)) + val italic = text.spanStyles.single { it.item.fontStyle == FontStyle.Italic } + assertEquals("new", text.text.substring(italic.start, italic.end)) + assertEquals("2 * 3 = 6", summaryText("2 * 3 = 6").text) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TimelineTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TimelineTest.kt new file mode 100644 index 00000000000..c387cfadc4f --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TimelineTest.kt @@ -0,0 +1,38 @@ +package so.cap.mobile.features.cap + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import so.cap.kit.Chapter + +class TimelineTest { + private val chapters = + listOf( + Chapter("Intro", 0.0), + Chapter("Snapping", 30.0), + Chapter("Zoom", 90.0), + Chapter("Late", 200.0), + ) + + @Test + fun gapsSitAtEachChapterAfterTheFirstThatStartsInsideTheVideo() { + assertEquals(listOf(0.25, 0.75), chapterGaps(chapters, duration = 120.0)) + } + + @Test + fun aChapterAtTheStartOrBeforeAnyDurationDrawsNoGap() { + assertEquals( + emptyList(), + chapterGaps(listOf(Chapter("A", 0.0), Chapter("B", 0.0)), 60.0), + ) + assertEquals(emptyList(), chapterGaps(chapters, duration = 0.0)) + } + + @Test + fun theScrubBubbleNamesTheChapterUnderTheFinger() { + assertEquals("Intro", chapterAt(chapters, 29.9)) + assertEquals("Snapping", chapterAt(chapters, 30.0)) + assertEquals("Late", chapterAt(chapters, 500.0)) + assertNull(chapterAt(listOf(Chapter("Later", 10.0)), 5.0)) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TranscriptSearchTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TranscriptSearchTest.kt new file mode 100644 index 00000000000..5fb3bcf83a9 --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/cap/TranscriptSearchTest.kt @@ -0,0 +1,27 @@ +package so.cap.mobile.features.cap + +import org.junit.Assert.assertEquals +import org.junit.Test +import so.cap.kit.TranscriptCue + +class TranscriptSearchTest { + private val cues = + listOf( + TranscriptCue(0, 0.0, 2.0, "The Café opens at nine."), + TranscriptCue(1, 2.0, 4.0, "Zoom handles are new."), + TranscriptCue(2, 4.0, 6.0, "Résumé the timeline."), + ) + + @Test + fun searchIgnoresCaseAndAccents() { + assertEquals(listOf(0), filterCues(cues, "CAFE").map { it.id }) + assertEquals(listOf(2), filterCues(cues, "resume").map { it.id }) + assertEquals(listOf(1), filterCues(cues, "zoom HAND").map { it.id }) + } + + @Test + fun anEmptySearchShowsEveryCueAndAMissShowsNone() { + assertEquals(cues, filterCues(cues, "")) + assertEquals(emptyList(), filterCues(cues, "pricing")) + } +} diff --git a/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/home/CapActionTest.kt b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/home/CapActionTest.kt new file mode 100644 index 00000000000..4aac4f2566d --- /dev/null +++ b/apps/mobile-android/app/src/test/kotlin/so/cap/mobile/features/home/CapActionTest.kt @@ -0,0 +1,42 @@ +package so.cap.mobile.features.home + +import org.junit.Assert.assertEquals +import org.junit.Test +import so.cap.mobile.app.Samples +import so.cap.mobile.features.home.CapAction.CopyLink +import so.cap.mobile.features.home.CapAction.Delete +import so.cap.mobile.features.home.CapAction.MakePrivate +import so.cap.mobile.features.home.CapAction.MakePublic +import so.cap.mobile.features.home.CapAction.Share + +class CapActionTest { + private val cap = Samples.decodedCap("a") + + @Test + fun theOwnerOfAPublicCapCanMakeItPrivateAndDeleteIt() { + assertEquals( + listOf(CopyLink, Share, MakePrivate, Delete), + CapAction.available(cap, owned = true), + ) + } + + @Test + fun theOwnerOfAPrivateCapCanMakeItPublic() { + assertEquals( + listOf(CopyLink, Share, MakePublic, Delete), + CapAction.available(cap.copy(isPublic = false), owned = true), + ) + } + + @Test + fun someoneElseCanOnlyCopyAndShare() { + assertEquals(listOf(CopyLink, Share), CapAction.available(cap, owned = false)) + } + + @Test + fun aCapWhoseLinkIsNotAnHttpsLinkIsNotShared() { + val odd = cap.copy(shareUrl = "http://cap.so/s/a") + + assertEquals(listOf(CopyLink), CapAction.available(odd, owned = false)) + } +} diff --git a/apps/mobile-android/app/src/testDebug/kotlin/so/cap/mobile/LaunchArgumentsTest.kt b/apps/mobile-android/app/src/testDebug/kotlin/so/cap/mobile/LaunchArgumentsTest.kt new file mode 100644 index 00000000000..efda3979450 --- /dev/null +++ b/apps/mobile-android/app/src/testDebug/kotlin/so/cap/mobile/LaunchArgumentsTest.kt @@ -0,0 +1,38 @@ +package so.cap.mobile + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import so.cap.kit.CapEnvironment +import so.cap.kit.CredentialSnapshot + +class LaunchArgumentsTest { + private val key = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e" + private val local = + checkNotNull(CapEnvironment.parse("http://localhost:4310", allowInsecureLocalhost = true)) + + @Test + fun aKeyAndUserForALocalServerBecomeASession() { + assertEquals( + CredentialSnapshot(key, "user_richie"), + LaunchArguments.session("$key:user_richie", local), + ) + } + + @Test + fun aSessionIsNeverSeededForAServerThatIsNotLocal() { + assertNull(LaunchArguments.session("$key:user_richie", CapEnvironment.PRODUCTION)) + val remote = + checkNotNull(CapEnvironment.parse("https://cap.example", allowInsecureLocalhost = true)) + assertNull(LaunchArguments.session("$key:user_richie", remote)) + } + + @Test + fun anArgumentThatIsNotAKeyAndAUserIsIgnored() { + assertNull(LaunchArguments.session(key, local)) + assertNull(LaunchArguments.session("nope:user_richie", local)) + assertNull(LaunchArguments.session("$key:", local)) + assertNull(LaunchArguments.session("$key:not a user", local)) + assertNull(LaunchArguments.session("", local)) + } +} diff --git a/apps/mobile-android/build.gradle.kts b/apps/mobile-android/build.gradle.kts new file mode 100644 index 00000000000..5099b7b9e68 --- /dev/null +++ b/apps/mobile-android/build.gradle.kts @@ -0,0 +1,18 @@ +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.jvm) apply false + alias(libs.plugins.kotlin.serialization) apply false + alias(libs.plugins.spotless) +} + +spotless { + kotlin { + target("*/src/**/*.kt") + ktfmt(libs.versions.ktfmt.get()).kotlinlangStyle() + } + kotlinGradle { + target("*.gradle.kts", "*/*.gradle.kts") + ktfmt(libs.versions.ktfmt.get()).kotlinlangStyle() + } +} diff --git a/apps/mobile-android/capkit/build.gradle.kts b/apps/mobile-android/capkit/build.gradle.kts new file mode 100644 index 00000000000..c65282a9769 --- /dev/null +++ b/apps/mobile-android/capkit/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.kotlin.serialization) +} + +kotlin { + jvmToolchain(17) + compilerOptions { + allWarningsAsErrors = true + } +} + +sourceSets { + test { + resources.srcDir("../../mobile-ios/CapKit/Tests/CapKitTests/Fixtures") + } +} + +dependencies { + api(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.coroutines.core) + implementation(libs.okhttp) + testImplementation(libs.junit) + testImplementation(libs.kotlinx.coroutines.test) +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiClient.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiClient.kt new file mode 100644 index 00000000000..15c6f4bc65c --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiClient.kt @@ -0,0 +1,621 @@ +package so.cap.kit + +import java.io.IOException +import java.time.Duration +import java.time.Instant +import java.util.Base64 +import kotlin.coroutines.resume +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.add +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray +import kotlinx.serialization.serializer +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Dispatcher +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response + +internal enum class HttpMethod { + GET, + POST, + PUT, + PATCH, + DELETE, +} + +internal class ApiRequest( + val method: HttpMethod = HttpMethod.GET, + val path: List, + val query: List> = emptyList(), + val body: JsonObject? = null, + val authenticated: Boolean = true, + val videoAccess: CapId? = null, +) + +data class CredentialSnapshot(val apiKey: String, val userId: String) + +class CapApi( + val environment: CapEnvironment, + private val userAgent: String, + private val credentials: () -> CredentialSnapshot?, + private val onUnauthorized: (CredentialSnapshot) -> Unit = {}, +) { + private val client = + OkHttpClient.Builder() + .followRedirects(false) + .followSslRedirects(false) + .retryOnConnectionFailure(false) + .connectTimeout(Duration.ofSeconds(30)) + .readTimeout(Duration.ofSeconds(30)) + .writeTimeout(Duration.ofSeconds(30)) + .callTimeout(Duration.ofSeconds(120)) + .dispatcher(Dispatcher().apply { maxRequestsPerHost = 6 }) + // OkHttp resends any request, a POST included, when the reply is 503 with + // Retry-After: 0, and retryOnConnectionFailure(false) does not switch that off. + .addNetworkInterceptor { chain -> + val response = chain.proceed(chain.request()) + if (response.code == 503) { + response.newBuilder().removeHeader("Retry-After").build() + } else { + response + } + } + .build() + + private val videoAccessTokens = mutableMapOf() + + internal fun makeUrl(request: ApiRequest): String { + val url = StringBuilder(environment.baseUrl) + for (segment in request.path) { + if (segment.isEmpty() || segment == "." || segment == "..") { + throw CapApiException(CapApiError.BadRequest) + } + url.append('/').append(percentEncode(segment)) + } + val query = request.query.filter { !it.second.isNullOrEmpty() } + query.forEachIndexed { index, (name, value) -> + url.append(if (index == 0) '?' else '&') + url.append(percentEncode(name)).append('=').append(percentEncode(value.orEmpty())) + } + return url.toString() + } + + private fun makeHttpRequest(request: ApiRequest): Pair { + val builder = Request.Builder().url(makeUrl(request)) + builder.header("Accept", "application/json") + builder.header("User-Agent", userAgent) + var snapshot: CredentialSnapshot? = null + if (request.authenticated) { + snapshot = credentials() ?: throw CapApiException(CapApiError.MissingSession) + builder.header("Authorization", "Bearer ${snapshot.apiKey}") + request.videoAccess?.let(::videoAccessToken)?.let { + builder.header("X-Cap-Video-Access", it) + } + } + val body = + when { + request.body != null -> request.body.toString().toByteArray().toRequestBody(json) + request.method == HttpMethod.GET || request.method == HttpMethod.DELETE -> null + else -> ByteArray(0).toRequestBody() + } + return builder.method(request.method.name, body).build() to snapshot + } + + internal suspend fun send(request: ApiRequest): String { + val (httpRequest, snapshot) = + try { + makeHttpRequest(request) + } catch (error: IllegalArgumentException) { + throw CapApiException(CapApiError.BadRequest, error) + } + + var attempt = 0 + while (true) { + val outcome = client.newCall(httpRequest).await() + val failure = outcome.exceptionOrNull() + if (failure != null) { + if ( + request.method == HttpMethod.GET && attempt == 0 && failure.isLostConnection() + ) { + attempt += 1 + continue + } + throw CapApiException(CapApiError.from(failure), failure) + } + val (status, body) = outcome.getOrThrow() + val error = CapApiError.from(status) ?: return body + if (error == CapApiError.Unauthorized && snapshot != null) onUnauthorized(snapshot) + throw CapApiException(error) + } + } + + internal suspend inline fun fetch(request: ApiRequest): Response { + val body = send(request) + return try { + CapJson.json.decodeFromString(serializer(), body) + } catch (error: IllegalArgumentException) { + throw CapApiException(CapApiError.InvalidResponse, error) + } + } + + private fun mobile( + method: HttpMethod, + vararg path: String, + query: List> = emptyList(), + body: JsonObject? = null, + authenticated: Boolean = true, + access: CapId? = null, + ) = ApiRequest(method, mobilePath + path, query, body, authenticated, access) + + private suspend fun expectSuccess(request: ApiRequest) { + if (!fetch(request).success) { + throw CapApiException(CapApiError.InvalidResponse) + } + } + + suspend fun authConfig(): AuthConfig = + fetch(mobile(HttpMethod.GET, "session", "config", authenticated = false)) + + suspend fun requestEmailCode(email: String) { + val body = buildJsonObject { put("email", EmailValidator.normalize(email)) } + expectSuccess( + mobile( + HttpMethod.POST, + "session", + "email", + "request", + body = body, + authenticated = false, + ) + ) + } + + suspend fun verifyEmailCode(email: String, code: String): ApiKeySession { + val body = buildJsonObject { + put("email", EmailValidator.normalize(email)) + put("code", code) + } + val session: ApiKeySession = + fetch( + mobile( + HttpMethod.POST, + "session", + "email", + "verify", + body = body, + authenticated = false, + ) + ) + if (!ApiKeyValidator.isPlausible(session.apiKey) || CapId.parse(session.userId) == null) { + throw CapApiException(CapApiError.InvalidResponse) + } + return session + } + + fun sessionRequestUrl(provider: String, state: String): String { + val redirectUri = percentEncode(AuthCallback.REDIRECT_URI) + return "${environment.baseUrl}${CapKit.API_PATH_PREFIX}/session/request" + + "?redirectUri=$redirectUri&provider=${percentEncode(provider)}" + + "&state=${percentEncode(state)}" + } + + suspend fun revokeSession() = expectSuccess(mobile(HttpMethod.POST, "session", "revoke")) + + suspend fun bootstrap(): Bootstrap = fetch(mobile(HttpMethod.GET, "bootstrap")) + + suspend fun setActiveOrganization(organizationId: String): Bootstrap { + val body = buildJsonObject { put("organizationId", organizationId) } + return fetch(mobile(HttpMethod.PATCH, "user", "active-organization", body = body)) + } + + suspend fun updateProfile(name: String, lastName: String?): CapUser { + val body = buildJsonObject { + put("name", name) + put("lastName", lastName) + } + return fetch(mobile(HttpMethod.PATCH, "user", "profile", body = body)) + } + + suspend fun updateProfileImage(image: EncodedImage): CapUser = + fetch(mobile(HttpMethod.PUT, "user", "profile", "image", body = image.payload)) + + suspend fun removeProfileImage(): CapUser = + fetch(mobile(HttpMethod.DELETE, "user", "profile", "image")) + + suspend fun requestAccountDeletion() { + val body = buildJsonObject { put("confirmation", "DELETE") } + expectSuccess(mobile(HttpMethod.POST, "user", "account-deletion", body = body)) + } + + suspend fun blockUser(userId: String) { + val body = buildJsonObject { put("userId", userId) } + expectSuccess(mobile(HttpMethod.POST, "user", "blocks", body = body)) + } + + suspend fun notificationPreferences(): NotificationPreferences = + fetch(mobile(HttpMethod.GET, "user", "notification-preferences")) + + suspend fun setNotification( + kind: NotificationPreferences.Kind, + enabled: Boolean, + ): NotificationPreferences { + val body = buildJsonObject { put(kind.rawValue, enabled) } + return fetch(mobile(HttpMethod.PATCH, "user", "notification-preferences", body = body)) + } + + suspend fun registerPushToken(token: String, environment: PushEnvironment) { + val body = buildJsonObject { + put("token", token) + put("environment", environment.rawValue) + } + expectSuccess(mobile(HttpMethod.POST, "user", "push-tokens", body = body)) + } + + suspend fun removePushToken(token: String) { + val body = buildJsonObject { put("token", token) } + expectSuccess(mobile(HttpMethod.POST, "user", "push-tokens", "remove", body = body)) + } + + suspend fun listCaps( + folderId: String? = null, + spaceId: String? = null, + page: Int = 1, + limit: Int = 30, + ): CapsPage { + val query = + listOf( + "folderId" to folderId, + "spaceId" to spaceId, + "page" to page.coerceAtLeast(1).toString(), + "limit" to limit.coerceIn(1, 50).toString(), + ) + return fetch(mobile(HttpMethod.GET, "caps", query = query)) + } + + suspend fun capStatuses(ids: List): List { + val unique = ids.distinct().sorted().take(25) + if (unique.isEmpty()) return emptyList() + val body = buildJsonObject { putJsonArray("ids") { unique.forEach(::add) } } + return fetch(mobile(HttpMethod.POST, "caps", "statuses", body = body)) + .caps + } + + suspend fun createFolder(name: String, color: FolderColor, spaceId: String?): Folder { + val body = buildJsonObject { + put("name", name) + put("color", color.rawValue) + if (spaceId != null) put("spaceId", spaceId) + } + return fetch(mobile(HttpMethod.POST, "folders", body = body)) + } + + suspend fun cap(id: CapId): CapDetail = + fetch(mobile(HttpMethod.GET, "caps", id.rawValue, access = id)) + + suspend fun capAccess(id: CapId): CapAccessStatus = + fetch(mobile(HttpMethod.GET, "caps", id.rawValue, "access", access = id)) + .status + + suspend fun unlockCap(id: CapId, password: String) { + val body = buildJsonObject { put("password", password) } + val unlock: CapUnlock = + fetch(mobile(HttpMethod.POST, "caps", id.rawValue, "unlock", body = body)) + if (unlock.accessToken.isEmpty() || unlock.accessToken.toByteArray().size > 4096) { + throw CapApiException(CapApiError.InvalidResponse) + } + rememberVideoAccess(id, unlock) + } + + suspend fun trackView(id: CapId, sessionId: String) { + val body = buildJsonObject { put("sessionId", sessionId) } + expectSuccess( + mobile(HttpMethod.POST, "caps", id.rawValue, "views", body = body, access = id) + ) + } + + suspend fun reportCap(id: CapId, reason: ContentReportReason) { + val body = buildJsonObject { put("reason", reason.rawValue) } + expectSuccess( + mobile(HttpMethod.POST, "caps", id.rawValue, "report", body = body, access = id) + ) + } + + suspend fun updateSharing( + id: CapId, + isPublic: Boolean, + linkAccess: LinkAccess? = null, + ): CapSummary { + val body = buildJsonObject { + put("public", isPublic) + if (linkAccess != null) put("linkAccess", linkAccess.rawValue) + } + return fetch(mobile(HttpMethod.PATCH, "caps", id.rawValue, "sharing", body = body)) + } + + suspend fun updateTitle(id: CapId, title: String): CapSummary { + val body = buildJsonObject { put("title", title) } + return fetch(mobile(HttpMethod.PATCH, "caps", id.rawValue, "title", body = body)) + } + + suspend fun updatePassword(id: CapId, password: String?): CapSummary { + val body = buildJsonObject { put("password", password) } + return fetch(mobile(HttpMethod.PATCH, "caps", id.rawValue, "password", body = body)) + } + + suspend fun deleteCap(id: CapId) = expectSuccess(mobile(HttpMethod.DELETE, "caps", id.rawValue)) + + suspend fun playback(id: CapId): Playback = + fetch(mobile(HttpMethod.GET, "caps", id.rawValue, "playback", access = id)) + + suspend fun download(id: CapId): DownloadLink = + fetch(mobile(HttpMethod.GET, "caps", id.rawValue, "download", access = id)) + + suspend fun capAnalytics(id: CapId, range: AnalyticsRange): AnalyticsResponse { + val query = listOf("range" to range.rawValue) + return fetch(mobile(HttpMethod.GET, "caps", id.rawValue, "analytics", query = query)) + } + + suspend fun organizationAnalytics( + range: AnalyticsRange, + spaceId: String? = null, + ): AnalyticsResponse { + val query = listOf("range" to range.rawValue, "spaceId" to spaceId) + return fetch(mobile(HttpMethod.GET, "analytics", query = query)) + } + + suspend fun organizationSettings(): OrganizationSettings = + fetch(mobile(HttpMethod.GET, "organization", "settings")) + + suspend fun updateOrganizationSettings( + name: String, + allowedEmailDomain: String?, + ): OrganizationSettings { + val body = buildJsonObject { + put("name", name) + put("allowedEmailDomain", allowedEmailDomain) + } + return fetch(mobile(HttpMethod.PATCH, "organization", "settings", body = body)) + } + + suspend fun updateOrganizationIcon(image: EncodedImage): OrganizationSettings = + fetch(mobile(HttpMethod.PUT, "organization", "settings", "icon", body = image.payload)) + + suspend fun removeOrganizationIcon(): OrganizationSettings = + fetch(mobile(HttpMethod.DELETE, "organization", "settings", "icon")) + + suspend fun importLoom(url: String): LoomImportResult { + val body = buildJsonObject { put("loomUrl", url) } + return fetch(mobile(HttpMethod.POST, "imports", "loom", body = body)) + } + + suspend fun createComment( + id: CapId, + content: String, + timestamp: Double?, + parentCommentId: String? = null, + ): CapComment { + val body = buildJsonObject { + put("content", content) + put("timestamp", finite(timestamp)) + if (parentCommentId != null) put("parentCommentId", parentCommentId) + } + return fetch( + mobile(HttpMethod.POST, "caps", id.rawValue, "comments", body = body, access = id) + ) + } + + suspend fun deleteComment(commentId: String) = + expectSuccess(mobile(HttpMethod.DELETE, "comments", commentId)) + + suspend fun createReaction(id: CapId, emoji: String, timestamp: Double?): CapComment { + val body = buildJsonObject { + put("content", emoji) + put("timestamp", finite(timestamp)) + } + return fetch( + mobile(HttpMethod.POST, "caps", id.rawValue, "reactions", body = body, access = id) + ) + } + + suspend fun createUpload(input: UploadRequest): UploadCreated = + fetch(mobile(HttpMethod.POST, "uploads", body = encode(input))) + + suspend fun updateUploadProgress(id: CapId, uploaded: Long, total: Long) { + val body = buildJsonObject { + put("uploaded", uploaded) + put("total", total) + } + expectSuccess(mobile(HttpMethod.POST, "uploads", id.rawValue, "progress", body = body)) + } + + suspend fun completeUpload(id: CapId, rawFileKey: String, contentLength: Long?) { + val body = buildJsonObject { + put("rawFileKey", rawFileKey) + if (contentLength != null) put("contentLength", contentLength) + } + expectSuccess(mobile(HttpMethod.POST, "uploads", id.rawValue, "complete", body = body)) + } + + suspend fun createRecording( + fileName: String, + width: Int, + height: Int, + fps: Int, + organizationId: String?, + folderId: String?, + ): RecordingCreated { + val body = buildJsonObject { + if (organizationId != null) put("organizationId", organizationId) + if (folderId != null) put("folderId", folderId) + put("fileName", fileName) + put("width", width) + put("height", height) + put("fps", fps) + } + return fetch(mobile(HttpMethod.POST, "recordings", body = body)) + } + + suspend fun recordingUploadTargets( + id: CapId, + subpaths: List, + ): Map { + val body = buildJsonObject { putJsonArray("subpaths") { subpaths.forEach(::add) } } + val request = + mobile(HttpMethod.POST, "recordings", id.rawValue, "segments", "targets", body = body) + return fetch(request).uploads + } + + suspend fun completeRecording(id: CapId, completion: RecordingCompletion) = + expectSuccess( + mobile( + HttpMethod.POST, + "recordings", + id.rawValue, + "complete", + body = encode(completion), + ) + ) + + suspend fun plan(): PlanStatus = fetch(ApiRequest(path = listOf("api", "desktop", "plan"))) + + fun authorizationHeader(url: String): String? = mediaHeaders(url)["Authorization"] + + fun mediaHeaders(url: String): Map { + val target = environment.sameOrigin(url) ?: return emptyMap() + val authorization = credentials()?.let { "Bearer ${it.apiKey}" } ?: return emptyMap() + val parts = target.pathSegments.filter { it.isNotEmpty() } + val capId = + when { + parts.size == 5 && + parts.take(3) == mobilePath + "caps" && + parts[4] == "thumbnail" -> parts[3] + parts == listOf("api", "playlist") -> target.queryParameter("videoId") + else -> null + } + val token = capId?.let(CapId::parse)?.let(::videoAccessToken) + return buildMap { + put("Authorization", authorization) + if (token != null) put("X-Cap-Video-Access", token) + } + } + + private fun videoAccessToken(id: CapId): String? = + synchronized(videoAccessTokens) { + val unlock = videoAccessTokens[id] ?: return null + if (!unlock.expiresAt.isAfter(Instant.now())) { + videoAccessTokens.remove(id) + return null + } + unlock.accessToken + } + + internal fun rememberVideoAccess(id: CapId, unlock: CapUnlock) { + synchronized(videoAccessTokens) { videoAccessTokens[id] = unlock } + } + + fun hasVideoAccess(id: CapId): Boolean = videoAccessToken(id) != null + + fun clearVideoAccess() { + synchronized(videoAccessTokens) { videoAccessTokens.clear() } + } + + private companion object { + val json = "application/json".toMediaType() + + val mobilePath = CapKit.API_PATH_PREFIX.split('/').filter { it.isNotEmpty() } + + fun finite(value: Double?): Double? { + if (value != null && !value.isFinite()) throw CapApiException(CapApiError.BadRequest) + return value + } + + inline fun encode(value: Body): JsonObject = + try { + CapJson.json.encodeToJsonElement(serializer(), value).jsonObject + } catch (error: IllegalArgumentException) { + throw CapApiException(CapApiError.BadRequest, error) + } + + const val UNRESERVED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~" + + fun percentEncode(value: String): String = + value.toByteArray().joinToString("") { byte -> + val character = byte.toInt().toChar() + if (character in UNRESERVED) character.toString() + else "%%%02X".format(byte.toInt() and 0xFF) + } + + // The failure travels as a value: with assertions on, kotlinx.coroutines rethrows a copy + // of an exception that crosses a resume, which hides the original's type and cause. + suspend fun Call.await(): Result> = + suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { cancel() } + enqueue( + object : Callback { + override fun onFailure(call: Call, e: IOException) { + continuation.resume(Result.failure(e)) + } + + override fun onResponse(call: Call, response: Response) { + continuation.resume( + try { + Result.success(response.use { it.code to it.body.string() }) + } catch (error: IOException) { + Result.failure(error) + } + ) + } + } + ) + } + } +} + +@Serializable +internal class SuccessResponse( + @Serializable(with = StrictBooleanSerializer::class) val success: Boolean +) + +@Serializable internal class RecordingTargetsResponse(val uploads: Map) + +class EncodedImage(val data: ByteArray, val contentType: String, val fileName: String) { + internal val payload: JsonObject + get() = buildJsonObject { + put("data", Base64.getEncoder().encodeToString(data)) + put("contentType", contentType) + put("fileName", fileName) + } +} + +@Serializable +data class UploadRequest( + val organizationId: String?, + val folderId: String?, + val fileName: String, + val contentType: String, + val contentLength: Long?, + val durationSeconds: Double?, + val width: Int?, + val height: Int?, + val fps: Double?, +) + +@Serializable data class RecordingCreated(val id: String, val shareUrl: String) + +@Serializable +data class RecordingCompletion( + val durationSeconds: Double, + val totalBytes: Long, + val videoSegments: List, + val audioSegments: List, +) { + @Serializable data class Segment(val index: Int, val duration: Double) +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiError.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiError.kt new file mode 100644 index 00000000000..961b3913e04 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/ApiError.kt @@ -0,0 +1,114 @@ +package so.cap.kit + +import java.io.EOFException +import java.io.IOException +import java.io.InterruptedIOException +import java.net.ConnectException +import java.net.NoRouteToHostException +import java.net.ProtocolException +import java.net.SocketException +import java.net.UnknownHostException +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.serialization.SerializationException + +sealed interface CapApiError { + data object Unauthorized : CapApiError + + data object Forbidden : CapApiError + + data object NotFound : CapApiError + + data object BadRequest : CapApiError + + data object Conflict : CapApiError + + data object PayloadTooLarge : CapApiError + + data object RateLimited : CapApiError + + data class Server(val status: Int) : CapApiError + + data class UnexpectedStatus(val status: Int) : CapApiError + + data object Offline : CapApiError + + data object TimedOut : CapApiError + + data object Cancelled : CapApiError + + data object InvalidResponse : CapApiError + + data class Transport(val detail: String) : CapApiError + + data object MissingSession : CapApiError + + val description: String + get() = + when (this) { + Unauthorized, + MissingSession -> "Your session expired. Sign in again." + Forbidden -> "You don't have access to this." + NotFound -> "This couldn't be found. It may have been deleted or moved." + BadRequest -> "Cap couldn't accept that. Check the details and try again." + Conflict -> "This changed somewhere else. Refresh and try again." + PayloadTooLarge -> "That file is too large." + RateLimited -> "Too many attempts. Wait a moment and try again." + is Server -> "Cap is having trouble right now. Try again shortly." + is UnexpectedStatus -> "Something went wrong. Try again." + Offline -> "You're offline. Check your connection and try again." + TimedOut -> "The request timed out. Try again." + Cancelled -> "The request was cancelled." + InvalidResponse -> "Cap sent an unexpected response. Update the app or try again." + is Transport -> "Couldn't reach Cap. Check your connection and try again." + } + + val isRetryable: Boolean + get() = + when (this) { + Offline, + TimedOut, + is Server, + is Transport, + RateLimited -> true + else -> false + } + + companion object { + fun from(status: Int): CapApiError? = + when (status) { + in 200..299 -> null + 400, + 422 -> BadRequest + 401 -> Unauthorized + 403 -> Forbidden + 404, + 410 -> NotFound + 409 -> Conflict + 413 -> PayloadTooLarge + 429 -> RateLimited + in 500..599 -> Server(status) + else -> UnexpectedStatus(status) + } + + fun from(error: Throwable): CapApiError = + when { + error is CapApiException -> error.error + error is CancellationException -> Cancelled + error is SerializationException -> InvalidResponse + error is InterruptedIOException -> TimedOut + error is UnknownHostException || + error is SocketException || + error.isLostConnection() -> Offline + error is ProtocolException -> InvalidResponse + else -> Transport(error.javaClass.simpleName) + } + } +} + +class CapApiException(val error: CapApiError, cause: Throwable? = null) : + Exception(error.description, cause) + +internal fun Throwable.isLostConnection(): Boolean = + (this is SocketException && this !is ConnectException && this !is NoRouteToHostException) || + this is EOFException || + (this is IOException && cause is EOFException) diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/CapKit.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/CapKit.kt new file mode 100644 index 00000000000..4ff45effc38 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/CapKit.kt @@ -0,0 +1,5 @@ +package so.cap.kit + +object CapKit { + const val API_PATH_PREFIX = "/api/mobile" +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Decoding.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Decoding.kt new file mode 100644 index 00000000000..b11da1bd193 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Decoding.kt @@ -0,0 +1,212 @@ +package so.cap.kit + +import java.time.Instant +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter +import java.time.format.DateTimeParseException +import java.time.temporal.ChronoUnit +import kotlin.math.roundToInt +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.doubleOrNull + +object CapJson { + val json = Json { + ignoreUnknownKeys = true + explicitNulls = false + encodeDefaults = true + } + + private val shape = + Regex("""(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?)(Z|[+-]\d{2}:?\d{2})""") + + fun parseDate(value: String): Instant? { + val (local, offset) = shape.matchEntire(value)?.destructured ?: return null + val zone = if (offset.length == 5) offset.replaceRange(3, 3, ":") else offset + return try { + OffsetDateTime.parse(local + zone).toInstant() + } catch (_: DateTimeParseException) { + null + } + } +} + +interface RawValue { + val rawValue: String +} + +internal open class RawValueSerializer( + serialName: String, + private val cases: List, + private val unknownCase: E? = null, +) : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor(serialName, PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: E) = encoder.encodeString(value.rawValue) + + override fun deserialize(decoder: Decoder): E { + val raw = decoder.decodeString() + return cases.firstOrNull { it.rawValue == raw } + ?: unknownCase + ?: throw SerializationException("Unknown ${descriptor.serialName} value") + } +} + +internal object NumberSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.Number", PrimitiveKind.DOUBLE) + + override fun serialize(encoder: Encoder, value: Double) = encoder.encodeDouble(value) + + override fun deserialize(decoder: Decoder): Double { + val primitive = decoder.asJson().decodeJsonElement() as? JsonPrimitive + return primitive?.takeUnless { it.isString }?.doubleOrNull?.takeIf { it.isFinite() } + ?: throw SerializationException("Expected a JSON number") + } +} + +internal object CountSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.Count", PrimitiveKind.INT) + + override fun serialize(encoder: Encoder, value: Int) = encoder.encodeInt(value) + + override fun deserialize(decoder: Decoder): Int = + NumberSerializer.deserialize(decoder).coerceIn(0.0, Int.MAX_VALUE.toDouble()).roundToInt() +} + +internal object StrictBooleanSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.Boolean", PrimitiveKind.BOOLEAN) + + override fun serialize(encoder: Encoder, value: Boolean) = encoder.encodeBoolean(value) + + override fun deserialize(decoder: Decoder): Boolean { + val primitive = decoder.asJson().decodeJsonElement() as? JsonPrimitive + return when (primitive?.takeUnless { it.isString }?.content) { + "true" -> true + "false" -> false + else -> throw SerializationException("Expected a JSON boolean") + } + } +} + +internal object InstantSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.Instant", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Instant) = + encoder.encodeString( + DateTimeFormatter.ISO_INSTANT.format(value.truncatedTo(ChronoUnit.SECONDS)) + ) + + override fun deserialize(decoder: Decoder): Instant = + CapJson.parseDate(decoder.decodeString()) + ?: throw SerializationException("Invalid ISO 8601 date") +} + +internal open class LenientSerializer( + private val strict: KSerializer, + private val fallback: T, +) : KSerializer { + override val descriptor: SerialDescriptor = strict.descriptor + + override fun serialize(encoder: Encoder, value: T) = strict.serialize(encoder, value) + + // With explicitNulls off, the tree decoder calls a nullable serialiser for an absent key, and + // decodeJsonElement then throws NoSuchElementException; the null mark is the supported check. + @OptIn(ExperimentalSerializationApi::class) + override fun deserialize(decoder: Decoder): T { + val json = decoder.asJson() + val element = + if (descriptor.isNullable && !json.decodeNotNullMark()) JsonNull + else json.decodeJsonElement() + return try { + json.json.decodeFromJsonElement(strict, element) + } catch (_: IllegalArgumentException) { + fallback + } + } +} + +internal open class NullFallbackSerializer( + private val strict: KSerializer, + private val fallback: T, +) : KSerializer { + override val descriptor: SerialDescriptor = strict.descriptor + + override fun serialize(encoder: Encoder, value: T) = strict.serialize(encoder, value) + + override fun deserialize(decoder: Decoder): T { + val json = decoder.asJson() + val element = json.decodeJsonElement() + return if (element is JsonNull) fallback + else json.json.decodeFromJsonElement(strict, element) + } +} + +internal class LossyListSerializer(private val element: KSerializer) : KSerializer> { + private val strict = ListSerializer(element) + + override val descriptor: SerialDescriptor = strict.descriptor + + override fun serialize(encoder: Encoder, value: List) = strict.serialize(encoder, value) + + override fun deserialize(decoder: Decoder): List { + val json = decoder.asJson() + val items = + when (val array = json.decodeJsonElement()) { + is JsonNull -> return emptyList() + is JsonArray -> array + else -> throw SerializationException("Expected a JSON array") + } + return items.mapNotNull { + try { + json.json.decodeFromJsonElement(element, it) + } catch (_: IllegalArgumentException) { + null + } + } + } +} + +internal object LenientCountSerializer : LenientSerializer(CountSerializer, 0) + +internal object LenientNullableCountSerializer : + LenientSerializer(CountSerializer.nullable, null) + +internal object LenientNumberSerializer : LenientSerializer(NumberSerializer, 0.0) + +internal object LenientNullableNumberSerializer : + LenientSerializer(NumberSerializer.nullable, null) + +internal object LenientFalseSerializer : LenientSerializer(StrictBooleanSerializer, false) + +internal object LenientNullableBooleanSerializer : + LenientSerializer(StrictBooleanSerializer.nullable, null) + +internal object LenientNullableStringSerializer : + LenientSerializer(String.serializer().nullable, null) + +internal object EmptyWhenNullSerializer : NullFallbackSerializer(String.serializer(), "") + +internal object FalseWhenNullSerializer : + NullFallbackSerializer(StrictBooleanSerializer, false) + +private fun Decoder.asJson(): JsonDecoder = + this as? JsonDecoder ?: throw SerializationException("Cap models decode from JSON only") diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Environment.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Environment.kt new file mode 100644 index 00000000000..10024f8720e --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Environment.kt @@ -0,0 +1,158 @@ +package so.cap.kit + +import java.io.ByteArrayOutputStream +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +@JvmInline +value class CapEnvironment private constructor(val baseUrl: String) { + fun url(path: String): String = "$baseUrl/$path" + + fun isSameOrigin(url: String): Boolean = sameOrigin(url) != null + + internal fun sameOrigin(url: String): HttpUrl? { + val base = baseUrl.toHttpUrlOrNull() ?: return null + return url.toHttpUrlOrNull()?.takeIf { + it.scheme == base.scheme && it.host == base.host && it.port == base.port + } + } + + fun shareUrl(capId: CapId): String = "$baseUrl/s/${capId.rawValue}" + + fun shareUrl(capId: CapId, seconds: Double): String { + val whole = (if (seconds.isFinite()) seconds else 0.0).toLong() + return if (whole > 0) "${shareUrl(capId)}?t=$whole" else shareUrl(capId) + } + + val privacyUrl: String + get() = url("privacy") + + val termsUrl: String + get() = url("terms") + + val supportUrl: String + get() = url("docs") + + val dashboardUrl: String + get() = url("dashboard") + + val upgradeUrl: String + get() = url("dashboard/settings/organization/billing") + + companion object { + val PRODUCTION = CapEnvironment("https://cap.so") + + private val hostPattern = Regex("""[a-z0-9._-]+|\[[0-9a-f:.]+]""") + private val addressLabel = Regex("0|[1-9][0-9]{0,2}") + + fun parse(string: String, allowInsecureLocalhost: Boolean): CapEnvironment? { + val parts = UrlParts.parse(string.trim()) ?: return null + val scheme = parts.scheme?.lowercase() ?: return null + val host = parts.host?.lowercase() ?: return null + if (!hostPattern.matches(host)) return null + if (parts.userInfo != null || parts.query != null || parts.fragment != null) return null + if (parts.path.isNotEmpty() && parts.path != "/") return null + val port = parts.port?.let { ":$it" }.orEmpty() + val baseUrl = "$scheme://$host$port" + val requestHost = baseUrl.toHttpUrlOrNull()?.host ?: return null + val allowed = + scheme == "https" || (allowInsecureLocalhost && isLocalDevelopmentHost(requestHost)) + return if (allowed) CapEnvironment(baseUrl) else null + } + + fun isLocalDevelopmentHost(host: String): Boolean { + if (host == "localhost" || host == "127.0.0.1" || host.endsWith(".local")) return true + val labels = host.split('.') + if (labels.size != 4 || !labels.all(addressLabel::matches)) return false + val parts = labels.map(String::toInt) + if (parts.any { it > 255 }) return false + return parts[0] == 10 || + (parts[0] == 192 && parts[1] == 168) || + (parts[0] == 172 && parts[1] in 16..31) + } + } +} + +object SafeUrl { + fun web(string: String?): String? = string?.toHttpUrlOrNull()?.takeIf { it.isHttps }?.toString() + + fun media(string: String?, environment: CapEnvironment): String? { + val url = string?.let { environment.baseUrl.toHttpUrlOrNull()?.resolve(it) } ?: return null + return url.toString().takeIf { url.isHttps || environment.isSameOrigin(it) } + } +} + +internal class UrlParts +private constructor( + val scheme: String?, + val userInfo: String?, + val host: String?, + val port: Int?, + val path: String, + val query: String?, + val fragment: String?, +) { + val pathSegments: List + get() = path.split('/').filter { it.isNotEmpty() }.map(::percentDecode) + + val queryItems: List> + get() = + query + .orEmpty() + .split('&') + .filter { it.isNotEmpty() } + .map { item -> + val name = percentDecode(item.substringBefore('=')) + name to if ('=' in item) percentDecode(item.substringAfter('=')) else null + } + + companion object { + private val pattern = + Regex( + """(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?""", + RegexOption.DOT_MATCHES_ALL, + ) + + fun parse(string: String): UrlParts? { + if (string.any { it.isWhitespace() }) return null + val groups = pattern.matchEntire(string)?.groups ?: return null + val authority = groups[2]?.value + val hostAndPort = authority?.substringAfterLast('@').orEmpty() + val portSeparator = + hostAndPort.lastIndexOf(':').takeIf { it > hostAndPort.lastIndexOf(']') } + val portText = portSeparator?.let { hostAndPort.substring(it + 1) }.orEmpty() + val port = portText.toIntOrNull() + if (portText.isNotEmpty() && (port == null || portText.any { it !in '0'..'9' })) { + return null + } + return UrlParts( + scheme = groups[1]?.value, + userInfo = authority?.takeIf { '@' in it }?.substringBeforeLast('@'), + host = + hostAndPort.substring(0, portSeparator ?: hostAndPort.length).ifEmpty { null }, + port = port, + path = groups[3]?.value.orEmpty(), + query = groups[4]?.value, + fragment = groups[5]?.value, + ) + } + + private fun percentDecode(value: String): String { + val bytes = ByteArrayOutputStream() + var index = 0 + while (index < value.length) { + val high = value.getOrNull(index + 1)?.digitToIntOrNull(16) + val low = value.getOrNull(index + 2)?.digitToIntOrNull(16) + if (value[index] == '%' && high != null && low != null) { + bytes.write(high * 16 + low) + index += 3 + } else { + val end = value.offsetByCodePoints(index, 1) + bytes.write(value.substring(index, end).toByteArray()) + index = end + } + } + return bytes.toString(Charsets.UTF_8.name()) + } + } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Formatting.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Formatting.kt new file mode 100644 index 00000000000..4df377d4c8f --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Formatting.kt @@ -0,0 +1,175 @@ +package so.cap.kit + +import java.math.BigDecimal +import java.math.RoundingMode +import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.time.DayOfWeek +import java.time.Duration +import java.time.Instant +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.temporal.ChronoUnit +import java.time.temporal.TemporalAdjusters +import java.time.temporal.WeekFields +import java.util.IllformedLocaleException +import java.util.Locale +import kotlin.math.abs +import kotlin.math.floor +import kotlin.math.sign + +object CapFormat { + fun duration(seconds: Double?): String? { + if (seconds == null || !seconds.isFinite() || seconds < 0) return null + return timestamp(seconds) + } + + fun timestamp(seconds: Double): String { + val total = floor(if (seconds.isFinite()) seconds.coerceAtLeast(0.0) else 0.0).toLong() + val hours = total / 3600 + val minutes = (total % 3600) / 60 + val secs = total % 60 + return if (hours > 0) String.format(Locale.ROOT, "%d:%02d:%02d", hours, minutes, secs) + else String.format(Locale.ROOT, "%d:%02d", minutes, secs) + } + + fun count(value: Int): String { + var scaled = BigDecimal(value) + var suffix = "" + for (next in listOf("K", "M", "B")) { + if (scaled.abs().setScale(1, RoundingMode.HALF_EVEN) < thousand) break + scaled = scaled.movePointLeft(3) + suffix = next + } + return decimal("0.#").format(scaled) + suffix + } + + fun relative( + date: Instant, + now: Instant = Instant.now(), + zone: ZoneId = ZoneId.systemDefault(), + firstDayOfWeek: DayOfWeek = WeekFields.of(Locale.getDefault()).firstDayOfWeek, + ): String { + val interval = Duration.between(date, now).toMillis() / 1000.0 + if (interval < 60 && interval > -60) return "Just now" + val destination = date.atZone(zone) + val reference = + destination.plusSeconds((abs(interval) + 0.5).toLong() * interval.sign.toLong()) + val (unit, value) = largestComponent(reference, destination) ?: return "Just now" + val (alignedUnit, alignedValue) = + if (unit == ChronoUnit.HOURS || unit == ChronoUnit.MINUTES) { + rounded(unit, value, reference, destination) + } else { + aligned(unit, reference, destination, firstDayOfWeek) ?: (unit to value) + } + return phrase(alignedUnit, alignedValue) + } + + fun percentage(value: Double): String { + val fraction = if (value > 1) value / 100 else value + if (fraction.isNaN()) return "NaN%" + if (fraction.isInfinite()) return if (fraction > 0) "∞%" else "-∞%" + return decimal("#,##0.#").format(BigDecimal.valueOf(fraction).movePointRight(2)) + "%" + } + + fun flag(regionCode: String): String? { + val upper = regionCode.uppercase() + if (upper.length != 2 || !upper.all { it in 'A'..'Z' }) return null + return upper.map { String(Character.toChars(127397 + it.code)) }.joinToString("") + } + + fun regionName(code: String, locale: Locale = Locale.getDefault()): String { + val upper = code.uppercase() + val name = + try { + Locale.Builder().setRegion(upper).build().getDisplayCountry(locale) + } catch (_: IllformedLocaleException) { + return code + } + return if (name.isEmpty() || name == upper) code else name + } + + fun byteCount(bytes: Long): String { + if (bytes == 0L) return "Zero KB" + if (bytes == 1L || bytes == -1L) return "$bytes byte" + if (bytes in -999L..999L) return "$bytes bytes" + val units = listOf("KB", "MB", "GB", "TB", "PB", "EB") + val scaled = + units.indices.map { + BigDecimal(bytes) + .movePointLeft(3 * (it + 1)) + .setScale(minOf(it, 2), RoundingMode.HALF_UP) + } + val index = scaled.indexOfFirst { it.abs() < thousand } + return "${scaled[index].stripTrailingZeros().toPlainString()} ${units[index]}" + } + + private val thousand = BigDecimal(1000) + + private val relativeUnits = + listOf( + ChronoUnit.YEARS, + ChronoUnit.MONTHS, + ChronoUnit.WEEKS, + ChronoUnit.DAYS, + ChronoUnit.HOURS, + ChronoUnit.MINUTES, + ) + + private fun decimal(pattern: String) = DecimalFormat(pattern, DecimalFormatSymbols(Locale.US)) + + private fun largestComponent(from: ZonedDateTime, to: ZonedDateTime): Pair? = + relativeUnits.firstNotNullOfOrNull { unit -> + unit.between(from, to).takeIf { it != 0L }?.let { unit to it } + } + + private fun rounded( + unit: ChronoUnit, + value: Long, + reference: ZonedDateTime, + destination: ZonedDateTime, + ): Pair { + val smaller = if (unit == ChronoUnit.HOURS) ChronoUnit.MINUTES else ChronoUnit.SECONDS + val rest = smaller.between(reference.plus(value, unit), destination) + val roundedValue = if (abs(rest) * 2 >= 60) value + rest.sign else value + val carried = largestComponent(destination.minus(roundedValue, unit), destination) + return if (carried != null && carried.first != unit) carried else unit to roundedValue + } + + private fun aligned( + unit: ChronoUnit, + reference: ZonedDateTime, + destination: ZonedDateTime, + firstDayOfWeek: DayOfWeek, + ): Pair? { + val day = reference.toLocalDate() + val start = + when (unit) { + ChronoUnit.YEARS -> day.withDayOfYear(1) + ChronoUnit.MONTHS -> day.withDayOfMonth(1) + ChronoUnit.WEEKS -> day.with(TemporalAdjusters.previousOrSame(firstDayOfWeek)) + else -> day + }.atStartOfDay(reference.zone) + val anchor = if (reference < destination) start else start.plus(1, unit).minusSeconds(1) + return largestComponent(anchor, destination) + } + + private fun phrase(unit: ChronoUnit, value: Long): String { + val count = abs(value) + val past = value < 0 + val name = + when (unit) { + ChronoUnit.YEARS -> "yr." + ChronoUnit.MONTHS -> "mo." + ChronoUnit.WEEKS -> "wk." + ChronoUnit.DAYS -> "days" + ChronoUnit.HOURS -> "hr." + else -> "min." + } + if (count == 1L && unit == ChronoUnit.DAYS) return if (past) "yesterday" else "tomorrow" + if (count == 1L && unit != ChronoUnit.HOURS && unit != ChronoUnit.MINUTES) { + return if (past) "last $name" else "next $name" + } + return if (past) "$count $name ago" else "in $count $name" + } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Links.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Links.kt new file mode 100644 index 00000000000..ec9a446c9d9 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Links.kt @@ -0,0 +1,181 @@ +package so.cap.kit + +import java.security.SecureRandom +import java.util.Base64 + +@JvmInline +value class CapId private constructor(val rawValue: String) { + override fun toString(): String = rawValue + + companion object { + fun parse(value: String): CapId? { + val trimmed = value.trim() + if (trimmed.length !in 1..128 || !trimmed.all(::isAllowed)) return null + return CapId(trimmed) + } + + private fun isAllowed(character: Char): Boolean = + character in 'a'..'z' || + character in 'A'..'Z' || + character in '0'..'9' || + character == '-' || + character == '_' + } +} + +data class ShareTarget( + val id: CapId, + val startTime: Double? = null, + val commentId: String? = null, +) { + internal companion object { + const val MAX_START_TIME = 7.0 * 24 * 60 * 60 + + private val decimal = Regex("""[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?""") + + fun from(id: CapId, query: List>): ShareTarget { + fun value(name: String) = query.firstOrNull { it.first == name }?.second + val seconds = value("t")?.takeIf(decimal::matches)?.toDouble() + return ShareTarget( + id = id, + startTime = seconds?.takeIf { it.isFinite() && it > 0 && it <= MAX_START_TIME }, + commentId = (value("comment") ?: value("reply"))?.let(CapId::parse)?.rawValue, + ) + } + } +} + +sealed interface DeepLink { + data class Share(val target: ShareTarget) : DeepLink + + data class AuthCallback(val url: String) : DeepLink + + data object StopScreenRecording : DeepLink + + companion object { + const val STOP_SCREEN_RECORDING_URL = "cap://record/stop" + + fun parse(url: String): DeepLink? { + val parts = UrlParts.parse(url) ?: return null + val scheme = parts.scheme?.lowercase() ?: return null + if (scheme != "cap") { + val capId = ShareLinkParser.capId(parts) ?: return null + return Share(ShareTarget.from(capId, parts.queryItems)) + } + return when (parts.host?.lowercase()) { + "auth" -> AuthCallback(url) + "record" -> StopScreenRecording.takeIf { parts.pathSegments == listOf("stop") } + "s" -> + parts.pathSegments.singleOrNull()?.let(CapId::parse)?.let { + Share(ShareTarget.from(it, parts.queryItems)) + } + else -> null + } + } + } +} + +object ShareLinkParser { + internal fun capId(parts: UrlParts): CapId? { + if (parts.scheme?.lowercase() != "https" || parts.host == null || parts.userInfo != null) { + return null + } + val segments = parts.pathSegments + if (segments.size != 2 || segments[0] != "s") return null + return CapId.parse(segments[1]) + } + + fun capIdFromUserInput(input: String): CapId? { + val trimmed = input.trim() + if (trimmed.isEmpty()) return null + if (UrlParts.parse(trimmed)?.scheme != null) { + return (DeepLink.parse(trimmed) as? DeepLink.Share)?.target?.id + } + if ('/' in trimmed) return UrlParts.parse("https://$trimmed")?.let(::capId) + return CapId.parse(trimmed) + } +} + +sealed class AuthCallbackError(message: String) : Exception(message) { + class Provider(val detail: String) : AuthCallbackError(detail) + + class InvalidCallback : AuthCallbackError("Sign in did not return a Cap session. Try again.") +} + +object AuthCallback { + const val SCHEME = "cap" + const val REDIRECT_URI = "cap://auth" + + fun session(url: String): ApiKeySession { + val parts = UrlParts.parse(url) + if ( + parts == null || + parts.scheme?.lowercase() != SCHEME || + parts.host?.lowercase() != "auth" || + parts.userInfo != null || + parts.port != null || + (parts.path.isNotEmpty() && parts.path != "/") + ) { + throw AuthCallbackError.InvalidCallback() + } + + val items = parts.queryItems + fun value(name: String) = items.singleOrNull { it.first == name }?.second?.trim() + + val message = value("error_description") + if (!message.isNullOrEmpty()) { + val end = + message.offsetByCodePoints(0, minOf(200, message.codePointCount(0, message.length))) + throw AuthCallbackError.Provider(message.substring(0, end)) + } + val apiKey = value("api_key") + val userId = value("user_id") + if ( + apiKey == null || + !ApiKeyValidator.isPlausible(apiKey) || + userId == null || + CapId.parse(userId) == null + ) { + throw AuthCallbackError.InvalidCallback() + } + return ApiKeySession(apiKey = apiKey, userId = userId) + } + + fun state(url: String): String? = + UrlParts.parse(url)?.queryItems?.singleOrNull { it.first == "state" }?.second + + fun newState(): String { + val bytes = ByteArray(STATE_BYTES).also(SecureRandom()::nextBytes) + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + } + + private const val STATE_BYTES = 24 +} + +object ApiKeyValidator { + fun isPlausible(key: String): Boolean = + key.length in 16..512 && key.all { it.code in 0x21..0x7E } +} + +object EmailValidator { + fun normalize(email: String): String = email.trim().lowercase() + + fun isValid(email: String): Boolean { + val value = normalize(email) + if (value.toByteArray().size > 254 || value.any { it.isWhitespace() }) return false + val parts = value.split('@') + if (parts.size != 2 || parts[0].isEmpty()) return false + if (parts[0].codePointCount(0, parts[0].length) > 64) return false + val labels = parts[1].split('.') + return labels.size >= 2 && + labels.all { it.isNotEmpty() && !it.startsWith('-') && !it.endsWith('-') } + } +} + +object VerificationCode { + const val LENGTH = 6 + + fun sanitize(input: String): String = input.filter { it in '0'..'9' }.take(LENGTH) + + fun isComplete(code: String): Boolean = code.length == LENGTH && code.all { it in '0'..'9' } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Models.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Models.kt new file mode 100644 index 00000000000..a60af28e830 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Models.kt @@ -0,0 +1,589 @@ +@file:UseSerializers( + StrictBooleanSerializer::class, + NumberSerializer::class, + InstantSerializer::class, +) + +package so.cap.kit + +import java.time.Instant +import kotlin.math.abs +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.UseSerializers +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable(with = MemberRole.Serializer::class) +enum class MemberRole(override val rawValue: String) : RawValue { + OWNER("owner"), + ADMIN("admin"), + MEMBER("member"); + + val canManage: Boolean + get() = this == OWNER || this == ADMIN + + val displayName: String + get() = + when (this) { + OWNER -> "Owner" + ADMIN -> "Admin" + MEMBER -> "Member" + } + + internal object Serializer : RawValueSerializer("MemberRole", entries, MEMBER) +} + +enum class PushEnvironment(override val rawValue: String) : RawValue { + SANDBOX("sandbox"), + PRODUCTION("production"), +} + +@Serializable +data class NotificationPreferences( + val comments: Boolean, + val replies: Boolean, + val views: Boolean, + val anonymousViews: Boolean, + val reactions: Boolean, +) { + enum class Kind(override val rawValue: String) : RawValue { + COMMENTS("comments"), + REPLIES("replies"), + VIEWS("views"), + ANONYMOUS_VIEWS("anonymousViews"), + REACTIONS("reactions"), + } + + operator fun get(kind: Kind): Boolean = + when (kind) { + Kind.COMMENTS -> comments + Kind.REPLIES -> replies + Kind.VIEWS -> views + Kind.ANONYMOUS_VIEWS -> anonymousViews + Kind.REACTIONS -> reactions + } + + fun with(kind: Kind, enabled: Boolean): NotificationPreferences = + when (kind) { + Kind.COMMENTS -> copy(comments = enabled) + Kind.REPLIES -> copy(replies = enabled) + Kind.VIEWS -> copy(views = enabled) + Kind.ANONYMOUS_VIEWS -> copy(anonymousViews = enabled) + Kind.REACTIONS -> copy(reactions = enabled) + } +} + +@Serializable +data class CapUser( + val id: String, + val name: String?, + val lastName: String?, + val email: String, + val imageUrl: String?, + val activeOrganizationId: String, +) { + val displayName: String + get() { + val full = + listOfNotNull(name, lastName) + .map { it.trim() } + .filter { it.isNotEmpty() } + .joinToString(" ") + if (full.isNotEmpty()) return full + return email.split('@').firstOrNull { it.isNotEmpty() } ?: email + } +} + +@Serializable +data class Organization( + val id: String, + val name: String, + val iconUrl: String?, + val role: MemberRole, +) + +@Serializable(with = SpaceKind.Serializer::class) +enum class SpaceKind(override val rawValue: String) : RawValue { + ORGANIZATION("organization"), + SPACE("space"); + + internal object Serializer : RawValueSerializer("SpaceKind", entries, SPACE) +} + +@Serializable(with = SpacePrivacy.Serializer::class) +enum class SpacePrivacy(override val rawValue: String) : RawValue { + PUBLIC("Public"), + PRIVATE("Private"); + + internal object Serializer : RawValueSerializer("SpacePrivacy", entries, PRIVATE) +} + +@Serializable +data class Space( + val id: String, + val name: String, + val iconUrl: String?, + val kind: SpaceKind, + val privacy: SpacePrivacy, + val role: MemberRole?, + val canManage: Boolean, + val hasPassword: Boolean, +) + +@Serializable(with = FolderColor.Serializer::class) +enum class FolderColor(override val rawValue: String) : RawValue { + NORMAL("normal"), + BLUE("blue"), + RED("red"), + YELLOW("yellow"); + + val displayName: String + get() = + when (this) { + NORMAL -> "Default" + BLUE -> "Blue" + RED -> "Red" + YELLOW -> "Yellow" + } + + internal object Serializer : RawValueSerializer("FolderColor", entries, NORMAL) + + internal object Lenient : LenientSerializer(Serializer, NORMAL) +} + +@Serializable +data class Folder( + val id: String, + val name: String, + @Serializable(with = FolderColor.Lenient::class) val color: FolderColor = FolderColor.NORMAL, + val parentId: String?, + @Serializable(with = LenientCountSerializer::class) val videoCount: Int = 0, +) + +@Serializable(with = UploadPhase.Serializer::class) +enum class UploadPhase(override val rawValue: String) : RawValue { + UPLOADING("uploading"), + PROCESSING("processing"), + GENERATING_THUMBNAIL("generating_thumbnail"), + COMPLETE("complete"), + ERROR("error"); + + internal object Serializer : RawValueSerializer("UploadPhase", entries, PROCESSING) + + internal object Lenient : LenientSerializer(Serializer, PROCESSING) +} + +@Serializable +data class UploadProgress( + @Serializable(with = LenientNumberSerializer::class) val uploaded: Double = 0.0, + @Serializable(with = LenientNumberSerializer::class) val total: Double = 0.0, + @Serializable(with = UploadPhase.Lenient::class) + val phase: UploadPhase = UploadPhase.PROCESSING, + @Serializable(with = LenientNumberSerializer::class) val processingProgress: Double = 0.0, + val processingMessage: String?, + val processingError: String?, +) { + val fractionCompleted: Double + get() = + when (phase) { + UploadPhase.UPLOADING -> + if (total > 0) (uploaded / total).coerceIn(0.0, 1.0) else 0.0 + UploadPhase.PROCESSING, + UploadPhase.GENERATING_THUMBNAIL -> (processingProgress / 100).coerceIn(0.0, 1.0) + UploadPhase.COMPLETE -> 1.0 + UploadPhase.ERROR -> 0.0 + } + + val statusText: String + get() = + when (phase) { + UploadPhase.UPLOADING -> "Uploading" + UploadPhase.PROCESSING -> processingMessage ?: "Processing" + UploadPhase.GENERATING_THUMBNAIL -> "Generating thumbnail" + UploadPhase.COMPLETE -> "Ready" + UploadPhase.ERROR -> "Processing failed" + } + + internal object Lenient : LenientSerializer(serializer().nullable, null) +} + +enum class LinkAccess(override val rawValue: String) : RawValue { + ANYONE("anyone"), + RESTRICTED("restricted"); + + internal object Serializer : RawValueSerializer("LinkAccess", entries) + + internal object Lenient : LenientSerializer(Serializer.nullable, null) +} + +@Serializable +data class CapSummary( + val id: String, + val shareUrl: String, + val title: String, + val createdAt: Instant, + val updatedAt: Instant, + val ownerId: String?, + @Serializable(with = EmptyWhenNullSerializer::class) val ownerName: String = "", + @Serializable(with = LenientNullableNumberSerializer::class) val durationSeconds: Double?, + val thumbnailUrl: String?, + val thumbnailCacheKey: String?, + val folderId: String?, + @SerialName("public") val isPublic: Boolean, + @SerialName("protected") + @Serializable(with = FalseWhenNullSerializer::class) + val isProtected: Boolean = false, + @Serializable(with = LenientCountSerializer::class) val viewCount: Int = 0, + @Serializable(with = LenientCountSerializer::class) val commentCount: Int = 0, + @Serializable(with = LenientCountSerializer::class) val reactionCount: Int = 0, + @Serializable(with = UploadProgress.Lenient::class) val upload: UploadProgress?, + val ownedByCurrentUser: Boolean?, + @Serializable(with = LinkAccess.Lenient::class) val linkAccess: LinkAccess? = null, + @Serializable(with = LenientNullableBooleanSerializer::class) + val linkRestricted: Boolean? = null, +) { + fun isOwned(userId: String?): Boolean { + if (ownedByCurrentUser != null) return ownedByCurrentUser + if (userId == null || ownerId == null) return false + return ownerId == userId + } + + val isProcessing: Boolean + get() = + upload != null && + upload.phase != UploadPhase.COMPLETE && + upload.phase != UploadPhase.ERROR +} + +@Serializable(with = CommentKind.Serializer::class) +enum class CommentKind(override val rawValue: String) : RawValue { + TEXT("text"), + EMOJI("emoji"); + + internal object Serializer : RawValueSerializer("CommentKind", entries, TEXT) +} + +@Serializable data class CommentAuthor(val id: String, val name: String?, val imageUrl: String?) + +@Serializable +data class CapComment( + val id: String, + val videoId: String, + val type: CommentKind, + val content: String, + val timestamp: Double?, + val parentCommentId: String?, + val createdAt: Instant, + val updatedAt: Instant, + val author: CommentAuthor, +) + +@Serializable data class Chapter(val title: String, val start: Double) + +@Serializable(with = TranscriptionStatus.Serializer::class) +enum class TranscriptionStatus(override val rawValue: String) : RawValue { + PROCESSING("PROCESSING"), + COMPLETE("COMPLETE"), + ERROR("ERROR"), + SKIPPED("SKIPPED"), + NO_AUDIO("NO_AUDIO"); + + internal object Serializer : + RawValueSerializer("TranscriptionStatus", entries, SKIPPED) + + internal object Lenient : LenientSerializer(Serializer.nullable, null) +} + +@Serializable +data class ViewerSettings( + @Serializable(with = LenientFalseSerializer::class) val disableSummary: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val disableCaptions: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val disableChapters: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val disableReactions: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val disableTranscript: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val disableComments: Boolean = false, +) { + internal object Lenient : LenientSerializer(serializer(), ViewerSettings()) +} + +@Serializable +data class CapViewer( + @Serializable(with = ViewerSettings.Lenient::class) + val settings: ViewerSettings = ViewerSettings(), + @Serializable(with = PlaybackSpeedSerializer::class) val defaultPlaybackSpeed: Float = 1.2f, + @Serializable(with = LenientFalseSerializer::class) val canDownload: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val isScreenshot: Boolean = false, + @Serializable(with = LenientFalseSerializer::class) val overShareLimit: Boolean = false, + @Serializable(with = LenientNullableStringSerializer::class) val ownerImageUrl: String? = null, + @Serializable(with = LenientNullableStringSerializer::class) + val aiGenerationStatus: String? = null, +) { + val isGeneratingAi: Boolean + get() = aiGenerationStatus == "QUEUED" || aiGenerationStatus == "PROCESSING" + + internal object Lenient : LenientSerializer(serializer(), CapViewer()) + + internal object PlaybackSpeedSerializer : KSerializer { + private val lenient = LenientSerializer(NumberSerializer, 1.2) + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.PlaybackSpeed", PrimitiveKind.FLOAT) + + override fun serialize(encoder: Encoder, value: Float) = encoder.encodeFloat(value) + + override fun deserialize(decoder: Decoder): Float = + nearestSpeed(lenient.deserialize(decoder)) + } + + companion object { + val PLAYBACK_SPEEDS = listOf(0.5f, 0.75f, 1f, 1.2f, 1.5f, 1.75f, 2f) + + fun nearestSpeed(value: Double): Float { + if (!value.isFinite() || value <= 0) return 1.2f + return PLAYBACK_SPEEDS.minBy { abs(it.toDouble() - value) } + } + } +} + +@Serializable(with = CapAccessStatus.Serializer::class) +enum class CapAccessStatus(override val rawValue: String) : RawValue { + GRANTED("granted"), + PASSWORD_REQUIRED("password_required"), + RESTRICTED("restricted"), + UNKNOWN("unknown"); + + internal object Serializer : + RawValueSerializer("CapAccessStatus", entries, UNKNOWN) +} + +@Serializable internal data class CapAccessResponse(val status: CapAccessStatus) + +@Serializable internal data class CapUnlock(val accessToken: String, val expiresAt: Instant) + +@Serializable +data class CapDetail( + val cap: CapSummary, + val summary: String?, + @Serializable(with = LossyListSerializer::class) val chapters: List = emptyList(), + @Serializable(with = TranscriptionStatus.Lenient::class) + val transcriptionStatus: TranscriptionStatus?, + @Serializable(with = LossyListSerializer::class) val comments: List = emptyList(), + val shareUrl: String, + @Serializable(with = CapViewer.Lenient::class) val viewer: CapViewer = CapViewer(), +) + +@Serializable +data class CapsPage( + @Serializable(with = LossyListSerializer::class) val folders: List = emptyList(), + @Serializable(with = LossyListSerializer::class) val caps: List = emptyList(), + @Serializable(with = CountSerializer::class) val page: Int, + @Serializable(with = CountSerializer::class) val limit: Int, + @Serializable(with = CountSerializer::class) val total: Int, + @Serializable(with = LenientNullableCountSerializer::class) val collectionTotal: Int?, + val hasMore: Boolean, +) + +@Serializable data class CapStatus(val id: String, val upload: UploadProgress?) + +@Serializable internal data class CapStatusesResponse(val caps: List) + +@Serializable +data class Bootstrap( + val user: CapUser, + @Serializable(with = LossyListSerializer::class) + val organizations: List = emptyList(), + val activeOrganizationId: String?, + @Serializable(with = LossyListSerializer::class) val rootFolders: List = emptyList(), + @Serializable(with = LossyListSerializer::class) val spaces: List = emptyList(), +) { + val activeOrganization: Organization? + get() { + val id = activeOrganizationId ?: user.activeOrganizationId + return organizations.firstOrNull { it.id == id } + } +} + +@Serializable(with = PlaybackKind.Serializer::class) +enum class PlaybackKind(override val rawValue: String) : RawValue { + MP4("mp4"), + HLS("hls"); + + internal object Serializer : RawValueSerializer("PlaybackKind", entries, MP4) +} + +@Serializable +data class Playback(val kind: PlaybackKind, val url: String, val transcriptUrl: String?) + +@Serializable data class DownloadLink(val fileName: String, val url: String) + +enum class AnalyticsRange(override val rawValue: String) : RawValue { + DAY("24h"), + WEEK("7d"), + MONTH("30d"), + LIFETIME("lifetime"); + + val title: String + get() = + when (this) { + DAY -> "24H" + WEEK -> "7D" + MONTH -> "30D" + LIFETIME -> "All" + } + + val accessibilityTitle: String + get() = + when (this) { + DAY -> "Last 24 hours" + WEEK -> "Last 7 days" + MONTH -> "Last 30 days" + LIFETIME -> "All time" + } + + val usesHourlyBuckets: Boolean + get() = this == DAY +} + +@Serializable +data class AnalyticsBreakdown( + val name: String, + val subtitle: String?, + @Serializable(with = LenientCountSerializer::class) val views: Int = 0, + @Serializable(with = LenientNumberSerializer::class) val percentage: Double = 0.0, + @SerialName("id") val capId: String? = null, +) { + val id: String + get() = listOf(capId.orEmpty(), name, subtitle.orEmpty()).joinToString("|") +} + +@Serializable +data class AnalyticsCounts( + @Serializable(with = LenientCountSerializer::class) val caps: Int = 0, + @Serializable(with = LenientCountSerializer::class) val views: Int = 0, + @Serializable(with = LenientCountSerializer::class) val comments: Int = 0, + @Serializable(with = LenientCountSerializer::class) val reactions: Int = 0, +) + +@Serializable +data class AnalyticsPoint( + val bucket: String, + @Serializable(with = LenientCountSerializer::class) val caps: Int = 0, + @Serializable(with = LenientCountSerializer::class) val views: Int = 0, + @Serializable(with = LenientCountSerializer::class) val comments: Int = 0, + @Serializable(with = LenientCountSerializer::class) val reactions: Int = 0, +) { + val date: Instant? + get() = CapJson.parseDate(bucket) +} + +@Serializable +data class AnalyticsBreakdowns( + @Serializable(with = LossyListSerializer::class) + val countries: List = emptyList(), + @Serializable(with = LossyListSerializer::class) + val cities: List = emptyList(), + @Serializable(with = LossyListSerializer::class) + val browsers: List = emptyList(), + @Serializable(with = LossyListSerializer::class) + val operatingSystems: List = emptyList(), + @Serializable(with = LossyListSerializer::class) + val devices: List = emptyList(), + @Serializable(with = LossyListSerializer::class) + val topCaps: List = emptyList(), +) + +@Serializable +data class AnalyticsData( + val capName: String?, + val counts: AnalyticsCounts, + @Serializable(with = LossyListSerializer::class) val chart: List = emptyList(), + val breakdowns: AnalyticsBreakdowns, +) + +@Serializable data class AnalyticsResponse(val available: Boolean, val data: AnalyticsData?) + +@Serializable +data class OrganizationSettings( + val id: String, + val name: String, + val role: MemberRole, + val canManage: Boolean, + val iconUrl: String?, + val allowedEmailDomain: String?, + val customDomain: String?, + val domainVerified: Boolean, +) + +@Serializable data class LoomImportResult(val id: String, val shareUrl: String) + +@Serializable +sealed interface UploadTarget { + val url: String + + @Serializable + @SerialName("s3Post") + data class S3Post(override val url: String, val fields: Map) : UploadTarget + + @Serializable + @SerialName("put") + data class Put(override val url: String, val headers: Map) : UploadTarget + + @Serializable + @SerialName("driveResumable") + data class DriveResumable(override val url: String, val headers: Map) : + UploadTarget +} + +@Serializable +data class UploadCreated( + val id: String, + val shareUrl: String, + val rawFileKey: String, + val upload: UploadTarget, +) + +@Serializable data class ApiKeySession(val apiKey: String, val userId: String) + +@Serializable +data class AuthConfig( + val appleAuthAvailable: Boolean, + val googleAuthAvailable: Boolean, + val workosAuthAvailable: Boolean, +) { + companion object { + val FALLBACK = + AuthConfig( + appleAuthAvailable = true, + googleAuthAvailable = true, + workosAuthAvailable = true, + ) + } +} + +@Serializable data class PlanStatus(val upgraded: Boolean, val stripeSubscriptionStatus: String?) + +enum class ContentReportReason(override val rawValue: String) : RawValue { + HARASSMENT("harassment"), + HATE("hate"), + SEXUAL("sexual"), + VIOLENCE("violence"), + COPYRIGHT("copyright"), + OTHER("other"); + + val title: String + get() = + when (this) { + HARASSMENT -> "Harassment or bullying" + HATE -> "Hate speech" + SEXUAL -> "Sexual content" + VIOLENCE -> "Violence or threats" + COPYRIGHT -> "Copyright infringement" + OTHER -> "Other concern" + } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/SnapshotCache.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/SnapshotCache.kt new file mode 100644 index 00000000000..e593410cdd5 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/SnapshotCache.kt @@ -0,0 +1,103 @@ +package so.cap.kit + +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.DeserializationStrategy +import kotlinx.serialization.SerializationStrategy + +class SnapshotCache(private val root: File) { + private val serial = Dispatchers.IO.limitedParallelism(1) + + suspend fun read( + serializer: DeserializationStrategy, + namespace: String, + key: String, + ): T? { + val file = file(namespace, key) ?: return null + return withContext(serial) { + try { + CapJson.json.decodeFromString(serializer, file.readText()) + } catch (_: IOException) { + null + } catch (_: IllegalArgumentException) { + null + } + } + } + + suspend fun write( + serializer: SerializationStrategy, + value: T, + namespace: String, + key: String, + ) { + val file = file(namespace, key) ?: return + withContext(serial) { + val text = + try { + CapJson.json.encodeToString(serializer, value) + } catch (_: IllegalArgumentException) { + return@withContext + } + var temporary: File? = null + try { + Files.createDirectories(file.parentFile.toPath()) + temporary = File.createTempFile("snapshot", ".tmp", file.parentFile) + temporary.writeText(text) + Files.move(temporary.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE) + } catch (_: IOException) { + temporary?.delete() + file.deleteRecursively() + } + } + } + + suspend fun remove(namespace: String, key: String) { + val file = file(namespace, key) ?: return + withContext(serial) { file.delete() } + } + + suspend fun removeAll() { + withContext(serial) { root.deleteRecursively() } + } + + private fun file(namespace: String, key: String): File? { + val directory = CapId.parse(namespace)?.rawValue ?: return null + val scalars = key.codePoints().toArray() + if (scalars.size !in 1..MAX_KEY_LENGTH) return null + val name = StringBuilder() + for (scalar in scalars) { + if (Character.getType(scalar) in alphanumerics || scalar == '-'.code) { + name.appendCodePoint(scalar) + } else { + name.append('_') + } + } + return File(File(root, directory), "$name.json") + } + + private companion object { + const val MAX_KEY_LENGTH = 200 + + val alphanumerics = + setOf( + Character.UPPERCASE_LETTER, + Character.LOWERCASE_LETTER, + Character.TITLECASE_LETTER, + Character.MODIFIER_LETTER, + Character.OTHER_LETTER, + Character.NON_SPACING_MARK, + Character.ENCLOSING_MARK, + Character.COMBINING_SPACING_MARK, + Character.DECIMAL_DIGIT_NUMBER, + Character.LETTER_NUMBER, + Character.OTHER_NUMBER, + ) + .map { it.toInt() } + .toSet() + } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Social.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Social.kt new file mode 100644 index 00000000000..162a5eb8769 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/Social.kt @@ -0,0 +1,149 @@ +package so.cap.kit + +import java.util.Locale + +object Reactions { + val emojis = listOf("😂", "😍", "😮", "🙌", "👍", "👎") +} + +data class CommentThread(val root: CapComment, val replies: List) { + val id: String + get() = root.id +} + +object CommentThreads { + private const val MAX_DEPTH = 16 + private val order = compareBy({ it.createdAt }, { it.id }) + + fun build(comments: List): List { + val text = comments.filter { it.type == CommentKind.TEXT } + val byId = mutableMapOf() + for (comment in text) byId.putIfAbsent(comment.id, comment) + + fun rootId(comment: CapComment): String? { + var current = comment + repeat(MAX_DEPTH) { + val parent = + current.parentCommentId?.takeIf { it.isNotEmpty() } ?: return current.id + current = byId[parent] ?: return null + } + return null + } + + val replies = mutableMapOf>() + val roots = mutableListOf() + for (comment in text) { + val root = rootId(comment) ?: continue + if (root == comment.id) roots += comment + else replies.getOrPut(root) { mutableListOf() } += comment + } + return roots.sortedWith(order).map { root -> + CommentThread(root, replies[root.id].orEmpty().sortedWith(order)) + } + } +} + +data class TimelineMarker( + val id: String, + val time: Double, + val position: Double, + val commentIds: List, + val authors: List, + val emojis: List, + val textCount: Int, + val reactionCount: Int, +) { + val count: Int + get() = textCount + reactionCount + + val leadingEmoji: String? + get() { + if (textCount != 0) return null + return emojis + .groupingBy { it } + .eachCount() + .entries + .maxWithOrNull( + compareBy> { it.value }.thenByDescending { it.key } + ) + ?.key + } +} + +object TimelineMarkers { + private const val MAX_AUTHORS = 3 + + fun build(comments: List, duration: Double, buckets: Int): List { + if (!duration.isFinite() || duration <= 0 || buckets <= 0) return emptyList() + val threads = CommentThreads.build(comments).map { it.id }.toSet() + val groups = sortedMapOf>() + for (comment in comments) { + val time = comment.timestamp?.takeIf { it.isFinite() && it >= 0 } ?: continue + if (comment.type == CommentKind.TEXT && comment.id !in threads) continue + val index = minOf(buckets - 1, (minOf(time, duration) / duration * buckets).toInt()) + groups.getOrPut(index) { mutableListOf() } += comment + } + return groups.values.map { group -> + val items = group.sortedBy { it.timestamp } + val time = minOf(items.first().timestamp ?: 0.0, duration) + val text = items.filter { it.type == CommentKind.TEXT } + TimelineMarker( + id = items.first().id, + time = time, + position = time / duration, + commentIds = items.map { it.id }, + authors = text.map { it.author }.distinctBy { it.id }.take(MAX_AUTHORS), + emojis = items.filter { it.type == CommentKind.EMOJI }.map { it.content }, + textCount = text.size, + reactionCount = items.size - text.size, + ) + } + } +} + +object TranscriptExport { + private const val PARAGRAPH_GAP_SECONDS = 2 + private const val PARAGRAPH_CUES = 6 + + fun plainText(cues: List): String { + val paragraphs = mutableListOf>() + var previousEnd: Double? = null + for (cue in cues) { + val text = cue.text.trim() + if (text.isEmpty()) continue + val last = paragraphs.lastOrNull() + if ( + last != null && + previousEnd != null && + cue.start - previousEnd < PARAGRAPH_GAP_SECONDS && + last.size < PARAGRAPH_CUES + ) { + last += text + } else { + paragraphs += mutableListOf(text) + } + previousEnd = cue.end + } + return paragraphs.joinToString("\n\n") { it.joinToString(" ") } + } + + fun timestamped(cues: List): String = + cues.joinToString("\n") { "[${CapFormat.timestamp(it.start)}] ${it.text}" } + + fun vtt(cues: List): String { + fun stamp(seconds: Double): String { + val millis = Math.round(maxOf(0.0, seconds) * 1000) + return String.format( + Locale.ROOT, + "%02d:%02d:%02d.%03d", + millis / 3_600_000, + (millis / 60_000) % 60, + (millis / 1000) % 60, + millis % 1000, + ) + } + val body = + cues.joinToString("\n\n") { "${stamp(it.start)} --> ${stamp(it.end)}\n${it.text}" } + return "WEBVTT\n\n$body\n" + } +} diff --git a/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/WebVtt.kt b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/WebVtt.kt new file mode 100644 index 00000000000..89340678f85 --- /dev/null +++ b/apps/mobile-android/capkit/src/main/kotlin/so/cap/kit/WebVtt.kt @@ -0,0 +1,105 @@ +package so.cap.kit + +import kotlin.math.ceil + +data class TranscriptCue(val id: Int, val start: Double, val end: Double, val text: String) { + fun caption(time: Double, maxCharacters: Int = 64): String { + val phrases = phrases(text, maxCharacters) + if (phrases.size <= 1 || end <= start) return phrases.firstOrNull() ?: text + val total = phrases.sumOf { it.length } + val spoken = (time - start) / (end - start) * total + var reached = 0.0 + for (phrase in phrases) { + reached += phrase.length + if (spoken < reached) return phrase + } + return phrases.last() + } + + companion object { + fun phrases(text: String, maxCharacters: Int): List { + val words = text.split(whitespace).filter { it.isNotEmpty() } + if (words.isEmpty()) return emptyList() + val length = words.joinToString(" ").length + if (length <= maxCharacters) return listOf(words.joinToString(" ")) + val count = ceil(length.toDouble() / maxCharacters).toInt() + val target = length.toDouble() / count + val phrases = mutableListOf() + val current = mutableListOf() + var currentLength = 0 + for (word in words) { + val added = if (currentLength == 0) word.length else currentLength + 1 + word.length + val breaks = + currentLength > 0 && + (added > maxCharacters || + (added > target && + phrases.size < count - 1 && + currentLength >= target * 0.6)) + if (breaks) { + phrases += current.joinToString(" ") + current.clear() + current += word + currentLength = word.length + } else { + current += word + currentLength = added + } + } + if (current.isNotEmpty()) phrases += current.joinToString(" ") + return phrases + } + + fun active(cues: List, time: Double): TranscriptCue? { + var low = 0 + var high = cues.size - 1 + var match: Int? = null + while (low <= high) { + val mid = (low + high) / 2 + if (cues[mid].start <= time) { + match = mid + low = mid + 1 + } else { + high = mid - 1 + } + } + return match?.let(cues::get)?.takeIf { time < it.end } + } + + private val whitespace = Regex("[\\s\\p{Z}]+") + } +} + +object WebVtt { + private val markup = Regex("<[^>]+>") + + fun parse(source: String): List { + val normalized = source.replace("\r\n", "\n").replace("\r", "\n") + val cues = mutableListOf() + for (block in normalized.split("\n\n")) { + val lines = block.split("\n").filter { it.isNotEmpty() } + val timing = lines.indexOfFirst { "-->" in it } + if (timing < 0) continue + val parts = lines[timing].split("-->") + if (parts.size != 2) continue + val start = parseTime(parts[0]) ?: continue + val end = + parseTime(parts[1].split(" ").firstOrNull { it.isNotEmpty() }.orEmpty()) ?: continue + val text = lines.drop(timing + 1).joinToString(" ").replace(markup, "").trim() + if (text.isEmpty()) continue + cues += TranscriptCue(cues.size, start, end, text) + } + return cues + } + + internal fun parseTime(raw: String): Double? { + val pieces = raw.trim(' ', '\t').split(":") + if (pieces.size !in 2..3) return null + var seconds = 0.0 + for (piece in pieces.dropLast(1)) { + val number = piece.toIntOrNull() ?: return null + seconds = seconds * 60 + number + } + val last = pieces.last().replace(',', '.').toDoubleOrNull() ?: return null + return seconds * 60 + last + } +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/ApiClientTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/ApiClientTest.kt new file mode 100644 index 00000000000..a302c6aca49 --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/ApiClientTest.kt @@ -0,0 +1,1385 @@ +package so.cap.kit + +import com.sun.net.httpserver.Headers +import com.sun.net.httpserver.HttpServer +import java.io.EOFException +import java.io.IOException +import java.net.ConnectException +import java.net.InetSocketAddress +import java.net.NoRouteToHostException +import java.net.ProtocolException +import java.net.SocketException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import java.time.Instant +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicInteger +import javax.net.ssl.SSLHandshakeException +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ApiClientTest { + @Test + fun mapsStatusCodes() { + assertNull(CapApiError.from(204)) + assertEquals(CapApiError.Forbidden, CapApiError.from(403)) + assertEquals(CapApiError.RateLimited, CapApiError.from(429)) + assertEquals(CapApiError.Server(503), CapApiError.from(503)) + assertEquals(CapApiError.UnexpectedStatus(302), CapApiError.from(302)) + assertEquals(CapApiError.Offline, CapApiError.from(UnknownHostException("cap.so"))) + assertEquals(CapApiError.Cancelled, CapApiError.from(CancellationException())) + } + + @Test + fun mapsEveryStatusTheServerUses() { + val expected = + mapOf( + 200 to null, + 299 to null, + 400 to CapApiError.BadRequest, + 422 to CapApiError.BadRequest, + 401 to CapApiError.Unauthorized, + 404 to CapApiError.NotFound, + 410 to CapApiError.NotFound, + 409 to CapApiError.Conflict, + 413 to CapApiError.PayloadTooLarge, + 500 to CapApiError.Server(500), + 599 to CapApiError.Server(599), + 100 to CapApiError.UnexpectedStatus(100), + 418 to CapApiError.UnexpectedStatus(418), + 600 to CapApiError.UnexpectedStatus(600), + ) + for ((status, error) in expected) { + assertEquals(status.toString(), error, CapApiError.from(status)) + } + } + + @Test + fun mapsTransportFailures() { + val expected = + listOf( + CapApiException(CapApiError.Conflict) to CapApiError.Conflict, + SerializationException("bad") to CapApiError.InvalidResponse, + SocketTimeoutException("timeout") to CapApiError.TimedOut, + ConnectException("Connection refused") to CapApiError.Offline, + NoRouteToHostException("No route to host") to CapApiError.Offline, + SocketException("Connection reset") to CapApiError.Offline, + EOFException() to CapApiError.Offline, + IOException("unexpected end of stream", EOFException()) to CapApiError.Offline, + ProtocolException("Unexpected status line") to CapApiError.InvalidResponse, + SSLHandshakeException("bad certificate") to + CapApiError.Transport("SSLHandshakeException"), + IllegalStateException("closed") to CapApiError.Transport("IllegalStateException"), + ) + for ((failure, error) in expected) { + assertEquals(failure.toString(), error, CapApiError.from(failure)) + } + } + + @Test + fun errorCopyMatchesIOS() { + val copy = + mapOf( + CapApiError.Unauthorized to "Your session expired. Sign in again.", + CapApiError.MissingSession to "Your session expired. Sign in again.", + CapApiError.Forbidden to "You don't have access to this.", + CapApiError.NotFound to + "This couldn't be found. It may have been deleted or moved.", + CapApiError.BadRequest to + "Cap couldn't accept that. Check the details and try again.", + CapApiError.Conflict to "This changed somewhere else. Refresh and try again.", + CapApiError.PayloadTooLarge to "That file is too large.", + CapApiError.RateLimited to "Too many attempts. Wait a moment and try again.", + CapApiError.Server(500) to "Cap is having trouble right now. Try again shortly.", + CapApiError.UnexpectedStatus(302) to "Something went wrong. Try again.", + CapApiError.Offline to "You're offline. Check your connection and try again.", + CapApiError.TimedOut to "The request timed out. Try again.", + CapApiError.Cancelled to "The request was cancelled.", + CapApiError.InvalidResponse to + "Cap sent an unexpected response. Update the app or try again.", + CapApiError.Transport("x") to + "Couldn't reach Cap. Check your connection and try again.", + ) + for ((error, text) in copy) { + assertEquals(text, error.description) + assertEquals(text, CapApiException(error).message) + } + val retryable = + setOf( + CapApiError.Offline, + CapApiError.TimedOut, + CapApiError.Server(500), + CapApiError.Transport("x"), + CapApiError.RateLimited, + ) + assertEquals(retryable, copy.keys.filter { it.isRetryable }.toSet()) + } + + @Test + fun onlyAnEstablishedConnectionCountsAsLost() { + assertTrue(SocketException("Connection reset").isLostConnection()) + assertTrue(EOFException().isLostConnection()) + assertTrue(IOException("unexpected end of stream", EOFException()).isLostConnection()) + assertFalse(ConnectException("Connection refused").isLostConnection()) + assertFalse(NoRouteToHostException("No route to host").isLostConnection()) + assertFalse(UnknownHostException("cap.so").isLostConnection()) + assertFalse(SocketTimeoutException("timeout").isLostConnection()) + } + + @Test + fun percentEncodesPathSegments() = runTest { + LoopbackServer { Reply(200) } + .use { server -> + val api = server.api() + val request = ApiRequest(path = listOf("api", "mobile", "comments", "a/b?c#d")) + assertEquals( + "${server.environment.baseUrl}/api/mobile/comments/a%2Fb%3Fc%23d", + api.makeUrl(request), + ) + assertEquals( + CapApiError.BadRequest, + failure { + api.makeUrl(ApiRequest(path = listOf("api", "mobile", "comments", ".."))) + }, + ) + assertEquals( + CapApiError.BadRequest, + failure { api.makeUrl(ApiRequest(path = listOf("api", "", "x"))) }, + ) + api.send(request) + assertEquals("/api/mobile/comments/a%2Fb%3Fc%23d", server.requests.single().path) + } + } + + @Test + fun encodesQueryValuesAndDropsEmptyOnes() = runTest { + LoopbackServer { Reply(200) } + .use { server -> + val query = listOf("a" to "x y&z=1+2/é", "b" to null, "c" to "", "d" to "~-._") + server.api().send(ApiRequest(path = listOf("x"), query = query)) + assertEquals("a=x%20y%26z%3D1%2B2%2F%C3%A9&d=~-._", server.requests.single().query) + server.api().send(ApiRequest(path = listOf("x"))) + assertNull(server.requests.last().query) + } + } + + @Test + fun sendsTheFixedHeadersAndNothingElseOfOurs() = runTest { + LoopbackServer { Reply(200, "ok") } + .use { server -> + val api = server.api() + assertEquals("ok", api.send(ApiRequest(path = listOf("x")))) + api.send(ApiRequest(path = listOf("x"), authenticated = false)) + val (signedIn, public) = server.requests + assertEquals("GET", signedIn.method) + assertEquals("application/json", signedIn.header("Accept")) + assertEquals(TEST_USER_AGENT, signedIn.header("User-Agent")) + assertEquals("Bearer ${testCredentials.apiKey}", signedIn.header("Authorization")) + assertNull(signedIn.header("Content-Type")) + assertEquals("", signedIn.body) + assertEquals(TEST_USER_AGENT, public.header("User-Agent")) + assertNull(public.header("Authorization")) + assertTrue(server.requests.all { it.header("Cookie") == null }) + assertTrue(server.requests.all { it.header("X-Cap-Video-Access") == null }) + } + } + + @Test + fun sendsJSONBodiesWithEveryWritingMethod() = runTest { + LoopbackServer { Reply(200) } + .use { server -> + val api = server.api() + val body = buildJsonObject { put("title", "Démo") } + val writing = + listOf(HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE) + for (method in writing) { + api.send(ApiRequest(method, path = listOf("x"), body = body)) + api.send(ApiRequest(method, path = listOf("x"))) + } + val requests = server.requests + assertEquals( + writing.flatMap { listOf(it.name, it.name) }, + requests.map { it.method }, + ) + for ((withBody, without) in requests.chunked(2)) { + assertEquals("application/json", withBody.header("Content-Type")) + assertEquals(body, withBody.json) + assertNull(without.header("Content-Type")) + assertEquals("", without.body) + } + } + } + + @Test + fun refusesToSendWithoutASessionOrWithAnUnsendableKey() = runTest { + LoopbackServer { Reply(200) } + .use { server -> + val request = ApiRequest(path = listOf("x")) + assertEquals(CapApiError.MissingSession, failure { server.api(null).send(request) }) + val unsendable = CredentialSnapshot(apiKey = "clé\nsecrète", userId = "user_123") + assertEquals( + CapApiError.BadRequest, + failure { server.api(unsendable).send(request) }, + ) + assertEquals(emptyList(), server.requests) + server.api(null).send(ApiRequest(path = listOf("x"), authenticated = false)) + assertEquals(1, server.requests.size) + } + } + + @Test + fun reportsUnauthorizedOnlyForRequestsThatCarriedCredentials() = runTest { + LoopbackServer { Reply(if (it.path == "/gone") 403 else 401) } + .use { server -> + val calls = CopyOnWriteArrayList() + val api = server.api(onUnauthorized = calls::add) + val public = ApiRequest(path = listOf("x"), authenticated = false) + assertEquals(CapApiError.Unauthorized, failure { api.send(public) }) + assertEquals( + CapApiError.Forbidden, + failure { api.send(ApiRequest(path = listOf("gone"))) }, + ) + assertEquals(emptyList(), calls.toList()) + assertEquals( + CapApiError.Unauthorized, + failure { api.send(ApiRequest(path = listOf("x"))) }, + ) + assertEquals(listOf(testCredentials), calls.toList()) + } + } + + @Test + fun retriesAGETOnceWhenTheConnectionDrops() = runTest { + val drops = AtomicInteger(1) + LoopbackServer { if (drops.getAndDecrement() > 0) null else Reply(200, "ok") } + .use { server -> + val api = server.api() + assertEquals("ok", api.send(ApiRequest(path = listOf("x")))) + assertEquals(2, server.requests.size) + + drops.set(2) + assertEquals( + CapApiError.Offline, + failure { api.send(ApiRequest(path = listOf("x"))) }, + ) + assertEquals(4, server.requests.size) + + drops.set(1) + val post = ApiRequest(HttpMethod.POST, path = listOf("x")) + assertEquals(CapApiError.Offline, failure { api.send(post) }) + assertEquals(5, server.requests.size) + assertEquals("ok", api.send(ApiRequest(path = listOf("x")))) + } + } + + @Test + fun sendsARequestOnceWhenTheServerAsksForAnImmediateRetry() = runTest { + LoopbackServer { Reply(503, headers = mapOf("Retry-After" to "0")) } + .use { server -> + val api = server.api() + val body = buildJsonObject { put("content", "hello") } + val requests = + listOf( + ApiRequest(HttpMethod.POST, path = listOf("x"), body = body), + ApiRequest(HttpMethod.POST, path = listOf("x")), + ApiRequest(HttpMethod.PUT, path = listOf("x"), body = body), + ApiRequest(HttpMethod.PATCH, path = listOf("x"), body = body), + ApiRequest(HttpMethod.DELETE, path = listOf("x")), + ApiRequest(path = listOf("x")), + ) + for (request in requests) { + assertEquals(CapApiError.Server(503), failure { api.send(request) }) + } + assertEquals( + listOf("POST", "POST", "PUT", "PATCH", "DELETE", "GET"), + server.requests.map { it.method }, + ) + } + } + + @Test + fun refusesRedirects() = runTest { + LoopbackServer { Reply(302, headers = mapOf("Location" to "/elsewhere")) } + .use { server -> + val error = failure { server.api().send(ApiRequest(path = listOf("x"))) } + assertEquals(CapApiError.UnexpectedStatus(302), error) + assertEquals(listOf("/x"), server.requests.map { it.path }) + } + } + + @Test + fun mapsErrorStatusesAndUnreachableServers() = runTest { + val server = LoopbackServer { Reply(it.path.removePrefix("/").toInt(), "{}") } + val api = server.api() + server.use { + val statuses = listOf(400, 404, 409, 413, 422, 429, 500) + assertEquals( + statuses.map(CapApiError::from), + statuses.map { failure { api.send(ApiRequest(path = listOf(it.toString()))) } }, + ) + } + assertEquals(CapApiError.Offline, failure { api.send(ApiRequest(path = listOf("200"))) }) + } + + @Test + fun undecodableBodiesBecomeInvalidResponse() = runTest { + LoopbackServer { Reply(200, if (it.path == "/html") "" else """{"success":"yes"}""") } + .use { server -> + val api = server.api() + for (path in listOf("html", "json")) { + val error = failure { api.fetch(ApiRequest(path = listOf(path))) } + assertEquals(path, CapApiError.InvalidResponse, error) + } + } + } + + @Test + fun sendsAnUnlockOnlyForItsCapAndOnlyWhileItLasts() = runTest { + LoopbackServer { Reply(200) } + .use { server -> + val api = server.api() + val abc = CapId.parse("abc")!! + val old = CapId.parse("old")!! + api.rememberVideoAccess( + abc, + CapUnlock("sealed-token", Instant.parse("2099-01-01T00:00:00Z")), + ) + api.rememberVideoAccess( + old, + CapUnlock("stale", Instant.parse("2001-01-01T00:00:00Z")), + ) + assertTrue(api.hasVideoAccess(abc)) + assertFalse(api.hasVideoAccess(old)) + for (access in listOf(abc, old, CapId.parse("other"), null)) { + api.send(ApiRequest(path = listOf("x"), videoAccess = access)) + } + api.send(ApiRequest(path = listOf("x"), authenticated = false, videoAccess = abc)) + assertEquals( + listOf("sealed-token", null, null, null, null), + server.requests.map { it.header("X-Cap-Video-Access") }, + ) + api.clearVideoAccess() + assertFalse(api.hasVideoAccess(abc)) + } + } + + @Test + fun cancellingTheCallerCancelsTheRequest() = runTest { + val arrived = CompletableDeferred() + val release = CountDownLatch(1) + LoopbackServer { + arrived.complete(Unit) + release.await() + Reply(200) + } + .use { server -> + val call = async { + runCatching { server.api().send(ApiRequest(path = listOf("x"))) } + } + arrived.await() + call.cancelAndJoin() + release.countDown() + assertTrue(call.isCancelled) + } + } + + @Test + fun attachesBearerOnlyToAuthenticatedRequests() = runTest { + LoopbackServer { request -> + if (request.path == "/api/mobile/session/config") cannedReply(request) + else Reply(200, fixture("bootstrap")) + } + .use { server -> + val api = server.api() + val config = api.authConfig() + assertFalse(config.googleAuthAvailable) + api.bootstrap() + val requests = server.requests + assertNull(requests[0].header("Authorization")) + assertEquals( + "Bearer ${testCredentials.apiKey}", + requests[1].header("Authorization"), + ) + assertEquals("/api/mobile/bootstrap", requests[1].path) + assertTrue(requests.all { it.header("Cookie") == null }) + } + } + + @Test + fun refusesAuthenticatedRequestsWithoutSession() = runTest { + LoopbackServer { Reply(200, "{}") } + .use { server -> + assertEquals(CapApiError.MissingSession, failure { server.api(null).bootstrap() }) + assertEquals(emptyList(), server.requests) + } + } + + @Test + fun dropsEmptyQueryItemsAndClampsPaging() = runTest { + LoopbackServer { Reply(200, fixture("caps")) } + .use { server -> + server.api().listCaps(folderId = null, spaceId = "space_1", page = 0, limit = 500) + assertEquals("spaceId=space_1&page=1&limit=50", server.requests.single().query) + } + } + + @Test + fun reportsUnauthorizedWithTheCredentialsThatFailed() = runTest { + LoopbackServer { Reply(401) } + .use { server -> + val calls = CopyOnWriteArrayList() + val api = server.api(onUnauthorized = calls::add) + assertEquals(CapApiError.Unauthorized, failure { api.bootstrap() }) + assertEquals(listOf(testCredentials), calls.toList()) + } + } + + @Test + fun doesNotSignOutOnPublicUnauthorized() = runTest { + LoopbackServer { Reply(401) } + .use { server -> + val calls = CopyOnWriteArrayList() + val api = server.api(onUnauthorized = calls::add) + assertEquals(CapApiError.Unauthorized, failure { api.authConfig() }) + assertEquals(emptyList(), calls.toList()) + } + } + + @Test + fun invalidJSONBecomesInvalidResponse() = runTest { + LoopbackServer { Reply(200, "") } + .use { server -> + assertEquals(CapApiError.InvalidResponse, failure { server.api().bootstrap() }) + } + } + + @Test + fun encodesExplicitNullsWhereTheContractRequiresThem() = runTest { + val cap = json(fixture("cap-detail")).getValue("cap").toString() + LoopbackServer { request -> + when (request.path) { + "/api/mobile/caps/cap_1/password" -> Reply(200, cap) + "/api/mobile/organization/settings" -> Reply(200, fixture("org-settings")) + else -> cannedReply(request) + } + } + .use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + api.updateProfile(name = "R", lastName = null) + api.updatePassword(id, password = null) + api.updateOrganizationSettings(name = "Cap", allowedEmailDomain = null) + api.createReaction(id, emoji = "👍", timestamp = null) + api.createComment(id, content = "Hi", timestamp = null) + + val bodies = server.requests.map { it.json } + assertEquals(JsonNull, bodies[0]["lastName"]) + assertEquals(JsonNull, bodies[1]["password"]) + assertEquals(JsonNull, bodies[2]["allowedEmailDomain"]) + assertEquals(JsonNull, bodies[3]["timestamp"]) + assertEquals(JsonNull, bodies[4]["timestamp"]) + assertFalse("parentCommentId" in bodies[4]) + assertEquals( + listOf("PATCH", "PATCH", "PATCH", "POST", "POST"), + server.requests.map { it.method }, + ) + assertTrue(server.requests.all { it.header("Content-Type") == "application/json" }) + } + } + + @Test + fun emailRequestsNormalizeAddresses() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + api.requestEmailCode(email = " Richie@Cap.so ") + val session = api.verifyEmailCode(email = "Richie@Cap.so", code = "123456") + assertEquals("user_123", session.userId) + val bodies = server.requests.map { it.json } + assertEquals(json("""{"email":"richie@cap.so"}"""), bodies[0]) + assertEquals(json("""{"email":"richie@cap.so","code":"123456"}"""), bodies[1]) + assertTrue(server.requests.all { it.header("Authorization") == null }) + } + } + + @Test + fun registersAndRemovesPushTokens() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + api.registerPushToken("ab12", PushEnvironment.SANDBOX) + api.removePushToken("ab12") + val requests = server.requests + assertEquals( + listOf("/api/mobile/user/push-tokens", "/api/mobile/user/push-tokens/remove"), + requests.map { it.path }, + ) + assertEquals(listOf("POST", "POST"), requests.map { it.method }) + assertTrue( + requests.all { it.header("Authorization") == "Bearer ${testCredentials.apiKey}" } + ) + assertEquals(json("""{"token":"ab12","environment":"sandbox"}"""), requests[0].json) + assertEquals(json("""{"token":"ab12"}"""), requests[1].json) + } + } + + @Test + fun sharingSendsLinkAccessOnlyWhenChosen() = runTest { + LoopbackServer { Reply(200, CAP_JSON.replace("}", ""","linkAccess":"anyone"}""")) } + .use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + api.updateSharing(id, isPublic = false) + val opened = api.updateSharing(id, isPublic = true, linkAccess = LinkAccess.ANYONE) + api.updateSharing(id, isPublic = true, linkAccess = LinkAccess.RESTRICTED) + val requests = server.requests + assertTrue( + requests.all { + it.path == "/api/mobile/caps/cap_1/sharing" && it.method == "PATCH" + } + ) + assertEquals(json("""{"public":false}"""), requests[0].json) + assertEquals(json("""{"public":true,"linkAccess":"anyone"}"""), requests[1].json) + assertEquals( + json("""{"public":true,"linkAccess":"restricted"}"""), + requests[2].json, + ) + assertEquals(LinkAccess.ANYONE, opened.linkAccess) + } + } + + @Test + fun rejectsImplausibleSessionsFromVerify() = runTest { + LoopbackServer { Reply(200, """{"type":"api_key","apiKey":"x","userId":"user_123"}""") } + .use { server -> + val error = failure { + server.api().verifyEmailCode(email = "r@cap.so", code = "123456") + } + assertEquals(CapApiError.InvalidResponse, error) + } + } + + @Test + fun sessionRequestURLUsesFixedRedirect() { + val url = + productionApi().sessionRequestUrl(provider = "google", state = "abc_DEF-0123456789") + assertEquals( + "https://cap.so/api/mobile/session/request?redirectUri=cap%3A%2F%2Fauth&provider=google" + + "&state=abc_DEF-0123456789", + url, + ) + val parts = UrlParts.parse(url)!! + assertEquals("cap.so", parts.host) + assertEquals("/api/mobile/session/request", parts.path) + assertEquals( + listOf( + "redirectUri" to "cap://auth", + "provider" to "google", + "state" to "abc_DEF-0123456789", + ), + parts.queryItems, + ) + } + + @Test + fun authorizationHeaderOnlyForCapOrigin() { + val api = productionApi() + assertEquals( + "Bearer ${testCredentials.apiKey}", + api.authorizationHeader("https://cap.so/api/mobile/caps/x/thumbnail"), + ) + assertNull(api.authorizationHeader("https://s3.amazonaws.com/x")) + assertNull(api.authorizationHeader("http://cap.so/x")) + assertNull(productionApi(credentials = null).authorizationHeader("https://cap.so/x")) + } + + @Test + fun credentialsFollowTheHostTheHTTPClientConnectsTo() { + val api = productionApi() + for (url in + listOf( + "https://evil.example\\@cap.so/x", + "https://evil.example:443\\@cap.so:443/x", + "https://evil.example\\.cap.so/x", + "https://cap.so@evil.example/x", + "https://cap.so:443@evil.example:444/x", + "https://evil.example#@cap.so/x", + "https://evil.example?@cap.so/x", + "https://evil.example/@cap.so/x", + "https://cap.so%2Eevil.example/x", + "https://cap.so%00.evil.example/x", + "https://cap.so;evil.example/x", + "https://cap.so,evil.example/x", + "https://cap.so./x", + "https://cap.so:444/x", + "https://cap.so:443:444/x", + "https://cap.so\t/x", + "https://cap.so\n.evil.example/x", + "https://ca\tp.so/x", + "ht\ttps://cap.so/x", + "https://cap.so /x", + "https://сap.so/x", + "http:\\\\cap.so/x", + "//cap.so/x", + "cap.so/x", + )) { + assertFalse(url, CapEnvironment.PRODUCTION.isSameOrigin(url)) + assertNull(url, api.authorizationHeader(url)) + assertEquals(url, emptyMap(), api.mediaHeaders(url)) + } + for (url in + listOf( + "https://cap.so\\@evil.example/x", + "https://evil.example%2f@cap.so/x", + "https://evil.example@cap.so/x", + "https://evil.example\t@cap.so/x", + "HTTPS://CAP.SO/x", + "https://cap.so:0443/x", + "https://cap。so/x", + "https://cap.so/x", + "https:\\\\cap.so/x", + "https:cap.so/x", + " https://cap.so/x ", + )) { + assertTrue(url, CapEnvironment.PRODUCTION.isSameOrigin(url)) + assertEquals(url, "Bearer ${testCredentials.apiKey}", api.authorizationHeader(url)) + } + } + + @Test + fun hostileMediaURLsNeverCarryCredentialsToAnotherServer() = runTest { + LoopbackServer(::cannedReply).use { cap -> + LoopbackServer { Reply(200) } + .use { other -> + val api = cap.api() + api.unlockCap(CapId.parse("cap_1")!!, password = "pw") + val capHost = cap.environment.baseUrl.removePrefix("http://") + val otherHost = other.environment.baseUrl.removePrefix("http://") + val path = "api/mobile/caps/cap_1/thumbnail" + val toOther = + listOf( + "http://$otherHost\\@$capHost/$path", + "http://$otherHost\\.$capHost/$path", + "http://$capHost@$otherHost/$path", + "http://$otherHost#@$capHost/$path", + "http://$otherHost?@$capHost/$path", + "http://$otherHost/@$capHost/$path", + "HTTP:\\\\$otherHost/$path#$capHost", + ) + val toCapUnderAnotherName = + "http://localhost:${capHost.substringAfter(':')}/$path" + val toCap = + listOf( + "http://$capHost/$path", + "HTTP://$capHost/$path", + "http://$otherHost%2f@$capHost/$path", + "http://$otherHost\t@$capHost/$path", + "http://$capHost\\@$otherHost/$path", + ) + val client = OkHttpClient() + for (url in toOther + toCapUnderAnotherName + toCap) { + val request = Request.Builder().url(url) + api.mediaHeaders(url).forEach { (name, value) -> + request.header(name, value) + } + client.newCall(request.build()).execute().close() + } + + val fetches = cap.requests.filter { it.method == "GET" } + val strays = other.requests + fetches.filter { it.header("Host") != capHost } + assertEquals(toOther.size, other.requests.size) + assertEquals(toOther.size + 1, strays.size) + for (request in strays) { + assertNull(request.path, request.header("Authorization")) + assertNull(request.path, request.header("X-Cap-Video-Access")) + } + val served = fetches.filter { it.header("Host") == capHost } + assertEquals(toCap.size, served.size) + assertTrue( + served.all { + it.header("Authorization") == "Bearer ${testCredentials.apiKey}" + } + ) + assertEquals("sealed-token", served.first().header("X-Cap-Video-Access")) + } + } + } + + @Test + fun capStatusesDedupesAndCaps() = runTest { + LoopbackServer { Reply(200, """{"caps":[]}""") } + .use { server -> + val api = server.api() + api.capStatuses(ids = (0 until 40).map { "cap_${it % 30}" }) + val ids = + server.requests[0].json.getValue("ids").jsonArray.map { + it.jsonPrimitive.content + } + assertEquals(25, ids.size) + assertEquals(25, ids.toSet().size) + assertEquals(ids.sorted(), ids) + api.capStatuses(ids = emptyList()) + assertEquals(1, server.requests.size) + } + } + + @Test + fun passwordUnlockIsSentOnlyForThatCap() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val abc = CapId.parse("cap_1")!! + val other = CapId.parse("other")!! + api.unlockCap(abc, password = "hunter2") + api.capAccess(abc) + api.capAccess(other) + val requests = server.requests + assertNull(requests[0].header("X-Cap-Video-Access")) + assertEquals(json("""{"password":"hunter2"}"""), requests[0].json) + assertEquals("sealed-token", requests[1].header("X-Cap-Video-Access")) + assertNull(requests[2].header("X-Cap-Video-Access")) + api.clearVideoAccess() + assertFalse(api.hasVideoAccess(abc)) + } + } + + @Test + fun unlockTravelsOnlyWithThatCapsThumbnail() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val origin = server.environment.baseUrl + api.unlockCap(CapId.parse("cap_1")!!, password = "pw") + fun unlock(url: String) = api.mediaHeaders(url)["X-Cap-Video-Access"] + assertEquals("sealed-token", unlock("$origin/api/mobile/caps/cap_1/thumbnail?v=1")) + assertNull(unlock("$origin/api/mobile/caps/other/thumbnail")) + assertNull(unlock("$origin/api/mobile/caps/cap_1")) + assertNull(unlock("$origin/api/desktop/caps/cap_1/thumbnail")) + assertEquals( + emptyMap(), + api.mediaHeaders("https://s3.amazonaws.com/api/mobile/caps/cap_1/thumbnail"), + ) + assertEquals( + "Bearer ${testCredentials.apiKey}", + api.mediaHeaders("$origin/api/mobile/caps/cap_1/thumbnail")["Authorization"], + ) + assertEquals( + mapOf("Authorization" to "Bearer ${testCredentials.apiKey}"), + api.mediaHeaders("$origin/avatars/user_1.png"), + ) + } + } + + @Test + fun unlockTravelsOnlyWithThatCapsPlaylists() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val origin = server.environment.baseUrl + api.unlockCap(CapId.parse("cap_1")!!, password = "pw") + fun unlock(url: String) = api.mediaHeaders(url)["X-Cap-Video-Access"] + assertEquals( + "sealed-token", + unlock("$origin/api/playlist?videoId=cap_1&videoType=segments-master"), + ) + assertEquals( + "sealed-token", + unlock("$origin/api/playlist?videoId=cap_1&videoType=segments-video"), + ) + assertNull(unlock("$origin/api/playlist?videoId=other&videoType=segments-master")) + assertNull(unlock("$origin/api/playlist?videoType=segments-master")) + assertNull(unlock("$origin/api/playlists?videoId=cap_1")) + assertNull(unlock("$origin/other/api/playlist?videoId=cap_1")) + assertEquals( + emptyMap(), + api.mediaHeaders("https://s3.amazonaws.com/api/playlist?videoId=cap_1"), + ) + } + } + + @Test + fun expiredUnlocksAreDropped() = runTest { + LoopbackServer { + Reply(200, """{"accessToken":"t","expiresAt":"2001-01-01T00:00:00.000Z"}""") + } + .use { server -> + val api = server.api() + api.unlockCap(CapId.parse("abc")!!, password = "pw") + assertFalse(api.hasVideoAccess(CapId.parse("abc")!!)) + } + } + + @Test + fun accessStatusFallsBackToUnknown() = runTest { + LoopbackServer { Reply(200, """{"status":"sign_in_required"}""") } + .use { server -> + assertEquals(CapAccessStatus.UNKNOWN, server.api().capAccess(CapId.parse("abc")!!)) + } + } + + @Test + fun rejectsUnusableUnlockTokens() = runTest { + val tokens = listOf("", "x".repeat(4097)) + LoopbackServer { + val token = tokens[it.path.split('/')[4].removePrefix("cap").toInt()] + Reply(200, """{"accessToken":"$token","expiresAt":"2099-01-01T00:00:00.000Z"}""") + } + .use { server -> + val api = server.api() + for (index in tokens.indices) { + val id = CapId.parse("cap$index")!! + assertEquals(CapApiError.InvalidResponse, failure { api.unlockCap(id, "pw") }) + assertFalse(api.hasVideoAccess(id)) + } + } + } + + @Test + fun sessionAndAccountRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + api.revokeSession() + val bootstrap = api.setActiveOrganization("org_2") + api.requestAccountDeletion() + api.blockUser("user_9") + assertEquals("org_1", bootstrap.user.activeOrganizationId) + server.assertShapes( + Shape("POST", "/api/mobile/session/revoke"), + Shape( + "PATCH", + "/api/mobile/user/active-organization", + """{"organizationId":"org_2"}""", + ), + Shape("POST", "/api/mobile/user/account-deletion", """{"confirmation":"DELETE"}"""), + Shape("POST", "/api/mobile/user/blocks", """{"userId":"user_9"}"""), + ) + } + } + + @Test + fun imageUploadsSendBase64JSON() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val image = EncodedImage(byteArrayOf(-1, -40, -1, 0, 62), "image/jpeg", "image.jpg") + val payload = + """{"data":"/9j/AD4=","contentType":"image/jpeg","fileName":"image.jpg"}""" + assertEquals("user_123", api.updateProfileImage(image).id) + assertEquals("user_123", api.removeProfileImage().id) + assertEquals("org_123", api.updateOrganizationIcon(image).id) + assertEquals("org_123", api.removeOrganizationIcon().id) + server.assertShapes( + Shape("PUT", "/api/mobile/user/profile/image", payload), + Shape("DELETE", "/api/mobile/user/profile/image"), + Shape("PUT", "/api/mobile/organization/settings/icon", payload), + Shape("DELETE", "/api/mobile/organization/settings/icon"), + ) + } + } + + @Test + fun folderAndReportRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + assertEquals( + FolderColor.BLUE, + api.createFolder("Product", FolderColor.BLUE, spaceId = null).color, + ) + api.createFolder("Design", FolderColor.NORMAL, spaceId = "space_1") + for (reason in ContentReportReason.entries) { + api.reportCap(id, reason) + } + val reasons = listOf("harassment", "hate", "sexual", "violence", "copyright", "other") + server.assertShapes( + Shape("POST", "/api/mobile/folders", """{"name":"Product","color":"blue"}"""), + Shape( + "POST", + "/api/mobile/folders", + """{"name":"Design","color":"normal","spaceId":"space_1"}""", + ), + *reasons + .map { Shape("POST", "/api/mobile/caps/cap_1/report", """{"reason":"$it"}""") } + .toTypedArray(), + ) + } + } + + @Test + fun userAndOrganisationRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + assertEquals("Richie", api.updateProfile(name = "Richie", lastName = "McIlroy").name) + assertFalse(api.notificationPreferences().replies) + api.setNotification(NotificationPreferences.Kind.ANONYMOUS_VIEWS, enabled = false) + assertEquals("Cap", api.organizationSettings().name) + api.updateOrganizationSettings(name = "Cap", allowedEmailDomain = "cap.so") + assertTrue(api.plan().upgraded) + server.assertShapes( + Shape( + "PATCH", + "/api/mobile/user/profile", + """{"name":"Richie","lastName":"McIlroy"}""", + ), + Shape("GET", "/api/mobile/user/notification-preferences"), + Shape( + "PATCH", + "/api/mobile/user/notification-preferences", + """{"anonymousViews":false}""", + ), + Shape("GET", "/api/mobile/organization/settings"), + Shape( + "PATCH", + "/api/mobile/organization/settings", + """{"name":"Cap","allowedEmailDomain":"cap.so"}""", + ), + Shape("GET", "/api/desktop/plan"), + ) + } + } + + @Test + fun capRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + assertEquals(1, api.listCaps(folderId = "folder_1", page = 3).page) + assertEquals("cap_1", api.cap(id).cap.id) + assertEquals(CapAccessStatus.GRANTED, api.capAccess(id)) + api.trackView(id, sessionId = "session_1") + assertEquals("Demo", api.updateTitle(id, title = "Renamed").title) + api.updatePassword(id, password = "hunter2") + assertEquals(PlaybackKind.HLS, api.playback(id).kind) + assertEquals("Demo.mp4", api.download(id).fileName) + assertFalse(api.capAnalytics(id, AnalyticsRange.DAY).available) + api.organizationAnalytics(AnalyticsRange.LIFETIME) + api.organizationAnalytics(AnalyticsRange.MONTH, spaceId = "space_1") + assertEquals("cap_9", api.importLoom("https://www.loom.com/share/abc").id) + api.deleteCap(id) + server.assertShapes( + Shape("GET", "/api/mobile/caps", query = "folderId=folder_1&page=3&limit=30"), + Shape("GET", "/api/mobile/caps/cap_1"), + Shape("GET", "/api/mobile/caps/cap_1/access"), + Shape("POST", "/api/mobile/caps/cap_1/views", """{"sessionId":"session_1"}"""), + Shape("PATCH", "/api/mobile/caps/cap_1/title", """{"title":"Renamed"}"""), + Shape("PATCH", "/api/mobile/caps/cap_1/password", """{"password":"hunter2"}"""), + Shape("GET", "/api/mobile/caps/cap_1/playback"), + Shape("GET", "/api/mobile/caps/cap_1/download"), + Shape("GET", "/api/mobile/caps/cap_1/analytics", query = "range=24h"), + Shape("GET", "/api/mobile/analytics", query = "range=lifetime"), + Shape("GET", "/api/mobile/analytics", query = "range=30d&spaceId=space_1"), + Shape( + "POST", + "/api/mobile/imports/loom", + """{"loomUrl":"https://www.loom.com/share/abc"}""", + ), + Shape("DELETE", "/api/mobile/caps/cap_1"), + ) + } + } + + @Test + fun commentRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + assertEquals( + CommentKind.EMOJI, + api.createReaction(id, emoji = "🔥", timestamp = 12.5).type, + ) + api.createComment(id, content = "Reply", timestamp = 3.0, parentCommentId = "c_1") + api.deleteComment("c/1") + assertEquals( + CapApiError.BadRequest, + failure { api.createComment(id, "Hi", Double.NaN) }, + ) + assertEquals( + CapApiError.BadRequest, + failure { api.createReaction(id, "🔥", Double.POSITIVE_INFINITY) }, + ) + server.assertShapes( + Shape( + "POST", + "/api/mobile/caps/cap_1/reactions", + """{"content":"🔥","timestamp":12.5}""", + ), + Shape( + "POST", + "/api/mobile/caps/cap_1/comments", + """{"content":"Reply","timestamp":3.0,"parentCommentId":"c_1"}""", + ), + Shape("DELETE", "/api/mobile/comments/c%2F1"), + ) + } + } + + @Test + fun uploadRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + val full = + UploadRequest( + organizationId = "org_1", + folderId = "folder_1", + fileName = "clip.mp4", + contentType = "video/mp4", + contentLength = 5_000_000_000, + durationSeconds = 12.5, + width = 1920, + height = 1080, + fps = 29.97, + ) + val created = api.createUpload(full) + assertEquals( + UploadTarget.Put("https://r2.example.com/x", mapOf("Content-Type" to "video/mp4")), + created.upload, + ) + api.createUpload( + full.copy( + organizationId = null, + folderId = null, + contentLength = null, + durationSeconds = null, + width = null, + height = null, + fps = null, + ) + ) + api.updateUploadProgress(id, uploaded = 2_500_000_000, total = 5_000_000_000) + api.completeUpload( + id, + rawFileKey = "user_123/cap_1/raw-upload.mp4", + contentLength = 5_000_000_000, + ) + api.completeUpload( + id, + rawFileKey = "user_123/cap_1/raw-upload.mp4", + contentLength = null, + ) + assertEquals( + CapApiError.BadRequest, + failure { api.createUpload(full.copy(durationSeconds = Double.NaN)) }, + ) + server.assertShapes( + Shape( + "POST", + "/api/mobile/uploads", + """{"organizationId":"org_1","folderId":"folder_1","fileName":"clip.mp4","contentType":"video/mp4","contentLength":5000000000,"durationSeconds":12.5,"width":1920,"height":1080,"fps":29.97}""", + ), + Shape( + "POST", + "/api/mobile/uploads", + """{"fileName":"clip.mp4","contentType":"video/mp4"}""", + ), + Shape( + "POST", + "/api/mobile/uploads/cap_1/progress", + """{"uploaded":2500000000,"total":5000000000}""", + ), + Shape( + "POST", + "/api/mobile/uploads/cap_1/complete", + """{"rawFileKey":"user_123/cap_1/raw-upload.mp4","contentLength":5000000000}""", + ), + Shape( + "POST", + "/api/mobile/uploads/cap_1/complete", + """{"rawFileKey":"user_123/cap_1/raw-upload.mp4"}""", + ), + ) + } + } + + @Test + fun recordingRequestsMatchTheContract() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + val created = + api.createRecording( + "Recording.mp4", + 1080, + 1920, + 30, + organizationId = "org_1", + folderId = null, + ) + assertEquals(RecordingCreated("cap_9", "https://cap.so/s/cap_9"), created) + api.createRecording( + "Recording.mp4", + 1080, + 1920, + 30, + organizationId = null, + folderId = "folder_1", + ) + val subpaths = listOf("segments/video/init.mp4", "segments/video/segment_001.m4s") + val targets = api.recordingUploadTargets(id, subpaths) + assertEquals( + mapOf(subpaths[0] to UploadTarget.Put("https://r2.example.com/init", emptyMap())), + targets, + ) + val segment = RecordingCompletion.Segment(index = 1, duration = 2.0) + api.completeRecording(id, RecordingCompletion(2.0, 4096, listOf(segment), emptyList())) + server.assertShapes( + Shape( + "POST", + "/api/mobile/recordings", + """{"organizationId":"org_1","fileName":"Recording.mp4","width":1080,"height":1920,"fps":30}""", + ), + Shape( + "POST", + "/api/mobile/recordings", + """{"folderId":"folder_1","fileName":"Recording.mp4","width":1080,"height":1920,"fps":30}""", + ), + Shape( + "POST", + "/api/mobile/recordings/cap_1/segments/targets", + """{"subpaths":["segments/video/init.mp4","segments/video/segment_001.m4s"]}""", + ), + Shape( + "POST", + "/api/mobile/recordings/cap_1/complete", + """{"durationSeconds":2.0,"totalBytes":4096,"videoSegments":[{"index":1,"duration":2.0}],"audioSegments":[]}""", + ), + ) + } + } + + @Test + fun everySignedInRequestCarriesTheBearerAndOnlyViewerRequestsTheUnlock() = runTest { + LoopbackServer(::cannedReply).use { server -> + val api = server.api() + val id = CapId.parse("cap_1")!! + api.unlockCap(id, password = "pw") + api.cap(id) + api.capAccess(id) + api.trackView(id, sessionId = "s") + api.reportCap(id, ContentReportReason.OTHER) + api.playback(id) + api.download(id) + api.createComment(id, content = "Hi", timestamp = null) + api.createReaction(id, emoji = "👍", timestamp = null) + api.updateSharing(id, isPublic = true) + api.updateTitle(id, title = "T") + api.updatePassword(id, password = null) + api.capAnalytics(id, AnalyticsRange.WEEK) + api.updateUploadProgress(id, uploaded = 1, total = 2) + api.deleteCap(id) + val requests = server.requests + assertTrue( + requests.all { it.header("Authorization") == "Bearer ${testCredentials.apiKey}" } + ) + assertTrue(requests.all { it.header("User-Agent") == TEST_USER_AGENT }) + assertEquals( + listOf( + "cap_1", + "access", + "views", + "report", + "playback", + "download", + "comments", + "reactions", + ), + requests + .filter { it.header("X-Cap-Video-Access") == "sealed-token" } + .map { it.path.substringAfterLast('/') }, + ) + } + } + + @Test + fun anUnsuccessfulAcknowledgementIsAnInvalidResponse() = runTest { + LoopbackServer { Reply(200, """{"success":false}""") } + .use { server -> + assertEquals(CapApiError.InvalidResponse, failure { server.api().revokeSession() }) + assertEquals( + CapApiError.InvalidResponse, + failure { server.api().deleteComment("c_1") }, + ) + } + } +} + +internal class RecordedRequest( + val method: String, + val path: String, + val query: String?, + private val headers: Headers, + val body: String, +) { + fun header(name: String): String? = headers.getFirst(name) + + val json: JsonObject + get() = CapJson.json.parseToJsonElement(body).jsonObject +} + +internal class Reply( + val status: Int, + val body: String = "", + val headers: Map = emptyMap(), +) + +internal class LoopbackServer(private val responder: (RecordedRequest) -> Reply?) : AutoCloseable { + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + private val recorded = CopyOnWriteArrayList() + + val requests: List + get() = recorded.toList() + + val environment: CapEnvironment + get() = + CapEnvironment.parse( + "http://127.0.0.1:${server.address.port}", + allowInsecureLocalhost = true, + )!! + + init { + server.createContext("/") { exchange -> + val request = + RecordedRequest( + exchange.requestMethod, + exchange.requestURI.rawPath, + exchange.requestURI.rawQuery, + exchange.requestHeaders, + exchange.requestBody.readBytes().decodeToString(), + ) + recorded += request + val reply = responder(request) + if (reply == null) { + exchange.close() + return@createContext + } + val bytes = reply.body.toByteArray() + reply.headers.forEach { (name, value) -> exchange.responseHeaders.add(name, value) } + exchange.sendResponseHeaders( + reply.status, + if (bytes.isEmpty()) -1 else bytes.size.toLong(), + ) + exchange.responseBody.use { it.write(bytes) } + } + server.start() + } + + fun api( + credentials: CredentialSnapshot? = testCredentials, + onUnauthorized: (CredentialSnapshot) -> Unit = {}, + ) = CapApi(environment, TEST_USER_AGENT, { credentials }, onUnauthorized) + + override fun close() = server.stop(0) +} + +internal const val TEST_USER_AGENT = "Cap-Android/1.2.3 (45)" + +internal val testCredentials = + CredentialSnapshot(apiKey = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e", userId = "user_123") + +internal suspend fun failure(block: suspend () -> Unit): CapApiError { + try { + block() + } catch (exception: CapApiException) { + return exception.error + } + throw AssertionError("Expected a CapApiException") +} + +internal class Shape( + val method: String, + val path: String, + val body: String? = null, + val query: String? = null, +) + +internal fun LoopbackServer.assertShapes(vararg expected: Shape) { + val actual = requests + assertEquals( + expected.map { "${it.method} ${it.path}?${it.query.orEmpty()}" }, + actual.map { "${it.method} ${it.path}?${it.query.orEmpty()}" }, + ) + for ((shape, request) in expected.zip(actual)) { + val label = "${shape.method} ${shape.path}" + if (shape.body == null) { + assertEquals(label, "", request.body) + assertNull(label, request.header("Content-Type")) + } else { + assertEquals(label, json(shape.body), request.json) + assertEquals(label, "application/json", request.header("Content-Type")) + } + } +} + +internal fun json(text: String): JsonObject = CapJson.json.parseToJsonElement(text).jsonObject + +private fun productionApi(credentials: CredentialSnapshot? = testCredentials) = + CapApi(CapEnvironment.PRODUCTION, TEST_USER_AGENT, { credentials }) + +private const val USER_JSON = + """{"id":"user_123","name":"Richie","lastName":null,"email":"r@cap.so","imageUrl":null,"activeOrganizationId":"org_1"}""" + +private const val CAP_JSON = + """{"id":"cap_1","shareUrl":"https://cap.so/s/cap_1","title":"Demo","createdAt":"2026-11-01T00:00:00.000Z","updatedAt":"2026-11-01T00:00:00.000Z","ownerName":"Owner","durationSeconds":null,"thumbnailUrl":null,"folderId":null,"public":true,"protected":false,"viewCount":0,"commentCount":0,"reactionCount":0,"upload":null}""" + +private const val COMMENT_JSON = + """{"id":"c","videoId":"cap_1","type":"emoji","content":"👍","timestamp":null,"parentCommentId":null,"createdAt":"2026-10-28T11:00:00.000Z","updatedAt":"2026-10-28T11:00:00.000Z","author":{"id":"u","name":null,"imageUrl":null}}""" + +private const val SETTINGS_JSON = + """{"id":"org_123","name":"Cap","role":"admin","canManage":true,"iconUrl":null,"allowedEmailDomain":"cap.so","customDomain":null,"domainVerified":false}""" + +private fun cannedReply(request: RecordedRequest): Reply { + val path = request.path.removePrefix("/api/mobile/") + val body = + when { + path == "session/config" -> + """{"appleAuthAvailable":true,"googleAuthAvailable":false,"workosAuthAvailable":true}""" + path == "session/email/verify" -> + """{"type":"api_key","apiKey":"${testCredentials.apiKey}","userId":"user_123"}""" + path == "bootstrap" || path == "user/active-organization" -> + """{"user":$USER_JSON,"organizations":[],"activeOrganizationId":"org_1","rootFolders":[]}""" + path.startsWith("user/profile") -> USER_JSON + path == "user/notification-preferences" -> + """{"comments":true,"replies":false,"views":true,"anonymousViews":true,"reactions":true}""" + path == "caps" -> + """{"folders":[],"caps":[$CAP_JSON],"page":1,"limit":30,"total":1,"hasMore":false}""" + path == "folders" -> + """{"id":"folder_9","name":"Product","color":"blue","parentId":null,"videoCount":0}""" + path == "caps/cap_1" && request.method == "GET" -> + """{"cap":$CAP_JSON,"summary":null,"chapters":[],"transcriptionStatus":null,"comments":[],"shareUrl":"https://cap.so/s/cap_1"}""" + path.endsWith("/access") -> """{"status":"granted"}""" + path.endsWith("/unlock") -> + """{"accessToken":"sealed-token","expiresAt":"2099-01-01T00:00:00.000Z"}""" + path.endsWith("/sharing") || path.endsWith("/title") || path.endsWith("/password") -> + CAP_JSON + path.endsWith("/playback") -> + """{"kind":"hls","url":"https://cap.so/api/playlist?videoId=cap_1","transcriptUrl":null}""" + path.endsWith("/download") -> + """{"fileName":"Demo.mp4","url":"https://s3.example.com/x"}""" + path.endsWith("analytics") -> """{"available":false,"data":null}""" + path.startsWith("organization/settings") -> SETTINGS_JSON + path == "imports/loom" || path == "recordings" -> + """{"id":"cap_9","shareUrl":"https://cap.so/s/cap_9"}""" + path.endsWith("/comments") || path.endsWith("/reactions") -> COMMENT_JSON + path == "uploads" -> + """{"id":"cap_9","shareUrl":"https://cap.so/s/cap_9","rawFileKey":"user_123/cap_9/raw-upload.mp4","upload":{"type":"put","url":"https://r2.example.com/x","headers":{"Content-Type":"video/mp4"}}}""" + path.endsWith("/segments/targets") -> + """{"uploads":{"segments/video/init.mp4":{"type":"put","url":"https://r2.example.com/init","headers":{}}}}""" + request.path == "/api/desktop/plan" -> + """{"upgraded":true,"stripeSubscriptionStatus":"active"}""" + else -> """{"success":true}""" + } + return Reply(200, body) +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/DecodingTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/DecodingTest.kt new file mode 100644 index 00000000000..0d12be8c239 --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/DecodingTest.kt @@ -0,0 +1,776 @@ +package so.cap.kit + +import java.time.Instant +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.builtins.serializer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +internal fun fixture(name: String): String = + checkNotNull(DecodingTest::class.java.getResource("/$name.json")) { "No fixture named $name" } + .readText() + +class DecodingTest { + private val json = CapJson.json + + @Test + fun bootstrapSkipsMalformedOrganizationsAndDefaultsUnknownRoles() { + val bootstrap = json.decodeFromString(fixture("bootstrap")) + assertEquals("Richie McIlroy", bootstrap.user.displayName) + assertEquals(listOf("org_123", "org_456"), bootstrap.organizations.map { it.id }) + assertEquals(MemberRole.MEMBER, bootstrap.organizations[1].role) + assertEquals("Cap", bootstrap.activeOrganization?.name) + assertEquals(2, bootstrap.spaces.size) + assertEquals(SpacePrivacy.PUBLIC, bootstrap.spaces[1].privacy) + assertTrue(bootstrap.spaces[1].hasPassword) + assertEquals(FolderColor.BLUE, bootstrap.rootFolders.first().color) + } + + @Test + fun capsPageDropsBrokenCapsInsteadOfFailing() { + val page = json.decodeFromString(fixture("caps")) + assertEquals(listOf("cap_1", "cap_2"), page.caps.map { it.id }) + assertEquals(FolderColor.NORMAL, page.folders.first().color) + assertEquals(12, page.collectionTotal) + val first = page.caps[0] + assertTrue(first.isPublic) + assertEquals(1200, first.viewCount) + assertEquals(125.4, first.durationSeconds) + assertTrue(first.isOwned("someone-else")) + val second = page.caps[1] + assertTrue(second.isProtected) + assertNull(second.ownedByCurrentUser) + assertFalse(second.isOwned("user_123")) + assertEquals(0.25, second.upload?.fractionCompleted) + assertTrue(second.isProcessing) + } + + @Test + fun capDetailDecodesChaptersAndComments() { + val detail = json.decodeFromString(fixture("cap-detail")) + assertEquals(2, detail.chapters.size) + assertEquals(TranscriptionStatus.COMPLETE, detail.transcriptionStatus) + assertEquals(listOf(CommentKind.TEXT, CommentKind.EMOJI), detail.comments.map { it.type }) + assertEquals(12.5, detail.comments[0].timestamp) + assertFalse(detail.cap.isOwned("user_123")) + } + + @Test + fun analyticsParsesBucketsAndTopCapIds() { + val data = json.decodeFromString(fixture("analytics")).data!! + assertEquals(1200, data.counts.views) + assertEquals(2, data.chart.mapNotNull { it.date }.size) + assertEquals("cap_1", data.breakdowns.topCaps.first().capId) + assertEquals("GB", data.breakdowns.cities.first().subtitle) + } + + @Test + fun organizationSettingsDecode() { + val settings = json.decodeFromString(fixture("org-settings")) + assertEquals(MemberRole.ADMIN, settings.role) + assertEquals("videos.cap.so", settings.customDomain) + } + + @Test + fun snapshotsRoundTripThroughEncoder() { + val page = json.decodeFromString(fixture("caps")) + assertEquals(page, json.decodeFromString(json.encodeToString(page))) + val analytics = json.decodeFromString(fixture("analytics")) + assertEquals( + analytics, + json.decodeFromString(json.encodeToString(analytics)), + ) + } + + @Test + fun numbersAndBooleansMustBeUnquotedJSON() { + assertEquals(12.0, json.decodeFromString(NumberSerializer, "12"), 0.0) + assertEquals(12.7, json.decodeFromString(NumberSerializer, "12.7"), 0.0) + for (bad in listOf("\"12\"", "true", "null", "1e400", "{}")) { + assertThrows(bad, SerializationException::class.java) { + json.decodeFromString(NumberSerializer, bad) + } + } + assertEquals(true, json.decodeFromString(StrictBooleanSerializer, "true")) + for (bad in listOf("\"true\"", "1", "null")) { + assertThrows(bad, SerializationException::class.java) { + json.decodeFromString(StrictBooleanSerializer, bad) + } + } + assertThrows(SerializationException::class.java) { + json.decodeFromString(String.serializer(), "12") + } + } + + @Test + fun countsRoundAndClamp() { + assertEquals(13, json.decodeFromString(CountSerializer, "12.7")) + assertEquals(3, json.decodeFromString(CountSerializer, "2.5")) + assertEquals(0, json.decodeFromString(CountSerializer, "-4")) + assertEquals(Int.MAX_VALUE, json.decodeFromString(CountSerializer, "5e12")) + assertThrows(SerializationException::class.java) { + json.decodeFromString(CountSerializer, "\"7\"") + } + } + + @Test + fun lenientFieldsFallBackInsteadOfFailing() { + assertEquals(Sample(), json.decodeFromString("{}")) + assertEquals( + Sample(), + json.decodeFromString( + """{"count":"7","duration":"x","name":null,"items":null}""" + ), + ) + assertEquals( + Sample(count = 7, duration = 1.5, name = "n", items = listOf(Item("a"), Item("b"))), + json.decodeFromString( + """{"count":7,"duration":1.5,"name":"n","items":[{"id":"a"},{"id":7},null,{"id":"b"}]}""" + ), + ) + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"name":7}""") + } + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"items":{}}""") + } + } + + @Test + fun unknownEnumValuesUseTheirFallback() { + assertEquals(Shade.DARK, json.decodeFromString(Shade.Lenient, "\"dark\"")) + assertEquals(Shade.LIGHT, json.decodeFromString(Shade.Lenient, "\"mauve\"")) + assertEquals("\"dark\"", json.encodeToString(Shade.Lenient, Shade.DARK)) + assertThrows(SerializationException::class.java) { + json.decodeFromString(Shade.Lenient, "7") + } + assertEquals(Shade.DARK, json.decodeFromString(Shade.Strict, "\"dark\"")) + assertThrows(SerializationException::class.java) { + json.decodeFromString(Shade.Strict, "\"mauve\"") + } + } + + @Test + fun parsesISO8601DatesWithAndWithoutFractionalSeconds() { + val expected = + mapOf( + "2026-10-28T09:15:00.000Z" to 1793178900.0, + "2026-10-28T09:15:00Z" to 1793178900.0, + "2026-10-28T09:15:00.5Z" to 1793178900.5, + "2026-10-28T09:15:00.123456Z" to 1793178900.123456, + "2026-10-28T09:15:00+01:00" to 1793175300.0, + "2026-10-28T09:15:00+0100" to 1793175300.0, + "2026-10-28T09:15:00.000+02:00" to 1793171700.0, + ) + for ((text, seconds) in expected) { + val date = CapJson.parseDate(text) + assertEquals(text, seconds, date!!.epochSecond + date.nano / 1e9, 1e-6) + } + val rejected = + listOf( + "2026-10-28T09:15Z", + "2026-10-28", + "2026-10-28 09:15:00", + "2026-10-28T09:15:00", + "2026-10-28t09:15:00z", + "20261028T091500Z", + "2026-13-28T09:15:00Z", + ) + for (text in rejected) { + assertNull(text, CapJson.parseDate(text)) + } + assertEquals( + Instant.ofEpochSecond(1793178900), + json.decodeFromString(InstantSerializer, "\"2026-10-28T09:15:00.000Z\""), + ) + assertEquals( + "\"2026-10-28T09:15:00Z\"", + json.encodeToString(InstantSerializer, Instant.ofEpochMilli(1793178900500)), + ) + assertThrows(SerializationException::class.java) { + json.decodeFromString(InstantSerializer, "\"yesterday\"") + } + } + + @Test + fun userDisplayNameFallsBackToTheEmailName() { + fun user(name: String?, lastName: String?, email: String = "richie@cap.so") = + CapUser( + "user_1", + name, + lastName, + email, + imageUrl = null, + activeOrganizationId = "org_1", + ) + assertEquals("Richie McIlroy", user(" Richie ", "McIlroy").displayName) + assertEquals("McIlroy", user(" ", "McIlroy").displayName) + assertEquals("richie", user(null, null).displayName) + assertEquals("cap.so", user(null, "", email = "@cap.so").displayName) + assertEquals("@", user(null, null, email = "@").displayName) + } + + @Test + fun bootstrapDefaultsMissingListsAndFindsTheActiveOrganization() { + val bootstrap = + json.decodeFromString( + """ + {"user":{"id":"user_1","name":null,"email":"r@cap.so","imageUrl":null,"activeOrganizationId":"org_2"}, + "organizations":[{"id":"org_1","name":"One","iconUrl":null,"role":"admin"},{"id":"org_2","name":"Two","iconUrl":null,"role":7},{"id":"org_2","name":"Two","iconUrl":null,"role":"owner"}], + "activeOrganizationId":null,"rootFolders":null} + """ + ) + assertNull(bootstrap.user.lastName) + assertEquals(listOf("org_1", "org_2"), bootstrap.organizations.map { it.id }) + assertEquals("Two", bootstrap.activeOrganization?.name) + assertEquals(emptyList(), bootstrap.rootFolders) + assertEquals(emptyList(), bootstrap.spaces) + assertNull( + bootstrap + .copy(user = bootstrap.user.copy(activeOrganizationId = "org_9")) + .activeOrganization + ) + assertEquals("One", bootstrap.copy(activeOrganizationId = "org_1").activeOrganization?.name) + } + + @Test + fun rolesDecideWhoCanManage() { + assertEquals(listOf(true, true, false), MemberRole.entries.map { it.canManage }) + assertEquals(listOf("Owner", "Admin", "Member"), MemberRole.entries.map { it.displayName }) + assertEquals(MemberRole.MEMBER, json.decodeFromString("\"superuser\"")) + assertEquals("\"admin\"", json.encodeToString(MemberRole.ADMIN)) + } + + @Test + fun foldersTolerateUnknownColoursAndBadCounts() { + val folder = + json.decodeFromString( + """{"id":"f","name":"Product","color":7,"videoCount":"4"}""" + ) + assertEquals( + Folder("f", "Product", FolderColor.NORMAL, parentId = null, videoCount = 0), + folder, + ) + val yellow = + json.decodeFromString( + """{"id":"f","name":"Product","color":"yellow","parentId":"p","videoCount":3.6}""" + ) + assertEquals( + Folder("f", "Product", FolderColor.YELLOW, parentId = "p", videoCount = 4), + yellow, + ) + assertEquals( + listOf("Default", "Blue", "Red", "Yellow"), + FolderColor.entries.map { it.displayName }, + ) + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"id":"f","name":"Product","parentId":7}""") + } + } + + @Test + fun spacesDefaultUnknownKindAndPrivacy() { + val space = + json.decodeFromString( + """{"id":"s","name":"Design","iconUrl":null,"kind":"team","privacy":"Secret","role":"lead","canManage":false,"hasPassword":true}""" + ) + assertEquals(SpaceKind.SPACE, space.kind) + assertEquals(SpacePrivacy.PRIVATE, space.privacy) + assertEquals(MemberRole.MEMBER, space.role) + assertThrows(SerializationException::class.java) { + json.decodeFromString( + """{"id":"s","name":"Design","kind":"space","privacy":"Public","canManage":"false","hasPassword":true}""" + ) + } + assertThrows(SerializationException::class.java) { + json.decodeFromString( + """{"id":"s","name":"Design","kind":"space","privacy":"Public","hasPassword":true}""" + ) + } + } + + @Test + fun notificationPreferencesReadAndChangeOneKind() { + val preferences = + json.decodeFromString( + """{"comments":true,"replies":false,"views":true,"anonymousViews":false,"reactions":true}""" + ) + assertEquals( + listOf(true, false, true, false, true), + NotificationPreferences.Kind.entries.map { preferences[it] }, + ) + for (kind in NotificationPreferences.Kind.entries) { + val changed = preferences.with(kind, !preferences[kind]) + assertEquals( + NotificationPreferences.Kind.entries.map { + if (it == kind) !preferences[it] else preferences[it] + }, + NotificationPreferences.Kind.entries.map { changed[it] }, + ) + } + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"comments":true}""") + } + } + + @Test + fun sessionAndPlanResponsesDecode() { + assertEquals( + ApiKeySession(apiKey = "key", userId = "user_1"), + json.decodeFromString( + """{"type":"api_key","apiKey":"key","userId":"user_1"}""" + ), + ) + assertEquals( + AuthConfig( + appleAuthAvailable = true, + googleAuthAvailable = false, + workosAuthAvailable = true, + ), + json.decodeFromString( + """{"appleAuthAvailable":true,"googleAuthAvailable":false,"workosAuthAvailable":true}""" + ), + ) + assertEquals( + PlanStatus(upgraded = true, stripeSubscriptionStatus = null), + json.decodeFromString( + """{"upgraded":true,"stripeSubscriptionStatus":null}""" + ), + ) + assertEquals( + listOf(true, true, true), + with(AuthConfig.FALLBACK) { + listOf(appleAuthAvailable, googleAuthAvailable, workosAuthAvailable) + }, + ) + } + + private fun capJson(extra: String = "") = + """{"id":"cap_1","shareUrl":"https://cap.so/s/cap_1","title":"Demo","createdAt":"2026-11-01T00:00:00.000Z","updatedAt":"2026-11-01T00:00:00.000Z","ownerName":"Owner","durationSeconds":null,"thumbnailUrl":null,"folderId":null,"public":true,"protected":false,"viewCount":0,"commentCount":0,"reactionCount":0,"upload":null$extra}""" + + @Test + fun capLinkAccessIsOptionalAndToleratesUnknownValues() { + fun cap(extra: String) = json.decodeFromString(capJson(extra)) + assertNull(cap("").linkAccess) + assertEquals(LinkAccess.RESTRICTED, cap(""","linkAccess":"restricted"""").linkAccess) + assertEquals(LinkAccess.ANYONE, cap(""","linkAccess":"anyone"""").linkAccess) + assertNull(cap(""","linkAccess":"something-new"""").linkAccess) + assertNull(cap(""","linkAccess":null""").linkAccess) + assertNull(cap("").linkRestricted) + assertEquals(true, cap(""","linkRestricted":true""").linkRestricted) + assertEquals(false, cap(""","linkRestricted":false,"linkAccess":"anyone"""").linkRestricted) + assertNull(cap(""","linkRestricted":"yes"""").linkRestricted) + val page = json.decodeFromString(fixture("caps")) + assertTrue(page.caps.all { it.linkAccess == null }) + } + + @Test + fun capSummaryKeepsWhatItCanAndFailsOnWhatItNeeds() { + val sparse = + json.decodeFromString( + """{"id":"cap_1","shareUrl":"u","title":"Demo","createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z","ownerName":null,"durationSeconds":"12","public":false,"protected":null,"viewCount":"9","commentCount":2.5,"upload":{"processingMessage":7},"linkRestricted":"true"}""" + ) + assertEquals("", sparse.ownerName) + assertNull(sparse.ownerId) + assertNull(sparse.durationSeconds) + assertFalse(sparse.isProtected) + assertEquals( + listOf(0, 3, 0), + listOf(sparse.viewCount, sparse.commentCount, sparse.reactionCount), + ) + assertNull(sparse.upload) + assertNull(sparse.linkRestricted) + assertFalse(sparse.isProcessing) + val required = + listOf( + capJson().replace(""""public":true,""", ""), + capJson().replace(""""public":true""", """"public":"true""""), + capJson() + .replace( + """"createdAt":"2026-11-01T00:00:00.000Z"""", + """"createdAt":"last week"""", + ), + capJson().replace(""""ownerName":"Owner"""", """"ownerName":7"""), + capJson().replace(""""protected":false""", """"protected":"no""""), + capJson(""","ownedByCurrentUser":"yes""""), + capJson(""","ownerId":7"""), + ) + for (broken in required) { + assertThrows(broken, SerializationException::class.java) { + json.decodeFromString(broken) + } + } + } + + @Test + fun capOwnershipPrefersTheServerAnswer() { + val cap = json.decodeFromString(capJson(""","ownerId":"user_1"""")) + assertTrue(cap.isOwned("user_1")) + assertFalse(cap.isOwned("user_2")) + assertFalse(cap.isOwned(null)) + assertTrue(cap.copy(ownedByCurrentUser = true).isOwned("user_2")) + assertFalse(cap.copy(ownedByCurrentUser = false).isOwned("user_1")) + assertFalse(cap.copy(ownerId = null).isOwned("user_1")) + } + + @Test + fun uploadProgressReportsFractionAndStatus() { + fun progress(body: String) = json.decodeFromString(body) + val uploading = + progress("""{"uploaded":50,"total":200,"phase":"uploading","processingProgress":0}""") + assertEquals(0.25, uploading.fractionCompleted, 0.0) + assertEquals("Uploading", uploading.statusText) + assertEquals( + 0.0, + progress("""{"uploaded":50,"total":0,"phase":"uploading"}""").fractionCompleted, + 0.0, + ) + assertEquals( + 1.0, + progress("""{"uploaded":500,"total":200,"phase":"uploading"}""").fractionCompleted, + 0.0, + ) + val processing = + progress( + """{"phase":"processing","processingProgress":40,"processingMessage":"Transcoding"}""" + ) + assertEquals(0.4, processing.fractionCompleted, 0.0) + assertEquals("Transcoding", processing.statusText) + assertEquals("Processing", progress("""{"phase":"processing"}""").statusText) + val thumbnail = progress("""{"phase":"generating_thumbnail","processingProgress":250}""") + assertEquals(1.0, thumbnail.fractionCompleted, 0.0) + assertEquals("Generating thumbnail", thumbnail.statusText) + val complete = progress("""{"phase":"complete"}""") + assertEquals(1.0, complete.fractionCompleted, 0.0) + assertEquals("Ready", complete.statusText) + val failed = + progress( + """{"phase":"error","processingProgress":80,"processingError":"ffmpeg exited 1"}""" + ) + assertEquals(0.0, failed.fractionCompleted, 0.0) + assertEquals("Processing failed", failed.statusText) + val unknown = + progress("""{"uploaded":"1","total":null,"phase":"queued","processingProgress":true}""") + assertEquals( + UploadProgress( + 0.0, + 0.0, + UploadPhase.PROCESSING, + 0.0, + processingMessage = null, + processingError = null, + ), + unknown, + ) + assertEquals(UploadPhase.PROCESSING, progress("""{"phase":7}""").phase) + assertThrows(SerializationException::class.java) { progress("""{"processingError":7}""") } + val cap = json.decodeFromString(capJson()) + assertTrue(cap.copy(upload = uploading).isProcessing) + assertFalse(cap.copy(upload = complete).isProcessing) + assertFalse(cap.copy(upload = failed).isProcessing) + } + + @Test + fun viewerSnapsPlaybackSpeedAndDefaultsFlags() { + assertEquals(CapViewer(), json.decodeFromString("{}")) + val viewer = + json.decodeFromString( + """{"settings":{"disableSummary":true,"disableComments":"yes"},"defaultPlaybackSpeed":1.6,"canDownload":true,"isScreenshot":1,"ownerImageUrl":7,"aiGenerationStatus":"QUEUED"}""" + ) + assertEquals(ViewerSettings(disableSummary = true), viewer.settings) + assertEquals(1.5f, viewer.defaultPlaybackSpeed) + assertTrue(viewer.canDownload) + assertFalse(viewer.isScreenshot) + assertNull(viewer.ownerImageUrl) + assertTrue(viewer.isGeneratingAi) + assertTrue(viewer.copy(aiGenerationStatus = "PROCESSING").isGeneratingAi) + assertFalse(viewer.copy(aiGenerationStatus = "COMPLETE").isGeneratingAi) + assertEquals( + ViewerSettings(), + json.decodeFromString("""{"settings":[]}""").settings, + ) + for ((raw, speed) in + mapOf( + "0" to 1.2f, + "-1" to 1.2f, + "100" to 2f, + "0.1" to 0.5f, + "\"2\"" to 1.2f, + "null" to 1.2f, + "0.875" to 0.75f, + )) { + assertEquals( + raw, + speed, + json + .decodeFromString("""{"defaultPlaybackSpeed":$raw}""") + .defaultPlaybackSpeed, + ) + } + assertEquals(1.2f, CapViewer.nearestSpeed(Double.NaN)) + assertEquals(viewer, json.decodeFromString(json.encodeToString(viewer))) + } + + @Test + fun capDetailDropsBrokenChaptersAndComments() { + val comment = + """{"id":"c_1","videoId":"cap_1","type":"sticker","content":"Hi","timestamp":null,"parentCommentId":null,"createdAt":"2026-10-28T11:00:00.000Z","updatedAt":"2026-10-28T11:00:00.000Z","author":{"id":"u","name":null,"imageUrl":null}}""" + val detail = + json.decodeFromString( + """{"cap":${capJson()},"summary":null,"chapters":[{"title":"Intro","start":0},{"title":"Quoted","start":"4"},{"start":9}],"transcriptionStatus":"TRANSLATING","comments":[$comment,${comment.replace(""""timestamp":null""", """"timestamp":"12"""")},${comment.replace("2026-10-28T11:00:00.000Z", "today")}],"shareUrl":"https://cap.so/s/cap_1"}""" + ) + assertEquals(listOf(Chapter("Intro", 0.0)), detail.chapters) + assertEquals(TranscriptionStatus.SKIPPED, detail.transcriptionStatus) + assertEquals(1, detail.comments.size) + assertEquals(CommentKind.TEXT, detail.comments[0].type) + assertEquals(CapViewer(), detail.viewer) + val bare = + json.decodeFromString( + """{"cap":${capJson()},"transcriptionStatus":7,"viewer":"none","shareUrl":"u"}""" + ) + assertEquals(emptyList(), bare.chapters) + assertEquals(emptyList(), bare.comments) + assertNull(bare.transcriptionStatus) + assertEquals(CapViewer(), bare.viewer) + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"cap":${capJson()},"summary":7,"shareUrl":"u"}""") + } + } + + @Test + fun capsPageNeedsItsPagingNumbers() { + val page = + json.decodeFromString( + """{"caps":[${capJson()},{"id":"broken"}],"page":1,"limit":30.0,"total":1,"collectionTotal":"12","hasMore":false}""" + ) + assertEquals(listOf("cap_1"), page.caps.map { it.id }) + assertEquals(emptyList(), page.folders) + assertEquals(30, page.limit) + assertNull(page.collectionTotal) + for (broken in + listOf( + """{"limit":30,"total":1,"hasMore":false}""", + """{"page":"1","limit":30,"total":1,"hasMore":false}""", + """{"page":1,"limit":30,"total":1}""", + """{"caps":{},"page":1,"limit":30,"total":1,"hasMore":false}""", + )) { + assertThrows(broken, SerializationException::class.java) { + json.decodeFromString(broken) + } + } + } + + @Test + fun accessUnlockAndStatusResponsesDecode() { + assertEquals( + listOf( + CapAccessStatus.GRANTED, + CapAccessStatus.PASSWORD_REQUIRED, + CapAccessStatus.RESTRICTED, + CapAccessStatus.UNKNOWN, + ), + listOf("granted", "password_required", "restricted", "banned").map { + json.decodeFromString("""{"status":"$it"}""").status + }, + ) + val unlock = + json.decodeFromString( + """{"accessToken":"token","expiresAt":"2026-11-01T12:00:00.000Z"}""" + ) + assertEquals(CapUnlock("token", Instant.parse("2026-11-01T12:00:00Z")), unlock) + val statuses = + json.decodeFromString( + """{"caps":[{"id":"cap_1","upload":null},{"id":"cap_2","upload":{"phase":"complete"}}]}""" + ) + assertEquals(listOf(null, UploadPhase.COMPLETE), statuses.caps.map { it.upload?.phase }) + assertThrows(SerializationException::class.java) { + json.decodeFromString( + """{"caps":[{"id":"cap_1"},{"upload":null}]}""" + ) + } + } + + @Test + fun uploadTargetsDecodeAllVariantsAndRejectUnknown() { + val post = + json.decodeFromString( + """{"type":"s3Post","url":"https://s3.example.com","fields":{"key":"a"}}""" + ) + assertEquals( + UploadTarget.S3Post(url = "https://s3.example.com", fields = mapOf("key" to "a")), + post, + ) + val put = + json.decodeFromString( + """{"type":"put","url":"https://r2.example.com/x","headers":{"Content-Type":"video/mp4"}}""" + ) + assertEquals("https://r2.example.com/x", put.url) + assertThrows(SerializationException::class.java) { + json.decodeFromString("""{"type":"ftp","url":"ftp://x"}""") + } + } + + @Test + fun uploadTargetsKeepTheirTypeWhenEncoded() { + val created = + json.decodeFromString( + """{"id":"cap_1","shareUrl":"https://cap.so/s/cap_1","rawFileKey":"u/cap_1/raw-upload.mp4","upload":{"type":"driveResumable","url":"https://drive.example.com/x","headers":{"X-Upload":"1"}}}""" + ) + assertEquals( + UploadTarget.DriveResumable("https://drive.example.com/x", mapOf("X-Upload" to "1")), + created.upload, + ) + assertEquals(created, json.decodeFromString(json.encodeToString(created))) + for (broken in + listOf( + """{"url":"https://x"}""", + """{"type":"put","url":"https://x"}""", + """{"type":"s3Post","url":"https://x","fields":{"key":7}}""", + """{"type":"put","headers":{}}""", + )) { + assertThrows(broken, SerializationException::class.java) { + json.decodeFromString(broken) + } + } + } + + @Test + fun analyticsToleratesBadNumbersAndRows() { + val data = + json.decodeFromString( + """{"capName":null,"counts":{"views":"9","comments":2.4},"chart":[{"bucket":"2026-10-27T00:00:00Z","views":4},{"bucket":"2026-10-27","views":"x"},{"views":1}],"breakdowns":{"countries":[{"name":"GB","views":7,"percentage":"58"},{"views":1}],"topCaps":[{"id":"cap_1","name":"Launch","subtitle":null,"views":3,"percentage":100}],"devices":null}}""" + ) + assertEquals(AnalyticsCounts(caps = 0, views = 0, comments = 2, reactions = 0), data.counts) + assertEquals(listOf("2026-10-27T00:00:00Z", "2026-10-27"), data.chart.map { it.bucket }) + assertEquals( + listOf(Instant.parse("2026-10-27T00:00:00Z"), null), + data.chart.map { it.date }, + ) + assertEquals(listOf(4, 0), data.chart.map { it.views }) + assertEquals( + listOf(AnalyticsBreakdown("GB", subtitle = null, views = 7, percentage = 0.0)), + data.breakdowns.countries, + ) + assertEquals("|GB|", data.breakdowns.countries[0].id) + assertEquals("cap_1|Launch|", data.breakdowns.topCaps[0].id) + assertEquals("|London|GB", AnalyticsBreakdown("London", "GB", 1, 1.0).id) + assertEquals(emptyList(), data.breakdowns.devices) + assertEquals(emptyList(), data.breakdowns.cities) + assertEquals( + AnalyticsResponse(available = false, data = null), + json.decodeFromString("""{"available":false,"data":null}"""), + ) + for (broken in + listOf( + """{"counts":{},"chart":[]}""", + """{"chart":[],"breakdowns":{}}""", + """{"counts":{},"chart":{},"breakdowns":{}}""", + )) { + assertThrows(broken, SerializationException::class.java) { + json.decodeFromString(broken) + } + } + } + + @Test + fun analyticsRangesCarryTheirQueryValueAndTitles() { + assertEquals( + listOf("24h", "7d", "30d", "lifetime"), + AnalyticsRange.entries.map { it.rawValue }, + ) + assertEquals(listOf("24H", "7D", "30D", "All"), AnalyticsRange.entries.map { it.title }) + assertEquals( + listOf("Last 24 hours", "Last 7 days", "Last 30 days", "All time"), + AnalyticsRange.entries.map { it.accessibilityTitle }, + ) + assertEquals( + listOf(true, false, false, false), + AnalyticsRange.entries.map { it.usesHourlyBuckets }, + ) + } + + @Test + fun playbackDownloadAndImportResponsesDecode() { + assertEquals( + Playback( + PlaybackKind.HLS, + "https://cap.so/api/playlist?videoId=cap_1", + transcriptUrl = null, + ), + json.decodeFromString( + """{"kind":"hls","url":"https://cap.so/api/playlist?videoId=cap_1","transcriptUrl":null}""" + ), + ) + assertEquals( + PlaybackKind.MP4, + json.decodeFromString("""{"kind":"dash","url":"https://x/y.mpd"}""").kind, + ) + assertEquals( + DownloadLink(fileName = "Demo.mp4", url = "https://s3.example.com/x"), + json.decodeFromString( + """{"fileName":"Demo.mp4","url":"https://s3.example.com/x"}""" + ), + ) + assertEquals( + LoomImportResult(id = "cap_1", shareUrl = "https://cap.so/s/cap_1"), + json.decodeFromString( + """{"id":"cap_1","shareUrl":"https://cap.so/s/cap_1"}""" + ), + ) + assertThrows(SerializationException::class.java) { + json.decodeFromString( + """{"id":"org_1","name":"Cap","role":"owner","canManage":true,"domainVerified":"true"}""" + ) + } + } + + @Test + fun reportReasonsCarryTheirValueAndTitle() { + assertEquals( + listOf("harassment", "hate", "sexual", "violence", "copyright", "other"), + ContentReportReason.entries.map { it.rawValue }, + ) + assertEquals( + listOf( + "Harassment or bullying", + "Hate speech", + "Sexual content", + "Violence or threats", + "Copyright infringement", + "Other concern", + ), + ContentReportReason.entries.map { it.title }, + ) + } +} + +@Serializable private data class Item(val id: String) + +@Serializable +private data class Sample( + @Serializable(with = LenientCount::class) val count: Int = 0, + @Serializable(with = LenientDuration::class) val duration: Double? = null, + @Serializable(with = EmptyWhenNull::class) val name: String = "", + @Serializable(with = LossyListSerializer::class) val items: List = emptyList(), +) + +private object LenientCount : LenientSerializer(CountSerializer, 0) + +private object LenientDuration : LenientSerializer(NumberSerializer.nullable, null) + +private object EmptyWhenNull : NullFallbackSerializer(String.serializer(), "") + +private enum class Shade(override val rawValue: String) : RawValue { + LIGHT("light"), + DARK("dark"); + + object Lenient : RawValueSerializer("Shade", entries, LIGHT) + + object Strict : RawValueSerializer("Shade", entries) +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/LinkTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/LinkTest.kt new file mode 100644 index 00000000000..22781074a70 --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/LinkTest.kt @@ -0,0 +1,470 @@ +package so.cap.kit + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class AuthCallbackTest { + private val key = "0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7e" + + @Test + fun acceptsExactCallback() { + val session = AuthCallback.session("cap://auth?api_key=$key&user_id=user_123") + assertEquals(ApiKeySession(apiKey = key, userId = "user_123"), session) + } + + @Test + fun surfacesProviderErrors() { + val error = + assertThrows(AuthCallbackError.Provider::class.java) { + AuthCallback.session("cap://auth?error_description=Access%20denied") + } + assertEquals("Access denied", error.detail) + assertEquals("Access denied", error.message) + } + + @Test + fun rejectsMalformedCallbacks() { + val cases = + listOf( + "https://auth?api_key=$key&user_id=user_123", + "cap://evil?api_key=$key&user_id=user_123", + "cap://auth/extra?api_key=$key&user_id=user_123", + "cap://user@auth?api_key=$key&user_id=user_123", + "cap://auth:8080?api_key=$key&user_id=user_123", + "cap://auth?api_key=short&user_id=user_123", + "cap://auth?api_key=$key&user_id=../../etc", + "cap://auth?api_key=$key&api_key=0f3a5c2e-6b4d-4a7f-9e1c-2d3b4a5c6d7f&user_id=user_123", + "cap://auth?user_id=user_123", + "cap://auth", + ) + for (raw in cases) { + val error = + assertThrows(raw, AuthCallbackError.InvalidCallback::class.java) { + AuthCallback.session(raw) + } + assertEquals("Sign in did not return a Cap session. Try again.", error.message) + } + } + + @Test + fun trimsValuesAndCapsProviderMessages() { + val session = AuthCallback.session("CAP://AUTH/?api_key=%20$key%20&user_id=user_123") + assertEquals(key, session.apiKey) + val long = "👍".repeat(250) + val error = + assertThrows(AuthCallbackError.Provider::class.java) { + AuthCallback.session("cap://auth?error_description=$long") + } + assertEquals("👍".repeat(200), error.detail) + assertThrows(AuthCallbackError.InvalidCallback::class.java) { + AuthCallback.session("cap://auth?error_description=&user_id=user_123") + } + } + + @Test + fun readsTheStateOnlyWhenItAppearsOnce() { + assertEquals( + "abc_DEF-0123456789", + AuthCallback.state("cap://auth?api_key=$key&state=abc_DEF-0123456789"), + ) + assertNull(AuthCallback.state("cap://auth?api_key=$key")) + assertNull(AuthCallback.state("cap://auth?state=one&state=two")) + } + + @Test + fun makesAnUnguessableUrlSafeState() { + val states = List(64) { AuthCallback.newState() } + assertEquals(states.size, states.toSet().size) + states.forEach { assertTrue(it, Regex("[A-Za-z0-9_-]{32}").matches(it)) } + } +} + +class DeepLinkTest { + @Test + fun parsesShareLinks() { + val cases = + listOf( + "https://cap.so/s/abc123" to "abc123", + "https://www.cap.so/s/abc_123-x" to "abc_123-x", + "https://videos.acme.com/s/abc123" to "abc123", + "https://cap.so/s/abc123?t=12" to "abc123", + "cap://s/abc123" to "abc123", + ) + for ((raw, expected) in cases) { + val link = DeepLink.parse(raw) + assertTrue("Expected a share link for $raw", link is DeepLink.Share) + assertEquals(raw, expected, (link as DeepLink.Share).target.id.rawValue) + } + } + + @Test + fun parsesStopScreenRecording() { + assertEquals( + DeepLink.StopScreenRecording, + DeepLink.parse(DeepLink.STOP_SCREEN_RECORDING_URL), + ) + assertNull(DeepLink.parse("cap://record")) + assertNull(DeepLink.parse("cap://record/stop/now")) + assertNull(DeepLink.parse("https://cap.so/record/stop")) + } + + @Test + fun rejectsOtherLinks() { + val cases = + listOf( + "http://cap.so/s/abc123", + "https://cap.so/s/", + "https://cap.so/s/abc/def", + "https://cap.so/dashboard", + "https://cap.so/s/abc%2F..", + "https://user:pass@cap.so/s/abc123", + "cap://s/abc/def", + "cap://settings", + "javascript://s/abc", + ) + for (raw in cases) { + assertFalse("Unexpected share link for $raw", DeepLink.parse(raw) is DeepLink.Share) + } + } + + @Test + fun parsesUserInput() { + assertEquals( + "abc123", + ShareLinkParser.capIdFromUserInput(" https://cap.so/s/abc123 ")?.rawValue, + ) + assertEquals("abc123", ShareLinkParser.capIdFromUserInput("cap.so/s/abc123")?.rawValue) + assertEquals("abc123", ShareLinkParser.capIdFromUserInput("abc123")?.rawValue) + assertNull(ShareLinkParser.capIdFromUserInput("not a link")) + assertNull(ShareLinkParser.capIdFromUserInput("https://loom.com/share/abc")) + assertNull(ShareLinkParser.capIdFromUserInput("")) + } + + @Test + fun capIDRejectsUnsafeCharacters() { + assertNotNull(CapId.parse("abc")) + assertNull(CapId.parse("a/b")) + assertNull(CapId.parse("..")) + assertNull(CapId.parse("a b")) + assertNull(CapId.parse("ä")) + assertNull(CapId.parse("a".repeat(129))) + } + + @Test + fun shareTargetsReadTimeAndComment() { + val target = + (DeepLink.parse("https://cap.so/s/abc?t=83.5&comment=c_12") as DeepLink.Share).target + assertEquals(83.5, target.startTime) + assertEquals("c_12", target.commentId) + val bad = + (DeepLink.parse("https://cap.so/s/abc?t=-1&comment=../x") as DeepLink.Share).target + assertNull(bad.startTime) + assertNull(bad.commentId) + val huge = (DeepLink.parse("cap://s/abc?t=1e12&reply=r1") as DeepLink.Share).target + assertNull(huge.startTime) + assertEquals("r1", huge.commentId) + val id = CapId.parse("abc")!! + assertEquals("https://cap.so/s/abc?t=83", CapEnvironment.PRODUCTION.shareUrl(id, 83.9)) + assertEquals("https://cap.so/s/abc", CapEnvironment.PRODUCTION.shareUrl(id, 0.4)) + } + + @Test + fun readsPathsAndQueriesTheWayFoundationDoes() { + assertEquals(DeepLink.StopScreenRecording, DeepLink.parse("CAP://RECORD/stop/")) + assertNull(DeepLink.parse("cap://record/Stop")) + for (raw in + listOf( + "https://cap.so/s/abc/", + "https://cap.so//s/abc", + "cap://S//abc", + "HTTPS://cap.so/s/abc#x", + )) { + assertEquals( + raw, + CapId.parse("abc"), + (DeepLink.parse(raw) as? DeepLink.Share)?.target?.id, + ) + } + for (raw in + listOf( + "https://cap.so/s%2Fabc", + "https://cap.so/S/abc", + "https:///s/abc", + "https://@cap.so/s/abc", + "cap:s/abc", + )) { + assertNull(raw, DeepLink.parse(raw)) + } + val encoded = + (DeepLink.parse("https://cap.so/s/abc?x&t=1%2E5&t=9&comment=&reply=r1") + as DeepLink.Share) + .target + assertEquals(1.5, encoded.startTime) + assertNull(encoded.commentId) + for (time in listOf("12f", "0x10", "nan", "inf", "604801", "0", "\u0663", "\uFF11\uFF12")) { + val target = (DeepLink.parse("cap://s/abc?t=$time") as DeepLink.Share).target + assertNull(time, target.startTime) + } + assertEquals( + 604800.0, + (DeepLink.parse("cap://s/abc?t=604800") as DeepLink.Share).target.startTime, + ) + } +} + +class EnvironmentTest { + @Test + fun acceptsHTTPSOrigins() { + assertEquals( + "https://cap.so", + CapEnvironment.parse("https://cap.so", allowInsecureLocalhost = false)?.baseUrl, + ) + assertEquals( + "https://cap.so", + CapEnvironment.parse("https://CAP.so/", allowInsecureLocalhost = false)?.baseUrl, + ) + } + + @Test + fun onlyAllowsHTTPForLocalDevelopment() { + assertNull(CapEnvironment.parse("http://cap.so", allowInsecureLocalhost = true)) + assertNull(CapEnvironment.parse("http://localhost:3000", allowInsecureLocalhost = false)) + assertEquals( + "http://localhost:3000", + CapEnvironment.parse("http://localhost:3000", allowInsecureLocalhost = true)?.baseUrl, + ) + assertNotNull( + CapEnvironment.parse("http://192.168.1.20:3000", allowInsecureLocalhost = true) + ) + assertNull(CapEnvironment.parse("http://8.8.8.8:3000", allowInsecureLocalhost = true)) + } + + @Test + fun rejectsOriginsWithExtras() { + assertNull(CapEnvironment.parse("https://cap.so/api", allowInsecureLocalhost = false)) + assertNull(CapEnvironment.parse("https://cap.so?x=1", allowInsecureLocalhost = false)) + assertNull(CapEnvironment.parse("https://a:b@cap.so", allowInsecureLocalhost = false)) + assertNull(CapEnvironment.parse("ftp://cap.so", allowInsecureLocalhost = true)) + } + + @Test + fun sameOriginComparesSchemeHostAndPort() { + val env = CapEnvironment.PRODUCTION + assertTrue(env.isSameOrigin("https://cap.so/api/x")) + assertTrue(env.isSameOrigin("https://cap.so:443/api/x")) + assertFalse(env.isSameOrigin("http://cap.so/api/x")) + assertFalse(env.isSameOrigin("https://cap.so.evil.com/api/x")) + assertFalse(env.isSameOrigin("https://cdn.cap.so/x")) + } + + @Test + fun safeURLsRequireHTTPS() { + assertNotNull(SafeUrl.web("https://cap.so/privacy")) + assertNull(SafeUrl.web("http://cap.so/privacy")) + assertNull(SafeUrl.web("javascript:alert(1)")) + assertEquals( + "https://cap.so/api/mobile/caps/x/thumbnail", + SafeUrl.media("/api/mobile/caps/x/thumbnail", CapEnvironment.PRODUCTION), + ) + assertNull(SafeUrl.media("file:///etc/passwd", CapEnvironment.PRODUCTION)) + } + + @Test + fun rejectsOriginsThatAreNotPlainHosts() { + for (origin in + listOf( + "https://cap so", + "https://cap.so:abc", + "https://:80", + "https://@cap.so", + "https://cap.so//", + "https://cap.so#", + "https:cap.so", + "cap.so", + )) { + assertNull(origin, CapEnvironment.parse(origin, allowInsecureLocalhost = true)) + } + assertEquals( + "https://cap.so:8443", + CapEnvironment.parse(" HTTPS://Cap.So:8443 ", allowInsecureLocalhost = false)?.baseUrl, + ) + } + + @Test + fun treatsOnlyPrivateAddressesAsLocalDevelopmentHosts() { + for (host in + listOf( + "localhost", + "127.0.0.1", + "mac.local", + "10.0.0.5", + "172.16.0.1", + "172.31.9.9", + "192.168.0.2", + )) { + assertTrue(host, CapEnvironment.isLocalDevelopmentHost(host)) + } + for (host in listOf("172.15.0.1", "172.32.0.1", "192.169.0.1", "11.0.0.1", "example.com")) { + assertFalse(host, CapEnvironment.isLocalDevelopmentHost(host)) + } + } + + @Test + fun aPrivateAddressIsExactlyFourPlainNumbers() { + for (host in + listOf( + "10.1.2.3.evil.example", + "evil.10.1.2.3", + "10.evil.1.example.2.3", + "192.168.1.1.", + "10..0.0.1", + "10.0.1", + "10.0.0.0.1", + "+10.0.0.1", + "192.168.-0.1", + "10.0.0.256", + "10.0.0.1000", + "010.0.0.1", + "10.0.0.01", + "10.0.0.١", + "10.0.0.1 ", + "", + )) { + assertFalse(host, CapEnvironment.isLocalDevelopmentHost(host)) + } + for (host in listOf("10.0.0.0", "10.255.255.255", "172.20.10.2", "192.168.255.1")) { + assertTrue(host, CapEnvironment.isLocalDevelopmentHost(host)) + } + for (origin in + listOf( + "http://10.1.2.3.evil.example", + "http://10.1.2.3.evil.example:3000", + "http://192.168.1.1.", + "http://010.0.0.1:3000", + )) { + assertNull(origin, CapEnvironment.parse(origin, allowInsecureLocalhost = true)) + } + assertEquals( + "http://10.1.2.3:3000", + CapEnvironment.parse("http://10.1.2.3:3000", allowInsecureLocalhost = true)?.baseUrl, + ) + } + + @Test + fun mediaURLsStayOnHTTPSOrTheLocalOrigin() { + val local = CapEnvironment.parse("http://localhost:3000", allowInsecureLocalhost = true)!! + assertEquals("http://localhost:3000/x/y", SafeUrl.media("x/y", local)) + assertEquals("http://localhost:3000/x", SafeUrl.media("http://localhost:3000/x", local)) + assertNull(SafeUrl.media("http://localhost:3902/x", local)) + assertEquals("https://s3.example.com/x", SafeUrl.media("https://s3.example.com/x", local)) + assertEquals("https://evil.com/x", SafeUrl.media("//evil.com/x", CapEnvironment.PRODUCTION)) + assertNull(SafeUrl.media(null, CapEnvironment.PRODUCTION)) + } + + @Test + fun mediaURLsCannotSmuggleAnotherHostPastTheLocalOrigin() { + val local = CapEnvironment.parse("http://localhost:3000", allowInsecureLocalhost = true)!! + for (url in + listOf( + "http://evil.example\\@localhost:3000/x", + "http://evil.example:3000\\@localhost:3000/x", + "http://localhost:3000@evil.example/x", + "http://evil.example#@localhost:3000/x", + "http://localhost.:3000/x", + "http://localhost:3000.evil.example/x", + "\\\\evil.example/x", + "/\\evil.example/x", + "http://local\thost:3000/x", + )) { + assertNull(url, SafeUrl.media(url, local)) + } + assertEquals( + "http://localhost:3000/@evil.example/x", + SafeUrl.media("http://localhost:3000\\@evil.example/x", local), + ) + assertEquals("http://localhost:3000/x", SafeUrl.media("HTTP://LOCALHOST:3000/x", local)) + assertEquals( + "https://evil.example/@cap.so/x", + SafeUrl.media("https://evil.example\\@cap.so/x", CapEnvironment.PRODUCTION), + ) + assertEquals("https://cap.so/privacy", SafeUrl.web(" HTTPS://Cap.so/privacy ")) + assertEquals( + "https://evil.example/@cap.so/x", + SafeUrl.web("https://evil.example\\@cap.so/x"), + ) + assertNull(SafeUrl.web("https://cap.so\t/privacy")) + assertNull(SafeUrl.web("//cap.so/privacy")) + } + + @Test + fun acceptedOriginsAreOnesTheHTTPClientCanReach() { + for (origin in + listOf( + "https://cap.so", + "https://cap.so:8443", + "https://my_host.local", + "https://cap.so.", + "https://[::1]:8443", + "http://localhost:3000", + "http://192.168.1.20:3000", + )) { + val environment = CapEnvironment.parse(origin, allowInsecureLocalhost = true) + assertEquals(origin, origin, environment?.baseUrl) + assertTrue(origin, environment!!.isSameOrigin(environment.url("api/mobile/bootstrap"))) + } + for (origin in + listOf( + "https://a..b", + "https://cap.so..", + "https://cap.so:65536", + "https://cap.so:0", + )) { + assertNull(origin, CapEnvironment.parse(origin, allowInsecureLocalhost = true)) + } + } + + @Test + fun buildsSiteLinksUnderTheBaseURL() { + val env = CapEnvironment.PRODUCTION + assertEquals("https://cap.so/privacy", env.privacyUrl) + assertEquals("https://cap.so/terms", env.termsUrl) + assertEquals("https://cap.so/docs", env.supportUrl) + assertEquals("https://cap.so/dashboard", env.dashboardUrl) + assertEquals("https://cap.so/dashboard/settings/organization/billing", env.upgradeUrl) + } + + @Test + fun validatesEmailsAndCodes() { + assertTrue(EmailValidator.isValid(" Richie@Cap.so ")) + assertEquals("richie@cap.so", EmailValidator.normalize(" Richie@Cap.so ")) + assertFalse(EmailValidator.isValid("richie@cap")) + assertFalse(EmailValidator.isValid("richie cap@cap.so")) + assertFalse(EmailValidator.isValid("@cap.so")) + assertEquals("123456", VerificationCode.sanitize("12a3 45-678")) + assertEquals("", VerificationCode.sanitize("١٢٣")) + assertTrue(VerificationCode.isComplete("123456")) + assertFalse(VerificationCode.isComplete("12345")) + } + + @Test + fun rejectsEmailsAndKeysOutsideTheLimits() { + assertTrue(EmailValidator.isValid("a".repeat(64) + "@cap.so")) + assertFalse(EmailValidator.isValid("a".repeat(65) + "@cap.so")) + assertFalse(EmailValidator.isValid("a@" + "b".repeat(250) + ".so")) + assertFalse(EmailValidator.isValid("a@b@cap.so")) + assertFalse(EmailValidator.isValid("a@cap..so")) + assertFalse(EmailValidator.isValid("a@-cap.so")) + assertFalse(EmailValidator.isValid("a@cap-.so")) + assertFalse(VerificationCode.isComplete("123456")) + assertTrue(ApiKeyValidator.isPlausible("a".repeat(16))) + assertFalse(ApiKeyValidator.isPlausible("a".repeat(15))) + assertFalse(ApiKeyValidator.isPlausible("a".repeat(513))) + assertFalse(ApiKeyValidator.isPlausible("a".repeat(15) + " ")) + assertFalse(ApiKeyValidator.isPlausible("a".repeat(15) + "é")) + } +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/SocialTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/SocialTest.kt new file mode 100644 index 00000000000..7e4e717e8cd --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/SocialTest.kt @@ -0,0 +1,368 @@ +package so.cap.kit + +import java.time.Instant +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private fun comment( + id: String, + kind: CommentKind = CommentKind.TEXT, + content: String = "hi", + at: Double? = null, + parent: String? = null, + author: String = "a", + minute: Int = 0, +): CapComment { + val date = Instant.ofEpochSecond(1_700_000_000L + minute * 60L) + return CapComment( + id, + "v", + kind, + content, + at, + parent, + date, + date, + CommentAuthor(author, author, null), + ) +} + +class SocialTest { + private fun shape(threads: List) = threads.map { thread -> + thread.id to thread.replies.map { it.id } + } + + @Test + fun threadsAreOneLevelDeepOldestFirst() { + val threads = + CommentThreads.build( + listOf( + comment("b", minute = 2), + comment("a", minute = 1), + comment("a1", parent = "a", minute = 3), + comment("a1x", parent = "a1", minute = 4), + comment("orphan", parent = "gone", minute = 5), + comment("r", CommentKind.EMOJI, content = "👍", minute = 6), + comment("empty-parent", parent = "", minute = 7), + ) + ) + assertEquals(listOf("a", "b", "empty-parent"), threads.map { it.id }) + assertEquals(listOf("a1", "a1x"), threads[0].replies.map { it.id }) + } + + @Test + fun threadingSurvivesParentCycles() { + val threads = + CommentThreads.build(listOf(comment("x", parent = "y"), comment("y", parent = "x"))) + assertTrue(threads.isEmpty()) + } + + @Test + fun threadsFollowParentsForSixteenStepsAndNoFurther() { + val chain = + listOf(comment("c0")) + + (1..18).map { comment("c$it", parent = "c${it - 1}", minute = it) } + assertEquals( + listOf("c0" to (1..15).map { "c$it" }), + shape(CommentThreads.build(chain)), + ) + assertEquals( + listOf("c0" to (1..14).map { "c$it" }), + shape(CommentThreads.build(chain.take(15))), + ) + } + + @Test + fun threadsOrderTiesByIdAndIgnoreWhatIsNotAThread() { + assertEquals( + listOf("B" to emptyList(), "a" to listOf("a0", "a1"), "b" to emptyList()), + shape( + CommentThreads.build( + listOf( + comment("b"), + comment("a"), + comment("B"), + comment("a1", parent = "a"), + comment("a0", parent = "a"), + ) + ) + ), + ) + assertEquals( + listOf("t" to listOf("r")), + shape( + CommentThreads.build(listOf(comment("r", parent = "t"), comment("t", minute = 5))) + ), + ) + val notThreads = + listOf( + comment("e", CommentKind.EMOJI, content = "👍"), + comment("reply-to-reaction", parent = "e", minute = 1), + comment( + "reaction-reply", + CommentKind.EMOJI, + content = "👍", + parent = "t", + minute = 1, + ), + comment("self", parent = "self"), + comment("t", minute = 2), + ) + assertEquals(listOf("t" to emptyList()), shape(CommentThreads.build(notThreads))) + assertEquals(emptyList(), CommentThreads.build(emptyList())) + } + + @Test + fun viewerDecodesDefensively() { + val viewer = + CapJson.json.decodeFromString( + CapViewer.serializer(), + """{"settings":{"disableComments":true,"disableCaptions":"yes"},"defaultPlaybackSpeed":99,"canDownload":true}""", + ) + assertTrue(viewer.settings.disableComments) + assertFalse(viewer.settings.disableCaptions) + assertEquals(2f, viewer.defaultPlaybackSpeed) + assertTrue(viewer.canDownload) + assertFalse(viewer.overShareLimit) + assertEquals(1.2f, CapViewer.nearestSpeed(Double.NaN)) + assertEquals(1.2f, CapViewer.nearestSpeed(1.16)) + } + + @Test + fun markersBucketNearbyMomentsAndSkipUntimed() { + val markers = + TimelineMarkers.build( + listOf( + comment("c1", at = 10.0, author = "sam"), + comment("c2", at = 11.0, author = "ana"), + comment("r1", CommentKind.EMOJI, content = "😂", at = 12.0), + comment("r2", CommentKind.EMOJI, content = "😂", at = 90.0), + comment("r3", CommentKind.EMOJI, content = "👍", at = 91.0), + comment("r4", CommentKind.EMOJI, content = "😂", at = 92.0), + comment("untimed", at = null), + comment("reply", at = 50.0, parent = "c1"), + comment("late", at = 500.0), + ), + duration = 100.0, + buckets = 20, + ) + assertEquals(3, markers.size) + assertEquals(listOf("c1", "c2", "r1"), markers[0].commentIds) + assertEquals(2, markers[0].textCount) + assertEquals(listOf("sam", "ana"), markers[0].authors.map { it.id }) + assertNull(markers[0].leadingEmoji) + assertEquals("😂", markers[1].leadingEmoji) + assertEquals(1.0, markers[2].position, 0.0) + assertTrue( + TimelineMarkers.build(listOf(comment("c", at = 1.0)), duration = 0.0, buckets = 10) + .isEmpty() + ) + } + + @Test + fun markersClampOrderAndCountLikeIOS() { + val comments = + listOf( + comment("neg", at = -1.0), + comment("nan", at = Double.NaN), + comment("inf", at = Double.POSITIVE_INFINITY), + comment("zero", at = 0.0, author = "u1"), + comment("end", at = 100.0, author = "u2"), + comment("almost", at = 99.999, author = "u3"), + comment("b1", at = 55.0, author = "u1", minute = 3), + comment("b2", at = 54.0, author = "u2", minute = 2), + comment("b3", at = 53.0, author = "u3", minute = 1), + comment("b4", at = 52.0, author = "u4", minute = 0), + comment("b5", at = 51.0, author = "u1", minute = 4), + comment("orphan", at = 30.0, parent = "gone"), + comment( + "emoji-reply", + CommentKind.EMOJI, + content = "🙌", + at = 31.0, + parent = "gone", + ), + comment("t1", CommentKind.EMOJI, content = "👍", at = 71.0), + comment("t2", CommentKind.EMOJI, content = "😂", at = 72.0), + comment("t3", CommentKind.EMOJI, content = "👎", at = 73.0), + comment("t4", CommentKind.EMOJI, content = "😂", at = 74.0), + comment("t5", CommentKind.EMOJI, content = "👍", at = 74.5), + ) + fun author(id: String) = CommentAuthor(id, id, null) + assertEquals( + listOf( + TimelineMarker( + "zero", + 0.0, + 0.0, + listOf("zero"), + listOf(author("u1")), + emptyList(), + 1, + 0, + ), + TimelineMarker( + "emoji-reply", + 31.0, + 0.31, + listOf("emoji-reply"), + emptyList(), + listOf("🙌"), + 0, + 1, + ), + TimelineMarker( + "b5", + 51.0, + 0.51, + listOf("b5", "b4", "b3", "b2", "b1"), + listOf(author("u1"), author("u4"), author("u3")), + emptyList(), + 5, + 0, + ), + TimelineMarker( + "t1", + 71.0, + 0.71, + listOf("t1", "t2", "t3", "t4", "t5"), + emptyList(), + listOf("👍", "😂", "👎", "😂", "👍"), + 0, + 5, + ), + TimelineMarker( + "almost", + 99.999, + 0.9999899999999999, + listOf("almost", "end"), + listOf(author("u3"), author("u2")), + emptyList(), + 2, + 0, + ), + ), + TimelineMarkers.build(comments, duration = 100.0, buckets = 10), + ) + val markers = TimelineMarkers.build(comments, duration = 100.0, buckets = 10) + assertEquals(listOf(1, 1, 5, 5, 2), markers.map { it.count }) + assertEquals(listOf(null, "🙌", null, "👍", null), markers.map { it.leadingEmoji }) + val one = TimelineMarkers.build(comments, duration = 100.0, buckets = 1).single() + assertEquals("zero", one.id) + assertEquals(14, one.count) + assertEquals( + listOf("y", "x", "z"), + TimelineMarkers.build( + listOf( + comment("y", at = 5.0), + comment("x", at = 5.0), + comment("z", CommentKind.EMOJI, content = "👍", at = 5.0), + ), + duration = 10.0, + buckets = 4, + ) + .single() + .commentIds, + ) + for ((duration, buckets) in + listOf( + 100.0 to 0, + 100.0 to -1, + Double.NaN to 10, + Double.POSITIVE_INFINITY to 10, + -5.0 to 10, + )) { + assertTrue( + "$duration $buckets", + TimelineMarkers.build(comments, duration, buckets).isEmpty(), + ) + } + } + + @Test + fun noCueIsActiveOutsideEveryRange() { + val cues = + listOf( + TranscriptCue(0, 1.0, 2.0, "a"), + TranscriptCue(1, 3.0, 3.0, "b"), + TranscriptCue(2, 6.0, 8.0, "c"), + ) + assertNull(TranscriptCue.active(cues, 0.5)) + assertNull(TranscriptCue.active(cues, -1.0)) + assertNull(TranscriptCue.active(cues, 3.0)) + assertNull(TranscriptCue.active(cues, 8.0)) + assertNull(TranscriptCue.active(cues, Double.NaN)) + assertNull(TranscriptCue.active(cues, Double.POSITIVE_INFINITY)) + assertEquals(0, TranscriptCue.active(cues, 1.999)?.id) + assertEquals(2, TranscriptCue.active(cues, 7.999)?.id) + } + + @Test + fun transcriptExports() { + val cues = + listOf( + TranscriptCue(0, 0.0, 2.0, "Hello"), + TranscriptCue(1, 2.5, 4.0, "there."), + TranscriptCue(2, 70.0, 72.25, "Later"), + ) + assertEquals("Hello there.\n\nLater", TranscriptExport.plainText(cues)) + val run = (0 until 13).map { TranscriptCue(it, it.toDouble(), it + 0.9, "w$it") } + val paragraphs = TranscriptExport.plainText(run).split("\n\n") + assertEquals(listOf(6, 6, 1), paragraphs.map { it.split(" ").size }) + assertEquals(run.joinToString(" ") { it.text }, paragraphs.joinToString(" ")) + assertEquals( + "[0:00] Hello\n[0:02] there.\n[1:10] Later", + TranscriptExport.timestamped(cues), + ) + assertTrue( + TranscriptExport.vtt(cues).startsWith("WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nHello") + ) + assertTrue("00:01:10.000 --> 00:01:12.250" in TranscriptExport.vtt(cues)) + assertEquals( + listOf("Hello", "there.", "Later"), + WebVtt.parse(TranscriptExport.vtt(cues)).map { it.text }, + ) + } + + @Test + fun exportsHandleOddCuesLikeIOS() { + val cues = + listOf( + TranscriptCue(0, -3.0, 0.0005, " a "), + TranscriptCue(1, 1.9995, 3599.9996, " "), + TranscriptCue(2, 3.9, 360000.5, "b\nc"), + TranscriptCue(3, 360002.4, Double.NaN, "d"), + TranscriptCue(4, 0.0, 1.0, "e"), + TranscriptCue(5, 5.0, 4.0, "f"), + TranscriptCue(6, 5.99, 6.0, "g"), + ) + assertEquals("a\n\nb\nc d\n\ne\n\nf g", TranscriptExport.plainText(cues)) + assertEquals( + "[0:00] a \n[0:01] \n[0:03] b\nc\n[100:00:02] d\n[0:00] e\n[0:05] f\n[0:05] g", + TranscriptExport.timestamped(cues), + ) + assertEquals( + "WEBVTT\n\n00:00:00.000 --> 00:00:00.001\n a \n\n00:00:02.000 --> 01:00:00.000\n \n\n00:00:03.900 --> 100:00:00.500\nb\nc\n\n100:00:02.400 --> 00:00:00.000\nd\n\n00:00:00.000 --> 00:00:01.000\ne\n\n00:00:05.000 --> 00:00:04.000\nf\n\n00:00:05.990 --> 00:00:06.000\ng\n", + TranscriptExport.vtt(cues), + ) + assertEquals("", TranscriptExport.plainText(emptyList())) + assertEquals("", TranscriptExport.timestamped(emptyList())) + assertEquals("WEBVTT\n\n\n", TranscriptExport.vtt(emptyList())) + val stamps = + mapOf( + 0.0005 to "00:00:00.001", + 0.0015 to "00:00:00.002", + 0.0025 to "00:00:00.003", + 59.9995 to "00:01:00.000", + 3599.9995 to "01:00:00.000", + 1e9 to "277777:46:40.000", + ) + for ((time, stamp) in stamps) { + val text = TranscriptExport.vtt(listOf(TranscriptCue(0, time, time, "x"))) + assertEquals(time.toString(), "WEBVTT\n\n$stamp --> $stamp\nx\n", text) + } + } +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/UtilityTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/UtilityTest.kt new file mode 100644 index 00000000000..4365637a78d --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/UtilityTest.kt @@ -0,0 +1,422 @@ +package so.cap.kit + +import java.io.File +import java.time.DayOfWeek +import java.time.Instant +import java.time.ZoneId +import java.util.Locale +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.SerializationException +import kotlinx.serialization.SerializationStrategy +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Encoder +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class FormattingTest { + @Test + fun formatsTimestamps() { + assertEquals("0:00", CapFormat.timestamp(0.0)) + assertEquals("1:05", CapFormat.timestamp(65.9)) + assertEquals("1:02:03", CapFormat.timestamp(3723.0)) + assertEquals("0:00", CapFormat.timestamp(Double.NEGATIVE_INFINITY)) + assertNull(CapFormat.duration(null)) + assertNull(CapFormat.duration(Double.NaN)) + } + + @Test + fun buildsFlags() { + assertEquals("🇬🇧", CapFormat.flag("gb")) + assertNull(CapFormat.flag("USA")) + assertNull(CapFormat.flag("1A")) + } + + @Test + fun formatsPercentages() { + assertEquals(CapFormat.percentage(0.5), CapFormat.percentage(50.0)) + } + + @Test + fun durationsRejectWhatCannotBeShown() { + assertEquals("2:05", CapFormat.duration(125.4)) + assertEquals("0:00", CapFormat.duration(0.0)) + assertNull(CapFormat.duration(-1.0)) + assertNull(CapFormat.duration(Double.POSITIVE_INFINITY)) + assertEquals("0:00", CapFormat.timestamp(Double.NaN)) + assertEquals("0:59", CapFormat.timestamp(59.999)) + assertEquals("59:59", CapFormat.timestamp(3599.0)) + assertEquals("100:00:00", CapFormat.timestamp(360000.0)) + } + + @Test + fun percentagesRoundLikeIOS() { + val expected = + mapOf( + 0.0 to "0%", + 0.5 to "50%", + 58.3 to "58.3%", + 41.6 to "41.6%", + 1.0 to "100%", + 1.5 to "1.5%", + 0.005 to "0.5%", + 0.0005 to "0%", + 0.125 to "12.5%", + 0.0025 to "0.2%", + 100.0 to "100%", + 0.999 to "99.9%", + 0.9995 to "100%", + 33.333 to "33.3%", + 0.0835 to "8.4%", + 0.0845 to "8.4%", + 250.0 to "250%", + 99.95 to "100%", + 99.949 to "99.9%", + -0.5 to "-50%", + -50.0 to "-5,000%", + 0.2225 to "22.2%", + 0.2235 to "22.4%", + 2.675 to "2.7%", + 12345.678 to "12,345.7%", + Double.NaN to "NaN%", + Double.POSITIVE_INFINITY to "∞%", + Double.NEGATIVE_INFINITY to "-∞%", + ) + for ((value, text) in expected) { + assertEquals(value.toString(), text, CapFormat.percentage(value)) + } + } + + @Test + fun countsUseCompactNames() { + val expected = + mapOf( + 0 to "0", + 7 to "7", + 999 to "999", + 1000 to "1K", + 1049 to "1K", + 1050 to "1K", + 1051 to "1.1K", + 1200 to "1.2K", + 1250 to "1.2K", + 1350 to "1.4K", + 1450 to "1.4K", + 1550 to "1.6K", + 1950 to "2K", + 1999 to "2K", + 9949 to "9.9K", + 9950 to "10K", + 9999 to "10K", + 10000 to "10K", + 12345 to "12.3K", + 99949 to "99.9K", + 99950 to "100K", + 150000 to "150K", + 999499 to "999.5K", + 999949 to "999.9K", + 999950 to "1M", + 999999 to "1M", + 1000000 to "1M", + 1050000 to "1M", + 1150000 to "1.2M", + 1250000 to "1.2M", + 1500000000 to "1.5B", + Int.MAX_VALUE to "2.1B", + -999 to "-999", + -1200 to "-1.2K", + -999950 to "-1M", + Int.MIN_VALUE to "-2.1B", + ) + for ((value, text) in expected) { + assertEquals(value.toString(), text, CapFormat.count(value)) + } + } + + @Test + fun relativeDatesMatchIOS() { + val lines = javaClass.getResource("/relative-dates.txt")!!.readText().lines() + var zone = ZoneId.of("UTC") + var firstDay = DayOfWeek.MONDAY + var now = Instant.EPOCH + var checked = 0 + for (line in lines.filter { it.isNotEmpty() }) { + if (line.startsWith("zone ")) { + val fields = line.split(' ') + zone = ZoneId.of(fields[1]) + firstDay = DayOfWeek.valueOf(fields[2]) + now = Instant.ofEpochSecond(fields[3].toLong()) + continue + } + val (offset, expected) = line.split('|') + val date = now.minusSeconds(offset.toLong()) + assertEquals("$zone $offset", expected, CapFormat.relative(date, now, zone, firstDay)) + checked += 1 + } + assertEquals(192, checked) + } + + @Test + fun relativeDatesWithinAMinuteAreJustNow() { + val now = Instant.parse("2026-11-30T12:00:00Z") + val utc = ZoneId.of("UTC") + for (seconds in listOf(0L, 1, 59, -1, -59)) { + val text = CapFormat.relative(now.minusSeconds(seconds), now, utc, DayOfWeek.MONDAY) + assertEquals(seconds.toString(), "Just now", text) + } + assertEquals( + "Just now", + CapFormat.relative(now.minusMillis(59_999), now, utc, DayOfWeek.MONDAY), + ) + assertEquals( + "1 min. ago", + CapFormat.relative(now.minusSeconds(60), now, utc, DayOfWeek.MONDAY), + ) + assertEquals( + "in 1 min.", + CapFormat.relative(now.plusSeconds(60), now, utc, DayOfWeek.MONDAY), + ) + assertEquals( + "1 min. ago", + CapFormat.relative(now.minusMillis(89_400), now, utc, DayOfWeek.MONDAY), + ) + assertEquals( + "2 min. ago", + CapFormat.relative(now.minusMillis(89_500), now, utc, DayOfWeek.MONDAY), + ) + } + + @Test + fun byteCountsMatchIOS() { + val expected = + mapOf( + 0L to "Zero KB", + 1L to "1 byte", + 2L to "2 bytes", + 999L to "999 bytes", + 1000L to "1 KB", + 1024L to "1 KB", + 1499L to "1 KB", + 1500L to "2 KB", + 2500L to "3 KB", + 999_499L to "999 KB", + 999_500L to "1 MB", + 1_049_999L to "1 MB", + 1_050_000L to "1.1 MB", + 1_250_000L to "1.3 MB", + 25_000_000L to "25 MB", + 999_949_999L to "999.9 MB", + 999_950_000L to "1 GB", + 1_005_000_000L to "1.01 GB", + 1_025_000_000L to "1.03 GB", + 5_000_000_000L to "5 GB", + 999_999_999_999L to "1 TB", + 1_234_567_890_123L to "1.23 TB", + 1_000_000_000_000_000L to "1 PB", + Long.MAX_VALUE to "9.22 EB", + -1L to "-1 byte", + -1500L to "-2 KB", + -1_500_000L to "-1.5 MB", + ) + for ((value, text) in expected) { + assertEquals(value.toString(), text, CapFormat.byteCount(value)) + } + } + + @Test + fun namesRegionsAndKeepsUnknownCodes() { + assertEquals("United Kingdom", CapFormat.regionName("gb", Locale.ENGLISH)) + assertEquals("Deutschland", CapFormat.regionName("DE", Locale.GERMAN)) + assertEquals("xx", CapFormat.regionName("xx", Locale.ENGLISH)) + assertEquals("", CapFormat.regionName("", Locale.ENGLISH)) + assertEquals("not a code", CapFormat.regionName("not a code", Locale.ENGLISH)) + } +} + +class DiskCacheTest { + @get:Rule val folder = TemporaryFolder() + + private val counts = MapSerializer(String.serializer(), Int.serializer()) + + @Test + fun namespacesAndRejectsUnsafeNamespaces() = runTest { + val base = folder.newFolder() + val cache = SnapshotCache(File(base, "snap")) + cache.write(counts, mapOf("a" to 1), "user_1", "caps/org_1") + assertEquals(mapOf("a" to 1), cache.read(counts, "user_1", "caps/org_1")) + assertNull(cache.read(counts, "user_2", "caps/org_1")) + cache.write(counts, mapOf("a" to 1), "../evil", "x") + assertFalse(File(base, "evil").exists()) + cache.removeAll() + assertNull(cache.read(counts, "user_1", "caps/org_1")) + } + + @Test + fun keysBecomeFileNamesThatCannotLeaveTheNamespace() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + val names = + mapOf( + "caps/org_1" to "caps_org_1", + "caps-org_1-personal-root" to "caps-org_1-personal-root", + "a.b" to "a_b", + ".." to "__", + "../../x" to "______x", + "a b" to "a_b", + "a\u0000b" to "a_b", + "\uD83D\uDE00" to "_", + "\u00E9" to "\u00E9", + "\u4E2D\u6587" to "\u4E2D\u6587", + "\u00BD\u00B2\u2167\u0663" to "\u00BD\u00B2\u2167\u0663", + "k".repeat(200) to "k".repeat(200), + ) + for ((key, name) in names) { + cache.write(counts, mapOf(key to 1), "user_1", key) + assertTrue(key, File(root, "user_1/$name.json").isFile) + assertEquals(key, mapOf(key to 1), cache.read(counts, "user_1", key)) + } + val before = File(root, "user_1").list()!!.toSet() + for (key in listOf("", "k".repeat(201))) { + cache.write(counts, mapOf("a" to 1), "user_1", key) + assertNull(cache.read(counts, "user_1", key)) + } + assertEquals(before, File(root, "user_1").list()!!.toSet()) + assertEquals(listOf("user_1"), root.list()!!.toList()) + } + + @Test + fun namespacesMustBeIds() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + for (namespace in listOf("", "..", ".", "a/b", "a\\b", "user 1", "u".repeat(129))) { + cache.write(counts, mapOf("a" to 1), namespace, "caps") + assertNull(namespace, cache.read(counts, namespace, "caps")) + } + assertEquals(emptyList(), root.list()!!.toList()) + cache.write(counts, mapOf("a" to 1), "u".repeat(128), "caps") + assertEquals(listOf("u".repeat(128)), root.list()!!.toList()) + } + + @Test + fun aNewSnapshotReplacesTheOldOneAndLeavesNothingElseBehind() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + cache.write(counts, mapOf("a" to 1), "user_1", "caps") + cache.write(counts, mapOf("b" to 2), "user_1", "caps") + assertEquals(mapOf("b" to 2), cache.read(counts, "user_1", "caps")) + assertEquals(listOf("caps.json"), File(root, "user_1").list()!!.toList()) + } + + @Test + fun writesToOneKeyDoNotInterleave() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + val snapshots = (0 until 64).map { index -> (0..index).associate { "key$it" to index } } + snapshots + .map { launch(Dispatchers.Default) { cache.write(counts, it, "user_1", "caps") } } + .joinAll() + assertTrue(cache.read(counts, "user_1", "caps") in snapshots) + assertEquals(listOf("caps.json"), File(root, "user_1").list()!!.toList()) + } + + @Test + fun removesOneSnapshotOrAllOfThem() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + cache.write(counts, mapOf("a" to 1), "user_1", "bootstrap") + cache.write(counts, mapOf("b" to 2), "user_1", "caps") + cache.write(counts, mapOf("c" to 3), "user_2", "caps") + cache.remove("user_1", "caps") + cache.remove("user_1", "never-written") + cache.remove("../evil", "caps") + assertNull(cache.read(counts, "user_1", "caps")) + assertEquals(mapOf("a" to 1), cache.read(counts, "user_1", "bootstrap")) + assertEquals(mapOf("c" to 3), cache.read(counts, "user_2", "caps")) + cache.removeAll() + assertFalse(root.exists()) + cache.removeAll() + assertNull(cache.read(counts, "user_1", "bootstrap")) + cache.write(counts, mapOf("d" to 4), "user_1", "bootstrap") + assertEquals(mapOf("d" to 4), cache.read(counts, "user_1", "bootstrap")) + } + + @Test + fun unreadableSnapshotsReadAsMissing() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + cache.write(counts, mapOf("a" to 1), "user_1", "caps") + assertNull(cache.read(CapsPage.serializer(), "user_1", "caps")) + File(root, "user_1/caps.json").writeText("{\"a\":") + assertNull(cache.read(counts, "user_1", "caps")) + File(root, "user_1/caps.json").writeText("") + assertNull(cache.read(counts, "user_1", "caps")) + File(root, "user_1/caps.json").delete() + File(root, "user_1/caps.json").mkdir() + assertNull(cache.read(counts, "user_1", "caps")) + } + + @Test + fun aCacheThatCannotBeWrittenStaysQuiet() = runTest { + val blocked = folder.newFile() + val cache = SnapshotCache(blocked) + cache.write(counts, mapOf("a" to 1), "user_1", "caps") + assertNull(cache.read(counts, "user_1", "caps")) + cache.remove("user_1", "caps") + assertTrue(blocked.isFile) + } + + @Test + fun aFailedWriteRemovesWhatItCouldNotReplace() = runTest { + val root = folder.newFolder() + val cache = SnapshotCache(root) + cache.write(counts, mapOf("a" to 1), "user_1", "caps") + cache.write(Unencodable, 1, "user_1", "caps") + assertEquals(mapOf("a" to 1), cache.read(counts, "user_1", "caps")) + File(root, "user_1/bootstrap.json").mkdirs() + File(root, "user_1/bootstrap.json/stale").writeText("x") + cache.write(counts, mapOf("b" to 2), "user_1", "bootstrap") + assertEquals(listOf("caps.json"), File(root, "user_1").list()!!.toList()) + cache.write(counts, mapOf("b" to 2), "user_1", "bootstrap") + assertEquals(mapOf("b" to 2), cache.read(counts, "user_1", "bootstrap")) + } + + @Test + fun libraryAndSessionSnapshotsSurviveTheDisk() = runTest { + val cache = SnapshotCache(folder.newFolder()) + val page = CapJson.json.decodeFromString(fixture("caps")) + val bootstrap = CapJson.json.decodeFromString(fixture("bootstrap")) + val analytics = CapJson.json.decodeFromString(fixture("analytics")) + cache.write(CapsPage.serializer(), page, "user_123", "caps-org_123-personal-root") + cache.write(Bootstrap.serializer(), bootstrap, "user_123", "bootstrap") + cache.write(AnalyticsResponse.serializer(), analytics, "user_123", "analytics-org_123") + assertEquals( + page, + cache.read(CapsPage.serializer(), "user_123", "caps-org_123-personal-root"), + ) + assertEquals(bootstrap, cache.read(Bootstrap.serializer(), "user_123", "bootstrap")) + assertEquals( + analytics, + cache.read(AnalyticsResponse.serializer(), "user_123", "analytics-org_123"), + ) + assertNull(cache.read(Bootstrap.serializer(), "user_123", "caps-org_123-personal-root")) + } +} + +private object Unencodable : SerializationStrategy { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("so.cap.kit.Unencodable", PrimitiveKind.INT) + + override fun serialize(encoder: Encoder, value: Int) = + throw SerializationException("Cannot be encoded") +} diff --git a/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/WebVttTest.kt b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/WebVttTest.kt new file mode 100644 index 00000000000..5074935719a --- /dev/null +++ b/apps/mobile-android/capkit/src/test/kotlin/so/cap/kit/WebVttTest.kt @@ -0,0 +1,85 @@ +package so.cap.kit + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class WebVttTest { + @Test + fun parsesCuesAndStripsMarkup() { + val source = + "WEBVTT\r\n\r\n1\r\n00:00:01.000 --> 00:00:04.500 align:start\r\n" + + "Hello there\r\n\r\n00:01:02,250 --> 00:01:05.000\n" + + "Second line\ncontinues\n\nbroken --> cue\nIgnored\n" + val cues = WebVtt.parse(source) + assertEquals(2, cues.size) + assertEquals(1.0, cues[0].start, 0.0) + assertEquals(4.5, cues[0].end, 0.0) + assertEquals("Hello there", cues[0].text) + assertEquals(62.25, cues[1].start, 0.0) + assertEquals("Second line continues", cues[1].text) + } + + @Test + fun activeCueUsesHalfOpenRanges() { + val cues = + listOf( + TranscriptCue(0, 0.0, 2.0, "a"), + TranscriptCue(1, 2.0, 4.0, "b"), + TranscriptCue(2, 6.0, 8.0, "c"), + ) + assertEquals(0, TranscriptCue.active(cues, 0.0)?.id) + assertEquals(1, TranscriptCue.active(cues, 2.0)?.id) + assertNull(TranscriptCue.active(cues, 5.0)) + assertNull(TranscriptCue.active(cues, 9.0)) + assertNull(TranscriptCue.active(emptyList(), 1.0)) + } +} + +class CaptionPhraseTest { + private val long = + TranscriptCue( + 0, + 10.0, + 20.0, + "So the first thing you will notice is that the timeline now snaps clips to each " + + "other and to the playhead, which makes trimming much faster", + ) + + @Test + fun shortCuesShowWhole() { + val cue = TranscriptCue(0, 0.0, 2.0, "Short and sweet.") + assertEquals("Short and sweet.", cue.caption(1.0)) + } + + @Test + fun longCuesSplitIntoEvenPhrasesOfWholeWords() { + val phrases = TranscriptCue.phrases(long.text, 64) + assertEquals(3, phrases.size) + assertTrue(phrases.all { it.length <= 64 }) + assertEquals(long.text, phrases.joinToString(" ")) + val lengths = phrases.map { it.length } + assertTrue(lengths.max() - lengths.min() < 25) + } + + @Test + fun phrasesFollowTheSpeech() { + val phrases = TranscriptCue.phrases(long.text, 64) + assertEquals(phrases[0], long.caption(10.2)) + assertEquals(phrases[1], long.caption(15.0)) + assertEquals(phrases[2], long.caption(19.9)) + assertEquals(phrases[2], long.caption(25.0)) + } + + @Test + fun aSingleLongWordStillShows() { + val word = "w".repeat(90) + assertEquals(listOf(word), TranscriptCue.phrases(word, 64)) + } + + @Test + fun noBreakSpacesSeparateWordsToo() { + assertEquals(listOf("one", "two"), TranscriptCue.phrases("one\u00A0two", 3)) + } +} diff --git a/apps/mobile-android/capkit/src/test/resources/relative-dates.txt b/apps/mobile-android/capkit/src/test/resources/relative-dates.txt new file mode 100644 index 00000000000..1611315b9e2 --- /dev/null +++ b/apps/mobile-android/capkit/src/test/resources/relative-dates.txt @@ -0,0 +1,196 @@ +zone Europe/London MONDAY 1796081129 +61|1 min. ago +62|1 min. ago +90|2 min. ago +91|2 min. ago +120|2 min. ago +1800|30 min. ago +1801|30 min. ago +3570|1 hr. ago +3571|1 hr. ago +3600|1 hr. ago +3601|1 hr. ago +5400|2 hr. ago +5401|2 hr. ago +82801|23 hr. ago +84601|yesterday +86400|yesterday +86401|yesterday +129601|yesterday +169201|yesterday +172801|2 days ago +518401|6 days ago +604801|last wk. +691201|2 wk. ago +1123201|2 wk. ago +1209601|2 wk. ago +1728001|3 wk. ago +2332801|last mo. +2419201|last mo. +2505601|last mo. +2592001|last mo. +2678401|last mo. +3888001|last mo. +5184001|last mo. +17280001|6 mo. ago +31449601|11 mo. ago +31536001|last yr. +31622401|last yr. +34560001|last yr. +69120001|2 yr. ago +-89|in 1 min. +-3599|in 1 hr. +-84599|in 23 hr. +-86399|tomorrow +-172799|in 2 days +-604799|next wk. +-691199|next wk. +-2678399|next mo. +-34559999|in 2 yr. +zone America/Los_Angeles SUNDAY 1796081129 +61|1 min. ago +62|1 min. ago +90|2 min. ago +91|2 min. ago +120|2 min. ago +1800|30 min. ago +1801|30 min. ago +3570|1 hr. ago +3571|1 hr. ago +3600|1 hr. ago +3601|1 hr. ago +5400|2 hr. ago +5401|2 hr. ago +82801|23 hr. ago +84601|yesterday +86400|yesterday +86401|yesterday +129601|yesterday +169201|2 days ago +172801|2 days ago +518401|6 days ago +604801|last wk. +691201|last wk. +1123201|2 wk. ago +1209601|2 wk. ago +1728001|3 wk. ago +2332801|last mo. +2419201|last mo. +2505601|last mo. +2592001|last mo. +2678401|last mo. +3888001|last mo. +5184001|last mo. +17280001|6 mo. ago +31449601|11 mo. ago +31536001|last yr. +31622401|last yr. +34560001|last yr. +69120001|2 yr. ago +-89|in 1 min. +-3599|in 1 hr. +-84599|in 23 hr. +-86399|tomorrow +-172799|in 2 days +-604799|next wk. +-691199|next wk. +-2678399|next mo. +-34559999|in 2 yr. +zone Asia/Kolkata SUNDAY 1796081129 +61|1 min. ago +62|1 min. ago +90|2 min. ago +91|2 min. ago +120|2 min. ago +1800|30 min. ago +1801|30 min. ago +3570|1 hr. ago +3571|1 hr. ago +3600|1 hr. ago +3601|1 hr. ago +5400|2 hr. ago +5401|2 hr. ago +82801|23 hr. ago +84601|yesterday +86400|yesterday +86401|yesterday +129601|2 days ago +169201|2 days ago +172801|2 days ago +518401|6 days ago +604801|last wk. +691201|last wk. +1123201|2 wk. ago +1209601|2 wk. ago +1728001|3 wk. ago +2332801|last mo. +2419201|last mo. +2505601|last mo. +2592001|last mo. +2678401|2 mo. ago +3888001|2 mo. ago +5184001|2 mo. ago +17280001|7 mo. ago +31449601|last yr. +31536001|last yr. +31622401|last yr. +34560001|last yr. +69120001|2 yr. ago +-89|in 1 min. +-3599|in 1 hr. +-84599|in 23 hr. +-86399|tomorrow +-172799|in 2 days +-604799|next wk. +-691199|next wk. +-2678399|next mo. +-34559999|in 2 yr. +zone Pacific/Auckland MONDAY 1796081129 +61|1 min. ago +62|1 min. ago +90|2 min. ago +91|2 min. ago +120|2 min. ago +1800|30 min. ago +1801|30 min. ago +3570|1 hr. ago +3571|1 hr. ago +3600|1 hr. ago +3601|1 hr. ago +5400|2 hr. ago +5401|2 hr. ago +82801|23 hr. ago +84601|yesterday +86400|yesterday +86401|yesterday +129601|yesterday +169201|2 days ago +172801|2 days ago +518401|6 days ago +604801|last wk. +691201|last wk. +1123201|2 wk. ago +1209601|2 wk. ago +1728001|3 wk. ago +2332801|last mo. +2419201|last mo. +2505601|last mo. +2592001|last mo. +2678401|2 mo. ago +3888001|2 mo. ago +5184001|2 mo. ago +17280001|7 mo. ago +31449601|last yr. +31536001|last yr. +31622401|last yr. +34560001|last yr. +69120001|2 yr. ago +-89|in 1 min. +-3599|in 1 hr. +-84599|in 23 hr. +-86399|tomorrow +-172799|in 2 days +-604799|next wk. +-691199|next wk. +-2678399|next mo. +-34559999|in 2 yr. diff --git a/apps/mobile-android/gradle.properties b/apps/mobile-android/gradle.properties new file mode 100644 index 00000000000..507addfcaaa --- /dev/null +++ b/apps/mobile-android/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=true +kotlin.code.style=official diff --git a/apps/mobile-android/gradle/libs.versions.toml b/apps/mobile-android/gradle/libs.versions.toml new file mode 100644 index 00000000000..b6056495a11 --- /dev/null +++ b/apps/mobile-android/gradle/libs.versions.toml @@ -0,0 +1,52 @@ +[versions] +activityCompose = "1.13.0" +agp = "9.5.3" +androidxTestExtJunit = "1.3.0" +androidxTestRunner = "1.7.0" +browser = "1.10.0" +coil = "3.6.3" +datastore = "1.3.0" +composeBom = "2026.11.01" +espresso = "3.7.0" +junit = "4.13.2" +kotlin = "2.4.21" +kotlinxCoroutines = "1.11.0" +kotlinxSerialization = "1.13.0" +media3 = "1.11.1" +ktfmt = "0.64" +navigation3 = "1.2.2" +okhttp = "5.5.1" +spotless = "8.12.0" + +[libraries] +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } +androidx-browser = { module = "androidx.browser:browser", version.ref = "browser" } +androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" } +androidx-compose-material3 = { module = "androidx.compose.material3:material3" } +androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4" } +androidx-navigation3-runtime = { module = "androidx.navigation3:navigation3-runtime", version.ref = "navigation3" } +androidx-navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "navigation3" } +androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "espresso" } +androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExtJunit" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" } +coil-compose-core = { module = "io.coil-kt.coil3:coil-compose-core", version.ref = "coil" } +coil-network-okhttp = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" } +datastore-preferences-core = { module = "androidx.datastore:datastore-preferences-core", version.ref = "datastore" } +junit = { module = "junit:junit", version.ref = "junit" } +kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" } +kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerialization" } +media3-datasource-okhttp = { module = "androidx.media3:media3-datasource-okhttp", version.ref = "media3" } +media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3" } +media3-session = { module = "androidx.media3:media3-session", version.ref = "media3" } +media3-exoplayer-hls = { module = "androidx.media3:media3-exoplayer-hls", version.ref = "media3" } +media3-ui-compose = { module = "androidx.media3:media3-ui-compose", version.ref = "media3" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } diff --git a/apps/mobile-android/gradle/wrapper/gradle-wrapper.jar b/apps/mobile-android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..51cbd2a6f81 Binary files /dev/null and b/apps/mobile-android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/apps/mobile-android/gradle/wrapper/gradle-wrapper.properties b/apps/mobile-android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..2f9728a9015 --- /dev/null +++ b/apps/mobile-android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=4f2135b741f272acc88c168a52202a0a63fceee0cd61ee753da79694cd2b1e4b +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.3-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/apps/mobile-android/gradlew b/apps/mobile-android/gradlew new file mode 100755 index 00000000000..249efbb032c --- /dev/null +++ b/apps/mobile-android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/apps/mobile-android/gradlew.bat b/apps/mobile-android/gradlew.bat new file mode 100644 index 00000000000..03754c4c3d9 --- /dev/null +++ b/apps/mobile-android/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/apps/mobile-android/settings.gradle.kts b/apps/mobile-android/settings.gradle.kts new file mode 100644 index 00000000000..59865730556 --- /dev/null +++ b/apps/mobile-android/settings.gradle.kts @@ -0,0 +1,27 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "cap-android" + +include(":app") + +include(":capkit") diff --git a/apps/web/__tests__/unit/mobile-api-contract.test.ts b/apps/web/__tests__/unit/mobile-api-contract.test.ts index 4cef5e49ffe..feba009962b 100644 --- a/apps/web/__tests__/unit/mobile-api-contract.test.ts +++ b/apps/web/__tests__/unit/mobile-api-contract.test.ts @@ -193,6 +193,66 @@ describe("mobile API contract schemas", () => { ).toBe("org_123"); }); + it("accepts a per-attempt state and refuses malformed ones", () => { + const state = "q7Rk2_Vb-9xLmP4tZw8sYc"; + expect( + Schema.decodeUnknownSync(Mobile.MobileSessionRequestParams)({ + redirectUri: "cap://auth", + provider: "google", + state, + }).state, + ).toBe(state); + for (const malformed of [ + "short", + "has space in it here", + "a".repeat(129), + ]) { + expect(() => + Schema.decodeUnknownSync(Mobile.MobileSessionRequestParams)({ + redirectUri: "cap://auth", + state: malformed, + }), + ).toThrow(); + } + }); + + it("echoes the state in the auth callback only when one was sent", () => { + const withState = Mobile.createMobileAuthCallbackUrl( + new URL("cap://auth"), + { + apiKey: "key_123", + userId: "user_456", + state: "q7Rk2_Vb-9xLmP4tZw8sYc", + }, + ); + const withoutState = Mobile.createMobileAuthCallbackUrl( + new URL("cap://auth"), + { apiKey: "key_123", userId: "user_456" }, + ); + + expect(withState.protocol).toBe("cap:"); + expect(withState.hostname).toBe("auth"); + expect(withState.searchParams.get("api_key")).toBe("key_123"); + expect(withState.searchParams.get("user_id")).toBe("user_456"); + expect(withState.searchParams.get("state")).toBe("q7Rk2_Vb-9xLmP4tZw8sYc"); + expect(withoutState.searchParams.has("state")).toBe(false); + }); + + it("keeps the state through the signed-out login redirect", () => { + const loginRedirectUrl = Mobile.createMobileSessionLoginRedirectUrl({ + deploymentOrigin: "https://cap.so", + requestUrl: + "/api/mobile/session/request?provider=google&redirectUri=cap%3A%2F%2Fauth&state=q7Rk2_Vb-9xLmP4tZw8sYc", + provider: "google", + }); + + expect( + new URL(loginRedirectUrl.searchParams.get("next") ?? "").searchParams.get( + "state", + ), + ).toBe("q7Rk2_Vb-9xLmP4tZw8sYc"); + }); + it("builds signed-out Apple login redirects", () => { const requestUrl = "/api/mobile/session/request?provider=apple&redirectUri=cap%3A%2F%2Fauth"; diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts index 4be2dc20ab2..f54dabfec73 100644 --- a/apps/web/app/api/mobile/[...route]/route.ts +++ b/apps/web/app/api/mobile/[...route]/route.ts @@ -3822,9 +3822,15 @@ const ApiLive = HttpApiBuilder.api(Mobile.MobileApiContract).pipe( return yield* Effect.fail(new HttpApiError.BadRequest()); } - redirectUrl.searchParams.set("api_key", session.apiKey); - redirectUrl.searchParams.set("user_id", user.value.id); - return HttpServerResponse.redirect(redirectUrl.toString()); + const callbackUrl = Mobile.createMobileAuthCallbackUrl( + redirectUrl, + { + apiKey: session.apiKey, + userId: user.value.id, + state: urlParams.state, + }, + ); + return HttpServerResponse.redirect(callbackUrl.toString()); } return session; diff --git a/packages/web-domain/src/Mobile.ts b/packages/web-domain/src/Mobile.ts index 2056a655053..5303447fc3b 100644 --- a/packages/web-domain/src/Mobile.ts +++ b/packages/web-domain/src/Mobile.ts @@ -156,8 +156,22 @@ export const MobileSessionRequestParams = Schema.Struct({ redirectUri: Schema.optional(MobileAuthRedirectUri), provider: Schema.optional(Schema.Literal("apple", "google", "workos")), organizationId: Schema.optional(Schema.String), + state: Schema.optional( + Schema.String.pipe(Schema.pattern(/^[A-Za-z0-9_-]{16,128}$/)), + ), }); +export const createMobileAuthCallbackUrl = ( + redirectUrl: URL, + { apiKey, userId, state }: { apiKey: string; userId: string; state?: string }, +) => { + const callbackUrl = new URL(redirectUrl); + callbackUrl.searchParams.set("api_key", apiKey); + callbackUrl.searchParams.set("user_id", userId); + if (state !== undefined) callbackUrl.searchParams.set("state", state); + return callbackUrl; +}; + export const MobileEmailSessionRequestInput = Schema.Struct({ email: Schema.String, });