Compare commits

...
Author SHA1 Message Date
0b0a6e6040
No more Platform menu.
Some checks failed
Forgejo Release / release (push) Successful in 14m11s
Dotnet build and test / build (pull_request) Failing after 16m7s
2026-11-14 23:47:14 +00:00
c4d599cda1
Refactor rendez-vous address editing
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 23:28:19 +00:00
7893777ab3
Replace status bar with global notifications
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 22:44:23 +00:00
910d1ebc35
see th message 2026-11-14 21:33:06 +00:00
f282d14126
si le state persistant est stale ou absent, on accepte le démarrage plutôt que de déclencher l’exception de fond 2026-11-14 21:10:33 +00:00
5ec23d1278
Avoid all users tracking new bugs 2026-11-14 21:08:20 +00:00
6ed1b91019
Starts 1.0.8-rc38 Change description 2026-11-14 19:26:45 +00:00
5c834025d7
enable telemetry 2026-11-14 19:24:18 +00:00
0fa7615a60
Add server-side admin user pagination
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 19:18:01 +00:00
05cefaff32
in a scroll viewer 2026-11-14 18:45:32 +00:00
6839d9cac9
Add opt-in PostIt exception reporting
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 18:09:45 +00:00
0ac6970e9d
feat(postit): keep sessions online and replace banner with auth modal
All checks were successful
Forgejo Release / release (push) Successful in 10m4s
Dotnet build and test / build (pull_request) Successful in 15m16s
Remove the sticky session banner, keep the app connected when possible, restore sessions silently on startup, and show a blocking authentication modal with login, register, and forgot-password actions when auto-reconnect cannot resume the session. Add targeted auth and responsive-layout regressions and update the architecture notes to match the session lifecycle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-13 12:32:58 +00:00
b709d4dd6d
restores the blogs page header height, and fixes the bool 'is in a romm and connected'
Some checks failed
Forgejo Release / release (push) Has been cancelled
Dotnet build and test / build (pull_request) Has been cancelled
2026-11-13 10:10:35 +00:00
5dc991b885
feat(resources): notify users at consumption thresholds
Persist private alerts at 50, 75, 90, 95 and 99 percent of net consumption, reporting only the highest crossed threshold and rearming after consumption decreases. Keep notification reading and dismissal accessible at quota. Add crossing, concurrency, rollback and privacy tests. Verified 229 API and 238 server tests pass.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 18:33:28 +00:00
9a0b5cc06c
better
All checks were successful
Dotnet build and test / build (pull_request) Successful in 20m29s
2026-11-12 17:59:19 +00:00
bf17c5be5d
fix(api): restore SQLite test isolation and relief problem responses
Recreate the anchored SQLite test schema before seeding, restore haircut command seeds, and preserve problem+json error responses with matching OpenAPI metadata. Add regression coverage for repeated resets and response contracts. Verified all 227 API SQLite tests pass.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 17:55:15 +00:00
f8f2d943aa
test(yavsc): categorize server suites as non-regression
Add Category=non-reg to all 75 test classes across the four server test projects, preserve existing traits, document filtered execution, and remove the empty Services class.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 17:29:36 +00:00
adb4a8bc42
test(postit): introduce Avalonia UI collection fixture
Own the headless session lifecycle, centralize window cleanup, migrate subscription page bindings, and guard shared runtime access during the progressive migration.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 17:19:01 +00:00
972b1a5cce
feat(postit): separate call interfaces from text chat
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 16:49:48 +00:00
c36b7e02c6
feat(postit): restore direct calls and list contacts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 16:36:14 +00:00
e35cc5a87f
Fixes the build
All checks were successful
Dotnet build and test / build (pull_request) Successful in 14m30s
2026-11-12 15:01:19 +00:00
3ca07a8c1c
Postgres should already be running
Some checks failed
Dotnet build and test / build (pull_request) Failing after 10m20s
2026-11-12 14:37:00 +00:00
4f95a8840c
test reorg/filtering
Some checks failed
Dotnet build and test / build (pull_request) Failing after 25s
2026-11-12 14:32:19 +00:00
2e3f1af6f8
WebRTC Android et Linux + Admin refund + User UX @Post del 2026-11-11 16:30:42 +00:00
d812266ee0
feat(postit): add native WebRTC calls with TURN IP masking
Replace the direct chat call panel with native Android and Linux WebRTC engines, enforce relay-only privacy, and cover consent, lifecycle, rendering and coturn interoperability. Document deployment and upgrade Avalonia to 12.1.6.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-11 09:24:59 +00:00
384e330a78
reorg 2026-11-10 23:58:19 +00:00
7cda466fa8
feat(postit): add native PayPal subscription page
Add bearer-authenticated subscription checkout, reconciliation and cancellation on the authority host, reuse web subscription services, and document the flow with regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-10 23:57:26 +00:00
993f1bfadb
icon and soft keyboard usage in Android 2026-11-10 22:51:23 +00:00
b1be8e16c5
pgsql17
Some checks failed
Dotnet build and test / build (pull_request) Failing after 29s
2026-11-10 16:20:48 +00:00
362e3aa142
removes confilct between 'run on' and conainer image
Some checks failed
Dotnet build and test / build (pull_request) Failing after 11s
2026-11-10 15:43:32 +00:00
737145dd2c
removes 'docker run' usages
Some checks failed
Dotnet build and test / build (pull_request) Failing after 18s
2026-11-10 14:59:50 +00:00
24e4d9f8a3
Start Postgres
Some checks are pending
Dotnet build and test / build (pull_request) Has started running
2026-11-10 14:18:52 +00:00
3795d6c5f5
try Npgsql in CI
Some checks failed
Dotnet build and test / build (pull_request) Failing after 15m45s
Forgejo Release / release (push) Successful in 10m25s
2026-11-09 22:02:53 +00:00
47b2a1bd27
use Npgsql @CI
Some checks failed
Dotnet build and test / build (pull_request) Failing after 11s
2026-11-09 21:20:26 +00:00
2179a5b22f
ffmpeg from the build image
Some checks failed
Dotnet build and test / build (pull_request) Failing after 12m23s
2026-11-09 17:17:10 +00:00
f54cb90172
test needs ffmpeg
Some checks failed
Dotnet build and test / build (pull_request) Failing after 12m7s
2026-11-09 16:07:10 +00:00
7325a8ec8a
allow partial restore
Some checks failed
Dotnet build and test / build (pull_request) Failing after 13m52s
2026-11-09 15:32:01 +00:00
2ff595a3ef
Don(t block the administration
Some checks failed
Dotnet build and test / build (pull_request) Failing after 15s
2026-11-09 15:23:27 +00:00
30bcb070d9
gives the CORS header to discovery document 2026-11-09 13:21:11 +00:00
689b1a48c2
Add Android podcast background blur
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 19:27:05 +00:00
e72df234bc
Replace MediaMTX with encrypted SRT ingestion via FFmpeg.NET
Manage bounded UDP listeners directly in Yavsc.Api, expose secret SRT URLs in PostIt, and preserve quotas, revocation and replay. Update deployment and privacy documentation, remove relay configuration, and add real-media lifecycle regressions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 16:19:41 +00:00
b157dce4e4
Add OBS podcast ingestion and account withdrawal privacy controls
Support scoped RTMPS publishing through MediaMTX, authenticated replay, resource accounting and PostIt activation/revocation. Close withdrawn accounts, erase managed files and purge eligible payment residues after one year. Include migrations, documentation and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 07:43:15 +00:00
97b350be2d
Owner and admin link to 2026-11-08 05:46:05 +00:00
ed8f41bd4a
feat: refund tracked storage usage on deletion and replacement
Persist per-file storage receipts, preserve refundability on rename, account for PDF replacements and permit deletion at the consumption limit. Update CGU, installation documentation and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 05:40:08 +00:00
650e5f5e30
feat: add resource quotas, PayPal subscriptions and paid disk allowances
Calculate and enforce configurable resource consumption, expose balances in PostIt and document the rule in CGU. Add confirmed monthly PayPal credits and disk quotas of twice the free default for Discovery and five times for Premium, with payment reconciliation, migrations and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 05:02:23 +00:00
0728d2a3f7
Allow amateur performer profiles
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 02:29:09 +00:00
f1c23965b2
Blog edition accessibility 2026-11-08 02:04:59 +00:00
a131a6ddf8
+ chqt_regular 2026-11-07 23:38:02 +00:00
99da1ebe76
blog interface icons 2026-11-06 17:44:14 +00:00
e87165cf38
layout 2026-11-06 15:15:31 +00:00
b98f82663d
fix(android): prevent crash when starting broadcast from preview
Detach preview callbacks through the retained surface holder before deferred native view destruction. Cover native preview teardown followed by camera capture and document the regression check.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-05 11:54:03 +00:00
fa8038c676
screen orientation and awake 2026-11-05 10:44:19 +00:00
256fd5738c
refresh the token 2026-11-04 09:11:21 +00:00
311d55dcc6
feat(postit): keep Android SignalR chat in background without ongoing notification
Share the chat transport between UI, calls and an opt-in background service. Restore account rooms and attempt boot restart, keeping event alerts independent from connection permissions. Document Android limits and add lifecycle regressions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 12:43:46 +00:00
a39c3912ea
Support IPv6 addresses for direct SRTP calls
Extend shared endpoint validation, interface discovery and native media sockets to IPv6. Add real bidirectional IPv6 SRTP, wrong-key rejection and port lifecycle tests, and document connectivity limitations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-02 15:33:03 +00:00
73411f2f7e
Allow public IPv4 addresses for direct SRTP calls
Use shared unicast IPv4 validation for interface discovery, media endpoints and server signaling. Preserve disclosure consent and privacy constraints, and document direct connectivity requirements.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-02 15:25:54 +00:00
7f0e868a32
Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. 2026-11-02 15:20:43 +00:00
377afc711a
Share podcast devices with calls and persist network selection
Reuse camera and microphone preferences across podcast and chat-room pages. Restore available LAN/VPN addresses without persisting disclosure consent, and cover shared preferences and save failures with regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-02 15:17:23 +00:00
ff1a016c91
Persist PostIt podcast device and title preferences
All checks were successful
Forgejo Release / release (push) Successful in 13m7s
Remember detected capture devices, camera and microphone selections, and the default podcast title in user settings. Restore preferences on page creation and surface save failures.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-02 14:13:48 +00:00
4a5a3c8844
Prepare podcast emissions using LiveFlow
Persist scheduled emissions, expose owner-only planning controls in PostIt and publish optional presentation-only announcements on Yavsc.Org. Preserve manual broadcasting and authenticated playback.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-02 14:08:22 +00:00
e3b4414ab1
Dons PayPal 2026-11-02 10:40:29 +00:00
20a44bfde1
warn on podcast deletion 2026-11-01 20:17:10 +00:00
89d9137884
Open Podcast in external browser (WIP) 2026-11-01 18:53:38 +00:00
9578a9c416
dotnet workload restore 2026-11-01 18:51:46 +00:00
a676ef3575
feat(calls): add Android LAN peer calls using Podcast capture
Share the LibVLC SRTP engine with Linux and feed Android MediaRecorder output through its native pipe without transcoding or HLS files. Reuse front-camera capture, preview, remote rendering and foreground service with consent-based controls and background cleanup.

Use separate RTP/RTCP ports to avoid the diagnosed Android VLC SDP crash. Add physical-device media checks and lifecycle regressions; document LAN/VPN scope and remaining separate-device validation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-26 04:15:19 +00:00
cc28ee8b29
feat(calls): implement Linux LAN peer calls over SRTP
Reuse existing ChatHub consent and Podcast LibVLC capture for direct bidirectional H.264/AAC media, with embedded call controls and cleanup. Require HTTPS key exchange and reject IP-masking policies for this opt-in LAN/VPN transport.

Add native SRTP, signaling and lifecycle tests; document setup and remaining physical-device validation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-26 03:05:23 +00:00
5e48831d6d
feat(calls): add consent-based signaling to existing ChatHub
Wire shared PostIt call signaling, account-derived relay policy and temporary TURN credentials. Keep calls disabled pending native Android/Linux media integration. Document experimental Android crash and laboratory removal.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-26 01:00:19 +00:00
56ca115f50
+dotnet-ef 2026-10-25 18:33:41 +00:00
e47bc10026
git version 2026-10-25 16:53:07 +00:00
d8200cb98d
feat(postit): persist call IP privacy preference
Store HideIpAddressInCalls on user accounts, expose it in the profile API and PostIt editor, and preserve preferences for older clients. Add the EF migration, regression tests and architecture documentation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-25 16:49:51 +00:00
df32ec11bf
archidoc calls 2026-10-25 14:02:03 +00:00
c2068f1476
feat(postit): add live capture previews on Android and Desktop
Reuse oriented Android EGL frames and duplicate Desktop video output before encoding without microphone monitoring. Cover preview lifecycle, rendering and recording with targeted tests and document the feature.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-25 01:03:36 +00:00
1dcbfe159a
feat(podcasts): prepare seekable MP4 replays and overlay controls
Remux completed broadcasts with FFmpeg, retain source segments and account for both formats. Serve authenticated byte ranges and add native Android/Desktop replay controls with auto-hide.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-25 00:48:53 +01:00
482 changed files with 99071 additions and 2388 deletions

View file

@ -26,13 +26,12 @@ on:
jobs:
build:
runs-on: docker
container:
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v4
steps:
- name: Clone yavsc
run: |
set -e
cd /src
echo "🔄 Cloning repository ${FORGEJO_SERVER_URL}/${FORGEJO_REPOSITORY}.git"
git clone "${FORGEJO_SERVER_URL}/${FORGEJO_REPOSITORY}.git" _src
cd _src
if [ -n "${GITHUB_REF:-}" ]; then
@ -44,18 +43,19 @@ jobs:
- name: Secret scan
run: |
echo "🔍 Scanning for secrets..."
cd /src/_src && dotnet tool restore && dotnet picket git --verbose --redact --exit-code 1 --log-opts main..HEAD \
cd /src/_src && dotnet tool restore || true
dotnet picket git --verbose --redact --exit-code 1 --log-opts main..HEAD
- name: Build
run: |
echo "🏗️ Building the solution..."
cd /src/_src && dotnet build --verbosity normal
- name: Test
env:
YAVSC_API_TEST_DB_PROVIDER: npgsql
YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION: Host=127.0.0.1;Port=55432;Database=postgres;Username=postgres;Password=postgres;Include Error Detail=true
run: |
echo "🚀 Lancement des tests..."
cd /src/_src && dotnet test \
--report-xunit \
--report-xunit-html \
--report-xunit-html-filename "test-results.html"
cd /src/_src && make test
TEST_EXIT_CODE=$?
echo "Test exit code: $TEST_EXIT_CODE"
if [ $TEST_EXIT_CODE -ne 0 ]; then

1
.gitattributes vendored
View file

@ -1,5 +1,6 @@
# Auto detect text files and perform LF normalization
* text=auto
*.onnx binary
# Custom for Visual Studio
*.cs diff=csharp

View file

@ -9,6 +9,20 @@ on:
jobs:
production-deploy:
runs-on: ubuntu-26.04
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
ports:
- 5432:5432
options: >-
--health-cmd="pg_isready -U postgres -d postgres"
--health-interval=10s
--health-timeout=5s
--health-retries=5
steps:
# 1. Récupération du code
- name: Check out the repo
@ -33,6 +47,8 @@ jobs:
- name: Test
env:
TEST_FAILED: ""
YAVSC_API_TEST_DB_PROVIDER: npgsql
YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION: Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=postgres;Include Error Detail=true
run: make test || export TEST_FAILED=$?
- uses: actions/upload-artifact@v7
with:

4
.vscode/launch.json vendored
View file

@ -17,8 +17,7 @@
"program": "${workspaceFolder}/src/PostIt/PostIt.Desktop/bin/Debug/net10.0/PostIt.Desktop.dll",
"env": {
"POSTIT_SETTINGS_JSON": "/home/paul/Workspace/yavsc/src/PostIt/PostIt/postit-settings.json"
},
"preLaunchTask": "dotnet: build-postit-desktop"
}
},
{
"name": "Android Debug",
@ -57,7 +56,6 @@
"request": "launch",
"projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj"
},
{
"name": "Test PostIt.Android launch (Xamarin.UITest)",
"type": "coreclr",

19
.vscode/tasks.json vendored
View file

@ -1,7 +1,6 @@
{
"version": "2.0.0",
"isRoot": true,
"tasks": [
{
"label": "build-debug-android",
@ -124,11 +123,11 @@
{
"label": "dotnet: build-postit-desktop",
"type": "process",
"problemMatcher": "$msCompile",
"isBuildCommand": true,
"isTestCommand": false,
"isBackground": true,
"command": "dotnet",
"problemMatcher": ["$msCompile"],
"args": ["build", "/property:GenerateFullPaths=true"],
"options": {
"cwd": "src/PostIt/PostIt.Desktop"
@ -136,6 +135,22 @@
"group": {
"kind": "build"
}
},
{
"label": "build-postit-browser",
"type": "process",
"problemMatcher": ["$msCompile"],
"isBuildCommand": true,
"isTestCommand": false,
"isBackground": true,
"command": "dotnet",
"args": ["build", "/property:GenerateFullPaths=true"],
"options": {
"cwd": "src/PostIt/PostIt.Browser"
},
"group": {
"kind": "build"
},
}
]
}

View file

@ -1,6 +1,107 @@
# Changelog
## [1.0.8-rc37] - unstable
### Added
* [PostIt] Replace the persistent status bar with a global notification service using ephemeral toasts for info/success and dismissible modal alerts for warnings/errors.
* [PostIt] Refactor rendez-vous address editing around a dedicated physical-address view model and a dedicated address editor page so the map remains usable without a ScrollViewer and the main command form stays compact on small screens.
* [PostIt/Administration] Rechercher les utilisateurs côté serveur par login ou nom, par pages de 25 résultats maximum avec navigation précédente/suivante.
* [PostIt] Telemetry
## [1.0.8-rc36] - unstable
### Added
* [PostIt/Authentication] Remove the persistent session status bar to recover small-screen space. Restore cached sessions silently and launch OIDC login automatically at startup when restoration fails. Keep proactive renewal and transient-failure retries; display a blocking, scrollable authentication modal on login failure, logout, expired/revoked sessions or a final authenticated 401, with login, registration and password recovery on the configured authority. Move settings, About and logout to the Home menu, preserve the current page during recovery, and cover startup, renewal, account URLs, focus and compact layouts.
* [Resources/Notifications] Persist private user alerts when net resource consumption crosses 50%, 75%, 90%, 95% or 99% of the personal limit, atomically with accounting. Report only the highest threshold crossed per update and rearm after credits or released storage lower consumption. Keep notification consultation and dismissal accessible at quota without consuming resources; no email or live push is sent.
* [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage.
* [Yavsc.Api/Tests] Reset the anchored shared SQLite in-memory database by dropping and recreating its tables before seeding, avoiding duplicate user emails across tests. Restore foreign-key enforcement after cleanup and cover repeated resets with a regression test; leave PostgreSQL cleanup unchanged.
* [Yavsc/Tests] Apply the class-level `Category=non-reg` trait to all test classes in Yavsc.Org.Tests, Yavsc.Api.Tests, Yavsc.Blogs.Tests and Yavsc.Server.Tests, including inherited tests, while preserving existing traits. Remove the empty Services class.
* [PostIt/Tests] Add an xUnit collection fixture owning a headless UI session and its thread, with shared window creation, layout, closing and binding cleanup even after failures. Migrate the subscription page binding test as a pilot; retain per-dispatch application isolation and the parallelism guard during coexistence with legacy headless tests.
* [PostIt/Tests] Disable parallel execution of test collections sharing the Avalonia runtime and static platform state, preventing cross-thread headless initialization and test-case cleanup failures when UI and ordinary tests run together.
* [PostIt/Calls] Move WebRTC and direct SRTP controls out of the text chat into a dedicated call page, opened for a selected room member or an incoming invitation. Include resolved room-member names in chat snapshots for call targeting, without replacing internal connection identifiers. Preserve the call when leaving the chat for that page and hang up when leaving the call page.
* [PostIt/Contacts] Add a Contacts page listing circle members and their associated circles, with duplicate members merged. Presence and calling contacts outside a shared chat room are not yet implemented.
* [PostIt/Calls] Restore the direct IPv4/IPv6 VLC/SRTP call panel alongside WebRTC on supported platforms, route invitations to the matching transport, and retain explicit IP disclosure consent and server privacy policy. Add transport routing and lifecycle regressions.
* [PostIt/Administration] Add an administrator-only consumption relief page reachable from Administration: select a user at their limit, preview and confirm an arbitrary point erasure up to current consumption. Protect the quota-exempt API with the Administrator policy, serialize adjustments with accounting, reject stale confirmations, preserve technical counters and disk quotas, and audit the actor. Add API, service, client and responsive-page regressions.
* [PostIt] Upgrade Avalonia to 12.1.6 and align the headless and native Skia test rendering packages.
* [PostIt/Calls] Replace the chat's direct VLC/SRTP call panel with native WebRTC on Android and Linux: official libwebrtc/Camera2 and GStreamer webrtcbin, existing consent/SignalR signaling, ICE/STUN/coturn, and fail-closed relay-only IP masking. Cancel pending startup and release media on hangup, navigation, interruption and backgrounding. Add privacy/lifecycle, real Linux media/rendering and debug Android interoperability regressions, coturn deployment instructions and a protected-server-secret configuration example.
* [PostIt/PayPal] Add a native subscription page reachable from Home, profile and About: load server-priced Discovery/Premium offers, prepare or resume checkout with the current bearer session, open only PayPal for approval, reconcile confirmed payments and balances, and cancel with confirmation. Add quota-exempt bearer-only endpoints on Yavsc.Org, sharing checkout/cancellation logic with the existing web flow, and regression coverage. Browser return never confirms payment.
## [1.0.8-rc35] - unstable
### Added
* [Resource usage] Let users with the `Administrator` role continue making requests after reaching their consumption quota, while still recording their usage.
* [PostIt.Android/Podcasts] Add an optional persisted background blur for camera preview and broadcasting. Run the bundled PPHumanSeg model locally with ONNX Runtime and composite with OpenGL before encoding; preserve the unfiltered pipeline for calls and OBS.
* [Podcasts/OBS/PostIt] Replace the MediaMTX relay with direct encrypted SRT ingestion managed by [FFmpeg.NET](https://github.com/cmxl/FFmpeg.NET). Reserve bounded UDP listeners on activation, display a secret SRT URL with an empty OBS stream-key field, start on received media, preserve revocation/expiry/quotas and authenticated replay, and invalidate in-memory activations after restart. Remove relay configuration and its authentication endpoint; update deployment, privacy and real-media regressions. Use separate request connections to the shared SQLite test database for reliable concurrent podcast requests.
* [Podcasts/OBS/PostIt] Add opt-in MediaMTX RTMPS ingestion for programmed emissions, activated explicitly from PostIt with one-time scoped, expiring and revocable keys. Start on publisher connection, remux H.264/AAC into the existing authenticated segments and MP4 replay workflow, bound concurrency/duration/buffering, enforce consumption and effective disk quotas, account storage with deletion refunds, and report owner-only ingest errors. Add relay configuration, installation instructions and real synthetic RTMP/RTMPS-to-replay regressions, including active revocation.
* [Yavsc/PostIt/Privacy] Close and pseudonymize withdrawn accounts, cancel PayPal subscriptions before confirming withdrawal, erase managed personal files, avatars and podcasts, and reject old sessions across hosts. Purge eligible technical payment residues one year after effective withdrawal automatically and through a confirmed administrator-only PostIt action; preserve accounting records separately. Clarify the privacy policy, recipients, third-party integrations, withdrawal failures and deployment responsibilities. Make the unique email constraint mutable to support pseudonymization without deleting accounting identities.
* [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions.
* [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU.
* [Yavsc/PostIt/Subscriptions] Align new users' free quota with the existing 500 MiB database default; grant twice that standard quota for Discovery (1,000 MiB) and five times for Premium (2,500 MiB) during confirmed paid monthly periods, including their remainder after cancellation. Restore the user's base quota after expiry or refund without deleting files, refuse uploads beyond available space before writing, and expose the effective quota in profile and usage responses.
* [PostIt/API/Blogs/Yavsc.Org] Compute cumulative resource consumption in configurable points per API call, recorded CPU second, MiB transferred and MiB added to storage, with backend-defined defaults, a default 1,000-point limit and per-user overrides. Serialize accounting and known-cost admission across PostgreSQL hosts, count streamed HTTP bodies, reject further consuming operations with HTTP 429, and check personal uploads before writing. Keep usage/session access available, display the indicator and balance in PostIt, and publish linked CGU explaining the rule and after-measurement enforcement.
* [PostIt.Android] Embed managed assemblies in APKs by default, including Debug builds launched outside the Makefile, to prevent the native startup abort "No assemblies found" when fast-deployment files are absent.
* [PostIt] Remove the redundant "Post detail" heading and its grid row from the blog editor, including the compact layout.
* [PostIt/Android] Combine system-bar/cutout safe-area insets with actual keyboard overlap at the root, instead of replacing Avalonia's automatic safe-area padding with keyboard-only padding. Preserve the toolbar, session banner, attachments and status controls; place article details beside the editor during landscape keyboard input. Only on Android, temporarily hide the title input while editing in compact mode with the keyboard open, restoring it on keyboard closure or focus change without modifying the draft. Verify visible controls outside native system bars, at least three editor lines and the editor's bottom above IME insets.
* [PostIt/Android] Remove the outer blog-page scroll container so the editor, reader and list retain bounded viewports. Keep the editing caret visible after the keyboard resizes the editor; request the native keyboard on a touch tap, not a scroll gesture, without cycling focus or replacing the selection. Add headless regressions and a debug-only device check using a local synthetic article.
* [PostIt.Android] Fix the crash when starting a podcast broadcast with camera preview active: detach preview callbacks using the retained surface holder, before deferred native-view destruction, without accessing an already disposed SurfaceView. Add a device regression covering preview teardown followed by local capture.
* [PostIt.Android] Keep the screen awake during foreground video playback and release it on pause, stop, completion, error or video teardown. Add a persisted, default-off podcast option to keep the screen awake during camera preview/live capture; release on capture end and allow normal sleep in the background without changing the broadcast service. Include native LibVLC libraries when building with a single runtime identifier (including physical ARM64 phones).
* [PostIt/Podcasts] Preview the selected camera before starting a live broadcast, without creating an emission, encoding files or opening the microphone. Release preview on stop, navigation, logout and Android backgrounding, and before starting the actual broadcast. Correct Android portrait orientation for rear and front cameras: subtract the sensor rotation already carried by Camera2's SurfaceTexture matrix, reversing the remaining rotation when that matrix mirrors the front camera (it was turned 90° or upside down); track display changes for both preview and encoded frames, preserving aspect ratio and fixed live stream dimensions.
* [PostIt] Schedule silent OIDC renewal independently of API traffic and SignalR reconnects, while the app is active or background chat is enabled. Derive the wait from the access-token expiration minus the existing 60-second safety margin instead of polling; recalculate after token rotation, login/logout, activity and preference changes. Persist rotated tokens and serialize with request-driven renewal/logout. Run the same maintenance in headless Android chat; background execution and absolute refresh-token lifetime remain subject to Android/identity-provider limits.
* [PostIt.Android] Request Android's battery optimization exemption when explicitly saving settings with background chat enabled, only if not already exempt. Keep automatic settings saves and reconnects free of prompts; refusal does not disable SignalR.
* [PostIt.Android] Add an opt-in ordinary background service for the existing SignalR ChatHub connection, without a permanent notification; show native alerts only for received messages/events and attempt restart after phone startup where Android permits it. Reuse one process-wide connection between service, pages and calls, restore locally remembered rooms per account/host and clean up on opt-out/logout. No Firebase, Google push configuration or server push migration; explain background-data/battery settings and Android execution limits.
* [PostIt/Calls] Support direct IPv6 SRTP calls using global, ULA and loopback addresses, shared endpoint validation, IPv6 UDP sockets and bracketed reception URLs. Exclude scoped/link-local, multicast, unspecified and IPv4-mapped addresses; verify real bidirectional IPv6 audio/video, wrong-key rejection and port lifecycle with LibVLC.
* [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal.
* [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection.
* [Performers] Allow performer profiles without a business registration for amateur use; keep activities available while disabling estimate issuance and new invoicing in the UI and server APIs.
## [1.0.8-rc34] - unstable
### Added
* [PostIt] Share podcast camera/microphone preferences with chat-room calls and persist the selected LAN/VPN address. Restore only currently available network addresses without remembering address-disclosure consent; require an explicit microphone choice for calls when podcasts use no microphone.
* [PostIt] Remember detected podcast cameras/microphones, selected devices (including no microphone) and the default title in user settings; restore them when reopening the page and report persistence failures.
* [Podcasts] Reuse persisted LiveFlow entities to prepare, edit and delete emissions from PostIt with a title, scheduled start and estimated duration. Keep start/stop manual and plans private; optionally publish presentation-only announcements on Yavsc.Org without opening anonymous playback. Preserve broadcast identifiers, legacy recordings and authenticated HLS/MP4 access; add a scheduling migration and lifecycle/privacy regressions.
* [PostIt/API/Yavsc.Org] Expose the private PayPal recipient setting in PostIt's performer editor and authenticated profile API; validate addresses, allow disabling with an empty value and preserve the setting for older clients. Make Web donation settings discoverable from the performer profile and podcast catalogue.
* [API] Initialize the required address field when creating a performer profile so a first configuration can be saved.
* [Yavsc.Org] Add an authenticated Razor podcast catalogue with same-origin API-backed HLS/MP4 playback and replay byte-range support. Reuse Site.ApiUrl and the authority's signing credentials to issue short-lived user tokens, without a separate OAuth client or PodcastWeb configuration. Distinguish an empty catalogue from API/configuration failures.
* [Yavsc.Org] Integrate direct PayPal donations to performers: self-service recipient settings, Yavsc donation pages/history, server-verified checkout and capture, antiforgery/concurrency protection, and validated IPN reconciliation. Reuse the existing merchant settings and persist donation receipts in a dedicated migration; keep uncertain and pending payments distinct from completed donations.
* [PostIt] Open the Yavsc.Org podcast catalogue in the browser instead of the authenticated API playlist; preserve embedded playback and external blog-video links.
* [PostIt.Android/Desktop] Extend LAN/VPN SRTP calls to Android 8+ using the existing front-camera/microphone Podcast capture, rotated native preview and embedded LibVLC remote video, without libwebrtc or new dependencies. Pass the live MediaRecorder pipe directly to the shared SRTP engine without HLS files or transcoding; add a call-specific foreground notification, stop on backgrounding, and allow incoming callers to configure devices before acceptance. Use separate RTP/RTCP UDP ports to avoid a diagnosed Android VLC `rtcp-mux` SDP-generation crash. Add debug-only physical camera/SRTP checks and shared control/pipe-input regressions; Internet/TURN/group calls remain outside this transport.
* [PostIt.Desktop/API] Add opt-in Linux LAN/VPN peer calls through the existing ChatHub, reusing Podcast LibVLC camera/microphone capture and H.264/AAC encoding with direct SRTP instead of HLS. Add consent, embedded local/remote video, hangup/interruption cleanup, private IPv4 validation and per-direction ephemeral keys over HTTPS-only signaling. Reject IP-masking accounts rather than silently bypassing TURN; keep this transport disabled by default and separate from the future Internet/group-call design. Test real bidirectional encrypted audio/video, wrong-key rejection, preview output, signaling and UI lifecycle; physical camera/two-machine rendering remains to validate.
* [PostIt/API] Begin Android/Linux call integration on the existing authenticated ChatHub: typed invitation, single-device consent, bounded SDP/ICE exchange and hangup; derive relay policy from account preferences and issue temporary coturn credentials. Attach the shared PostIt signaling client to the chat connection, end calls on disconnect/room departure/privacy activation, and add targeted regression tests. Calls remain disabled by default; native media adapters and Android/Linux end-to-end validation are not implemented yet.
* [PostIt] Clarify reuse of the existing ChatHub for call signaling and document the inconclusive Android native WebRTC experiment; discard the isolated laboratory without changing production chat or media behavior.
* [PostIt/API] Persist the account-level `HideIpAddressInCalls` preference (default false), expose it through the authenticated profile API and PostIt profile editor, and preserve it when older clients omit it. Prepare future TURN-only calls without enabling media transport yet.
* [PostIt] Show a local live capture preview on Android and Desktop without opening a second camera or reading back uploaded segments. Share Android's oriented EGL frames with an aspect-preserving preview surface; duplicate Desktop LibVLC output without local microphone playback.
* [Podcasts] Prepare authenticated, seekable MP4 replays for new and existing Completed broadcasts using server-side FFmpeg stream copy and faststart. Retain MPEG-TS, account for both copies in the owner quota, recover preparation after restarts, and expose owner-only retries plus GET/HEAD byte-range playback.
* [PostIt] Add Android/Desktop native video overlays for MP4 replay position, duration, seeking and play/pause, with three-second auto-hide. Use bounded authenticated range input with token refresh; preserve MPEG-TS live/interrupted playback.
## [1.0.8-rc33] - unstable
### Added

View file

@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="DotMarkdown" Version="0.3.0" />
<PackageVersion Include="xFFmpeg.NET" Version="7.4.0" />
<PackageVersion Include="Markdig" Version="1.4.1" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="10.0.13" />
<PackageVersion Include="HigginsSoft.IdentityServer8" Version="$(IdentityServer8Version)" />

View file

@ -93,6 +93,7 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
ENTRYPOINT ["dotnet", "Yavsc.Org.dll"]
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS api-runtime
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg && apt-get clean
WORKDIR /app
COPY --from=publish-api /publish/ ./
RUN --mount=type=secret,id=yavsc_appsettings,dst=/run/secrets/yavsc_appsettings \

View file

@ -28,6 +28,61 @@ dotnet publish -c Release
and then, install the app, from the `src/PostIt/PostIt.Android/bin/Release/net10.0/PostIt.apk`
## PostIt native WebRTC calls (Android and Linux)
Calls are opt-in on the HTTPS chat host. Configure `AudioVideoCalls` there:
```json
{
"AudioVideoCalls": {
"Enabled": true,
"EnableLanCalls": false,
"StunUrls": ["stun:turn.example.org:3478"],
"TurnUrls": [
"turn:turn.example.org:3478?transport=udp",
"turn:turn.example.org:3478?transport=tcp",
"turns:turn.example.org:5349?transport=tcp"
]
}
}
```
Set `AudioVideoCalls__TurnSharedSecret` through the host's protected environment
or secret store, **not** in a committed settings file or in PostIt. Generate
a strong random secret (for example `openssl rand -hex 32`), install coturn and
adapt [coturn.conf.example](contrib/coturn.conf.example) outside the repository.
Set its `static-auth-secret` to the same value. The server issues separate,
short-lived REST/HMAC credentials only after invitation acceptance; clients
never receive the shared secret. Keep clocks synchronized.
Expose TURN on UDP/TCP 3478, TLS/TCP 5349, and the configured **UDP relay range**
(49160–49200 in the example). Use a publicly trusted certificate matching the
TURN hostname and ensure coturn can read its key. TURN is not an HTTP reverse
proxy route. If behind NAT, configure coturn's `external-ip=PUBLIC/PRIVATE`,
`listening-ip` and `relay-ip` for the actual deployment and forward the relay
range without changing port numbers. Restrict relay access to private services,
set bandwidth/capacity limits appropriate to the host, and avoid logging SDP,
credentials or candidates. Do not copy the loopback permissions used by tests.
Android 8+ bundles native libwebrtc from the official Maven AAR. Linux needs
Python 3 GI and GStreamer with `webrtcbin`, libnice, VP8, Opus, JPEG, V4L2 and
PulseAudio/PipeWire support. On Debian/Ubuntu:
```bash
sudo apt install python3-gi python3-gst-1.0 gir1.2-gst-plugins-bad-1.0 \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-nice gstreamer1.0-pulseaudio
```
Join the same chat room, refresh/select camera and microphone, invite a peer,
then accept on the other client. Capture starts only after acceptance.
The profile's IP-masking setting forces **both participants** through TURN;
missing/unreachable TURN fails the call, never falls back to direct media.
Without masking, explicit IP-disclosure consent is required.
TURN still sees each client's address, and masking does not hide addresses
from the signaling host or local network. See the
[architecture and native regression commands](doc/architecture/audio-video-calls.md).
## PostIt.Desktop on Windows (per-user installer)
@ -76,13 +131,364 @@ login callback, updating and uninstallation on Windows with a standard
(non-administrator) account. Installer compilation alone does not validate
these Windows runtime behaviours.
## Resource consumption and CGU
### Account withdrawal and payment retention
Apply the `AccountWithdrawal` migration before deploying all three hosts. It adds
withdrawal timestamps and replaces the immutable alternate email key with a
required unique email index, preserving uniqueness while allowing pseudonymization.
Do not run the withdrawal flow until every host uses the matching backend.
Yavsc.Org must have write/delete access to the same managed volumes as API/Blogs:
`Site:UserFilesRoot`, `Site:Avatars` and `Podcast:RootPath`.
Use absolute paths shared across processes; defaults relative to application
directories are not shared automatically. Accounting files under `Site:Bills`
are not erased by withdrawal. Symbolic links in managed user directories are
refused rather than followed.
The account is blocked before cancellation/erasure, and withdrawal is only
confirmed when these operations and pseudonymization succeed. On an explicit
failure, an administrator must fix the cause and retry the existing administrative
withdrawal action. Ensure no live upload/encoding operation is still writing to
the user's volumes during withdrawal; drain such operations before retrying.
The Org hosted worker purges eligible technical payment records at startup and
checks at most every minute, with an earlier wake-up for a known anniversary.
Monitor errors and service availability: scheduled processing
cannot ensure an exact wall-clock deletion while the host is stopped. At least
one Org instance must run, and an external operations process must enforce the
one-year retention deadline during prolonged downtime. PostIt administrators can
also confirm and run `POST /api/v1/administration/payment-residues/purge`.
The report counts accounts, subscriptions, monthly payments, donations and legacy
PayPal payments. Active accounts and unfinished withdrawals are never purged.
No new subscription credits may be granted after withdrawal begins.
Invoice payments, invoices and other legal accounting records are excluded.
Define and publish the actual accounting, logs and backup retention policy for
the deployment, verify configured providers and international-transfer safeguards,
and prevent withdrawn data from being reactivated by backup restoration.
Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and
Yavsc.Org. API and Blogs must also use the same application database.
All three hosts and configuration templates inherit the backend defaults
from [ResourceUsageOptions](src/Yavsc.Server/Settings/ResourceUsageOptions.cs).
Deploy matching backend versions across hosts. The public CGU renders the
effective coefficients and limit. The default limit is 1,000 points.
The following is an example explicit override, not a duplicate of defaults.
Use the account's immutable user ID (`sub`), not its login, for overrides:
```json
{
"ResourceUsage": {
"ApiCallWeight": 0.2,
"CpuSecondWeight": 0.1,
"BandwidthMbWeight": 0.05,
"StorageMbWeight": 0.5,
"DefaultLimit": 1000,
"UserLimits": {
"example-account-id": 20000
}
}
}
```
Environment variables follow ASP.NET's convention, for example
`ResourceUsage__DefaultLimit` and
`ResourceUsage__UserLimits__example-account-id`. Restart all three services
after changing the rule. Invalid weights or limits fail startup.
Existing cumulative `ResourceUsageRecords` are reused, and changing weights
recalculates their gross indicator. Apply the `ResourceSubscriptions`
migration before deploying any of the three hosts: it adds the credit
balance and subscription/payment tables without clearing existing counters.
Consumption is in **points**, independent of `EstimatedCompensation` and
currency. Counters have no automatic reset. Storage means cumulative
instrumented writes less individually tracked bytes removed or replaced,
not total filesystem occupancy. Replacements refund their tracked previous
size and charge the new size. Legacy files without an individual receipt
receive no refund; storage counters never become negative. Deletion remains
available at the consumption limit, but API/transfer/CPU costs are not refunded.
Apply the `RefundableResourceStorage` migration before deployment; its empty
receipt table deliberately does not infer provenance from historical counters.
Renames preserve receipts and repeated PDF generation replaces the previous
tracked volume rather than charging the whole file again. The historical CPU counter is
instrumented elapsed processing time, not exhaustive CPU profiling.
Authenticated HTTP operations are admitted atomically against known costs
(API call and declared request body). Personal-file uploads additionally
check their aggregate storage cost before writing. Response bytes and
unknown-length request bodies are measured through counting streams, and
remaining costs are recorded after execution, including failed requests.
PostgreSQL transaction-scoped advisory locks serialize admission and
accounting for each user across hosts. In-flight operations can exceed the
limit through costs unknown at admission; subsequent operations return
HTTP 429 with `resource_quota_exceeded` Problem Details. No permanent account
suspension or strict running-operation interruption is performed.
`GET /api/v1/resource-usage/me` returns `Consumption`, `ConsumptionLimit`,
`RemainingConsumption` and `IsQuotaReached`, alongside existing counters.
It also returns `GrossConsumption`, `AppliedCredits` and `CreditBalance`.
`Consumption` is the gross indicator less acquired credits, floored at zero.
`RemainingConsumption` includes both unused free quota and carried credit.
Usage consultation (including the role-protected admin overview), login,
session refresh and the CGU remain accessible without consuming quota.
The quota does not measure local PostIt resources, direct peer calls or
WebSocket traffic. HTTP upload size limits and disk quotas still apply.
The public page `/Home/CGU` describes the effective rule and default limit
(and the individual limit for a signed-in user). It is linked from the Web
footer and PostIt's **About** page, using the configured authentication
authority. PostIt displays consumption and remaining points in **My profile**
and the administration usage views.
PostIt **Administration > Effacer des points de consommation** lets an
`Administrator` select an account whose consumption limit is reached, enter
a positive amount (up to eight decimal places), preview the remaining
consumption and explicitly confirm. An amount exceeding current consumption
is rejected: this action grants neither future credit nor additional disk
space, and preserves the technical counters and payment history.
`POST /api/v1/resource-usage/admin/{userId}/erase` accepts `points` and
`expectedCredits` (the displayed `AppliedCredits + CreditBalance`). The
Administrator-only endpoint is quota-exempt, rechecks eligibility under the
shared accounting lock and rejects stale credit snapshots with HTTP 409.
Refresh and confirm again after a conflict or uncertain request outcome.
Successful adjustments record the administrator as the modifying actor and
log the target, amount and remaining consumption. No new migration is needed
beyond the existing resource-subscription credit column.
### Monthly resource subscriptions (PayPal REST)
The free registration keeps the configured cumulative quota without a
monthly reset. Discovery costs EUR 1 excluding VAT (EUR 1.20 including 20%
VAT) per month; Premium costs EUR 2 excluding VAT (EUR 2.40 including VAT).
Every **confirmed payment** grants up to one / three default quotas,
respectively, with renewal on the UTC monthly anniversary of the PayPal
start date. The pack allowance is captured at subscription creation, not
multiplied by an individual user's quota override.
At reconciliation, old carried credit is used first; the new allowance
erases remaining net usage. Two thirds of the unused allowance are added
to permanent carried credit, rounded down to eight decimal places.
Old carried credit never loses another third and survives cancellation.
Example: 400 points of usage and 1,000 new points erase 400 and carry
400; an idle Premium month carries 2,000 points.
Counters are never deleted. Pending/failed payments give no credit.
Refunds (including partial refunds) revoke the corresponding award once.
Discovery grants **twice `Constants.DefaultFSQ`** (1,000 MiB), and Premium
**five times `Constants.DefaultFSQ`** (2,500 MiB) of disk space during each
confirmed, non-reversed paid monthly period. Free registrations use the standard quota.
The reference is the standard free quota (500 MiB), not an individual's
administratively adjusted `DiskQuota`. That base quota is never overwritten.
New user objects now use the existing 500 MiB database default rather than
the former 512 MiB CLR initializer; existing accounts retain their stored quota.
Cancellation retains the disk allowance through the UTC anniversary ending
the paid period; expiry or refund restores the base quota without deleting
existing files. Uploads exceeding available space are refused before writing.
The maximum size of one file and separate podcast limits are unchanged.
Pending/failed payments grant no disk bonus. Apply the
`ResourceSubscriptions`, `PremiumDiskQuota` and `DiscoveryDiskQuota` EF migrations to the shared
database before deploying any host. Profile and usage responses expose the
effective disk quota; usage also exposes `PremiumDiskQuotaUntil` and `DiscoveryDiskQuotaUntil`.
When paid periods overlap, Premium takes precedence until its expiry, then
any still-paid Discovery period applies.
Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need
the migrated shared database and matching resource weights, not PayPal
credentials. Existing Classic donation settings remain unchanged.
PostIt's **Mon abonnement PayPal** page (Home, profile or About) loads offers
and creates/resumes checkout through `api/v1/resource-subscriptions` on the
configured OIDC **authority**, not the business API host. These routes require
the current bearer token, reject cookie-only requests, and remain accessible
at the resource-consumption limit. Prices, VAT, monthly points and plan IDs
are controlled by the server; no PayPal credentials are shipped to PostIt.
Only approval opens in the browser. The anonymous `/api/v1/resource-subscriptions/return`
landing page asks the user to return to PostIt and press **Actualiser**:
it does not reconcile or grant credit, and requires no second web login.
The authenticated `POST refresh` reconciles verified PayPal transactions;
`POST {id}/cancel` cancels only the caller's subscription. Existing web
checkout and verified webhooks remain supported. Deploy Yavsc.Org with the
new routes before distributing the updated client. Example requests are in
[`resource-subscriptions.http`](src/Yavsc.Org/resource-subscriptions.http).
Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret`
REST settings; keep credentials in user-secrets or environment variables.
```json
{
"ResourceSubscriptions": {
"DiscoveryPlanId": "P-REPLACEWITHDISCOVERYPLAN",
"PremiumPlanId": "P-REPLACEWITHPREMIUMPLAN",
"WebhookId": "REPLACEWITHWEBHOOKID",
"DiscoveryPriceExcludingTax": 1,
"PremiumPriceExcludingTax": 2,
"VatPercent": 20
}
}
```
Before enabling checkout, create a PayPal subscription product and two
**ACTIVE** billing plans in the same REST app and environment:
one indefinite `REGULAR` cycle with `interval_unit: MONTH`,
`interval_count: 1`, `total_cycles: 0`, and EUR `fixed_price.value`
of **1.20** / **2.40** respectively. These are **already VAT-inclusive**
amounts: do not add PayPal tax, setup fees, trials, quantity support or
shipping fees. Disable billing outstanding balances in the plans
(`auto_bill_outstanding: false`) to avoid bundling missed installments
into an amount that does not match one monthly payment.
Checkout checks the configured plan against its expected TTC amount and
refuses automatic collection of outstanding balances.
Numerically invalid pricing fails startup; missing plan IDs/webhook/
credentials returns an explicit unavailable error instead of a fake success.
Register the HTTPS endpoint
`https://<Yavsc.Org host>/ResourceSubscription/Notify` in that REST app.
Subscribe to `BILLING.SUBSCRIPTION.ACTIVATED`, `UPDATED`, `CANCELLED`,
`SUSPENDED`, `EXPIRED`, `PAYMENT.FAILED`, and `PAYMENT.SALE.COMPLETED`,
`REFUNDED`, `REVERSED` (the lifecycle events use the
`BILLING.SUBSCRIPTION.` prefix). Set the returned webhook ID in configuration.
The server verifies the signature through PayPal, then fetches the bound
subscription and transaction history; it never grants credit from an
unverified webhook or the browser return. Payment IDs and monthly cycles
are unique, and the same per-user PostgreSQL lock serializes usage and awards.
Delayed notifications take effect on the usage measured when reconciled.
Users manage subscriptions at `/ResourceSubscription`, linked from the Web
footer and PostIt's About/profile pages. A browser Web login may be required
independently of PostIt's session. Create/refresh/cancel require antiforgery
tokens and ownership; the management page remains available at the quota.
**Refresh payments** reconciles missed notifications and historical refunds.
Cancellation is confirmed with PayPal, not merely recorded locally.
Only one non-terminal subscription is allowed per account.
An uncertain creation is retried with its same PayPal request ID for at
most 24 hours; an older unresolved creation requires merchant-side review
before allowing a second checkout. Do not delete that record and retry
without checking PayPal for a possible existing agreement.
Run a real Sandbox approval, first payment, renewal, repeated webhook,
refund and cancellation before enabling production. The repository tests
use synthetic PayPal transports and do not validate merchant credentials
or PayPal account eligibility.
## Podcast live broadcasts and replays
### OBS Studio for planned emissions
OBS publishes **encrypted SRT directly to Yavsc.Api**, using
[FFmpeg.NET](https://github.com/cmxl/FFmpeg.NET) (`xFFmpeg.NET`) to manage FFmpeg
listeners. No MediaMTX, external media server, authentication callback or RTMPS
certificate is required. Install **FFmpeg with libsrt, H.264/AAC and MPEG-TS
support** on the **single Yavsc.Api media host** (`ffmpeg -h protocol=srt`).
OBS supports SRT in its Custom streaming service; see its
[SRT streaming guide](https://obsproject.com/kb/srt-protocol-streaming-guide).
This replaces the previous RTMP/RTMPS transport, not the authenticated playback API.
Apply the `PodcastObsIngestion` migration on the shared database. Configure
`Podcast:Obs` on **Yavsc.Api only**, for example:
```json
{
"Podcast": {
"Obs": {
"Enabled": true,
"ServerUrl": "srt://obs.example.org",
"ListenAddress": "0.0.0.0",
"FirstPort": 10000,
"PortCount": 16,
"ActivationMinutes": 30,
"MaxDurationMinutes": 120,
"MaxConcurrentBroadcasts": 2
}
}
}
```
`ServerUrl` contains the public SRT host only, with no port, path, secret or query.
`ListenAddress` is a literal local IP address (IPv4 or IPv6); configure a matching
public address family. Open/forward **UDP 10000-10015** in this example.
An ordinary HTTP reverse proxy does not carry SRT. NAT forwarding must preserve
the advertised port numbers.
One FFmpeg process and UDP port are reserved per armed emission, even before OBS
connects. Armed and running emissions share `MaxConcurrentBroadcasts`; an exhausted
pool returns HTTP 503. The port range is bounded (at most 128 ports) and must be
large enough for the concurrency limit. Listener startup failure is reported,
not treated as successful activation.
Keep process arguments and credentials accessible only to the service administrator.
Limit ingress bitrate at the network level and in OBS: application quotas are checked
on completed media segments, not on every incoming packet.
In PostIt:
1. Prepare an emission and select it.
2. Choose **Activer OBS / renouveler la cle**.
3. In OBS, select **Parametres > Stream > Service : Personnalise**, then copy
the complete displayed **secret SRT URL as Server**, leaving **Stream Key empty**.
The URL includes caller mode, a random passphrase and enforced AES-256 encryption.
Use **H.264 video**, **AAC audio**,
a **2-second keyframe interval** and a bitrate producing segments below 8 MiB.
4. Start streaming in OBS before the activation expires. The actual emission
starts when the first complete media segment arrives, even if the scheduled date is later.
No camera capture in PostIt is required; PostIt may be closed afterwards.
5. Stop OBS or choose **Revoquer OBS et arreter le diffuseur** in PostIt.
Committed segments remain available and the normal MP4 worker prepares replay.
Passphrases are scoped to one emission, displayed once and rotated on activation.
Only a SHA-256 hash and lifecycle metadata are stored in the database; FFmpeg needs
the actual passphrase in memory/process arguments for SRT encryption. It is never
included in status responses or persisted in PostIt. Navigation/logout clears
the displayed secret URL but does not revoke a running
external emission. Revocation is available at the consumption limit.
After disconnect, restart or timeout, the emission ends rather than silently
resuming under a new publisher: prepare a new emission for another broadcast.
An API restart invalidates all old activations; an unstarted emission must be
activated again because its passphrase is not recoverable from the database.
An invalid handshake can end an armed listener; no podcast is created without
media, and the owner can activate again. Rate-limit connection attempts at deployment.
The worker manages bounded FFmpeg.NET listener/remuxing tasks. It rejects ended,
deleted, revoked or withdrawn accounts and caps
concurrent captures and duration (the lower of planned duration and configured
maximum). Revocation cancels the corresponding FFmpeg process and frees its port.
Activation expiry stops unused listeners. The passphrase is required before SRT
media can be received; a stream name alone is not an authentication mechanism.
Committed segments are charged as transferred and stored MiB under the same
consumption rule; their storage receipts are refunded on podcast deletion.
OBS storage counts towards the user's effective disk quota and the existing
podcast media limits. Pending capture files are monitored and bounded; enforcement
can overshoot by one polling interval of incoming data. Processing errors are
reported in the owner-only OBS status endpoint, without exposing secret URLs or
FFmpeg diagnostics. Monitor process/cleanup failures and drain active captures
before maintenance. An API outage ends ingestion and requires reactivation.
The normal HTTP API authenticates playback; OBS stream credentials never grant
viewer or account access.
For the real media regressions, install FFmpeg with libsrt and run:
```bash
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj --filter-class '*PodcastObsTests'
```
The tests launch loopback-only listeners, generate synthetic H.264/AAC media
with FFmpeg, verify encrypted SRT through FFmpeg.NET, wrong-passphrase rejection,
revocation during streaming,
AAC audio, HLS segments, MP4 replay and refund,
then stops its own processes and removes its temporary files.
PostIt Desktop's home page provides **Podcasts : directs et replays**.
Install LibVLC 3 with the `livehttp`, MPEG-TS, x264 and AAC plugins on the
Desktop machine. Windows capture uses DirectShow; Linux uses V4L2 and the
default PulseAudio microphone. FFmpeg is **not** a runtime dependency.
default PulseAudio microphone. FFmpeg is **not** a client dependency.
Select a camera and optionally a microphone, enter a title, then start.
An **Apercu local de la capture** appears at the top of the Podcasts page on
Android and Desktop. It uses the current capture, not a second camera session
or the server replay. Android displays the same oriented frames as the encoder,
with black bars to preserve proportions; Desktop duplicates LibVLC's video
output. Local microphone playback is disabled to avoid acoustic feedback.
Stopping releases the preview; hiding/recreating the Android preview surface
does not restart the encoder or change its timestamps.
Stopping publishes the retained replay; navigating away or logging out
stops capture too. A second signed-in PostIt instance can watch the live
broadcast while it is being captured.
@ -93,7 +499,12 @@ replays; only the broadcaster can upload, complete or delete their podcast.
Media is not anonymous and no access token is included in a playback URL.
Configure Yavsc.Api's `Podcast` section (or environment variables such as
`Podcast__RootPath`). No database migration or server-side encoder is needed:
`Podcast__RootPath`). The base media store needs no database migration;
planned emissions and OBS require their migrations documented above. Install **FFmpeg 5+
on the API server** (with `concatf`, MPEG-TS, MP4 and AAC bitstream-filter
support; for Debian/Ubuntu: `apt-get install ffmpeg`). The API runtime stage
in the main Dockerfile includes it. Only stream-copy remuxing is performed,
not video/audio re-encoding:
```json
{
@ -103,7 +514,9 @@ Configure Yavsc.Api's `Podcast` section (or environment variables such as
"MaxOwnerBytes": 1073741824,
"MaxSegments": 7200,
"MaxOwnerPodcasts": 100,
"IdleTimeoutSeconds": 60
"IdleTimeoutSeconds": 60,
"FfmpegPath": "ffmpeg",
"ReplayTimeoutSeconds": 600
}
}
```
@ -118,9 +531,15 @@ Defaults allow 8 MiB per segment (also the HTTP endpoint's hard limit),
1 GiB retained per owner, 7,200 segments per episode and 100 episodes per
owner. At the target two-second segment duration, this is roughly four hours
per episode; the byte quota can be reached earlier. Podcast quotas are
separate from the legacy user-files `DiskQuota`. Deleting an ended podcast
separate from the legacy user-files `DiskQuota` for native HTTP capture.
OBS source segments also count towards the user's effective disk quota and
instrumented consumption; the additional MP4 is counted only by `MaxOwnerBytes`.
Deleting an ended podcast
releases its podcast quota. Reverse proxies must allow an 8 MiB PUT body
and forward Authorization on every API request.
and forward Authorization, Range and Content-Range on every API request/response.
The retained MPEG-TS **and** the additional MP4 count toward `MaxOwnerBytes`.
Allow enough free quota and disk space for both copies and the temporary MP4;
deletion removes all copies.
A broadcast without a new committed segment for 60 seconds, or present
when the API restarts, becomes an interrupted replay on the next catalogue,
@ -134,9 +553,26 @@ for manual recovery. There is no automatic resumption after an application
restart; these private local recordings may be removed manually when no
longer needed.
The replay is **HLS/MPEG-TS**, not an MP4 download. PostIt's authenticated
player joins a live broadcast up to three segments behind the edge and
reads a replay from its beginning; seeking is not implemented. Native
On completion, the API queues a private, seekable **MP4** (`-c copy`,
`+faststart`). The persisted `replay.state` moves through `Pending`,
`Processing`, `Ready` or `Failed`; completion itself does not wait for FFmpeg.
The single API worker also queues older Completed indexes automatically,
recovers interrupted preparation after a restart, and scans every five seconds.
Interrupted broadcasts keep MPEG-TS playback unless the owner explicitly
completes them. Source segments and existing HLS routes remain available.
Preparation failure keeps all source media and reports an error; after checking
server logs, FFmpeg installation, timeout and quota, the owner can use PostIt's
**Relancer la preparation MP4** action, or `POST /api/v1/podcasts/{id}/replay/retry`.
The MP4 is exposed only when ready, at authenticated
`GET /api/v1/podcasts/{id}/replay.mp4` (also HEAD; byte ranges supported).
PostIt's Android and Desktop player waits for MP4 preparation, then fetches
bounded authenticated ranges with token refresh rather than giving LibVLC
a bearer URL. Replay controls overlay the native video: play/pause, position,
duration and draggable seek bar. They hide after three seconds without
interaction while playing, stay visible during seeking/pause/keyboard focus,
and reappear on pointer movement or touch.
The live player still joins up to three segments behind the edge. Native
camera/microphone permissions, drivers and codecs must still be verified
on each target Windows/Linux machine.
@ -147,6 +583,16 @@ the same Avalonia video page as desktop. Catalogue, playback controls and
authenticated segment downloads are shared; no external browser, public media
URL or camera/microphone permissions are needed to watch a podcast.
Video playback keeps the screen awake while PostIt is visible. Pausing,
stopping, reaching the end, a playback error or leaving the video releases
this request; backgrounding the app always allows the screen to sleep.
The podcast page offers **Garder l'ecran allume pendant l'apercu camera et le
direct** on Android. This preference is saved and disabled by default. It
only keeps the screen awake during an active camera preview or broadcast
while PostIt is visible, and can be changed during capture. Turning it off
does not stop capture or alter the existing background broadcast service.
Leaving the app stops playback and cancels downloads. Returning recreates the
player: a replay starts from the beginning, and a live stream rejoins near the
live edge. Seeking and background audio are not supported.
@ -166,6 +612,22 @@ at IDR frames, with timestamps used for segment durations. Closed segments
enter the same ordered upload/retry/quota/replay pipeline as desktop.
Devices without a supported camera/encoder report a startup error.
On Android, the optional **Flouter le decor de la camera** setting is saved
locally and disabled by default. It applies to podcast camera preview and
recording, not calls or OBS. The bundled Apache-2.0 PPHumanSeg model from
[OpenCV Zoo](https://github.com/opencv/opencv_zoo/tree/main/models/human_segmentation_pphumanseg)
is evaluated locally with ONNX Runtime; OpenGL blends the blurred background
before the native encoder. No frames are sent to a third party. Segmentation
is imperfect and can expose parts of the background: check the preview and do
not rely on it to conceal sensitive surroundings. Performance and battery
usage depend on the device. Capture stops on processing failure.
The bundled `pphumanseg.onnx` is the OpenCV Zoo 2023mar model (SHA-256
`552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24`);
its Apache-2.0 license is included beside the asset.
ONNX Runtime's Android library requires API 24; it is only loaded by the
podcast capture code, which is restricted to API 26 and later. The manifest
override preserves PostIt's existing API 23 minimum for its other features.
Camera frames are rotated through an OpenGL surface before encoding, so both
live playback and replays have upright pixels without relying on rotation
metadata (not supported by the MPEG-TS recorder). The sensor, front/rear lens
@ -262,6 +724,6 @@ You'll need to send e-mail ... using smtp and the provider of your choice, see t
### Google
I'll have to make with it, a least a moment, it needs a *service account*, and some setup,
in the `appsettings.*.json` file, and
I'll have to make with it, a least a moment, it needs a *service account*, and some setup,
in the `appsettings.*.json` file, and
the execution environment variable GOOGLE_APPLICATION_CREDENTIALS to a value pointing the json description file for the Google Service account.

View file

@ -4,6 +4,7 @@ FRAMEWORK=net9.0
DESTDIR=/tmp/yavsc
APP_PATH=srv/www/yavsc
APP_FULL_PATH=$(DESTDIR)/$(APP_PATH)
UNITTESTEXTRA= --long-running 8 --filter-trait Category=non-reg --filter-not-trait Speed=Slow --filter-not-trait DependsOn=Native
all:
dotnet build --nologo
@ -19,29 +20,36 @@ src/Yavsc/bin/output/wwwroot:
dotnet --project src/Yavsc.Org/Yavsc.Org.csproj publish
test:
ASPNETCORE_ENVIRONMENT=Development dotnet test --report-xunit \
--report-xunit-html \
--results-directory "test-reports"
ASPNETCORE_ENVIRONMENT=Development \
TESTINGPLATFORM_EXITCODE_IGNORE="110" \
dotnet test yavsc.sln \
-- --report-xunit \
--report-xunit-html \
--results-directory "test-reports" \
$(UNITTESTEXTRA) || EXITCODE=$$? && echo "🗱💻 Tests failed, exited with code $$EXITCODE";
test-postit:
ASPNETCORE_ENVIRONMENT=Development dotnet test \
--report-xunit \
--report-xunit-html \
--results-directory "test-reports" \
--report-xunit-html-filename "postit-test-results.html" \
--project src/PostIt/PostIt.Tests/PostIt.Tests.csproj
ASPNETCORE_ENVIRONMENT=Development \
TESTINGPLATFORM_EXITCODE_IGNORE="110" \
dotnet test \
src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
-- --report-xunit \
--report-xunit-html \
--results-directory "test-reports" \
--report-xunit-html-filename "postit-test-results.html" \
$(UNITTESTEXTRA) || EXITCODE=$$? && echo "🗱📱 Tests failed, exited with code $$EXITCODE";
backend-tests: Blogs-backend-test Org-backend-test Api-backend-test
Api-backend-test:
Blogs-backend-test:
Org-backend-test:
%-backend-test:
ASPNETCORE_ENVIRONMENT=Development dotnet test \
ASPNETCORE_ENVIRONMENT=Development dotnet test
src/test/Yavsc.$*.Tests/Yavsc.$*.Tests.csproj \
--report-xunit \
--report-xunit-html \
--results-directory "test-reports" \
--report-xunit-html-filename "$*-backend-test-results.html" \
--project src/test/Yavsc.$*.Tests/Yavsc.$*.Tests.csproj
--report-xunit-html-filename "$*-backend-test-results.html"
watch:
dotnet watch -p:Configuration=$(CONFIG) --project src/Yavsc/Yavsc.csproj

View file

@ -38,7 +38,8 @@ Pour une prise en main guidee avec agents IA:
## Construction
```bash
dotnet build
sudo dotnet workload restore
dotnet build
```
et, pour execution en environment de développement

View file

@ -0,0 +1,32 @@
# Copy outside the repository; replace the realm, secret and certificate paths.
# Use the same randomly generated secret in AudioVideoCalls:TurnSharedSecret.
realm=turn.example.org
fingerprint
use-auth-secret
static-auth-secret=REPLACE_WITH_A_RANDOM_SERVER_ONLY_SECRET
listening-port=3478
tls-listening-port=5349
cert=/etc/letsencrypt/live/turn.example.org/fullchain.pem
pkey=/etc/letsencrypt/live/turn.example.org/privkey.pem
min-port=49160
max-port=49200
no-cli
no-multicast-peers
no-tcp-relay
user-quota=4
total-quota=512
stale-nonce=600
# Do not allow the relay to reach private infrastructure or loopback services.
denied-peer-ip=0.0.0.0-0.255.255.255
denied-peer-ip=10.0.0.0-10.255.255.255
denied-peer-ip=100.64.0.0-100.127.255.255
denied-peer-ip=127.0.0.0-127.255.255.255
denied-peer-ip=169.254.0.0-169.254.255.255
denied-peer-ip=172.16.0.0-172.31.255.255
denied-peer-ip=192.168.0.0-192.168.255.255
denied-peer-ip=224.0.0.0-255.255.255.255
denied-peer-ip=::
denied-peer-ip=::1
denied-peer-ip=fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
denied-peer-ip=fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff

View file

@ -1,4 +1,7 @@
{
"ResourceUsage": {
"UserLimits": {}
},
"Site": {
"Authority": "https://preprod-yavsc.$DOMAIN",
"Audience": ["api"],

View file

@ -1,4 +1,7 @@
{
"ResourceUsage": {
"UserLimits": {}
},
"Site": {
"Title": "Yavsc Blogs",
"Description": "A collection of blogs about software development, technology, and programming.",

View file

@ -1,4 +1,15 @@
{
"ResourceSubscriptions": {
"DiscoveryPlanId": "",
"PremiumPlanId": "",
"WebhookId": "",
"DiscoveryPriceExcludingTax": 1,
"PremiumPriceExcludingTax": 2,
"VatPercent": 20
},
"ResourceUsage": {
"UserLimits": {}
},
"Logging": {
"LogLevel": {
"Default": "Information"
@ -18,7 +29,8 @@
"ApiUrl": "https://preprod-api.$DOMAIN",
"CorsAllowedOrigins": [
"https://preprod-blogs.$DOMAIN",
"https://preprod-api.$DOMAIN"
"https://preprod-api.$DOMAIN",
"https://postit.$DOMAIN"
],
"Banner": "/images/banner-dewang.jpg",
"Owner": {

View file

@ -23,6 +23,7 @@ Chaque sujet est détaillé dans sa propre page (sous
| Dictionnaires métier (héritage en arbre) | [dictionnaires-metier.md](architecture/dictionnaires-metier.md) |
| Offre fournisseur + frontmatter (`ClasseFormulaire`, `ClasseDevis`, parsing) | [offres-frontmatter.md](architecture/offres-frontmatter.md) |
| PostIt / OIDC (client desktop, custom URI scheme, silent refresh) | [postit-oidc.md](architecture/postit-oidc.md) |
| Notifications Web/PostIt, ChatHub et service Android SignalR | [notifications.md](architecture/notifications.md) |
## Stack technique
@ -57,6 +58,147 @@ sudo adduser --ingroup yavsc --add-extra-groups www-data \
--disabled-password --system yavsc
```
## Catalogue Web de podcasts
`/Podcast` (vue `src/Yavsc.Org/Views/Podcast/Index.cshtml`) exige une
session Identity Yavsc.Org, y compris pour chaque requête de lecture.
Yavsc.Org interroge Yavsc.Api côté serveur ; aucun jeton n'est transmis
au navigateur et aucun second catalogue de stockage n'est créé.
Les replays MP4 prêts prennent en charge GET, HEAD et les plages
d'octets. Les directs et replays non encore convertis utilisent HLS
natif ou hls.js (servi localement, installé par `npm install` et copié par
`npm run build:podcasts`, également inclus dans la copie d'assets de
`npm run build:js`). Sans support vidéo compatible, la page affiche un
avertissement et invite à utiliser PostIt. Cette page ne crée ni ne
supprime de podcast.
Depuis le lecteur PostIt, « Ouvrir dans le navigateur » ouvre `/Podcast`
sur l'hôte `Authentication.Authority`, pas la playlist API authentifiée.
La session Web reste distincte de celle de PostIt : le navigateur peut
donc demander une connexion.
Il n'y a pas de section de configuration `PodcastWeb`, ni de client OAuth
technique à enregistrer. L'adresse API est celle de `Site:ApiUrl`, en HTTPS
(avec ou sans suffixe `/api/v1`). Yavsc.Org est l'autorité : comme pour
l'envoi d'avatar, `IdentityServerTools.IssueJwtAsync` utilise sa signature
existante pour émettre un jeton de cinq minutes au nom de l'utilisateur
connecté (`sub`, audience `api`, scope `api` attendu par Yavsc.Api).
Ce jeton reste côté serveur. Une adresse API manquante renvoie 503 ;
une panne de l'API renvoie une erreur explicite, pas un catalogue vide.
### Emissions preparees
PostIt memorise dans ses parametres utilisateur les cameras et microphones
detectes, leurs identifiants selectionnes et le titre par defaut. La page
les restaure sans redetection automatique ; le bouton de detection actualise
le materiel disponible en conservant les choix encore presents. Le choix
« sans microphone » est memorise lui aussi. Charger le titre d'une emission
preparee ne remplace pas le titre par defaut ; une saisie explicite le modifie.
Les erreurs de sauvegarde sont affichees dans la page.
Les appels des salons de discussion reutilisent ces memes choix camera/micro
et enregistrent leurs changements dans les memes parametres. La page Podcasts
les recharge a son activation. Les appels exigent toujours un microphone :
le choix podcast « sans microphone » laisse donc le micro d'appel non selectionne.
L'adresse LAN/VPN choisie pour les appels est aussi memorisee, mais restauree
uniquement si elle est encore presente sur une interface locale active.
Sinon, une nouvelle selection est requise. Le consentement au partage
d'adresse avec le pair n'est jamais memorise.
PostIt permet de preparer, modifier et supprimer une emission avant son
demarrage : titre, date/heure locale, duree entiere positive en minutes et
annonce publique optionnelle. Les horaires sont previsionnels : la camera,
le demarrage et l'arret restent manuels. Les heures locales inexistantes ou
ambigues au changement d'heure sont refusees.
La table existante `LiveFlow` conserve la preparation et son proprietaire ;
`PodcastId` (GUID unique) relie cette emission au manifeste media sur disque.
`PodcastResponse` reste un DTO, enrichi de `FlowId`, `ScheduledStartAt`,
`PlannedDurationMinutes` et `PublicAnnouncement`. Un etat `Planned`
precede le direct ; la date previsionnelle n'est jamais confondue avec
`CreatedAt` du direct ni la duree previsionnelle avec les secondes enregistrees.
Les anciens manifestes sans `LiveFlow` restent lisibles ; aucune copie ou
migration de leurs medias n'est requise. Le demarrage immediat historique
reste disponible sans preparation.
L'API propose `POST /api/v1/podcasts/planned`,
`PUT /api/v1/podcasts/{id}/planned` et `POST /api/v1/podcasts/{id}/start`.
La preparation n'est visible que du proprietaire, meme avec une annonce ;
les nouvelles routes de mutation exigent le scope `api`. Le demarrage
conserve le GUID et les tentatives concurrentes reutilisent le meme direct.
Une emission demarree ne peut plus etre reprogrammee ou redemarree apres
sa fin. Les medias restent geres par `ILiveProcessor`, avec ses quotas,
expiration, reprise et preparation MP4. Une suppression conserve un
marqueur en base pour ne pas ressusciter une emission deja supprimee.
Le verrou de coordination suit le deploiement mono-processus du stockage
media actuel ; un deploiement multi-instance necessiterait un stockage et
une coordination distribues.
Seul `GET /api/v1/podcasts/announcements` est anonyme : titre, nom d'auteur,
horaire UTC, duree et texte public, sans URL de flux ni metadonnees privees.
`/Podcast/Announcements` affiche ces annonces avec encodage Razor et sans
jeton utilisateur. Retirer le texte public avant le debut retire l'annonce.
Les annonces restent disponibles apres le direct jusqu'a suppression du
podcast. Les pages et toutes les routes de lecture restent authentifiees.
Appliquer la migration `PodcastScheduling` au deploiement, apres celle des
dons ; aucune migration de production n'est appliquee automatiquement ici.
### Dons PayPal aux performers
Les dons sont gérés par Yavsc.Org, pas par un lien de paiement externe
configuré par l'opérateur :
1. Depuis **Mon compte > Dons PayPal**, le performer renseigne l'adresse
de son propre compte PayPal (`/Donation/Settings`). Un champ vide
désactive les nouveaux dons. Seuls les performers actifs ayant
configuré leur compte proposent un bouton de don dans le catalogue.
Le formulaire est aussi accessible depuis le catalogue de podcasts et
le profil professionnel Web. Dans PostIt : **Mon profil > Gérer mon
activité professionnelle > Dons PayPal**, puis **Enregistrer**.
L'API privée `GET/PUT /api/v1/account/performer-profile` transporte
`DonationPayPalEmail` uniquement pour le compte connecté ; une chaîne
vide désactive les dons, une propriété omise ou nulle préserve
l'adresse existante pour les anciens clients.
2. Le donateur connecté choisit un montant en euros (`/Donation/Create`).
Yavsc conserve le don et son bénéficiaire avant de créer le checkout.
3. Yavsc utilise les paramètres marchands existants
`Authentication:PayPal` (mode sandbox/production et identifiants NVP).
Express Checkout désigne le compte du performer par
`PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID` : le paiement va directement
au performer ; Yavsc ne collecte pas les fonds et ne les reverse pas.
4. PayPal recueille l'accord du donateur puis le renvoie dans Yavsc.
Une confirmation POST avec protection antiforgery déclenche le
paiement, après vérification côté serveur du token, du montant,
de la devise, de la référence et du bénéficiaire. Un simple retour
du navigateur n'est jamais considéré comme une preuve de paiement.
5. Seule une réponse PayPal vérifiée permet d'afficher le don comme payé.
Les notifications IPN reçues sur `/Donation/Notify` sont revalidées
auprès de PayPal, puis rapprochées du bénéficiaire, du montant, de la
devise et de la transaction. Elles permettent aussi de confirmer
ultérieurement un paiement Pending ou une réponse de capture perdue.
`Site:ExternalUrl` doit être l'URL HTTPS publique de Yavsc.Org, utilisée
pour les retours et notifications (jamais le Host fourni par le client).
PayPal doit pouvoir joindre `/Donation/Notify`. Le compte marchand
doit être autorisé par PayPal pour les paiements directs à un tiers ;
valider ce parcours en sandbox avec deux comptes distincts avant mise
en production. Les tests locaux utilisent un serveur PayPal simulé,
pas de véritables transactions.
`PerformerDonations` conserve la référence, le donateur, le performer,
le bénéficiaire figé à la création, le montant et l'état du paiement.
La migration `PerformerPayPalDonations` ajoute ce suivi et l'adresse
PayPal optionnelle du performer. Les profils ayant un historique de
dons ne peuvent pas être supprimés. Les rééditions du profil général
ne remplacent pas la configuration du bénéficiaire.
Le paiement n'est capturé qu'une fois : contrôle de concurrence,
référence de déduplication PayPal (`MSGSUBID`) et transaction unique.
En cas de réponse ambiguë, le don reste en vérification sans nouvelle
capture automatique. Le donateur retrouve son suivi dans **Mon compte >
Mes dons** (`/Donation`). Si l'IPN ne réconcilie pas cet état, l'opérateur
doit vérifier la transaction auprès de PayPal avant toute nouvelle
tentative. Les dons sont facultatifs et n'ouvrent pas droit à un reçu
fiscal émis par cette page.
## À documenter ensuite
- Modèle `ProjetMusical`

View file

@ -16,6 +16,7 @@ La racine de l'architecture est [Architecture.md](Architecture.md).
| [architecture/offres-frontmatter.md](architecture/offres-frontmatter.md) | Offre fournisseur, ClasseFormulaire, ClasseDevis, parsing frontmatter |
| [architecture/postit-oidc.md](architecture/postit-oidc.md) | Client desktop PostIt, custom URI scheme, silent refresh |
| [architecture/postit.md](architecture/postit.md) | PostIt — topologie des projets, ViewLocator custo, navigation, DI, conventions de binding |
| [architecture/audio-video-calls.md](architecture/audio-video-calls.md) | Plan des appels WebRTC PostIt : SignalR, préférence de masquage IP via TURN et groupes via SFU |
| [architecture/notifications.md](architecture/notifications.md) | Notifications persistées, messages Web et événements temps réel côté serveur, Web et PostIt |
| [architecture/decoupage-organisation.md](architecture/decoupage-organisation.md) | Découpage des projets .NET (Abstract, Server, Org, Api, Blogs, Web, Org.Tests) |
| [testing.md](testing.md) | Stratégie de test : conventions des dossiers, EF Core in-memory, auth stubs, scaffold partagé |

View file

@ -0,0 +1,697 @@
# Appels audio-vidéo PostIt — architecture cible
## Statut et périmètre
Ce document décrit l'architecture cible, l'implementation native actuelle et
l'historique du transport direct.
La préférence de confidentialité est persistée et éditable dans le profil.
La signalisation est intégrée au chat, désactivée par défaut. Une page d'appel
separee propose **WebRTC natif** et le transport direct VLC/SRTP sur Android et
Desktop Linux. WebRTC utilise ICE/STUN/TURN et le masquage IP impose par la
politique serveur. Le mode SRTP direct ne masque pas les adresses IP et exige
que cette preference soit desactivee pour les deux participants. Les groupes
et les clients navigateur ne sont pas implementes.
Depuis le chat textuel, selectionner un membre present puis « Ouvrir l'appel »
prepare le pair sans demarrer les medias. Les invitations entrantes disposent
d'un bouton pour ouvrir cette meme page sans selection de membre. Passer du
chat a la page d'appel ne raccroche pas ; quitter la page d'appel termine les
medias. Un salon commun reste requis ; les capacites distantes et les appels
depuis Contacts ne sont pas encore raccordes.
Il complète la [topologie de PostIt](postit.md) et les
[mécanismes de notification existants](notifications.md).
La cible couvre :
- les appels audio-vidéo bidirectionnels entre deux utilisateurs ;
- un réglage utilisateur booléen persistant permettant de masquer son adresse
IP aux autres participants en imposant TURN ;
- les appels de groupe ;
- les clients Browser, Android et Desktop.
## Implementation actuelle : WebRTC natif Android et Linux
- [WebRtcCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/WebRtcCallViewModel.cs)
conserve invitation/acceptation/fin via SignalR, sans demarrer la capture
avant consentement. Les SDP et candidats ICE utilisent les contrats existants.
- [AndroidWebRtcMedia](../../src/PostIt/PostIt.Android/Services/AndroidWebRtcMedia.cs)
heberge deux surfaces natives. Le pont Java
[WebRtcPeer](../../src/PostIt/PostIt.Android/Services/WebRtcPeer.java) utilise
l'AAR officiel `io.github.webrtc-sdk:android:150.7871.04`, Camera2,
l'audio natif et DTLS-SRTP. Les commandes et callbacks SDP/ICE restent en
Java sur un executeur unique ; pas de WebView ni de binding C# complet du SDK.
- [LinuxWebRtcMedia](../../src/PostIt/PostIt/Services/LinuxWebRtcMedia.cs)
pilote un processus Python GI prive utilisant GStreamer `webrtcbin`,
VP8/Opus, la camera V4L2 et le microphone PulseAudio/PipeWire.
Les trames decodees sont affichees dans Avalonia, l'audio sur la sortie native.
Le protocole JSON utilise uniquement stdin/stdout, pas de serveur local.
- Le serveur impose `RelayOnly` aux deux clients si l'un des comptes masque
son IP. Le client configure la politique native avant capture/negociation,
valide les SDP/candidats sortants et confirme le type du candidat local
de la paire ICE selectionnee. Aucun repli direct ni transport SRTP historique
n'est tente en cas d'echec TURN.
- Avec libnice, les metadonnees ICE `raddr`/`rport` des candidats relais sont
neutralisees a la frontiere de signalisation (RFC 8828), sans modifier
l'adresse du relais ni reecrire le SDP. UPnP est desactive. Les politiques
`relay` de webrtcbin et `force-relay` de libnice sont toutes deux activees.
Un SDP qui expose une adresse non relayee est refuse, pas corrige.
- Raccrocher, sortir de la page/salle, se deconnecter ou passer l'application
en arriere-plan annule aussi un demarrage natif en cours et libere les medias.
Un echec natif, une perte ICE ou 30 secondes sans progression audio/video
terminent l'appel explicitement. Il n'y a pas d'ICE restart/renegociation
automatique ni de migration transparente d'un appel existant.
Le panneau WebRTC ne demande pas d'adresse ni de port RTP manuel. Le panneau
SRTP direct demande une adresse locale, un port UDP pair et le consentement au
partage d'adresse ; il requiert HTTPS pour proteger les cles de signalisation.
Les invitations sont dirigees vers le panneau correspondant, sans bascule
automatique entre transports. Sans masquage,
un consentement explicite au partage IP reste requis. Activer le masquage
dans le profil pendant un appel fait terminer cet appel par le serveur :
il faut rappeler pour appliquer la nouvelle politique.
Configuration coturn, certificats, ports et dependances Linux :
[INSTALL](../../INSTALL.md#postit-native-webrtc-calls-android-and-linux).
Les moteurs d'appel sont independants des captures/encodeurs Podcast ;
les Podcasts conservent leur chemin existant.
### Regressions natives
Tests Linux reels, sans compte ni camera, avec sources video/audio synthetiques,
decodage bidirectionnel, selection effective d'un relais coturn, controle des
adresses signalees et panne TURN sans repli :
```bash
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py -v
```
Installer coturn pour ces tests (ou definir `POSTIT_TURN_SERVER` vers son
executable). Ils demarrent un processus local prive, avec secret REST aleatoire
temporaire, et l'arretent en fin de test ; ils ne changent aucun service systeme.
Tests du consentement, de la politique, des interruptions et du rendu de vraies
trames dans Avalonia/Skia :
```bash
XDG_CONFIG_HOME="$(mktemp -d)" POSTIT_TEST_NATIVE_WEBRTC=1 \
dotnet test --project src/PostIt/PostIt.Tests \
--filter-class 'PostIt.Tests.WebRtcCallViewModelTests' \
--filter-class 'PostIt.Tests.LanCallViewModelTests'
```
Le test de rendu natif est ignore sans `POSTIT_TEST_NATIVE_WEBRTC=1`.
Les tests headless ordinaires conservent leur moteur de dessin simule.
Utiliser un dossier de configuration de test sans comptes reels et le supprimer
apres execution.
Le test Android physique est reserve a l'APK **Debug** installe : camera avant,
microphone, deux surfaces natives, pair Linux synthetique et coturn local,
aucun compte ni enregistrement. Il utilise `adb reverse` pour des ports TCP
temporaires et retire uniquement ses propres redirections :
```bash
POSTIT_TEST_ANDROID_WEBRTC=1 POSTIT_ANDROID_SERIAL=SERIAL \
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py \
NativeWebRtcTests.test_android_linux_relay_bidirectional_media -v
```
Ce controle local ne remplace pas un essai sur deux reseaux Internet distincts,
avec DNS/certificats publics et pare-feu de production.
Validation effectuee : 37 tests PostIt (dont rendu Linux avec Skia), 76 tests
serveur de signalisation et 5 regressions natives reussis. Sur le telephone
Android arm64, les deux roles appelant/appele ont recu plus de 100 trames
video et 500 paquets audio pendant au moins 10 secondes, avec deux rendus
natifs confirmes et un candidat local `relay` des deux cotes. La panne TURN
ne produit aucun candidat direct sur Android ou Linux. Les essais utilisent
la camera avant et le microphone Android reels, des sources Linux synthetiques
et un coturn TCP local via USB ; la camera et la sortie audio Linux materielles,
TURN/TLS et les reseaux Internet distincts restent a verifier.
## Implementation SRTP direct IPv4/IPv6
Les paragraphes suivants decrivent le transport direct historique, de nouveau
propose a cote de WebRTC dans la page d'appel.
Les adresses IPv4 publiques directement assignees a une interface locale active
sont egalement disponibles, avec la meme validation unicast cote client,
media et signalisation serveur. Les IPv6 globales (2000::/3), privees ULA
(fc00::/7) et de boucle locale (::1) sont aussi acceptees. Les sockets UDP
utilisent la famille de l'adresse locale et les URL de reception encadrent
les IPv6 de crochets. Les adresses non specifiees, link-local, multicast,
reservees IPv4 (240/4), IPv4-mapped IPv6 et les formes non canoniques ou
avec identifiant de zone sont refusees. Une zone link-local du premier
pair n'est pas reutilisable telle quelle par le second.
Il faut autoriser en entree les deux ports UDP consecutifs choisis et assurer
la joignabilite entre les pairs. Ce support n'ajoute ni ICE/TURN ni traversee
NAT automatique : l'adresse publique d'un routeur ne remplace pas une adresse
assignee a la machine. Le consentement explicite au partage d'IP et le refus
du mode direct pour les comptes masquant leur IP restent inchanges.
Les pairs doivent disposer de routes vers leurs adresses respectives ;
aucune traduction automatique IPv4/IPv6 n'est fournie. Les tests natifs
Linux verifient sur ::1 la reception audio/video bidirectionnelle chiffree,
le rejet d'une mauvaise cle et le cycle de vie des ports RTP/RTCP.
Un appel IPv6 entre deux machines et le transport IPv6 Android restent
a valider en conditions reelles.
Cette tranche réutilise la capture caméra/microphone et les encodeurs des
Podcasts, mais **pas leur segmentation HLS ni leurs envois de fichiers** :
```text
PostIt A ----------- ChatHub authentifié / HTTPS ----------- PostIt B
invitation, consentement,
adresses et clés, fin
PostIt A ========== H.264/AAC, MPEG-TS sur SRTP/UDP ========== PostIt B
dans les deux sens
```
L'implémentation est dans
[LibVlcLanCallMedia](../../src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs),
[LinuxLanCallVideo](../../src/PostIt/PostIt/Services/LinuxLanCallVideo.cs) et
[LanCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs).
Android utilise
[AndroidLanCallMedia](../../src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs)
avec les mêmes contrats et clés SRTP.
Les contrôles et les deux surfaces vidéo sont intégrés à la page du chat.
Il n'y a pas de service de salles supplémentaire, d'enregistrement,
de fichier média temporaire ou de moteur WebRTC Android ajouté.
### Activer et essayer
1. Sur le serveur, activer explicitement les deux options :
```json
{
"AudioVideoCalls": {
"Enabled": true,
"EnableLanCalls": true
}
}
```
Les deux valeurs sont `false` par défaut. Les paramètres TURN ne sont
pas nécessaires pour ce mode. Utiliser le ChatHub en **HTTPS** ;
invitation, acceptation et échange de clés LAN sont refusés en HTTP.
Derrière un proxy TLS, configurer correctement le schéma HTTPS transmis
à ASP.NET Core, uniquement depuis les proxys de confiance.
2. Utiliser deux clients Android 8+ ou Desktop Linux. Linux nécessite LibVLC
avec V4L2, PulseAudio, x264, AAC et RTP/SRTP installés. Android réutilise
la bibliothèque VLC embarquée pour les Podcasts et MediaRecorder pour
H.264/AAC. La version Debian 13 a été utilisée pour les essais Linux.
Les deux comptes doivent être présents dans
la même salle existante et ne pas se bloquer mutuellement.
3. Selectionner le destinataire dans les membres presents du chat puis
« Ouvrir l'appel ». Dans la section « Appel direct IPv4/IPv6 SRTP »,
actualiser les périphériques, sélectionner la caméra, le microphone et
une adresse locale accessible depuis le pair. Les adresses IPv4 privées
ou publiques assignées et les IPv6 globales ou ULA sont acceptées, pas
les noms DNS ni les adresses link-local. Le bouclage sert aux
essais sur un même hôte, pas à joindre un second poste.
4. Choisir un port UDP **pair entre 1024 et 65534**, par défaut 5004.
Autoriser l'entrée UDP sur ce port **et le suivant** depuis le pair dans
le pare-feu : RTP sur le port pair, RTCP sur le port impair suivant.
Les deux ports doivent être disponibles. Deux clients sur la même
adresse doivent utiliser des paires distinctes.
Aucun pare-feu n'est modifié automatiquement.
5. Verifier le pseudo du destinataire selectionne, confirmer la divulgation de
l'adresse IP locale (LAN/VPN ou publique), puis appeler. Le destinataire choisit ses propres
périphériques et son adresse, confirme et accepte explicitement.
Aucun accès à la caméra/microphone ne commence avant l'acceptation ;
l'émission attend également la destination validée du pair.
6. Utiliser un **casque** : il n'y a pas d'annulation d'écho acoustique.
« Refuser / Raccrocher », la sortie de page et la perte de SignalR
arrêtent et libèrent les médias. Il n'y a pas de reprise automatique
de capture après reconnexion.
### Capture et cycle de vie Android
- La caméra avant est sélectionnée en priorité dans la liste ; une autre
caméra reste sélectionnable explicitement. Le microphone est obligatoire.
- Les permissions caméra, microphone et notifications sont demandées
après acceptation et réception de l'endpoint distant, avant la capture.
Un refus termine explicitement l'appel, sans tentative de capture de repli.
- Camera2, MediaRecorder et la rotation EGL sont ceux des Podcasts.
Le descripteur du pipe MPEG-TS est lu directement par LibVLC (`fd://`)
puis remultiplexé vers SRTP, **sans réencodage**, HLS ou fichier média.
Le pipe système assure une mémoire bornée ; il n'y a pas de file de
segments ni de lecture de capture par callbacks managés.
- La prévisualisation réutilise la surface EGL existante. Le retour
distant utilise la surface Android LibVLC déjà employée pour les Podcasts.
La rotation capteur/écran tient compte de celle déjà portée par la matrice
`SurfaceTexture` (miroir de la caméra avant compris) et suit les changements
portrait/paysage. Les dimensions
encodées restent fixes pendant l'appel, avec bandes noires si nécessaire.
- Le service de capture partagé affiche une notification d'appel avec
l'action « Raccrocher » ; cette action ne publie aucun Podcast.
Un Podcast et un appel ne peuvent pas posséder la capture simultanément.
- Le passage de PostIt en arrière-plan termine cet appel vidéo ; revenir
dans l'application ne le redémarre pas. La sortie de page et la perte
SignalR conservent la même règle d'arrêt.
- À l'arrêt, le lecteur natif libère d'abord son entrée. Le pipe restant
est drainé pendant la finalisation de MediaRecorder, pour ne pas bloquer
son écrivain, puis caméra, microphone, lecteurs et service sont libérés.
#### Particularité VLC Android : RTCP séparé
L'essai matériel initial a identifié un SIGSEGV dans `libc.__vfprintf`,
appelé par `vlc_memstream_vprintf` puis `sdp_AddAttribute` pendant la
création de la sortie RTP. Le code VLC 3 génère l'attribut sans valeur
`rtcp-mux` avec un format nul ; cette combinaison échoue avec le binaire
Android embarqué. Ce crash est distinct du précédent essai libwebrtc/JNI.
Les appels utilisent donc une paire RTP/RTCP standard, sans `rtcp-mux`,
sur Android **et** Linux. Les médias conservent les mêmes codecs, clés et
port RTP : c'est un changement de configuration du transport, pas
l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet.
### Confidentialité et limites
- Une clé SRTP aléatoire de 128 bits et un sel de 112 bits sont générés
par appel et par direction avec le générateur cryptographique système.
Seuls les deux appareils ayant accepté échangent un endpoint chacun
via SignalR authentifié. Les représentations diagnostiques masquent
adresse, clé et sel.
- Le chiffrement SRTP est fourni par LibVLC ; les clés passent par
le serveur de signalisation, qui **peut donc les connaître**. Ce n'est
pas un chiffrement de bout en bout à l'insu du serveur.
- Si l'un des comptes impose `HideIpAddressInCalls`, le mode LAN est
**refusé**, y compris si la préférence change avant l'acceptation.
Il n'y a aucun repli direct contournant cette préférence.
- Pas d'ICE, de STUN, de TURN, de traversée NAT automatique, de groupe,
d'interopérabilité Browser, de négociation de codecs ni
d'adaptation de débit. Ce mode exige une connectivite IP directe entre les pairs
(LAN/VPN ou adresse publique assignee), avec les ports UDP ouverts.
- H.264 à 30 images/s, cible 1 200 kbit/s ; AAC mono 48 kHz, 96 kbit/s.
Ces réglages ne constituent pas une garantie de latence ni de débit.
Le retour local n'émet pas le son du microphone.
- L'absence de première réception audio **et** vidéo provoque l'arrêt
après 30 secondes ; les erreurs natives sont affichées et terminent
l'appel. Après réception initiale, les compteurs LibVLC ne permettent
pas ici de diagnostiquer précisément une panne média silencieuse :
l'utilisateur peut raccrocher, et la perte de SignalR arrête toujours
la capture. Pas encore de mesure de qualité ou de latence affichée.
### Validation effectuée et restante
Les tests natifs utilisent deux moteurs LibVLC réels, un fichier audio-vidéo
synthétique fourni explicitement et de vrais sockets UDP de bouclage :
- décodage bidirectionnel de trames vidéo et d'échantillons audio PCM ;
- refus de décodage avec une mauvaise clé, sans casser l'autre direction ;
- même échange avec la branche de prévisualisation locale activée
(sortie factice dans ce test sans fenêtre).
- entrée MPEG-TS déjà encodée à travers un pipe, sans transcodage.
Les tests de signalisation couvrent consentement, sélection d'un seul
appareil, confidentialité, HTTPS, validation des endpoints et arrêt.
Les tests Avalonia sans fenêtre couvrent l'ordre invitation/acceptation/
capture, le refus, les événements tardifs, l'interruption, les erreurs média
et l'annulation d'un démarrage natif en attente. Ils vérifient aussi les
hooks Android, le choix initial de caméra avant, la configuration lors
d'une invitation entrante et l'arrêt lors du passage en arrière-plan.
Pour exécuter les tests média, définir `POSTIT_TEST_MEDIA` avec le chemin
d'un MP4 H.264/AAC de test (640 × 480), puis :
```sh
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-class '*LinuxLanCallMediaTests'
```
Sans cette entrée explicite, ces tests sont ignorés, pas remplacés par un
succès fictif. Les tests de contrôle s'exécutent sans caméra.
Le test de pipe utilise `POSTIT_TEST_TS`, un MPEG-TS H.264/AAC explicite.
Une activité **Debug uniquement**,
[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs),
teste l'adaptateur réel sur téléphone : caméra avant/microphone, surfaces
de retour et prévisualisation attachées, deux moteurs SRTP en UDP de
bouclage, retour synthétique et rejet d'une mauvaise clé. Elle n'utilise
ni compte ni API ; elle ne valide donc pas à elle seule un appel SignalR
entre deux comptes. L'activité n'est pas compilée dans l'APK Release.
Pour la lancer sur un appareil de développement dont les permissions
ont été accordées, installer l'APK Debug et ses assemblies via
`dotnet build -t:Install`, puis copier un MPEG-TS synthétique de 40 secondes,
640 × 480 avec audio AAC, sous `files/lan-call-fixture.ts` dans les données
privées de l'application. Exécuter :
```sh
adb shell am start -S -n fr.pschneider.postit/fr.pschneider.postit.LanCallTestActivity
adb shell run-as fr.pschneider.postit cat files/lan-call-test-result.txt
# Variante : ajouter --es wrongKey true à la commande am start.
```
Le résultat ne devient `PASS` qu'après vérification des médias et nettoyage
complet. Le test ne produit aucun enregistrement de caméra.
Sur le téléphone Android 15 arm64 connecté, l'essai positif a décodé
158 trames caméra et 399 360 échantillons audio en environ dix secondes,
avec un retour audio/vidéo décodé simultanément. L'essai avec mauvaise clé
a produit zéro trame et zéro échantillon dans la direction concernée,
tout en conservant le retour. Les deux essais ont terminé leur nettoyage,
sans service de capture restant. La capture Podcast antérieure a également
été retestée sur caméra avant : quatre segments, environ 11,8 secondes,
audio AAC présent, capture en arrière-plan puis arrêt par notification.
**La caméra physique, le rendu natif visible dans deux applications, le
son audible et un appel entre deux machines restent à valider côté Linux** :
aucune caméra n'était disponible sur cet hôte. La capture matérielle Android
est testée, mais un appel Android ↔ Linux ou entre deux téléphones distincts
sur LAN/VPN et la qualité acoustique restent à valider. Les essais de
bouclage ne prouvent pas une latence conversationnelle.
## Choix des protocoles
La table suivante demeure la **cible multi-plateforme initiale**, distincte
du premier transport Linux LAN/VPN décrit ci-dessus.
| Besoin | Choix | Rôle |
|---|---|---|
| Médias temps réel | WebRTC | Audio-vidéo bidirectionnel à faible latence, adaptation au réseau |
| Chiffrement du transport média | DTLS-SRTP | Établissement des clés et protection des médias |
| Signalisation | SignalR sur HTTPS | Invitation, acceptation/refus, négociation SDP, candidats ICE, fin d'appel |
| Connectivité | ICE, STUN et TURN | Sélection du chemin réseau, découverte d'adresse et relais |
| Audio | Opus | Codec privilégié pour la voix |
| Vidéo | VP8 ou H.264 | Codec négocié selon les capacités réelles des clients |
| Appels de groupe | SFU compatible WebRTC | Réception et redistribution sélective des flux |
SignalR transporte les messages de contrôle, **jamais les flux audio-vidéo**.
La signalisation doit réutiliser le [ChatHub existant](../../src/Yavsc.Server/Hubs/ChatHub.cs),
déjà exposé par [Yavsc.Api](../../src/Yavsc.Api/Program.cs), et ses salles de
discussion. Il n'est pas nécessaire de créer un second service de salles.
Les contrats d'appel et leurs autorisations restent à définir explicitement :
l'appartenance à une salle ne vaut pas acceptation d'un appel.
Le choix des bibliothèques natives, du SFU et des codecs effectivement
disponibles reste à valider par un prototype multi-plateforme.
## Topologies média
### Appels à deux
```text
PostIt A ---- SignalR / HTTPS ---- Serveur ---- SignalR / HTTPS ---- PostIt B
Invitation, acceptation, SDP, candidats ICE, fin
PostIt A ================= WebRTC direct ========================= PostIt B
ou
PostIt A ================= relais TURN =========================== PostIt B
```
Privilégier un chemin direct lorsque les préférences de confidentialité le
permettent. Prévoir TURN dès la première version : STUN seul ne suffit pas sur
certains réseaux mobiles, NAT ou réseaux d'entreprise.
Déployer par exemple coturn, avec des transports UDP et des solutions de
repli TCP/TLS, dont TURN/TLS sur le port 443. Ce dernier améliore la
connectivité sans garantir la traversée de tous les pare-feu et proxys.
### Appels de groupe
```text
PostIt A ---- WebRTC, éventuellement via TURN ----+
PostIt B ---- WebRTC, éventuellement via TURN ----+---- SFU
PostIt C ---- WebRTC, éventuellement via TURN ----+
```
Utiliser un **SFU**, plutôt qu'un maillage de connexions entre participants :
chaque client envoie ses pistes au serveur, qui redistribue les flux utiles.
Cela évite de multiplier les envois montants avec le nombre de participants.
Prévoir la sélection des pistes reçues et, selon les capacités des clients,
le simulcast ou le codage vidéo scalable pour adapter débit et résolution.
Le SFU ne remplace pas TURN : un client peut avoir besoin d'un relais pour
atteindre le SFU, ou l'imposer par sa préférence de confidentialité.
Les contrats de signalisation doivent représenter dès le départ un appel et
ses participants, sans être limités à un couple appelant/appelé. Pour ajouter
un troisième participant à un appel direct, établir les connexions au SFU,
puis fermer les connexions directes après confirmation du nouveau transport.
En cas d'échec, conserver l'appel à deux et signaler l'échec de l'ajout.
Une topologie SFU pour tous les appels reste une alternative à évaluer si la
simplicité d'exploitation prime sur le coût serveur.
## Préférence persistante de masquage d'adresse IP
### Contrat fonctionnel
Le booléen de compte `HideIpAddressInCalls` est persisté côté serveur et
accessible en lecture/écriture uniquement par
l'utilisateur concerné via `GET /api/v1/account/me` et
`PUT /api/v1/account/me`, ainsi que dans « Mon profil » de PostIt.
Le réglage est partagé entre ses appareils ; une préférence locale seule
ne suffit pas.
Valeur initiale : `false`, pour les nouveaux comptes et les comptes existants
après migration. Le champ de mise à jour est nullable : son absence ou `null`
conserve la valeur existante, notamment pour les anciens clients ; `false`
explicite désactive la préférence.
`false` autorise le chemin direct mais n'interdit pas TURN lorsqu'il est
nécessaire à la connectivité. `true` impose un transport relayé.
Présenter le réglage comme « Masquer mon adresse IP aux autres participants »,
en précisant le surcoût potentiel en latence et en bande passante serveur.
Il ne procure pas l'anonymat : les services contactés, notamment l'API, le
serveur de signalisation et TURN, peuvent toujours connaître l'adresse IP.
La migration EF Core `HideIpAddressInCalls`, dans le projet Yavsc.Org, ajoute
la colonne booléenne non nullable à `AspNetUsers`. Elle doit être déployée
avant de servir les nouvelles lectures et écritures de profil. Cette étape
n'installe ni TURN ni SFU et n'implémente pas encore les règles de négociation
décrites ci-dessous.
### Application à la négociation
- Charger la préférence avant de créer le transport média. Si sa lecture
échoue, signaler l'erreur et bloquer l'établissement plutôt que supposer
que le masquage est désactivé.
- Lorsque le réglage est activé, configurer une politique ICE **relay-only**
(`iceTransportPolicy: "relay"` dans le navigateur, équivalent natif ailleurs)
avant la collecte des candidats.
- Ne publier aucun candidat local `host` ou `srflx`, ni aucune adresse locale
dans les descriptions SDP ou messages de signalisation. Utiliser les API du
moteur WebRTC et vérifier les descriptions produites, plutôt qu'une
réécriture ad hoc du SDP.
- Appliquer cette contrainte aux offres, réponses, renégociations,
redémarrages ICE et transitions vers le SFU.
- Le masquage d'un participant impose le relais de **son propre transport**,
même si les autres participants n'ont pas activé cette préférence.
- Si TURN est indisponible ou qu'aucune paire de candidats relayée n'aboutit,
afficher une erreur explicite ; **aucun repli direct automatique**.
Le serveur détermine la politique attendue depuis la préférence persistée,
contrôle les messages de signalisation et distribue les paramètres autorisés.
Le client applique la politique ICE ; les tests doivent vérifier le chemin
réellement sélectionné, pas seulement la configuration demandée.
Une modification pendant un appel doit être prise en charge explicitement :
l'activation suspend l'émission et remplace le transport avant de reprendre
les médias en mode relayé. L'interface ne doit pas annoncer le masquage tant
que ce remplacement n'est pas confirmé. Elle précise qu'une adresse déjà
divulguée auparavant ne peut pas être retirée aux participants.
La désactivation peut attendre l'appel suivant, sans abandonner le relais
en cours.
## Intégration dans PostIt
Séparer le cycle de vie partagé de l'appel du moteur média :
- code partagé : invitation, sonnerie, acceptation/refus, participants,
préférences, état de connexion, coupure micro/caméra et raccrochage ;
- Browser : API WebRTC du navigateur via interop JavaScript ;
- Android et Desktop : moteur WebRTC natif et intégration de la capture,
des périphériques et du rendu dans Avalonia.
Le prototype doit vérifier les bindings maintenus, leurs licences, les
architectures processeur supportées, les codecs et l'intégration Avalonia.
Ne pas supposer qu'une bibliothèque .NET couvre à elle seule la capture,
l'annulation d'écho et le rendu sur toutes les plateformes.
Prévoir les permissions caméra/micro, les changements de périphérique,
les interruptions Android, la reconnexion et le redémarrage ICE.
Les appels entrants en arrière-plan nécessitent une intégration aux
notifications système et au cycle de vie Android ; une connexion SignalR
active ne peut pas être présumée.
## Autorisations, confidentialité et exploitation
- Authentifier la signalisation et vérifier côté serveur l'appartenance à
l'appel pour chaque commande et événement, y compris rejoindre un groupe,
inviter, publier une piste et recevoir les flux.
- Prévoir des invitations expirables et gérer les réponses concurrentes de
plusieurs appareils sans accepter plusieurs fois le même participant.
- Délivrer des identifiants TURN temporaires et des autorisations SFU limitées
à l'appel et au participant ; aucun secret permanent dans les clients.
- Limiter les invitations, les participants et les débits selon une politique
produit à définir ; surveiller la capacité et le coût TURN/SFU.
- Ne pas journaliser systématiquement SDP, candidats ICE ou identifiants TURN.
Préférer des métriques de qualité et des identifiants techniques d'appel.
- Distinguer chiffrement du transport et chiffrement de bout en bout :
en connexion directe ou via TURN, les médias restent chiffrés entre les deux
clients ; avec un SFU classique, DTLS-SRTP se termine au SFU. Un chiffrement
de bout en bout des groupes demanderait un mécanisme supplémentaire et une
gestion des clés à concevoir, sans être promis par ce plan.
## Étapes proposées
1. **Prototype multi-plateforme** : valider capture, rendu, codecs et WebRTC
entre Browser, Android et Desktop, y compris via TURN.
2. **Appels à deux** : signalisation authentifiée, cycle de vie d'appel,
coturn, préférence persistante et politique relay-only opérationnelle.
3. **Appels de groupe** : sélectionner et intégrer le SFU, autoriser les
participants, gérer les pistes et la transition depuis un appel direct.
4. **Fiabilisation** : arrière-plan Android, réseau mobile, reprise après
interruption, accessibilité des contrôles et observabilité.
Les appels de groupe font partie de la cible finale, pas d'une simple
extension facultative. Leur modèle de participants doit être anticipé dès
la signalisation des premiers appels à deux.
## Critères de validation
- Audio et vidéo bidirectionnels sur les combinaisons de plateformes ciblées.
- Appel direct autorisé quand le réglage est désactivé et relais disponible
lorsque le réseau l'exige.
- Préférence conservée après reconnexion et relue sur un autre appareil.
- Avec masquage activé, absence d'adresses locales/publiques propres au client
dans la signalisation transmise aux pairs et sélection effective d'un
candidat local `relay`, confirmée par les statistiques WebRTC.
- Aucun repli direct si TURN échoue, y compris après redémarrage ICE,
changement de réseau ou ajout d'un participant.
- En groupe, contrôle d'accès aux pistes, départ et arrivée de participants,
adaptation de qualité et respect individuel de la politique TURN.
- Activation du masquage pendant un appel : suspension des médias,
remplacement vérifié du transport et retour d'état fidèle dans l'interface.
- Échecs de permissions, de signalisation, de TURN et du SFU visibles,
ressources caméra/micro et connexions libérées à la fin de l'appel.
## Première tranche intégrée : signalisation Android et Desktop Linux
Le périmètre initial retenu est **Android + Desktop Linux**. Il n'ajoute
aucun serveur ni aucune salle : les méthodes suivantes appartiennent au
[ChatHub](../../src/Yavsc.Server/Hubs/ChatHub.Calls.cs) existant.
Les [contrats partagés](../../src/Yavsc.Abstract/Chat/Calls/CallContracts.cs)
sont utilisés par le serveur et PostIt.
| Méthode | Effet |
|---|---|
| `InviteCall(roomName, callee)` | Invite un autre compte présent dans la salle et retourne un identifiant d'appel |
| `AcceptCall(callId)` | Accepte sur un seul appareil, notifie les deux pairs et ferme l'invitation sur les autres appareils |
| `SendCallSignal(callId, signal)` | Transmet l'offre, la réponse ou un candidat ICE uniquement à l'autre appareil accepté |
| `EndCall(callId)` | Annule, refuse ou termine l'appel depuis un appareil autorisé |
Événements : `CallInvitation`, `CallAccepted`, `CallSignal(callId, signal)`
et `CallEnded`. **Accepté ne veut pas dire connecté** : l'événement accepté
exprime le consentement et fournit la politique ICE et les paramètres
STUN/TURN, pas une réussite de l'échange média.
Le serveur vérifie les comptes, la présence dans la salle et le blocage
entre utilisateurs. Les appareils d'un compte reçoivent l'invitation ;
seul le premier qui accepte peut ensuite émettre la réponse et les
candidats. L'appelant reste lié à sa connexion d'origine. Les médias
ne sont jamais diffusés au groupe SignalR de la salle.
La préférence persistée est lue à l'invitation et relue à l'acceptation.
Pour cette première version à deux, si l'un des comptes demande le
masquage, **les deux transports doivent être relayés**, règle conservatrice
plus stricte que la politique individuelle cible. L'acceptation ne peut
pas diminuer la protection annoncée à l'invitation. Sans TURN configuré,
un appel imposant le relais échoue explicitement.
La signalisation refuse les candidats non relayés, les adresses associées
non masquées et les adresses directes dans les champs SDP contrôlés lorsque
le relais est imposé. Ces contrôles de forme ne constituent pas un audit
exhaustif de toutes les extensions SDP possibles : la non-divulgation doit
encore être prouvée avec les SDP et statistiques des moteurs réellement
intégrés. Aucun SDP n'est réécrit.
L'activation du masquage ou le changement de pseudo par l'API de profil
termine l'appel existant ; le client devra libérer les médias et proposer
un nouvel appel. La renégociation transparente du transport n'est pas
implémentée. La déconnexion d'un pair sélectionné, le départ ou l'exclusion
de la salle terminent également l'appel. Pas de reprise automatique après
reconnexion : elle crée une nouvelle identité de connexion.
Les appels sont temporaires, en mémoire et **sur une seule instance API**.
Une invitation expire après 45 secondes, une session acceptée après une
heure ; les identifiants TURN expirent cinq minutes plus tard. Cette borne
initiale ne remplace pas un futur renouvellement d'identifiants pour les
appels longs. Un compte ne peut avoir qu'un appel réservé ou accepté à la
fois. Le registre est limité à 128 appels et 256 candidats par appel.
La tranche ne permet qu'une offre initiale de l'appelant et une réponse ;
les redémarrages ICE et renégociations restent à implémenter.
Configuration serveur, section `AudioVideoCalls` :
- `Enabled` : `false` par défaut, a activer apres configuration et validation
du deploiement ICE/TURN ;
- `StunUrls` : tableau d'URI `stun:` ou `stuns:` ;
- `TurnUrls` : tableau d'URI `turn:` ou `turns:`, avec transport optionnel ;
- `TurnSharedSecret` : secret REST coturn, **uniquement côté serveur**,
à fournir par le gestionnaire de secrets ou la variable d'environnement
`AudioVideoCalls__TurnSharedSecret`, jamais dans le dépôt.
Linux GStreamer prend en charge `stun:`, mais pas `stuns:` : utiliser TURN/TLS
pour ce dernier besoin.
Les credentials TURN temporaires sont calculés côté serveur avec le
format REST coturn (expiration, nonce aléatoire et HMAC-SHA1). Aucun secret
de longue durée n'est envoyé aux clients. Aucun service TURN de production
n'est deploye automatiquement ; seuls les tests lancent un coturn isole.
Le [transport PostIt](../../src/PostIt/PostIt/Services/CallSignalingClient.cs)
utilise la connexion authentifiée du `ChatViewModel`, sans seconde connexion
ni interrogation HTTP. Il expose les commandes et événements typés et
signale les interruptions ; il ne capture aucun média.
Le panneau WebRTC de la page du chat et les deux adaptateurs natifs
consomment maintenant cette signalisation, toujours sans acceptation automatique.
### Travail restant pour la cible Internet multi-plateforme
- Valider les cameras, microphones et sorties audio Linux materiels.
- Valider les appels sur deux reseaux Internet distincts, UDP/TCP/TLS,
DNS, certificats et politiques de pare-feu de production.
- Ajouter si necessaire les commandes de sourdine, renegociation/ICE restart
et renouvellement des credentials pour les appels longs.
- Les groupes/SFU, Browser et les autres plateformes restent hors perimetre.
## Retour sur l'essai Android du 25 octobre 2026
Le laboratoire indépendant a été supprimé ; il ne constitue pas une base
de salles de discussion ni une implémentation de PostIt. La suite doit
réutiliser le ChatHub existant pour la signalisation.
L'essai en échec opposait un téléphone Android 15 arm64 à Chromium,
en mode TURN uniquement, avec signalisation HTTP locale et TURN/TCP
accessibles par redirections USB adb. Il n'utilisait ni ChatHub ni
PostIt.Desktop Linux.
Les observations doivent être distinguées :
- Camera2, la capture audio et un premier rendu EGL local ont démarré.
Cela ne valide ni le transport ni le rendu distant.
- Le processus Android a subi un SIGABRT dans
`libjingle_peerconnection_so.so`. Une première pile passait par
`PeerConnection.nativeAddIceCandidate` ; après modification du traitement
des candidats, un arrêt natif persistait sur `network_thread`.
- Le test a attendu un échange média qui n'est jamais arrivé. Le dernier
rapport Browser indiquait `connection: new`, zéro octet audio/vidéo et
aucune paire ICE sélectionnée ; aucun rapport Android n'a validé l'appel.
- Le problème a été reproduit avec les SDK libwebrtc 150.7871.04 et
144.7559.15. L'attente des descriptions distantes, la résolution du
`sdpMid` et l'ajout asynchrone des candidats n'ont pas suffi.
Il s'agit donc d'un **crash natif pendant la tentative d'établissement**,
pas d'un refus de codec ou d'un échec TURN identifié. Le dernier appel JNI
visible ne prouve pas la cause du crash. Sans message fatal détaillé ni
pile native symbolisée, un défaut du code expérimental, de son intégration
Java/JNI ou de libwebrtc reste à départager. Rien ne démontre une
impossibilité de WebRTC sur Android ou une défaillance du ChatHub.
Les essais Browser/GStreamer réussis utilisaient des sources synthétiques
et un décodage sans affichage côté GStreamer : ils ne valident pas
PostIt.Desktop Linux, ses périphériques réels ou son rendu Avalonia.
Ces limites de l'ancien laboratoire ne constituent plus le bilan du moteur
actuel : les nouvelles regressions Android/GStreamer ci-dessus verifient
des medias bidirectionnels et des rendus reels via TURN. La cause precise
du crash de cet ancien prototype reste inconnue ; aucun crash natif n'a
ete reproduit pendant les nouveaux essais. Cela ne remplace pas les
validations Internet et materielles encore indiquees.

View file

@ -20,12 +20,13 @@ clients.
| Annonce persistée | Entité `Notification` en base, API HTTP | Affichée dans le layout et masquable | Liste sur `HomePage`, chargée par HTTP et masquable |
| Message d'interface | Liste de portée requête dans `ViewBag.Notify` | Affichée comme alerte dans le layout | Non consommé |
| Événement de chat | Hub SignalR authentifié à `/chathub` | Le site Web n'en consomme pas dans ses vues MVC | `notifyUser` et `notifyRoom` alimentent les journaux du chat |
| Événement métier `push` | SignalR vers les connexions actives, plus e-mail | Pas de consommateur identifié dans les vues Web | Pas de gestionnaire `push` dans le client PostIt actuel |
| Événement métier `push` | SignalR vers les connexions actives, plus e-mail | Pas de consommateur identifié dans les vues Web | Alerte native par le service Android ; liste persistée sur l'accueil via HTTP |
| Alerte native Android | Connexion SignalR existante | Sans objet | Service de fond facultatif ; notification seulement à réception d'un événement |
Les notifications persistées sont donc différentes d'une notification système
native (notification du navigateur ou du système d'exploitation). Le client
PostIt affiche une liste dans sa page d'accueil ; il ne demande pas de
permission de notification native.
PostIt affiche une liste dans sa page d'accueil. Sur Android, le service de
messagerie peut aussi afficher des notifications natives, après autorisation.
## 1. Annonces persistées
@ -173,6 +174,7 @@ Les événements de notification émis par le hub comprennent notamment :
| `notifyRoom` | `type`, salon, utilisateur ou détail | Ajout au journal du salon ; met à jour la liste d'utilisateurs sur `UserJoin` |
| `joint` | `ChatRoomInfo` | Initialise la vue du salon rejoint |
| `ReceiveMessage` | message avec nom, salon et corps | Ajoute le message à l'historique du salon |
| `addPV` | expéditeur, texte privé | Ajoute le message privé au journal système ; alerte native Android en arrière-plan |
| `notifyUserInRoom` | `type`, salon, message | Pas de gestionnaire correspondant dans `ChatViewModel` actuellement |
Les constantes de types du chat sont déclarées dans
@ -181,23 +183,171 @@ Les messages `notifyUser` et `notifyRoom` ne sont pas enregistrés en base :
ils décrivent l'état temps réel de connexion, de salon ou les erreurs de
conversation.
Le [`ChatViewModel`](../../src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs)
Le singleton
[`ChatHubConnection`](../../src/PostIt/PostIt/Services/ChatHubConnection.cs)
ouvre le hub avec le jeton d'accès PostIt, tente un renouvellement silencieux
du jeton, et active la reconnexion automatique. Après reconnexion, il rejoint
à nouveau le salon sélectionné, car la connexion SignalR précédente et ses
groupes ne sont plus actifs. Les callbacks mettent à jour les collections sur
le thread UI d'Avalonia.
du jeton et active la reconnexion automatique. Il est partagé par le service
Android, le
[`ChatViewModel`](../../src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs)
et la signalisation des appels : ouvrir la page ne crée pas une seconde
connexion.
Le transport conserve en mémoire les 500 dernières livraisons de messages
privés et de salon pour les présenter si l'interface s'ouvre après le
démarrage du service. Ce tampon est borné, non persisté sur disque et vidé
à l'arrêt de la connexion ou au changement de compte. Il ne permet pas de
récupérer les messages envoyés lorsque le socket était déconnecté.
Les salons sont mémorisés localement, par hôte et compte, dans
`Settings.ChatRoomsByAccount`. Le transport les rejoint à nouveau après une
reconnexion ou un redémarrage du processus, sans dépendre de l'interface
Avalonia. « Quitter le salon » supprime cette mémorisation. Cela n'ajoute pas
d'abonnement serveur hors ligne ni d'historique des messages manqués.
Les callbacks destinés aux collections de l'interface sont dispatchés sur
le thread UI et les callbacks obsolètes sont ignorés après déconnexion.
### Événement métier `push`
En plus des événements du chat, `YavscMessageSender` utilise le même contexte
SignalR pour émettre `push` avec le topic et une charge utile sérialisée. Ce
nom d'événement est distinct de `notifyUser` et `notifyRoom`. Aucun
gestionnaire `push` n'est présent dans le client PostIt actuel : les annonces
métier persistées sont visibles dans PostIt lors du prochain chargement ou
rafraîchissement HTTP.
nom d'événement est distinct de `notifyUser` et `notifyRoom`. Le service
Android peut en afficher une alerte native ; les annonces métier persistées
restent visibles dans PostIt lors du prochain chargement ou rafraîchissement
HTTP.
## 5. Points d'attention pour les évolutions
## 5. Android : connexion SignalR en arrière-plan
### Réglage utilisateur et durée de vie
`AndroidKeepChatConnected`, désactivé par défaut, est éditable dans les
paramètres Android :
« Garder la connexion au serveur active et la reprendre au démarrage du
téléphone ». Enregistrer les paramètres pour appliquer le changement.
Lorsque l'utilisateur clique sur « Sauver » avec cette option activée,
PostIt vérifie `PowerManager.IsIgnoringBatteryOptimizations` :
- si l'application n'est pas exemptée, ouvrir
`ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` avec l'URI `package:...` ;
- si elle est déjà exemptée, ne rien ouvrir ni demander.
La permission `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` est déclarée pour
cette demande explicite. Android conserve la décision finale ; refuser
ne désactive ni l'option ni SignalR. Les sauvegardes internes (jetons,
salons), reconnexions et démarrages du téléphone n'ouvrent pas cet écran.
Cette demande directe d'exemption est soumise aux règles Google Play
applicables à l'usage de cette permission ; sa présence ne vaut pas
approbation pour la publication.
- **Désactivé** : le chat reste connecté pendant la vie du processus PostIt,
même si l'activité est masquée, mais rien ne garantit que ce processus
survive en arrière-plan. Les messages alimentent le journal ; les alertes
natives en arrière-plan nécessitent le service activé.
- **Activé** : un service Android ordinaire héberge la même connexion
SignalR, **sans notification permanente**. Un récepteur
`BOOT_COMPLETED` tente de reprendre ce service si l'option et une session
enregistrée sont encore disponibles.
- La fermeture d'une page ou de l'activité ne ferme pas la messagerie.
La déconnexion du compte arrête le service et la connexion avant la
suppression des jetons. Les appels et captures caméra/micro restent
soumis à leur propre cycle de vie.
- Le service peut démarrer sans construire l'interface Avalonia. L'ouverture
ultérieure de l'application réutilise le même conteneur et le même
transport, sans connexion doublonnée.
Le service n'appelle ni `StartForegroundService` ni `StartForeground` et ne
publie aucune notification de connexion/reconnexion. Pour l'arrêter,
désactiver l'option et enregistrer les paramètres, ou déconnecter le compte.
Les notifications ne sont créées que lors de nouveaux messages ou événements ;
elles disparaissent à leur ouverture et ne sont pas marquées permanentes.
Android 13+ demande l'autorisation `POST_NOTIFICATIONS` pour ces alertes
visibles. Un refus empêche les alertes, **pas la connexion SignalR**.
Les échecs de démarrage sont signalés, sans basculer silencieusement vers
un service de premier plan et sans répéter une permission refusée.
### Renouvellement de session
Une maintenance unique par client API démarre avec l'interface et aussi
avec le service Android démarré sans interface. Elle programme une attente
à partir de `AccessTokenExpiresAt` (échéance calculée depuis la durée fournie
par le serveur OIDC, ou le claim JWT `exp`), moins la marge de sécurité de
60 secondes, indépendamment des appels HTTP et des reconnexions SignalR :
- pendant l'activité Android visible (sur desktop, pendant l'exécution
de l'application), même si « Garder la connexion » est désactivé ;
- ou avec « Garder la connexion » activé, même si l'activité est masquée.
Le renouvellement utilise le `refresh_token` lorsque l'**access token**
entre dans sa marge d'expiration de 60 secondes. Les renouvellements
concurrents partagent le même verrou ; les jetons tournants sont
enregistrés et aucun renouvellement n'est engagé pendant la déconnexion.
Après chaque renouvellement, l'attente est recalculée avec la nouvelle
échéance. Connexion, déconnexion, changement d'activité ou de l'option
réveillent aussi l'ordonnanceur. Sans session ou lorsque les deux conditions
d'activité sont fausses, il attend un changement, sans contrôle périodique.
Un échec transitoire est signalé et retenté après 30 secondes ; un rejet
définitif exige une nouvelle connexion.
Le serveur ne fournit pas ici d'échéance du refresh token au client :
PostIt n'en invente pas et ne peut pas repousser sa durée de vie absolue.
La rotation régulière ne garantit pas de prolonger une session révoquée
ou arrivée à sa limite absolue. Un processus suspendu ou arrêté par Android
ne peut pas exécuter ce timer ; au retour, le renouvellement reprend si la
session reste renouvelable.
### Notifications et limites
Le service écoute les messages privés, les messages des salons rejoints et
l'événement métier SignalR `push`. En arrière-plan, il affiche des alertes
locales génériques pour ne pas exposer de contenu privé sur l'écran
verrouillé. Il ne faut pas confondre cet événement SignalR nommé `push` avec
un service de push externe.
**Aucun Firebase/FCM, serveur Google de notifications, jeton d'appareil,
configuration de projet ou migration push n'est requis.** Les API métier et
le ChatHub existants restent les seuls services réseau utilisés pour la
messagerie.
Cette solution est de type *best effort*, pas une connexion immortelle :
- Android, Doze, l'absence de réseau et les politiques des constructeurs
peuvent interrompre le socket ou empêcher le redémarrage du service.
Autoriser les données en arrière-plan permet le trafic réseau ; désactiver
manuellement l'optimisation de batterie pour PostIt assouplit les limites
de Doze. Ces réglages ne garantissent pas la survie du processus ou du
service et ne suppriment pas les autres limites d'exécution Android.
- Android 8+ peut arrêter un service ordinaire lorsque l'application reste
en arrière-plan, ou refuser `StartService` depuis le récepteur de démarrage.
Dans ce cas, PostIt signale le refus et attend une nouvelle ouverture de
l'application ; aucune tentative de contournement par service de premier
plan, tâche périodique ou exemption sans consentement n'est ajoutée.
- Après un arrêt forcé par l'utilisateur, rouvrir PostIt ; le démarrage du
téléphone n'est pas un contournement de cet arrêt.
- Le renouvellement nécessite une session encore valide. Une session
révoquée ou sans jeton de renouvellement exige une reconnexion.
- Les messages de chat sont éphémères : les messages envoyés pendant une
interruption ne sont pas récupérés par cette fonctionnalité. Les
notifications métier persistées restent accessibles par l'API.
- Aucun type `specialUse` ni permission `FOREGROUND_SERVICE_SPECIAL_USE`
n'est déclaré pour la messagerie. Les services de premier plan des appels
et captures caméra/micro restent inchangés : ils ne sont pas utilisés pour
maintenir le chat.
### Validation sur téléphone
Les tests locaux vérifient le partage de connexion, la restauration des
salons et le nettoyage de session. Ils ne remplacent pas une validation
Android réelle : absence de notification lors de l'activation et des
reconnexions, notification seulement à réception d'un événement activité
masquée, retour dans l'interface sans second socket, désactivation dans les
paramètres, déconnexion/reconnexion, coupure et retour réseau, veille
prolongée, redémarrage du téléphone et refus de permission sans arrêt du chat.
Une activité de vérification est incluse uniquement dans l'APK Debug :
`fr.pschneider.postit.ChatServiceTestActivity`. Son résultat est écrit dans
le fichier privé de l'application `files/chat-service-test-result.txt`.
Elle vérifie la composition du conteneur partagé, pas la réception réelle
après un démarrage ou une longue veille.
## 6. Points d'attention pour les évolutions
- Conserver les règles d'audience alignées entre l'API et le site Web ; en
particulier, appliquer un filtrage `Target` côté Web avant d'exposer les

View file

@ -20,7 +20,10 @@ L'authentification suit **RFC 8252 §7.1** (OAuth 2.0 for Native
Apps — Custom URI Scheme Redirect), pas le pattern loopback
historique. La séquence :
1. L'utilisateur clique **Se connecter** sur `LoginPage`.
1. Au démarrage, PostIt restaure la session silencieusement. Si cette
reprise échoue, il lance directement le login OIDC, sans confirmation.
Une nouvelle tentative peut aussi être lancée avec **Se connecter**
dans la modale d'authentification.
2. `YavscApiClient.LoginInteractiveAsync` demande à `OidcClient`
de calculer l'authorize URL et de la passer à
`CustomSchemeBrowser.InvokeAsync`.
@ -61,8 +64,8 @@ pas vers un serveur HTTP.
| `Services/CustomSchemeBrowser` | `IBrowser` OidcClient qui ouvre le système + attend le pipe. |
| `Services/SchemeUrlDetector` | Détection pure, testable, du `postit://callback` dans argv. |
| `Services/TokenStore` | Persiste `RefreshTokenRecord` (access/refresh/id + expiry). Mode 0600 sur POSIX. |
| `ViewModels/SessionStatusViewModel` | VM du bandeau persistant Connecté/Déconnecté + Logout. |
| `Views/SessionStatusBanner` | Bandeau affiché en haut de `MainWindow`, visible sur toutes les pages. |
| `ViewModels/SessionStatusViewModel` | État partagé de session, démarrage automatique, login/logout et liens de compte. |
| `Views/Layout/MainView` | Modale d'authentification superposée à la navigation, sans barre d'état persistante. |
## Plateformes (`PostIt.Desktop`, `PostIt.Android`, `PostIt.Browser`)
@ -78,8 +81,9 @@ Chaque plateforme injecte son propre `IBrowser` via
## UX observable
`LoginPage` affiche en continu la **phase** courante du flow
(badge `PhaseLabel`) en plus du `StatusMessage` textuel :
La modale affiche l'attente du navigateur et les erreurs de connexion.
Les actions sont désactivées pendant le login pour éviter les ouvertures
concurrentes. Le client expose aussi les phases suivantes à ses appelants :
| Phase | Signification |
|--------------------|------------------------------------------------------------------|
@ -89,7 +93,7 @@ Chaque plateforme injecte son propre `IBrowser` via
| `ExchangingCode` | Trade du `code` contre les tokens à `/connect/token`. |
| `Success` / `Error`| Issue du flow. |
Si le badge reste bloqué sur `OpeningBrowser`, **l'OS n'a jamais
Si le flow reste bloqué sur `OpeningBrowser`, **l'OS n'a jamais
relancé PostIt avec l'URL `postit://callback`** : le scheme
handler n'est pas enregistré correctement.
@ -100,19 +104,42 @@ Au boot, `App.OnFrameworkInitializationCompleted` :
1. Construit le `TokenStore` (~/.config/PostIt/tokens.json) et
`YavscApiClient`. Ce dernier charge `_tokens = store.Load()`
dans son constructeur.
2. Ouvre `MainWindow` avec `HomePage` comme racine.
3. Sur l'événement `Opened`, appelle `TrySilentLoginAsync` :
2. Crée la racine `MainView` et démarre la maintenance de session.
3. À l'initialisation de la racine, appelle `TrySilentLoginAsync` une
seule fois par processus :
- si l'access token a encore `> RefreshSkew` (60 s) de vie →
`Success` immédiat, push `MainPage`.
`Success` immédiat.
- sinon, tente un refresh via le refresh token. Si l'IdP
accepte → push `MainPage`. Si l'IdP rejette (révocation,
vol, expiration du refresh) → `_store.Clear()`, retour à
`HomePage`.
accepte → la session est restaurée. Un rejet permanent
(`invalid_grant` / `invalid_client`) purge le store ; une erreur
temporaire conserve les jetons pour une nouvelle tentative.
- sans session restaurée, lance immédiatement le login interactif.
4. Initialise la messagerie et affiche `HomePage` si la pile est vide.
Le bandeau `SessionStatusBanner` reflète `Api.HasValidSession`
en continu et expose le bouton **Se déconnecter**, qui appelle
`Api.LogoutAsync()` (purge du store) puis `PopToRootAsync`
pour ramener sur `HomePage`.
La maintenance renouvelle les jetons 60 secondes avant expiration,
sans attendre un appel API. Les échecs temporaires sont retentés après
30 secondes ; la reprise d'activité réveille également la maintenance.
L'option Android de maintien en arrière-plan conserve son comportement.
Un échec de login ou de renouvellement, l'expiration sans refresh token,
une déconnexion explicite ou un 401 authentifié persistant après la
tentative de refresh affiche la modale de `MainView`. La navigation en
dessous est désactivée et le clavier reste dans la modale. Celle-ci
défile sur les petits écrans et propose :
- **Se connecter** : nouveau flow OIDC/PKCE ;
- **Créer un compte** : navigateur sur `Account/Register` de l'autorité ;
- **Mot de passe oublié** : navigateur sur `Account/ForgotPassword`
de la même autorité configurée.
Les liens conservent l'éventuel préfixe de chemin de l'autorité.
L'ouverture d'un lien de compte ne valide pas une session : l'utilisateur
revient ensuite sur **Se connecter**. Un renouvellement silencieux réussi
ferme la modale sans changer la page ni les brouillons.
**Paramètres**, **À propos** et **Se déconnecter** sont dans le menu
secondaire de l'accueil. La déconnexion purge le store puis ramène la
navigation à l'accueil ; elle ne relance pas le navigateur automatiquement.
## Garanties testées
@ -125,9 +152,13 @@ pour ramener sur `HomePage`.
case-insensitive, refuse les faux positifs (`postit-…://`),
retourne le premier match de manière déterministe.
Le chemin "refresh token rejeté → purge du store" est testé
manuellement ; le stub `OidcStubAuthority` ne sait pas encore
rejeter un refresh token précis — extension future.
- Démarrage sans session, avec session valide et après refresh silencieux.
- Rejet du refresh token, erreur temporaire puis reprise, expiration sans
refresh token, refus 401 persistant et déconnexion explicite.
- Modale en portrait compact et paysage bas : actions accessibles par
défilement, navigation bloquée, restauration du focus et de la page.
- Liens de création de compte et de récupération du mot de passe sur
l'autorité configurée, y compris avec un préfixe de chemin.
## Voir aussi

View file

@ -12,6 +12,13 @@
## Surface : un code-base, trois front-ends
Le projet Android active `EmbedAssembliesIntoApk` par défaut, y compris en
Debug : un APK installé directement doit contenir les assemblies .NET,
sans dépendre des fichiers de Fast Deployment sous `files/.__override__`.
Sans elles, le runtime Android abandonne avant de charger l'interface
avec « No assemblies found ». Le Makefile conserve également ce réglage
explicite pour ses commandes de compilation.
```
┌────────────────────────┐
│ PostIt (lib) │
@ -40,6 +47,21 @@ spécifiques (IntentFilter Android, `app.manifest` Desktop).
Toute la logique (VM, services, navigation, settings, OIDC) est
dans le code-base partagé.
## Abonnements PayPal
La page native **Mon abonnement PayPal** est accessible depuis l'accueil,
le profil et « À propos ». Elle utilise `ResourceSubscriptionsApiClient`
avec l'autorité OIDC configurée pour charger les offres, l'abonnement en
cours et le solde. Les prix HT/TTC, la TVA et les droits proviennent du serveur.
La création ou reprise de souscription utilise la session bearer de PostIt ;
seule l'approbation est ouverte dans le navigateur, sur un domaine PayPal HTTPS.
Après approbation ou abandon, l'utilisateur revient dans PostIt et utilise
**Actualiser les paiements et mon solde**. Ni l'ouverture du navigateur ni
la page de retour ne prouvent un paiement : seul le rapprochement serveur
des transactions vérifiées accorde les droits. La résiliation demande une
confirmation explicite et conserve les droits des périodes déjà payées.
La configuration serveur et les routes sont décrites dans [INSTALL.md](../../INSTALL.md).
## Reprise Android
`IActivityApplicationLifetime.MainViewFactory` crée une nouvelle `MainView`
@ -53,12 +75,56 @@ Le rafraîchissement silencieux de session reste unique par processus.
Cette restauration couvre la recréation d'activité dans le même processus,
pas la destruction du processus par Android.
## Prévisualisation et orientation des Podcasts
« Prévisualiser la caméra » ouvre un aperçu local avant « Démarrer le
direct », sans exiger de titre. Cette phase ne crée aucune émission côté
serveur, n'enregistre aucun segment et n'ouvre pas le microphone. Le choix
de caméra est verrouillé pendant l'aperçu ; l'arrêter pour changer de caméra.
Le microphone sélectionné n'est ouvert qu'au démarrage du direct.
« Arrêter la prévisualisation », la sortie de page et la déconnexion libèrent
la caméra. Le passage au direct ferme d'abord l'aperçu, puis ouvre la capture
avec les périphériques sélectionnés : les images d'essai ne sont pas publiées.
Sous Android, un aperçu seul s'arrête aussi au passage en arrière-plan,
sans lancer de service de capture ni de notification de direct.
Les Podcasts en direct conservent leur service caméra/microphone existant.
Le chemin Android partage le rendu Camera2/EGL entre aperçu seul et encodage.
L'arrêt de l'aperçu détache ses callbacks via le `SurfaceHolder` conservé,
avant la destruction différée du contrôle natif ; le nettoyage ne relit pas
la propriété `Holder` d'une `SurfaceView` dont le wrapper Java peut être libéré.
La rotation physique utilise l'orientation du capteur, la caméra avant/arrière
et la rotation de l'écran. Camera2 peut déjà inclure la rotation du capteur
dans la matrice `SurfaceTexture`, ainsi qu'un miroir pour la caméra avant :
seule la rotation restante est appliquée, dans le sens inverse si la matrice
contient un miroir, afin de ne pas tourner l'image deux fois.
Un changement de rotation d'écran recalcule ce rendu pendant la capture.
L'aperçu conserve les proportions ; les dimensions encodées restent celles
du démarrage du direct, avec des bandes noires si la nouvelle orientation
l'exige, pour ne pas modifier le format HLS/SRTP en cours d'émission.
Les tests partagés couvrent l'aperçu sans appel API, le passage au direct,
les arrêts et une sortie de page pendant l'ouverture de caméra. L'activité
Debug `CameraFrameRotationTestActivity` vérifie les quatre rotations avec
encodage, puis l'aperçu sans encodeur et ses changements de rotation.
Une validation physique caméra avant/arrière en portrait et paysage reste
nécessaire : les tests synthétiques ne vérifient pas le comportement du HAL
de chaque téléphone.
## Administration et profil personnel
Le quota disque renvoyé par le profil est le quota effectif : Découverte donne
deux fois et Premium cinq fois le quota gratuit standard durant la mensualité confirmée payée,
y compris après résiliation jusqu'à son échéance UTC. Ensuite, ou après
remboursement, le quota habituel reprend sans suppression des fichiers.
Les téléversements dépassant l'espace disponible sont refusés avant écriture.
La taille maximale par fichier et les quotas podcast restent inchangés.
L'accueil présente un seul accès **Administration**, visible et exécutable
uniquement pour le rôle exact `Administrator`. `SessionStatusViewModel.RefreshAsync`
lit les rôles dans `GET account/me` après le rafraîchissement de session ;
une erreur de lecture masque l'accès et affiche une erreur dans la bannière.
une erreur de lecture masque l'accès et affiche une erreur sur l'accueil.
La déconnexion invalide aussi les vérifications de droits encore en vol.
`AdministrationPage` regroupe sept onglets : utilisateurs, usages globaux,
@ -75,6 +141,50 @@ indépendamment de la visibilité du bouton dans PostIt.
endpoints `account/me` pour lire et enregistrer les informations personnelles.
Elle affiche aussi `resource-usage/me`, sans appeler la liste des usages
globaux. Une indisponibilité de l'usage n'empêche pas la gestion du profil.
La consommation est chargée avant le profil, pour rester consultable même
si une opération de gestion reçoit un refus de quota. L'administration
charge également les usages avant ses autres outils et les conserve sur
un refus HTTP 429, tant que le rôle administrateur est toujours présent.
L'indicateur est exprimé en points selon les coefficients effectifs du
backend, présentés dans les CGU. Le stockage correspond aux volumes
instrumentés ajoutés, moins les volumes individuellement suivis supprimés
ou remplacés. Les anciens fichiers sans suivi ne sont pas remboursés.
La suppression reste disponible au seuil ; CPU, appels API et transferts
ne sont pas remboursés. Les renommages conservent le suivi individuel.
Le profil et les vues d'administration affichent le seuil effectif, le
solde et l'atteinte du quota, indépendamment de l'estimation financière.
La section serveur `ResourceUsage` configure les coefficients et les
seuils individuels ; voir [INSTALL.md](../../INSTALL.md#resource-consumption-and-cgu).
Le contrôle admet les coûts connus puis constate les coûts restants :
il bloque les opérations suivantes, sans interrompre strictement celles
déjà en cours.
Au franchissement de 50 %, 75 %, 90 %, 95 % ou 99 % de la limite personnelle,
le serveur enregistre une notification privée `user/{UserId}`, visible dans
les notifications de l'accueil lors de leur prochain chargement. Le calcul
porte sur le total pondéré net des crédits, pas sur chaque compteur séparé.
Une mise à jour franchissant plusieurs paliers ne produit que l'avertissement
du plus haut palier atteint ; rester au-dessus ne répète pas l'alerte.
Après une baisse sous un palier (crédit ou suppression de stockage suivi),
un nouveau franchissement produit une nouvelle notification, même si la
précédente a été fermée. Les notifications et le comptage sont enregistrés
ensemble ; aucune migration de schéma n'est nécessaire.
La lecture et la fermeture des notifications restent accessibles au quota
atteint et ne consomment pas de points. Aucun email ni push immédiat n'est envoyé.
La page **À propos** ouvre les CGU dédiées de PostIt et de Yavsc sur
`Home/CGU` auprès de l'autorité configurée, y compris sans session.
Cette page publique présente les coefficients réellement configurés,
la période cumulée, le seuil et les limites de la mesure.
**Mon profil** et **À propos** proposent aussi un lien vers
`ResourceSubscription` sur cette même autorité. La souscription mensuelle
et la résiliation PayPal utilisent la session Web et des formulaires
antiforgery ; PostIt ne stocke ni identifiant marchand ni secret PayPal.
Le profil affiche la consommation brute, l'usage effacé et le crédit
reporté, en plus de l'indicateur net. Les crédits Découverte/Premium ne
suppriment pas les compteurs : les paiements confirmés sont rapprochés
par Yavsc.Org et leur déduction est appliquée aussi au quota API/Blogs.
### Outils d'administration du site
@ -320,7 +430,7 @@ le DI est construit. Ordre, dans cet ordre :
| `SettingsPage` | **Singleton** | Une seule instance pour la vie de l'app : le `DataContext` est câblé une fois au boot, le push est idempotent (cf. section *Garde anti-empilement* ci-dessous). |
| `MainPage` / `HomePage` / `SignaturePage` | Transient | Résolution à la demande par le `ViewLocator`. |
| `MainPageViewModel` / `HomePageViewModel` / `SignaturePageViewModel` | Transient | VM reconstruites à chaque navigation ; pas d'état partagé à conserver. |
| `SessionStatusViewModel` + `SessionStatusBanner` | Singleton + Transient | Le VM est un singleton (survit à la navigation), le bandeau est transient (réinstancié quand la fenêtre le recrée). |
| `SessionStatusViewModel` | Singleton | État partagé de session ; la modale de `MainView` survit fonctionnellement à la navigation et à la recréation d'activité via ce VM. |
> **Invariant** : `Settings` est **uniquement** un singleton. Un
> `AddTransient<Settings>()` supplémentaire (qui réécrase le
@ -339,7 +449,8 @@ de modifier cette répartition. La liste et l'article défilent séparément.
Lorsque la largeur de la fenêtre atteint ou dépasse sa hauteur, le lecteur
ou l'éditeur passe à gauche (deux tiers de la largeur par défaut), et
l'en-tête, la recherche, les commandes et la liste passent à droite.
l'en-tête, la recherche et la liste passent à droite ; les commandes
restent dans la barre de navigation.
Le séparateur devient vertical. En portrait, la disposition verticale
revient sans recréer les contrôles ni perdre le brouillon.
Le seuil utilise les dimensions clientes de la fenêtre, indépendamment
@ -358,6 +469,41 @@ dépasser le viewport pour que les barres automatiques s'activent.
Ne pas placer cette grille dans un `StackPanel` vertical ou un
`ScrollViewer` de page, qui lui donnerait une hauteur de mesure illimitée.
Après un redimensionnement de la zone de texte (notamment à l'ouverture du
clavier Android avec `AdjustResize`), l'éditeur remet le curseur dans son
viewport après la mise en page, uniquement s'il garde le focus. Un toucher
dans la zone éditable demande aussi le clavier via le pont natif Android,
sans retirer puis redonner le focus ni modifier la sélection. Les autres
plateformes conservent leur gestion habituelle du clavier.
`MainView` compose les marges de `TopLevel.InsetsManager` (barres système
et découpes) avec le recouvrement réel indiqué par `TopLevel.InputPane`,
car le clavier ne redimensionne pas toujours la fenêtre Android en mode
edge-to-edge. Si `AdjustResize` a déjà réduit la fenêtre, cette réserve
ne soustrait pas une seconde fois la hauteur du clavier. La racine gère
explicitement ces marges et désactive `TopLevel.AutoSafeAreaPadding` pour
éviter deux propriétaires du même padding. Ne pas remplacer les marges
système par un padding contenant uniquement la hauteur du clavier.
En disposition large, tant que le clavier est ouvert et que l'article
garde le focus, son titre et ses pièces jointes passent dans
une colonne à côté du texte. La barre de commandes, la bannière de session
et le statut restent visibles. La disposition habituelle revient à la
fermeture du clavier ou au changement de focus, sans recréer le brouillon.
Sous Android uniquement, le champ du titre est masqué pendant la saisie
compacte avec le clavier ouvert, en portrait comme en paysage ; il réapparaît à la fermeture du clavier
ou quand le focus quitte l'article. Sa valeur n'est jamais effacée.
En Debug Android, `fr.pschneider.postit.MarkdownEditorTestActivity` ouvre
un billet synthétique local, vérifie au moins trois lignes visibles et
le bas de l'éditeur au-dessus des insets natifs du clavier et les contrôles
en dehors des barres système,
ferme puis rouvre le clavier par toucher sans perte de focus. Le résultat
est écrit dans `files/markdown-editor-test-result.txt`. Ce test nécessite
Android 11 ou plus pour vérifier les insets du clavier ; il ne publie
aucun billet et retire sa page à la fin.
L'extra booléen `landscape=true` force le paysage pendant le test et restaure
l'orientation demandée précédemment à la fin.
## Navigation
Le host de navigation est un `NavigationPage x:Name="NavRoot"`
@ -475,7 +621,7 @@ pour `[RelayCommand]`".
| Page | DataContext | Rôle |
|----------------------------|--------------------------|-----------------------------------------------------------------------|
| `MainWindow` | `HomePageViewModel` (initial) | Host de la `NavigationPage`. |
| `SessionStatusBanner` | `SessionStatusViewModel` | Bandeau persistant en haut de la fenêtre, visible sur toutes les pages. Boutons Login / Logout / Paramètres. |
| Modale de `MainView` | `SessionStatusViewModel` | Connexion requise : login, inscription et mot de passe oublié. Navigation bloquée jusqu'à la reprise de session ; aucune barre d'état persistante. |
| `HomePage` | `HomePageViewModel` | Page d'accueil publique. |
| `MainPage` | `MainPageViewModel` | Éditeur de post de blog (après login). |
| `SignaturePage` | `SignaturePageViewModel` | Capture de signature (estimateur). |

173
doc/plan-test-cleanup.md Normal file
View file

@ -0,0 +1,173 @@
# Plan de nettoyage de la suite PostIt
## Objectif
Rendre la suite PostIt plus rapide, plus fiable et plus lisible, sans bloquer le développement quotidien par des tests dépendants d’un matériel, d’un binaire externe ou d’un environnement local spécifique.
## Problème actuel
La suite a grossi sans vraie séparation entre :
- tests rapides et déterministes,
- tests UI headless,
- tests d’intégration,
- tests dépendants de l’environnement,
- tests Android / native / device-specific.
Résultat : la routine par défaut devient bruitée et peu fiable, et les sujets de fond (comportement métier) sont noyés dans des tests exigeants en dépendances système.
## Plan proposé
### 1. Séparer la suite par catégorie de dépendance
Les tests doivent être classés selon leur coût et leur dépendance externe, avec des annotations de classe xUnit du type :
```csharp
[Trait("Category", "Native")]
[Trait("Category", "Slow")]
public sealed class PodcastNativeCaptureTests
```
Et pour les tests Android :
```csharp
[Trait("Category", "Android")]
public class AndroidAppLaunchTests
```
- Fast unit tests
- Headless UI tests
- Integration tests
- Native / environment-dependent tests
- Android-only tests
La règle doit être simple : un test ne doit entrer dans la routine par défaut que s’il est exécutable sans matériel, binaire externe ni fichier de test local spécifique.
### 2. Garder la routine par défaut “portable”
La suite standard de développement doit couvrir uniquement :
- les comportements métier,
- les flux UI sans environnement spécifique,
- les tests reproductibles sans dépendances natives.
Les tests qui exigent :
- LibVLC,
- ffprobe / codecs,
- fichiers médias locaux,
- Android emulator / adb,
- services device-bound,
doivent être exclus de la routine standard.
### 3. Isoler les tests non-portables
Les tests dépendants de l’environnement doivent être déplacés ou séparés dans une catégorie spécifique, par exemple :
- `Native`
- `Android`
- `Slow`
Cela permet de conserver la signalisation de leur objectif sans polluer la suite principale.
### 4. Nettoyer les doublons fonctionnels
Les tests qui vérifient le même comportement avec seulement de légères variantes doivent être regroupés, fusionnés ou simplifiés.
Règle de qualité :
- 1 test = 1 comportement clair,
- 1 titre = 1 intention claire,
- 1 appel de fonction = 1 vérification utile.
### 5. Structurer les tests par feature et par niveau
Exemple de structure suggérée :
- `PostIt.Tests/Fast/`
- `PostIt.Tests/Headless/`
- `PostIt.Tests/Integration/`
- `PostIt.Tests/Native/`
- `PostIt.Tests/Android/`
Cette structure permet de distinguer immédiatement les tests de comportement des tests d’infrastructure.
### 6. Séparer la CI en deux niveaux
- CI standard / PR : tests rapides + headless
- CI nocturne / full : tests native + Android + integration lourde
Cela permet d’avoir un cycle de développement rapide sans sacrifier une vraie validation dans les scénarios spécifiques.
## Catégorisation cible des tests
Important : les catégories xUnit ne doivent être appliquées qu’aux vraies classes de test. Les `Activity` Android utilisées comme harness de test ne sont pas des classes de test et ne doivent pas porter de `[Trait("Category", ...)]`.
### Native
Classes de test xUnit qui dépendent de LibVLC, de fichiers multimédia locaux, de codecs ou d’un support natif Linux/OS spécifique.
- `LinuxLanCallMediaTests`
- `PodcastNativeCaptureTests`
- `PodcastReplayTests`
- `WebRtcCallViewModelTests` — sous-cas natif activé avec `POSTIT_TEST_NATIVE_WEBRTC=1`
### Android
Classes de test xUnit qui tournent sur un contexte Android spécifique, sur `adb`, sur un émulateur ou sur un device Android réel.
- `AndroidAppLaunchTests`
### Slow
Classes de test xUnit lourdes ou lentes, souvent partielles sur le flux média, la capture ou la lecture de données. Elles doivent être explicitement marquées comme `Slow` pour ne pas polluer la suite standard.
- `PodcastNativeCaptureTests`
- `PodcastReplayTests`
- `LinuxLanCallMediaTests`
- `WebRtcCallViewModelTests` — variante native / réseau / media-heavy
### Harness Android de support (non test classes)
Ces classes servent à déclencher un test Android dans un `Activity` dédié, mais elles ne sont pas des classes xUnit de test et ne portent pas de trait de catégorie.
- `AndroidCameraFrameRotationTestActivity`
- `AndroidChatServiceTestActivity`
- `AndroidLanCallTestActivity`
- `AndroidMarkdownEditorTestActivity`
- `AndroidPodcastBlurTestActivity`
- `AndroidPodcastCaptureTestActivity`
- `AndroidScreenAwakeTestActivity`
- `AndroidWebRtcTestActivity`
### Tests non-portables à sortir de la routine par défaut
Les classes de test ci-dessous dépendent d’un environnement local spécifique, d’un binaire externe ou d’un matériel Android / native. Elles ne devraient pas faire partie de la routine quotidienne standard.
- `AndroidAppLaunchTests`
- `LinuxLanCallMediaTests`
- `PodcastNativeCaptureTests`
- `PodcastReplayTests`
- `WebRtcCallViewModelTests` — cas native spécifique avec `POSTIT_TEST_NATIVE_WEBRTC=1`
## Exemples de dépendances qui rendent ces tests non-portables
- `POSTIT_TEST_MEDIA`
- `POSTIT_TEST_TS`
- `POSTIT_TEST_REPLAY`
- `POSTIT_TEST_NATIVE_WEBRTC`
- `adb` / appareil Android connecté
- LibVLC installé avec les codecs nécessaires
- fichiers vidéo/audio locaux
- machines Linux spécifiques
## État souhaité
Une suite PostIt propre doit avoir :
- une routine standard courte et stable,
- des tests natifs clairement isolés,
- une séparation nette des responsabilités,
- un signal de qualité lisible pour les contributeurs.

View file

@ -31,6 +31,92 @@ bug : ils doivent être **rouges avant le fix, verts après**, et
continuer à **casser** si quelqu'un revert le fix. Pas de test
qui passe à vide.
## Selection des tests serveur
Toutes les classes de tests des projets `Yavsc.Org.Tests`, `Yavsc.Api.Tests`,
`Yavsc.Blogs.Tests` et `Yavsc.Server.Tests`, sous `src/test/`, portent
`[Trait("Category", "non-reg")]`, y compris celles qui heritent de tests.
Conserver ce trait sur toute nouvelle classe de tests ; les fixtures et
les helpers sans tests n'en ont pas besoin. Les autres traits restent inchanges.
Avec le runner Microsoft.Testing.Platform et le SDK .NET 10 :
```bash
dotnet test --project src/test/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj \
--filter-trait 'Category=non-reg'
```
Remplacer le projet pour executer les trois autres suites. Le trait couvre
aussi les tests d'integration qui requierent leurs services/configurations ;
il ne supprime ni ces prerequis ni les exclusions d'autres traits.
Ajouter `--list-tests` pour verifier la selection sans executer les tests.
### Remise a zero SQLite des tests API
`ApiWebServerFixture` conserve une connexion d'ancrage vers la base SQLite
en memoire partagee. `EnsureDeleted()` ne vide pas cette base tant que cette
connexion reste ouverte. Le reset supprime donc les tables, puis recree
explicitement le schema avant le peuplement ; `EnsureCreated()` seul ne suffit
pas car SQLite conserve sa table interne `sqlite_sequence`.
Les cles etrangeres sont desactivees uniquement pendant la suppression et
reactivees en `finally`. Le nettoyage PostgreSQL reste distinct.
`ResetAndSeedHaircutGraph()` inclut le catalogue de trois prestations, une
commande `brush` et une commande groupee `mbrush`, toutes deux pour Alice.
Les tests de facturation s'appuient sur ces commandes initiales ; les tests
CRUD creent et manipulent leurs propres commandes par identifiant.
## Isolation des tests PostIt
L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans
parallelisme. Les tests `[AvaloniaFact]`/`[AvaloniaTheory]` reinitialisent le
runtime Avalonia entre tests ; des tests ordinaires utilisent aussi
`App.Current` et les delegates statiques de `Platform`. Leur execution
concurrente peut creer le dispatcher sur un autre thread ou utiliser une
application appartenant a un test headless en cours, avec une erreur de
thread UI signalee comme `Test Case Cleanup`.
Conserver provisoirement cette isolation dans `Fixtures/TestApp.cs`. Les tests qui exercent
intentionnellement plusieurs operations concurrentes peuvent toujours le faire
dans leur propre methode ; les autres assemblees de tests ne sont pas affectees.
### Migration progressive vers une fixture UI
La collection `[Collection(AvaloniaUiCollection.Name)]` fournit
`AvaloniaUiFixture` par injection de constructeur. La fixture possede sa
session `HeadlessUnitTestSession`, initialise le runtime sur son thread UI et
arrete ce thread a la fin de la collection. Les tests migres utilisent `[Fact]`
ou `[Theory]`, pas `[AvaloniaFact]` : la fixture assure elle-meme le dispatch.
`RunAsync` execute du code sur le thread UI. `WithWindowAsync` cree le contenu
et la fenetre sur ce thread, affiche la fenetre, effectue le layout, puis la
ferme et detache ses bindings en `finally`, meme si une assertion echoue :
```csharp
[Collection(AvaloniaUiCollection.Name)]
public sealed class ExampleTests(AvaloniaUiFixture ui)
{
[Fact]
public Task Page_is_visible() => ui.WithWindowAsync(
() => new TextBlock { Text = "Example" },
window =>
{
Assert.True(window.IsVisible);
return Task.CompletedTask;
},
TestContext.Current.CancellationToken,
width: 640, height: 480);
}
```
Le pilote est `SubscriptionsPageTests`. Le thread est conserve pour la
collection, mais l'application reste isolee **par dispatch** : conserver une
application unique des maintenant changerait l'isolation des anciens tests
et risquerait de partager navigation, services et preferences. Ne pas conserver
de controles entre dispatchs dans les tests metier. La protection globale
contre le parallelisme reste necessaire tant que les autres consommateurs
d'Avalonia et de l'etat statique ne sont pas migres.
## EF Core en test
Pour les tests qui ont besoin d'un `ApplicationDbContext`, on
@ -78,24 +164,62 @@ pour éviter de monter un host complet.
Avec le runner Microsoft.Testing.Platform du depot (.NET 10, xUnit v3) :
```bash
dotnet test --project src/test/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj \
--filter-class '*PodcastWebTests' --filter-class '*PerformerDonationTests'
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj \
--filter-class '*LiveProcessorTests' --filter-class '*PodcastControllerTests'
--filter-class '*LiveProcessorTests' --filter-class '*PodcastControllerTests' \
--filter-class '*PodcastReplayTests' --filter-class '*PodcastScheduleTests' \
--filter-class '*PerformerDonationSettingsTests'
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-class '*PodcastTests' --filter-class '*PodcastNativeCaptureTests'
--filter-class '*PodcastTests' --filter-class '*PodcastReplayTests' \
--filter-class '*YavscApiClientTests' --filter-class '*PodcastNativeCaptureTests' \
--filter-class '*PerformerDonationSettingsTests'
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-method '*Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal'
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-class '*PodcastScheduleTests'
```
Les tests serveur couvrent HTTP/authentification, proprietaire, sequences,
reprises idempotentes, limites exactes, concurrence et persistance des replays
apres interruption/redemarrage, dans des dossiers temporaires isoles.
Les tests de configuration PayPal couvrent la lecture privee, la creation,
la validation avant toute sauvegarde, l'effacement, la compatibilite des anciens
clients, ainsi que le chargement, la liaison du champ et l'enregistrement PostIt.
Les tests `PodcastScheduleTests` couvrent la preparation persistante dans
`LiveFlow`, la confidentialite, l'annonce/unpublication, les controles
proprietaire, la validation et le demarrage manuel idempotent.
La preparation PostIt et les tests de capture headless ont ete verifies
separement : leur selection groupee peut rester bloquee alors que chaque
test cible reussit isole.
Installer FFmpeg 5+ et ffprobe pour ces tests serveur : ils generent une
source H.264/AAC synthetique de quatre secondes, verifient le remuxage reel
(pistes, duree, faststart, decodage et seek a deux secondes), puis les reponses
HTTP authentifiees GET/HEAD/206/416 du worker. Aucune camera ni microphone
n'est utilise. Les tests client couvrent les plages exactes et bornees,
les seeks avant/arriere/EOF, l'annulation, le renouvellement des jetons
et le seuil exact d'auto-hide de trois secondes.
Pour tester aussi le decodage MP4 et les seeks avant/arriere dans LibVLC,
definir `POSTIT_TEST_REPLAY` sur un MP4 H.264/AAC local de 8 a 30 secondes
(LibVLC installe sur la machine de test). Le test natif est ignore sinon.
Verifier manuellement les overlays sur Desktop et Android : pause/reprise,
glissement de la barre, masquage apres trois secondes, reapparition au
toucher/survol et nettoyage apres navigation ou mise en arriere-plan.
Les tests natifs sont explicitement ignores sans `POSTIT_TEST_MEDIA`.
Pour les activer, installer LibVLC avec ses encodeurs H.264/AAC et definir
cette variable sur un fichier video local d'environ huit secondes contenant
une piste audio. Ils exercent la segmentation LibVLC reelle, l'envoi et la
reprise apres acquittement perdu, le dernier segment apres arret et le
decodage authentifie du replay. Aucun FFmpeg n'est requis par ces tests ni
par l'application (le fichier d'entree peut provenir de n'importe quelle source).
decodage authentifie du replay MPEG-TS. FFmpeg n'est pas une dependance
d'execution de PostIt (le serveur MP4, lui, en a besoin).
Les tests materiels camera/microphone Windows/Linux restent manuels.
Les deux variantes du test d'encodage HLS (avec/sans apercu) necessitent
egalement `ffprobe` pour verifier independamment les pistes H.264 et AAC
du premier segment. La variante avec apercu attend une image decodee
par LibVLC dans un tampon memoire, sans ouvrir de camera ni diffuser le son
sur les haut-parleurs. Le test de page headless verifie aussi le binding
du controle d'apercu et son retrait avant liberation de la capture.
### Rotation de la capture Android
@ -118,10 +242,20 @@ adb shell am start -n fr.pschneider.postit/fr.pschneider.postit.CameraFrameRotat
adb shell run-as fr.pschneider.postit cat files/camera-rotation-test-result.txt
```
Pour un telephone ARM64, ajouter `-r android-arm64` au build et installer
l'APK de `bin/Debug/net10.0-android/android-arm64/`. Le projet transmet ce RID
aux targets natives LibVLC : l'APK doit contenir `libvlc.so` et
`libc++_shared.so`. Utiliser `adb -s <serial>` si plusieurs appareils sont
connectes. Laisser l'appareil deverrouille et les tests au premier plan ;
ne lancer le test suivant qu'apres `PASS` ou `FAIL`.
Attendre la fin du test : `RUNNING` doit devenir `PASS`. Il encode quatre
quadrants colores en MPEG-TS pour 0, 90, 180 et 270 degres, decode une image et
verifie les dimensions (640x480 ou 480x640) et les couleurs aux quatre positions.
La tolerance de chaque composante RGB est de 40 pour tenir compte de H.264.
Il verifie aussi les couleurs RGBA de l'apercu OpenGL (tolerance 5), les
bandes noires sans deformation et le detachement/rattachement de sa surface
pendant l'encodage, toujours pour les quatre rotations.
Une erreur de rendu, d'encodage, de decodage ou de comparaison produit `FAIL`
avec l'exception. Cette activite est exclue des builds Release.
@ -134,6 +268,17 @@ adb shell am start -n fr.pschneider.postit/fr.pschneider.postit.PodcastCaptureTe
adb shell run-as fr.pschneider.postit cat files/podcast-capture-test-result.txt
```
Pour verifier la transition apercu vers diffusion sans contacter le serveur :
```bash
adb shell am start -S -n fr.pschneider.postit/fr.pschneider.postit.PodcastCaptureTestActivity --es microphone false --es previewTransition true
```
Cette variante affiche puis retire deux apercus natifs avant la capture :
nettoyage normal, puis nettoyage apres liberation du wrapper Java de la vue.
Elle attend la destruction differee Avalonia et verifie que la capture suivante
produit toujours des segments. Le resultat doit inclure `previewTransition=True`.
Attendre `PASS` : au moins trois segments, 8 a 16 secondes capturees,
pistes H.264 et AAC presentes, et progression des segments en arriere-plan.
Ce test detecte notamment les captures de zero seconde dues au decalage entre
@ -143,13 +288,36 @@ Le resultat inclut les angles capteur/ecran et la premiere matrice
SurfaceTexture recue. Les tests unitaires couvrent notamment la matrice
reelle `[0,-1,0,0,-1,0,0,0,0,0,1,0,1,1,0,1]` : pour un capteur a 90 degres
et un ecran a 0, elle porte deja la rotation et ne doit pas recevoir 90 degres
supplementaires. Le test synthetique seul ne detecte pas cette double rotation.
supplementaires. La camera avant mesuree
`[0,-1,0,0,1,0,0,0,0,0,1,0,0,1,0,1]` (capteur a 270 degres) contient en plus
un miroir : la rotation restante y est appliquee dans le sens inverse.
Le test synthetique seul ne detecte pas cette double rotation.
Verifier aussi manuellement les cameras avant/arriere en portrait et paysage,
le son, le direct et le replay, et la poursuite de l'emission en arriere-plan.
L'orientation est fixee au demarrage d'une emission ; tourner le telephone
pendant l'emission ne reconfigure pas le format encode.
### Anti-veille Android
`ScreenAwakeRequestsTests`, `PodcastPreferencesTests` et les regressions
d'apercu de `PodcastBroadcasterTests` couvrent les demandes independantes,
leur liberation, le changement d'option pendant la capture et sa persistance.
Le test natif Debug utilise une video MP4 H.264 locale synthetique, sans API,
camera ni microphone :
```bash
adb push /chemin/video-test.mp4 /data/local/tmp/postit-screen-awake-fixture.mp4
adb shell run-as fr.pschneider.postit cp /data/local/tmp/postit-screen-awake-fixture.mp4 files/screen-awake-fixture.mp4
adb shell am start -n fr.pschneider.postit/fr.pschneider.postit.ScreenAwakeTestActivity
adb shell run-as fr.pschneider.postit cat files/screen-awake-test-result.txt
```
Attendre `PASS` : lecture, pause/reprise, arret, fin, destruction de la surface,
demandes simultanees, arriere-plan et retour au premier plan sont verifies
sur le drapeau Android `KeepScreenOn`. Les changements de page et le retour
temporaire a l'accueil pendant ce test sont automatiques.
## Quand ne PAS écrire de test
Un test qui ne détecte rien n'est pas un test. Si l'invariant

View file

@ -8,6 +8,20 @@
"picket"
],
"rollForward": false
},
"gitversion.tool": {
"version": "6.8.2",
"commands": [
"dotnet-gitversion"
],
"rollForward": false
},
"dotnet-ef": {
"version": "10.0.13",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View file

@ -48,6 +48,10 @@ const bundleNames = [
// of bootstrap, jquery-ui, etc., which are NOT touched by this
// toolchain).
const staticAssets = [
{
src: 'node_modules/hls.js/dist/hls.light.min.js',
dst: 'hls.light.min.js',
},
{
src: 'node_modules/@aspnet/signalr/dist/browser/signalr.min.js',
dst: 'signalr.min.js',

View file

@ -5,25 +5,18 @@
"description": "Yavsc front-end toolchain (esbuild bundles for Yavsc.Org).",
"scripts": {
"build:js": "node esbuild.config.mjs",
"build:podcasts": "node -e \"require('node:fs').copyFileSync('node_modules/hls.js/dist/hls.light.min.js', 'src/Yavsc.Org/wwwroot/js/hls.light.min.js')\"",
"build:js:watch": "node esbuild.config.mjs --watch",
"clean:js": "node esbuild.config.mjs --clean"
},
"dependencies": {
"@aspnet/signalr": "^1.0.27",
"bootstrap": "^4.6.2",
"dropzone": "^5.9.3",
"eonasdan-bootstrap-datetimepicker": "^4.17.49",
"jquery": "^3.7.1",
"jquery-timepicker": "^1.3.3",
"jquery-ui": "^1.13.3",
"jquery-validation": "^1.20.0",
"jquery-validation-unobtrusive": "^4.0.0",
"moment": "^2.30.1",
"quill": "^1.3.7",
"showdown": "^2.1.0",
"to-markdown": "^3.1.1"
"jquery-validation-unobtrusive": "^4.0.0"
},
"devDependencies": {
"esbuild": "^0.24.0"
"esbuild": "^0.28.2"
}
}

View file

@ -4,18 +4,19 @@
<!-- https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management -->
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AvaloniaVersionBase>12.1.4</AvaloniaVersionBase>
<AvaloniaVersionBase>12.1.6</AvaloniaVersionBase>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Browser" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Android" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless" Version="12.1.4" />
<PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Skia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
<PackageVersion Include="DirectShowLib" Version="1.0.0" />
<PackageVersion Include="LibVLCSharp.Avalonia" Version="3.10.2" />
<PackageVersion Include="LibVLCSharp" Version="3.10.2" />
@ -39,5 +40,6 @@
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Process" Version="2.11.0.1" />
<PackageVersion Include="Xamarin.UITest" Version="4.4.2" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.31.1" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,203 @@
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
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
http://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.

File diff suppressed because it is too large Load diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

View file

@ -16,8 +16,8 @@ namespace PostIt.Android;
Theme = "@style/MyTheme.NoActionBar",
Icon = "@drawable/icon",
MainLauncher = true,
WindowSoftInputMode = SoftInput.AdjustResize,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode)
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode
)
]
public class MainActivity : AvaloniaMainActivity
{
@ -39,6 +39,40 @@ public class MainActivity : AvaloniaMainActivity
PlatformBootstrap.InitPlatform();
Current = this;
base.OnCreate(savedInstanceState);
PostIt.Services.Platform.ScreenAwake.Changed += OnScreenAwakeChanged;
}
private void OnScreenAwakeChanged() => RunOnUiThread(UpdateScreenAwake);
internal static void ShowSoftKeyboard()
{
if (Current is not { } activity || !IsForeground)
{
global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a foreground activity.");
return;
}
activity.RunOnUiThread(() =>
{
if (activity.CurrentFocus is not { } view
|| activity.GetSystemService(InputMethodService) is not global::Android.Views.InputMethods.InputMethodManager inputMethod)
{
global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a focused native view and input method.");
return;
}
if (!inputMethod.ShowSoftInput(view, global::Android.Views.InputMethods.ShowFlags.Implicit))
global::Android.Util.Log.Warn("PostIt", "The input method did not accept the keyboard activation request.");
});
}
private void UpdateScreenAwake()
{
if (Window is not { } window) return;
if (ReferenceEquals(Current, this) && IsForeground && PostIt.Services.Platform.ScreenAwake.IsRequested)
window.AddFlags(WindowManagerFlags.KeepScreenOn);
else
window.ClearFlags(WindowManagerFlags.KeepScreenOn);
}
/// <summary>
/// Receives the deep-link Intent fired by the system browser after the
@ -71,14 +105,32 @@ public class MainActivity : AvaloniaMainActivity
{
base.OnResume();
IsForeground = true;
PostIt.Services.Platform.IsApplicationActive = true;
UpdateScreenAwake();
}
protected override void OnPause()
{
IsForeground = false;
PostIt.Services.Platform.IsApplicationActive = false;
UpdateScreenAwake();
base.OnPause();
}
protected override void OnDestroy()
{
PostIt.Services.Platform.ScreenAwake.Changed -= OnScreenAwakeChanged;
Window?.ClearFlags(WindowManagerFlags.KeepScreenOn);
if (ReferenceEquals(Current, this))
{
Current = null;
IsForeground = false;
PostIt.Services.Platform.IsApplicationActive = false;
PostIt.Android.Services.NotificationPermission.OnActivityDestroyed();
}
base.OnDestroy();
}
protected override void OnRestart()
{
base.OnRestart();
@ -87,7 +139,8 @@ public class MainActivity : AvaloniaMainActivity
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
if (PostIt.Android.Services.PodcastPermissions.HandleResult(requestCode, permissions, grantResults)
if (PostIt.Android.Services.NotificationPermission.HandleResult(requestCode, permissions, grantResults)
|| PostIt.Android.Services.PodcastPermissions.HandleResult(requestCode, permissions, grantResults)
|| PostIt.Android.Services.AndroidCurrentLocationProvider
.HandlePermissionResult(requestCode, grantResults))
{

View file

@ -20,13 +20,28 @@ internal static class PlatformBootstrap
return activity is null ? null : new AndroidSystemBrowser(activity);
};
Platform.CreateServiceProvider = AndroidServiceProvider.GetOrCreate;
Platform.BackgroundChatService = AndroidBackgroundChatService.Instance;
Platform.ShowSoftKeyboard = MainActivity.ShowSoftKeyboard;
Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync;
Platform.CreateVideoSurface = player => new AndroidVideoSurface(player);
Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay);
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
{
Platform.CreateWebRtcMedia = () => System.OperatingSystem.IsAndroidVersionAtLeast(26)
? new AndroidWebRtcMedia()
: throw new System.PlatformNotSupportedException("Android 8 requis pour WebRTC.");
Platform.GetWebRtcDevices = AndroidLanCallMedia.GetDevices;
Platform.GetLanCallDevices = AndroidLanCallMedia.GetDevices;
Platform.CreateLanCallMedia = (address, port) =>
System.OperatingSystem.IsAndroidVersionAtLeast(26)
? new AndroidLanCallMedia(address, port)
: throw new System.PlatformNotSupportedException("Android 8 requis pour les appels LAN.");
Platform.GetPodcastCaptureDevices = AndroidPodcastCapture.GetDevices;
Platform.RequestPodcastPermissionsAsync = AndroidPodcastCapture.RequestPermissionsAsync;
Platform.CreatePodcastCaptureAsync = AndroidPodcastCapture.StartAsync;
Platform.CreatePodcastPreviewAsync = AndroidPodcastCapture.StartPreviewAsync;
Platform.CreateBlurredPodcastCaptureAsync = AndroidPodcastCapture.StartBlurredAsync;
Platform.CreateBlurredPodcastPreviewAsync = AndroidPodcastCapture.StartBlurredPreviewAsync;
}
}
}

View file

@ -8,11 +8,14 @@
<ApplicationVersion>1</ApplicationVersion>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<AndroidPackageFormat>apk</AndroidPackageFormat>
<EmbedAssembliesIntoApk>true</EmbedAssembliesIntoApk>
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
<AssemblyVersion>1.0.8.0</AssemblyVersion>
<FileVersion>1.0.8.0</FileVersion>
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
<Version>1.0.8-458</Version>
<!-- LibVLC's native package targets inspect the plural RID property. -->
<RuntimeIdentifiers Condition="'$(RuntimeIdentifiers)' == '' and '$(RuntimeIdentifier)' != ''">$(RuntimeIdentifier)</RuntimeIdentifiers>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
<Version>1.1.0-feat-calls.1</Version>
</PropertyGroup>
<ItemGroup>
<AndroidResource Include="Icon.png">
@ -22,16 +25,27 @@
<ItemGroup>
<PackageReference Include="Avalonia.Android" />
<PackageReference Include="LibVLCSharp" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
<PackageReference Include="VideoLAN.LibVLC.Android" />
<PackageReference Include="Xamarin.AndroidX.Core.SplashScreen" />
<PackageReference Include="Xamarin.AndroidX.Browser" />
</ItemGroup>
<ItemGroup>
<AndroidMavenLibrary Include="io.github.webrtc-sdk:android" Version="150.7871.04" Bind="false" VerifyDependencies="false" />
<AndroidJavaSource Update="Services/WebRtcPeer.java" Bind="false" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<Compile Include="..\PostIt.Tests\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidMarkdownEditorTestActivity.cs" Link="Tests\AndroidMarkdownEditorTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidChatServiceTestActivity.cs" Link="Tests\AndroidChatServiceTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidPodcastBlurTestActivity.cs" Link="Tests\AndroidPodcastBlurTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidLanCallTestActivity.cs" Link="Tests\AndroidLanCallTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidWebRtcTestActivity.cs" Link="Tests\AndroidWebRtcTestActivity.cs" />
<Compile Include="..\PostIt.Tests\Fixtures\AndroidScreenAwakeTestActivity.cs" Link="Tests\AndroidScreenAwakeTestActivity.cs" />
</ItemGroup>
<!-- This is an Avalonia app, not a MAUI app: exclude the .NET MAUI VS Code
extension's injected HotReload agent (references Microsoft.Maui.*).
@ -42,4 +56,4 @@
<Compile Remove="$(MauiDeployHotReloadAgentSource)" />
</ItemGroup>
</Target>
</Project>
</Project>

View file

@ -1,19 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<application
android:label="PostIt"
android:icon="@drawable/Icon"
android:networkSecurityConfig="@xml/network_security_config"
android:hardwareAccelerated="true">
</application>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:installLocation="auto"
>
<!-- ONNX Runtime is loaded only for podcast capture, which requires API 26. -->
<uses-sdk tools:overrideLibrary="ai.onnxruntime" android:targetSdkVersion="36" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<application
android:label="PostIt"
android:icon="@drawable/Icon"
android:networkSecurityConfig="@xml/network_security_config"
android:hardwareAccelerated="true">
</application>
</manifest>

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4,2h16a2,2 0,0 1,2 2v12a2,2 0,0 1,-2 2H8l-4,4V4a2,2 0,0 1,2,-2z" />
</vector>

View file

@ -0,0 +1,145 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Util;
using PostIt.Models;
using PostIt.Services;
namespace PostIt.Android.Services;
internal enum BackgroundChatFailure { SessionRequired, StartRejected, ConnectionFailed }
internal sealed class BackgroundChatException(BackgroundChatFailure failure, string message, Exception? inner = null)
: InvalidOperationException(message, inner)
{
internal BackgroundChatFailure Failure { get; } = failure;
}
internal sealed class AndroidBackgroundChatService : IBackgroundChatService
{
internal static readonly AndroidBackgroundChatService Instance = new();
internal static readonly ChatServiceEpoch Epoch = new();
internal const string EpochExtra = "postit-chat-epoch";
internal const string IdentityExtra = "postit-chat-identity";
private readonly SemaphoreSlim _gate = new(1, 1);
public async Task SynchronizeAsync(YavscApiClient api, bool enabled, CancellationToken ct = default)
{
// This runs before the first await: cancellation cannot queue a stop
// behind an in-flight permission dialog or a native start.
if (!enabled || !api.Settings.AndroidKeepChatConnected)
{
Invalidate();
return;
}
ct.ThrowIfCancellationRequested();
if (api.IsSigningOut)
{
Invalidate();
throw new BackgroundChatException(BackgroundChatFailure.SessionRequired, "Deconnexion en cours.");
}
var epoch = Epoch.Begin();
var identity = ChatBootState.Identity(api);
var entered = false;
try
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
entered = true;
Validate(api, epoch, identity, ct);
if (!Epoch.Run(epoch, () => ChatBootState.Save(api))) throw new OperationCanceledException(ct);
if (!ChatBootState.CanStart(api))
throw new BackgroundChatException(BackgroundChatFailure.SessionRequired, "Connectez-vous avant d'activer la connexion de fond.");
var context = global::Android.App.Application.Context;
await ChatConnectionService.StartAndWaitAsync(context, epoch, identity!, ct).ConfigureAwait(false);
Validate(api, epoch, identity, ct);
if (!NotificationPermission.IsGranted(context))
{
if (MainActivity.Current is { } activity && MainActivity.IsForeground)
{
try
{
var granted = await NotificationPermission.RequestAsync(activity, ct).ConfigureAwait(false);
Validate(api, epoch, identity, ct);
await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(granted
? "Connexion de fond active sans notification permanente. Android peut l'interrompre."
: "Notifications refusees : SignalR reste actif, mais les alertes ne seront pas affichees.",
granted ? StatusSeverity.Info : StatusSeverity.Warning)).ConfigureAwait(false);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Notification permission request failed: " + ex);
AndroidSettings.ReportError(api.Settings,
"SignalR reste actif ; demande d'autorisation des alertes impossible : " + ex.Message);
}
}
}
Validate(api, epoch, identity, ct);
}
catch (OperationCanceledException)
{
Cancel(epoch);
throw;
}
catch (Exception ex)
{
Cancel(epoch);
Log.Error("PostIt.Chat", ex.ToString());
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
try
{
await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error))
.ConfigureAwait(false);
}
catch (Exception statusError) { Log.Error("PostIt.Chat", statusError.ToString()); }
if (ex is BackgroundChatException) throw;
throw new BackgroundChatException(BackgroundChatFailure.StartRejected,
"Android n'a pas pu demarrer le service de messagerie : " + ex.Message, ex);
}
finally { if (entered) _gate.Release(); }
}
public Task DisableAsync(YavscApiClient api, CancellationToken ct = default)
{
Invalidate();
// Logout calls this before deleting tokens. Never stop the shared
// socket here: the process-owned messaging session manages it.
try { ChatBootState.MarkSignedOut(); }
catch (Exception ex)
{
Log.Error("PostIt.Chat", ex.ToString());
AndroidSettings.ReportError(api.Settings, ex.Message);
}
return Task.CompletedTask;
}
private static void Validate(YavscApiClient api, string epoch, string? identity, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (!Epoch.IsCurrent(epoch) || api.IsSigningOut || !api.Settings.AndroidKeepChatConnected
|| !api.HasValidSession || identity is null || identity != ChatBootState.Identity(api))
throw new OperationCanceledException("Demarrage de messagerie obsolete.", ct);
}
internal static bool StartNative(Context context, string epoch, string identity) =>
Epoch.Run(epoch, () =>
{
var intent = new Intent(context, typeof(ChatConnectionService))
.PutExtra(EpochExtra, epoch).PutExtra(IdentityExtra, identity);
context.StartService(intent);
});
internal static void Invalidate() => Epoch.Invalidate(Stop);
internal static void Cancel(string epoch) => Epoch.Cancel(epoch, Stop);
internal static bool IsCurrent(string? epoch) => Epoch.IsCurrent(epoch);
private static void Stop()
{
ChatConnectionService.Suspend();
global::Android.App.Application.Context.StopService(
new Intent(global::Android.App.Application.Context, typeof(ChatConnectionService)));
}
}

View file

@ -0,0 +1,51 @@
using System;
using Android.Content;
using Android.OS;
using Android.Util;
using PostIt.ViewModels;
using AndroidSettingsIntent = Android.Provider.Settings;
namespace PostIt.Android.Services;
internal static class AndroidBatteryOptimization
{
internal static Intent? CreateIntent(Context context)
{
var packageName = context.PackageName
?? throw new InvalidOperationException("Identifiant de l'application Android indisponible.");
var power = context.GetSystemService(Context.PowerService) as PowerManager
?? throw new InvalidOperationException("Gestion de la batterie Android indisponible.");
return power.IsIgnoringBatteryOptimizations(packageName)
? null
: new Intent(AndroidSettingsIntent.ActionRequestIgnoreBatteryOptimizations)
.SetData(global::Android.Net.Uri.Parse("package:" + packageName));
}
internal static void Request(Settings settings)
{
if (MainActivity.Current is not { IsFinishing: false, IsDestroyed: false } activity
|| !MainActivity.IsForeground)
{
AndroidSettings.ReportError(settings,
"Ouvrez PostIt pour demander l'exemption d'optimisation batterie.");
return;
}
activity.RunOnUiThread(() =>
{
try
{
if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed)
throw new InvalidOperationException("PostIt doit etre visible pour ouvrir les parametres batterie.");
if (!settings.AndroidKeepChatConnected) return;
using var intent = CreateIntent(activity);
if (intent is not null) activity.StartActivity(intent);
}
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Battery optimization settings failed: " + ex);
AndroidSettings.ReportError(settings,
"Impossible d'ouvrir les parametres batterie Android : " + ex.Message);
}
});
}
}

View file

@ -1,6 +1,7 @@
using System;
using System.Threading.Tasks;
using Android.Graphics;
using Android.Content;
using Android.Opengl;
using Android.OS;
using Android.Views;
@ -17,9 +18,32 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
attribute vec2 textureCoordinate;
uniform mat4 textureMatrix;
varying vec2 uv;
varying vec2 maskUv;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
uv = (textureMatrix * vec4(textureCoordinate, 0.0, 1.0)).xy;
maskUv = (position + vec2(1.0)) * 0.5;
}
""";
private const string BlurFragmentShader = """
#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES cameraTexture;
uniform sampler2D personMask;
uniform vec2 blurStep;
varying vec2 uv;
varying vec2 maskUv;
void main() {
vec4 original = texture2D(cameraTexture, uv);
vec4 blurred = vec4(0.0);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
blurred += texture2D(cameraTexture, uv + vec2(float(x), float(y)) * blurStep);
}
}
blurred /= 25.0;
float person = texture2D(personMask, maskUv).r;
gl_FragColor = mix(blurred, original, person);
}
""";
private const string FragmentShader = """
@ -37,9 +61,20 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
private readonly Action<Exception> _failed;
private readonly float[] _textureMatrix = new float[16];
private readonly CameraFrameClock _clock = new();
private readonly object _lifecycle = new();
private EGLDisplay? _display;
private EGLConfig? _config;
private EGLContext? _context;
private EGLSurface? _window;
private EGLSurface? _previewWindow;
private Action<Exception>? _previewFailed;
private int _previewWidth;
private int _previewHeight;
private int _outputWidth;
private int _outputHeight;
private int _inputWidth;
private int _inputHeight;
private bool _previewOnly;
private SurfaceTexture? _texture;
private FrameListener? _listener;
private Surface? _cameraSurface;
@ -48,10 +83,20 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
private int _program;
private int _textureId;
private int _matrixLocation;
private int _blurProgram;
private int _blurMatrixLocation;
private int _maskTexture;
private int _samplingTexture;
private int _framebuffer;
private IPodcastPersonSegmenter? _segmenter;
private ByteBuffer? _samplingBuffer;
private ByteBuffer? _maskBuffer;
private byte[]? _samplingBytes;
private bool _rendering;
private bool _blackout;
private bool _disposed;
private int _rotation;
private int? _remainingRotation;
private int _remainingRotation = -1;
internal string? FirstTextureTransform { get; private set; }
internal Surface CameraSurface => _cameraSurface
@ -65,12 +110,13 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
}
internal static async Task<AndroidCameraFrameRotator> CreateAsync(
Surface encoderSurface, int width, int height, int rotation, Action<Exception> failed)
Surface? encoderSurface, int width, int height, int rotation, Action<Exception> failed, Context? blurContext = null,
Func<Context, IPodcastPersonSegmenter>? segmenterFactory = null)
{
var rotator = new AndroidCameraFrameRotator(failed);
try
{
await rotator.InvokeAsync(() => rotator.Initialize(encoderSurface, width, height, rotation));
await rotator.InvokeAsync(() => rotator.Initialize(encoderSurface, width, height, rotation, blurContext, segmenterFactory));
return rotator;
}
catch
@ -80,9 +126,13 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
}
}
private void Initialize(Surface encoderSurface, int width, int height, int rotation)
private void Initialize(Surface? encoderSurface, int width, int height, int rotation, Context? blurContext,
Func<Context, IPodcastPersonSegmenter>? segmenterFactory)
{
_rotation = rotation;
_inputWidth = width;
_inputHeight = height;
_previewOnly = encoderSurface is null;
_display = EGL14.EglGetDisplay(EGL14.EglDefaultDisplay);
if (_display is null || _display.Equals(EGL14.EglNoDisplay))
throw EglError("Obtention de l'affichage EGL");
@ -92,23 +142,27 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
[
EGL14.EglRedSize, 8, EGL14.EglGreenSize, 8, EGL14.EglBlueSize, 8,
EGL14.EglRenderableType, EGL14.EglOpenglEs2Bit,
EGL14.EglSurfaceType, EGL14.EglWindowBit, RecordableAndroid, 1, EGL14.EglNone
EGL14.EglSurfaceType, EGL14.EglWindowBit | EGL14.EglPbufferBit, RecordableAndroid, 1, EGL14.EglNone
];
var configs = new EGLConfig[1];
var count = new int[1];
if (!EGL14.EglChooseConfig(_display, attributes, 0, configs, 0, 1, count, 0) || count[0] == 0)
throw EglError("Configuration EGL pour l'encodeur");
_config = configs[0];
_context = EGL14.EglCreateContext(_display, configs[0], EGL14.EglNoContext,
[EGL14.EglContextClientVersion, 2, EGL14.EglNone], 0);
if (_context is null || _context.Equals(EGL14.EglNoContext))
throw EglError("Creation du contexte EGL");
_window = EGL14.EglCreateWindowSurface(_display, configs[0], encoderSurface, [EGL14.EglNone], 0);
_window = encoderSurface is null
? EGL14.EglCreatePbufferSurface(_display, configs[0],
[EGL14.EglWidth, 1, EGL14.EglHeight, 1, EGL14.EglNone], 0)
: EGL14.EglCreateWindowSurface(_display, configs[0], encoderSurface, [EGL14.EglNone], 0);
if (_window is null || _window.Equals(EGL14.EglNoSurface))
throw EglError("Creation de la surface EGL");
if (!EGL14.EglMakeCurrent(_display, _window, _window, _context))
throw EglError("Activation du contexte EGL");
_program = CreateProgram();
_program = CreateProgram(FragmentShader);
var ids = new int[1];
GLES20.GlGenTextures(1, ids, 0);
_textureId = ids[0];
@ -118,13 +172,16 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
GLES20.GlTexParameteri(ExternalTexture, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
GLES20.GlTexParameteri(ExternalTexture, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
_vertices = CreateBuffer([-1, -1, 1, -1, -1, 1, 1, 1]);
_coordinates = CreateBuffer(CameraFrameOrientation.GetTextureCoordinates(0));
_coordinates = CreateBuffer(CameraFrameOrientation.GetTextureCoordinates(rotation));
GLES20.GlUseProgram(_program);
BindAttribute("position", _vertices);
BindAttribute("textureCoordinate", _coordinates);
_matrixLocation = GLES20.GlGetUniformLocation(_program, "textureMatrix");
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_program, "cameraTexture"), 0);
GLES20.GlViewport(0, 0, rotation is 90 or 270 ? height : width, rotation is 90 or 270 ? width : height);
if (blurContext is not null) InitializeBlur(blurContext, segmenterFactory);
_outputWidth = rotation is 90 or 270 ? height : width;
_outputHeight = rotation is 90 or 270 ? width : height;
GLES20.GlViewport(0, 0, _outputWidth, _outputHeight);
CheckGl();
_texture = new SurfaceTexture(_textureId);
@ -136,14 +193,132 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
internal Task StartAsync() => InvokeAsync(() => _rendering = true);
internal Task SetRotationAsync(int rotation) => InvokeAsync(() =>
{
_rotation = rotation;
_remainingRotation = -1;
});
internal Task SetPreviewAsync(Surface? surface, int width = 0, int height = 0, Action<Exception>? failed = null)
{
lock (_lifecycle)
{
if (_disposed) return Task.CompletedTask;
return InvokeAsync(() =>
{
ReleasePreview();
if (surface is null) return;
_previewWindow = EGL14.EglCreateWindowSurface(_display, _config, surface, [EGL14.EglNone], 0);
if (_previewWindow is null || _previewWindow.Equals(EGL14.EglNoSurface))
throw EglError("Creation de la surface d'apercu");
_previewWidth = width;
_previewHeight = height;
_previewFailed = failed;
});
}
}
private void InitializeBlur(Context context, Func<Context, IPodcastPersonSegmenter>? segmenterFactory)
{
_segmenter = segmenterFactory is null ? new PodcastPersonSegmenter(context) : segmenterFactory(context);
_samplingBytes = new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size * 4];
_samplingBuffer = ByteBuffer.AllocateDirect(_samplingBytes.Length)
?? throw new InvalidOperationException("Tampon de segmentation indisponible.");
_maskBuffer = ByteBuffer.AllocateDirect(PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size)
?? throw new InvalidOperationException("Tampon du masque indisponible.");
_blurProgram = CreateProgram(BlurFragmentShader);
GLES20.GlUseProgram(_blurProgram);
_blurMatrixLocation = GLES20.GlGetUniformLocation(_blurProgram, "textureMatrix");
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_blurProgram, "cameraTexture"), 0);
GLES20.GlUniform1i(GLES20.GlGetUniformLocation(_blurProgram, "personMask"), 1);
GLES20.GlUniform2f(GLES20.GlGetUniformLocation(_blurProgram, "blurStep"), 4f / _inputWidth, 4f / _inputHeight);
var ids = new int[1];
GLES20.GlGenTextures(1, ids, 0);
_maskTexture = ids[0];
GLES20.GlActiveTexture(GLES20.GlTexture1);
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
SetTextureParameters();
GLES20.GlTexImage2D(GLES20.GlTexture2d, 0, GLES20.GlLuminance,
PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size, 0, GLES20.GlLuminance, GLES20.GlUnsignedByte, null);
GLES20.GlGenTextures(1, ids, 0);
_samplingTexture = ids[0];
GLES20.GlBindTexture(GLES20.GlTexture2d, _samplingTexture);
SetTextureParameters();
GLES20.GlTexImage2D(GLES20.GlTexture2d, 0, GLES20.GlRgba,
PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size, 0, GLES20.GlRgba, GLES20.GlUnsignedByte, null);
GLES20.GlGenFramebuffers(1, ids, 0);
_framebuffer = ids[0];
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, _framebuffer);
GLES20.GlFramebufferTexture2D(GLES20.GlFramebuffer, GLES20.GlColorAttachment0,
GLES20.GlTexture2d, _samplingTexture, 0);
if (GLES20.GlCheckFramebufferStatus(GLES20.GlFramebuffer) != GLES20.GlFramebufferComplete)
throw new InvalidOperationException("Surface de segmentation OpenGL indisponible.");
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
GLES20.GlActiveTexture(GLES20.GlTexture0);
GLES20.GlUseProgram(_program);
BindAttribute("position", _vertices!);
BindAttribute("textureCoordinate", _coordinates!);
CheckGl();
}
private static void SetTextureParameters()
{
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinear);
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear);
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
}
private void UpdatePersonMask()
{
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, _framebuffer);
GLES20.GlViewport(0, 0, PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size);
GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);
_samplingBuffer!.Position(0);
GLES20.GlReadPixels(0, 0, PodcastPersonSegmenter.Size, PodcastPersonSegmenter.Size,
GLES20.GlRgba, GLES20.GlUnsignedByte, _samplingBuffer);
CheckGl();
_samplingBuffer.Position(0);
_samplingBuffer.Get(_samplingBytes!);
var mask = _segmenter!.Segment(_samplingBytes!);
_maskBuffer!.Position(0);
_maskBuffer.Put(mask);
_maskBuffer.Position(0);
GLES20.GlActiveTexture(GLES20.GlTexture1);
GLES20.GlBindTexture(GLES20.GlTexture2d, _maskTexture);
GLES20.GlTexSubImage2D(GLES20.GlTexture2d, 0, 0, 0, PodcastPersonSegmenter.Size,
PodcastPersonSegmenter.Size, GLES20.GlLuminance, GLES20.GlUnsignedByte, _maskBuffer);
GLES20.GlActiveTexture(GLES20.GlTexture0);
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
CheckGl();
}
private void DrawFrame(SurfaceTexture texture)
{
if (!_rendering) return;
try
{
if (!EGL14.EglMakeCurrent(_display, _window, _window, _context))
throw EglError("Activation de l'encodeur");
texture.UpdateTexImage();
var presentationTime = _clock.GetPresentationTime(texture.Timestamp, Java.Lang.JavaSystem.NanoTime());
if (presentationTime is null) return;
if (_blackout)
{
if (!_previewOnly)
{
GLES20.GlBindFramebuffer(GLES20.GlFramebuffer, 0);
GLES20.GlViewport(0, 0, _outputWidth, _outputHeight);
GLES20.GlClearColor(0, 0, 0, 1);
GLES20.GlClear(GLES20.GlColorBufferBit);
CheckGl();
if (!EGLExt.EglPresentationTimeANDROID(_display, _window, presentationTime.Value)
|| !EGL14.EglSwapBuffers(_display, _window))
throw EglError("Envoi d'une image noire a l'encodeur");
}
return;
}
texture.GetTransformMatrix(_textureMatrix);
var remainingRotation = CameraFrameOrientation.GetRemainingRotation(_rotation, _textureMatrix);
if (_remainingRotation != remainingRotation)
@ -154,23 +329,98 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
_coordinates.Put(CameraFrameOrientation.GetTextureCoordinates(remainingRotation));
_coordinates.Position(0);
global::Android.Util.Log.Info("PostIt.Podcast",
$"Camera texture transform: [{FirstTextureTransform}], remaining rotation={remainingRotation}");
$"Camera texture transform: [{FirstTextureTransform}], sensor/display rotation={_rotation}, remaining rotation={remainingRotation}");
}
GLES20.GlUniformMatrix4fv(_matrixLocation, 1, false, _textureMatrix, 0);
GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);
CheckGl();
if (!EGLExt.EglPresentationTimeANDROID(_display, _window, presentationTime.Value))
throw EglError("Horodatage de l'image camera");
if (!EGL14.EglSwapBuffers(_display, _window))
throw EglError("Envoi de l'image a l'encodeur");
if (_segmenter is not null) UpdatePersonMask();
if (_blurProgram != 0)
{
GLES20.GlUseProgram(_blurProgram);
BindAttribute("position", _vertices!);
BindAttribute("textureCoordinate", _coordinates!);
GLES20.GlUniformMatrix4fv(_blurMatrixLocation, 1, false, _textureMatrix, 0);
}
if (!_previewOnly)
{
SetViewport(_outputWidth, _outputHeight);
GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);
CheckGl();
if (!EGLExt.EglPresentationTimeANDROID(_display, _window, presentationTime.Value))
throw EglError("Horodatage de l'image camera");
if (!EGL14.EglSwapBuffers(_display, _window))
throw EglError("Envoi de l'image a l'encodeur");
}
DrawPreview();
if (_blurProgram != 0)
{
GLES20.GlUseProgram(_program);
BindAttribute("position", _vertices!);
BindAttribute("textureCoordinate", _coordinates!);
}
}
catch (Exception ex)
{
_rendering = false;
_failed(new InvalidOperationException("Rotation de la capture Android impossible.", ex));
if (_blackout)
{
_rendering = false;
global::Android.Util.Log.Error("PostIt.Podcast", $"Arret de la capture impossible : {ex}");
}
else
{
_blackout = true;
_failed(new InvalidOperationException("Traitement de la capture Android impossible.", ex));
}
}
}
private void DrawPreview()
{
if (_previewWindow is null || _previewWidth <= 0 || _previewHeight <= 0) return;
try
{
if (!EGL14.EglMakeCurrent(_display, _previewWindow, _previewWindow, _context))
throw EglError("Activation de l'apercu");
SetViewport(_previewWidth, _previewHeight);
GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);
CheckGl();
if (!EGL14.EglSwapBuffers(_display, _previewWindow))
throw EglError("Affichage de l'apercu");
}
catch (Exception ex)
{
var failed = _previewFailed;
global::Android.Util.Log.Error("PostIt.Podcast", $"Apercu indisponible : {ex}");
ReleasePreview();
failed?.Invoke(ex);
}
}
private void SetViewport(int targetWidth, int targetHeight)
{
GLES20.GlClearColor(0, 0, 0, 1);
GLES20.GlClear(GLES20.GlColorBufferBit);
var contentWidth = _rotation is 90 or 270 ? _inputHeight : _inputWidth;
var contentHeight = _rotation is 90 or 270 ? _inputWidth : _inputHeight;
var scale = Math.Min((double)targetWidth / contentWidth, (double)targetHeight / contentHeight);
var width = Math.Max(1, (int)(contentWidth * scale));
var height = Math.Max(1, (int)(contentHeight * scale));
GLES20.GlViewport((targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
}
private void ReleasePreview()
{
if (_previewWindow is not null)
{
// Never leave a surface current when its Android holder is about to destroy it.
EGL14.EglMakeCurrent(_display, _window, _window, _context);
if (!_previewWindow.Equals(EGL14.EglNoSurface))
EGL14.EglDestroySurface(_display, _previewWindow);
_previewWindow.Dispose();
_previewWindow = null;
}
_previewFailed = null;
}
private Task InvokeAsync(Action action)
{
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
@ -215,14 +465,14 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
throw new InvalidOperationException($"Compilation du shader camera impossible : {error}");
}
private static int CreateProgram()
private static int CreateProgram(string fragmentSource)
{
var vertex = CreateShader(GLES20.GlVertexShader, VertexShader);
var fragment = 0;
var program = 0;
try
{
fragment = CreateShader(GLES20.GlFragmentShader, FragmentShader);
fragment = CreateShader(GLES20.GlFragmentShader, fragmentSource);
program = GLES20.GlCreateProgram();
GLES20.GlAttachShader(program, vertex);
GLES20.GlAttachShader(program, fragment);
@ -257,9 +507,14 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { InvokeAsync(Release).GetAwaiter().GetResult(); }
Task release;
lock (_lifecycle)
{
if (_disposed) return;
_disposed = true;
release = InvokeAsync(Release);
}
try { release.GetAwaiter().GetResult(); }
finally
{
_thread.QuitSafely();
@ -272,12 +527,20 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
private void Release()
{
_rendering = false;
ReleasePreview();
_texture?.SetOnFrameAvailableListener(null);
_cameraSurface?.Release();
_cameraSurface?.Dispose();
_texture?.Release();
_texture?.Dispose();
_listener?.Dispose();
_segmenter?.Dispose();
_samplingBuffer?.Dispose();
_maskBuffer?.Dispose();
if (_framebuffer != 0) GLES20.GlDeleteFramebuffers(1, [_framebuffer], 0);
if (_samplingTexture != 0) GLES20.GlDeleteTextures(1, [_samplingTexture], 0);
if (_maskTexture != 0) GLES20.GlDeleteTextures(1, [_maskTexture], 0);
if (_blurProgram != 0) GLES20.GlDeleteProgram(_blurProgram);
if (_program != 0) GLES20.GlDeleteProgram(_program);
if (_textureId != 0) GLES20.GlDeleteTextures(1, [_textureId], 0);
_vertices?.Dispose();
@ -293,6 +556,7 @@ internal sealed class AndroidCameraFrameRotator : IDisposable
EGL14.EglTerminate(_display);
}
_window?.Dispose();
_config?.Dispose();
_context?.Dispose();
_display?.Dispose();
}

View file

@ -0,0 +1,102 @@
using System;
using Android.Views;
using Avalonia.Android;
using Avalonia.Controls;
using Avalonia.Platform;
using Avalonia.Threading;
namespace PostIt.Android.Services;
internal sealed class AndroidCapturePreview : Grid, IDisposable
{
private readonly PreviewHost _host;
private readonly TextBlock _status = new() { TextWrapping = Avalonia.Media.TextWrapping.Wrap };
internal AndroidCapturePreview(AndroidCameraFrameRotator rotator)
{
RowDefinitions = new RowDefinitions("*,Auto");
_host = new PreviewHost(rotator, ReportFailure);
Children.Add(_host);
SetRow(_status, 1);
Children.Add(_status);
}
private void ReportFailure(Exception error)
{
global::Android.Util.Log.Error("PostIt.Podcast", $"Apercu indisponible : {error}");
Dispatcher.UIThread.Post(() => _status.Text = $"Apercu indisponible : {error.Message}. La capture continue.");
}
public void Dispose() => _host.Dispose();
private sealed class PreviewHost(AndroidCameraFrameRotator rotator, Action<Exception> failed)
: NativeControlHost, IDisposable
{
private ISurfaceHolder? _holder;
private SurfaceCallback? _callback;
private bool _disposed;
protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
{
var activity = MainActivity.Current
?? throw new InvalidOperationException("Activite Android indisponible pour l'apercu.");
var view = new SurfaceView(activity);
if (!_disposed)
{
_holder = view.Holder
?? throw new InvalidOperationException("Surface Android indisponible pour l'apercu.");
_callback = new SurfaceCallback(this);
_holder.AddCallback(_callback);
}
return new AndroidViewControlHandle(view);
}
private void SetSurface(ISurfaceHolder holder, int width, int height)
{
if (_disposed) return;
try { rotator.SetPreviewAsync(holder.Surface, width, height, failed).GetAwaiter().GetResult(); }
catch (Exception ex) { failed(ex); }
}
private void Detach()
{
try { rotator.SetPreviewAsync(null).GetAwaiter().GetResult(); }
catch (Exception ex) { failed(ex); }
}
protected override void DestroyNativeControlCore(IPlatformHandle control)
{
ReleaseSurface();
base.DestroyNativeControlCore(control);
}
private void ReleaseSurface()
{
Detach();
if (_callback is not null)
{
// The native view wrapper may already be disposed during deferred host destruction.
_holder?.RemoveCallback(_callback);
_callback.Dispose();
_callback = null;
}
_holder?.Dispose();
_holder = null;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
ReleaseSurface();
}
private sealed class SurfaceCallback(PreviewHost owner) : Java.Lang.Object, ISurfaceHolderCallback
{
public void SurfaceCreated(ISurfaceHolder holder) { }
public void SurfaceChanged(ISurfaceHolder holder, global::Android.Graphics.Format format, int width, int height)
=> owner.SetSurface(holder, width, height);
public void SurfaceDestroyed(ISurfaceHolder holder) => owner.Detach();
}
}
}

View file

@ -0,0 +1,117 @@
using System;
using System.Linq;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using PostIt.Services;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Android.Services;
[SupportedOSPlatform("android26.0")]
internal sealed class AndroidLanCallMedia : ILanCallMedia
{
private readonly LibVlcLanCallMedia _media;
private readonly ContentControl _local = new();
private readonly AndroidVideoSurface _remote;
private readonly CancellationTokenSource _lifetime = new();
private readonly TaskCompletionSource _captureEnded = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Task _receiving;
private IPodcastCapture? _capture;
private bool _disposed;
public Control LocalVideo => _local;
public Control RemoteVideo => _remote;
public LanCallEndpoint Endpoint => _media.Endpoint;
public bool HasRemoteMedia => !_disposed && _media.HasRemoteMedia;
public Task Completion { get; }
public static PodcastCaptureDevices GetDevices()
{
var devices = AndroidPodcastCapture.GetDevices();
return new(devices.Cameras.OrderByDescending(c => c.Name == "Camera avant").ToArray(),
devices.Microphones.Where(m => m.Value == "microphone").ToArray());
}
public AndroidLanCallMedia(string localAddress, int port)
{
_media = new LibVlcLanCallMedia(localAddress, port);
_remote = new AndroidVideoSurface(_media.Receiver, replay: false);
_receiving = ReceiveAsync();
Completion = ObserveAsync();
}
private async Task ReceiveAsync()
{
await _remote.Ready.WaitAsync(TimeSpan.FromSeconds(10), _lifetime.Token);
await _media.StartReceivingAsync(_lifetime.Token);
}
private async Task ObserveAsync()
{
var first = await Task.WhenAny(_media.Completion, _captureEnded.Task, _receiving);
await first;
if (first == _receiving)
{
var finished = await Task.WhenAny(_media.Completion, _captureEnded.Task);
await finished;
}
}
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_capture != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
_capture = await AndroidPodcastCapture.StartCallAsync(camera, microphone,
(fd, token) => _media.StartEncodedSendingAsync(remote, fd, token), _media.StopAsync, linked.Token);
_local.Content = _capture.Preview;
_ = ObserveCaptureAsync(_capture);
}
private async Task ObserveCaptureAsync(IPodcastCapture capture)
{
try
{
await capture.Completion;
if (!_disposed)
_captureEnded.TrySetException(new InvalidOperationException("Capture de l'appel arretee."));
}
catch (Exception error) { _captureEnded.TrySetException(error); }
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
_lifetime.Cancel();
var stop = _capture?.StopAsync();
try
{
if (stop != null) await stop;
}
finally
{
try
{
if (_capture != null) await _capture.DisposeAsync();
}
finally
{
_local.Content = null;
try { await _media.StopAsync(); }
finally
{
_remote.Dispose();
try { await _media.DisposeAsync(); }
finally
{
_lifetime.Dispose();
_captureEnded.TrySetResult();
}
}
}
}
}
}

View file

@ -8,18 +8,26 @@ using System.Threading.Tasks;
using Android.Content;
using Android.Hardware.Camera2;
using Android.Hardware.Camera2.Params;
using Android.Hardware.Display;
using Android.Media;
using Android.OS;
using Android.Views;
using Microsoft.Win32.SafeHandles;
using PostIt.Services;
using Stream = System.IO.Stream;
namespace PostIt.Android.Services;
[SupportedOSPlatform("android26.0")]
internal sealed class AndroidPodcastCapture : IPodcastCapture
{
private readonly PodcastCaptureService _service;
private static readonly SemaphoreSlim CaptureGate = new(1, 1);
private readonly PodcastCaptureService? _service;
private readonly Context _context;
private DisplayManager? _displayManager;
private RotationListener? _rotationListener;
private int _sensorDegrees;
private bool _frontFacing;
private readonly SemaphoreSlim _stopGate = new(1);
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Handler _handler = new(Looper.MainLooper!);
@ -27,10 +35,13 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
private CameraCaptureSession? _session;
private MediaRecorder? _recorder;
private AndroidCameraFrameRotator? _rotator;
private AndroidCapturePreview? _preview;
public Avalonia.Controls.Control? Preview => _preview;
private Surface? _surface;
private ParcelFileDescriptor? _readPipe;
private ParcelFileDescriptor? _writePipe;
private Task _pump = Task.CompletedTask;
private Func<Task>? _stopOutput;
private Exception? _failure;
private bool _stopped;
private bool _stopRequested;
@ -40,7 +51,11 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
internal string OrientationDiagnostics { get; private set; } = "";
internal string? TextureTransform => _rotator?.FirstTextureTransform;
private AndroidPodcastCapture(PodcastCaptureService service) => _service = service;
private AndroidPodcastCapture(Context context, PodcastCaptureService? service = null)
{
_context = context;
_service = service;
}
private static CameraManager GetManager(Context context)
=> context.GetSystemService(Context.CameraService) as CameraManager
@ -69,16 +84,29 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
}
public static async Task<IPodcastCapture> StartAsync(string camera, string? microphone, string directory, CancellationToken ct)
=> await StartCoreAsync(camera, microphone,
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct, false);
public static async Task<IPodcastCapture> StartBlurredAsync(string camera, string? microphone, string directory, CancellationToken ct)
=> await StartCoreAsync(camera, microphone,
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct, true);
public static Task<IPodcastCapture> StartPreviewAsync(string camera, CancellationToken ct) => StartPreviewAsync(camera, ct, false);
public static Task<IPodcastCapture> StartBlurredPreviewAsync(string camera, CancellationToken ct) => StartPreviewAsync(camera, ct, true);
private static async Task<IPodcastCapture> StartPreviewAsync(string camera, CancellationToken ct, bool blur)
{
await RequestPermissionsAsync(microphone, ct);
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
var service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct);
var capture = new AndroidPodcastCapture(service);
service.Capture = capture;
await PodcastPermissions.EnsureAsync(activity, false, ct, notifications: false);
if (!MainActivity.IsForeground)
throw new InvalidOperationException("Revenez dans PostIt pour previsualiser la camera.");
if (!await CaptureGate.WaitAsync(0, ct))
throw new InvalidOperationException("La camera est deja utilisee par un apercu, un podcast ou un appel.");
var capture = new AndroidPodcastCapture(activity);
Platform.PlaybackSuspending += capture.RequestStop;
try
{
ct.ThrowIfCancellationRequested();
await capture.StartNativeAsync(camera, microphone is not null, directory, ct);
await capture.StartNativeAsync(camera, false, null, null, ct, blur);
return capture;
}
catch
@ -88,16 +116,54 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
}
}
private async Task StartNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
internal static Task<IPodcastCapture> StartCallAsync(string camera, string microphone,
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
StartCoreAsync(camera, microphone, null, output, stopOutput, ct, false);
private static async Task<IPodcastCapture> StartCoreAsync(string camera, string? microphone,
Func<Stream, CancellationToken, Task>? output,
Func<int, CancellationToken, Task>? pipeOutput, Func<Task>? stopOutput, CancellationToken ct, bool blur)
{
await RequestPermissionsAsync(microphone, ct);
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
if (!await CaptureGate.WaitAsync(0, ct))
throw new InvalidOperationException("La camera est deja utilisee par un apercu, un podcast ou un appel.");
PodcastCaptureService service;
try { service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct, pipeOutput != null); }
catch
{
CaptureGate.Release();
throw;
}
var capture = new AndroidPodcastCapture(service, service) { _stopOutput = stopOutput };
service.Capture = capture;
try
{
ct.ThrowIfCancellationRequested();
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
return capture;
}
catch
{
await capture.DisposeAsync();
throw;
}
}
private async Task StartNativeAsync(string cameraId, bool microphone,
Func<Stream, CancellationToken, Task>? output,
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)
{
await _stopGate.WaitAsync(ct);
try { await ConfigureNativeAsync(cameraId, microphone, directory, ct); }
try { await ConfigureNativeAsync(cameraId, microphone, output, pipeOutput, ct, blur); }
finally { _stopGate.Release(); }
}
private async Task ConfigureNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
private async Task ConfigureNativeAsync(string cameraId, bool microphone,
Func<Stream, CancellationToken, Task>? output,
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)
{
var manager = GetManager(_service);
var manager = GetManager(_context);
using var characteristics = manager.GetCameraCharacteristics(cameraId);
using var formats = characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap) as StreamConfigurationMap
?? throw new InvalidOperationException("Formats camera indisponibles.");
@ -110,6 +176,107 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
?? throw new InvalidOperationException("Orientation du capteur camera indisponible.");
using var facing = characteristics.Get(CameraCharacteristics.LensFacing) as Java.Lang.Integer
?? throw new InvalidOperationException("Position du capteur camera indisponible.");
_sensorDegrees = sensor.IntValue();
_frontFacing = facing.IntValue() == (int)LensFacing.Front;
var rotation = GetRotation();
var previewOnly = output is null && pipeOutput is null;
if (!previewOnly)
{
#pragma warning disable CS0618
_recorder = OperatingSystem.IsAndroidVersionAtLeast(31)
? new MediaRecorder(_context) : new MediaRecorder();
#pragma warning restore CS0618
_recorder.Error += OnRecorderError;
if (microphone) _recorder.SetAudioSource(AudioSource.Mic);
_recorder.SetVideoSource(VideoSource.Surface);
_recorder.SetOutputFormat(OutputFormat.Mpeg2Ts);
_recorder.SetVideoSize(rotation is 90 or 270 ? size.Height : size.Width,
rotation is 90 or 270 ? size.Width : size.Height);
_recorder.SetVideoFrameRate(30);
_recorder.SetVideoEncodingBitRate(1200000);
_recorder.SetVideoEncoder(VideoEncoder.H264);
if (microphone)
{
_recorder.SetAudioSamplingRate(48000);
_recorder.SetAudioChannels(1);
_recorder.SetAudioEncodingBitRate(96000);
_recorder.SetAudioEncoder(AudioEncoder.Aac);
}
var pipe = ParcelFileDescriptor.CreatePipe()
?? throw new IOException("Creation du canal MPEG-TS impossible.");
_readPipe = pipe[0];
_writePipe = pipe[1];
_recorder.SetOutputFile(_writePipe.FileDescriptor);
await Task.Run(_recorder.Prepare, ct);
_surface = _recorder.Surface ?? throw new InvalidOperationException("Surface encodeur indisponible.");
}
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
_rotator = await AndroidCameraFrameRotator.CreateAsync(_surface, size.Width, size.Height, rotation, Fail,
blur ? _context : null);
_preview = new AndroidCapturePreview(_rotator);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
var cameraSurface = _rotator.CameraSurface;
var opened = new TaskCompletionSource<CameraDevice>(TaskCreationOptions.RunContinuationsAsynchronously);
manager.OpenCamera(cameraId, new DeviceCallback(this, opened), _handler);
_camera = await opened.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
var configured = new TaskCompletionSource<CameraCaptureSession>(TaskCreationOptions.RunContinuationsAsynchronously);
#pragma warning disable CS0618, CA1422
_camera.CreateCaptureSession(new List<Surface> { cameraSurface }, new SessionCallback(this, configured), _handler);
#pragma warning restore CS0618, CA1422
_session = await configured.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
using var request = _camera.CreateCaptureRequest(previewOnly ? CameraTemplate.Preview : CameraTemplate.Record);
request.AddTarget(cameraSurface);
using var built = request.Build();
if (pipeOutput != null)
await pipeOutput(_readPipe!.Fd, ct);
else if (output is not null)
{
var handle = new SafeFileHandle((IntPtr)_readPipe!.Fd, ownsHandle: false);
var stream = new FileStream(handle, FileAccess.Read);
_pump = Task.Run(async () =>
{
using (handle)
using (stream)
{
try
{
await output(stream, CancellationToken.None);
if (_failure is not null) throw new IOException("Capture Android interrompue.", _failure);
if (!_stopped) throw new IOException("Le flux de capture Android s'est ferme prematurement.");
_completion.TrySetResult();
}
catch (Exception ex)
{
_completion.TrySetException(ex);
// Drain until MediaRecorder stops, so its writer cannot block Stop().
await stream.CopyToAsync(Stream.Null);
}
}
});
}
if (_recorder is not null)
{
await Task.Run(_recorder.Start, ct);
_started = true;
}
_displayManager = _context.GetSystemService(Context.DisplayService) as DisplayManager
?? throw new InvalidOperationException("Service d'affichage Android indisponible.");
_rotationListener = new RotationListener(this);
_displayManager.RegisterDisplayListener(_rotationListener, _handler);
await _rotator.SetRotationAsync(GetRotation());
await _rotator.StartAsync();
_session.SetRepeatingRequest(built, null, _handler);
_writePipe?.Close();
_writePipe?.Dispose();
_writePipe = null;
}
private int GetRotation()
{
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
#pragma warning disable CS0618, CA1422
var display = OperatingSystem.IsAndroidVersionAtLeast(30)
@ -125,86 +292,27 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
SurfaceOrientation.Rotation270 => 270,
_ => throw new InvalidOperationException($"Rotation d'ecran Android inconnue : {displayRotation}.")
};
var rotation = CameraFrameOrientation.GetRotation(sensor.IntValue(), displayDegrees,
facing.IntValue() == (int)LensFacing.Front);
var rotation = CameraFrameOrientation.GetRotation(_sensorDegrees, displayDegrees, _frontFacing);
global::Android.Util.Log.Info("PostIt.Podcast",
$"Camera orientation: sensor={sensor.IntValue()}, display={displayDegrees}, facing={facing.IntValue()}, rotation={rotation}");
OrientationDiagnostics = $"sensor={sensor.IntValue()}, display={displayDegrees}, facing={facing.IntValue()}, rotation={rotation}";
#pragma warning disable CS0618
_recorder = OperatingSystem.IsAndroidVersionAtLeast(31)
? new MediaRecorder(_service) : new MediaRecorder();
#pragma warning restore CS0618
_recorder.Error += OnRecorderError;
if (microphone) _recorder.SetAudioSource(AudioSource.Mic);
_recorder.SetVideoSource(VideoSource.Surface);
_recorder.SetOutputFormat(OutputFormat.Mpeg2Ts);
_recorder.SetVideoSize(rotation is 90 or 270 ? size.Height : size.Width,
rotation is 90 or 270 ? size.Width : size.Height);
_recorder.SetVideoFrameRate(30);
_recorder.SetVideoEncodingBitRate(1200000);
_recorder.SetVideoEncoder(VideoEncoder.H264);
if (microphone)
$"Camera orientation: sensor={_sensorDegrees}, display={displayDegrees}, front={_frontFacing}, rotation={rotation}");
OrientationDiagnostics = $"sensor={_sensorDegrees}, display={displayDegrees}, front={_frontFacing}, rotation={rotation}";
return rotation;
}
private sealed class RotationListener(AndroidPodcastCapture capture) : Java.Lang.Object, DisplayManager.IDisplayListener
{
public void OnDisplayAdded(int displayId) { }
public void OnDisplayRemoved(int displayId) { }
public async void OnDisplayChanged(int displayId)
{
_recorder.SetAudioSamplingRate(48000);
_recorder.SetAudioChannels(1);
_recorder.SetAudioEncodingBitRate(96000);
_recorder.SetAudioEncoder(AudioEncoder.Aac);
}
var pipe = ParcelFileDescriptor.CreatePipe()
?? throw new IOException("Creation du canal MPEG-TS impossible.");
_readPipe = pipe[0];
_writePipe = pipe[1];
_recorder.SetOutputFile(_writePipe.FileDescriptor);
await Task.Run(_recorder.Prepare, ct);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
_surface = _recorder.Surface ?? throw new InvalidOperationException("Surface encodeur indisponible.");
_rotator = await AndroidCameraFrameRotator.CreateAsync(_surface, size.Width, size.Height, rotation, Fail);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
var cameraSurface = _rotator.CameraSurface;
var opened = new TaskCompletionSource<CameraDevice>(TaskCreationOptions.RunContinuationsAsynchronously);
manager.OpenCamera(cameraId, new DeviceCallback(this, opened), _handler);
_camera = await opened.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
var configured = new TaskCompletionSource<CameraCaptureSession>(TaskCreationOptions.RunContinuationsAsynchronously);
#pragma warning disable CS0618, CA1422
_camera.CreateCaptureSession(new List<Surface> { cameraSurface }, new SessionCallback(this, configured), _handler);
#pragma warning restore CS0618, CA1422
_session = await configured.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
using var request = _camera.CreateCaptureRequest(CameraTemplate.Record);
request.AddTarget(cameraSurface);
using var built = request.Build();
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
var stream = new FileStream(handle, FileAccess.Read);
_pump = Task.Run(async () =>
{
using (handle)
using (stream)
try
{
try
{
await new TransportStreamCapture(directory).RunAsync(stream, CancellationToken.None);
if (_failure is not null) throw new IOException("Capture Android interrompue.", _failure);
if (!_stopped) throw new IOException("Le flux de capture Android s'est ferme prematurement.");
_completion.TrySetResult();
}
catch (Exception ex)
{
_completion.TrySetException(ex);
// Drain until MediaRecorder stops, so its writer cannot block Stop().
await stream.CopyToAsync(System.IO.Stream.Null);
}
if (!capture._stopRequested && MainActivity.Current is { IsDestroyed: false }
&& capture._rotator is { } rotator)
await rotator.SetRotationAsync(capture.GetRotation());
}
});
await Task.Run(_recorder.Start, ct);
_started = true;
await _rotator.StartAsync();
_session.SetRepeatingRequest(built, null, _handler);
_writePipe.Close();
_writePipe.Dispose();
_writePipe = null;
catch (Exception ex) { capture.Fail(ex); }
}
}
private sealed class DeviceCallback(AndroidPodcastCapture capture, TaskCompletionSource<CameraDevice> opened)
@ -286,12 +394,48 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
{
if (_stopped) return;
_stopped = true;
await Task.Run(StopNative);
await _pump;
try
{
if (_preview is not null)
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(_preview.Dispose);
}
finally
{
try { await StopOutputAsync(); }
finally
{
await Task.Run(StopNative);
await _pump;
}
}
_completion.TrySetResult();
}
catch (Exception error)
{
_completion.TrySetException(error);
throw;
}
finally { _stopGate.Release(); }
}
private async Task StopOutputAsync()
{
if (_stopOutput == null || _readPipe == null) return;
try { await _stopOutput(); }
finally
{
// The native sender has released its reader. Drain so the recorder can always stop.
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
var stream = new FileStream(handle, FileAccess.Read);
_pump = Task.Run(async () =>
{
using (handle)
using (stream)
await stream.CopyToAsync(Stream.Null);
});
}
}
private void StopNative()
{
try
@ -307,6 +451,14 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
finally
{
_started = false;
if (_rotationListener is not null)
{
_displayManager?.UnregisterDisplayListener(_rotationListener);
_rotationListener.Dispose();
_rotationListener = null;
}
_displayManager?.Dispose();
_displayManager = null;
_session?.Close();
_session?.Dispose();
_session = null;
@ -337,12 +489,17 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
try { await StopAsync(); }
finally
{
Platform.PlaybackSuspending -= RequestStop;
_readPipe?.Dispose();
_readPipe = null;
_service.Capture = null;
_service.StopSelf();
if (_service is not null)
{
_service.Capture = null;
_service.StopSelf();
}
_handler.Dispose();
_stopGate.Dispose();
CaptureGate.Release();
}
}
}

View file

@ -0,0 +1,39 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers;
using PostIt.Services;
namespace PostIt.Android.Services;
internal static class AndroidServiceProvider
{
private static readonly Lazy<IServiceProvider> Provider = new(() =>
{
var provider = new ServiceCollection().BuildPostItServices();
var api = provider.GetRequiredService<YavscApiClient>();
api.Settings.Saved += (_, _) =>
{
if (!api.Settings.AndroidKeepChatConnected) AndroidBackgroundChatService.Invalidate();
ChatBootState.Save(api);
};
api.Settings.Applied += (_, _) =>
{
if (api.Settings.AndroidKeepChatConnected)
AndroidBatteryOptimization.Request(api.Settings);
};
api.SigningOut += () =>
{
AndroidBackgroundChatService.Invalidate();
try { ChatBootState.MarkSignedOut(); }
catch (Exception ex)
{
global::Android.Util.Log.Error("PostIt.Chat", ex.ToString());
AndroidSettings.ReportError(api.Settings, ex.Message);
}
return System.Threading.Tasks.Task.CompletedTask;
};
return provider;
});
internal static IServiceProvider GetOrCreate() => Provider.Value;
}

View file

@ -0,0 +1,38 @@
using System;
using System.Threading.Tasks;
using PostIt.ViewModels;
namespace PostIt.Android.Services;
internal static class AndroidSettings
{
internal static Task UpdateAsync(Settings settings, Action<Settings> update)
{
if (MainActivity.Current is not { IsDestroyed: false, IsFinishing: false } activity)
{
update(settings);
return Task.CompletedTask;
}
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
activity.RunOnUiThread(() =>
{
try
{
update(settings);
completion.TrySetResult();
}
catch (Exception ex) { completion.TrySetException(ex); }
});
return completion.Task;
}
internal static void ReportError(Settings settings, string message)
{
_ = ReportAsync();
async Task ReportAsync()
{
try { await UpdateAsync(settings, s => s.SetActionStatus(message, PostIt.Models.StatusSeverity.Error)); }
catch (Exception ex) { global::Android.Util.Log.Error("PostIt.Chat", ex.ToString()); }
}
}
}

View file

@ -1,16 +1,28 @@
using System;
using System.Threading.Tasks;
using Avalonia.Android;
using Avalonia.Controls;
using Avalonia.Platform;
using LibVLCSharp.Shared;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using PostIt.Services;
using VideoView = LibVLCSharp.Platforms.Android.VideoView;
using Button = Android.Widget.Button;
namespace PostIt.Android.Services;
internal sealed class AndroidVideoSurface(MediaPlayer player) : NativeControlHost, IDisposable
internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : NativeControlHost, IDisposable
{
private VideoView? _video;
private ReplayLayout? _layout;
private bool _disposed;
private bool _playbackSubscribed;
private IDisposable? _screenAwake;
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal Task Ready => _ready.Task;
protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
{
@ -18,13 +30,34 @@ internal sealed class AndroidVideoSurface(MediaPlayer player) : NativeControlHos
?? throw new InvalidOperationException("L'activite Android est indisponible.");
var video = new VideoView(activity) { MediaPlayer = _disposed ? null : player };
_video = video;
if (!_disposed)
{
player.Playing += OnPlaybackChanged;
player.Paused += OnPlaybackChanged;
player.Stopped += OnPlaybackChanged;
player.EndReached += OnPlaybackChanged;
player.EncounteredError += OnPlaybackChanged;
_playbackSubscribed = true;
}
UpdateScreenAwake();
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
if (!_disposed) _ready.TrySetResult();
}, Avalonia.Threading.DispatcherPriority.Loaded);
if (replay && !_disposed)
{
_layout = new ReplayLayout(activity, video, player);
return new AndroidViewControlHandle(_layout);
}
return new AndroidViewControlHandle(video);
}
protected override void DestroyNativeControlCore(IPlatformHandle control)
{
if (control is AndroidViewControlHandle { View: VideoView video })
video.MediaPlayer = null;
ReleaseScreenAwake();
_layout?.Stop();
_layout = null;
if (_video is not null) _video.MediaPlayer = null;
_video = null;
base.DestroyNativeControlCore(control);
}
@ -32,6 +65,132 @@ internal sealed class AndroidVideoSurface(MediaPlayer player) : NativeControlHos
public void Dispose()
{
_disposed = true;
ReleaseScreenAwake();
_ready.TrySetCanceled();
_layout?.Stop();
if (_video is not null) _video.MediaPlayer = null;
}
private void OnPlaybackChanged(object? sender, EventArgs e)
=> Avalonia.Threading.Dispatcher.UIThread.Post(UpdateScreenAwake);
private void UpdateScreenAwake()
{
if (!_disposed && _video is not null && player.IsPlaying)
_screenAwake ??= Platform.ScreenAwake.Acquire();
else
{
_screenAwake?.Dispose();
_screenAwake = null;
}
}
private void ReleaseScreenAwake()
{
if (_playbackSubscribed)
{
player.Playing -= OnPlaybackChanged;
player.Paused -= OnPlaybackChanged;
player.Stopped -= OnPlaybackChanged;
player.EndReached -= OnPlaybackChanged;
player.EncounteredError -= OnPlaybackChanged;
_playbackSubscribed = false;
}
_screenAwake?.Dispose();
_screenAwake = null;
}
private sealed class ReplayLayout : FrameLayout
{
private readonly MediaPlayer _player;
private readonly ReplayControlsState _state = new();
private readonly Handler _handler = new(Looper.MainLooper!);
private readonly Java.Lang.Runnable _tick;
private readonly LinearLayout _bar;
private readonly Button _toggle;
private readonly SeekBar _seek;
private readonly TextView _time;
private bool _stopped;
public ReplayLayout(Context context, VideoView video, MediaPlayer player) : base(context)
{
_player = player;
AddView(video, new FrameLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent));
_bar = new LinearLayout(context) { Orientation = Orientation.Horizontal };
_bar.SetGravity(GravityFlags.CenterVertical);
_bar.SetPadding(12, 8, 12, 8);
_bar.SetBackgroundColor(global::Android.Graphics.Color.Argb(210, 20, 20, 20));
_toggle = new Button(context) { Text = "Pause", ContentDescription = "Lecture ou pause du replay" };
_seek = new SeekBar(context) { Max = 10000, ContentDescription = "Position dans le replay" };
_time = new TextView(context);
_time.SetTextColor(global::Android.Graphics.Color.White);
_bar.AddView(_toggle);
_bar.AddView(_seek, new LinearLayout.LayoutParams(0, LayoutParams.WrapContent, 1));
_bar.AddView(_time);
AddView(_bar, new FrameLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent, GravityFlags.Bottom));
_toggle.Click += Toggle;
_seek.StartTrackingTouch += BeginSeek;
_seek.StopTrackingTouch += EndSeek;
_seek.ProgressChanged += ProgressChanged;
_tick = new Java.Lang.Runnable(Update);
_handler.Post(_tick);
}
public override bool DispatchTouchEvent(MotionEvent? e)
{
_state.Show();
_bar.Visibility = ViewStates.Visible;
return base.DispatchTouchEvent(e);
}
private void Update()
{
if (_stopped) return;
var duration = Math.Max(0, _player.Length);
var position = Math.Max(0, _player.Time);
_bar.Visibility = _state.IsVisible(_player.IsPlaying, _bar.HasFocus) ? ViewStates.Visible : ViewStates.Gone;
_toggle.Text = _player.IsPlaying ? "Pause" : "Lire";
_seek.Enabled = duration > 0 && _player.IsSeekable;
if (!_state.IsInteracting)
_seek.Progress = duration > 0 ? (int)Math.Clamp(position * 10000d / duration, 0, 10000) : 0;
_time.Text = $"{ReplayControlsState.FormatTime(_state.IsInteracting ? (long)(duration * (_seek.Progress / 10000d)) : position)} / {ReplayControlsState.FormatTime(duration)}";
_handler.PostDelayed(_tick, 250);
}
private void Toggle(object? sender, EventArgs e)
{
if (_player.IsPlaying) _player.Pause();
else _player.Play();
_state.Show();
}
private void BeginSeek(object? sender, SeekBar.StartTrackingTouchEventArgs e) => _state.IsInteracting = true;
private void EndSeek(object? sender, SeekBar.StopTrackingTouchEventArgs e)
{
Seek();
_state.IsInteracting = false;
}
private void ProgressChanged(object? sender, SeekBar.ProgressChangedEventArgs e)
{
if (e.FromUser && !_state.IsInteracting) Seek();
}
private void Seek()
{
if (_player.IsSeekable) _player.Time = (long)(_player.Length * (_seek.Progress / 10000d));
_state.Show();
}
public void Stop()
{
if (_stopped) return;
_stopped = true;
_handler.RemoveCallbacks(_tick);
_toggle.Click -= Toggle;
_seek.StartTrackingTouch -= BeginSeek;
_seek.StopTrackingTouch -= EndSeek;
_seek.ProgressChanged -= ProgressChanged;
_tick.Dispose();
_handler.Dispose();
}
}
}

View file

@ -0,0 +1,164 @@
using System;
using System.Diagnostics;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Runtime;
using Avalonia.Android;
using Avalonia.Controls;
using Avalonia.Platform;
using PostIt.Services;
namespace PostIt.Android.Services;
[SupportedOSPlatform("android26.0")]
internal sealed class AndroidWebRtcMedia : WebRtcNativeMedia
{
private readonly CancellationTokenSource _lifetime = new();
private readonly Peer _peer;
private readonly Surface _local;
private readonly Surface _remote;
private readonly Task _poll;
private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _disposed;
public override Control LocalVideo => _local;
public override Control RemoteVideo => _remote;
public AndroidWebRtcMedia()
{
_peer = new Peer(MainActivity.Current ?? throw new InvalidOperationException("Activité Android indisponible."));
_local = new Surface(_peer.GetView("localView"));
_remote = new Surface(_peer.GetView("remoteView"));
_poll = Task.Run(PollAsync);
}
protected override async Task StartCoreAsync(WebRtcMediaConfiguration configuration, CancellationToken ct)
{
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activité Android indisponible.");
await PodcastPermissions.EnsureAsync(activity, microphone: true, ct, notifications: false);
if (!MainActivity.IsForeground)
throw new InvalidOperationException("Revenez dans PostIt pour demarrer l'appel.");
await Task.WhenAll(_local.Ready, _remote.Ready).WaitAsync(TimeSpan.FromSeconds(10), ct);
await SendCommandAsync(StartCommand(configuration), ct);
}
protected override Task SendCommandAsync(string json, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
_peer.Command(json);
return Task.CompletedTask;
}
private async Task PollAsync()
{
var stats = Stopwatch.StartNew();
var failed = false;
try
{
while (!_lifetime.IsCancellationRequested)
{
for (var i = 0; i < 64 && _peer.Poll() is { } message; i++)
{
if (message == "{\"type\":\"closed\"}") _closed.TrySetResult();
if (!failed)
{
try { ProcessMessage(message); }
catch (Exception error)
{
failed = true;
Fail(error);
if (_disposed) _closed.TrySetException(error);
}
}
}
if (!_disposed && !failed && Configuration is not null && stats.Elapsed >= TimeSpan.FromSeconds(1))
{
_peer.Command("{\"command\":\"stats\"}");
stats.Restart();
}
await Task.Delay(20, _lifetime.Token);
}
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
catch (Exception error) { Fail(error); _closed.TrySetException(error); }
}
public override async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
try
{
_peer.Command("{\"command\":\"close\"}");
await _closed.Task.WaitAsync(TimeSpan.FromSeconds(10));
}
finally
{
_lifetime.Cancel();
await _poll;
_peer.Dispose();
_lifetime.Dispose();
Closed();
}
}
private sealed class Surface(global::Android.Views.View view) : NativeControlHost
{
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task Ready => _ready.Task;
protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
{
_ready.TrySetResult();
return new AndroidViewControlHandle(view);
}
}
// Only this small Java bridge crosses JNI. SDP and ICE callbacks stay in Java,
// where the native SDK owns their lifetime and thread affinity.
private sealed class Peer : IDisposable
{
private readonly Java.Lang.Class _type;
private readonly Java.Lang.Object _instance;
private readonly Java.Lang.Reflect.Method _command;
private readonly Java.Lang.Reflect.Method _poll;
public Peer(Context context)
{
_type = Java.Lang.Class.ForName("fr.pschneider.postit.WebRtcPeer")!;
using var contextType = Java.Lang.Class.FromType(typeof(Context));
using var constructor = _type.GetConstructor(contextType);
_instance = constructor!.NewInstance(context)!;
using var stringType = Java.Lang.Class.FromType(typeof(Java.Lang.String));
_command = _type.GetMethod("command", stringType)!;
_poll = _type.GetMethod("poll")!;
}
public global::Android.Views.View GetView(string method)
{
using var getter = _type.GetMethod(method);
return getter!.Invoke(_instance)!.JavaCast<global::Android.Views.View>()!;
}
public void Command(string message)
{
using var value = new Java.Lang.String(message);
_command.Invoke(_instance, value);
}
public string? Poll()
{
using var result = _poll.Invoke(_instance);
return result?.ToString();
}
public void Dispose()
{
_command.Dispose();
_poll.Dispose();
_instance.Dispose();
_type.Dispose();
}
}
}

View file

@ -37,14 +37,21 @@ internal static class CameraFrameOrientation
throw new ArgumentException("A SurfaceTexture transform must contain 16 elements.", nameof(textureMatrix));
// SurfaceTexture's usual Y flip changes the sign of the first column's Y.
// Camera2 can also put the sensor rotation in this matrix; don't apply it twice.
var angle = Math.Atan2(-textureMatrix[1], textureMatrix[0]) * 180 / Math.PI;
// Front cameras can add a mirror: with Rot(p)·Mirror·Rot(r) = Rot(p - r)·Mirror,
// the remaining rotation must then be applied in the opposite direction.
var mirrored = textureMatrix[4] * textureMatrix[1] - textureMatrix[0] * textureMatrix[5] < 0;
var angle = mirrored
? Math.Atan2(textureMatrix[1], -textureMatrix[0]) * 180 / Math.PI
: Math.Atan2(-textureMatrix[1], textureMatrix[0]) * 180 / Math.PI;
if (!double.IsFinite(angle) || (textureMatrix[0] == 0 && textureMatrix[1] == 0))
throw new ArgumentException("Invalid SurfaceTexture orientation.", nameof(textureMatrix));
var quarterTurns = (int)Math.Round(angle / 90);
if (Math.Abs(angle - quarterTurns * 90) > 0.01)
throw new ArgumentException("SurfaceTexture orientation is not a quarter turn.", nameof(textureMatrix));
var producerRotation = (quarterTurns * 90 + 360) % 360;
return (clockwiseDegrees - producerRotation + 360) % 360;
return mirrored
? (producerRotation - clockwiseDegrees + 360) % 360
: (clockwiseDegrees - producerRotation + 360) % 360;
}
private static void Validate(int degrees)

View file

@ -0,0 +1,46 @@
using System;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Util;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Models;
using PostIt.Services;
namespace PostIt.Android.Services;
[BroadcastReceiver(Name = "fr.pschneider.postit.ChatBootReceiver", Enabled = true, Exported = true)]
[IntentFilter([Intent.ActionBootCompleted])]
public sealed class ChatBootReceiver : BroadcastReceiver
{
public override void OnReceive(Context? context, Intent? intent)
{
if (context is null || intent?.Action != Intent.ActionBootCompleted || !ChatBootState.OptedIn) return;
var epoch = AndroidBackgroundChatService.Epoch.Restore();
if (epoch is null) return;
var pending = GoAsync();
_ = Task.Run(() =>
{
YavscApiClient? api = null;
try
{
api = AndroidServiceProvider.GetOrCreate().GetRequiredService<YavscApiClient>();
if (!ChatBootState.CanStart(api)) return;
var identity = ChatBootState.Identity(api);
if (identity is null || !AndroidBackgroundChatService.StartNative(context, epoch, identity)) return;
Log.Info("PostIt.Chat", "Best-effort chat restart requested after boot.");
}
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Boot restart rejected: " + ex);
if (api is not null)
{
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
AndroidSettings.ReportError(api.Settings,
"Android a refuse le redemarrage de la messagerie : " + ex.Message);
}
}
finally { pending?.Finish(); }
});
}
}

View file

@ -0,0 +1,74 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using Android.Content;
using PostIt.Services;
namespace PostIt.Android.Services;
internal static class ChatBootState
{
private static ISharedPreferences Preferences =>
global::Android.App.Application.Context.GetSharedPreferences("postit-chat-service", FileCreationMode.Private)!;
internal static bool OptedIn => Preferences.GetBoolean("enabled", false);
internal static void Save(YavscApiClient api)
{
var identity = Identity(api);
var saved = Preferences.Edit()!
.PutBoolean("enabled", api.Settings.AndroidKeepChatConnected)!
.PutBoolean("signed-in", !api.IsSigningOut && api.HasValidSession && identity is not null)!
.PutString("identity", identity)!.Commit();
if (!saved) throw new IOException("Impossible d'enregistrer l'etat Android de la messagerie.");
}
internal static void MarkSignedOut()
{
if (!Preferences.Edit()!.PutBoolean("signed-in", false)!.Commit())
throw new IOException("Impossible d'enregistrer la deconnexion Android.");
}
internal static bool CanStart(YavscApiClient api)
{
if (!OptedIn || !api.Settings.AndroidKeepChatConnected || api.IsSigningOut || !api.HasValidSession)
return false;
var identity = Identity(api);
if (identity is null) return false;
var signedIn = Preferences.GetBoolean("signed-in", false);
var storedIdentity = Preferences.GetString("identity", null);
// A valid refresh-capable session can coexist with stale native prefs
// (for example after app relaunch or an interrupted token renewal).
// Treat missing/lagging prefs as recoverable instead of rejecting the
// start outright, but keep strict identity matching when both values exist.
if (!signedIn && string.IsNullOrEmpty(storedIdentity)) return true;
if (signedIn && !string.IsNullOrEmpty(storedIdentity)) return identity == storedIdentity;
return true;
}
internal static string? Identity(YavscApiClient api)
{
var token = api.CurrentIdToken ?? api.CurrentAccessToken;
if (string.IsNullOrEmpty(token)) return null;
try
{
var parts = token.Split('.');
if (parts.Length != 3) return null;
var payload = parts[1].Replace('-', '+').Replace('_', '/');
payload = payload.PadRight((payload.Length + 3) / 4 * 4, '=');
using var json = JsonDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload)));
if (!json.RootElement.TryGetProperty("sub", out var subject)
|| string.IsNullOrEmpty(subject.GetString())) return null;
return $"{api.Settings.ApiUrl.TrimEnd('/')}\n{api.Settings.Authentication.Authority.TrimEnd('/')}\n{subject.GetString()}";
}
catch (Exception ex) when (ex is FormatException or JsonException or InvalidOperationException)
{
global::Android.Util.Log.Warn("PostIt.Chat", "Session identity unavailable for boot restart.");
return null;
}
}
}

View file

@ -0,0 +1,296 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using AndroidX.Core.App;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Models;
using PostIt.Services;
using PostIt.ViewModels.Chat;
using OperationCanceledException = System.OperationCanceledException;
namespace PostIt.Android.Services;
[Service(Name = "fr.pschneider.postit.ChatConnectionService", Exported = false)]
public sealed class ChatConnectionService : Service
{
private const string MessageChannel = "postit-chat-messages";
private const int MessageNotificationId = 4053;
private static readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> Startups = new();
private static volatile ChatConnectionService? _current;
private CancellationTokenSource _stop = new();
private string? _epoch;
private readonly List<IDisposable> _subscriptions = [];
private readonly object _observerGate = new();
private YavscApiClient? _api;
private ChatHubConnection? _transport;
private HubConnection? _observedConnection;
private Task? _loop;
private volatile bool _destroyed;
private bool _wasConnected;
internal static async Task StartAndWaitAsync(Context context, string epoch, string identity, CancellationToken ct)
{
var pending = Startups.GetOrAdd(epoch,
_ => new(TaskCreationOptions.RunContinuationsAsynchronously));
try
{
ct.ThrowIfCancellationRequested();
if (!AndroidBackgroundChatService.StartNative(context, epoch, identity))
throw new OperationCanceledException("Demarrage de messagerie obsolete.", ct);
await pending.Task.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
}
catch
{
// Cancel only the owner of this attempt, never a later re-enable.
AndroidBackgroundChatService.Cancel(epoch);
throw;
}
finally
{
Startups.TryRemove(epoch, out _);
}
}
internal static void Suspend()
{
foreach (var startup in Startups)
if (!AndroidBackgroundChatService.IsCurrent(startup.Key))
startup.Value.TrySetException(new OperationCanceledException("Demarrage de messagerie annule."));
if (_current is not { } current) return;
current._stop.Cancel();
current.FailStartup(new OperationCanceledException("Demarrage de messagerie annule."));
}
public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
{
var epoch = intent is null
? AndroidBackgroundChatService.Epoch.Restore()
: intent.GetStringExtra(AndroidBackgroundChatService.EpochExtra);
try
{
if (!AndroidBackgroundChatService.IsCurrent(epoch))
{
if (_current == this && AndroidBackgroundChatService.IsCurrent(_epoch))
return StartCommandResult.Sticky;
StopSelfResult(startId);
return StartCommandResult.NotSticky;
}
EnsureChannels();
var provider = AndroidServiceProvider.GetOrCreate();
_api = provider.GetRequiredService<YavscApiClient>();
_transport = provider.GetRequiredService<ChatHubConnection>();
var identity = intent is null ? ChatBootState.Identity(_api)
: intent.GetStringExtra(AndroidBackgroundChatService.IdentityExtra);
if (!ChatBootState.CanStart(_api) || identity is null || identity != ChatBootState.Identity(_api))
throw new BackgroundChatException(BackgroundChatFailure.SessionRequired,
"Connexion de fond inactive : option ou session absente.");
_api.StartSessionMaintenance();
if (!AndroidBackgroundChatService.Epoch.Run(epoch, () =>
{
if (_epoch == epoch && _loop is { IsCompleted: false } && !_stop.IsCancellationRequested)
{
if (_transport.Connection.State == HubConnectionState.Connected) CompleteStartup(epoch!);
return;
}
_stop.Cancel();
_stop = new CancellationTokenSource();
_epoch = epoch;
_current = this;
_wasConnected = false;
_loop = RunAsync(epoch!, _stop.Token);
}))
{
StopSelfResult(startId);
return StartCommandResult.NotSticky;
}
return StartCommandResult.Sticky;
}
catch (Exception ex)
{
ReportError(ex);
if (epoch is not null)
{
if (Startups.TryGetValue(epoch, out var pending)) pending.TrySetException(ex);
AndroidBackgroundChatService.Cancel(epoch);
}
if (!AndroidBackgroundChatService.IsCurrent(_epoch)) StopSelfResult(startId);
return StartCommandResult.NotSticky;
}
}
private async Task RunAsync(string epoch, CancellationToken ct)
{
while (!ct.IsCancellationRequested && AndroidBackgroundChatService.IsCurrent(epoch))
{
if (_api is null || _transport is null || !ChatBootState.CanStart(_api))
{
FailStartup(new BackgroundChatException(BackgroundChatFailure.SessionRequired,
"La connexion de fond necessite une session active."), epoch);
AndroidBackgroundChatService.Cancel(epoch);
return;
}
try
{
var connection = await _transport.GetConnectionAsync().ConfigureAwait(false);
if (ct.IsCancellationRequested || !AndroidBackgroundChatService.IsCurrent(epoch)) return;
Observe(connection);
if (connection.State == HubConnectionState.Disconnected)
{
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
attempt.CancelAfter(TimeSpan.FromSeconds(20));
await _transport.StartAsync(attempt.Token).ConfigureAwait(false);
}
if (connection.State == HubConnectionState.Connected)
{
if (!_wasConnected)
await AndroidSettings.UpdateAsync(_api.Settings,
s =>
{
if (!_destroyed && AndroidBackgroundChatService.IsCurrent(epoch)
&& ChatBootState.CanStart(_api))
s.SetActionStatus(NotificationPermission.IsGranted(this)
? "Connexion de fond active sans notification permanente. Android peut l'interrompre."
: "SignalR actif sans notification permanente. Alertes desactivees dans Android.",
NotificationPermission.IsGranted(this) ? StatusSeverity.Info : StatusSeverity.Warning);
})
.ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
if (!AndroidBackgroundChatService.IsCurrent(epoch)) return;
if (!ChatBootState.CanStart(_api)) { AndroidBackgroundChatService.Cancel(epoch); return; }
_wasConnected = true;
CompleteStartup(epoch);
}
else
{
_wasConnected = false;
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex)
{
if (!AndroidBackgroundChatService.IsCurrent(epoch)) return;
_wasConnected = false;
var failure = new BackgroundChatException(BackgroundChatFailure.ConnectionFailed,
"Connexion de fond indisponible ; nouvelle tentative automatique. " + ex.Message, ex);
ReportError(failure);
FailStartup(failure, epoch);
}
try { await Task.Delay(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
}
}
private void Observe(HubConnection connection)
{
lock (_observerGate)
{
if (_destroyed || ReferenceEquals(connection, _observedConnection)) return;
ClearSubscriptions();
_observedConnection = connection;
_subscriptions.Add(connection.On<string, string, string>("notifyUser", (type, _, _) =>
{
if (type is "pv" or "private" or "private_message" or "PrivateMessage")
NotifyMessage("Nouveau message prive. Ouvrez PostIt.");
}));
// The current Yavsc hub delivers private chat under addPV.
_subscriptions.Add(connection.On<string, string>("addPV", (_, _) =>
NotifyMessage("Nouveau message prive. Ouvrez PostIt.")));
_subscriptions.Add(connection.On<ChatMessage>("ReceiveMessage", _ =>
NotifyMessage("Nouveau message dans un salon. Ouvrez PostIt.")));
_subscriptions.Add(connection.On<string, string>("push", (_, _) =>
NotifyMessage("Nouvelle notification d'activite. Ouvrez PostIt.")));
}
}
private void NotifyMessage(string text)
{
if (_destroyed || _stop.IsCancellationRequested || !AndroidBackgroundChatService.IsCurrent(_epoch)
|| MainActivity.IsForeground
|| _api is null || !ChatBootState.CanStart(_api)
|| !NotificationPermission.IsGranted(this)) return;
try
{
var builder = new NotificationCompat.Builder(this, MessageChannel);
builder.SetSmallIcon(Yavsc.Resource.Drawable.ic_stat_postit);
builder.SetContentTitle("PostIt");
builder.SetContentText(text);
builder.SetVisibility(NotificationCompat.VisibilityPrivate);
builder.SetContentIntent(OpenApp());
builder.SetAutoCancel(true);
builder.SetOnlyAlertOnce(false);
GetNotificationManager().Notify(MessageNotificationId, builder.Build());
}
catch (Exception ex) { ReportError(ex); }
}
private void EnsureChannels()
{
if (!OperatingSystem.IsAndroidVersionAtLeast(26)) return;
var manager = (NotificationManager?)GetSystemService(NotificationService)
?? throw new InvalidOperationException("Notifications Android indisponibles.");
manager.CreateNotificationChannel(new NotificationChannel(MessageChannel,
"Messages et activite", NotificationImportance.Default));
}
private PendingIntent? OpenApp()
{
var launch = PackageManager?.GetLaunchIntentForPackage(PackageName!);
return launch is null ? null : PendingIntent.GetActivity(this, 4053, launch,
PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
}
private NotificationManagerCompat GetNotificationManager() =>
NotificationManagerCompat.From(this)
?? throw new InvalidOperationException("Notifications Android indisponibles.");
private void ReportError(Exception ex)
{
Log.Error("PostIt.Chat", ex.ToString());
_api?.QueueExceptionReport(ex, "PostIt.Android.Chat");
if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message);
}
private static void CompleteStartup(string epoch)
{
if (Startups.TryGetValue(epoch, out var pending)) pending.TrySetResult(true);
}
private void FailStartup(Exception ex, string? epoch = null)
{
epoch ??= _epoch;
if (epoch is not null && Startups.TryGetValue(epoch, out var pending)) pending.TrySetException(ex);
}
private void ClearSubscriptions()
{
lock (_observerGate)
{
foreach (var subscription in _subscriptions) subscription.Dispose();
_subscriptions.Clear();
_observedConnection = null;
}
}
public override void OnDestroy()
{
_destroyed = true;
_stop.Cancel();
ClearSubscriptions();
if (ReferenceEquals(_current, this))
{
_current = null;
FailStartup(new OperationCanceledException("Service de messagerie arrete."));
}
// The socket belongs to the shared process session, not this service.
base.OnDestroy();
}
public override IBinder? OnBind(Intent? intent) => null;
}

View file

@ -0,0 +1,70 @@
using System;
namespace PostIt.Android.Services;
/// <summary>Serializes native launch ownership, including intents delivered after cancellation.</summary>
internal sealed class ChatServiceEpoch
{
private readonly object _gate = new();
private readonly string _process = Guid.NewGuid().ToString("N");
private long _epoch;
private bool _enabled;
internal string Begin()
{
lock (_gate)
{
if (!_enabled) { ++_epoch; _enabled = true; }
return Current;
}
}
internal string? Restore()
{
lock (_gate)
{
// Only a genuinely fresh process may restore without a new user request.
if (_epoch == 0) { ++_epoch; _enabled = true; }
return _enabled ? Current : null;
}
}
internal bool IsCurrent(string? epoch)
{
lock (_gate) return _enabled && epoch == Current;
}
internal bool Run(string? epoch, Action action)
{
lock (_gate)
{
if (!_enabled || epoch != Current) return false;
action();
return true;
}
}
internal void Invalidate(Action stop)
{
lock (_gate)
{
++_epoch;
_enabled = false;
stop();
}
}
internal bool Cancel(string epoch, Action stop)
{
lock (_gate)
{
if (!_enabled || epoch != Current) return false;
++_epoch;
_enabled = false;
stop();
return true;
}
}
private string Current => $"{_process}:{_epoch}";
}

View file

@ -0,0 +1,85 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.PM;
using AndroidX.Core.App;
using AndroidX.Core.Content;
namespace PostIt.Android.Services;
/// <summary>Runtime POST_NOTIFICATIONS request (Android 13+), routed through MainActivity.</summary>
internal static class NotificationPermission
{
private const int RequestCode = 4051;
private const string AskedKey = "notification-permission-asked";
private const string PermissionName = "android.permission.POST_NOTIFICATIONS";
private static TaskCompletionSource<bool>? _pending;
internal static bool IsGranted(Context context)
=> (!OperatingSystem.IsAndroidVersionAtLeast(33)
|| ContextCompat.CheckSelfPermission(context, PermissionName) == Permission.Granted)
&& NotificationManagerCompat.From(context)?.AreNotificationsEnabled() == true;
internal static async Task<bool> RequestAsync(Activity activity, CancellationToken ct)
{
if (IsGranted(activity)) return true;
if (!OperatingSystem.IsAndroidVersionAtLeast(33))
return false; // Disabled from system settings: no runtime prompt exists.
if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed)
return false;
ct.ThrowIfCancellationRequested();
if (_pending is { } existing)
return await existing.Task.WaitAsync(ct).ConfigureAwait(false);
var preferences = activity.GetSharedPreferences("postit-chat-service", FileCreationMode.Private)!;
if (preferences.GetBoolean(AskedKey, false))
return false; // Subsequent retries must use Android notification settings.
var pending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
if (Interlocked.CompareExchange(ref _pending, pending, null) is { } inFlight)
return await inFlight.Task.WaitAsync(ct).ConfigureAwait(false);
activity.RunOnUiThread(() =>
{
try
{
if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed)
{
Interlocked.CompareExchange(ref _pending, null, pending);
pending.TrySetResult(false);
return;
}
if (!preferences.Edit()!.PutBoolean(AskedKey, true)!.Commit())
throw new System.IO.IOException("Impossible d'enregistrer la demande d'autorisation Android.");
ActivityCompat.RequestPermissions(activity, [PermissionName], RequestCode);
}
catch (Exception ex)
{
Interlocked.CompareExchange(ref _pending, null, pending);
pending.TrySetException(ex);
}
});
// Cancellation cancels only this waiter, not the OS request. Retain the
// request until its callback so retries cannot open a second dialog.
return await pending.Task.WaitAsync(ct).ConfigureAwait(false);
}
internal static bool HandleResult(int requestCode, string[]? permissions, Permission[]? results)
{
if (requestCode != RequestCode) return false;
var granted = false;
if (permissions is not null && results is not null)
{
var index = Array.IndexOf(permissions, PermissionName);
granted = index >= 0 && index < results.Length && results[index] == Permission.Granted;
}
Interlocked.Exchange(ref _pending, null)?.TrySetResult(granted);
return true;
}
internal static void OnActivityDestroyed() =>
Interlocked.Exchange(ref _pending, null)?.TrySetResult(false);
}

View file

@ -21,14 +21,16 @@ public sealed class PodcastCaptureService : Service
private PowerManager.WakeLock? _wakeLock;
internal AndroidPodcastCapture? Capture { get; set; }
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone, CancellationToken ct)
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone,
CancellationToken ct, bool call = false)
{
if (_pending is not null) throw new InvalidOperationException("Un direct Android est deja en cours.");
var pending = new TaskCompletionSource<PodcastCaptureService>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending = pending;
try
{
var intent = new Intent(activity, typeof(PodcastCaptureService)).PutExtra("microphone", microphone);
var intent = new Intent(activity, typeof(PodcastCaptureService))
.PutExtra("microphone", microphone).PutExtra("call", call);
activity.StartForegroundService(intent);
return await pending.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
}
@ -65,11 +67,13 @@ public sealed class PodcastCaptureService : Service
PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
var builder = new NotificationCompat.Builder(this, Channel);
builder.SetSmallIcon(global::Android.Resource.Drawable.IcMenuCamera);
builder.SetContentTitle("Podcast en direct");
builder.SetContentText("Camera active. Toucher pour revenir au direct.");
var call = intent?.GetBooleanExtra("call", false) == true;
builder.SetContentTitle(call ? "Appel audio-video LAN/VPN" : "Podcast en direct");
builder.SetContentText(call ? "Camera et microphone actifs. Toucher pour revenir a l'appel."
: "Camera active. Toucher pour revenir au direct.");
builder.SetContentIntent(open);
builder.SetOngoing(true);
builder.AddAction(global::Android.Resource.Drawable.IcMediaPause, "Arreter et publier", stop);
builder.AddAction(global::Android.Resource.Drawable.IcMediaPause, call ? "Raccrocher" : "Arreter et publier", stop);
var notification = builder.Build();
var type = (ForegroundService)0;
if (OperatingSystem.IsAndroidVersionAtLeast(30))

View file

@ -17,11 +17,11 @@ internal static class PodcastPermissions
private static TaskCompletionSource<bool>? _pending;
private static string[] _requested = [];
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct)
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct, bool notifications = true)
{
var requested = new List<string> { Manifest.Permission.Camera };
if (microphone) requested.Add(Manifest.Permission.RecordAudio);
if (OperatingSystem.IsAndroidVersionAtLeast(33)) requested.Add(Manifest.Permission.PostNotifications);
if (notifications && OperatingSystem.IsAndroidVersionAtLeast(33)) requested.Add(Manifest.Permission.PostNotifications);
var permissions = requested.ToArray();
if (permissions.All(p => ContextCompat.CheckSelfPermission(activity, p) == Permission.Granted)) return;
if (_pending is not null) throw new InvalidOperationException("Une demande de permissions est deja en cours.");
@ -30,7 +30,10 @@ internal static class PodcastPermissions
_pending = pending;
ActivityCompat.RequestPermissions(activity, permissions, RequestCode);
if (!await pending.Task.WaitAsync(ct))
throw new UnauthorizedAccessException("Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser.");
throw new UnauthorizedAccessException(notifications
? "Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser."
: microphone ? "Autorisez la camera et le microphone pour l'appel."
: "Autorisez la camera pour la previsualisation.");
}
public static bool HandleResult(int requestCode, string[]? permissions, Permission[]? results)

View file

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Android.Content;
using Microsoft.ML.OnnxRuntime;
namespace PostIt.Android.Services;
internal interface IPodcastPersonSegmenter : IDisposable
{
byte[] Segment(byte[] rgba);
}
internal sealed class PodcastPersonSegmenter : IPodcastPersonSegmenter
{
internal const int Size = 192;
private const int Pixels = Size * Size;
private readonly InferenceSession _session;
private readonly RunOptions _runOptions = new();
private readonly float[] _input = new float[3 * Pixels];
private readonly byte[] _mask = new byte[Pixels];
private readonly string _inputName;
internal PodcastPersonSegmenter(Context context)
{
using var asset = context.Assets?.Open("PodcastBackground/pphumanseg.onnx")
?? throw new InvalidOperationException("Modele de segmentation Android introuvable.");
using var model = new MemoryStream();
asset.CopyTo(model);
using var options = new SessionOptions { IntraOpNumThreads = 2, InterOpNumThreads = 1 };
_session = new InferenceSession(model.ToArray(), options);
_inputName = _session.InputNames.Single();
}
public byte[] Segment(byte[] rgba)
{
if (rgba.Length != Pixels * 4) throw new ArgumentException("Image de segmentation invalide.", nameof(rgba));
for (var y = 0; y < Size; y++)
{
for (var x = 0; x < Size; x++)
{
var pixel = y * Size + x;
var source = ((Size - 1 - y) * Size + x) * 4;
_input[pixel] = rgba[source] / 127.5f - 1;
_input[Pixels + pixel] = rgba[source + 1] / 127.5f - 1;
_input[2 * Pixels + pixel] = rgba[source + 2] / 127.5f - 1;
}
}
using var input = OrtValue.CreateTensorValueFromMemory(_input, [1, 3, Size, Size]);
using var outputs = _session.Run(_runOptions, new Dictionary<string, OrtValue> { [_inputName] = input }, _session.OutputNames);
var result = outputs[0].GetTensorDataAsSpan<float>();
if (result.Length != 2 * Pixels) throw new InvalidDataException("Sortie du modele de segmentation invalide.");
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var pixel = y * Size + x;
var background = result[pixel];
var person = result[Pixels + pixel];
if (!float.IsFinite(background) || !float.IsFinite(person))
throw new InvalidDataException("Sortie du modele de segmentation non finie.");
_mask[(Size - 1 - y) * Size + x] = person > background ? (byte)255 : (byte)0;
}
return _mask;
}
public void Dispose()
{
_session.Dispose();
_runOptions.Dispose();
}
}

View file

@ -0,0 +1,323 @@
package fr.pschneider.postit;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONObject;
import org.webrtc.*;
import org.webrtc.audio.JavaAudioDeviceModule;
import java.util.*;
import java.util.concurrent.*;
/** Keeps all SDK operations and asynchronous SDP callbacks on one executor. */
public final class WebRtcPeer {
private final Context context;
private final EglBase egl = EglBase.create();
private final SurfaceViewRenderer local;
private final SurfaceViewRenderer remote;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final ArrayBlockingQueue<String> events = new ArrayBlockingQueue<>(64);
private final List<IceCandidate> pendingLocal = new ArrayList<>();
private final List<IceCandidate> pendingRemote = new ArrayList<>();
private PeerConnectionFactory factory;
private PeerConnection peer;
private JavaAudioDeviceModule audioModule;
private VideoCapturer capturer;
private SurfaceTextureHelper texture;
private VideoSource videoSource;
private AudioSource audioSource;
private VideoTrack videoTrack;
private AudioTrack audioTrack;
private VideoTrack remoteTrack;
private boolean localDescriptionSent;
private boolean remoteDescriptionSet;
private volatile boolean closed;
private volatile boolean localRendered;
private volatile boolean remoteRendered;
public WebRtcPeer(Context context) {
this.context = context.getApplicationContext();
local = new SurfaceViewRenderer(context);
remote = new SurfaceViewRenderer(context);
local.init(egl.getEglBaseContext(), new RendererCommon.RendererEvents() {
public void onFirstFrameRendered() { localRendered = true; }
public void onFrameResolutionChanged(int width, int height, int rotation) {}
});
local.setMirror(true);
remote.init(egl.getEglBaseContext(), new RendererCommon.RendererEvents() {
public void onFirstFrameRendered() { remoteRendered = true; }
public void onFrameResolutionChanged(int width, int height, int rotation) {}
});
local.setEnableHardwareScaler(true);
remote.setEnableHardwareScaler(true);
}
public android.view.View localView() { return local; }
public android.view.View remoteView() { return remote; }
public String poll() { return events.poll(); }
private void enqueue(Runnable action) {
try {
executor.execute(() -> {
try { action.run(); }
catch (Exception failure) { error(failure.getMessage()); }
});
} catch (RejectedExecutionException failure) {
if (!closed) throw failure;
}
}
public void command(String json) {
enqueue(() -> {
try {
JSONObject message = new JSONObject(json);
switch (message.getString("command")) {
case "start": start(message.getJSONObject("configuration")); break;
case "signal": signal(message.getJSONObject("signal")); break;
case "stats": if (peer != null && !closed) peer.getStats(this::stats); break;
case "close": close(); break;
default: throw new IllegalArgumentException("Unknown WebRTC command");
}
} catch (Exception error) { error(error.getMessage()); }
});
}
private void emit(JSONObject value) {
if (!events.offer(value.toString())) {
events.clear();
events.offer("{\"type\":\"error\",\"message\":\"WebRTC event queue overflow\"}");
}
}
private void error(String message) {
try { emit(new JSONObject().put("type", "error").put("message", message)); }
catch (org.json.JSONException impossible) { throw new IllegalStateException(impossible); }
}
private void start(JSONObject configuration) throws Exception {
if (factory != null || closed) throw new IllegalStateException("WebRTC already started or closed");
PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(context)
.setEnableInternalTracer(false).createInitializationOptions());
audioModule = JavaAudioDeviceModule.builder(context).createAudioDeviceModule();
factory = PeerConnectionFactory.builder().setAudioDeviceModule(audioModule)
.setVideoEncoderFactory(new DefaultVideoEncoderFactory(egl.getEglBaseContext(), true, true))
.setVideoDecoderFactory(new DefaultVideoDecoderFactory(egl.getEglBaseContext())).createPeerConnectionFactory();
List<PeerConnection.IceServer> servers = new ArrayList<>();
JSONArray configuredServers = configuration.getJSONArray("iceServers");
boolean relay = configuration.getBoolean("relayOnly");
for (int i = 0; i < configuredServers.length(); i++) {
JSONObject item = configuredServers.getJSONObject(i);
JSONArray urls = item.getJSONArray("urls");
for (int j = 0; j < urls.length(); j++) {
String url = urls.getString(j);
if (relay && !url.startsWith("turn:") && !url.startsWith("turns:")) continue;
PeerConnection.IceServer.Builder server = PeerConnection.IceServer.builder(url);
if (!item.isNull("username")) server.setUsername(item.getString("username"));
if (!item.isNull("credential")) server.setPassword(item.getString("credential"));
servers.add(server.createIceServer());
}
}
PeerConnection.RTCConfiguration rtc = new PeerConnection.RTCConfiguration(servers);
rtc.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
rtc.bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE;
rtc.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE;
rtc.iceTransportsType = relay ? PeerConnection.IceTransportsType.RELAY : PeerConnection.IceTransportsType.ALL;
peer = factory.createPeerConnection(rtc, new Observer());
if (peer == null) throw new IllegalStateException("Cannot create native WebRTC peer");
Camera2Enumerator cameras = new Camera2Enumerator(context);
String camera = configuration.getString("camera");
capturer = cameras.createCapturer(camera, new CameraVideoCapturer.CameraEventsHandler() {
public void onCameraError(String message) { error("Camera: " + message); }
public void onCameraDisconnected() { if (!closed) error("Camera disconnected"); }
public void onCameraFreezed(String message) { error("Camera frozen: " + message); }
public void onCameraOpening(String name) {}
public void onFirstFrameAvailable() {}
public void onCameraClosed() { if (!closed) error("Camera closed unexpectedly"); }
});
if (capturer == null) throw new IllegalArgumentException("Camera unavailable");
texture = SurfaceTextureHelper.create("PostIt-WebRTC-camera", egl.getEglBaseContext());
videoSource = factory.createVideoSource(false);
capturer.initialize(texture, context, videoSource.getCapturerObserver());
videoTrack = factory.createVideoTrack("postit-video", videoSource);
videoTrack.addSink(local);
audioSource = factory.createAudioSource(new MediaConstraints());
audioTrack = factory.createAudioTrack("postit-audio", audioSource);
peer.addTrack(audioTrack, Collections.singletonList("postit"));
peer.addTrack(videoTrack, Collections.singletonList("postit"));
capturer.startCapture(640, 480, 24);
if (configuration.getBoolean("caller")) peer.createOffer(new CreateDescription("offer"), new MediaConstraints());
}
private abstract class SdpCallback implements SdpObserver {
public void onCreateSuccess(SessionDescription description) {}
public void onSetSuccess() {}
public void onCreateFailure(String message) { error("SDP creation failed: " + message); }
public void onSetFailure(String message) { error("SDP application failed: " + message); }
}
private final class CreateDescription extends SdpCallback {
private final String kind;
CreateDescription(String kind) { this.kind = kind; }
public void onCreateSuccess(SessionDescription description) {
enqueue(() -> {
if (closed) return;
peer.setLocalDescription(new SdpCallback() {
public void onSetSuccess() {
enqueue(() -> {
if (closed) return;
try {
emit(new JSONObject().put("type", "signal").put("signal",
new JSONObject().put("kind", kind).put("sdp", description.description)));
localDescriptionSent = true;
for (IceCandidate candidate : pendingLocal) sendCandidate(candidate);
pendingLocal.clear();
} catch (Exception failure) { error(failure.getMessage()); }
});
}
}, description);
});
}
}
private void signal(JSONObject signal) throws Exception {
if (closed || peer == null) throw new IllegalStateException("WebRTC peer not running");
String kind = signal.getString("kind");
if (kind.equals("candidate")) {
IceCandidate candidate = new IceCandidate(signal.getString("sdpMid"),
signal.getInt("sdpMLineIndex"), signal.getString("candidate"));
if (remoteDescriptionSet) addCandidate(candidate);
else {
if (pendingRemote.size() >= 256) throw new IllegalStateException("Too many pending ICE candidates");
pendingRemote.add(candidate);
}
} else if (kind.equals("offer") || kind.equals("answer")) {
peer.setRemoteDescription(new SdpCallback() {
public void onSetSuccess() {
enqueue(() -> {
if (closed) return;
remoteDescriptionSet = true;
for (IceCandidate candidate : pendingRemote) addCandidate(candidate);
pendingRemote.clear();
if (kind.equals("offer")) peer.createAnswer(new CreateDescription("answer"), new MediaConstraints());
});
}
}, new SessionDescription(kind.equals("offer") ? SessionDescription.Type.OFFER : SessionDescription.Type.ANSWER,
signal.getString("sdp")));
} else throw new IllegalArgumentException("Invalid WebRTC signal");
}
private void addCandidate(IceCandidate candidate) {
peer.addIceCandidate(candidate, new AddIceObserver() {
public void onAddSuccess() {}
public void onAddFailure(String message) { error("ICE candidate rejected: " + message); }
});
}
private void sendCandidate(IceCandidate candidate) {
try {
emit(new JSONObject().put("type", "signal").put("signal", new JSONObject()
.put("kind", "candidate").put("candidate", candidate.sdp)
.put("sdpMid", candidate.sdpMid).put("sdpMLineIndex", candidate.sdpMLineIndex)));
} catch (Exception failure) { error(failure.getMessage()); }
}
private void stats(RTCStatsReport report) {
enqueue(() -> {
if (closed) return;
try {
Map<String, RTCStats> all = report.getStatsMap();
String selectedId = null, localType = null;
long audioPackets = 0, videoFrames = 0;
for (RTCStats item : all.values()) {
Map<String, Object> values = item.getMembers();
if (item.getType().equals("transport") && values.get("selectedCandidatePairId") instanceof String)
selectedId = (String)values.get("selectedCandidatePairId");
if (item.getType().equals("inbound-rtp")) {
String media = String.valueOf(values.getOrDefault("kind", values.get("mediaType")));
if (media.equals("audio")) audioPackets += number(values.get("packetsReceived"));
if (media.equals("video")) videoFrames += number(values.get("framesDecoded"));
}
}
RTCStats pair = all.get(selectedId);
if (pair != null) {
RTCStats candidate = all.get(String.valueOf(pair.getMembers().get("localCandidateId")));
if (candidate != null) localType = String.valueOf(candidate.getMembers().get("candidateType"));
}
String state = peer.connectionState().toString().toLowerCase(Locale.ROOT);
if (state.equals("connected") && localType == null) state = "checking";
emit(new JSONObject().put("type", "status").put("status", new JSONObject()
.put("connectionState", state).put("localCandidateType", localType)
.put("audioPackets", audioPackets).put("videoFrames", videoFrames)
.put("localVideoRendered", localRendered).put("remoteVideoRendered", remoteRendered)));
} catch (Exception failure) { error(failure.getMessage()); }
});
}
private static long number(Object value) { return value instanceof Number ? ((Number)value).longValue() : 0; }
private final class Observer implements PeerConnection.Observer {
public void onSignalingChange(PeerConnection.SignalingState state) {}
public void onIceConnectionChange(PeerConnection.IceConnectionState state) {}
public void onIceConnectionReceivingChange(boolean receiving) {}
public void onIceGatheringChange(PeerConnection.IceGatheringState state) {}
public void onIceCandidatesRemoved(IceCandidate[] candidates) {}
public void onAddStream(MediaStream stream) {}
public void onRemoveStream(MediaStream stream) {}
public void onDataChannel(DataChannel channel) {}
public void onRenegotiationNeeded() {}
public void onIceCandidate(IceCandidate candidate) {
enqueue(() -> {
if (closed) return;
if (localDescriptionSent) sendCandidate(candidate);
else if (pendingLocal.size() < 256) pendingLocal.add(candidate);
else error("Too many local ICE candidates");
});
}
public void onTrack(RtpTransceiver transceiver) {
MediaStreamTrack track = transceiver.getReceiver().track();
if (track instanceof VideoTrack) {
enqueue(() -> {
if (closed) return;
remoteTrack = (VideoTrack)track;
remoteTrack.addSink(remote);
});
}
}
}
private interface Cleanup { void run() throws Exception; }
private void release(Cleanup cleanup, List<String> failures) {
try { cleanup.run(); }
catch (Exception failure) { failures.add(failure.toString()); }
}
private void close() {
if (closed) return;
closed = true;
List<String> failures = new ArrayList<>();
if (capturer != null) release(() -> capturer.stopCapture(), failures);
if (remoteTrack != null) release(() -> remoteTrack.removeSink(remote), failures);
if (videoTrack != null) release(() -> videoTrack.removeSink(local), failures);
if (peer != null) {
release(() -> peer.close(), failures);
release(() -> peer.dispose(), failures);
}
if (videoTrack != null) release(() -> videoTrack.dispose(), failures);
if (audioTrack != null) release(() -> audioTrack.dispose(), failures);
if (capturer != null) release(() -> capturer.dispose(), failures);
if (texture != null) release(() -> texture.dispose(), failures);
if (videoSource != null) release(() -> videoSource.dispose(), failures);
if (audioSource != null) release(() -> audioSource.dispose(), failures);
if (factory != null) release(() -> factory.dispose(), failures);
if (audioModule != null) release(() -> audioModule.release(), failures);
new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
release(() -> local.release(), failures);
release(() -> remote.release(), failures);
release(() -> egl.release(), failures);
if (!failures.isEmpty()) error("WebRTC cleanup failed: " + String.join("; ", failures));
try { emit(new JSONObject().put("type", "closed")); }
catch (Exception failure) { error(failure.getMessage()); }
});
executor.shutdown();
}
}

View file

@ -0,0 +1,80 @@
#if DEBUG
using System;
using System.Threading;
using System.Threading.Tasks;
using PostIt.Android.Services;
namespace PostIt.Android.Tests;
/// <summary>Platform-free deterministic launch/disable races; also invoked by the Android debug activity.</summary>
internal static class ChatServiceEpochTests
{
internal static async Task VerifyAsync()
{
foreach (var reason in new[] { "Sync(false)", "logout", "saved opt-out" })
{
var policy = new ChatServiceEpoch();
var queued = policy.Begin();
var stopped = 0;
policy.Invalidate(() => stopped++);
Require(!policy.Run(queued, () => throw new Exception("Stale launch executed")), reason);
Require(policy.Restore() is null, reason + " restored in same process");
Require(stopped == 1, reason + " did not stop synchronously");
}
var owner = new ChatServiceEpoch();
var old = owner.Begin();
owner.Invalidate(() => { });
var newer = owner.Begin();
var laterStopped = false;
Require(!owner.Cancel(old, () => laterStopped = true), "old timeout cancelled later enable");
Require(!laterStopped && owner.IsCurrent(newer), "new generation lost");
Require(owner.Cancel(newer, () => laterStopped = true), "current cancellation not applied");
Require(laterStopped && !owner.IsCurrent(newer), "timed-out generation still launchable");
Require(!owner.Run(newer, () => throw new Exception("Timed-out intent executed")), "timeout leak");
var firstProcess = new ChatServiceEpoch();
var staleIntent = firstProcess.Begin();
var freshProcess = new ChatServiceEpoch();
var restored = freshProcess.Restore();
Require(restored is not null && freshProcess.IsCurrent(restored), "fresh boot restore failed");
Require(!freshProcess.IsCurrent(staleIntent), "previous-process intent accepted");
var queuedPolicy = new ChatServiceEpoch();
var beforeSemaphore = queuedPolicy.Begin();
using var release = new SemaphoreSlim(0, 1);
var launched = false;
var delayedLaunch = Task.Run(async () =>
{
await release.WaitAsync();
queuedPolicy.Run(beforeSemaphore, () => launched = true);
});
queuedPolicy.Invalidate(() => { });
release.Release();
await delayedLaunch;
Require(!launched, "queued semaphore/permission continuation launched after disable");
var concurrent = new ChatServiceEpoch();
var concurrentEpoch = concurrent.Begin();
var nativeLaunch = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finishLaunch = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var launch = Task.Run(() => concurrent.Run(concurrentEpoch, () =>
{
nativeLaunch.TrySetResult();
finishLaunch.Task.GetAwaiter().GetResult();
}));
await nativeLaunch.Task.WaitAsync(TimeSpan.FromSeconds(5));
var stop = Task.Run(() => concurrent.Invalidate(() => { }));
finishLaunch.TrySetResult();
await Task.WhenAll(launch, stop).WaitAsync(TimeSpan.FromSeconds(5));
Require(!concurrent.IsCurrent(concurrentEpoch), "native launch escaped concurrent disable");
Require(!concurrent.Run(concurrentEpoch, () => throw new Exception("Delayed Android intent executed")),
"delayed Android intent accepted");
}
private static void Require(bool value, string message)
{
if (!value) throw new InvalidOperationException(message);
}
}
#endif

View file

@ -7,3 +7,5 @@
-keepattributes *Annotation*
-dontwarn org.videolan.libvlc.**
-dontwarn org.videolan.medialibrary.**
-keep class org.webrtc.** { *; }
-keep class fr.pschneider.postit.WebRtcPeer { *; }

View file

@ -4,10 +4,11 @@
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<AssemblyVersion>1.0.8.0</AssemblyVersion>
<FileVersion>1.0.8.0</FileVersion>
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
<Version>1.0.8-458</Version>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
<Version>1.1.0-feat-calls.1</Version>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Browser" />
@ -15,4 +16,4 @@
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
</Project>
</Project>

View file

@ -12,9 +12,6 @@ internal sealed partial class Program
return BuildAvaloniaApp()
.WithInterFont()
#if DEBUG
.WithDeveloperTools()
#endif
.StartBrowserAppAsync("out");
}

View file

@ -5,10 +5,10 @@
See https://docs.avaloniaui.net/docs/guides/platforms/platform-specific-code/dotnet for more details.-->
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<AssemblyVersion>1.0.8.0</AssemblyVersion>
<FileVersion>1.0.8.0</FileVersion>
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
<Version>1.0.8-458</Version>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
<Version>1.1.0-feat-calls.1</Version>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>app.manifest</ApplicationManifest>

View file

@ -14,6 +14,8 @@ sealed class Program
public static void Main(string[] args)
{
Platform.IsPodcastSupported = true;
Platform.CreateBrowser = () => new CustomSchemeBrowser("postit://callback");
CLIOptionHandler.HandleArgs(args);
// Short-circuit 2nd-instance launches (OS handing us the

View file

@ -0,0 +1,20 @@
using PostIt.ViewModels;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class AboutTermsTests
{
[Fact]
public void Terms_follow_the_configured_instance_and_changes_to_it()
{
var settings = new Settings();
settings.Authentication.Authority = "https://first.example/";
var model = new AboutPageViewModel(settings);
Assert.Equal("https://first.example/Home/CGU", model.TermsUri.AbsoluteUri);
Assert.Equal("https://first.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri);
settings.Authentication.Authority = "https://second.example";
Assert.Equal("https://second.example/Home/CGU", model.TermsUri.AbsoluteUri);
Assert.Equal("https://second.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri);
}
}

View file

@ -5,6 +5,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class ActivitiesPageViewModelTests
{
[Fact]

View file

@ -7,6 +7,7 @@ using PostIt.Views;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class ActivityNavigationTests
{
[AvaloniaFact]

View file

@ -2,7 +2,6 @@
using Avalonia;
using Avalonia.Headless.XUnit;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
@ -29,6 +28,7 @@ namespace PostIt.Tests;
/// click via <c>button.Command?.Execute(...)</c> + flush
/// any async command before asserting.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class AddCircleMemberDialogTests
{
/// <summary>

View file

@ -1,4 +1,3 @@
using System.Net.Http;
using System.Text.Json;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
@ -7,50 +6,40 @@ using Avalonia.VisualTree;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Administration;
using Yavsc.Abstract.Identity;
using Yavsc.Abstract.Resources;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationAccessTests
{
[AvaloniaTheory]
[InlineData("Moderator", false)]
[InlineData("Administrator", true)]
[InlineData("administrator", false)]
[InlineData("Performer", false)]
[InlineData("moderator", false)]
[InlineData("", false)]
public async Task Home_administration_visibility_and_command_follow_the_administrator_role(string role, bool allowed)
[Fact]
public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes()
{
await using var api = new ProfileTransport(role);
var session = new SessionStatusViewModel { Api = api };
var vm = new HomePageViewModel(api, api.Settings, session, null!);
var page = new HomePage { DataContext = vm };
var window = new Window { Content = page };
try
{
window.Show();
var button = Assert.Single(page.GetVisualDescendants().OfType<Button>(),
button => Equals(button.Content, "Administration"));
Assert.False(button.IsVisible);
await session.RefreshAsync();
Assert.Equal(allowed, session.IsAdministrator);
Assert.Equal(allowed, button.IsVisible);
Assert.Equal(allowed, vm.OpenAdministration.CanExecute(null));
Assert.DoesNotContain(page.GetVisualDescendants().OfType<Button>(),
button => Equals(button.Content, "Mon usage / administration"));
await using var api = new ProfileTransport("Performer") { ExhaustedQuota = true };
var model = new UserProfilePageViewModel(api, usageClient: api.UsageClient);
await model.RefreshAsync();
Assert.True(model.ResourceUsage?.IsQuotaReached);
Assert.False(model.IsProfileLoaded);
Assert.False(model.SaveProfileCommand.CanExecute(null));
Assert.Contains("resource_quota_exceeded", model.StatusMessage);
}
session.Api = null;
session.Refresh();
Assert.False(button.IsVisible);
Assert.False(vm.OpenAdministration.CanExecute(null));
}
finally
{
window.Close();
}
[Fact]
public async Task Administration_quota_failure_keeps_the_authorized_usage_overview()
{
await using var api = new ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = api };
await session.RefreshAsync();
api.ExhaustedQuota = true;
var model = new AdministrationPageViewModel(api, api.UsageClient, session);
await model.RefreshAsync();
Assert.True(Assert.Single(model.UsageOverview).IsQuotaReached);
Assert.Empty(model.Users);
Assert.Contains("les usages restent consultables", model.StatusMessage);
}
[Fact]
@ -94,6 +83,42 @@ public class AdministrationAccessTests
Assert.DoesNotContain(api.Requests, path => path.EndsWith("/resource-usage/me"));
}
[Fact]
public async Task Administration_searches_users_on_the_server_and_pages_results()
{
await using var api = new ProfileTransport("Administrator") { ManyUsers = true };
var session = new SessionStatusViewModel { Api = api };
await session.RefreshAsync();
var vm = new AdministrationPageViewModel(api, api.UsageClient, session);
await vm.RefreshAsync();
Assert.Equal(1, vm.UserPage);
Assert.True(vm.HasNextUserPage);
Assert.Equal(25, vm.Users.Count);
Assert.Contains(api.Requests, path => path.Contains(
"/administration/users?page=1&query=", StringComparison.Ordinal));
vm.SearchText = "Jean Dupont";
await vm.SearchUsersCommand.ExecuteAsync(null);
Assert.Equal(1, vm.UserPage);
Assert.False(vm.HasNextUserPage);
Assert.Contains(api.Requests, path => path.Contains(
"/administration/users?page=1&query=Jean", StringComparison.Ordinal));
vm.SearchText = "";
await vm.SearchUsersCommand.ExecuteAsync(null);
Assert.True(vm.HasNextUserPage);
await vm.NextUserPageCommand.ExecuteAsync(null);
Assert.Equal(2, vm.UserPage);
Assert.False(vm.HasNextUserPage);
Assert.Contains(api.Requests, path => path.Contains(
"/administration/users?page=2&query=", StringComparison.Ordinal));
Assert.False(vm.NextUserPageCommand.CanExecute(null));
await vm.PreviousUserPageCommand.ExecuteAsync(null);
Assert.Equal(1, vm.UserPage);
}
[AvaloniaFact]
public async Task Administration_displays_both_tabs_and_selected_user_usage()
{
@ -180,6 +205,60 @@ public class AdministrationAccessTests
Assert.Contains("Impossible de charger mon usage", vm.UsageError);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task My_profile_loads_and_includes_the_call_privacy_preference_in_the_save_payload(bool initial)
{
await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = initial };
var vm = new UserProfilePageViewModel(api);
await vm.RefreshAsync();
Assert.Equal(initial, vm.HideIpAddressInCalls);
vm.HideIpAddressInCalls = !initial;
Assert.Equal(!initial, vm.BuildProfileUpdateRequest().HideIpAddressInCalls);
Assert.True(vm.SaveProfileCommand.CanExecute(null));
Assert.True(vm.IsProfileLoaded);
}
[AvaloniaFact]
public async Task My_profile_privacy_checkbox_is_two_way_and_disabled_before_loading()
{
await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = true };
var vm = new UserProfilePageViewModel(api);
var page = new UserProfilePage { DataContext = vm };
var window = new Window { Content = page };
try
{
window.Show();
var checkbox = Assert.Single(page.GetVisualDescendants().OfType<CheckBox>(),
control => Equals(control.Content, "Masquer mon adresse IP aux autres participants"));
Assert.False(checkbox.IsEffectivelyEnabled);
await vm.RefreshAsync();
Assert.True(checkbox.IsEffectivelyEnabled);
Assert.True(checkbox.IsChecked);
checkbox.IsChecked = false;
Assert.False(vm.HideIpAddressInCalls);
Assert.Equal(false, vm.BuildProfileUpdateRequest().HideIpAddressInCalls);
vm.IsBusy = true;
Assert.False(checkbox.IsEffectivelyEnabled);
}
finally
{
window.Close();
}
}
[Fact]
public async Task Profile_read_failure_prevents_saving_a_default_call_privacy_preference()
{
await using var api = new ProfileTransport("Performer") { FailProfile = true };
var vm = new UserProfilePageViewModel(api);
await vm.RefreshAsync();
Assert.False(vm.IsProfileLoaded);
Assert.False(vm.SaveProfileCommand.CanExecute(null));
Assert.Contains("Impossible de charger le profil", vm.StatusMessage);
}
internal sealed class ProfileTransport : YavscApiClient
{
private readonly string _tokenPath;
@ -188,6 +267,9 @@ public class AdministrationAccessTests
public Task<Me>? PendingProfile { get; set; }
public bool FailProfile { get; set; }
public bool FailUsage { get; set; }
public bool ExhaustedQuota { get; set; }
public bool HideIpAddressInCalls { get; set; }
public bool ManyUsers { get; set; }
public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl);
public ProfileTransport(string role)
@ -213,20 +295,44 @@ public class AdministrationAccessTests
object result;
if (path.EndsWith("/account/me"))
{
if (ExhaustedQuota)
throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests);
if (FailProfile)
throw new HttpRequestException("Profile unavailable");
result = PendingProfile is not null ? await PendingProfile
: new Me { UserId = "alice-id", UserName = "alice", Roles = [_role] };
: new Me { UserId = "alice-id", UserName = "alice", Roles = [_role], HideIpAddressInCalls = HideIpAddressInCalls };
}
else if (path.Contains("/resource-usage/"))
{
if (FailUsage)
throw new HttpRequestException("Usage unavailable");
var usage = new ResourceUsageSummary { UserId = "alice-id", UserName = "alice", ApiCalls = 12m };
var usage = new ResourceUsageSummary
{
UserId = "alice-id", UserName = "alice", ApiCalls = 12m,
Consumption = ExhaustedQuota ? 10000m : 0.24m,
ConsumptionLimit = 10000m,
RemainingConsumption = ExhaustedQuota ? 0m : 9999.76m,
IsQuotaReached = ExhaustedQuota
};
result = path.EndsWith("/admin") ? new List<ResourceUsageSummary> { usage } : usage;
}
else if (path.EndsWith("/users"))
result = new List<UserInfo> { new() { UserId = "alice-id", UserName = "alice" } };
else if (path.Contains("/administration/users", StringComparison.Ordinal))
{
if (ExhaustedQuota)
throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests);
var matchingQuery = path.Contains("query=Jean", StringComparison.Ordinal);
var page = path.Contains("page=2", StringComparison.Ordinal);
var returnedUsers = !matchingQuery && !page && ManyUsers
? Enumerable.Range(1, 25).Select(index => new UserInfo
{
UserId = $"alice-id-{index}", UserName = $"alice-{index}"
}).ToList()
: matchingQuery
? new List<UserInfo> { new() { UserId = "jean-id", UserName = "jean", FullName = "Jean Dupont" } }
: page ? new List<UserInfo>()
: new List<UserInfo> { new() { UserId = "alice-id", UserName = "alice" } };
result = new AdministrationUserPage(returnedUsers, ManyUsers && !matchingQuery && !page);
}
else
throw new InvalidOperationException($"Unexpected endpoint: {path}");

View file

@ -1,5 +1,4 @@
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
@ -13,8 +12,34 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationToolsTests
{
[Fact]
public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new AdminTransport();
var vm = new AdministrationPageViewModel(null, session: session,
administrationClient: new AdministrationApiClient(transport, () => "https://example.invalid/api/v1"));
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Contains("POST https://example.invalid/api/v1/administration/payment-residues/purge", transport.Paths);
Assert.Contains("2 compte(s)", vm.PaymentPurgeReport);
Assert.False(vm.ConfirmDestructiveAction);
session.Api = null;
session.Refresh();
transport.Paths.Clear();
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
Assert.Empty(vm.PaymentPurgeReport);
}
[AvaloniaTheory]
[InlineData(400, 800)]
[InlineData(800, 400)]
@ -207,6 +232,8 @@ public class AdministrationToolsTests
: await PendingSecret.Task;
else if (typeof(T) == typeof(ImportResult))
result = new ImportResult(0, 0, 0);
else if (typeof(T) == typeof(PaymentResiduePurgeResult))
result = new PaymentResiduePurgeResult(2, 3, 4, 1, 1);
else
throw new NotSupportedException(typeof(T).Name);
return JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(result))!;

View file

@ -12,7 +12,8 @@ namespace PostIt.Tests;
/// Skip conditions: the package is not installed on the connected device,
/// or no device is connected via adb.
/// </summary>
[Trait("Category", "Platform-Android")]
[Trait("Platform", "Android")]
[Trait("Category", "non-reg")]
public class AndroidAppLaunchTests
{
private const string PackageName = "fr.pschneider.postit";
@ -34,6 +35,18 @@ public class AndroidAppLaunchTests
return;
}
if (!HasAdb())
{
_output.WriteLine("[skip] adb not available on this machine");
return;
}
if (!HasConnectedDevice())
{
_output.WriteLine("[skip] no Android device/emulator connected via adb");
return;
}
if (!IsPackageInstalledOnAnyDevice())
{
_output.WriteLine($"[skip] {PackageName} not installed on any device");
@ -60,6 +73,68 @@ public class AndroidAppLaunchTests
|| Environment.GetEnvironmentVariable("CI_NAME") is { Length: > 0 };
}
private static bool HasAdb()
{
try
{
var startInfo = new ProcessStartInfo("adb", "version")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
using var proc = Process.Start(startInfo);
if (proc is null) return false;
var _ = proc.StandardOutput.ReadToEnd();
var __ = proc.StandardError.ReadToEnd();
if (!proc.WaitForExit(2000))
{
proc.Kill(entireProcessTree: true);
return false;
}
return proc.ExitCode == 0;
}
catch
{
return false;
}
}
private static bool HasConnectedDevice()
{
try
{
var startInfo = new ProcessStartInfo("adb", "devices")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
using var proc = Process.Start(startInfo);
if (proc is null) return false;
var stdout = proc.StandardOutput.ReadToEnd();
_ = proc.StandardError.ReadToEnd();
if (!proc.WaitForExit(2000))
{
proc.Kill(entireProcessTree: true);
return false;
}
return stdout
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Any(line => line.Contains("device", StringComparison.OrdinalIgnoreCase)
&& !line.Contains("offline", StringComparison.OrdinalIgnoreCase));
}
catch
{
return false;
}
}
private static bool IsPackageInstalledOnAnyDevice()
{
try
@ -74,7 +149,13 @@ public class AndroidAppLaunchTests
using var proc = Process.Start(startInfo);
if (proc is null) return false;
var stdout = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(5000);
_ = proc.StandardError.ReadToEnd();
if (!proc.WaitForExit(5000))
{
proc.Kill(entireProcessTree: true);
return false;
}
return stdout
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Any(line => line.Trim().Equals($"package:{PackageName}", StringComparison.Ordinal));

View file

@ -0,0 +1,71 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
[Collection(AvaloniaUiCollection.Name)]
public sealed class AvaloniaUiFixtureTests(AvaloniaUiFixture ui)
{
[Fact]
public async Task Dispatches_share_the_UI_thread_but_isolate_the_application()
{
Application? firstApplication = null;
var firstThread = 0;
await ui.RunAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
firstApplication = Application.Current;
firstThread = Environment.CurrentManagedThreadId;
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
await ui.RunAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
Assert.Equal(firstThread, Environment.CurrentManagedThreadId);
Assert.NotNull(firstApplication);
Assert.NotNull(Application.Current);
Assert.NotSame(firstApplication, Application.Current);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Windows_are_closed_and_unbound_even_when_the_test_fails(bool fail)
{
var expectedFailure = new InvalidOperationException("Test failure");
Window? opened = null;
Control? content = null;
var run = ui.WithWindowAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
content = new TextBlock { DataContext = new object(), Text = "Fixture" };
return content;
}, window =>
{
opened = window;
Assert.True(window.IsVisible);
Assert.Equal(640, window.Width);
Assert.Equal(480, window.Height);
return fail ? Task.FromException(expectedFailure) : Task.CompletedTask;
}, TestContext.Current.CancellationToken, width: 640, height: 480);
if (fail)
Assert.Same(expectedFailure, await Assert.ThrowsAsync<InvalidOperationException>(() => run));
else
await run;
// The controls still belong to the fixture's UI thread after their application is disposed.
await ui.RunAsync(() =>
{
Assert.NotNull(opened);
Assert.False(opened.IsVisible);
Assert.Null(opened.Content);
Assert.Null(content!.DataContext);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
}
}

View file

@ -28,6 +28,7 @@ namespace PostIt.Tests;
/// it reaches production.
/// </para>
/// </summary>
[Trait("Category", "non-reg")]
public class BearerScopeTests
{
/// <summary>

View file

@ -10,6 +10,7 @@ using Yavsc.Models.Haircut;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BillingCommandPageViewModelTests
{
[Fact]

View file

@ -6,6 +6,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BillingQueriesPageViewModelTests
{
[Fact]

View file

@ -18,6 +18,7 @@ namespace PostIt.Tests;
/// (relative, authority-less) instead of
/// <c>https://{authority}/files/{user}/blogs/{id}/{name}</c>.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class BlogAttachmentLinkTests
{
[Theory]

View file

@ -28,6 +28,7 @@ namespace PostIt.Tests;
/// it actually manifested in production.
/// </para>
/// </summary>
[Trait("Category", "non-reg")]
public class BlogPostAuthorDtoTests
{
private static readonly JsonSerializerOptions CaseInsensitiveJson

View file

@ -21,6 +21,7 @@ using SkiaSharp;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BlogReaderTests
{
private static BlogPostDto Post(string article = "Texte du billet.") => new()
@ -82,6 +83,29 @@ public class BlogReaderTests
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
}
[Theory]
[InlineData("https://org.example.test/files/paul/clip.mp4", true)]
[InlineData("https://localhost/files/paul/clip.mp4", false)]
public void Video_links_only_open_externally_when_the_source_is_a_real_external_resource(string source, bool expected)
{
var vm = new VideoPageViewModel(new Uri(source), "video/mp4");
Assert.Equal(expected, vm.CanOpenExternal);
Assert.Equal(vm.Source, vm.ExternalUri);
}
[Theory]
[InlineData("https://org.example.test/Podcast", true)]
[InlineData("about:blank", false)]
public void Video_external_action_uses_the_web_resource_instead_of_the_playback_stream(string externalUrl, bool expected)
{
var source = new Uri("https://api.example.test/api/v1/podcasts/123/index.m3u8");
var externalUri = new Uri(externalUrl);
var vm = new VideoPageViewModel(source, "application/vnd.apple.mpegurl", externalUri);
Assert.Equal(source, vm.Source);
Assert.Equal(externalUri, vm.ExternalUri);
Assert.Equal(expected, vm.CanOpenExternal);
}
[AvaloniaFact]
public async Task Reader_hides_editor_and_wires_hyperlinks_to_the_application()
{
@ -116,57 +140,6 @@ public class BlogReaderTests
}
}
[AvaloniaFact]
public async Task Reader_initialization_and_empty_selection_do_not_report_binding_errors()
{
var vm = CreateViewModel();
await vm.InitializeAsync();
var post = Post();
vm.Posts.Add(post);
vm.FilteredPosts.Add(post);
var previousSink = Logger.Sink;
var sink = new RecordingLogSink();
Logger.Sink = sink;
Window? window = null;
try
{
var page = new BlogsPage();
var reader = page.FindControl<MarkdownScrollViewer>("ArticleReader")!;
var engine = Assert.IsAssignableFrom<IMarkdownEngine2>(reader.Engine);
Assert.NotNull(engine.HyperlinkCommand);
Assert.False(engine.HyperlinkCommand.CanExecute("https://example.test/"));
page.DataContext = vm;
var nav = new NavigationPage();
await nav.PushAsync(page);
window = new Window { Width = 800, Height = 700, Content = nav };
window.Show();
Dispatcher.UIThread.RunJobs();
Assert.Empty(vm.ReaderTitle);
Assert.Null(vm.ReaderDateModified);
Assert.Same(vm.OpenResourceCommand, engine.HyperlinkCommand);
Assert.IsType<BlogImageResolver>(reader.Plugins.PathResolver);
vm.SelectedPost = post;
Dispatcher.UIThread.RunJobs();
Assert.Equal(post.Title, vm.ReaderTitle);
Assert.Equal(post.DateModified, vm.ReaderDateModified);
vm.SelectedPost = null;
page.DataContext = null;
Dispatcher.UIThread.RunJobs();
Assert.Empty(vm.ReaderTitle);
Assert.Null(vm.ReaderDateModified);
Assert.NotNull(engine.HyperlinkCommand);
Assert.False(engine.HyperlinkCommand.CanExecute("https://example.test/"));
Assert.DoesNotContain(sink.Entries, entry => entry.Area == LogArea.Binding);
}
finally
{
window?.Close();
Logger.Sink = previousSink;
}
}
[AvaloniaTheory]
[InlineData(360, 800, false)]
[InlineData(1000, 420, true)]
@ -205,7 +178,6 @@ public class BlogReaderTests
{
Assert.True(reader.Bounds.Right <= list.Bounds.Left);
Assert.Equal(2, Grid.GetColumn(page.BlogsHeaderPanel));
Assert.Equal(2, Grid.GetColumn(page.BlogsCommandBar));
Assert.Equal(reader.Margin.Top, reader.Bounds.Top);
Assert.Equal(page.StatusBar.Bounds.Top - reader.Margin.Bottom, reader.Bounds.Bottom);
Assert.Equal(36, page.TranslatePoint(new Point(), nav)!.Value.Y);
@ -214,9 +186,9 @@ public class BlogReaderTests
{
Assert.True(list.Bounds.Bottom <= reader.Bounds.Top);
Assert.Equal(0, Grid.GetColumn(page.BlogsHeaderPanel));
Assert.Equal(0, Grid.GetColumn(page.BlogsCommandBar));
}
Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page));
var articleScroll = page.FindControl<MarkdownScrollViewer>("ArticleReader")!
.GetVisualDescendants().OfType<ScrollViewer>().Single();
Assert.InRange(articleScroll.Viewport.Height, 1, window.ClientSize.Height);

View file

@ -4,6 +4,7 @@ using PostIt.Services;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BlogResourceServiceTests
{
private const string Authority = "https://yavsc.pschneider.fr";

View file

@ -0,0 +1,61 @@
using System.Text.Json;
using Microsoft.AspNetCore.SignalR.Client;
using PostIt.Services;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CallSignalingClientTests
{
[Fact]
public async Task All_operations_fail_explicitly_without_a_connected_chat_transport()
{
await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
using var client = new CallSignalingClient(connection);
var id = Guid.NewGuid();
var ct = TestContext.Current.CancellationToken;
await Assert.ThrowsAsync<InvalidOperationException>(() => client.InviteAsync("General", "bob", ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => client.InviteLanAsync("General", "bob", ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => client.AcceptAsync(id, ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => client.EndAsync(id, ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(id, new("offer", "sdp"), ct));
}
[Fact]
public async Task Disposing_call_subscriptions_does_not_dispose_the_chat_connection()
{
await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
var client = new CallSignalingClient(connection);
client.Dispose();
client.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(() => client.AcceptAsync(Guid.NewGuid(), TestContext.Current.CancellationToken));
Assert.Equal(HubConnectionState.Disconnected, connection.State);
using var replacement = new CallSignalingClient(connection);
await Assert.ThrowsAsync<InvalidOperationException>(() => replacement.InviteAsync("General", "bob", TestContext.Current.CancellationToken));
}
[Fact]
public void Shared_contracts_round_trip_with_signalr_web_json_naming()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", true,
DateTimeOffset.Parse("2026-10-26T01:00:00Z"));
var ready = new CallAccepted(call, [new(["turns:turn.example.test:5349"], "expires:nonce", "credential")]);
var json = JsonSerializer.Serialize(ready, options);
var read = JsonSerializer.Deserialize<CallAccepted>(json, options);
Assert.NotNull(read);
Assert.Equal(call, read.Session);
Assert.Equal(ready.IceServers[0].Urls, read.IceServers[0].Urls);
Assert.Equal(ready.IceServers[0].Username, read.IceServers[0].Username);
Assert.Equal(ready.IceServers[0].Credential, read.IceServers[0].Credential);
var signal = new CallSignal("candidate", Candidate: "candidate:1 1 udp 100 192.0.2.1 5000 typ relay",
SdpMid: "video", SdpMLineIndex: 1);
Assert.Equal(signal, JsonSerializer.Deserialize<CallSignal>(JsonSerializer.Serialize(signal, options), options));
var lan = call with { RelayOnly = false, Transport = CallTransports.LanSrtp };
Assert.Equal(lan, JsonSerializer.Deserialize<CallSession>(JsonSerializer.Serialize(lan, options), options));
var endpoint = new CallSignal("rtp-endpoint",
Endpoint: new("192.168.1.2", 5004, new string('a', 32), new string('b', 28)));
Assert.Equal(endpoint, JsonSerializer.Deserialize<CallSignal>(JsonSerializer.Serialize(endpoint, options), options));
}
}

View file

@ -0,0 +1,182 @@
using Avalonia.Headless.XUnit;
using Avalonia.Controls;
using PostIt.Views.Chat;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CallTransportRoutingTests
{
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Incoming_calls_are_handled_only_by_the_matching_transport(string transport)
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
Assert.Equal(transport == CallTransports.LanSrtp, lan.Incoming);
Assert.Equal(transport == CallTransports.WebRtc, webRtc.Incoming);
Assert.Empty(signaling.EndedCalls);
if (lan.Incoming) await lan.HangupAsync();
else await webRtc.HangupAsync();
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
[AvaloniaFact]
public async Task Unknown_transport_is_rejected_once_without_starting_either_call()
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), "unknown");
signaling.Invite(call);
await WaitAsync(() => signaling.EndedCalls.Count != 0);
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Chat_updates_both_rooms_and_disconnects_the_active_transport(string transport)
{
var signaling = new Signaling();
var chat = new ChatViewModel(settings: new Settings());
var lan = new LanCallViewModel(signaling);
var webRtc = new WebRtcCallViewModel(signaling);
chat.LanCall = lan;
chat.VideoCall = webRtc;
chat.SelectedRoom = "General";
Assert.Equal("General", lan.Room);
Assert.Equal("General", webRtc.Room);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
await chat.DisconnectAsync();
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.Null(chat.LanCall);
Assert.Null(chat.VideoCall);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
signaling.Invite(call);
Assert.False(lan.Incoming);
Assert.False(webRtc.Incoming);
}
private static async Task WaitAsync(Func<bool> condition)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
while (!condition()) await Task.Delay(10, timeout.Token);
}
[AvaloniaFact]
public async Task Selecting_a_room_member_prepares_both_transports_without_inviting()
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var chat = new ChatViewModel(settings: new Settings())
{
LanCall = lan, VideoCall = webRtc, IsConnected = true, SelectedRoom = "General",
FocusedUsers = new()
};
chat.FocusedUsers.Add("bob");
Assert.False(chat.OpenCallCommand.CanExecute(null));
chat.SelectedUser = "bob";
Assert.True(chat.OpenCallCommand.CanExecute(null));
var page = chat.PrepareCallPage();
Assert.Same(chat, page.Chat);
Assert.Equal("bob", lan.Target);
Assert.Equal("bob", webRtc.Target);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
chat.FocusedUsers.Remove("bob");
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
chat.FocusedUsers.Add("bob");
chat.SelectedUser = "bob";
chat.SelectedRoom = "Other";
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
}
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Leaving_text_chat_preserves_invitation_and_leaving_call_page_ends_it(string transport)
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var chat = new ChatViewModel(settings: new Settings())
{
LanCall = lan, VideoCall = webRtc, IsConnected = true, SelectedRoom = "General",
FocusedUsers = new()
};
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
Assert.True(chat.ShowCallCommand.CanExecute(null));
var window = new Window { Content = new ChatPage { DataContext = chat } };
try
{
window.Show();
window.Content = new CallPage { DataContext = new CallPageViewModel(chat) };
Assert.Empty(signaling.EndedCalls);
Assert.True(lan.Incoming || webRtc.Incoming);
window.Content = null;
await WaitAsync(() => signaling.EndedCalls.Count != 0);
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
finally { window.Close(); }
}
private sealed class Signaling : IWebRtcCallSignaling
{
public event Action<CallSession>? Invitation;
public event Action<CallAccepted>? Accepted;
public event Action<CallEnded>? Ended;
public event Action<Guid, CallSignal>? Signal;
public event Action? Interrupted;
public List<Guid> EndedCalls { get; } = [];
public void Invite(CallSession call) => Invitation?.Invoke(call);
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task AcceptAsync(Guid callId, CancellationToken ct = default) => throw new NotSupportedException();
public Task EndAsync(Guid callId, CancellationToken ct = default)
{
EndedCalls.Add(callId);
return Task.CompletedTask;
}
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default) =>
throw new NotSupportedException();
}
}

View file

@ -2,6 +2,7 @@ using PostIt.Android.Services;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CameraFrameClockTests
{
[Theory]

View file

@ -2,6 +2,7 @@ using PostIt.Android.Services;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CameraFrameOrientationTests
{
[Theory]
@ -26,26 +27,44 @@ public sealed class CameraFrameOrientationTests
public void Maps_output_corners_to_input_for_clockwise_rotation(int rotation, float[] expected)
=> Assert.Equal(expected, CameraFrameOrientation.GetTextureCoordinates(rotation));
[Theory]
[InlineData(90, 0, -1, 0)]
[InlineData(270, 0, 1, 0)]
[InlineData(180, -1, 0, 0)]
[InlineData(90, 1, 0, 90)]
[InlineData(270, 1, 0, 270)]
[InlineData(0, 0, -1, 270)]
[InlineData(180, 0, -1, 90)]
public void Does_not_repeat_rotation_already_in_surface_texture(
int desired, float x, float y, int expected)
[Fact]
public void Sensor_rotation_and_display_changes_map_corners_for_all_lens_orientations()
{
float[] matrix = [x, y, 0, 0, y, -x, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1];
Assert.Equal(expected, CameraFrameOrientation.GetRemainingRotation(desired, matrix));
foreach (var sensor in new[] { 0, 90, 180, 270 })
foreach (var display in new[] { 0, 90, 180, 270 })
foreach (var front in new[] { false, true })
{
var rotation = CameraFrameOrientation.GetRotation(sensor, display, front);
var coordinates = CameraFrameOrientation.GetTextureCoordinates(rotation);
float[] expected = [0, 0, 1, 0, 0, 1, 1, 1];
var turns = (sensor / 90 + (front ? display / 90 : -display / 90) + 4) % 4;
for (var turn = 0; turn < turns; turn++)
for (var index = 0; index < expected.Length; index += 2)
(expected[index], expected[index + 1]) = (1 - expected[index + 1], expected[index]);
Assert.Equal(expected, coordinates);
}
}
[Theory]
[InlineData(new float[] { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 90, 90)]
[InlineData(new float[] { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 270, 270)]
// Measured on a real Android 15 phone in portrait (rear sensor 90°, front sensor 270°).
[InlineData(new float[] { 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1 }, 90, 0)]
[InlineData(new float[] { 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1 }, 0, 270)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 270, 0)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 0, 270)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 180, 90)]
public void Does_not_apply_the_rotation_already_in_the_texture_transform_twice(
float[] matrix, int rotation, int expected)
=> Assert.Equal(expected, CameraFrameOrientation.GetRemainingRotation(rotation, matrix));
[Fact]
public void Recognizes_the_measured_rear_camera_transform_even_with_cropping()
public void Rejects_invalid_texture_transforms()
{
float[] matrix = [0, -0.9f, 0, 0, -0.8f, 0, 0, 0, 0, 0, 1, 0, 0.9f, 0.95f, 0, 1];
Assert.Equal(0, CameraFrameOrientation.GetRemainingRotation(90, matrix));
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, new float[15]));
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, new float[16]));
var skewed = new float[] { 0.7f, -0.7f, 0, 0, -0.7f, -0.7f, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 };
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, skewed));
}
[Theory]

View file

@ -0,0 +1,61 @@
using System.Net;
using System.Text.Json;
using PostIt.ViewModels;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class ContactsPageViewModelTests
{
[Fact]
public async Task Contacts_are_deduplicated_and_show_all_their_circles()
{
await using var api = new FakeApi();
var vm = new ContactsPageViewModel(new CircleApiClient(api, "https://example.test/"));
await vm.RefreshAsync();
var contact = Assert.Single(vm.Contacts);
Assert.Equal("bob-id", contact.Id);
Assert.Equal("Bob", contact.DisplayName);
Assert.Equal("Amis, Travail", contact.Circles);
}
[Fact]
public async Task Missing_circle_is_reported_instead_of_showing_incomplete_contacts()
{
await using var api = new FakeApi { MissingCircle = true };
var vm = new ContactsPageViewModel(new CircleApiClient(api, "https://example.test/"));
await vm.RefreshAsync();
Assert.Empty(vm.Contacts);
Assert.Contains("n'est plus disponible", vm.Status);
Assert.False(vm.IsBusy);
}
private sealed class FakeApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public bool MissingCircle { get; init; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
string json = path switch
{
"circle" => """[{"id":1,"name":"Travail"},{"id":2,"name":"Amis"}]""",
"circle/1/members" => """[{"id":"bob-id","userName":"bob","fullName":"Bob"}]""",
"circle/2/members" when MissingCircle => "null",
"circle/2/members" => """[{"id":"bob-id","userName":"bob","fullName":"Bob"}]""",
_ => throw new HttpRequestException("Unexpected path", null, HttpStatusCode.NotFound)
};
return Task.FromResult(JsonSerializer.Deserialize<T>(json,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default) =>
throw new NotSupportedException();
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
}
}

View file

@ -1,4 +1,3 @@
using System.Net.Http;
using PostIt.Models;
using PostIt.ViewModels;
using Yavsc;
@ -6,6 +5,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class EstimateEditionPageViewModelTests
{
private static BillingQuerySummaryDto SampleQuery() => new()

View file

@ -4,6 +4,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class EstimateListPageViewModelTests
{
[Fact]

View file

@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using PostIt.Controls;
using PostIt.ViewModels;
using Yavsc.Api.Client;
@ -19,6 +16,7 @@ namespace PostIt.Tests;
/// <c>TestApp</c> makes <c>GoBackAsync</c> a no-op, so the success paths
/// run to completion without navigation side effects.
/// </summary>
[Trait("Category", "non-reg")]
public class EstimateValidationPageViewModelTests
{
private static EstimateDto SampleEstimate(long? commandId = 42) => new()
@ -252,4 +250,4 @@ public class EstimateValidationPageViewModelTests
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}

View file

@ -27,7 +27,8 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
{
foreach (var rotation in new[] { 0, 90, 180, 270 })
await VerifyRotationAsync(rotation);
File.WriteAllText(resultPath, "PASS\nrotations=0,90,180,270\nformat=MPEG-TS\nsource=synthetic");
await VerifyPreviewOnlyAsync();
File.WriteAllText(resultPath, "PASS\nrotations=0,90,180,270\nformat=MPEG-TS\npreview=RGBA,detach,reattach,letterbox,without-encoder,dynamic-rotation\nsource=synthetic");
}
catch (Exception ex)
{
@ -36,6 +37,59 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
finally { Finish(); }
}
private async Task VerifyPreviewOnlyAsync()
{
const int width = 640, height = 480;
using var reader = ImageReader.NewInstance(640, 640, (ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Preview reader unavailable.");
Exception? failure = null;
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, width, height, 0,
error => failure = error);
await rotator.SetPreviewAsync(reader.Surface, reader.Width, reader.Height, error => failure = error);
await rotator.StartAsync();
using var paint = new Paint();
Color[] colors = [Color.Red, Color.Green, Color.Blue, Color.Yellow];
foreach (var rotation in new[] { 0, 90, 180, 270 })
{
await rotator.SetRotationAsync(rotation);
var verified = 0;
for (var frame = 0; frame < 20; frame++)
{
if (failure is not null) throw failure;
var canvas = rotator.CameraSurface.LockCanvas(null)
?? throw new InvalidOperationException("Synthetic preview canvas unavailable.");
try
{
for (var index = 0; index < colors.Length; index++)
{
paint.Color = colors[index];
var x = index % 2 * width / 2;
var y = index / 2 * height / 2;
canvas.DrawRect(x, y, x + width / 2, y + height / 2, paint);
}
}
finally
{
rotator.CameraSurface.UnlockCanvasAndPost(canvas);
canvas.Dispose();
}
await Task.Delay(34);
using var image = reader.AcquireLatestImage();
if (image is null) continue;
try
{
if (frame < 3) continue;
VerifyPreview(image, rotation, rotation is 90 or 270 ? height : width,
rotation is 90 or 270 ? width : height);
verified++;
}
finally { image.Close(); }
}
if (verified < 3) throw new InvalidOperationException($"Preview-only rotation {rotation}: insufficient frames.");
}
await rotator.SetPreviewAsync(null);
}
private async Task VerifyRotationAsync(int rotation)
{
const int width = 640;
@ -60,6 +114,10 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
recorder.Prepare();
using var encoderSurface = recorder.Surface
?? throw new InvalidOperationException("Encoder surface unavailable.");
using var preview = ImageReader.NewInstance(outputWidth + 160, outputHeight + 80,
(ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Preview reader unavailable.");
var previewFrames = 0;
Exception? failure = null;
var stopping = 0;
Stage("initialize EGL");
@ -71,6 +129,8 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
File.WriteAllText(Path.Combine(FilesDir.AbsolutePath, "camera-rotation-test-result.txt"), $"FAIL\n{error}");
}))
{
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height,
error => failure = error);
Stage("start recorder");
recorder.Start();
Task? stop = null;
@ -83,6 +143,10 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
for (var frame = 0; frame < 90; frame++)
{
if (failure is not null) throw failure;
if (frame == 10) await rotator.SetPreviewAsync(null);
if (frame == 15)
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height,
error => failure = error);
if (frame == 45)
{
Volatile.Write(ref stopping, 1);
@ -107,11 +171,24 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
canvas.Dispose();
}
await Task.Delay(34);
using var image = preview.AcquireLatestImage();
if (image is not null)
{
try
{
VerifyPreview(image, rotation, outputWidth, outputHeight);
previewFrames++;
}
finally { image.Close(); }
}
}
if (failure is not null) throw failure;
Stage("wait for recorder stop");
await (stop ?? throw new InvalidOperationException("Recorder stop was not requested."))
.WaitAsync(TimeSpan.FromSeconds(10));
if (previewFrames < 8)
throw new InvalidOperationException($"Too few preview frames: {previewFrames}.");
await rotator.SetPreviewAsync(null);
}
finally
{
@ -143,5 +220,33 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
}
File.Delete(path);
}
private static void VerifyPreview(Image image, int rotation, int outputWidth, int outputHeight)
{
var plane = image.GetPlanes()![0];
var buffer = plane.Buffer!;
var scale = Math.Min((double)image.Width / outputWidth, (double)image.Height / outputHeight);
var width = (int)(outputWidth * scale);
var height = (int)(outputHeight * scale);
Color[] expected = rotation switch
{
90 => [Color.Blue, Color.Red, Color.Yellow, Color.Green],
180 => [Color.Yellow, Color.Blue, Color.Green, Color.Red],
270 => [Color.Green, Color.Yellow, Color.Red, Color.Blue],
_ => [Color.Red, Color.Green, Color.Blue, Color.Yellow]
};
for (var i = 0; i < expected.Length; i++)
{
var x = (image.Width - width) / 2 + (i % 2 * 2 + 1) * width / 4;
var y = (image.Height - height) / 2 + (i / 2 * 2 + 1) * height / 4;
var offset = y * plane.RowStride + x * plane.PixelStride;
var actual = new Color(buffer.Get(offset) & 255, buffer.Get(offset + 1) & 255, buffer.Get(offset + 2) & 255);
var target = expected[i];
if (Math.Abs(actual.R - target.R) > 5 || Math.Abs(actual.G - target.G) > 5 || Math.Abs(actual.B - target.B) > 5)
throw new InvalidOperationException($"Preview rotation {rotation}, quadrant {i}: {actual}, expected {target}.");
}
if (buffer.Get(0) != 0 || buffer.Get(1) != 0 || buffer.Get(2) != 0)
throw new InvalidOperationException("Preview letterbox is not black.");
}
}
#endif

View file

@ -0,0 +1,70 @@
#if ANDROID
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
using PostIt.ViewModels;
namespace PostIt.Tests;
/// <summary>Debug-only boot composition test, without Avalonia or network startup.</summary>
[Activity(Name = "fr.pschneider.postit.ChatServiceTestActivity", Exported = true)]
public sealed class AndroidChatServiceTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var resultPath = Path.Combine(FilesDir!.AbsolutePath, "chat-service-test-result.txt");
try
{
await PostIt.Android.Tests.ChatServiceEpochTests.VerifyAsync();
var boot = AndroidServiceProvider.GetOrCreate();
PlatformBootstrap.InitPlatform();
var ui = Platform.CreateServiceProvider!.Invoke();
Require(ReferenceEquals(boot, ui), "boot and UI providers differ");
Require(ReferenceEquals(boot.GetRequiredService<YavscApiClient>(),
ui.GetRequiredService<YavscApiClient>()), "API client differs");
Require(ReferenceEquals(boot.GetRequiredService<ChatHubConnection>(),
ui.GetRequiredService<ChatHubConnection>()), "chat transport differs");
Require(ReferenceEquals(boot.GetRequiredService<Settings>(),
ui.GetRequiredService<YavscApiClient>().Settings), "settings differ");
Require(ReferenceEquals(Platform.BackgroundChatService, AndroidBackgroundChatService.Instance),
"native adapter missing");
using (var battery = AndroidBatteryOptimization.CreateIntent(this))
{
var power = (PowerManager)GetSystemService(PowerService)!;
var exempt = power.IsIgnoringBatteryOptimizations(PackageName!);
Require(exempt ? battery is null
: battery?.Action == global::Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations,
"battery exemption must not prompt when already granted");
Require(battery?.DataString == (exempt ? null : "package:" + PackageName),
"battery settings package mismatch");
Require(CheckSelfPermission("android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS")
== Permission.Granted, "battery exemption request permission missing");
}
if (OperatingSystem.IsAndroidVersionAtLeast(29))
{
var name = new ComponentName(this, Java.Lang.Class.FromType(typeof(ChatConnectionService)));
var service = PackageManager!.GetServiceInfo(name, PackageInfoFlags.MetaData)!;
Require(service.ForegroundServiceType == (ForegroundService)0,
"chat must not be a foreground service");
Require(!service.Exported, "chat service must not be exported");
}
File.WriteAllText(resultPath, "PASS\nepoch-races=passed\nprovider=shared\napi=shared\nsettings=shared\ntransport=shared\nAvalonia=not-initialized");
}
catch (Exception ex) { File.WriteAllText(resultPath, $"FAIL\n{ex}"); }
finally { Finish(); }
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
}
#endif

View file

@ -0,0 +1,158 @@
#if ANDROID
using System;
using Stopwatch = System.Diagnostics.Stopwatch;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Avalonia.Controls;
using Avalonia.Threading;
using LibVLCSharp.Shared;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
using Path = System.IO.Path;
namespace PostIt.Tests;
/// <summary>Debug-only physical camera/SRTP test; no account, API or media recording.</summary>
[Activity(Name = "fr.pschneider.postit.LanCallTestActivity", Exported = true)]
[SupportedOSPlatform("android26.0")]
public sealed class AndroidLanCallTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "lan-call-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(55));
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true", timeout.Token);
File.WriteAllText(result, outcome);
}
catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
finally { Finish(); }
}
private async Task<string> RunAsync(string result, bool wrongKey, CancellationToken ct)
{
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View == null)
await Task.Delay(100, ct);
await Task.Delay(1000, ct);
var fixture = Path.Combine(FilesDir!.AbsolutePath, "lan-call-fixture.ts");
if (!File.Exists(fixture)) throw new IOException("Explicit H.264/AAC MPEG-TS fixture required.");
using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
await using var peer = new LibVlcLanCallMedia("127.0.0.1", 35102, headless: true);
using var decoded = new DecodedFrames(peer.Receiver);
AndroidLanCallMedia? call = null;
Task? pump = null;
using var sending = CancellationTokenSource.CreateLinkedTokenSource(ct);
var source = File.OpenRead(fixture);
var app = (App)Avalonia.Application.Current!;
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
var attached = false;
try
{
await peer.StartReceivingAsync(ct);
await Dispatcher.UIThread.InvokeAsync(async () =>
{
call = new AndroidLanCallMedia("127.0.0.1", 35100);
var grid = new Grid { RowDefinitions = new RowDefinitions("*,*") };
grid.Children.Add(call.LocalVideo);
Grid.SetRow(call.RemoteVideo, 1);
grid.Children.Add(call.RemoteVideo);
await navigation.PushAsync(new ContentPage { Content = grid });
attached = true;
});
if (call == null) throw new InvalidOperationException("Call UI not created.");
File.WriteAllText(result, "RUNNING\nstage=return source pump");
pump = Task.Run(async () =>
{
var buffer = new byte[1316];
while (await source.ReadAsync(buffer, sending.Token) is var count && count > 0)
{
await pipe.WriteAsync(buffer.AsMemory(0, count), sending.Token);
await Task.Delay(4, sending.Token);
}
}, ct);
File.WriteAllText(result, "RUNNING\nstage=return SRTP sender");
await peer.StartEncodedSendingAsync(call.Endpoint,
pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
File.WriteAllText(result, "RUNNING\nstage=enumerating cameras");
var devices = AndroidLanCallMedia.GetDevices();
var front = devices.Cameras.FirstOrDefault(c => c.Name == "Camera avant")
?? throw new InvalidOperationException("Front camera required; no rear-camera fallback.");
var endpoint = wrongKey ? peer.Endpoint with { Key = new string('0', 32) } : peer.Endpoint;
File.WriteAllText(result, "RUNNING\nstage=front camera and SRTP");
await Dispatcher.UIThread.InvokeAsync(() => call.StartSendingAsync(endpoint, front.Value, "microphone", ct));
File.WriteAllText(result, "RUNNING\nstage=receiving camera and return media");
var elapsed = Stopwatch.StartNew();
while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 10 : 25))
{
if (call.Completion.IsCompleted) await call.Completion;
if (peer.Completion.IsCompleted) await peer.Completion;
if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(10) &&
decoded.Frames >= 100 && decoded.Samples > 144000 && call.HasRemoteMedia) break;
await Task.Delay(100, ct);
}
if (!call.HasRemoteMedia) throw new IOException("Android did not decode return audio/video.");
if (wrongKey ? decoded.Frames != 0 || decoded.Samples != 0
: decoded.Frames < 100 || decoded.Samples <= 144000)
throw new IOException($"Unexpected camera decode: frames={decoded.Frames}, samples={decoded.Samples}.");
return $"PASS\nfrontCamera=true\nwrongKey={wrongKey}\n" +
$"cameraFrames={decoded.Frames}\ncameraAudioSamples={decoded.Samples}\nelapsedMs={elapsed.ElapsedMilliseconds}\nreturnAudioVideo=true\n" +
"transport=SRTP/UDP loopback\npreview=attached\nsource=camera+microphone,return=explicit fixture\ncleanup=complete";
}
finally
{
sending.Cancel();
File.WriteAllText(result, "RUNNING\nstage=stop return source");
if (pump != null)
{
try { await pump; }
catch (System.OperationCanceledException) when (sending.IsCancellationRequested) { }
}
File.WriteAllText(result, "RUNNING\nstage=dispose call");
if (call != null) await Dispatcher.UIThread.InvokeAsync(async () => await call.DisposeAsync());
File.WriteAllText(result, "RUNNING\nstage=stop return peer");
await peer.StopAsync();
source.Dispose();
File.WriteAllText(result, "RUNNING\nstage=detach test page");
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
}
}
private sealed class DecodedFrames : IDisposable
{
private readonly MediaPlayer _player;
private readonly IntPtr _buffer = Marshal.AllocHGlobal(640 * 640 * 4);
private int _frames;
private long _samples;
public int Frames => Volatile.Read(ref _frames);
public long Samples => Interlocked.Read(ref _samples);
public DecodedFrames(MediaPlayer player)
{
_player = player;
player.SetVideoFormat("RV32", 640, 640, 640 * 4);
player.SetVideoCallbacks((_, planes) =>
{
Marshal.WriteIntPtr(planes, _buffer);
return IntPtr.Zero;
}, null, (_, _) => Interlocked.Increment(ref _frames));
player.SetAudioFormat("S16N", 48000, 1);
player.SetAudioCallbacks((_, _, count, _) => Interlocked.Add(ref _samples, count),
null, null, null, null);
}
public void Dispose() { _player.Stop(); Marshal.FreeHGlobal(_buffer); }
}
}
#endif

View file

@ -0,0 +1,240 @@
#if ANDROID
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using Android.Views.InputMethods;
using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
using Avalonia.Threading;
using AvaloniaEdit;
using PostIt.Android;
using PostIt.Controls;
using PostIt.ViewModels;
using PostIt.Views.Blogs;
namespace PostIt.Tests;
[Activity(Name = "fr.pschneider.postit.MarkdownEditorTestActivity", Exported = true)]
public sealed class AndroidMarkdownEditorTestActivity : Activity
{
private string _stage = "startup";
private ScreenOrientation? _previousOrientation;
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "markdown-editor-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
await RunAsync(timeout.Token);
File.WriteAllText(result, "PASS\nbounded viewport above IME,at least three visible lines,visible caret,keyboard reopen,retained focus");
}
catch (Exception ex)
{
File.WriteAllText(result, $"FAIL at {_stage}\n" + ex);
}
finally
{
RunOnUiThread(Finish);
}
}
private async Task RunAsync(CancellationToken ct)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(30))
throw new PlatformNotSupportedException("Android 11 required for keyboard visibility assertions.");
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
_stage = "waiting for main activity";
await WaitAsync(() => MainActivity.IsForeground && (Avalonia.Application.Current as App)?.View is not null, ct);
var root = ((App)Avalonia.Application.Current!).View!;
if (Intent?.GetBooleanExtra("landscape", false) == true)
{
_previousOrientation = MainActivity.Current!.RequestedOrientation;
MainActivity.Current.RequestedOrientation = ScreenOrientation.Landscape;
await WaitAsync(() => TopLevel.GetTopLevel(root)!.ClientSize.Width > TopLevel.GetTopLevel(root)!.ClientSize.Height, ct);
}
var navigation = root.FindControl<NavigationPage>("NavRoot")!;
BlogsPage? page = null;
TextEditor? source = null;
var focusLosses = 0;
try
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
page = new BlogsPage
{
DataContext = new BlogsViewModel
{
IsEditing = true,
DraftTitle = "Local keyboard test",
DraftArticle = string.Join("\n", Enumerable.Range(1, 150).Select(i => $"Line {i}: local keyboard test"))
}
};
await navigation.PushAsync(page, null);
source = page.GetLogicalDescendants().OfType<MarkdownEditorControl>().Single()
.FindControl<TextEditor>("SourceEditor")!;
});
_stage = "waiting for editor layout";
await WaitAsync(() => source!.TextArea.Bounds.Height > 0, ct);
await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root));
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (!source!.TextArea.Focus())
throw new InvalidOperationException("Unable to focus the mounted editor.");
source.CaretOffset = source.Document.TextLength;
source.TextArea.Caret.BringCaretToView();
source.TextArea.LostFocus += (_, _) => focusLosses++;
});
_stage = "waiting for native input connection";
await WaitAsync(() =>
{
var activity = MainActivity.Current!;
var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!;
return activity.CurrentFocus is { } view && view.HasWindowFocus
&& manager.InvokeIsActive(view) && manager.IsAcceptingText;
}, ct);
_stage = "opening keyboard";
await TapAsync(source!, root);
await WaitAsync(KeyboardVisible, ct);
await Task.Delay(500, ct);
await Dispatcher.UIThread.InvokeAsync(() => CheckCaret(source!, root));
var activity = MainActivity.Current!;
await Dispatcher.UIThread.InvokeAsync(() =>
{
var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!;
if (!manager.HideSoftInputFromWindow(activity.CurrentFocus!.WindowToken, HideSoftInputFlags.None))
throw new InvalidOperationException("Keyboard hide request rejected.");
});
await WaitAsync(() => !KeyboardVisible(), ct);
await Task.Delay(500, ct);
await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root));
await TapAsync(source!, root);
_stage = "reopening keyboard";
await WaitAsync(KeyboardVisible, ct);
await Task.Delay(500, ct);
await Dispatcher.UIThread.InvokeAsync(() =>
{
CheckCaret(source!, root);
if (focusLosses != 0) throw new InvalidOperationException($"Editor lost focus {focusLosses} times.");
});
}
finally
{
if (page is not null)
await Dispatcher.UIThread.InvokeAsync(async () =>
{
if (ReferenceEquals(navigation.NavigationStack.LastOrDefault(), page))
await navigation.PopAsync();
});
if (_previousOrientation is { } orientation && MainActivity.Current is { } main)
main.RunOnUiThread(() => main.RequestedOrientation = orientation);
}
}
private static bool KeyboardVisible()
=> OperatingSystem.IsAndroidVersionAtLeast(30)
&& MainActivity.Current?.Window?.DecorView?.RootWindowInsets?.IsVisible(WindowInsets.Type.Ime()) == true;
private static void CheckCaret(TextEditor source, Control root)
{
var area = source.TextArea;
if (!area.IsFocused) throw new InvalidOperationException("Editor is not focused.");
var rect = area.Caret.CalculateCaretRectangle();
var view = area.TextView;
var bottom = rect.Bottom - view.ScrollOffset.Y;
if (rect.Top - view.ScrollOffset.Y < -1 || bottom > view.Bounds.Height + 1)
throw new InvalidOperationException($"Caret outside viewport: bottom={bottom}, height={view.Bounds.Height}.");
var editorBottom = source.TranslatePoint(new Point(0, source.Bounds.Height), root)!.Value.Y;
if (editorBottom > root.Bounds.Height + 1)
throw new InvalidOperationException($"Editor outside root: bottom={editorBottom}, height={root.Bounds.Height}.");
if (view.Bounds.Height < view.DefaultLineHeight * 3)
throw new InvalidOperationException($"Less than three visible lines: viewport={view.Bounds.Height}, line={view.DefaultLineHeight}.");
if (OperatingSystem.IsAndroidVersionAtLeast(30) && KeyboardVisible())
{
var activity = MainActivity.Current!;
var decor = activity.Window!.DecorView;
var keyboardTop = decor.Height - decor.RootWindowInsets!.GetInsets(WindowInsets.Type.Ime()).Bottom;
var location = new int[2];
activity.CurrentFocus!.GetLocationInWindow(location);
var topLevel = TopLevel.GetTopLevel(root)!;
var bottomInWindow = source.TranslatePoint(new Point(0, source.Bounds.Height), topLevel)!.Value.Y
* topLevel.RenderScaling + location[1];
if (bottomInWindow > keyboardTop + 2)
throw new InvalidOperationException($"Editor hidden by keyboard: bottom={bottomInWindow}, keyboardTop={keyboardTop}.");
}
CheckSystemBars(root);
}
private static void CheckSystemBars(Control root)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(30))
throw new PlatformNotSupportedException("Android 11 required for native inset assertions.");
var activity = MainActivity.Current!;
var decor = activity.Window!.DecorView;
var insets = decor.RootWindowInsets!;
var bars = insets.GetInsets(WindowInsets.Type.SystemBars() | WindowInsets.Type.DisplayCutout());
var location = new int[2];
activity.CurrentFocus!.GetLocationInWindow(location);
var topLevel = TopLevel.GetTopLevel(root)!;
var navigation = root.FindControl<NavigationPage>("NavRoot")!;
var top = navigation.TranslatePoint(new Point(), topLevel)!.Value.Y * topLevel.RenderScaling + location[1];
var bottom = navigation.TranslatePoint(new Point(0, navigation.Bounds.Height), topLevel)!.Value.Y
* topLevel.RenderScaling + location[1];
var visibleBottom = decor.Height - bars.Bottom;
if (KeyboardVisible())
visibleBottom = Math.Min(visibleBottom, decor.Height - insets.GetInsets(WindowInsets.Type.Ime()).Bottom);
if (top < bars.Top - 2 || bottom > visibleBottom + 2)
throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}.");
if (navigation.NavigationStack.LastOrDefault() is BlogsPage page)
{
var bar = NavigationPage.GetTopCommandBar(page)!;
var shouldShowTitle = !KeyboardVisible();
if (!bar.IsVisible || bar.Bounds.Height <= 0
|| page.FindControl<TextBox>("DraftTitleTextBox")?.IsVisible != shouldShowTitle)
throw new InvalidOperationException("Blog controls are unavailable.");
if (page.FindControl<TextBox>("DraftTitleTextBox")?.Text != "Local keyboard test")
throw new InvalidOperationException("The title changed during keyboard layout transitions.");
}
}
private static async Task TapAsync(TextEditor source, Control root)
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
var activity = MainActivity.Current!;
var point = source.TextArea.TranslatePoint(new Point(80, source.TextArea.Bounds.Height / 2), root)!.Value;
var location = new int[2];
activity.CurrentFocus!.GetLocationInWindow(location);
var scale = TopLevel.GetTopLevel(root)!.RenderScaling;
var x = (float)(point.X * scale + location[0]);
var y = (float)(point.Y * scale + location[1]);
var now = SystemClock.UptimeMillis();
using var properties = new MotionEvent.PointerProperties { Id = 0, ToolType = MotionEventToolType.Finger };
using var coordinates = new MotionEvent.PointerCoords { X = x, Y = y, Pressure = 1, Size = 1 };
using var down = MotionEvent.Obtain(now, now, MotionEventActions.Down, 1,
new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0,
InputSourceType.Touchscreen, 0)!;
using var up = MotionEvent.Obtain(now, now + 50, MotionEventActions.Up, 1,
new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0,
InputSourceType.Touchscreen, 0)!;
activity.DispatchTouchEvent(down);
activity.DispatchTouchEvent(up);
});
}
private static async Task WaitAsync(Func<bool> condition, CancellationToken ct)
{
while (!await Dispatcher.UIThread.InvokeAsync(condition))
await Task.Delay(50, ct);
}
}
#endif

View file

@ -0,0 +1,171 @@
#if ANDROID
using System;
using System.IO;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.OS;
using PostIt.Android.Services;
using Path = System.IO.Path;
namespace PostIt.Tests;
[Activity(Name = "fr.pschneider.postit.PodcastBlurTestActivity", Exported = true)]
[SupportedOSPlatform("android26.0")]
public sealed class AndroidPodcastBlurTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "podcast-blur-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
await VerifyAsync();
await VerifyRealModelAsync();
await VerifyFailureAsync();
File.WriteAllText(result, "PASS\nsegmentation=ONNX\nreal-model-preview=verified\npreview=verified\nencoded=created\nfailure=closed\nsource=synthetic");
}
catch (Exception ex) { File.WriteAllText(result, $"FAIL\n{ex}"); }
finally { Finish(); }
}
private async Task VerifyAsync()
{
const int width = 640, height = 480;
using (var segmenter = new PodcastPersonSegmenter(this))
{
var mask = segmenter.Segment(new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size * 4]);
if (mask.Length != PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size)
throw new InvalidOperationException("Masque de segmentation invalide.");
}
var path = Path.Combine(FilesDir!.AbsolutePath, "podcast-blur-test.ts");
#pragma warning disable CS0618
using var recorder = OperatingSystem.IsAndroidVersionAtLeast(31) ? new MediaRecorder(this) : new MediaRecorder();
#pragma warning restore CS0618
recorder.SetVideoSource(VideoSource.Surface);
recorder.SetOutputFormat(OutputFormat.Mpeg2Ts);
recorder.SetVideoSize(width, height);
recorder.SetVideoFrameRate(30);
recorder.SetVideoEncodingBitRate(1200000);
recorder.SetVideoEncoder(VideoEncoder.H264);
recorder.SetOutputFile(path);
recorder.Prepare();
using var surface = recorder.Surface ?? throw new InvalidOperationException("Encodeur indisponible.");
using var preview = ImageReader.NewInstance(width, height, (ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Apercu indisponible.");
Exception? failure = null;
using var rotator = await AndroidCameraFrameRotator.CreateAsync(surface, width, height, 0,
error => failure = error, this, _ => new SplitMask());
await rotator.SetPreviewAsync(preview.Surface, width, height, error => failure = error);
recorder.Start();
await rotator.StartAsync();
using var paint = new Paint();
var frames = 0;
Task? stop = null;
for (var frame = 0; frame < 60; frame++)
{
if (failure is not null) throw failure;
if (frame == 40) stop = Task.Run(recorder.Stop);
if (stop?.IsCompleted == true) break;
using var canvas = rotator.CameraSurface.LockCanvas(null)
?? throw new InvalidOperationException("Camera synthetique indisponible.");
try
{
for (var x = 0; x < width; x += 8)
{
paint.Color = x / 8 % 2 == 0 ? Color.Black : Color.White;
canvas.DrawRect(x, 0, x + 8, height, paint);
}
}
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
await Task.Delay(70);
using var image = preview.AcquireLatestImage();
if (image is not null)
{
var plane = image.GetPlanes()![0];
var buffer = plane.Buffer!;
int Red(int x, int y) => buffer.Get(y * plane.RowStride + x * plane.PixelStride) & 255;
var background = Math.Abs(Red(100, 240) - Red(108, 240));
var foreground = Math.Abs(Red(500, 240) - Red(508, 240));
if (frame > 5 && (background > 120 || foreground < 150))
throw new InvalidOperationException($"Apercu incorrect : decor={background}, personne={foreground}.");
frames++;
image.Close();
}
}
if (failure is not null) throw failure;
if (frames < 5) throw new InvalidOperationException($"Apercu insuffisant : {frames} images.");
await (stop ?? throw new InvalidOperationException("Arret de l'encodeur non demande."))
.WaitAsync(TimeSpan.FromSeconds(15));
if (new FileInfo(path).Length == 0) throw new InvalidOperationException("Video encodee vide.");
}
private sealed class SplitMask : IPodcastPersonSegmenter
{
private readonly byte[] _mask = new byte[PodcastPersonSegmenter.Size * PodcastPersonSegmenter.Size];
public SplitMask()
{
for (var y = 0; y < PodcastPersonSegmenter.Size; y++)
for (var x = PodcastPersonSegmenter.Size / 2; x < PodcastPersonSegmenter.Size; x++)
_mask[y * PodcastPersonSegmenter.Size + x] = 255;
}
public byte[] Segment(byte[] rgba) => _mask;
public void Dispose() { }
}
private async Task VerifyFailureAsync()
{
using var preview = ImageReader.NewInstance(640, 480, (ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Apercu indisponible.");
var failed = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, 640, 480, 0,
error => failed.TrySetResult(error), this, _ => new FailingMask());
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height,
error => failed.TrySetResult(error));
await rotator.StartAsync();
using var canvas = rotator.CameraSurface.LockCanvas(null)
?? throw new InvalidOperationException("Camera synthetique indisponible.");
try { canvas.DrawColor(Color.Red); }
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
await failed.Task.WaitAsync(TimeSpan.FromSeconds(10));
using var image = preview.AcquireLatestImage();
if (image is not null) throw new InvalidOperationException("Une image non filtree a ete affichee apres l'echec.");
}
private async Task VerifyRealModelAsync()
{
using var preview = ImageReader.NewInstance(640, 480, (ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Apercu indisponible.");
Exception? failure = null;
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, 640, 480, 0,
error => failure = error, this);
await rotator.SetPreviewAsync(preview.Surface, preview.Width, preview.Height, error => failure = error);
await rotator.StartAsync();
var frames = 0;
for (var i = 0; i < 15; i++)
{
if (failure is not null) throw failure;
using var canvas = rotator.CameraSurface.LockCanvas(null)
?? throw new InvalidOperationException("Camera synthetique indisponible.");
try { canvas.DrawColor(Color.Gray); }
finally { rotator.CameraSurface.UnlockCanvasAndPost(canvas); }
await Task.Delay(100);
using var image = preview.AcquireLatestImage();
if (image is not null) { frames++; image.Close(); }
}
if (failure is not null) throw failure;
if (frames < 2) throw new InvalidOperationException($"Apercu avec modele reel insuffisant : {frames} images.");
}
private sealed class FailingMask : IPodcastPersonSegmenter
{
public byte[] Segment(byte[] rgba) => throw new InvalidOperationException("Echec de segmentation simule.");
public void Dispose() { }
}
}
#endif

View file

@ -9,7 +9,9 @@ using Android.App;
using Android.Content;
using Android.Media;
using Android.OS;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
@ -23,12 +25,14 @@ public sealed class AndroidPodcastCaptureTestActivity : Activity
{
private bool _microphone = true;
private bool _notificationStop;
private bool _previewTransition;
private int _cameraIndex;
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
_microphone = Intent?.GetStringExtra("microphone") != "false";
_notificationStop = Intent?.GetStringExtra("notificationStop") == "true";
_previewTransition = Intent?.GetStringExtra("previewTransition") == "true";
_cameraIndex = Intent?.GetStringExtra("camera") == "front" ? 1 : 0;
var resultPath = Path.Combine(FilesDir!.AbsolutePath, "podcast-capture-test-result.txt");
File.WriteAllText(resultPath, "RUNNING");
@ -36,7 +40,7 @@ public sealed class AndroidPodcastCaptureTestActivity : Activity
try
{
await RunAsync(result);
File.WriteAllText(resultPath, $"PASS\nsegments={result.GetInt("segments")}\ndurationSeconds={result.GetDouble("durationSeconds")}\naudio={result.GetBoolean("audio")}\ndirectory={result.GetString("directory")}\nbackground={result.GetString("background")}\norientation={result.GetString("orientation")}\ntextureTransform={result.GetString("textureTransform")}");
File.WriteAllText(resultPath, $"PASS\nsegments={result.GetInt("segments")}\ndurationSeconds={result.GetDouble("durationSeconds")}\naudio={result.GetBoolean("audio")}\ndirectory={result.GetString("directory")}\nbackground={result.GetString("background")}\norientation={result.GetString("orientation")}\ntextureTransform={result.GetString("textureTransform")}\npreviewTransition={_previewTransition}");
}
catch (Exception ex)
{
@ -58,12 +62,26 @@ public sealed class AndroidPodcastCaptureTestActivity : Activity
Directory.CreateDirectory(directory);
var devices = AndroidPodcastCapture.GetDevices();
if (devices.Cameras.Count == 0) throw new InvalidOperationException("No emulator camera.");
var camera = devices.Cameras[Math.Min(_cameraIndex, devices.Cameras.Count - 1)].Value;
NavigationPage? navigation = null;
ContentPage? page = null;
IPodcastCapture? capture = null;
try
{
if (_previewTransition)
{
navigation = (Avalonia.Application.Current as App)?.View?.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
page = new ContentPage();
await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PushAsync(page));
foreach (var disposeViewFirst in new[] { false, true })
await VerifyPreviewTeardownAsync(camera, page, disposeViewFirst);
}
capture = await Dispatcher.UIThread.InvokeAsync(() => AndroidPodcastCapture.StartAsync(
devices.Cameras[Math.Min(_cameraIndex, devices.Cameras.Count - 1)].Value,
camera,
_microphone ? "microphone" : null, directory, CancellationToken.None));
if (page is not null)
await Dispatcher.UIThread.InvokeAsync(() => { page.Content = capture.Preview; });
await Task.Delay(3000);
var before = SegmentCount(directory);
context.StartActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome).AddFlags(ActivityFlags.NewTask));
@ -112,7 +130,50 @@ public sealed class AndroidPodcastCaptureTestActivity : Activity
}
finally
{
if (page is not null)
await Dispatcher.UIThread.InvokeAsync(() => { page.Content = null; });
if (capture is not null) await capture.DisposeAsync();
if (navigation is not null)
await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.SystemIdle);
}
}
private static async Task VerifyPreviewTeardownAsync(string camera, ContentPage page, bool disposeViewFirst)
{
await using var preview = await Dispatcher.UIThread.InvokeAsync(
() => AndroidPodcastCapture.StartPreviewAsync(camera, CancellationToken.None));
var control = preview.Preview ?? throw new InvalidOperationException("Camera preview unavailable.");
await Dispatcher.UIThread.InvokeAsync(() => { page.Content = control; });
try
{
// NativeControlHost does not expose its handle publicly.
var handleProperty = typeof(NativeControlHost).GetProperty("NativeControlHandle",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
?? throw new InvalidOperationException("Native preview handle property unavailable.");
Avalonia.Android.AndroidViewControlHandle? handle = null;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
while (handle is null)
{
handle = await Dispatcher.UIThread.InvokeAsync(() =>
handleProperty.GetValue(control.GetVisualDescendants().OfType<NativeControlHost>().Single())
as Avalonia.Android.AndroidViewControlHandle);
if (handle is null) await Task.Delay(50, timeout.Token);
}
await Task.Delay(500, timeout.Token);
await Dispatcher.UIThread.InvokeAsync(() =>
{
// Reproduce teardown after Avalonia has already released the Java view wrapper.
if (disposeViewFirst) handle.View.Dispose();
page.Content = null;
});
await preview.DisposeAsync();
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.SystemIdle);
await preview.Completion;
}
finally
{
await Dispatcher.UIThread.InvokeAsync(() => { page.Content = null; });
}
}

View file

@ -0,0 +1,118 @@
#if ANDROID
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Avalonia.Controls;
using Avalonia.Threading;
using LibVLCSharp.Shared;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
namespace PostIt.Tests;
[Activity(Name = "fr.pschneider.postit.ScreenAwakeTestActivity", Exported = true)]
public sealed class AndroidScreenAwakeTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "screen-awake-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45));
await RunAsync(timeout.Token);
File.WriteAllText(result, "PASS\nplayback,pause,resume,stop,end,teardown,overlap,background,foreground");
}
catch (Exception ex) { File.WriteAllText(result, "FAIL\n" + ex); }
finally { Finish(); }
}
private async Task RunAsync(CancellationToken ct)
{
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => MainActivity.IsForeground && (Avalonia.Application.Current as App)?.View is not null, ct);
var fixture = Path.Combine(FilesDir!.AbsolutePath, "screen-awake-fixture.mp4");
if (!File.Exists(fixture)) throw new IOException("An explicit local video fixture is required.");
var app = (App)Avalonia.Application.Current!;
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
using var vlc = new LibVLC();
using var player = new MediaPlayer(vlc);
AndroidVideoSurface? surface = null;
IDisposable? capture = null;
var attached = false;
try
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
surface = new AndroidVideoSurface(player, false);
await navigation.PushAsync(new ContentPage { Content = surface });
attached = true;
});
await surface!.Ready.WaitAsync(ct);
await WaitAsync(() => !ScreenIsKeptOn(), ct);
using var repeated = new Media(vlc, fixture, FromType.FromPath);
repeated.AddOption(":input-repeat=100");
if (!player.Play(repeated)) throw new InvalidOperationException("Playback did not start.");
await WaitAsync(() => player.IsPlaying && ScreenIsKeptOn(), ct);
player.Pause();
await WaitAsync(() => !player.IsPlaying && !ScreenIsKeptOn(), ct);
if (!player.Play()) throw new InvalidOperationException("Playback did not resume.");
await WaitAsync(ScreenIsKeptOn, ct);
capture = Platform.ScreenAwake.Acquire();
player.Stop();
await WaitAsync(() => !player.IsPlaying && Platform.ScreenAwake.IsRequested && ScreenIsKeptOn(), ct);
capture.Dispose();
capture = null;
await WaitAsync(() => !ScreenIsKeptOn(), ct);
using var once = new Media(vlc, fixture, FromType.FromPath);
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
player.EndReached += (_, _) => ended.TrySetResult();
if (!player.Play(once)) throw new InvalidOperationException("Finite playback did not start.");
await WaitAsync(ScreenIsKeptOn, ct);
await ended.Task.WaitAsync(ct);
await WaitAsync(() => !ScreenIsKeptOn(), ct);
if (!player.Play(repeated)) throw new InvalidOperationException("Teardown playback did not start.");
await WaitAsync(ScreenIsKeptOn, ct);
await Dispatcher.UIThread.InvokeAsync(() => surface.Dispose());
await WaitAsync(() => !ScreenIsKeptOn() && !Platform.ScreenAwake.IsRequested, ct);
player.Stop();
capture = Platform.ScreenAwake.Acquire();
await WaitAsync(ScreenIsKeptOn, ct);
StartActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => !MainActivity.IsForeground && !ScreenIsKeptOn(), ct);
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => MainActivity.IsForeground && ScreenIsKeptOn(), ct);
capture.Dispose();
capture = null;
await WaitAsync(() => !ScreenIsKeptOn(), ct);
}
finally
{
capture?.Dispose();
await Dispatcher.UIThread.InvokeAsync(() => surface?.Dispose());
player.Stop();
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
}
}
private static bool ScreenIsKeptOn()
=> MainActivity.Current?.Window?.Attributes is { } attributes
&& (attributes.Flags & WindowManagerFlags.KeepScreenOn) != 0;
private static async Task WaitAsync(Func<bool> condition, CancellationToken ct)
{
while (!await Dispatcher.UIThread.InvokeAsync(condition))
await Task.Delay(50, ct);
}
}
#endif

View file

@ -0,0 +1,140 @@
#if ANDROID
using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Avalonia.Controls;
using Avalonia.Threading;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
using Yavsc.Abstract.Chat.Calls;
using Path = System.IO.Path;
namespace PostIt.Tests;
[Activity(Name = "fr.pschneider.postit.WebRtcTestActivity", Exported = true)]
[SupportedOSPlatform("android26.0")]
public sealed class AndroidWebRtcTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "webrtc-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(75));
await RunAsync(Intent?.GetIntExtra("port", 0) ?? 0, timeout.Token);
File.WriteAllText(result, "PASS\nnative WebRTC media and cleanup complete");
}
catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
finally { Finish(); }
}
private async Task RunAsync(int port, CancellationToken ct)
{
if (port is < 1024 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View is null)
await Task.Delay(100, ct);
using var socket = new TcpClient();
await socket.ConnectAsync("127.0.0.1", port, ct);
using var stream = socket.GetStream();
using var reader = new StreamReader(stream, Encoding.UTF8, false, 4096, leaveOpen: true);
using var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, leaveOpen: true) { AutoFlush = true };
using var output = new SemaphoreSlim(1);
var callbackFailure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
async Task EmitAsync(object value)
{
await output.WaitAsync(ct);
try { await writer.WriteLineAsync(JsonSerializer.Serialize(value, new JsonSerializerOptions(JsonSerializerDefaults.Web))); }
finally { output.Release(); }
}
void Emit(object value) => _ = EmitObservedAsync(value);
async Task EmitObservedAsync(object value)
{
try { await EmitAsync(value); }
catch (Exception error) { callbackFailure.TrySetException(error); }
}
var navigation = ((App)Avalonia.Application.Current!).View!.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
AndroidWebRtcMedia? media = null;
var attached = false;
try
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
media = new AndroidWebRtcMedia();
var grid = new Grid { RowDefinitions = new RowDefinitions("*,*") };
grid.Children.Add(media.LocalVideo);
Grid.SetRow(media.RemoteVideo, 1);
grid.Children.Add(media.RemoteVideo);
await navigation.PushAsync(new ContentPage { Content = grid });
attached = true;
});
var peer = media ?? throw new InvalidOperationException("Native UI unavailable.");
peer.Signal += signal => Emit(new { type = "signal", signal });
peer.StatusChanged += status =>
{
Emit(new { type = "status", status });
if (status.LocalVideoRendered) Emit(new { type = "rendered", target = "local", size = 1_000 });
if (status.RemoteVideoRendered) Emit(new { type = "rendered", target = "remote", size = 1_000 });
};
while (true)
{
var read = reader.ReadLineAsync(ct).AsTask();
var completed = await Task.WhenAny(read, peer.Completion, callbackFailure.Task);
if (completed != read)
{
await completed;
throw new IOException("Native WebRTC stopped unexpectedly.");
}
var line = await read;
if (line is null) throw new IOException("Test signaling disconnected.");
using var document = JsonDocument.Parse(line);
var root = document.RootElement;
switch (root.GetProperty("command").GetString())
{
case "start":
var configuration = root.GetProperty("configuration").Deserialize<WebRtcMediaConfiguration>(
new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
var camera = AndroidLanCallMedia.GetDevices().Cameras.FirstOrDefault(c => c.Name == "Camera avant")
?? throw new InvalidOperationException("Front camera required.");
await Dispatcher.UIThread.InvokeAsync(() => peer.StartAsync(
configuration with { Camera = camera.Value, Microphone = "microphone" }, ct));
break;
case "signal":
var signal = root.GetProperty("signal").Deserialize<CallSignal>(
new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
await peer.HandleSignalAsync(signal, ct);
break;
case "close":
await Dispatcher.UIThread.InvokeAsync(async () => await peer.DisposeAsync());
await EmitAsync(new { type = "closed" });
return;
default: throw new InvalidOperationException("Unknown test command.");
}
}
}
catch (Exception error)
{
await EmitAsync(new { type = "error", message = error.ToString() });
throw;
}
finally
{
if (media is not null) await Dispatcher.UIThread.InvokeAsync(async () => await media.DisposeAsync());
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
}
}
}
#endif

View file

@ -0,0 +1,69 @@
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
namespace PostIt.Tests;
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class AvaloniaUiCollection : ICollectionFixture<AvaloniaUiFixture>
{
public const string Name = "Avalonia UI";
}
public sealed class AvaloniaUiFixture : IAsyncLifetime
{
private HeadlessUnitTestSession? _session;
public async ValueTask InitializeAsync()
{
_session = HeadlessUnitTestSession.StartNew(typeof(TestAppBuilder), AvaloniaTestIsolationLevel.PerTest);
try
{
await RunAsync(() => Task.CompletedTask, CancellationToken.None);
}
catch
{
await DisposeAsync();
throw;
}
}
public async Task RunAsync(Func<Task> action, CancellationToken ct)
{
var session = _session ?? throw new InvalidOperationException("La fixture Avalonia n'est pas initialisee.");
await session.Dispatch(async () =>
{
await action();
return true;
}, ct);
}
public Task WithWindowAsync(Func<Control> createContent, Func<Window, Task> test, CancellationToken ct,
double width = 800, double height = 600) => RunAsync(async () =>
{
var window = new Window { Width = width, Height = height };
try
{
window.Content = createContent();
window.Show();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
await test(window);
}
finally
{
window.Close();
if (window.Content is Control content) content.DataContext = null;
window.Content = null;
window.DataContext = null;
Dispatcher.UIThread.RunJobs();
}
}, ct);
public async ValueTask DisposeAsync()
{
if (_session is not { } session) return;
_session = null;
await session.DisposeAsync();
}
}

View file

@ -26,6 +26,7 @@ public sealed class OIDCStubAuthority : IAsyncDisposable, IDisposable
public string Issuer { get; }
public string LoopbackRedirectUri { get; }
public int RefreshRequestCount { get; private set; }
public string? RefreshError { get; set; }
private OIDCStubAuthority(HttpListener listener, RSA rsa, string kid, string issuer, string loopback)
{
@ -137,6 +138,11 @@ public sealed class OIDCStubAuthority : IAsyncDisposable, IDisposable
if (form.TryGetValue("grant_type", out var grantType) && grantType == "refresh_token")
{
RefreshRequestCount++;
if (RefreshError is { } error)
{
await WriteJsonAsync(ctx.Response, new { error }, 503);
return;
}
if (!form.TryGetValue("refresh_token", out var suppliedToken)
|| !_refreshTokens.Remove(suppliedToken))
{

View file

@ -0,0 +1,22 @@
using Avalonia;
using Avalonia.Headless;
[assembly: AvaloniaTestApplication(typeof(PostIt.Tests.TestAppBuilder))]
// Ordinary tests also use App.Current and Platform while headless tests reset the shared runtime.
[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)]
namespace PostIt.Tests;
public class TestAppBuilder
{
public static AppBuilder BuildAvaloniaApp()
{
var nativeMedia = System.Environment.GetEnvironmentVariable("POSTIT_TEST_NATIVE_WEBRTC") == "1";
var builder = AppBuilder.Configure<PostIt.App>();
if (nativeMedia) builder.UseSkia();
return builder.UseHeadless(new AvaloniaHeadlessPlatformOptions
{
UseHeadlessDrawing = !nativeMedia
});
}
}

View file

@ -1,4 +1,3 @@
using System.Net.Http;
using Yavsc.Api.Client;
namespace PostIt.Tests;
@ -9,6 +8,7 @@ namespace PostIt.Tests;
/// the PostIt signature payload, using a recording fake
/// <see cref="IYavscApiClient"/> (no network).
/// </summary>
[Trait("Category", "non-reg")]
public class FrontOfficeApiClientTests
{
private static QueryAcceptanceRequestDto SampleBody() => new()
@ -154,4 +154,4 @@ public class FrontOfficeApiClientTests
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}

View file

@ -1,15 +1,12 @@
using System.Net.Http;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Models.Messaging;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class HomePageNotificationsTests
{
[Fact]
@ -164,56 +161,6 @@ public class HomePageNotificationsTests
Assert.Null(transport.LastMethod);
}
[AvaloniaFact]
public async Task Home_page_loads_on_navigation_and_renders_wrapped_titles_and_bodies()
{
var transport = new NotificationTransport
{
Response = Task.FromResult(new List<Notification> { Note(1, "Notification title") })
};
var vm = CreateViewModel(transport);
var page = new HomePage { DataContext = vm };
var nav = new NavigationPage();
var window = new Window { Content = nav, Width = 320, Height = 450 };
try
{
window.Show();
await nav.PushAsync(page);
window.UpdateLayout();
Assert.Single(vm.Notifications);
var texts = page.GetVisualDescendants().OfType<TextBlock>().ToArray();
Assert.Contains(texts, t => t.Text == "Notification title"
&& t.TextWrapping == Avalonia.Media.TextWrapping.Wrap);
Assert.Contains(texts, t => t.Text == "Notification body"
&& t.TextWrapping == Avalonia.Media.TextWrapping.Wrap);
var refresh = Assert.Single(page.GetVisualDescendants().OfType<Button>(),
b => b.Command == vm.RefreshNotificationsCommand);
Assert.True(refresh.IsEnabled);
var dismiss = Assert.Single(page.GetVisualDescendants().OfType<Button>(),
b => b.Command == vm.DismissNotificationCommand);
Assert.Same(vm.Notifications[0], dismiss.CommandParameter);
Assert.Equal("Close", dismiss.Content);
Assert.True(dismiss.IsVisible);
Assert.True(dismiss.IsEnabled);
Assert.Contains(page.GetVisualDescendants().OfType<ScrollViewer>(),
s => s.Extent.Height > s.Viewport.Height);
await nav.PushAsync(new ContentPage());
transport.Response = Task.FromResult(new List<Notification> { Note(2, "Updated title") });
await nav.PopAsync();
Assert.Equal(2, Assert.Single(vm.Notifications).Id);
await vm.DismissNotificationCommand.ExecuteAsync(vm.Notifications[0]);
window.UpdateLayout();
Assert.Empty(vm.Notifications);
Assert.Null(transport.LastMethod);
}
finally
{
window.Close();
}
}
private static HomePageViewModel CreateViewModel(NotificationTransport transport,
SessionStatusViewModel? session = null)
=> new(null!, new Settings(), session ?? new SessionStatusViewModel(),

Some files were not shown because too many files have changed in this diff Show more