Compare commits

...
Author SHA1 Message Date
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
303 changed files with 90798 additions and 1176 deletions

View file

@ -26,8 +26,23 @@ on:
jobs:
build:
runs-on: docker
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
PGPORT: "55432"
ports:
- "55432:55432"
options: >-
--health-cmd="pg_isready -h 127.0.0.1 -p 55432 -U postgres -d postgres"
--health-interval=10s
--health-timeout=5s
--health-retries=10
container:
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v4
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v5
steps:
- name: Clone yavsc
run: |
@ -44,12 +59,29 @@ 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: Wait for PostgreSQL
run: |
echo "⏳ Waiting for PostgreSQL on 127.0.0.1:55432..."
for i in $(seq 1 30); do
if pg_isready -h 127.0.0.1 -p 55432 -U postgres >/dev/null 2>&1; then
echo "✅ PostgreSQL is accepting connections"
exit 0
fi
echo "PostgreSQL not ready yet ($i/30)"
sleep 2
done
echo "❌ PostgreSQL did not become ready in time" >&2
exit 1
- 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 \

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,62 @@
# Changelog
## [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

@ -76,13 +76,333 @@ 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.
### 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.
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 +413,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 +428,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 +445,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 +467,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 +497,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 +526,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 +638,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

@ -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

@ -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,587 @@
# Appels audio-vidéo PostIt — architecture cible
## Statut et périmètre
Ce document décrit l'architecture cible et l'implémentation commencée.
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. Un premier
transport natif **Android et Desktop Linux en IPv4/IPv6 directe (LAN/VPN ou IP publique)** est raccordé :
captures Podcast existantes et SRTP direct, sans libwebrtc ni nouvelle
couche JNI WebRTC. Il ne réalise pas encore la cible Internet, TURN ou groupe.
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.
## Première implémentation Android et Desktop Linux : SRTP direct IPv4/IPv6
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. Dans « Appel direct IPv4/IPv6 (LAN/VPN ou IP publique) », actualiser les périphériques,
sélectionner la caméra, le microphone et une IPv4 privée locale
accessible depuis le pair. Les adresses RFC1918 et de bouclage sont
acceptées ; pas de DNS, IPv6 ou adresse publique. 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. Saisir le pseudo exact du destinataire, 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, à conserver tant que les moteurs ne sont
pas validés ;
- `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.
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 n'a été
déployé ou configuré par cette tranche.
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. L'interface ne
propose pas encore de bouton d'appel ; une éventuelle invitation est
signalée comme non utilisable faute de moteur natif, sans acceptation
automatique.
### Travail restant pour la cible Internet multi-plateforme
- Android : l'approche Java/JNI libwebrtc a été écartée à la demande du
projet ; aucun adaptateur libwebrtc expérimental n'est conservé.
L'adaptateur SRTP LAN réutilise désormais la capture Podcast ; la solution
compatible avec la cible Internet reste à choisir.
- Desktop Linux : le transport SRTP LAN est raccordé, mais ne remplace pas
les validations matérielles ni une solution de connectivité Internet.
- Côté partagé : relier consentement, états réels du moteur, mise en
sourdine, arrêt et libération des ressources à la signalisation.
- Valider un appel Android ↔ Desktop Linux avec caméra avant et microphone
réels, rendu et audio distants, VP8/Opus, puis transport TURN sélectionné
dans les statistiques, sans repli direct lorsque le masquage est demandé.
Les tests de cette tranche portent sur les contrats, autorisations, courses
d'acceptation, expirations, limites, interruption et préférence persistée.
La compilation des applications Android et Desktop ne prouve pas le
fonctionnement de WebRTC natif : le crash antérieur n'est pas résolu.
## 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.
La validation multi-plateforme demeure incomplète.

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

@ -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) │
@ -53,8 +60,52 @@ 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 ;
@ -75,6 +126,37 @@ 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.
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
@ -339,7 +421,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 +441,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"`

View file

@ -78,24 +78,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 +156,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 +182,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 +202,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,6 +5,7 @@
"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"
},
@ -13,6 +14,7 @@
"bootstrap": "^4.6.2",
"dropzone": "^5.9.3",
"eonasdan-bootstrap-datetimepicker": "^4.17.49",
"hls.js": "1.6.13",
"jquery": "^3.7.1",
"jquery-timepicker": "^1.3.3",
"jquery-ui": "^1.13.3",

View file

@ -39,5 +39,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

View file

@ -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,24 @@ 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.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,6 +25,7 @@
<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" />
@ -30,8 +34,13 @@
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<Compile Include="..\PostIt.Tests\AndroidMarkdownEditorTestActivity.cs" Link="Tests\AndroidMarkdownEditorTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidChatServiceTestActivity.cs" Link="Tests\AndroidChatServiceTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidPodcastBlurTestActivity.cs" Link="Tests\AndroidPodcastBlurTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidLanCallTestActivity.cs" Link="Tests\AndroidLanCallTestActivity.cs" />
<Compile Include="..\PostIt.Tests\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.*).

View file

@ -1,9 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto">
<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" />
<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" />

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,144 @@
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());
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

@ -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,43 @@
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)
AndroidSettings.ReportError(api.Settings,
"Android a refuse le redemarrage de la messagerie : " + ex.Message);
}
finally { pending?.Finish(); }
});
}
}

View file

@ -0,0 +1,59 @@
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) =>
OptedIn && Preferences.GetBoolean("signed-in", false)
&& api.Settings.AndroidKeepChatConnected && !api.IsSigningOut && api.HasValidSession
&& Identity(api) is { } identity && identity == Preferences.GetString("identity", null);
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,295 @@
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());
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,9 @@ 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."
: "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,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

@ -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,19 @@
using PostIt.ViewModels;
namespace PostIt.Tests;
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

@ -15,6 +15,32 @@ namespace PostIt.Tests;
public class AdministrationAccessTests
{
[Fact]
public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes()
{
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);
}
[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);
}
[AvaloniaTheory]
[InlineData("Moderator", false)]
[InlineData("Administrator", true)]
@ -180,6 +206,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 +268,8 @@ 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 ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl);
public ProfileTransport(string role)
@ -213,20 +295,33 @@ 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"))
{
if (ExhaustedQuota)
throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests);
result = new List<UserInfo> { new() { UserId = "alice-id", UserName = "alice" } };
}
else
throw new InvalidOperationException($"Unexpected endpoint: {path}");

View file

@ -15,6 +15,31 @@ namespace PostIt.Tests;
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

@ -34,6 +34,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 +72,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 +148,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

@ -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,241 @@
#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 banner = root.FindControl<PostIt.Views.SessionStatusBanner>("SessionBanner")!;
var top = navigation.TranslatePoint(new Point(), topLevel)!.Value.Y * topLevel.RenderScaling + location[1];
var bottom = banner.TranslatePoint(new Point(0, banner.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 || !banner.IsVisible)
throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}, banner={banner.IsVisible}.");
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

@ -82,6 +82,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()
{
@ -205,7 +228,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 +236,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

@ -0,0 +1,60 @@
using System.Text.Json;
using Microsoft.AspNetCore.SignalR.Client;
using PostIt.Services;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
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

@ -26,26 +26,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,349 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels.Chat;
using PostIt.ViewModels;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
public sealed class LanCallViewModelTests
{
[AvaloniaFact]
public async Task Calls_restore_shared_devices_and_persist_choices_and_network_address()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json");
var previousDevices = Platform.GetLanCallDevices;
try
{
var settings = new Settings(path)
{
PodcastCameras = [new("Front", "front"), new("Rear", "rear")],
PodcastMicrophones = [new("None", ""), new("USB", "usb"), new("Built-in", "built-in")],
PodcastCameraId = "rear", PodcastMicrophoneId = "usb"
};
await using (var vm = new LanCallViewModel(new Signaling(), settings: settings))
{
Assert.Equal("rear", vm.Camera?.Value);
Assert.Equal("usb", vm.Microphone?.Value);
Assert.False(vm.AllowAddressDisclosure);
vm.Camera = vm.Cameras[0];
vm.Microphone = vm.Microphones[1];
Assert.Equal("front", settings.PodcastCameraId);
Assert.Equal("built-in", settings.PodcastMicrophoneId);
Assert.NotEmpty(vm.Addresses);
vm.Address = vm.Addresses.Last();
settings.Save();
var preferred = vm.Address;
Platform.GetLanCallDevices = () => new(
[new("Rear", "rear"), new("Front", "front")],
[new("Built-in", "built-in"), new("USB", "usb")]);
vm.RefreshDevicesCommand.Execute(null);
Assert.Equal("front", vm.Camera?.Value);
Assert.Equal("built-in", vm.Microphone?.Value);
Assert.Equal(preferred, vm.Address);
Assert.Contains(settings.PodcastMicrophones, d => d.Value == "");
var reloaded = new Settings(path);
reloaded.Authentication.Authority = "";
reloaded.Load();
await using var restored = new LanCallViewModel(new Signaling(), settings: reloaded);
Assert.Equal(preferred, restored.Address);
Assert.Equal("front", restored.Camera?.Value);
Assert.Equal("built-in", restored.Microphone?.Value);
Assert.False(restored.AllowAddressDisclosure);
settings.PodcastCameraId = "rear";
Assert.Equal("rear", vm.Camera?.Value);
settings.PodcastMicrophoneId = "";
Assert.Null(vm.Microphone);
vm.AllowAddressDisclosure = true;
vm.Room = "General";
vm.Target = "bob";
await vm.InviteCommand.ExecuteAsync(null);
Assert.Contains("microphone", vm.Status);
}
}
finally { Platform.GetLanCallDevices = previousDevices; File.Delete(path); }
}
[AvaloniaFact]
public async Task Call_preference_save_failures_are_reported_without_losing_the_choice()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}");
Directory.CreateDirectory(path);
try
{
var settings = new Settings(path);
await using var vm = new LanCallViewModel(new Signaling(), settings: settings);
vm.Address = null;
vm.Address = "127.0.0.1";
Assert.Equal("127.0.0.1", settings.LanCallAddress);
Assert.Contains("sauvegarde impossible", vm.Status);
Assert.True(settings.IsDirty);
}
finally { Directory.Delete(path); }
}
[AvaloniaFact]
public async Task Missing_saved_network_address_requires_a_new_selection_and_does_not_restore_consent()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json");
try
{
var settings = new Settings(path) { LanCallAddress = "not-a-local-address" };
await using var vm = new LanCallViewModel(new Signaling(), settings: settings);
Assert.Null(vm.Address);
Assert.False(vm.AllowAddressDisclosure);
Assert.Equal("not-a-local-address", settings.LanCallAddress);
}
finally { File.Delete(path); }
}
private static CallSession Session() => new(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), CallTransports.LanSrtp);
private static LanCallViewModel Configure(Signaling signaling, Func<string, int, ILanCallMedia> create)
{
var vm = new LanCallViewModel(signaling, create)
{
Address = "127.0.0.1", Camera = new("Camera", "/dev/video0"),
Microphone = new("Micro", "default"), AllowAddressDisclosure = true,
Room = "General", Target = "bob"
};
vm.Addresses.Add("127.0.0.1");
return vm;
}
[AvaloniaTheory]
[InlineData("8.8.8.8")]
[InlineData("2001:db8::1")]
[InlineData("fd00::1")]
public async Task Public_or_private_ip_can_be_selected_for_an_explicitly_consented_direct_call(string address)
{
var signaling = new Signaling();
await using var vm = Configure(signaling, (_, _) => throw new Exception("No media before acceptance"));
vm.Addresses.Add(address);
vm.Address = address;
await vm.InviteCommand.ExecuteAsync(null);
Assert.Equal(1, signaling.Invites);
Assert.True(vm.Busy);
}
[AvaloniaFact]
public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange()
{
var signaling = new Signaling();
var media = new FakeMedia();
var created = 0;
await using var vm = Configure(signaling, (_, _) => { created++; return media; });
signaling.Invite(vm, signaling.Call);
await WaitAsync(() => vm.Incoming);
Assert.Equal(0, created);
Assert.Empty(signaling.Sent);
await vm.AcceptCommand.ExecuteAsync(null);
await WaitAsync(() => vm.LocalVideo != null);
Assert.Equal(1, created);
Assert.False(media.Sending);
Assert.Single(signaling.Sent);
Assert.Equal("rtp-endpoint", signaling.Sent[0].Kind);
signaling.RemoteEndpoint(signaling.Call.Id);
await WaitAsync(() => media.Sending);
Assert.Same(media.LocalVideo, vm.LocalVideo);
Assert.Same(media.RemoteVideo, vm.RemoteVideo);
await vm.HangupAsync();
Assert.True(media.Disposed);
Assert.False(vm.Busy);
Assert.Null(vm.LocalVideo);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
[AvaloniaFact]
public async Task Caller_waits_for_consent_and_interruption_releases_media_without_reconnecting()
{
var signaling = new Signaling();
var media = new FakeMedia();
var created = 0;
await using var vm = Configure(signaling, (_, _) => { created++; return media; });
await vm.InviteCommand.ExecuteAsync(null);
Assert.True(vm.Busy);
Assert.Equal(0, created);
signaling.Ready();
await WaitAsync(() => vm.LocalVideo != null);
signaling.RemoteEndpoint(signaling.Call.Id);
await WaitAsync(() => media.Sending);
signaling.Disconnect();
await WaitAsync(() => media.Disposed);
Assert.False(vm.Busy);
Assert.Null(vm.RemoteVideo);
Assert.Contains("interrompue", vm.Status);
}
[AvaloniaFact]
public async Task Missing_disclosure_consent_or_devices_blocks_the_invitation()
{
var signaling = new Signaling();
await using var vm = Configure(signaling, (_, _) => throw new Exception("Must not capture"));
vm.AllowAddressDisclosure = false;
await vm.InviteCommand.ExecuteAsync(null);
Assert.Equal(0, signaling.Invites);
Assert.Contains("Confirmez", vm.Status);
vm.AllowAddressDisclosure = true;
vm.Camera = null;
await vm.InviteCommand.ExecuteAsync(null);
Assert.Equal(0, signaling.Invites);
Assert.Contains("camera", vm.Status);
Assert.False(vm.Busy);
}
[AvaloniaFact]
public async Task Refusal_never_creates_media_and_late_signals_cannot_restart_capture()
{
var signaling = new Signaling();
var created = 0;
await using var vm = Configure(signaling, (_, _) => { created++; return new FakeMedia(); });
signaling.Invite(vm, signaling.Call);
await WaitAsync(() => vm.Incoming);
await vm.HangupAsync();
signaling.Ready();
signaling.RemoteEndpoint(signaling.Call.Id);
await Task.Delay(30, TestContext.Current.CancellationToken);
Assert.Equal(0, created);
Assert.False(vm.Busy);
}
[AvaloniaFact]
public async Task Platform_devices_and_factory_are_used_and_backgrounding_ends_capture()
{
var previousDevices = Platform.GetLanCallDevices;
var previousFactory = Platform.CreateLanCallMedia;
var signaling = new Signaling();
var media = new FakeMedia();
var creations = 0;
try
{
Platform.GetLanCallDevices = () => new(
[new("Camera avant", "front"), new("Camera arriere", "rear")],
[new("Sans microphone", ""), new("Microphone Android", "microphone")]);
Platform.CreateLanCallMedia = (_, _) => { creations++; return media; };
await using var vm = new LanCallViewModel(signaling);
vm.RefreshDevicesCommand.Execute(null);
Assert.Equal("front", vm.Camera?.Value);
Assert.Equal("microphone", vm.Microphone?.Value);
Assert.Single(vm.Microphones);
Assert.Equal(0, creations);
signaling.Invite(vm, signaling.Call);
await WaitAsync(() => vm.Incoming);
Assert.True(vm.CanConfigure);
vm.RefreshDevicesCommand.Execute(null);
Assert.Equal("front", vm.Camera?.Value);
vm.Address = "127.0.0.1";
if (!vm.Addresses.Contains(vm.Address)) vm.Addresses.Add(vm.Address);
vm.AllowAddressDisclosure = true;
vm.Room = "General";
vm.Target = "bob";
await vm.AcceptCommand.ExecuteAsync(null);
await WaitAsync(() => vm.LocalVideo != null);
Assert.Equal(1, creations);
Assert.False(vm.CanConfigure);
signaling.RemoteEndpoint(signaling.Call.Id);
await WaitAsync(() => media.Sending);
Platform.SuspendPlayback();
await WaitAsync(() => media.Disposed);
Assert.False(vm.Busy);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
Platform.ResumePlayback();
await Task.Delay(30, TestContext.Current.CancellationToken);
Assert.Equal(1, creations);
}
finally
{
Platform.GetLanCallDevices = previousDevices;
Platform.CreateLanCallMedia = previousFactory;
}
}
[AvaloniaFact]
public async Task Hangup_cancels_pending_native_start_without_waiting_for_startup_timeout()
{
var signaling = new Signaling();
var media = new FakeMedia { DelayStartup = true };
await using var vm = Configure(signaling, (_, _) => media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => vm.LocalVideo != null);
signaling.RemoteEndpoint(signaling.Call.Id);
await WaitAsync(() => media.Sending);
await vm.HangupAsync().WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
Assert.True(media.Disposed);
Assert.False(vm.Busy);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
[AvaloniaFact]
public async Task Media_failure_ends_the_call_and_disposes_capture()
{
var signaling = new Signaling();
var media = new FakeMedia();
await using var vm = Configure(signaling, (_, _) => media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => vm.LocalVideo != null);
media.Fail();
await WaitAsync(() => media.Disposed);
Assert.False(vm.Busy);
Assert.Contains("test media failure", vm.Status);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
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);
}
private sealed class FakeMedia : ILanCallMedia
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Control LocalVideo { get; } = new Border();
public Control RemoteVideo { get; } = new Border();
public LanCallEndpoint Endpoint { get; } = new("127.0.0.1", 5004, new string('a', 32), new string('b', 28));
public Task Completion => _completion.Task;
public bool HasRemoteMedia => false;
public bool Sending { get; private set; }
public bool Disposed { get; private set; }
public bool DelayStartup { get; init; }
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
{
Sending = true;
if (DelayStartup) await Task.Delay(Timeout.Infinite, ct);
}
public void Fail() => _completion.TrySetException(new IOException("test media failure"));
public ValueTask DisposeAsync() { Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
}
private sealed class Signaling : ILanCallSignaling
{
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 CallSession Call { get; } = Session();
public List<CallSignal> Sent { get; } = [];
public List<Guid> EndedCalls { get; } = [];
public int Invites { get; private set; }
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default)
{ Invites++; return Task.FromResult(Call); }
public Task AcceptAsync(Guid id, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
public Task EndAsync(Guid id, CancellationToken ct = default)
{ EndedCalls.Add(id); Ended?.Invoke(new(id, "hangup")); return Task.CompletedTask; }
public Task SendAsync(Guid id, CallSignal signal, CancellationToken ct = default)
{ Sent.Add(signal); return Task.CompletedTask; }
public void Invite(LanCallViewModel _, CallSession call) => Invitation?.Invoke(call);
public void Ready() => Accepted?.Invoke(new(Call, []));
public void RemoteEndpoint(Guid id) => Signal?.Invoke(id, new("rtp-endpoint",
Endpoint: new("127.0.0.1", 5006, new string('c', 32), new string('d', 28))));
public void Disconnect() => Interrupted?.Invoke();
}
}

View file

@ -0,0 +1,201 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using LibVLCSharp.Shared;
using PostIt.Services;
namespace PostIt.Tests;
public sealed class LinuxLanCallMediaTests(ITestOutputHelper output)
{
public static bool HasFixture => OperatingSystem.IsLinux() &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
public static bool HasTsFixture => OperatingSystem.IsLinux() &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_TS"));
[Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
[InlineData("127.0.0.1")]
[InlineData("::1")]
public async Task Ports_are_released_and_credentials_regenerated_after_disposal(string address)
{
var port = FreePort(address: address);
var first = new LibVlcLanCallMedia(address, port, headless: true);
var endpoint = first.Endpoint;
await first.StartReceivingAsync(TestContext.Current.CancellationToken);
await first.DisposeAsync();
await first.DisposeAsync();
await using var next = new LibVlcLanCallMedia(address, port, headless: true);
Assert.NotEqual(endpoint.Key, next.Endpoint.Key);
Assert.NotEqual(endpoint.Salt, next.Endpoint.Salt);
await next.StartReceivingAsync(TestContext.Current.CancellationToken);
}
[Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
[InlineData("127.0.0.1")]
[InlineData("::1")]
public void Occupied_rtcp_port_is_rejected_before_capture_starts(string address)
{
var port = FreePort(address: address);
var ip = IPAddress.Parse(address);
using var socket = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(ip, port + 1));
var error = Assert.Throws<SocketException>(() => new LibVlcLanCallMedia(address, port, headless: true));
Assert.Equal(SocketError.AddressAlreadyInUse, error.SocketErrorCode);
}
[Theory(Skip = "Set POSTIT_TEST_TS to an H.264/AAC MPEG-TS file.", SkipUnless = nameof(HasTsFixture))]
[InlineData("127.0.0.1")]
[InlineData("::1")]
public async Task Already_encoded_capture_is_sent_over_srtp_without_transcoding(string address)
{
var ct = TestContext.Current.CancellationToken;
var firstPort = FreePort(address: address);
await using var sender = new LibVlcLanCallMedia(address, firstPort, headless: true);
await using var receiver = new LibVlcLanCallMedia(address, FreePort(firstPort, address), headless: true);
using var decoded = new DecodedVideo(receiver.Receiver);
using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
await using var source = File.OpenRead(Environment.GetEnvironmentVariable("POSTIT_TEST_TS")!);
await receiver.StartReceivingAsync(ct);
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
var pump = Task.Run(async () =>
{
var buffer = new byte[1316];
while (await source.ReadAsync(buffer, lifetime.Token) is var count && count > 0)
{
await pipe.WriteAsync(buffer.AsMemory(0, count), lifetime.Token);
await Task.Delay(4, lifetime.Token);
}
}, ct);
try
{
await sender.StartEncodedSendingAsync(receiver.Endpoint,
pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
var elapsed = Stopwatch.StartNew();
while (!HasMedia(receiver, decoded) && elapsed.Elapsed < TimeSpan.FromSeconds(20))
{
if (sender.Completion.IsCompleted) await sender.Completion;
if (receiver.Completion.IsCompleted) await receiver.Completion;
await Task.Delay(100, ct);
}
Assert.True(HasMedia(receiver, decoded));
}
finally
{
lifetime.Cancel();
try { await pump; }
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
await sender.StopAsync();
}
}
[Theory(Skip = "Set POSTIT_TEST_MEDIA to an audio/video file; requires Linux LibVLC SRTP and H.264/AAC encoders.",
SkipUnless = nameof(HasFixture))]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false, "::1")]
[InlineData(true, false, "::1")]
public async Task Two_peers_decode_bidirectional_encrypted_audio_video_and_reject_wrong_keys(
bool wrongKey, bool preview, string address = "127.0.0.1")
{
var ct = TestContext.Current.CancellationToken;
var firstPort = FreePort(address: address);
var secondPort = FreePort(firstPort, address);
await using var first = new LibVlcLanCallMedia(address, firstPort, headless: true);
await using var second = new LibVlcLanCallMedia(address, secondPort, headless: true);
using var firstVideo = new DecodedVideo(first.Receiver);
using var secondVideo = new DecodedVideo(second.Receiver);
await first.StartReceivingAsync(ct);
await second.StartReceivingAsync(ct);
await Task.Delay(300, ct);
Media Source(LibVLC vlc)
{
var media = new Media(vlc, new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA")!)));
media.AddOption(":input-repeat=5");
return media;
}
await first.StartSendingAsync(wrongKey ? second.Endpoint with { Key = new string('0', 32) } : second.Endpoint,
Source, preview, ct);
await second.StartSendingAsync(first.Endpoint, Source, preview, ct);
var elapsed = Stopwatch.StartNew();
while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 8 : 20))
{
if (first.Completion.IsCompleted) await first.Completion;
if (second.Completion.IsCompleted) await second.Completion;
if (!wrongKey && HasMedia(first, firstVideo) && HasMedia(second, secondVideo) &&
first.HasRemoteMedia && second.HasRemoteMedia) break;
await Task.Delay(100, ct);
}
var a = first.Statistics;
var b = second.Statistics;
output.WriteLine($"A: audioSamples={firstVideo.AudioSamples}, rendered={firstVideo.Frames}; " +
$"B: audioSamples={secondVideo.AudioSamples}, rendered={secondVideo.Frames}; elapsed={elapsed.ElapsedMilliseconds}ms");
Assert.True(HasMedia(first, firstVideo), "First peer must decode received audio and video.");
Assert.True(first.HasRemoteMedia, "The UI must detect initial audio/video reception.");
if (wrongKey)
{
Assert.Equal(0, b.DecodedVideo);
Assert.Equal(0, b.DecodedAudio);
Assert.Equal(0, secondVideo.Frames);
Assert.Equal(0, secondVideo.AudioSamples);
Assert.False(second.HasRemoteMedia);
}
else
{
Assert.True(HasMedia(second, secondVideo), "Second peer must decode received audio and video.");
Assert.True(second.HasRemoteMedia);
}
}
private static bool HasMedia(LibVlcLanCallMedia peer, DecodedVideo video) =>
peer.Statistics.DecodedAudio > 0 && video.AudioSamples > 4800 && video.Frames >= 10;
private static int FreePort(int except = 0, string address = "127.0.0.1")
{
var ip = IPAddress.Parse(address);
for (var port = 32000; port < 60000; port += 2)
{
if (port == except) continue;
using var socket = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
using var rtcp = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
try
{
socket.Bind(new IPEndPoint(ip, port));
rtcp.Bind(new IPEndPoint(ip, port + 1));
return port;
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse) { }
}
throw new IOException("No free RTP port available.");
}
private sealed class DecodedVideo : IDisposable
{
private readonly IntPtr _pixels = Marshal.AllocHGlobal(640 * 480 * 4);
private int _frames;
private long _audioSamples;
public int Frames => Volatile.Read(ref _frames);
public long AudioSamples => Interlocked.Read(ref _audioSamples);
private readonly MediaPlayer _player;
public DecodedVideo(MediaPlayer player)
{
_player = player;
player.SetAudioFormat("S16N", 48000, 1);
player.SetAudioCallbacks((_, _, count, _) => Interlocked.Add(ref _audioSamples, count),
null, null, null, null);
player.SetVideoFormat("RV32", 640, 480, 640 * 4);
player.SetVideoCallbacks((_, planes) =>
{
Marshal.WriteIntPtr(planes, _pixels);
return IntPtr.Zero;
}, null, (_, _) => Interlocked.Increment(ref _frames));
}
public void Dispose()
{
_player.Stop();
Marshal.FreeHGlobal(_pixels);
}
}
}

View file

@ -52,6 +52,46 @@ namespace PostIt.Tests;
/// </summary>
public class MainPageButtonsTests
{
[AvaloniaFact]
public async Task Blog_toolbar_uses_page_view_model_in_home_navigation_and_tracks_changes()
{
var home = new HomePageViewModel();
var root = new MainView { DataContext = home };
var window = new Window { Content = root };
window.Show();
try
{
await root.NavRoot.PushAsync(new ContentPage { DataContext = home });
var first = new BlogsViewModel();
var page = new BlogsPage { DataContext = first };
await root.NavRoot.PushAsync(page);
page.BlogsCommandBar.IsOpen = true;
Assert.All(page.BlogsCommandBar.PrimaryCommands.OfType<Control>(),
control => Assert.Same(first, control.DataContext));
Assert.Same(first.NewPostCommand, page.NewPostButton.Command);
Assert.Same(first.SaveCommand, page.SaveButton.Command);
Assert.NotNull(page.ManageAclButton.Command);
Assert.False(page.SaveButton.IsVisible);
first.IsEditing = true;
Assert.True(page.SaveButton.IsVisible);
var second = new BlogsViewModel();
page.DataContext = second;
Assert.All(page.BlogsCommandBar.PrimaryCommands.OfType<Control>(),
control => Assert.Same(second, control.DataContext));
Assert.Same(second.NewPostCommand, page.NewPostButton.Command);
Assert.Same(second.SaveCommand, page.SaveButton.Command);
Assert.NotNull(page.ManageAclButton.Command);
Assert.False(page.SaveButton.IsVisible);
}
finally
{
window.Close();
}
}
/// <summary>
/// Fake <see cref="YavscApiClient"/> that throws on any
/// wire call. These tests never invoke a command that hits

View file

@ -1,12 +1,17 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless;
using Avalonia.Headless.XUnit;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit;
using PostIt.Controls;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
namespace PostIt.Tests;
@ -16,6 +21,201 @@ public class MarkdownEditorScrollTests
private static readonly string LongArticle =
string.Join("\n\n", Enumerable.Range(1, 100).Select(i => $"Paragraph {i}: article content."));
[AvaloniaFact]
public async Task Landscape_keyboard_preserves_controls_and_restores_editor_layout()
{
var root = new MainView();
var page = new BlogsPage { DataContext = new BlogsViewModel { IsEditing = true, DraftArticle = LongArticle } };
var window = new Window { Width = 800, Height = 400, Content = root };
try
{
window.Show();
await root.NavRoot.PushAsync(page, null);
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var editor = page.ArticleEditor;
var source = editor.FindControl<TextEditor>("SourceEditor")!;
source.TextArea.Focus();
source.CaretOffset = source.Document.TextLength;
root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200));
window.UpdateLayout();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.IsVisible);
Assert.True(root.SessionBanner.IsVisible);
Assert.Equal(1, Grid.GetColumn(page.DraftTitleTextBox));
Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder));
Assert.True(page.StatusBar.IsVisible);
Assert.Equal(2, Grid.GetColumn(page.StatusBar));
Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page));
Assert.True(source.TextArea.Bounds.Height >= source.TextArea.TextView.DefaultLineHeight * 3);
var bottom = source.TranslatePoint(new Point(0, source.Bounds.Height), window)!.Value.Y;
Assert.InRange(bottom, 1, 200);
var document = source.Document;
root.ApplyKeyboardOcclusion(null);
window.UpdateLayout();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.IsVisible);
Assert.True(root.SessionBanner.IsVisible);
Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox));
Assert.Same(document, source.Document);
Assert.True(source.TextArea.IsFocused);
window.Height = 200;
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200));
Assert.Equal(0, root.Padding.Bottom);
}
finally
{
CloseWindow(window, page.ArticleEditor);
}
}
[AvaloniaFact]
public void Keyboard_padding_preserves_system_bar_insets_and_restores_them()
{
var root = new MainView();
var window = new Window { Width = 600, Height = 800, Content = root };
try
{
window.Show();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var safeArea = new Thickness(10, 24, 12, 30);
root.ApplySafeArea(safeArea);
Assert.Equal(safeArea, root.Padding);
root.ApplyKeyboardOcclusion(new Rect(0, 500, 600, 300));
Assert.Equal(new Thickness(10, 24, 12, 300), root.Padding);
root.ApplySafeArea(new Thickness(20, 26, 22, 32));
Assert.Equal(new Thickness(20, 26, 22, 300), root.Padding);
root.ApplyKeyboardOcclusion(null);
window.UpdateLayout();
Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding);
var navigationTop = root.NavRoot.TranslatePoint(new Point(), window)!.Value.Y;
var bannerBottom = root.SessionBanner.TranslatePoint(new Point(0, root.SessionBanner.Bounds.Height), window)!.Value.Y;
Assert.True(navigationTop >= 26);
Assert.True(bannerBottom <= 768);
Assert.True(root.SessionBanner.IsVisible);
}
finally
{
window.Close();
}
}
[AvaloniaTheory]
[InlineData(true)]
[InlineData(false)]
public void Resizing_keeps_the_focused_caret_visible_without_changing_selection(bool focused)
{
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
var other = new TextBox();
var panel = new DockPanel();
DockPanel.SetDock(other, Dock.Top);
panel.Children.Add(other);
panel.Children.Add(editor);
var window = new Window { Width = 600, Height = 500, Content = panel };
try
{
window.Show();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var source = editor.FindControl<TextEditor>("SourceEditor")!;
source.TextArea.Focus();
source.Select(LongArticle.Length - 20, 10);
source.TextArea.Caret.BringCaretToView();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var selectedText = source.SelectedText;
var caretOffset = source.CaretOffset;
var scroller = FindArticleScroller(editor, false);
if (!focused)
{
other.Focus();
scroller.ScrollToHome();
}
window.Height = 250;
window.UpdateLayout();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
Assert.Equal(selectedText, source.SelectedText);
Assert.Equal(caretOffset, source.CaretOffset);
if (focused)
{
Assert.True(source.TextArea.IsFocused);
var caret = source.TextArea.Caret.CalculateCaretRectangle();
var view = source.TextArea.TextView;
Assert.InRange(caret.Top - view.ScrollOffset.Y, 0, view.Bounds.Height);
Assert.InRange(caret.Bottom - view.ScrollOffset.Y, 0, view.Bounds.Height);
}
else
{
Assert.True(other.IsFocused);
Assert.Equal(0, scroller.Offset.Y);
}
}
finally
{
CloseWindow(window, editor);
}
}
[AvaloniaFact]
public void Repeated_touch_requests_keyboard_without_losing_focus_and_read_only_does_not()
{
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
var window = new Window { Width = 600, Height = 400, Content = editor };
var previous = Platform.ShowSoftKeyboard;
var requests = 0;
Platform.ShowSoftKeyboard = () => requests++;
try
{
window.Show();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var source = editor.FindControl<TextEditor>("SourceEditor")!;
source.TextArea.Focus();
var focusLosses = 0;
source.TextArea.LostFocus += (_, _) => focusLosses++;
var point = source.TextArea.TranslatePoint(new Point(60, 20), window)!.Value;
for (var i = 0; i < 2; i++)
{
using var touch = window.TouchBegin(point);
window.TouchEnd(touch, point);
Assert.True(source.TextArea.IsFocused);
Assert.Equal(i + 1, requests);
}
window.MouseDown(point, MouseButton.Left);
window.MouseUp(point, MouseButton.Left);
Assert.Equal(2, requests);
using (var scrollTouch = window.TouchBegin(point))
{
var end = point + new Vector(0, -80);
window.TouchMove(scrollTouch, end);
window.TouchEnd(scrollTouch, end);
}
Assert.Equal(2, requests);
source.IsReadOnly = true;
using var readOnlyTouch = window.TouchBegin(point);
window.TouchEnd(readOnlyTouch, point);
Assert.Equal(2, requests);
Assert.Equal(0, focusLosses);
}
finally
{
Platform.ShowSoftKeyboard = previous;
CloseWindow(window, editor);
}
}
[AvaloniaTheory]
[InlineData(false)]
[InlineData(true)]

View file

@ -0,0 +1,501 @@
using Avalonia.Headless.XUnit;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Text;
using System.Security.Cryptography;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using PostIt.Views;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public sealed class MessagingSessionTests
{
[Fact]
public void Only_explicit_settings_application_raises_Applied_after_successful_save()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}.json");
try
{
var settings = new Settings(path);
var saves = 0;
var applications = 0;
settings.Saved += (_, _) => saves++;
settings.Applied += (_, _) =>
{
Assert.False(settings.IsDirty);
Assert.True(File.Exists(path));
applications++;
};
settings.AndroidKeepChatConnected = true;
settings.Save();
Assert.Equal(0, applications);
settings.DarkMode = true;
Assert.True(settings.ApplyCommand.CanExecute(null));
settings.ApplyCommand.Execute(null);
Assert.Equal(1, applications);
Assert.Equal(2, saves);
Assert.False(settings.ApplyCommand.CanExecute(null));
settings.AndroidKeepChatConnected = false;
Assert.True(settings.ApplyCommand.CanExecute(null));
settings.Apply();
Assert.Equal(2, applications);
}
finally { File.Delete(path); }
}
[Fact]
public void Failed_settings_save_does_not_raise_Applied()
{
var directory = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
try
{
var settings = new Settings(directory);
var applied = false;
settings.Applied += (_, _) => applied = true;
settings.AndroidKeepChatConnected = true;
var failure = Record.Exception(() => settings.Apply());
Assert.True(failure is IOException or UnauthorizedAccessException);
Assert.False(applied);
Assert.True(settings.IsDirty);
}
finally { Directory.Delete(directory); }
}
#if DEBUG
[Fact]
public async Task Native_start_generations_reject_stale_requests_after_stop_and_timeout()
=> await PostIt.Android.Tests.ChatServiceEpochTests.VerifyAsync();
#endif
[AvaloniaFact]
public void Settings_page_binds_opt_in_and_hides_it_on_other_platforms()
{
var settings = new Settings();
var page = new SettingsPage { DataContext = settings };
var window = new Window { Content = page };
try
{
window.Show();
var checkbox = page.FindControl<CheckBox>("BackgroundChatCheckBox")!;
var container = checkbox.GetVisualAncestors().OfType<StackPanel>().First();
Assert.Equal(OperatingSystem.IsAndroid(), container.IsVisible);
var explanation = Assert.Single(container.Children.OfType<TextBlock>()).Text!;
Assert.Contains("sans notification permanente", explanation);
Assert.Contains("ne garantissent pas", explanation);
Assert.False(checkbox.IsChecked);
var save = Assert.Single(window.GetVisualDescendants().OfType<Button>(),
button => Equals(button.Content, "Sauver"));
Assert.Same(settings.ApplyCommand, save.Command);
checkbox.IsChecked = true;
Assert.True(settings.AndroidKeepChatConnected);
Assert.True(settings.IsDirty);
settings.AndroidKeepChatConnected = false;
Assert.False(checkbox.IsChecked);
}
finally { window.Close(); }
}
[Fact]
public void Background_chat_service_are_opt_in_and_saved_only_after_persistence()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-{Guid.NewGuid():N}.json");
try
{
var settings = new Settings(path);
Assert.False(settings.AndroidKeepChatConnected);
var saves = 0;
settings.Saved += (_, _) =>
{
Assert.True(File.Exists(path));
Assert.False(settings.IsDirty);
saves++;
};
settings.AndroidKeepChatConnected = true;
Assert.True(settings.IsDirty);
settings.Save();
var restored = new Settings(path);
restored.Authentication.Authority = "";
restored.Load();
Assert.True(restored.AndroidKeepChatConnected);
Assert.False(restored.IsDirty);
Assert.Equal(1, saves);
}
finally { File.Delete(path); }
}
[Fact]
public async Task Logout_exposes_credentials_for_service_shutdown_but_clears_them_even_if_cleanup_fails()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-{Guid.NewGuid():N}");
try
{
var store = CreateStore(path);
await using var api = new YavscApiClient(new Settings(), store);
api.SigningOut += () =>
{
Assert.True(api.IsSigningOut);
Assert.True(api.HasValidSession);
Assert.NotNull(api.CurrentAccessToken);
throw new HttpRequestException("offline");
};
await Assert.ThrowsAsync<HttpRequestException>(() => api.LogoutAsync());
Assert.False(api.HasValidSession);
Assert.False(api.IsSigningOut);
Assert.Null(api.CurrentAccessToken);
Assert.Null(store.Load());
}
finally { File.Delete(path); }
}
[Fact]
public async Task Starting_a_connection_during_logout_is_rejected_even_while_credentials_exist()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-signout-{Guid.NewGuid():N}");
try
{
var settings = new Settings();
await using var api = new YavscApiClient(settings, CreateStore(path));
await using var transport = new ChatHubConnection(api);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
api.SigningOut += () => release.Task;
var logout = api.LogoutAsync();
try
{
Assert.True(api.IsSigningOut);
Assert.True(api.HasValidSession);
await Assert.ThrowsAsync<InvalidOperationException>(() => transport.StartAsync());
var vm = new ChatViewModel(api, settings, transport);
await vm.ConnectAsync();
Assert.False(vm.ConnectionRequested);
Assert.False(vm.IsConnected);
}
finally
{
release.TrySetResult();
await logout;
}
Assert.False(api.HasValidSession);
Assert.False(api.IsSigningOut);
}
finally { File.Delete(path); }
}
[AvaloniaFact]
public async Task Disconnect_cancels_an_in_flight_chat_handshake_instead_of_waiting_for_network_timeout()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Logging.ClearProviders();
var handshake = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var server = builder.Build();
server.MapPost("/" + Yavsc.Constants.ChatHubPath + "/negotiate", async (Microsoft.AspNetCore.Http.HttpContext context) =>
{
handshake.TrySetResult();
await Task.Delay(Timeout.Infinite, context.RequestAborted);
});
await server.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-cancel-{Guid.NewGuid():N}");
try
{
var settings = new Settings { ApiUrl = server.Urls.Single() + "/api/v1/" };
settings.Authentication.Authority = "https://login.example.test";
await using var api = new YavscApiClient(settings, CreateStore(path));
await using var transport = new ChatHubConnection(api);
var vm = new ChatViewModel(api, settings, transport);
var connect = vm.ConnectAsync();
await handshake.Task.WaitAsync(TimeSpan.FromSeconds(5));
var disconnect = vm.DisconnectAsync();
var deadline = DateTime.UtcNow.AddSeconds(5);
while (!disconnect.IsCompleted && DateTime.UtcNow < deadline)
{
Dispatcher.UIThread.RunJobs();
await Task.Delay(10, TestContext.Current.CancellationToken);
}
Assert.True(disconnect.IsCompleted, $"Transport={transport.Connection.State}, chat={vm.Status.Message}");
await disconnect;
await connect;
Assert.False(vm.ConnectionRequested);
Assert.False(vm.IsConnected);
}
finally
{
File.Delete(path);
await server.StopAsync();
}
}
[Theory]
[InlineData("alice", "https://api.example.test/api/v1/", true)]
[InlineData("bob", "https://api.example.test/api/v1/", false)]
[InlineData("alice", "https://other.example.test/api/v1/", false)]
public async Task Remembered_rooms_are_isolated_by_account_and_server(string user, string apiUrl, bool restored)
{
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-identity-{Guid.NewGuid():N}");
try
{
const string authority = "https://login.example.test";
var settings = new Settings { ApiUrl = apiUrl };
settings.Authentication.Authority = authority;
var aliceKey = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
authority + "\nhttps://api.example.test/api/v1/\nalice")));
settings.ChatRoomsByAccount[aliceKey] = ["PrivateRoom"];
var jwt = "e30." + Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"sub\":\"" + user + "\"}"))
.TrimEnd('=').Replace('+', '-').Replace('/', '_') + ".signature";
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord(jwt, "refresh", DateTimeOffset.UtcNow.AddHours(1), jwt));
await using var api = new YavscApiClient(settings, store);
await using var transport = new ChatHubConnection(api);
Assert.Equal(restored ? 1 : 0, transport.JoinedRooms.Length);
}
finally { File.Delete(path); }
}
[AvaloniaTheory]
[InlineData(true)]
[InlineData(false)]
public async Task Session_uses_one_chat_connection_and_logout_disables_service_before_token_purge(bool connectOnLogin)
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Logging.ClearProviders();
builder.Services.AddSignalR();
builder.Services.AddSingleton<ConnectionCounter>();
await using var server = builder.Build();
server.MapHub<TestChatHub>("/" + Yavsc.Constants.ChatHubPath);
await server.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-{Guid.NewGuid():N}");
var previous = Platform.BackgroundChatService;
var native = new RecordingChatService();
Platform.BackgroundChatService = native;
try
{
var settings = new Settings(path + ".settings")
{
ApiUrl = server.Urls.Single() + "/api/v1/",
AndroidKeepChatConnected = true
};
settings.Authentication.Authority = "https://login.example.test";
await using var api = new YavscApiClient(settings, CreateStore(path));
await using var transport = new ChatHubConnection(api);
var chat = new ChatViewModel(api, settings, transport);
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
await using var messaging = new MessagingSession(api, session, chat);
await messaging.StartAsync(connectOnLogin);
if (!connectOnLogin)
{
Assert.False(chat.IsConnected);
await chat.ConnectAsync();
}
Assert.True(chat.IsConnected, chat.Status.Message);
await Task.WhenAll(chat.ConnectAsync(), chat.ConnectAsync(), messaging.StartAsync());
Assert.Equal(1, await transport.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal(connectOnLogin ? new[] { true } : new[] { false, true }, native.Preferences);
chat.CurrentRoom = "first";
await chat.JoinRoomCommand();
chat.CurrentRoom = "second";
await chat.JoinRoomCommand();
Assert.Equal(new[] { "first", "second" }, chat.JoinedRooms);
var counter = server.Services.GetRequiredService<ConnectionCounter>();
counter.Context!.Abort();
var deadline = DateTime.UtcNow.AddSeconds(40);
while (!counter.RoomsRejoined.Task.IsCompleted && DateTime.UtcNow < deadline)
{
Dispatcher.UIThread.RunJobs();
await Task.Delay(20, TestContext.Current.CancellationToken);
}
Assert.True(counter.RoomsRejoined.Task.IsCompleted,
$"Connections={counter.Count}, transport={transport.Connection.State}, chat={chat.Status.Message}");
Assert.Equal(2, await transport.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal(new[] { "first", "second" }, counter.RejoinedRooms);
Platform.SuspendPlayback();
Assert.True(chat.IsConnected);
await chat.DisconnectAsync();
settings.Save();
Assert.False(chat.ConnectionRequested);
Assert.False(native.Preferences.Last());
await chat.ConnectAsync();
Assert.True(native.Preferences.Last());
settings.AndroidKeepChatConnected = false;
settings.Save();
await native.DisabledByPreference.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.False(native.Preferences.Last());
native.BlockNextStart = true;
settings.AndroidKeepChatConnected = true;
settings.Save();
await native.ServiceStartRequested.Task.WaitAsync(TimeSpan.FromSeconds(5));
await session.LogoutAsync().WaitAsync(TimeSpan.FromSeconds(5));
Assert.False(chat.IsConnected);
Assert.False(chat.ConnectionRequested);
Assert.False(api.HasValidSession);
Assert.True(native.DisabledWithValidToken);
Assert.True(native.ServiceStartCancelled);
}
finally
{
Platform.BackgroundChatService = previous;
File.Delete(path);
File.Delete(path + ".settings");
await server.StopAsync();
}
}
[AvaloniaFact]
public async Task Headless_transport_restores_account_rooms_and_the_later_ui_reuses_its_socket()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Logging.ClearProviders();
builder.Services.AddSignalR();
builder.Services.AddSingleton<ConnectionCounter>();
await using var server = builder.Build();
server.MapHub<TestChatHub>("/" + Yavsc.Constants.ChatHubPath);
await server.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-rooms-{Guid.NewGuid():N}");
try
{
var settings = new Settings(path + ".settings") { ApiUrl = server.Urls.Single() + "/api/v1/" };
settings.Authentication.Authority = "https://login.example.test";
var store = CreateStore(path);
var jwt = "e30." + Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"sub\":\"alice\"}")).TrimEnd('=')
.Replace('+', '-').Replace('/', '_') + ".signature";
store.Save(new RefreshTokenRecord(jwt, "refresh", DateTimeOffset.UtcNow.AddHours(1), jwt));
await using (var api = new YavscApiClient(settings, store))
await using (var transport = new ChatHubConnection(api))
{
await transport.StartAsync(TestContext.Current.CancellationToken);
await transport.JoinAsync("SavedRoom", TestContext.Current.CancellationToken);
Assert.Single(settings.ChatRoomsByAccount);
}
var restored = new Settings(path + ".settings");
restored.Authentication.Authority = "";
restored.Load();
await using var resumedApi = new YavscApiClient(restored, store);
await using var resumed = new ChatHubConnection(resumedApi);
await resumed.StartAsync(TestContext.Current.CancellationToken);
Assert.Equal(2, await resumed.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal("SavedRoom", Assert.Single(resumed.JoinedRooms).Name);
Assert.Equal(new[] { "SavedRoom" }, server.Services.GetRequiredService<ConnectionCounter>().RejoinedRooms);
var firstMessages = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var allMessages = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
resumed.MessageReceived += delivery =>
{
if (delivery.Sequence == 2) firstMessages.TrySetResult();
if (delivery.Sequence == 504) allMessages.TrySetResult();
};
await resumed.Connection.InvokeAsync("EmitMessages", 1);
await firstMessages.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(2, resumed.RecentMessages.Length);
var vm = new ChatViewModel(resumedApi, restored, resumed);
await vm.ConnectAsync();
Assert.Equal(2, await resumed.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal(new[] { "SavedRoom" }, vm.JoinedRooms);
Assert.Contains("alice : room-0", vm.FocusedMessages);
vm.SelectedRoom = null;
Assert.Contains("[Prive] bob : private-0", vm.FocusedMessages);
vm.SelectedRoom = "SavedRoom";
await resumed.Connection.InvokeAsync("EmitMessages", 251);
await allMessages.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(500, resumed.RecentMessages.Length);
await vm.LeaveRoom();
Assert.Empty(resumed.JoinedRooms);
Assert.Empty(vm.JoinedRooms);
Assert.Empty(Assert.Single(restored.ChatRoomsByAccount).Value);
await vm.DisconnectAsync();
Assert.Empty(resumed.RecentMessages);
Assert.DoesNotContain(vm.FocusedMessages, message => message.Contains("private-0"));
}
finally
{
File.Delete(path);
File.Delete(path + ".settings");
await server.StopAsync();
}
}
private static TokenStore CreateStore(string path)
{
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1), null));
return store;
}
public sealed class ConnectionCounter
{
public int Count;
public HubCallerContext? Context;
public List<string> RejoinedRooms { get; } = [];
public TaskCompletionSource RoomsRejoined { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
public sealed class TestChatHub(ConnectionCounter counter) : Hub
{
public int ConnectionCount() => counter.Count;
public ChatRoomInfo Join(string room)
{
if (counter.Count > 1)
{
counter.RejoinedRooms.Add(room);
if (counter.RejoinedRooms.Count == 2) counter.RoomsRejoined.TrySetResult();
}
return new ChatRoomInfo { Name = room };
}
public Task Part(string room, string reason) => Task.CompletedTask;
public async Task EmitMessages(int count)
{
for (var index = 0; index < count; index++)
{
await Clients.Caller.SendAsync("ReceiveMessage", new ChatMessage
{
Room = "SavedRoom", Name = "alice", Message = $"room-{index}"
});
await Clients.Caller.SendAsync("addPV", "bob", $"private-{index}");
}
}
public override Task OnConnectedAsync()
{
counter.Context = Context;
Interlocked.Increment(ref counter.Count);
return base.OnConnectedAsync();
}
}
private sealed class RecordingChatService : IBackgroundChatService
{
public List<bool> Preferences { get; } = [];
public bool DisabledWithValidToken { get; private set; }
public bool BlockNextStart { get; set; }
public bool ServiceStartCancelled { get; private set; }
public TaskCompletionSource DisabledByPreference { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource ServiceStartRequested { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public async Task SynchronizeAsync(YavscApiClient api, bool enabled, CancellationToken ct = default)
{
Preferences.Add(enabled);
if (!enabled) DisabledByPreference.TrySetResult();
if (BlockNextStart)
{
ServiceStartRequested.TrySetResult();
try { await Task.Delay(Timeout.Infinite, ct); }
finally { ServiceStartCancelled = ct.IsCancellationRequested; }
}
}
public Task DisableAsync(YavscApiClient api, CancellationToken ct = default)
{
DisabledWithValidToken = api.HasValidSession;
return Task.CompletedTask;
}
}
}

View file

@ -0,0 +1,72 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Workflow;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public sealed class PerformerDonationSettingsTests
{
[Theory]
[InlineData("performer@payments.example", "performer@payments.example")]
[InlineData(" performer@payments.example ", "performer@payments.example")]
[InlineData("", "")]
public void Performer_editor_includes_the_paypal_recipient_in_the_save_payload(string value, string expected)
{
var vm = new PerformerConfigurationPageViewModel { DonationPayPalEmail = value };
Assert.Equal(expected, vm.BuildPerformerProfileSettings().DonationPayPalEmail);
}
[AvaloniaFact]
public async Task Performer_editor_loads_displays_edits_and_saves_the_private_recipient()
{
var tokenPath = Path.Combine(Path.GetTempPath(), "postit-donation-" + Guid.NewGuid().ToString("N") + ".json");
try
{
await using var api = new PerformerApi(tokenPath);
var vm = new PerformerConfigurationPageViewModel(api, new ActivityApiClient(api, api.Settings.ApiUrl));
await vm.RefreshAsync();
Assert.Equal("initial@payments.example", vm.DonationPayPalEmail);
var page = new PerformerConfigurationPage { DataContext = vm };
var input = page.FindControl<TextBox>("DonationPayPalEmailInput")!;
Assert.Equal("initial@payments.example", input.Text);
input.Text = "updated@payments.example";
Assert.Equal("updated@payments.example", vm.DonationPayPalEmail);
await vm.SaveAsync();
Assert.Equal("updated@payments.example", api.Saved?.DonationPayPalEmail);
input.Text = "";
await vm.SaveAsync();
Assert.Equal("", api.Saved?.DonationPayPalEmail);
}
finally
{
if (File.Exists(tokenPath)) File.Delete(tokenPath);
}
}
private sealed class PerformerApi(string tokenPath) : YavscApiClient(new Settings
{
Authentication = new AuthenticationSettings
{
Authority = "https://org.example.test", ClientId = "postit", Scopes = ["openid", "api"]
}
}, new TokenStore(tokenPath))
{
public PerformerProfileSettings? Saved { get; private set; }
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
if (typeof(T) == typeof(List<ActivityInfo>))
return Task.FromResult((T)(object)new List<ActivityInfo>());
Assert.EndsWith("/account/performer-profile", path);
if (method == HttpMethod.Put) Saved = Assert.IsType<PerformerProfileSettings>(body);
return Task.FromResult((T)(object)new PerformerProfileSettings
{
PerformerId = "author", DonationPayPalEmail = "initial@payments.example"
});
}
}
}

View file

@ -1,7 +1,10 @@
using System.Net;
using Avalonia.Headless.XUnit;
using Avalonia.Headless;
using Avalonia.Controls;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
@ -9,6 +12,236 @@ namespace PostIt.Tests;
public sealed class PodcastBroadcasterTests
{
[Theory]
[InlineData("stop")]
[InlineData("leave")]
[InlineData("logout")]
[InlineData("failure")]
[InlineData("broadcast")]
public Task Camera_can_be_previewed_without_creating_a_broadcast_and_is_released_before_next_capture(string action)
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-local-preview-{Guid.NewGuid():N}");
var previousDevices = Platform.GetPodcastCaptureDevices;
var previousPreview = Platform.CreatePodcastPreviewAsync;
var previousCapture = Platform.CreatePodcastCaptureAsync;
var previousPermissions = Platform.RequestPodcastPermissionsAsync;
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1)));
await using var api = new YavscApiClient(new Settings(path + ".settings"), store);
await using var transport = new Transport();
var preview = new PreviewCapture();
PodcastsPageViewModel? vm = null;
try
{
Platform.GetPodcastCaptureDevices = () => new([new("Camera", "camera")], [new("Mic", "microphone")]);
Platform.CreatePodcastPreviewAsync = (camera, _) =>
{
Assert.Equal("camera", camera);
return Task.FromResult<IPodcastCapture>(preview);
};
Platform.RequestPodcastPermissionsAsync = (_, _) => Task.CompletedTask;
Platform.CreatePodcastCaptureAsync = (_, microphone, directory, _) =>
{
Assert.True(preview.Disposed);
Assert.Equal("microphone", microphone);
return Task.FromResult<IPodcastCapture>(new FakeCapture(directory, new Border()));
};
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
vm = new PodcastsPageViewModel(new PodcastApiClient(transport, () => "https://api.example/"), api, session);
vm.DetectDevicesCommand.Execute(null);
vm.Title = "";
vm.KeepScreenOnDuringCapture = true;
Assert.False(Platform.ScreenAwake.IsRequested);
Assert.True(vm.PreviewCommand.CanExecute(null));
Assert.False(vm.StartCommand.CanExecute(null));
await vm.PreviewCommand.ExecuteAsync(null);
Assert.True(vm.IsPreviewing);
Assert.True(Platform.ScreenAwake.IsRequested);
vm.KeepScreenOnDuringCapture = false;
Assert.False(Platform.ScreenAwake.IsRequested);
vm.KeepScreenOnDuringCapture = true;
Assert.True(Platform.ScreenAwake.IsRequested);
Assert.True(vm.IsCapturing);
Assert.False(vm.IsBroadcasting);
Assert.Same(preview.Preview, vm.CapturePreview);
Assert.False(vm.DetectDevicesCommand.CanExecute(null));
Assert.True(vm.StopPreviewCommand.CanExecute(null));
Assert.Equal(0, transport.CreateCount);
Assert.Empty(transport.Uploads);
var page = new PodcastsPage { DataContext = vm };
Assert.Same(preview.Preview, page.FindControl<ContentControl>("CapturePreviewHost")!.Content);
preview.OnDispose = () => Assert.Null(vm.CapturePreview);
switch (action)
{
case "stop": await vm.StopPreviewCommand.ExecuteAsync(null); break;
case "leave": await vm.DeactivateAsync(); break;
case "logout": await session.LogoutAsync(); break;
case "failure": preview.Fail(); break;
case "broadcast":
vm.Title = "Emission";
Assert.True(vm.StartCommand.CanExecute(null));
await vm.StartCommand.ExecuteAsync(null);
Assert.True(vm.IsBroadcasting);
Assert.True(Platform.ScreenAwake.IsRequested);
Assert.Equal(1, transport.CreateCount);
await vm.StopAsync();
break;
}
await WaitForUiAsync(() => preview.Disposed && !vm.IsPreviewing && !vm.IsBroadcasting);
Assert.True(preview.Disposed);
Assert.False(vm.IsPreviewing);
Assert.False(Platform.ScreenAwake.IsRequested);
Assert.Null(vm.CapturePreview);
if (action == "failure") Assert.Contains("Camera disconnected", vm.Status);
if (action != "broadcast") Assert.Equal(0, transport.CreateCount);
return true;
}
finally
{
if (vm is not null) await vm.DeactivateAsync();
Platform.GetPodcastCaptureDevices = previousDevices;
Platform.CreatePodcastPreviewAsync = previousPreview;
Platform.CreatePodcastCaptureAsync = previousCapture;
Platform.RequestPodcastPermissionsAsync = previousPermissions;
File.Delete(path);
File.Delete(path + ".settings");
}
}, TestContext.Current.CancellationToken);
[Fact]
public Task Leaving_the_page_during_preview_start_disposes_the_late_camera_without_showing_it()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preview-race-{Guid.NewGuid():N}");
var previous = Platform.CreatePodcastPreviewAsync;
var previousDevices = Platform.GetPodcastCaptureDevices;
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1)));
await using var api = new YavscApiClient(new Settings(path + ".settings"), store);
var preview = new PreviewCapture();
var pending = new TaskCompletionSource<IPodcastCapture>(TaskCreationOptions.RunContinuationsAsynchronously);
try
{
Platform.GetPodcastCaptureDevices = () => new([new("Camera", "camera")], []);
Platform.CreatePodcastPreviewAsync = (_, _) => pending.Task;
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
vm.DetectDevicesCommand.Execute(null);
var start = vm.PreviewCommand.ExecuteAsync(null);
var leave = vm.DeactivateAsync();
pending.SetResult(preview);
await WaitForUiAsync(() => start.IsCompleted && leave.IsCompleted);
await start;
await leave;
Assert.True(preview.Disposed);
Assert.Null(vm.CapturePreview);
Assert.False(vm.IsPreviewing);
return true;
}
finally
{
Platform.CreatePodcastPreviewAsync = previous;
Platform.GetPodcastCaptureDevices = previousDevices;
File.Delete(path);
File.Delete(path + ".settings");
}
}, TestContext.Current.CancellationToken);
private static async Task WaitForUiAsync(Func<bool> done)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
while (!done())
{
Avalonia.Threading.Dispatcher.UIThread.RunJobs();
await Task.Delay(10, timeout.Token);
}
}
private sealed class PreviewCapture : IPodcastCapture
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task Completion => _completion.Task;
public Control? Preview { get; } = new Border();
public bool Disposed { get; private set; }
public Action? OnDispose { get; set; }
public void Fail() => _completion.TrySetException(new IOException("Camera disconnected"));
public Task StopAsync() { _completion.TrySetResult(); return Task.CompletedTask; }
public async ValueTask DisposeAsync()
{
OnDispose?.Invoke();
await StopAsync();
Disposed = true;
}
}
[Fact]
public Task Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-preview-{Guid.NewGuid():N}.json");
var devices = Platform.GetPodcastCaptureDevices;
var permissions = Platform.RequestPodcastPermissionsAsync;
var factory = Platform.CreatePodcastCaptureAsync;
var store = new TokenStore(tokenPath);
store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null));
await using var api = new YavscApiClient(new Settings(tokenPath + ".settings"), store);
await using var transport = new Transport();
FakeCapture? capture = null;
PodcastsPageViewModel? vm = null;
try
{
var preview = new Border();
var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Platform.GetPodcastCaptureDevices = () => new([new("Camera", "camera")], [new("None", "")]);
Platform.RequestPodcastPermissionsAsync = (_, _) => Task.CompletedTask;
Platform.CreatePodcastCaptureAsync = (_, _, directory, _) =>
{
capture = new FakeCapture(directory, preview)
{
OnDispose = () =>
{
Assert.Null(vm!.CapturePreview);
disposed.TrySetResult();
}
};
return Task.FromResult<IPodcastCapture>(capture);
};
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
vm = new PodcastsPageViewModel(new PodcastApiClient(transport, () => "https://api.example/"), api, session)
{
Title = "Preview"
};
vm.DetectDevicesCommand.Execute(null);
await vm.StartCommand.ExecuteAsync(null);
Assert.Same(preview, vm.CapturePreview);
Assert.True(vm.IsBroadcasting);
var page = new PodcastsPage { DataContext = vm };
var host = page.FindControl<ContentControl>("CapturePreviewHost");
Assert.NotNull(host);
Assert.Same(preview, host.Content);
await vm.DeactivateAsync();
await disposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
Assert.Null(vm.CapturePreview);
Assert.Null(host.Content);
Assert.True(capture!.Stopped);
return true;
}
finally
{
if (vm?.IsBroadcasting == true) await vm.StopAsync();
Platform.GetPodcastCaptureDevices = devices;
Platform.RequestPodcastPermissionsAsync = permissions;
Platform.CreatePodcastCaptureAsync = factory;
File.Delete(tokenPath);
File.Delete(tokenPath + ".settings");
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Shared_page_uses_platform_devices_and_requests_permissions_before_creating_server_broadcast()
{
@ -18,7 +251,7 @@ public sealed class PodcastBroadcasterTests
var factory = Platform.CreatePodcastCaptureAsync;
var store = new TokenStore(tokenPath);
store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null));
await using var api = new YavscApiClient(new Settings(), store);
await using var api = new YavscApiClient(new Settings(tokenPath + ".settings"), store);
await using var transport = new Transport();
try
{
@ -53,9 +286,26 @@ public sealed class PodcastBroadcasterTests
Platform.RequestPodcastPermissionsAsync = permissions;
Platform.CreatePodcastCaptureAsync = factory;
File.Delete(tokenPath);
File.Delete(tokenPath + ".settings");
}
}
[Fact]
public async Task Prepared_broadcast_starts_the_existing_emission_instead_of_creating_another()
{
await using var transport = new Transport();
var client = new PodcastApiClient(transport, () => "https://api.example/");
FakeCapture? capture = null;
await using var broadcaster = await PodcastBroadcaster.StartAsync(client, "Prepared",
(directory, _) => Task.FromResult<IPodcastCapture>(capture = new FakeCapture(directory)),
TestContext.Current.CancellationToken, transport.PodcastId);
Assert.Equal(transport.PodcastId, broadcaster.Podcast.Id);
Assert.Equal(transport.PodcastId, transport.StartedId);
Assert.Equal(0, transport.CreateCount);
await capture!.StopAsync();
await broadcaster.Completion.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
[Fact]
public async Task Native_stop_flushes_final_segment_before_completing_server_replay()
{
@ -120,9 +370,12 @@ public sealed class PodcastBroadcasterTests
public string Directory { get; }
public bool Stopped { get; private set; }
public bool Disposed { get; private set; }
public Control? Preview { get; }
public Action? OnDispose { get; init; }
public Task Completion => _completion.Task;
public FakeCapture(string directory)
public FakeCapture(string directory, Control? preview = null)
{
Preview = preview;
Directory = directory;
File.WriteAllBytes(Path.Combine(directory, "segment-00000000.ts"), [0x47, 1]);
File.WriteAllText(Path.Combine(directory, "index.m3u8"), "#EXTM3U\n#EXTINF:2,\nsegment-00000000.ts\n");
@ -136,7 +389,7 @@ public sealed class PodcastBroadcasterTests
_completion.TrySetResult();
return Task.CompletedTask;
}
public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; }
public ValueTask DisposeAsync() { Disposed = true; OnDispose?.Invoke(); return ValueTask.CompletedTask; }
}
private sealed class Transport : IYavscApiClient
@ -148,10 +401,14 @@ public sealed class PodcastBroadcasterTests
public List<string> Events { get; } = [];
public bool FailUpload { get; init; }
public int CreateCount { get; private set; }
public Guid PodcastId => _podcast.Id;
public Guid? StartedId { get; private set; }
public TaskCompletionSource FirstUpload { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
if (path.EndsWith("/complete", StringComparison.Ordinal)) Events.Add("complete");
else if (path.EndsWith("/start", StringComparison.Ordinal))
StartedId = Guid.Parse(new Uri(path).Segments[^2].TrimEnd('/'));
else CreateCount++;
return Task.FromResult((T)(object)_podcast);
}

View file

@ -1,5 +1,8 @@
using System.Net;
using System.Net.Http;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using LibVLCSharp.Shared;
using PostIt.Services;
using Yavsc.Abstract.Streaming;
@ -7,28 +10,47 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
public sealed class PodcastNativeCaptureTests
public sealed class PodcastNativeCaptureTests(ITestOutputHelper output)
{
public static bool HasFixture => File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
[Fact(Skip = "Set POSTIT_TEST_MEDIA to a local video with audio and install LibVLC with H.264/AAC encoders.", SkipUnless = nameof(HasFixture))]
public async Task LibVLC_produces_complete_H264_AAC_HLS_segments_without_external_encoder()
[Theory(Skip = "Set POSTIT_TEST_MEDIA to a local video with audio and install LibVLC with H.264/AAC encoders.", SkipUnless = nameof(HasFixture))]
[InlineData(false)]
[InlineData(true)]
public async Task LibVLC_produces_complete_H264_AAC_HLS_segments_without_external_encoder(bool preview)
{
var root = Path.Combine(Path.GetTempPath(), $"postit native's hls {Guid.NewGuid():N}");
Directory.CreateDirectory(root);
var pixels = preview ? Marshal.AllocHGlobal(640 * 480 * 4) : IntPtr.Zero;
try
{
Core.Initialize();
using var vlc = new LibVLC();
using var vlc = new LibVLC("--vout=dummy", "--aout=dummy", "--no-xlib",
"--avcodec-hw=none", "--avcodec-threads=2");
using var media = new Media(vlc, new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA")!)));
using var player = new MediaPlayer(vlc);
PodcastBroadcaster.ConfigureOutput(media, root);
var displayed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (preview)
{
player.SetVideoFormat("RV32", 640, 480, 640 * 4);
player.SetVideoCallbacks((_, planes) =>
{
Marshal.WriteIntPtr(planes, pixels);
return IntPtr.Zero;
}, null, (_, _) => displayed.TrySetResult());
}
PodcastBroadcaster.ConfigureOutput(media, root, preview);
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
player.EndReached += (_, _) => ended.TrySetResult();
player.EncounteredError += (_, _) => ended.TrySetException(new InvalidOperationException("LibVLC encoding failed."));
Assert.True(player.Play(media));
output.WriteLine($"Encoding started (preview={preview}).");
if (preview)
await displayed.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
await ended.Task.WaitAsync(TimeSpan.FromSeconds(45), TestContext.Current.CancellationToken);
output.WriteLine("End reached; stopping player.");
player.Stop();
output.WriteLine("Player stopped; checking segments.");
var playlist = await File.ReadAllTextAsync(Path.Combine(root, "index.m3u8"), TestContext.Current.CancellationToken);
var segments = HlsCapturePlaylist.Parse(playlist);
Assert.True(segments.Count >= 2, playlist);
@ -41,8 +63,34 @@ public sealed class PodcastNativeCaptureTests
Assert.InRange(segment.DurationSeconds, 0.001, 15);
for (var i = 0; i < bytes.Length; i += 188) Assert.Equal(0x47, bytes[i]);
}
var start = new ProcessStartInfo("ffprobe") { RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in new[] { "-v", "error", "-show_streams", "-of", "json", Path.Combine(root, segments[0].FileName) })
start.ArgumentList.Add(argument);
using var probe = Process.Start(start) ?? throw new IOException("Cannot start ffprobe.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
var stdout = probe.StandardOutput.ReadToEndAsync(timeout.Token);
var stderr = probe.StandardError.ReadToEndAsync(timeout.Token);
try
{
await probe.WaitForExitAsync(timeout.Token);
Assert.True(probe.ExitCode == 0, await stderr);
using var json = JsonDocument.Parse(await stdout);
var streams = json.RootElement.GetProperty("streams").EnumerateArray().ToArray();
Assert.Contains(streams, track => track.GetProperty("codec_name").GetString() == "h264");
Assert.Contains(streams, track => track.GetProperty("codec_name").GetString() == "aac");
}
finally
{
if (!probe.HasExited) probe.Kill(entireProcessTree: true);
await probe.WaitForExitAsync(CancellationToken.None);
}
}
finally
{
if (pixels != IntPtr.Zero) Marshal.FreeHGlobal(pixels);
Directory.Delete(root, recursive: true);
}
finally { Directory.Delete(root, recursive: true); }
}
[Fact(Skip = "Set POSTIT_TEST_MEDIA to a local video with audio and install LibVLC with H.264/AAC encoders.", SkipUnless = nameof(HasFixture))]

View file

@ -0,0 +1,109 @@
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using Yavsc.Api.Client;
using Yavsc.Abstract.Identity;
using Yavsc.Abstract.Streaming;
namespace PostIt.Tests;
public sealed class PodcastPreferencesTests
{
[AvaloniaFact]
public async Task Detection_selection_and_title_survive_settings_reload_without_detecting_again()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}.json");
var previous = Platform.GetPodcastCaptureDevices;
try
{
Platform.GetPodcastCaptureDevices = () => new(
[new("Front", "front"), new("Rear", "rear")],
[new("None", ""), new("USB", "usb")]);
var settings = new Settings(path);
await using var api = new YavscApiClient(settings, new TokenStore(path + ".tokens"));
var session = new SessionStatusViewModel();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => settings.ApiUrl), api, session);
vm.DetectDevicesCommand.Execute(null);
vm.SelectedCamera = vm.Cameras[1];
vm.SelectedMicrophone = vm.Microphones[0];
vm.Title = "Mon emission habituelle";
Assert.False(vm.KeepScreenOnDuringCapture);
vm.KeepScreenOnDuringCapture = true;
Assert.False(vm.BlurPodcastBackground);
vm.BlurPodcastBackground = true;
vm.DetectDevicesCommand.Execute(null);
Assert.Equal("rear", vm.SelectedCamera?.Value);
Assert.Equal("", vm.SelectedMicrophone?.Value);
var restored = new Settings(path);
restored.Authentication.Authority = "";
restored.Load();
Assert.False(restored.IsDirty);
Assert.Equal("Mon emission habituelle", restored.PodcastDefaultTitle);
Assert.Equal("rear", restored.PodcastCameraId);
Assert.Equal("", restored.PodcastMicrophoneId);
Assert.True(restored.PodcastKeepScreenOn);
Assert.True(restored.PodcastBlurBackground);
Platform.GetPodcastCaptureDevices = () => throw new InvalidOperationException("Must use saved devices.");
await using var otherApi = new PreferencesApi(restored, new TokenStore(path + ".tokens"));
var other = new PodcastsPageViewModel(new PodcastApiClient(otherApi, () => restored.ApiUrl), otherApi, session);
Assert.Equal(2, other.Cameras.Count);
Assert.Equal(2, other.Microphones.Count);
Assert.Equal("rear", other.SelectedCamera?.Value);
Assert.Equal("", other.SelectedMicrophone?.Value);
Assert.Equal(vm.Title, other.Title);
Assert.True(other.KeepScreenOnDuringCapture);
Assert.True(other.BlurPodcastBackground);
restored.PodcastCameraId = "front";
restored.PodcastMicrophoneId = "usb";
restored.PodcastKeepScreenOn = false;
restored.PodcastBlurBackground = false;
await other.ActivateAsync();
Assert.Equal("front", other.SelectedCamera?.Value);
Assert.Equal("usb", other.SelectedMicrophone?.Value);
Assert.False(other.KeepScreenOnDuringCapture);
Assert.False(other.BlurPodcastBackground);
Platform.GetPodcastCaptureDevices = () => new([], []);
other.DetectDevicesCommand.Execute(null);
Assert.Null(other.SelectedCamera);
Assert.Null(other.SelectedMicrophone);
Assert.Contains("Aucune camera", other.Status);
}
finally
{
Platform.GetPodcastCaptureDevices = previous;
File.Delete(path);
File.Delete(path + ".tokens");
}
}
private sealed class PreferencesApi(Settings settings, TokenStore store) : YavscApiClient(settings, store)
{
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
object response = path.EndsWith("/account/me", StringComparison.Ordinal)
? new Me { UserId = "owner" } : new List<PodcastResponse>();
return Task.FromResult((T)response);
}
}
[AvaloniaFact]
public async Task Failed_save_is_reported_without_losing_the_title()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}");
Directory.CreateDirectory(path);
try
{
var settings = new Settings(path);
await using var api = new YavscApiClient(settings, new TokenStore(path + ".tokens"));
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => settings.ApiUrl), api, new());
vm.Title = "Titre conserve";
Assert.Equal("Titre conserve", vm.Title);
Assert.Contains("sauvegarde impossible", vm.Status);
Assert.True(settings.IsDirty);
}
finally { Directory.Delete(path); File.Delete(path + ".tokens"); }
}
}

View file

@ -0,0 +1,199 @@
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using LibVLCSharp.Shared;
using Avalonia.Controls;
using Avalonia.Headless;
using PostIt.Services;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public sealed class PodcastReplayTests
{
private static readonly Guid Id = Guid.NewGuid();
private readonly CancellationToken _ct = TestContext.Current.CancellationToken;
public static bool HasNativeFixture => File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_REPLAY"));
[Fact(Skip = "Set POSTIT_TEST_REPLAY to a local MP4 (8+ seconds) and install LibVLC.", SkipUnless = nameof(HasNativeFixture))]
public async Task LibVLC_decodes_authenticated_MP4_ranges_and_seeks_in_both_directions()
{
using var transport = new RangeTransport
{
Bytes = await File.ReadAllBytesAsync(Environment.GetEnvironmentVariable("POSTIT_TEST_REPLAY")!, _ct)
};
var api = new PodcastApiClient(transport, () => "https://api.example/");
Core.Initialize();
using var vlc = new LibVLC("--vout=dummy", "--aout=dummy", "--no-xlib");
using var input = new PodcastReplayMediaInput(api, Id, transport.Bytes.Length);
using var media = new Media(vlc, input);
using var player = new MediaPlayer(vlc);
string? failure = null;
input.Failed += message => failure = message;
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
player.EndReached += (_, _) => ended.TrySetResult();
player.EncounteredError += (_, _) => ended.TrySetException(new IOException("LibVLC MP4 decoding failed."));
Assert.True(player.Play(media));
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_ct);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
while (player.Length <= 0 || !player.IsSeekable || player.Time <= 0)
await Task.Delay(20, timeout.Token);
Assert.InRange(player.Length, 8000, 30000);
var forward = player.Length / 2;
player.Time = forward;
while (player.Time < forward - 300)
await Task.Delay(20, timeout.Token);
Assert.InRange(player.Time, forward - 300, forward + 1000);
player.Time = 1000;
while (player.Time > 2500)
await Task.Delay(20, timeout.Token);
Assert.InRange(player.Time, 500, 2500);
await ended.Task.WaitAsync(timeout.Token);
Assert.Null(failure);
Assert.Contains(media.Tracks, t => t.TrackType == TrackType.Video && t.Codec == 0x34363268);
Assert.Contains(media.Tracks, t => t.TrackType == TrackType.Audio && t.Codec == 0x6134706d);
}
finally
{
input.Cancel();
player.Stop();
}
}
[Fact]
public Task Desktop_overlay_has_real_position_pause_and_duration_controls()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastReplayTests).Assembly).Dispatch(() =>
{
var overlay = new PostIt.Controls.ReplayControls();
var window = new Window { Content = overlay, Width = 640, Height = 360 };
try
{
window.Show();
Assert.NotNull(overlay.FindControl<Slider>("PositionSlider"));
Assert.NotNull(overlay.FindControl<Button>("ToggleButton"));
Assert.Equal("0:00 / 0:00", overlay.FindControl<TextBlock>("TimeLabel")?.Text);
}
finally { window.Close(); }
}, _ct);
[Fact]
public async Task Ranges_use_authenticated_factory_with_bounded_exact_content_and_no_token_in_URL()
{
await using var transport = new RangeTransport();
var api = new PodcastApiClient(transport, () => "https://api.example/");
Assert.Equal(transport.Bytes.Skip(12).Take(3), await api.DownloadReplayRangeAsync(Id, 12, 3, transport.Bytes.Length, _ct));
Assert.Equal("bytes=12-14", transport.Range);
Assert.Equal($"https://api.example/api/v1/podcasts/{Id}/replay.mp4", transport.Url);
Assert.Equal(transport.Bytes.Skip(transport.Bytes.Length - 2),
await api.DownloadReplayRangeAsync(Id, transport.Bytes.Length - 2, 256 * 1024, transport.Bytes.Length, _ct));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
api.DownloadReplayRangeAsync(Id, 0, 256 * 1024 + 1, transport.Bytes.Length, _ct));
}
[Theory]
[InlineData("full")]
[InlineData("range")]
[InlineData("size")]
[InlineData("extra")]
public async Task Untrusted_or_unbounded_responses_fail_instead_of_playing_wrong_bytes(string failure)
{
await using var transport = new RangeTransport { Failure = failure };
var api = new PodcastApiClient(transport, () => "https://api.example/");
await Assert.ThrowsAsync<InvalidDataException>(() => api.DownloadReplayRangeAsync(Id, 0, 8, transport.Bytes.Length, _ct));
}
[Fact]
public void Native_input_supports_backward_and_forward_seek_EOF_and_cancellation()
{
using var transport = new RangeTransport();
var api = new PodcastApiClient(transport, () => "https://api.example/");
using var input = new PodcastReplayMediaInput(api, Id, transport.Bytes.Length);
Assert.True(input.CanSeek);
var buffer = Marshal.AllocHGlobal(16);
try
{
Assert.True(input.Open(out var size));
Assert.Equal((ulong)transport.Bytes.Length, size);
Assert.True(input.CanSeek);
Assert.Equal(16, input.Read(buffer, 16));
Assert.Equal(0, Marshal.ReadByte(buffer));
Assert.True(input.Seek(300000));
Assert.Equal(16, input.Read(buffer, 16));
Assert.Equal(transport.Bytes[300000], Marshal.ReadByte(buffer));
Assert.True(input.Seek(2));
Assert.Equal(16, input.Read(buffer, 16));
Assert.Equal(2, Marshal.ReadByte(buffer));
Assert.True(input.Seek(size - 1));
Assert.Equal(1, input.Read(buffer, 16));
Assert.Equal(0, input.Read(buffer, 16));
Assert.False(input.Seek(size + 1));
string? error = null;
input.Failed += message => error = message;
input.Cancel();
Assert.Equal(-1, input.Read(buffer, 16));
Assert.Null(error);
}
finally { Marshal.FreeHGlobal(buffer); }
}
[Fact]
public void Controls_hide_at_three_seconds_but_not_during_drag_pause_or_keyboard_focus()
{
var clock = new Clock();
var controls = new ReplayControlsState(clock);
Assert.True(controls.IsVisible(true, false));
clock.Now += TimeSpan.FromMilliseconds(2999);
Assert.True(controls.IsVisible(true, false));
clock.Now += TimeSpan.FromMilliseconds(1);
Assert.False(controls.IsVisible(true, false));
Assert.True(controls.IsVisible(false, false));
Assert.True(controls.IsVisible(true, true));
controls.IsInteracting = true;
Assert.True(controls.IsVisible(true, false));
controls.IsInteracting = false;
controls.Show();
Assert.True(controls.IsVisible(true, false));
Assert.Equal("0:00", ReplayControlsState.FormatTime(-1));
Assert.Equal("1:02", ReplayControlsState.FormatTime(62000));
Assert.Equal("1:01:02", ReplayControlsState.FormatTime(3662000));
}
private sealed class Clock : TimeProvider
{
public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow;
public override DateTimeOffset GetUtcNow() => Now;
}
private sealed class RangeTransport : IYavscApiClient, IDisposable
{
public byte[] Bytes { get; init; } = Enumerable.Range(0, 600000).Select(i => (byte)i).ToArray();
public string? Failure { get; init; }
public string? Range { get; private set; }
public string? Url { get; private set; }
public HttpClient Http { get; } = new();
public Task<HttpResponseMessage> SendAuthenticatedAsync(Func<HttpRequestMessage> factory, CancellationToken ct = default)
{
using var request = factory();
Range = request.Headers.Range?.ToString();
Url = request.RequestUri!.AbsoluteUri;
var item = request.Headers.Range!.Ranges.Single();
var from = item.From!.Value;
var to = item.To!.Value;
var response = new HttpResponseMessage(Failure == "full" ? HttpStatusCode.OK : HttpStatusCode.PartialContent)
{
Content = new ByteArrayContent(Bytes[(int)from..(int)(to + 1 + (Failure == "extra" ? 1 : 0))])
};
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(
Failure == "range" ? from + 1 : from, to, Failure == "size" ? Bytes.Length + 1 : Bytes.Length);
return Task.FromResult(response);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default) => throw new NotSupportedException();
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> factory, 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> factory, CancellationToken ct = default) => throw new NotSupportedException();
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
public void Dispose() => Http.Dispose();
}
}

View file

@ -0,0 +1,194 @@
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using Yavsc.Abstract.Identity;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public sealed class PodcastScheduleTests
{
[AvaloniaFact]
public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
var activation = vm.ActivateObsCommand.ExecuteAsync(null);
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid() };
vm.SelectedPodcast = api.Plan;
api.PendingActivation.SetResult(new("srt://obs.example:10000?passphrase=secret", "", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
activation = vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
api.PendingActivation.SetResult(new("srt://obs.example:10000?passphrase=secret", "", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
Assert.True(vm.ActivateObsCommand.CanExecute(null));
await vm.ActivateObsCommand.ExecuteAsync(null);
Assert.Equal("srt://obs.example:10000?passphrase=stream-secret", vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
Assert.False(vm.IsBroadcasting);
api.Settings.Save();
Assert.DoesNotContain("stream-secret", await File.ReadAllTextAsync(path + ".settings"));
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid(), OwnerId = "other" };
Assert.Empty(vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
Assert.False(vm.ActivateObsCommand.CanExecute(null));
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
Assert.Empty(vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
Assert.True(api.ObsEnabled);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateObsCommand.ExecuteAsync(null);
Assert.False(api.ObsEnabled);
Assert.Empty(vm.ObsServerUrl);
Assert.Empty(vm.ObsStreamKey);
Assert.EndsWith("/obs", api.RevokedPath);
await vm.DeactivateAsync();
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-plan-{Guid.NewGuid():N}.json");
var store = new TokenStore(tokenPath);
store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, tokenPath + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session)
{
Title = "Concert", ScheduledDate = DateTimeOffset.Now.AddDays(7),
ScheduledTime = new TimeSpan(14, 15, 0), PlannedDurationMinutes = 90
};
Assert.True(vm.PrepareCommand.CanExecute(null));
await vm.PrepareCommand.ExecuteAsync(null);
Assert.Equal(HttpMethod.Post, api.SavedMethod);
Assert.EndsWith("/podcasts/planned", api.SavedPath);
Assert.Equal(90, api.Saved?.PlannedDurationMinutes);
Assert.Null(api.Saved?.PublicAnnouncement);
Assert.Equal(14, api.Saved?.ScheduledStartAt.Hour);
Assert.Equal(PodcastState.Planned, vm.SelectedPodcast?.State);
Assert.False(vm.FinishCommand.CanExecute(null));
Assert.True(vm.DeleteCommand.CanExecute(null));
Assert.True(vm.UpdatePlanCommand.CanExecute(null));
vm.Title = "Nouveau titre";
vm.PublishAnnouncement = true;
vm.Announcement = "Venez au concert";
await vm.UpdatePlanCommand.ExecuteAsync(null);
Assert.Equal(HttpMethod.Put, api.SavedMethod);
Assert.EndsWith($"/podcasts/{api.Plan.Id}/planned", api.SavedPath);
Assert.Equal("Venez au concert", api.Saved?.PublicAnnouncement);
Assert.Equal("Nouveau titre", vm.SelectedPodcast?.Title);
vm.PublishAnnouncement = false;
await vm.UpdatePlanCommand.ExecuteAsync(null);
Assert.Null(api.Saved?.PublicAnnouncement);
vm.PlannedDurationMinutes = 0;
api.Saved = null;
await vm.UpdatePlanCommand.ExecuteAsync(null);
Assert.Null(api.Saved);
Assert.Contains("Preparation impossible", vm.Status);
Assert.False(vm.IsBroadcasting);
vm.SelectedPodcast = api.Plan with { Title = "Titre programme distinct" };
Assert.Equal("Titre programme distinct", vm.Title);
Assert.Equal("Nouveau titre", api.Settings.PodcastDefaultTitle);
vm.NewPlanCommand.Execute(null);
Assert.Equal("Nouveau titre", vm.Title);
}
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}
private sealed class ScheduleApi(TokenStore store, string settingsPath)
: YavscApiClient(new Settings(settingsPath), store), IYavscApiClient
{
public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 };
public bool ObsEnabled { get; private set; }
public string? RevokedPath { get; private set; }
public PreparePodcastRequest? Saved { get; set; }
public string? SavedPath { get; private set; }
public HttpMethod? SavedMethod { get; private set; }
public TaskCompletionSource<PodcastObsCredentials>? PendingActivation { get; set; }
public override async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
object response;
if (path.EndsWith("/account/me", StringComparison.Ordinal)) response = new Me { UserId = "owner" };
else if (path.EndsWith("/obs", StringComparison.Ordinal))
{
if (method == HttpMethod.Post)
{
ObsEnabled = true;
response = PendingActivation is null
? new PodcastObsCredentials("srt://obs.example:10000?passphrase=stream-secret", "", DateTimeOffset.UtcNow.AddMinutes(30))
: await PendingActivation.Task;
}
else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null);
}
else if (method == HttpMethod.Get) response = new List<PodcastResponse> { Plan };
else
{
Saved = Assert.IsType<PreparePodcastRequest>(body);
SavedPath = path;
SavedMethod = method;
Plan = Plan with
{
Title = Saved.Title, ScheduledStartAt = Saved.ScheduledStartAt,
PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement
};
response = Plan;
}
return (T)response;
}
Task IYavscApiClient.CallAsync(HttpMethod method, string path, object? body, CancellationToken ct)
{
Assert.Equal(HttpMethod.Delete, method);
Assert.EndsWith("/obs", path);
ObsEnabled = false;
RevokedPath = path;
return Task.CompletedTask;
}
}
}

View file

@ -6,10 +6,10 @@
<IsPackable>false</IsPackable>
<RootNamespace>PostIt.Tests</RootNamespace>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<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>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
@ -20,12 +20,15 @@
<PackageReference Include="Avalonia.Headless.XUnit" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\PostIt.Android\Services\ChatServiceEpoch.cs" Link="Android\ChatServiceEpoch.cs" />
<Compile Include="..\PostIt.Android\Tests\ChatServiceEpochTests.cs" Link="Android\ChatServiceEpochTests.cs" />
<Compile Include="..\PostIt.Android\Services\CameraFrameOrientation.cs" Link="Android\CameraFrameOrientation.cs" />
<Compile Include="..\PostIt.Android\Services\CameraFrameClock.cs" Link="Android\CameraFrameClock.cs" />
</ItemGroup>

View file

@ -156,6 +156,21 @@ public class ProviderOngoingRequestsPageViewModelTests
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
[Fact]
public async Task CreateEstimateForSelectedCommand_is_disabled_for_an_amateur_profile()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var estimateClient = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(
client, estimateClient: estimateClient, canIssueEstimates: false);
await vm.InitializeAsync();
vm.SelectedQuery = vm.Queries[0];
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
private sealed class StubProviderApi : IYavscApiClient
{
public HttpClient Http { get; } = new();

View file

@ -7,6 +7,18 @@ namespace PostIt.Tests;
public class ResourceUsageApiClientTests
{
[Fact]
public async Task Usage_remains_visible_when_the_rest_of_the_profile_is_unavailable()
{
var usage = new ResourceUsageApiClient(new FakeYavscApiClient(), "https://example.invalid/api/v1/");
var model = new PostIt.ViewModels.UserProfilePageViewModel(null, usageClient: usage);
await model.RefreshAsync();
Assert.NotNull(model.ResourceUsage);
Assert.Equal(20.65m, model.ResourceUsage.Consumption);
Assert.Null(model.UsageError);
Assert.False(model.IsProfileLoaded);
Assert.False(model.IsBusy);
}
[Fact]
public async Task GetCurrentAsync_calls_user_usage_endpoint()
{
@ -19,6 +31,10 @@ public class ResourceUsageApiClientTests
Assert.Equal("GET", fake.LastMethod);
Assert.Equal(12.5m, usage.ApiCalls);
Assert.Equal(3.2m, usage.CpuSeconds);
Assert.Equal(20.65m, usage.Consumption);
Assert.Equal(10000m, usage.ConsumptionLimit);
Assert.Equal(9979.35m, usage.RemainingConsumption);
Assert.False(usage.IsQuotaReached);
}
[Fact]
@ -56,6 +72,9 @@ public class ResourceUsageApiClientTests
CpuSeconds = 3.2m,
BandwidthMb = 18.4m,
StorageMb = 51.2m,
Consumption = 20.65m,
ConsumptionLimit = 10000m,
RemainingConsumption = 9979.35m,
EstimatedCompensation = 4.9m,
Currency = "EUR",
RecordedAtUtc = DateTimeOffset.UtcNow

View file

@ -0,0 +1,23 @@
using PostIt.Services;
namespace PostIt.Tests;
public sealed class ScreenAwakeRequestsTests
{
[Fact]
public void Independent_requests_keep_the_screen_awake_until_all_are_released()
{
var requests = new ScreenAwakeRequests();
var states = new List<bool>();
requests.Changed += () => states.Add(requests.IsRequested);
Assert.False(requests.IsRequested);
var playback = requests.Acquire();
var capture = requests.Acquire();
playback.Dispose();
Assert.True(requests.IsRequested);
playback.Dispose();
capture.Dispose();
Assert.False(requests.IsRequested);
Assert.Equal(new[] { true, true, true, false }, states);
}
}

View file

@ -17,6 +17,191 @@ namespace PostIt.Tests;
/// </summary>
public class YavscApiClientTests
{
[Theory]
[InlineData(600, true, false, 540)]
[InlineData(3600, false, true, 3540)]
[InlineData(40, true, false, 0)]
[InlineData(-5, true, false, 0)]
[InlineData(600, false, false, -1)]
public async Task Maintenance_delay_is_derived_from_the_persisted_access_token_expiry(
int lifetimeSeconds, bool active, bool keepConnected, int expectedDelaySeconds)
{
var path = TokensPath();
var now = DateTimeOffset.UtcNow;
try
{
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", now.AddSeconds(lifetimeSeconds)));
var settings = new Settings();
await using var client = new YavscApiClient(settings, store);
settings.AndroidKeepChatConnected = keepConnected;
Assert.Equal(expectedDelaySeconds < 0 ? Timeout.InfiniteTimeSpan
: TimeSpan.FromSeconds(expectedDelaySeconds), client.GetSessionRefreshDelay(now, active));
}
finally { File.Delete(path); }
}
[Theory]
[InlineData(true, false, 40, 1)]
[InlineData(false, true, 40, 1)]
[InlineData(false, false, 40, 0)]
[InlineData(true, true, 180, 0)]
public async Task Session_maintenance_refreshes_before_expiry_only_while_active_or_opted_in(
bool active, bool keepConnected, int secondsUntilExpiry, int expectedRefreshes)
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer();
await apiServer.StartAsync();
var settings = BuildSettings(authority, apiServer.BaseUrl);
settings.AndroidKeepChatConnected = keepConnected;
var tokensPath = TokensPath();
try
{
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
var store = new TokenStore(tokensPath);
var previous = store.Load()!;
var expiry = DateTimeOffset.UtcNow.AddSeconds(secondsUntilExpiry);
store.Save(previous with { AccessTokenExpiresAt = expiry });
await using var client = new YavscApiClient(settings, store);
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ =>
client.RefreshSessionIfNeededAsync(active, TestContext.Current.CancellationToken)));
Assert.Equal(expectedRefreshes, authority.RefreshRequestCount);
Assert.Equal(0, apiServer.RequestCount);
Assert.True(expiry > DateTimeOffset.UtcNow, "Refresh must occur before expiry, not after a 401.");
var persisted = store.Load()!;
if (expectedRefreshes > 0)
{
Assert.NotEqual(previous.RefreshToken, persisted.RefreshToken);
Assert.True(persisted.AccessTokenExpiresAt > expiry);
}
else Assert.Equal(previous.RefreshToken, persisted.RefreshToken);
}
finally { File.Delete(tokensPath); }
}
[Fact]
public async Task Scheduled_maintenance_runs_without_an_API_call_and_starts_only_once()
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer();
await apiServer.StartAsync();
var settings = BuildSettings(authority, apiServer.BaseUrl);
settings.AndroidKeepChatConnected = true;
var tokensPath = TokensPath();
try
{
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
var store = new TokenStore(tokensPath);
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(62) });
await using var client = new YavscApiClient(settings, store);
var scheduledDelay = client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true);
Assert.InRange(scheduledDelay.TotalSeconds, 1, 2);
client.StartSessionMaintenance();
client.StartSessionMaintenance();
await Task.Delay(250, TestContext.Current.CancellationToken);
Assert.Equal(0, authority.RefreshRequestCount);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
while (store.Load()!.AccessTokenExpiresAt - DateTimeOffset.UtcNow < TimeSpan.FromMinutes(2))
await Task.Delay(20, timeout.Token);
Assert.Equal(1, authority.RefreshRequestCount);
Assert.Equal(0, apiServer.RequestCount);
Assert.InRange(client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true).TotalSeconds, 500, 600);
}
finally { File.Delete(tokensPath); }
}
[Fact]
public async Task Session_maintenance_rejects_revoked_tokens_and_does_not_retry_after_logout()
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer();
await apiServer.StartAsync();
var settings = BuildSettings(authority, apiServer.BaseUrl);
var tokensPath = TokensPath();
try
{
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
var store = new TokenStore(tokensPath);
store.Save(store.Load()! with
{
RefreshToken = "revoked-refresh-token",
AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40)
});
await using var client = new YavscApiClient(settings, store);
var ct = TestContext.Current.CancellationToken;
client.SigningOut += () => client.RefreshSessionIfNeededAsync(true, ct);
var error = await Assert.ThrowsAsync<RefreshFailedException>(() =>
client.RefreshSessionIfNeededAsync(true, ct));
Assert.True(error.IsPermanent);
Assert.Null(store.Load());
Assert.False(client.HasValidSession);
await client.LogoutAsync();
await client.RefreshSessionIfNeededAsync(true, ct);
Assert.Equal(1, authority.RefreshRequestCount);
}
finally { File.Delete(tokensPath); }
}
[Fact]
public async Task Session_maintenance_does_not_refresh_a_due_token_during_logout()
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer();
await apiServer.StartAsync();
var settings = BuildSettings(authority, apiServer.BaseUrl);
var tokensPath = TokensPath();
try
{
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
var store = new TokenStore(tokensPath);
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40) });
await using var client = new YavscApiClient(settings, store);
client.SigningOut += () =>
{
Assert.True(client.HasValidSession);
return client.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken);
};
await client.LogoutAsync();
Assert.Equal(0, authority.RefreshRequestCount);
Assert.Null(store.Load());
Assert.False(client.HasValidSession);
}
finally { File.Delete(tokensPath); }
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Authenticated_streaming_refreshes_tokens_and_recreates_range_requests(bool expired)
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer(forceFirstRequest: !expired);
await apiServer.StartAsync();
var settings = BuildSettings(authority, apiServer.BaseUrl);
var tokensPath = TokensPath();
try
{
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
if (expired) ExpireCachedAccessToken(tokensPath);
await using var client = new YavscApiClient(settings, new TokenStore(tokensPath));
var requests = new List<HttpRequestMessage>();
using var response = await client.SendAuthenticatedAsync(() =>
{
var request = new HttpRequestMessage(HttpMethod.Get, apiServer.BaseUrl + "/posts");
request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(10, 20);
requests.Add(request);
return request;
}, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expired ? 1 : 2, requests.Count);
Assert.All(requests, request => Assert.Equal("bytes=10-20", request.Headers.Range?.ToString()));
Assert.Equal(1, authority.RefreshRequestCount);
Assert.NotEmpty(apiServer.SeenBearers);
}
finally { File.Delete(tokensPath); }
}
[Fact]
public async Task GetAnonymousAsync_surfaces_http_errors_without_attempting_login_or_retry()
{
@ -442,7 +627,9 @@ public class YavscApiClientTests
.Select(_ => client.TrySilentLoginAsync(null, ct)).ToArray();
var calls = Enumerable.Range(0, 8)
.Select(_ => client.CallAsync<List<StubApiServer.Post>>(HttpMethod.Get, "posts", ct)).ToArray();
await Task.WhenAll(silentLogins.Cast<Task>().Concat(calls));
var maintenance = Enumerable.Range(0, 8)
.Select(_ => client.RefreshSessionIfNeededAsync(true, ct));
await Task.WhenAll(silentLogins.Cast<Task>().Concat(calls).Concat(maintenance));
Assert.All(silentLogins, login => Assert.True(login.Result));
Assert.All(calls, call => Assert.NotEmpty(call.Result));

View file

@ -1,16 +1,43 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PostIt"
x:Class="PostIt.App"
RequestedThemeVariant="Default">
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
<Application
x:Class="PostIt.App"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PostIt"
RequestedThemeVariant="Default">
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
<Application.DataTemplates>
<local:ViewLocator />
</Application.DataTemplates>
<Application.DataTemplates>
<local:ViewLocator />
</Application.DataTemplates>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://AvaloniaEdit/Themes/Fluent/AvaloniaEdit.xaml" />
</Application.Styles>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://AvaloniaEdit/Themes/Fluent/AvaloniaEdit.xaml" />
</Application.Styles>
<Application.Resources>
<StreamGeometry x:Key="settings_regular">M14 9.50006C11.5147 9.50006 9.5 11.5148 9.5 14.0001C9.5 16.4853 11.5147 18.5001 14 18.5001C15.3488 18.5001 16.559 17.9066 17.3838 16.9666C18.0787 16.1746 18.5 15.1365 18.5 14.0001C18.5 13.5401 18.431 13.0963 18.3028 12.6784C17.7382 10.8381 16.0253 9.50006 14 9.50006ZM11 14.0001C11 12.3432 12.3431 11.0001 14 11.0001C15.6569 11.0001 17 12.3432 17 14.0001C17 15.6569 15.6569 17.0001 14 17.0001C12.3431 17.0001 11 15.6569 11 14.0001Z M21.7093 22.3948L19.9818 21.6364C19.4876 21.4197 18.9071 21.4515 18.44 21.7219C17.9729 21.9924 17.675 22.4693 17.6157 23.0066L17.408 24.8855C17.3651 25.273 17.084 25.5917 16.7055 25.682C14.9263 26.1061 13.0725 26.1061 11.2933 25.682C10.9148 25.5917 10.6336 25.273 10.5908 24.8855L10.3834 23.0093C10.3225 22.4731 10.0112 21.9976 9.54452 21.7281C9.07783 21.4586 8.51117 21.4269 8.01859 21.6424L6.29071 22.4009C5.93281 22.558 5.51493 22.4718 5.24806 22.1859C4.00474 20.8536 3.07924 19.2561 2.54122 17.5137C2.42533 17.1384 2.55922 16.7307 2.8749 16.4977L4.40219 15.3703C4.83721 15.0501 5.09414 14.5415 5.09414 14.0007C5.09414 13.4598 4.83721 12.9512 4.40162 12.6306L2.87529 11.5051C2.55914 11.272 2.42513 10.8638 2.54142 10.4882C3.08038 8.74734 4.00637 7.15163 5.24971 5.82114C5.51684 5.53528 5.93492 5.44941 6.29276 5.60691L8.01296 6.36404C8.50793 6.58168 9.07696 6.54881 9.54617 6.27415C10.0133 6.00264 10.3244 5.52527 10.3844 4.98794L10.5933 3.11017C10.637 2.71803 10.9245 2.39704 11.3089 2.31138C12.19 2.11504 13.0891 2.01071 14.0131 2.00006C14.9147 2.01047 15.8128 2.11485 16.6928 2.31149C17.077 2.39734 17.3643 2.71823 17.4079 3.11017L17.617 4.98937C17.7116 5.85221 18.4387 6.50572 19.3055 6.50663C19.5385 6.507 19.769 6.45838 19.9843 6.36294L21.7048 5.60568C22.0626 5.44818 22.4807 5.53405 22.7478 5.81991C23.9912 7.1504 24.9172 8.74611 25.4561 10.487C25.5723 10.8623 25.4386 11.2703 25.1228 11.5035L23.5978 12.6297C23.1628 12.95 22.9 13.4586 22.9 13.9994C22.9 14.5403 23.1628 15.0489 23.5988 15.3698L25.1251 16.4965C25.441 16.7296 25.5748 17.1376 25.4586 17.5131C24.9198 19.2536 23.9944 20.8492 22.7517 22.1799C22.4849 22.4657 22.0671 22.5518 21.7093 22.3948ZM16.263 22.1966C16.4982 21.4685 16.9889 20.8288 17.6884 20.4238C18.5702 19.9132 19.6536 19.8547 20.5841 20.2627L21.9281 20.8526C22.791 19.8538 23.4593 18.7013 23.8981 17.4552L22.7095 16.5778L22.7086 16.5771C21.898 15.98 21.4 15.0277 21.4 13.9994C21.4 12.9719 21.8974 12.0195 22.7073 11.4227L22.7085 11.4218L23.8957 10.545C23.4567 9.2988 22.7881 8.14636 21.9248 7.1477L20.5922 7.73425L20.5899 7.73527C20.1844 7.91463 19.7472 8.00722 19.3039 8.00663C17.6715 8.00453 16.3046 6.77431 16.1261 5.15465L16.1259 5.15291L15.9635 3.69304C15.3202 3.57328 14.6677 3.50872 14.013 3.50017C13.3389 3.50891 12.6821 3.57367 12.0377 3.69328L11.8751 5.15452C11.7625 6.16272 11.1793 7.05909 10.3019 7.56986C9.41937 8.0856 8.34453 8.14844 7.40869 7.73694L6.07273 7.14893C5.20949 8.14751 4.54092 9.29983 4.10196 10.5459L5.29181 11.4233C6.11115 12.0269 6.59414 12.9837 6.59414 14.0007C6.59414 15.0173 6.11142 15.9742 5.29237 16.5776L4.10161 17.4566C4.54002 18.7044 5.2085 19.8585 6.07205 20.8587L7.41742 20.2682C8.34745 19.8613 9.41573 19.9215 10.2947 20.4292C11.174 20.937 11.7593 21.832 11.8738 22.84L11.8744 22.8445L12.0362 24.3088C13.3326 24.5638 14.6662 24.5638 15.9626 24.3088L16.1247 22.8418C16.1491 22.6217 16.1955 22.4055 16.263 22.1966Z</StreamGeometry>
<StreamGeometry x:Key="save_regular">M3 5.75C3 4.23122 4.23122 3 5.75 3H15.7145C16.5764 3 17.4031 3.34241 18.0126 3.9519L20.0481 5.98744C20.6576 6.59693 21 7.42358 21 8.28553V18.25C21 19.7688 19.7688 21 18.25 21H5.75C4.23122 21 3 19.7688 3 18.25V5.75ZM5.75 4.5C5.05964 4.5 4.5 5.05964 4.5 5.75V18.25C4.5 18.9404 5.05964 19.5 5.75 19.5H6V14.25C6 13.0074 7.00736 12 8.25 12H15.75C16.9926 12 18 13.0074 18 14.25V19.5H18.25C18.9404 19.5 19.5 18.9404 19.5 18.25V8.28553C19.5 7.8214 19.3156 7.37629 18.9874 7.0481L16.9519 5.01256C16.6918 4.75246 16.3582 4.58269 16 4.52344V7.25C16 8.49264 14.9926 9.5 13.75 9.5H9.25C8.00736 9.5 7 8.49264 7 7.25V4.5H5.75ZM16.5 19.5V14.25C16.5 13.8358 16.1642 13.5 15.75 13.5H8.25C7.83579 13.5 7.5 13.8358 7.5 14.25V19.5H16.5ZM8.5 4.5V7.25C8.5 7.66421 8.83579 8 9.25 8H13.75C14.1642 8 14.5 7.66421 14.5 7.25V4.5H8.5Z</StreamGeometry>
<StreamGeometry x:Key="search_regular">M11.5,2.75 C16.3324916,2.75 20.25,6.66750844 20.25,11.5 C20.25,13.6461673 19.4773285,15.6118676 18.1949905,17.1340957 L25.0303301,23.9696699 C25.3232233,24.2625631 25.3232233,24.7374369 25.0303301,25.0303301 C24.7640635,25.2965966 24.3473998,25.3208027 24.0537883,25.1029482 L23.9696699,25.0303301 L17.1340957,18.1949905 C15.6118676,19.4773285 13.6461673,20.25 11.5,20.25 C6.66750844,20.25 2.75,16.3324916 2.75,11.5 C2.75,6.66750844 6.66750844,2.75 11.5,2.75 Z M11.5,4.25 C7.49593556,4.25 4.25,7.49593556 4.25,11.5 C4.25,15.5040644 7.49593556,18.75 11.5,18.75 C15.5040644,18.75 18.75,15.5040644 18.75,11.5 C18.75,7.49593556 15.5040644,4.25 11.5,4.25 Z</StreamGeometry>
<StreamGeometry x:Key="signature_regular">M16.4798956,21.0019578 L16.75,21 C17.9702352,21 18.6112441,21.5058032 19.4020627,22.7041662 L19.7958278,23.3124409 C20.1028266,23.766938 20.2944374,23.9573247 20.535784,24.0567929 C20.9684873,24.2351266 21.3271008,24.1474446 22.6440782,23.5133213 L23.0473273,23.3170319 C23.8709982,22.9126711 24.4330286,22.6811606 25.0680983,22.5223931 C25.4699445,22.4219316 25.8771453,22.6662521 25.9776069,23.0680983 C26.0780684,23.4699445 25.8337479,23.8771453 25.4319017,23.9776069 C25.0371606,24.0762922 24.6589465,24.2178819 24.1641364,24.4458997 L23.0054899,25.0032673 C21.4376302,25.7436944 20.9059009,25.8317321 19.964216,25.4436275 C19.3391237,25.1860028 18.9836765,24.813298 18.4635639,24.0180227 L18.2688903,23.7140849 C17.7071112,22.8288731 17.4057794,22.5384538 16.8688444,22.5036655 L16.75,22.5 C16.2017306,22.5 16.0933104,22.5684572 14.009281,24.1150241 C12.2670395,25.4079488 10.9383359,26.0254984 9.24864243,26.0254984 C7.18872869,26.0254984 5.24773367,25.647067 3.43145875,24.8905363 L6.31377803,24.2241784 C7.25769404,24.4250762 8.23567143,24.5254984 9.24864243,24.5254984 C10.5393035,24.5254984 11.609129,24.0282691 13.1153796,22.9104743 L14.275444,22.0545488 C15.5468065,21.1304903 15.8296113,21.016032 16.4798956,21.0019578 L16.4798956,21.0019578 Z M22.7770988,3.22208979 C24.4507223,4.8957133 24.4507566,7.60916079 22.7771889,9.28281324 L21.741655,10.3184475 C22.8936263,11.7199657 22.8521526,13.2053774 21.7811031,14.279556 L18.7800727,17.2805874 L18.7800727,17.2805874 C18.4870374,17.5733384 18.0121637,17.573108 17.7194126,17.2800727 C17.4266616,16.9870374 17.426892,16.5121637 17.7199273,16.2194126 L20.7188969,13.220444 C21.2039571,12.7339668 21.2600021,12.1299983 20.678941,11.3818945 L10.0845437,21.9761011 C9.78635459,22.2743053 9.41036117,22.482705 8.99944703,22.5775313 L2.91864463,23.9807934 C2.37859061,24.1054212 1.89457875,23.6214094 2.0192066,23.0813554 L3.42247794,17.0005129 C3.51729557,16.5896365 3.72566589,16.2136736 4.0238276,15.9154968 L16.7165019,3.22217992 C18.3900415,1.54855555 21.1034349,1.54851059 22.7770988,3.22208979 Z M17.7771889,4.28281324 L5.08451462,16.9761302 C4.98512738,17.0755224 4.91567061,17.2008434 4.88406473,17.3378022 L3.7506248,22.2493752 L8.66215777,21.1159445 C8.79912915,21.0843357 8.92446029,21.0148692 9.02385665,20.9154678 L21.7165019,8.22217992 C22.8043063,7.13432049 22.8042862,5.37060478 21.7164588,4.2827701 C20.6285914,3.19496507 18.8649506,3.19499653 17.7771889,4.28281324 Z</StreamGeometry>
<StreamGeometry x:Key="signed_regular">M9.83606496,2.03419109 C9.94858299,2.07246679 10.0585014,2.11799647 10.1651286,2.17049372 L11.4478626,2.8020395 C11.7960005,2.97344294 12.2039995,2.97344294 12.5521374,2.8020395 L13.8348714,2.17049372 C15.1974596,1.4996322 16.8458964,2.06038752 17.5167579,3.4229758 L17.5902423,3.5852986 L17.6530606,3.75203947 L18.1135202,5.10563967 C18.2384903,5.47301088 18.5269891,5.76150971 18.8943603,5.88647984 L20.2479605,6.34693944 C21.6858267,6.83606412 22.4549336,8.39819882 21.9658089,9.83606496 C21.9275332,9.94858299 21.8820035,10.0585014 21.8295063,10.1651286 L21.1979605,11.4478626 C21.0265571,11.7960005 21.0265571,12.2039995 21.1979605,12.5521374 L21.8295063,13.8348714 C22.5003678,15.1974596 21.9396125,16.8458964 20.5770242,17.5167579 C20.4703969,17.5692552 20.3604786,17.6147849 20.2479605,17.6530606 L18.8943603,18.1135202 C18.5269891,18.2384903 18.2384903,18.5269891 18.1135202,18.8943603 L17.6530606,20.2479605 C17.1639359,21.6858267 15.6018012,22.4549336 14.163935,21.9658089 C14.051417,21.9275332 13.9414986,21.8820035 13.8348714,21.8295063 L12.5521374,21.1979605 C12.2039995,21.0265571 11.7960005,21.0265571 11.4478626,21.1979605 L10.1651286,21.8295063 C8.80254036,22.5003678 7.1541036,21.9396125 6.48324207,20.5770242 C6.43074483,20.4703969 6.38521515,20.3604786 6.34693944,20.2479605 L5.88647984,18.8943603 C5.76150971,18.5269891 5.47301088,18.2384903 5.10563967,18.1135202 L3.75203947,17.6530606 C2.31417333,17.1639359 1.54506641,15.6018012 2.03419109,14.163935 C2.07246679,14.051417 2.11799647,13.9414986 2.17049372,13.8348714 L2.8020395,12.5521374 C2.97344294,12.2039995 2.97344294,11.7960005 2.8020395,11.4478626 L2.17049372,10.1651286 C1.4996322,8.80254036 2.06038752,7.1541036 3.4229758,6.48324207 C3.52960307,6.43074483 3.63952144,6.38521515 3.75203947,6.34693944 L5.10563967,5.88647984 C5.47301088,5.76150971 5.76150971,5.47301088 5.88647984,5.10563967 L6.34693944,3.75203947 C6.83606412,2.31417333 8.39819882,1.54506641 9.83606496,2.03419109 Z M7.76702323,4.23511505 L7.30656364,5.58871525 C7.03162935,6.39693191 6.39693191,7.03162935 5.58871525,7.30656364 L4.23511505,7.76702323 C4.1839705,7.78442128 4.1340076,7.80511659 4.08554066,7.82897898 C3.46618235,8.13391603 3.21129357,8.88320547 3.51623062,9.50256378 L4.1477764,10.7852978 C4.52486398,11.5512011 4.52486398,12.4487989 4.1477764,13.2147022 L3.51623062,14.4974362 C3.49236824,14.5459032 3.47167293,14.5958661 3.45427488,14.6470106 C3.23194548,15.3005861 3.58153953,16.0106474 4.23511505,16.2329768 L5.58871525,16.6934364 C6.39693191,16.9683707 7.03162935,17.6030681 7.30656364,18.4112847 L7.76702323,19.7648849 C7.78442128,19.8160295 7.80511659,19.8659924 7.82897898,19.9144593 C8.13391603,20.5338176 8.88320547,20.7887064 9.50256378,20.4837694 L10.7852978,19.8522236 C11.5512011,19.475136 12.4487989,19.475136 13.2147022,19.8522236 L14.4974362,20.4837694 C14.5459032,20.5076318 14.5958661,20.5283271 14.6470106,20.5457251 C15.3005861,20.7680545 16.0106474,20.4184605 16.2329768,19.7648849 L16.6934364,18.4112847 C16.9683707,17.6030681 17.6030681,16.9683707 18.4112847,16.6934364 L19.7648849,16.2329768 C19.8160295,16.2155787 19.8659924,16.1948834 19.9144593,16.171021 C20.5338176,15.866084 20.7887064,15.1167945 20.4837694,14.4974362 L19.8522236,13.2147022 C19.475136,12.4487989 19.475136,11.5512011 19.8522236,10.7852978 L20.4837694,9.50256378 C20.5076318,9.45409684 20.5283271,9.40413394 20.5457251,9.35298938 C20.7680545,8.69941386 20.4184605,7.98935263 19.7648849,7.76702323 L18.4112847,7.30656364 C17.6030681,7.03162935 16.9683707,6.39693191 16.6934364,5.58871525 L16.2329768,4.23511505 L16.204423,4.15932375 L16.171021,4.08554066 L16.1087783,3.9737298 C15.7729303,3.43650807 15.0780846,3.23035213 14.4974362,3.51623062 L13.2147022,4.1477764 C12.4487989,4.52486398 11.5512011,4.52486398 10.7852978,4.1477764 L9.50256378,3.51623062 C9.45409684,3.49236824 9.40413394,3.47167293 9.35298938,3.45427488 C8.69941386,3.23194548 7.98935263,3.58153953 7.76702323,4.23511505 Z M10.0503988,14.3889411 L15.4696699,8.96966991 C15.7625631,8.6767767 16.2374369,8.6767767 16.5303301,8.96966991 C16.7965966,9.23593648 16.8208027,9.65260016 16.6029482,9.94621165 L16.5303301,10.0303301 L10.5303301,16.0303301 C10.2444669,16.3161932 9.79016317,16.3204881 9.49896014,16.0582536 L9.42383404,15.9801383 L6.92383404,12.9801383 C6.65866098,12.6619306 6.70165403,12.1890071 7.0198617,11.923834 C7.3091414,11.6827676 7.72628545,11.6963839 7.99896752,11.939926 L8.07616596,12.0198617 L10.0503988,14.3889411 L15.4696699,8.96966991 L10.0503988,14.3889411 Z</StreamGeometry>
<StreamGeometry x:Key="edit_off_regular">M8.93944 10.0001L2.21979 3.28027C1.9269 2.98737 1.9269 2.5125 2.2198 2.21961C2.51269 1.92672 2.98757 1.92672 3.28046 2.21962L21.7802 20.7198C22.0731 21.0127 22.0731 21.4875 21.7802 21.7804C21.4873 22.0733 21.0125 22.0733 20.7196 21.7804L14 15.0608L9.0621 19.9987C8.78522 20.2756 8.44089 20.4754 8.06312 20.5784L2.94743 21.9736C2.38756 22.1263 1.87383 21.6126 2.02652 21.0527L3.42171 15.937C3.52474 15.5593 3.72456 15.2149 4.00144 14.9381L8.93944 10.0001ZM12.9392 13.9999L10.0001 11.0607L5.0621 15.9987C4.96981 16.091 4.9032 16.2058 4.86886 16.3317L3.81901 20.1811L7.66845 19.1313C7.79437 19.097 7.90915 19.0303 8.00144 18.9381L12.9392 13.9999Z M17.9393 8.99963L15.0598 11.8793L16.1207 12.9401L21.0304 8.03039C22.4279 6.63293 22.4279 4.36719 21.0304 2.96973C19.633 1.57227 17.3672 1.57227 15.9698 2.96973L11.0601 7.87943L12.1207 8.94013L15.0003 6.06063L17.9393 8.99963ZM17.0304 4.03039C17.8421 3.21871 19.1581 3.21871 19.9698 4.03039C20.7814 4.84206 20.7814 6.15805 19.9698 6.96973L18.9993 7.93963L16.0603 4.99963L17.0304 4.03039Z</StreamGeometry>
<StreamGeometry x:Key="text_edit_style_regular">M20.0624471,8.44531708 C21.3187966,9.70246962 21.3181456,11.7400656 20.060993,12.9964151 L12.9378099,20.1075964 C12.6748336,20.3701297 12.3509291,20.5634444 11.9950254,20.6702751 L7.7020125,21.9588974 C7.17304403,22.1176765 6.61551448,21.8175787 6.4567354,21.2886102 C6.39849549,21.0945854 6.40055641,20.8874478 6.4626453,20.6946202 L7.82404878,16.466551 C7.93368607,16.1260538 8.12292759,15.8166043 8.37607629,15.5638705 L15.5089127,8.44272265 C16.767237,7.18646041 18.8055552,7.18762176 20.0624471,8.44531708 Z M16.5687028,9.50425223 L9.43586633,16.6254001 C9.35148343,16.7096447 9.28840293,16.8127945 9.25185716,16.9262936 L8.18207614,20.2486798 L11.563783,19.2336018 C11.6824175,19.1979916 11.7903857,19.1335534 11.8780445,19.0460423 L19.0000352,11.936052 C19.6718508,11.2646659 19.6721983,10.1768173 19.0014481,9.50563832 C18.3299482,8.83370918 17.2409679,8.83308872 16.5687028,9.50425223 Z M8.1508398,2.36975012 L8.20132289,2.47486675 L11.4537996,10.724 L10.2967996,11.879 L9.5557996,10 L5.4427996,10 L4.44747776,12.5208817 C4.30788849,12.8739875 3.9301318,13.0620782 3.57143476,12.9736808 L3.47427411,12.9426336 C3.1211683,12.8030443 2.93307758,12.4252876 3.02147501,12.0665906 L3.05252224,11.9694299 L6.80613337,2.47427411 C7.0415216,1.87883471 7.84863764,1.84414583 8.1508398,2.36975012 Z M7.50274363,4.79226402 L6.0357996,8.5 L8.9637996,8.5 L7.50274363,4.79226402 Z</StreamGeometry>
<StreamGeometry x:Key="preview_link_regular">M4.52393 6.25C4.52393 5.83579 4.85971 5.5 5.27393 5.5H18.7297C19.1439 5.5 19.4797 5.83579 19.4797 6.25V9.75C19.4797 10.1642 19.1439 10.5 18.7297 10.5H5.27393C4.85971 10.5 4.52393 10.1642 4.52393 9.75V6.25ZM6.02393 7V9H17.9797V7H6.02393Z M14.2297 11.979C13.8155 11.979 13.4797 12.3148 13.4797 12.729V17.229C13.4797 17.6432 13.8155 17.979 14.2297 17.979H18.7297C19.1439 17.979 19.4797 17.6432 19.4797 17.229V12.729C19.4797 12.3148 19.1439 11.979 18.7297 11.979H14.2297ZM14.9797 16.479V13.479H17.9797V16.479H14.9797Z M4.52393 13.25C4.52393 12.8358 4.85971 12.5 5.27393 12.5H11.25C11.6642 12.5 12 12.8358 12 13.25C12 13.6642 11.6642 14 11.25 14H5.27393C4.85971 14 4.52393 13.6642 4.52393 13.25Z M5.27393 16C4.85971 16 4.52393 16.3358 4.52393 16.75C4.52393 17.1642 4.85971 17.5 5.27393 17.5H11.25C11.6642 17.5 12 17.1642 12 16.75C12 16.3358 11.6642 16 11.25 16H5.27393Z M2 5.75C2 4.23122 3.23122 3 4.75 3H19.25C20.7688 3 22 4.23122 22 5.75V18.25C22 19.7688 20.7688 21 19.25 21H4.75C3.23122 21 2 19.7688 2 18.25V5.75ZM4.75 4.5C4.05964 4.5 3.5 5.05964 3.5 5.75V18.25C3.5 18.9404 4.05964 19.5 4.75 19.5H19.25C19.9404 19.5 20.5 18.9404 20.5 18.25V5.75C20.5 5.05964 19.9404 4.5 19.25 4.5H4.75Z</StreamGeometry>
<StreamGeometry x:Key="code_regular">M8.06561801,18.9432081 L14.565618,4.44320807 C14.7350545,4.06523433 15.1788182,3.8961815 15.5567919,4.06561801 C15.9032679,4.2209348 16.0741922,4.60676263 15.9697642,4.9611247 L15.934382,5.05679193 L9.43438199,19.5567919 C9.26494549,19.9347657 8.82118181,20.1038185 8.44320807,19.934382 C8.09673215,19.7790652 7.92580781,19.3932374 8.03023576,19.0388753 L8.06561801,18.9432081 L14.565618,4.44320807 L8.06561801,18.9432081 Z M2.21966991,11.4696699 L6.46966991,7.21966991 C6.76256313,6.9267767 7.23743687,6.9267767 7.53033009,7.21966991 C7.79659665,7.48593648 7.8208027,7.90260016 7.60294824,8.19621165 L7.53033009,8.28033009 L3.81066017,12 L7.53033009,15.7196699 C7.8232233,16.0125631 7.8232233,16.4874369 7.53033009,16.7803301 C7.26406352,17.0465966 6.84739984,17.0708027 6.55378835,16.8529482 L6.46966991,16.7803301 L2.21966991,12.5303301 C1.95340335,12.2640635 1.9291973,11.8473998 2.14705176,11.5537883 L2.21966991,11.4696699 L6.46966991,7.21966991 L2.21966991,11.4696699 Z M16.4696699,7.21966991 C16.7359365,6.95340335 17.1526002,6.9291973 17.4462117,7.14705176 L17.5303301,7.21966991 L21.7803301,11.4696699 C22.0465966,11.7359365 22.0708027,12.1526002 21.8529482,12.4462117 L21.7803301,12.5303301 L17.5303301,16.7803301 C17.2374369,17.0732233 16.7625631,17.0732233 16.4696699,16.7803301 C16.2034034,16.5140635 16.1791973,16.0973998 16.3970518,15.8037883 L16.4696699,15.7196699 L20.1893398,12 L16.4696699,8.28033009 C16.1767767,7.98743687 16.1767767,7.51256313 16.4696699,7.21966991 Z</StreamGeometry>
<StreamGeometry x:Key="open_regular">M7.25008054,4.49999913 L10.7494682,4.49999913 C11.1636818,4.49999913 11.4994682,4.83578644 11.4994682,5.25 C11.4994682,5.62969577 11.2173143,5.94349023 10.8512388,5.99315253 L10.7494682,5.99999913 L7.24972349,5.99999913 C6.07077742,5.99943864 5.10347879,6.90639393 5.00784424,8.06094921 L5.00026803,8.21986131 L5.00310465,16.7504962 C5.00341779,17.9413602 5.92883567,18.9158978 7.09964605,18.9947542 L7.25369622,18.9999045 L15.751762,18.9882338 C16.9414684,18.9865998 17.9144722,18.0618298 17.9934904,16.8921377 L17.9986716,16.738236 L17.9986716,13.2319436 C17.9986716,12.81773 18.334458,12.4819436 18.7486716,12.4819436 C19.1283674,12.4819436 19.4421626,12.7640975 19.491825,13.130173 L19.4986716,13.2319436 L19.4986716,16.738236 C19.4986716,18.7405488 17.9292489,20.3767194 15.9527826,20.4827708 L15.7538222,20.4882324 L7.25825518,20.499901 L7.05493071,20.4947588 C5.14237343,20.3951844 3.60893529,18.8625525 3.50835508,16.9500479 L3.5031047,16.7508907 L3.50087004,8.2525319 L3.50527942,8.05003289 C3.60537339,6.13731798 5.13865446,4.60431851 7.05094826,4.50510482 L7.25008054,4.49999913 L10.7494682,4.49999913 L7.25008054,4.49999913 Z M13.748109,3.00129623 L20.3017795,3.0018036 L20.4013609,3.01557712 L20.4013609,3.01557712 L20.5021655,3.04376069 L20.5021655,3.04376069 L20.5589882,3.06786568 L20.5589882,3.06786568 C20.6122302,3.09104804 20.6633548,3.12146211 20.7110467,3.15867802 L20.7803898,3.22139044 L20.7803898,3.22139044 L20.8641342,3.31997258 L20.8641342,3.31997258 L20.9183108,3.41008637 L20.9183108,3.41008637 L20.9570021,3.50039784 L20.9570021,3.50039784 L20.9762122,3.56459327 L20.9762122,3.56459327 L20.9897783,3.62845344 L20.9897783,3.62845344 L20.9991402,3.72265407 L20.9991402,3.72265407 L20.9996358,10.2551867 C20.9996358,10.6694002 20.6638494,11.0051867 20.2496358,11.0051867 C19.86994,11.0051867 19.5561448,10.7230328 19.5064824,10.3569572 L19.4996358,10.2551867 L19.49887,5.56129623 L12.2796385,12.7845179 C12.0134324,13.0508449 11.5967743,13.0751456 11.3031133,12.8573578 L11.2189784,12.7847587 C10.9526514,12.5185526 10.9283507,12.1018944 11.1461385,11.8082335 L11.2187376,11.7240986 L18.43687,4.50129623 L13.748109,4.50129623 C13.3684132,4.50129623 13.054618,4.21914235 13.0049556,3.85306678 L12.998109,3.75129623 C12.998109,3.37160046 13.2802629,3.05780527 13.6463384,3.00814284 L13.748109,3.00129623 Z</StreamGeometry>
<StreamGeometry x:Key="notepad_regular">M8 10.25C8 9.83579 8.33579 9.5 8.75 9.5H18.75C19.1642 9.5 19.5 9.83579 19.5 10.25C19.5 10.6642 19.1642 11 18.75 11H8.75C8.33579 11 8 10.6642 8 10.25Z M8 14.75C8 14.3358 8.33579 14 8.75 14H18.75C19.1642 14 19.5 14.3358 19.5 14.75C19.5 15.1642 19.1642 15.5 18.75 15.5H8.75C8.33579 15.5 8 15.1642 8 14.75Z M8.75 18.5C8.33579 18.5 8 18.8358 8 19.25C8 19.6642 8.33579 20 8.75 20H13.25C13.6642 20 14 19.6642 14 19.25C14 18.8358 13.6642 18.5 13.25 18.5H8.75Z M14 2C14.4142 2 14.75 2.33579 14.75 2.75V4H18.5V2.75C18.5 2.33579 18.8358 2 19.25 2C19.6642 2 20 2.33579 20 2.75V4H20.75C21.9926 4 23 5.00736 23 6.25V19.2459C23 19.4448 22.921 19.6356 22.7803 19.7762L17.2762 25.2803C17.1355 25.421 16.9447 25.5 16.7458 25.5H6.75C5.50736 25.5 4.5 24.4926 4.5 23.25V6.25C4.5 5.00736 5.50736 4 6.75 4H8V2.75C8 2.33579 8.33579 2 8.75 2C9.16421 2 9.5 2.33579 9.5 2.75V4H13.25V2.75C13.25 2.33579 13.5858 2 14 2ZM6 6.25V23.25C6 23.6642 6.33579 24 6.75 24H15.9958V20.7459C15.9958 19.5032 17.0032 18.4959 18.2458 18.4959H21.5V6.25C21.5 5.83579 21.1642 5.5 20.75 5.5H6.75C6.33579 5.5 6 5.83579 6 6.25ZM18.2458 19.9959C17.8316 19.9959 17.4958 20.3317 17.4958 20.7459V22.9394L20.4393 19.9959H18.2458Z</StreamGeometry>
<StreamGeometry x:Key="send_regular">M3.78963301,2.77233335 L24.8609339,12.8499121 C25.4837277,13.1477699 25.7471402,13.8941055 25.4492823,14.5168992 C25.326107,14.7744476 25.1184823,14.9820723 24.8609339,15.1052476 L3.78963301,25.1828263 C3.16683929,25.4806842 2.42050372,25.2172716 2.12264586,24.5944779 C1.99321184,24.3238431 1.96542524,24.015685 2.04435886,23.7262618 L4.7030903,13.9775798 L2.04435886,4.22889788 C1.8627142,3.56286745 2.25538645,2.87569101 2.92141688,2.69404635 C3.21084015,2.61511273 3.51899823,2.64289932 3.78963301,2.77233335 Z M3.63522914,4.36121177 L6.058,13.249 L17,13.25 C17.3796958,13.25 17.693491,13.5321539 17.7431534,13.8982294 L17.75,14 C17.75,14.3796958 17.4678461,14.693491 17.1017706,14.7431534 L17,14.75 L6.046,14.749 L3.63522914,23.5939479 L23.7421805,13.9775798 L3.63522914,4.36121177 Z</StreamGeometry>
<StreamGeometry x:Key="arrow_sync_circle_regular">M12,2 C17.5228,2 22,6.47715 22,12 C22,17.5228 17.5228,22 12,22 C6.47715,22 2,17.5228 2,12 C2,6.47715 6.47715,2 12,2 Z M12,3.5 C7.30558,3.5 3.5,7.30558 3.5,12 C3.5,16.6944 7.30558,20.5 12,20.5 C16.6944,20.5 20.5,16.6944 20.5,12 C20.5,7.30558 16.6944,3.5 12,3.5 Z M16.75,12 C17.1296833,12 17.4434889,12.2821653 17.4931531,12.6482323 L17.5,12.75 L17.5,15.75 C17.5,16.1642 17.1642,16.5 16.75,16.5 C16.3703167,16.5 16.0565111,16.2178347 16.0068469,15.8517677 L16,15.75 L16,15 C15.0881,16.2143 13.6362,17 11.9999,17 C10.4748,17 9.09587,16.316 8.17857,15.237 C7.91028,14.9214 7.94862,14.4481 8.2642,14.1798 C8.57979,13.9115 9.05311,13.9499 9.3214,14.2655 C9.96322,15.0204 10.9293,15.5 11.9999,15.5 C13.32553,15.5 14.4803167,14.7625672 15.0742404,13.6746351 L15.1633,13.5 L14,13.5 C13.5858,13.5 13.25,13.1642 13.25,12.75 C13.25,12.3703167 13.5321653,12.0565111 13.8982323,12.0068469 L14,12 L16.75,12 Z M11.9999,7 C13.5368,7 14.9041,7.66036 15.8268,8.77062 C16.0915,9.08918 16.0479,9.56205 15.7294,9.8268 C15.4108,10.0916 14.9379,10.0479 14.6732,9.72938 C14.0368,8.96361 13.093,8.5 11.9999,8.5 C10.5754318,8.5 9.34895806,9.35140335 8.80281957,10.5730172 L8.72948,10.75 L10,10.75 C10.4142,10.75 10.75,11.0858 10.75,11.5 C10.75,11.8796833 10.4678347,12.1934889 10.1017677,12.2431531 L10,12.25 L7.25,12.25 C6.8703075,12.25 6.55650958,11.9678347 6.50684668,11.6017677 L6.5,11.5 L6.5,8.25 C6.5,7.83579 6.83579,7.5 7.25,7.5 C7.6296925,7.5 7.94349042,7.78215688 7.99315332,8.14823019 L8,8.25 L8,8.99955 C8.9121,7.78531 10.364,7 11.9999,7 Z</StreamGeometry>
<StreamGeometry x:Key="organization_regular">M14 1.99774C11.6528 1.99774 9.75 3.90053 9.75 6.24774C9.75 8.33903 11.2605 10.0775 13.25 10.4318V13.5H8.75C7.50736 13.5 6.5 14.5074 6.5 15.75V17.566C4.51049 17.9202 3 19.6587 3 21.75C3 24.0972 4.90279 26 7.25 26C9.59721 26 11.5 24.0972 11.5 21.75C11.5 19.6587 9.98951 17.9202 8 17.566V15.75C8 15.3358 8.33579 15 8.75 15H19.25C19.6642 15 20 15.3358 20 15.75V17.566C18.0105 17.9202 16.5 19.6587 16.5 21.75C16.5 24.0972 18.4028 26 20.75 26C23.0972 26 25 24.0972 25 21.75C25 19.6587 23.4895 17.9202 21.5 17.566V15.75C21.5 14.5074 20.4926 13.5 19.25 13.5H14.75V10.4318C16.7395 10.0775 18.25 8.33904 18.25 6.24774C18.25 3.90053 16.3472 1.99774 14 1.99774ZM11.25 6.24774C11.25 4.72896 12.4812 3.49774 14 3.49774C15.5188 3.49774 16.75 4.72896 16.75 6.24774C16.75 7.76652 15.5188 8.99774 14 8.99774C12.4812 8.99774 11.25 7.76652 11.25 6.24774ZM4.5 21.75C4.5 20.2312 5.73122 19 7.25 19C8.76878 19 10 20.2312 10 21.75C10 23.2688 8.76878 24.5 7.25 24.5C5.73122 24.5 4.5 23.2688 4.5 21.75ZM20.75 19C22.2688 19 23.5 20.2312 23.5 21.75C23.5 23.2688 22.2688 24.5 20.75 24.5C19.2312 24.5 18 23.2688 18 21.75C18 20.2312 19.2312 19 20.75 19Z</StreamGeometry>
<StreamGeometry x:Key="eye_tracking_off_regular">M3.28034 2.21968C2.98745 1.92678 2.51257 1.92677 2.21968 2.21966C1.92678 2.51255 1.92677 2.98743 2.21966 3.28032L2.3466 3.40726C2.12399 3.80438 1.99707 4.26237 1.99707 4.75001V8.25234L2.00392 8.35411C2.05358 8.72019 2.36737 9.00234 2.74707 9.00234C3.16128 9.00234 3.49707 8.66656 3.49707 8.25234V4.75001L3.50352 4.6222C3.50528 4.60488 3.5074 4.58765 3.50986 4.57054L7.1851 8.24586C6.87013 8.47849 6.5908 8.72357 6.34469 8.96968C5.79018 9.52418 5.40882 10.0786 5.16468 10.4971C5.04233 10.7068 4.95353 10.884 4.89398 11.0123C4.86418 11.0765 4.84162 11.1286 4.82577 11.1666C4.81785 11.1856 4.8116 11.2012 4.80696 11.2129L4.80118 11.2277C4.79905 11.2333 4.63944 11.9783 5.23667 12.2023C5.62356 12.3473 6.05472 12.1521 6.2012 11.7662L6.202 11.7641L6.21039 11.7435C6.21896 11.723 6.23351 11.6892 6.25449 11.644C6.2965 11.5535 6.36395 11.4182 6.46035 11.2529C6.65371 10.9214 6.95985 10.4758 7.40535 10.0303C7.64639 9.78929 7.92961 9.54664 8.26059 9.32137L9.75443 10.8152C8.98764 11.4573 8.5 12.4217 8.5 13.5C8.5 15.433 10.067 17 12 17C13.0783 17 14.0427 16.5124 14.6847 15.7456L19.4283 20.4893C19.3691 20.4979 19.3086 20.5023 19.2471 20.5023H15.7471L15.6453 20.5092C15.2792 20.5589 14.9971 20.8726 14.9971 21.2523C14.9971 21.6666 15.3329 22.0023 15.7471 22.0023H19.2471L19.4146 21.9973C19.8401 21.9718 20.2395 21.8495 20.5911 21.6521L20.7194 21.7805C21.0123 22.0734 21.4872 22.0734 21.7801 21.7805C22.073 21.4876 22.073 21.0127 21.7801 20.7198L3.28034 2.21968ZM13.6167 14.6776C13.253 15.1761 12.6643 15.5 12 15.5C10.8954 15.5 10 14.6046 10 13.5C10 12.8357 10.3239 12.247 10.8224 11.8833L13.6167 14.6776Z M11.4501 8.26814L10.1217 6.93974C10.6928 6.81889 11.3177 6.75001 12 6.75001C14.7257 6.75001 16.5348 7.84916 17.6553 8.96968C18.2099 9.52418 18.5912 10.0786 18.8354 10.4971C18.9577 10.7068 19.0465 10.884 19.1061 11.0123C19.1359 11.0765 19.1584 11.1286 19.1743 11.1666C19.1822 11.1856 19.1884 11.2012 19.1931 11.2129L19.1988 11.2277L19.2008 11.2329L19.2016 11.235L19.2023 11.2367C19.3477 11.6245 19.1512 12.0568 18.7634 12.2023C18.3769 12.3472 17.9472 12.1443 17.798 11.7642L17.7896 11.7435C17.7896 11.7435 17.7665 11.6892 17.7455 11.644C17.7035 11.5535 17.6361 11.4182 17.5397 11.2529C17.3463 10.9214 17.0402 10.4758 16.5947 10.0303C15.7152 9.15086 14.2743 8.25001 12 8.25001C11.811 8.25001 11.6278 8.25623 11.4501 8.26814Z M21.9971 18.8153L20.4971 17.3153V15.75C20.4971 15.3358 20.8329 15 21.2471 15C21.6268 15 21.9406 15.2822 21.9902 15.6482L21.9971 15.75V18.8153Z M6.68208 3.50001L5.18211 2.00001H8.24707C8.66128 2.00001 8.99707 2.3358 8.99707 2.75001C8.99707 3.1297 8.71492 3.4435 8.34884 3.49316L8.24707 3.50001H6.68208Z M2.74707 15C3.12677 15 3.44056 15.2822 3.49022 15.6482L3.49707 15.75V19.2523L3.50352 19.3801C3.56327 19.9684 4.03097 20.4361 4.61927 20.4959L4.74707 20.5023H8.24707L8.34884 20.5092C8.71492 20.5589 8.99707 20.8726 8.99707 21.2523C8.99707 21.632 8.71492 21.9458 8.34884 21.9955L8.24707 22.0023H4.74707L4.57955 21.9973C3.19641 21.9142 2.08889 20.8088 2.0025 19.4265L1.99707 19.2523V15.75L2.00392 15.6482C2.05358 15.2822 2.36737 15 2.74707 15Z M19.2471 2.00001L19.4146 2.00503C20.7977 2.08814 21.9053 3.19358 21.9916 4.57584L21.9971 4.75001V8.25234L21.9902 8.35411C21.9406 8.72019 21.6268 9.00234 21.2471 9.00234C20.8674 9.00234 20.5536 8.72019 20.5039 8.35411L20.4971 8.25234V4.75001L20.4906 4.6222C20.4309 4.0339 19.9632 3.56621 19.3749 3.50646L19.2471 3.50001H15.7471L15.6453 3.49316C15.2792 3.4435 14.9971 3.1297 14.9971 2.75001C14.9971 2.37031 15.2792 2.05652 15.6453 2.00686L15.7471 2.00001H19.2471Z</StreamGeometry>
<StreamGeometry x:Key="eye_tracking_regular">M8.24707 2C8.66128 2 8.99707 2.33579 8.99707 2.75C8.99707 3.1297 8.71492 3.44349 8.34884 3.49315L8.24707 3.5H4.74707C4.09986 3.5 3.56754 3.99187 3.50352 4.62219L3.49707 4.75V8.25234C3.49707 8.66655 3.16128 9.00234 2.74707 9.00234C2.36737 9.00234 2.05358 8.72018 2.00392 8.35411L1.99707 8.25234V4.75C1.99707 3.28747 3.13877 2.0916 4.57955 2.00502L4.74707 2H8.24707Z M3.49022 15.6482C3.44056 15.2822 3.12677 15 2.74707 15C2.36737 15 2.05358 15.2822 2.00392 15.6482L1.99707 15.75V19.2523L2.0025 19.4265C2.08889 20.8088 3.19641 21.9142 4.57955 21.9973L4.74707 22.0023H8.24707L8.34884 21.9955C8.71492 21.9458 8.99707 21.632 8.99707 21.2523C8.99707 20.8726 8.71492 20.5588 8.34884 20.5092L8.24707 20.5023H4.74707L4.61927 20.4959C4.03097 20.4361 3.56327 19.9684 3.50352 19.3801L3.49707 19.2523V15.75L3.49022 15.6482Z M21.9902 15.6482C21.9406 15.2822 21.6268 15 21.2471 15C20.8329 15 20.4971 15.3358 20.4971 15.75V19.2523L20.4906 19.3801C20.4266 20.0105 19.8943 20.5023 19.2471 20.5023H15.7471L15.6453 20.5092C15.2792 20.5588 14.9971 20.8726 14.9971 21.2523C14.9971 21.6665 15.3329 22.0023 15.7471 22.0023H19.2471L19.4146 21.9973C20.8554 21.9107 21.9971 20.7149 21.9971 19.2523V15.75L21.9902 15.6482Z M19.4146 2.00502L19.2471 2H15.7471L15.6453 2.00685C15.2792 2.05651 14.9971 2.3703 14.9971 2.75C14.9971 3.1297 15.2792 3.44349 15.6453 3.49315L15.7471 3.5H19.2471L19.3749 3.50645C19.9632 3.5662 20.4309 4.0339 20.4906 4.62219L20.4971 4.75V8.25234L20.5039 8.35411C20.5536 8.72018 20.8674 9.00234 21.2471 9.00234C21.6268 9.00234 21.9406 8.72018 21.9902 8.35411L21.9971 8.25234V4.75L21.9916 4.57583C21.9053 3.19357 20.7977 2.08813 19.4146 2.00502Z M6.202 11.764L6.21039 11.7435C6.21896 11.723 6.23351 11.6891 6.25449 11.644C6.2965 11.5535 6.36395 11.4182 6.46035 11.2529C6.65371 10.9214 6.95985 10.4758 7.40535 10.0303C8.28483 9.15085 9.7257 8.25 12 8.25C14.2743 8.25 15.7152 9.15085 16.5947 10.0303C17.0402 10.4758 17.3463 10.9214 17.5397 11.2529C17.6361 11.4182 17.7035 11.5535 17.7455 11.644C17.7665 11.6891 17.7896 11.7435 17.7896 11.7435L17.798 11.7642C17.9472 12.1443 18.3769 12.3472 18.7634 12.2022C19.1512 12.0568 19.3477 11.6245 19.2023 11.2367L19.2016 11.235L19.2008 11.2329L19.1988 11.2277L19.1931 11.2129C19.1884 11.2011 19.1822 11.1856 19.1743 11.1666C19.1584 11.1286 19.1359 11.0765 19.1061 11.0123C19.0465 10.884 18.9577 10.7068 18.8354 10.4971C18.5912 10.0786 18.2099 9.52418 17.6553 8.96967C16.5348 7.84915 14.7257 6.75 12 6.75C9.27433 6.75 7.4652 7.84915 6.34469 8.96967C5.79018 9.52418 5.40882 10.0786 5.16468 10.4971C5.04233 10.7068 4.95353 10.884 4.89398 11.0123C4.86418 11.0765 4.84162 11.1286 4.82577 11.1666C4.81785 11.1856 4.8116 11.2011 4.80696 11.2129L4.80118 11.2277C4.79905 11.2333 4.63944 11.9783 5.23667 12.2022C5.62356 12.3473 6.05472 12.1521 6.2012 11.7662L6.202 11.764Z M12 10C10.067 10 8.5 11.567 8.5 13.5C8.5 15.433 10.067 17 12 17C13.933 17 15.5 15.433 15.5 13.5C15.5 11.567 13.933 10 12 10ZM10 13.5C10 12.3954 10.8954 11.5 12 11.5C13.1046 11.5 14 12.3954 14 13.5C14 14.6046 13.1046 15.5 12 15.5C10.8954 15.5 10 14.6046 10 13.5Z</StreamGeometry>
<StreamGeometry x:Key="play_regular">M13.7501344,8.41212026 L38.1671892,21.1169293 C39.7594652,21.9454306 40.3786269,23.9078584 39.5501255,25.5001344 C39.2420737,26.0921715 38.7592263,26.5750189 38.1671892,26.8830707 L13.7501344,39.5878797 C12.1578584,40.4163811 10.1954306,39.7972194 9.36692926,38.2049434 C9.12586301,37.7416442 9,37.2270724 9,36.704809 L9,11.295191 C9,9.50026556 10.4550746,8.045191 12.25,8.045191 C12.6976544,8.045191 13.1396577,8.13766178 13.5485655,8.31589049 L13.7501344,8.41212026 Z M12.5961849,10.629867 L12.4856981,10.5831892 C12.4099075,10.5581 12.3303482,10.545191 12.25,10.545191 C11.8357864,10.545191 11.5,10.8809774 11.5,11.295191 L11.5,36.704809 C11.5,36.8253313 11.5290453,36.9440787 11.584676,37.0509939 C11.7758686,37.4184422 12.2287365,37.5613256 12.5961849,37.370133 L37.0132397,24.665324 C37.1498636,24.5942351 37.2612899,24.4828088 37.3323788,24.3461849 C37.5235714,23.9787365 37.380688,23.5258686 37.0132397,23.334676 L12.5961849,10.629867 Z</StreamGeometry>
<StreamGeometry x:Key="form_new_regular">M6 11.25C6 8.35051 8.3505 6 11.25 6H36.75C39.6495 6 42 8.3505 42 11.25V24.0436C41.2196 23.544 40.3823 23.1255 39.5 22.7999V11.25C39.5 9.73122 38.2688 8.5 36.75 8.5H11.25C9.73122 8.5 8.5 9.73122 8.5 11.25V36.75C8.5 38.2688 9.73122 39.5 11.25 39.5H22.7999C23.1255 40.3823 23.544 41.2196 24.0436 42H11.25C8.35051 42 6 39.6495 6 36.75V11.25Z M10 21.5C10 19.0147 12.0147 17 14.5 17C16.9853 17 19 19.0147 19 21.5C19 23.9853 16.9853 26 14.5 26C12.0147 26 10 23.9853 10 21.5ZM14.5 19.5C13.3954 19.5 12.5 20.3954 12.5 21.5C12.5 22.6046 13.3954 23.5 14.5 23.5C15.6046 23.5 16.5 22.6046 16.5 21.5C16.5 20.3954 15.6046 19.5 14.5 19.5Z M14.5 29C12.0147 29 10 31.0147 10 33.5C10 35.9853 12.0147 38 14.5 38C16.9853 38 19 35.9853 19 33.5C19 31.0147 16.9853 29 14.5 29ZM12.5 33.5C12.5 32.3954 13.3954 31.5 14.5 31.5C15.6046 31.5 16.5 32.3954 16.5 33.5C16.5 34.6046 15.6046 35.5 14.5 35.5C13.3954 35.5 12.5 34.6046 12.5 33.5Z M21.0012 20.25C21.0012 19.5596 21.5609 19 22.2512 19H36.75C37.4404 19 38 19.5596 38 20.25C38 20.9404 37.4404 21.5 36.75 21.5H22.2512C21.5609 21.5 21.0012 20.9404 21.0012 20.25Z M11.2632 11.0952C10.5728 11.0952 10.0132 11.6549 10.0132 12.3452C10.0132 13.0356 10.5728 13.5952 11.2632 13.5952H36.7298C37.4202 13.5952 37.9798 13.0356 37.9798 12.3452C37.9798 11.6549 37.4202 11.0952 36.7298 11.0952H11.2632Z M46 35C46 41.0751 41.0751 46 35 46C28.9249 46 24 41.0751 24 35C24 28.9249 28.9249 24 35 24C41.0751 24 46 28.9249 46 35ZM36 28C36 27.4477 35.5523 27 35 27C34.4477 27 34 27.4477 34 28V34H28C27.4477 34 27 34.4477 27 35C27 35.5523 27.4477 36 28 36H34V42C34 42.5523 34.4477 43 35 43C35.5523 43 36 42.5523 36 42V36H42C42.5523 36 43 35.5523 43 35C43 34.4477 42.5523 34 42 34H36V28Z</StreamGeometry>
<StreamGeometry x:Key="attach_regular">M11.7715948,3.74348899 C14.113054,1.39990252 17.9120439,1.39990252 20.2551897,3.74304827 C22.5382548,6.02611336 22.5967949,9.69132107 20.4308101,12.0452653 L20.2426506,12.2426307 L11.4426304,21.0408404 L11.4426304,21.0408404 L11.4060613,21.0710739 C9.94482388,22.3878538 7.69082246,22.3431052 6.28344814,20.9357309 C4.96443071,19.6167134 4.84231478,17.5540367 5.91710035,16.0973219 C5.94044402,16.0519637 5.96869088,16.0082157 6.00190455,15.9670689 L6.0554581,15.9074233 L6.14236585,15.819689 L6.28344814,15.671807 L6.28636585,15.674689 L13.7221045,8.22037508 C13.9880171,7.95375494 14.4046482,7.92899525 14.6985489,8.14645937 L14.7827638,8.21896569 C15.0493839,8.4848782 15.0741436,8.90150935 14.8566795,9.19541007 L14.7841732,9.27962492 L7.18955772,16.8927175 C6.471921,17.7683146 6.52180093,19.0625849 7.33919752,19.8799815 C8.16826244,20.7090464 9.48791296,20.7485257 10.3637003,19.9984193 L19.1963769,11.1679575 L19.1963769,11.1679575 C20.9518888,9.41031016 20.9518888,6.56106776 19.1945295,4.80370845 C17.4920877,3.10126661 14.7649391,3.0480653 12.9984531,4.64410452 L12.8305685,4.80370845 L12.8180195,4.81801948 L3.28169594,14.354343 C2.98880272,14.6472363 2.51392898,14.6472363 2.22103577,14.354343 C1.9547692,14.0880765 1.93056315,13.6714128 2.14841761,13.3778013 L2.22103577,13.2936829 L11.7699083,3.74304827 L11.7715948,3.74348899 Z</StreamGeometry>
<StreamGeometry x:Key="share_android_regular">M17,2.49823144 C18.9339734,2.49823144 20.5017686,4.06602662 20.5017686,6 C20.5017686,7.93397338 18.9339734,9.50176856 17,9.50176856 C15.9700352,9.50176856 15.0439275,9.0571034 14.4031791,8.34927521 L9.84455071,10.9536986 C9.94786118,11.284101 10.0035371,11.6355486 10.0035371,12 C10.0035371,12.3644514 9.94786118,12.715899 9.84455071,13.0463014 L14.4022538,15.6517469 C15.0430358,14.9433244 15.9695393,14.4982314 17,14.4982314 C18.9339734,14.4982314 20.5017686,16.0660262 20.5017686,17.9999996 C20.5017686,19.9339729 18.9339734,21.5017681 17,21.5017681 C15.0660266,21.5017681 13.4982314,19.9339729 13.4982314,17.9999996 C13.4982314,17.6355481 13.5539074,17.2841005 13.6572179,16.9536982 L9.09951477,14.3482526 C8.45873279,15.0566751 7.53222925,15.5017686 6.50176856,15.5017686 C4.56779519,15.5017686 3,13.9339734 3,12 C3,10.0660266 4.56779519,8.49823144 6.50176856,8.49823144 C7.53173336,8.49823144 8.45784104,8.9428966 9.09858948,9.65072479 L13.6572179,7.04630139 C13.5539074,6.71589903 13.4982314,6.36445142 13.4982314,6 C13.4982314,4.06602662 15.0660266,2.49823144 17,2.49823144 Z M17,15.998231 C15.8944537,15.998231 14.9982314,16.8944533 14.9982314,17.9999996 C14.9982314,19.1055458 15.8944537,20.0017681 17,20.0017681 C18.1055463,20.0017681 19.0017686,19.1055458 19.0017686,17.9999996 C19.0017686,16.8944533 18.1055463,15.998231 17,15.998231 Z M6.50176856,9.99823144 C5.39622231,9.99823144 4.5,10.8944537 4.5,12 C4.5,13.1055463 5.39622231,14.0017686 6.50176856,14.0017686 C7.60731481,14.0017686 8.50353713,13.1055463 8.50353713,12 C8.50353713,10.8944537 7.60731481,9.99823144 6.50176856,9.99823144 Z M17,3.99823144 C15.8944537,3.99823144 14.9982314,4.89445375 14.9982314,6 C14.9982314,7.10554625 15.8944537,8.00176856 17,8.00176856 C18.1055463,8.00176856 19.0017686,7.10554625 19.0017686,6 C19.0017686,4.89445375 18.1055463,3.99823144 17,3.99823144 Z</StreamGeometry>
<StreamGeometry x:Key="comment_edit_regular">M2 14.75C2 16.5449 3.45507 18 5.25 18H5.99921L6 20.7499C6 21.0196 6.08736 21.2822 6.24901 21.4984C6.6625 22.0512 7.44585 22.1642 7.99868 21.7507L10.1239 20.1608L10.5199 18.5768C10.5914 18.2911 10.6965 18.0162 10.8322 17.7578L7.49986 20.2506L7.49879 16.5H5.25C4.2835 16.5 3.5 15.7165 3.5 14.75V6.25C3.5 5.2835 4.2835 4.5 5.25 4.5H18.75C19.7165 4.5 20.5 5.2835 20.5 6.25V10.0946C21.0475 10.2288 21.5671 10.5054 22 10.9246V6.25C22 4.45507 20.5449 3 18.75 3H5.25C3.45507 3 2 4.45507 2 6.25V14.75Z M18.0979 11.6695L12.1955 17.5719C11.8513 17.916 11.6072 18.3472 11.4892 18.8194L11.0315 20.6501C10.8325 21.4462 11.5536 22.1674 12.3497 21.9683L14.1804 21.5106C14.6526 21.3926 15.0838 21.1485 15.4279 20.8043L21.3303 14.9019C22.223 14.0093 22.223 12.5621 21.3303 11.6695C20.4377 10.7768 18.9905 10.7768 18.0979 11.6695Z</StreamGeometry>
<StreamGeometry x:Key="delete_regular">M24,7.25 C27.1017853,7.25 29.629937,9.70601719 29.7458479,12.7794443 L29.75,13 L37,13 C37.6903559,13 38.25,13.5596441 38.25,14.25 C38.25,14.8972087 37.7581253,15.4295339 37.1278052,15.4935464 L37,15.5 L35.909,15.5 L34.2058308,38.0698451 C34.0385226,40.2866784 32.1910211,42 29.9678833,42 L18.0321167,42 C15.8089789,42 13.9614774,40.2866784 13.7941692,38.0698451 L12.09,15.5 L11,15.5 C10.3527913,15.5 9.8204661,15.0081253 9.75645361,14.3778052 L9.75,14.25 C9.75,13.6027913 10.2418747,13.0704661 10.8721948,13.0064536 L11,13 L18.25,13 C18.25,9.82436269 20.8243627,7.25 24,7.25 Z M33.4021054,15.5 L14.5978946,15.5 L16.2870795,37.8817009 C16.3559711,38.7945146 17.116707,39.5 18.0321167,39.5 L29.9678833,39.5 C30.883293,39.5 31.6440289,38.7945146 31.7129205,37.8817009 L33.4021054,15.5 Z M27.25,20.75 C27.8972087,20.75 28.4295339,21.2418747 28.4935464,21.8721948 L28.5,22 L28.5,33 C28.5,33.6903559 27.9403559,34.25 27.25,34.25 C26.6027913,34.25 26.0704661,33.7581253 26.0064536,33.1278052 L26,33 L26,22 C26,21.3096441 26.5596441,20.75 27.25,20.75 Z M20.75,20.75 C21.3972087,20.75 21.9295339,21.2418747 21.9935464,21.8721948 L22,22 L22,33 C22,33.6903559 21.4403559,34.25 20.75,34.25 C20.1027913,34.25 19.5704661,33.7581253 19.5064536,33.1278052 L19.5,33 L19.5,22 C19.5,21.3096441 20.0596441,20.75 20.75,20.75 Z M24,9.75 C22.2669685,9.75 20.8507541,11.1064548 20.7551448,12.8155761 L20.75,13 L27.25,13 C27.25,11.2050746 25.7949254,9.75 24,9.75 Z</StreamGeometry>
<StreamGeometry x:Key="chat_regular">M14.0038862,2.5 C20.3551608,2.5 25.5038862,7.64872538 25.5038862,14 C25.5038862,20.3512746 20.3551608,25.5 14.0038862,25.5 C12.0828262,25.5 10.2289934,25.0277557 8.57453454,24.1400553 L4.06949813,25.4927799 C3.40830889,25.6913248 2.71135661,25.3162775 2.51281166,24.6550883 C2.44236748,24.4204969 2.44239769,24.1703786 2.5128929,23.935823 L3.86597493,19.4333464 C2.97690068,17.777898 2.50388618,15.9226229 2.50388618,14 C2.50388618,7.64872538 7.65261155,2.5 14.0038862,2.5 Z M14.0038862,4 C8.48103868,4 4.00388618,8.4771525 4.00388618,14 C4.00388618,15.7703119 4.46384891,17.4718347 5.32571954,18.9725127 L5.48656853,19.2525809 L4.08316234,23.9225148 L8.75512584,22.5196672 L9.03501121,22.6802549 C10.5348218,23.5407899 12.2350195,24 14.0038862,24 C19.5267337,24 24.0038862,19.5228475 24.0038862,14 C24.0038862,8.4771525 19.5267337,4 14.0038862,4 Z M10.2538862,15.5 L14.7521489,15.5 C15.1663625,15.5 15.5021489,15.8357864 15.5021489,16.25 C15.5021489,16.6296958 15.219995,16.943491 14.8539195,16.9931534 L14.7521489,17 L10.2538862,17 C9.83967261,17 9.50388618,16.6642136 9.50388618,16.25 C9.50388618,15.8703042 9.78604006,15.556509 10.1521156,15.5068466 L10.2538862,15.5 L14.7521489,15.5 L10.2538862,15.5 Z M10.2538862,11 L17.7583662,11 C18.1725798,11 18.5083662,11.3357864 18.5083662,11.75 C18.5083662,12.1296958 18.2262123,12.443491 17.8601368,12.4931534 L17.7583662,12.5 L10.2538862,12.5 C9.83967261,12.5 9.50388618,12.1642136 9.50388618,11.75 C9.50388618,11.3703042 9.78604006,11.056509 10.1521156,11.0068466 L10.2538862,11 L17.7583662,11 L10.2538862,11 Z</StreamGeometry>
</Application.Resources>
</Application>

View file

@ -50,8 +50,9 @@ public partial class App : Application, ILiveView, IVMPusherApp
{
if (TryHandOffCustomSchemeUrl()) return;
this.ServiceProvider = new ServiceCollection().BuildPostItServices();
this.ServiceProvider = Platform.CreateServiceProvider?.Invoke() ?? new ServiceCollection().BuildPostItServices();
var settings = ServiceProvider.GetRequiredService<Settings>();
ServiceProvider.GetRequiredService<YavscApiClient>().StartSessionMaintenance();
if (!LiveMode)
{
@ -295,6 +296,7 @@ public partial class App : Application, ILiveView, IVMPusherApp
await api.TrySilentLoginAsync().ConfigureAwait(true);
var sessionStatus = provider.GetRequiredService<SessionStatusViewModel>();
await sessionStatus.RefreshAsync();
await provider.GetRequiredService<MessagingSession>().StartAsync(connectOnLogin: OperatingSystem.IsAndroid());
}
/// <summary>

View file

@ -1,12 +1,19 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using PostIt.Services;
namespace PostIt.Controls;
public partial class MarkdownEditorControl : UserControl
{
private IPointer? _touchPointer;
private Point _touchStart;
public static readonly StyledProperty<string?> MarkdownTextProperty =
AvaloniaProperty.Register<MarkdownEditorControl, string?>(nameof(MarkdownText));
@ -38,6 +45,44 @@ public partial class MarkdownEditorControl : UserControl
{
InitializeComponent();
PropertyChanged += OnPropertyChanged;
SourceEditor.TextArea.SizeChanged += (_, _) =>
Dispatcher.UIThread.Post(KeepCaretVisible, DispatcherPriority.Loaded);
SourceEditor.TextArea.AddHandler(InputElement.PointerPressedEvent, OnEditorPointerPressed,
RoutingStrategies.Tunnel, handledEventsToo: true);
SourceEditor.TextArea.AddHandler(InputElement.PointerReleasedEvent, OnEditorPointerReleased,
RoutingStrategies.Bubble, handledEventsToo: true);
}
private void KeepCaretVisible()
{
if (SourceEditor.TextArea.IsFocused && SourceEditor.IsEffectivelyVisible
&& SourceEditor.TextArea.Bounds.Height > 0)
SourceEditor.TextArea.Caret.BringCaretToView();
}
private void OnEditorPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.Pointer.Type != PointerType.Touch)
return;
_touchPointer = e.Pointer;
_touchStart = e.GetPosition(SourceEditor.TextArea);
}
private void OnEditorPointerReleased(object? sender, PointerReleasedEventArgs e)
{
if (!ReferenceEquals(_touchPointer, e.Pointer))
return;
_touchPointer = null;
var point = e.GetPosition(SourceEditor.TextArea);
var settings = this.GetPlatformSettings()
?? throw new InvalidOperationException("The editor has no platform input settings.");
var tapSize = settings.GetTapSize(PointerType.Touch);
// AvaloniaEdit changes pointer capture during selection, so its taps may not raise Tapped.
if (new Rect(_touchStart, default(Size)).Inflate(new Thickness(tapSize.Width, tapSize.Height)).Contains(point)
&& SourceEditor.TextArea.IsFocused
&& !SourceEditor.IsReadOnly
&& new Rect(SourceEditor.TextArea.Bounds.Size).Contains(point))
Platform.ShowSoftKeyboard?.Invoke();
}
private void OnPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)

View file

@ -0,0 +1,17 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="PostIt.Controls.ReplayControls"
Background="Transparent">
<Border x:Name="ControlBar" Background="#CC151515" Padding="12"
VerticalAlignment="Bottom">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="12">
<Button x:Name="ToggleButton" Content="Pause" Click="Toggle_Click"
AutomationProperties.Name="Lecture ou pause du replay" />
<Slider x:Name="PositionSlider" Grid.Column="1" Minimum="0" Maximum="1"
ValueChanged="Position_Changed" VerticalAlignment="Center"
AutomationProperties.Name="Position dans le replay" />
<TextBlock x:Name="TimeLabel" Grid.Column="2" Foreground="White"
VerticalAlignment="Center" Text="0:00 / 0:00" />
</Grid>
</Border>
</UserControl>

View file

@ -0,0 +1,92 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Threading;
using LibVLCSharp.Shared;
using PostIt.Services;
namespace PostIt.Controls;
public partial class ReplayControls : UserControl
{
private readonly ReplayControlsState _state = new();
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private MediaPlayer? _player;
private bool _updating;
public ReplayControls()
{
InitializeComponent();
_timer.Tick += Update;
PointerMoved += (_, _) => _state.Show();
PointerPressed += (_, _) => _state.Show();
KeyDown += (_, _) => _state.Show();
PositionSlider.AddHandler(PointerPressedEvent, BeginSeek, RoutingStrategies.Tunnel);
PositionSlider.AddHandler(PointerReleasedEvent, EndSeek, RoutingStrategies.Bubble, handledEventsToo: true);
PositionSlider.PointerCaptureLost += (_, _) =>
{
if (_state.IsInteracting) CommitSeek();
};
}
public ReplayControls(MediaPlayer player) : this() => _player = player;
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
_state.Show();
_timer.Start();
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
_timer.Stop();
base.OnDetachedFromVisualTree(e);
}
private void Update(object? sender, EventArgs e)
{
if (_player is not { } player) return;
var duration = Math.Max(0, player.Length);
var position = Math.Max(0, player.Time);
ControlBar.IsVisible = _state.IsVisible(player.IsPlaying, ControlBar.IsKeyboardFocusWithin);
ToggleButton.Content = player.IsPlaying ? "Pause" : "Lire";
PositionSlider.IsEnabled = duration > 0 && player.IsSeekable;
_updating = true;
PositionSlider.Maximum = Math.Max(1, duration);
if (!_state.IsInteracting) PositionSlider.Value = Math.Min(position, duration);
_updating = false;
TimeLabel.Text = $"{ReplayControlsState.FormatTime(_state.IsInteracting ? (long)PositionSlider.Value : position)} / {ReplayControlsState.FormatTime(duration)}";
}
private void BeginSeek(object? sender, PointerPressedEventArgs e)
{
_state.IsInteracting = true;
_state.Show();
}
private void EndSeek(object? sender, PointerReleasedEventArgs e) => CommitSeek();
private void CommitSeek()
{
if (_player is { IsSeekable: true } player) player.Time = (long)PositionSlider.Value;
_state.IsInteracting = false;
_state.Show();
}
private void Position_Changed(object? sender, RangeBaseValueChangedEventArgs e)
{
if (!_updating && !_state.IsInteracting) CommitSeek();
}
private void Toggle_Click(object? sender, RoutedEventArgs e)
{
if (_player is not { } player) return;
if (player.IsPlaying) player.Pause();
else player.Play();
_state.Show();
}
}

View file

@ -53,6 +53,8 @@ public static class ServiceCollectionHelpers
// Models
services.AddSingleton<ChatViewModel>();
services.AddSingleton<ChatHubConnection>();
services.AddSingleton<MessagingSession>();
// Android activities need fresh controls; retain state in singleton VMs.
void AddReusablePage<TPage>() where TPage : class

View file

@ -3,10 +3,10 @@
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<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>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>

View file

@ -0,0 +1,87 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed class CallSignalingClient : ILanCallSignaling, IDisposable
{
private readonly HubConnection _connection;
private readonly IDisposable[] _subscriptions;
private bool _disposed;
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 CallSignalingClient(HubConnection connection)
{
_connection = connection;
_subscriptions =
[
connection.On<CallSession>(CallHubMethods.Invitation, call => Invitation?.Invoke(call)),
connection.On<CallAccepted>(CallHubMethods.Accepted, call => Accepted?.Invoke(call)),
connection.On<CallEnded>(CallHubMethods.Ended, call => Ended?.Invoke(call)),
connection.On<Guid, CallSignal>(CallHubMethods.SignalReceived,
(id, signal) => Signal?.Invoke(id, signal))
];
connection.Reconnecting += OnInterruptedAsync;
connection.Closed += OnInterruptedAsync;
}
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync<CallSession>(CallHubMethods.Invite, room, user, ct);
}
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLan, room, user, ct);
}
public Task AcceptAsync(Guid callId, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync(CallHubMethods.Accept, callId, ct);
}
public Task EndAsync(Guid callId, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync(CallHubMethods.End, callId, ct);
}
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync(CallHubMethods.Signal, callId, signal, ct);
}
private Task OnInterruptedAsync(Exception? error)
{
Interrupted?.Invoke();
return Task.CompletedTask;
}
private void EnsureConnected()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_connection.State != HubConnectionState.Connected)
throw new InvalidOperationException("La connexion de chat est interrompue ; l'appel ne peut pas continuer.");
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_connection.Reconnecting -= OnInterruptedAsync;
_connection.Closed -= OnInterruptedAsync;
foreach (var subscription in _subscriptions) subscription.Dispose();
}
}

View file

@ -0,0 +1,273 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using PostIt.ViewModels.Chat;
using PostIt.Models;
namespace PostIt.Services;
/// <summary>One authenticated chat transport per application process, independent of page lifetime.</summary>
public sealed class ChatHubConnection : IAsyncDisposable
{
private readonly SemaphoreSlim _gate = new(1);
private readonly YavscApiClient _api;
private string _apiUrl;
private string _authority;
private string? _accountKey;
private readonly object _roomsGate = new();
private readonly Dictionary<string, ChatRoomInfo> _rooms = new(StringComparer.Ordinal);
private readonly Queue<ChatDelivery> _messages = new();
private long _sequence;
public sealed record ChatDelivery(long Sequence, string? Room, string Sender, string Text);
public event Action<ChatDelivery>? MessageReceived;
public ChatDelivery[] RecentMessages
{
get { lock (_roomsGate) return _messages.ToArray(); }
}
public event Action<ChatRoomInfo>? RoomJoined;
public event Action<string>? Error;
public ChatRoomInfo[] JoinedRooms
{
get { lock (_roomsGate) return _rooms.Values.ToArray(); }
}
public HubConnection Connection { get; private set; }
public bool IsCurrentConfiguration => _apiUrl == _api.Settings.ApiUrl &&
_authority == _api.Settings.Authentication.Authority && _accountKey == GetAccountKey();
public ChatHubConnection(YavscApiClient api)
{
_api = api;
_apiUrl = api.Settings.ApiUrl;
_authority = api.Settings.Authentication.Authority;
_accountKey = GetAccountKey();
LoadRooms();
Connection = BuildConnection();
}
private HubConnection BuildConnection()
{
var api = _api;
var hubBase = api.Settings.ApiUrl.TrimEnd('/');
if (hubBase.EndsWith("/api/v1", StringComparison.OrdinalIgnoreCase))
hubBase = hubBase[..^"/api/v1".Length];
var connection = new HubConnectionBuilder().WithUrl(hubBase + "/" + Yavsc.Constants.ChatHubPath, options =>
{
options.AccessTokenProvider = async () =>
{
if (api.IsSigningOut || !IsCurrentConfiguration)
throw new InvalidOperationException("La configuration de messagerie a change.");
if (!await api.TrySilentLoginAsync())
throw new InvalidOperationException("La session de messagerie a expire. Reconnectez-vous.");
return api.CurrentAccessToken;
};
}).WithAutomaticReconnect(new RetryPolicy()).Build();
connection.On<ChatRoomInfo>("joint", room =>
{
if (ReferenceEquals(Connection, connection) && IsCurrentConfiguration)
RememberRoom(room);
});
connection.On<ChatMessage>("ReceiveMessage", message =>
RememberMessage(connection, message.Room, message.Name ?? "", message.Message ?? ""));
connection.On<string, string>("addPV", (sender, message) =>
RememberMessage(connection, null, sender, message));
connection.Reconnected += _ => ReferenceEquals(Connection, connection) && IsCurrentConfiguration
? RestoreRoomsAsync(connection, CancellationToken.None) : Task.CompletedTask;
return connection;
}
public async Task<HubConnection> GetConnectionAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
try
{
if (!IsCurrentConfiguration)
{
await Connection.DisposeAsync();
_apiUrl = _api.Settings.ApiUrl;
_authority = _api.Settings.Authentication.Authority;
_accountKey = GetAccountKey();
lock (_roomsGate) _messages.Clear();
LoadRooms();
Connection = BuildConnection();
}
return Connection;
}
finally { _gate.Release(); }
}
public async Task StartAsync(CancellationToken ct = default)
{
await GetConnectionAsync(ct);
await _gate.WaitAsync(ct);
try
{
if (_api.IsSigningOut)
throw new InvalidOperationException("La deconnexion du compte est en cours.");
if (Connection.State == HubConnectionState.Disconnected)
{
await Connection.StartAsync(ct);
await RestoreRoomsAsync(Connection, ct);
}
}
finally { _gate.Release(); }
}
public async Task StopAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
try { await Connection.StopAsync(ct); }
finally
{
lock (_roomsGate) _messages.Clear();
_gate.Release();
}
}
public async ValueTask DisposeAsync()
{
await Connection.DisposeAsync();
_gate.Dispose();
}
public async Task<ChatRoomInfo> JoinAsync(string room, CancellationToken ct = default)
{
var connection = Connection;
var info = await connection.InvokeAsync<ChatRoomInfo>("Join", room, ct)
?? throw new InvalidOperationException("Le serveur n'a pas confirme le salon.");
if (!ReferenceEquals(Connection, connection) || !IsCurrentConfiguration)
throw new InvalidOperationException("La session de messagerie a change.");
if (string.IsNullOrWhiteSpace(info.Name))
throw new InvalidOperationException("Le serveur a retourne un salon sans nom.");
RememberRoom(info);
lock (_roomsGate) PersistRooms();
return info;
}
public async Task LeaveAsync(string room, CancellationToken ct = default)
{
var connection = Connection;
await connection.InvokeAsync("Part", room, "Leaving", ct);
if (!ReferenceEquals(Connection, connection) || !IsCurrentConfiguration)
throw new InvalidOperationException("La session de messagerie a change.");
lock (_roomsGate)
{
_rooms.Remove(room);
PersistRooms();
}
}
private async Task RestoreRoomsAsync(HubConnection connection, CancellationToken ct)
{
foreach (var room in JoinedRooms)
{
try
{
var info = await connection.InvokeAsync<ChatRoomInfo>("Join", room.Name!, ct);
if (info == null || string.IsNullOrWhiteSpace(info.Name))
throw new InvalidOperationException("Le serveur n'a pas confirme le salon.");
if (ReferenceEquals(Connection, connection) && IsCurrentConfiguration)
RememberRoom(info);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
ReportError($"Impossible de rejoindre le salon {room.Name} : {ex.Message}");
}
}
}
private void RememberRoom(ChatRoomInfo room)
{
if (string.IsNullOrWhiteSpace(room.Name))
{
ReportError("Le serveur a retourne un salon sans nom.");
return;
}
lock (_roomsGate)
{
_rooms[room.Name] = room;
}
RoomJoined?.Invoke(room);
}
private void RememberMessage(HubConnection connection, string? room, string sender, string text)
{
if (!ReferenceEquals(Connection, connection) || !IsCurrentConfiguration) return;
ChatDelivery delivery;
lock (_roomsGate)
{
delivery = new ChatDelivery(++_sequence, room, sender, text);
_messages.Enqueue(delivery);
while (_messages.Count > 500) _messages.Dequeue();
}
MessageReceived?.Invoke(delivery);
}
private void LoadRooms()
{
lock (_roomsGate)
{
_rooms.Clear();
if (_accountKey != null && _api.Settings.ChatRoomsByAccount.TryGetValue(_accountKey, out var rooms))
foreach (var room in rooms.Where(room => !string.IsNullOrWhiteSpace(room)))
_rooms[room] = new ChatRoomInfo { Name = room };
}
}
private void PersistRooms()
{
if (_accountKey == null) return;
var rooms = new Dictionary<string, string[]>(_api.Settings.ChatRoomsByAccount)
{
[_accountKey] = _rooms.Keys.ToArray()
};
_api.Settings.ChatRoomsByAccount = rooms;
try { _api.Settings.Save(); }
catch (Exception ex) { ReportError($"Sauvegarde des salons impossible : {ex.Message}"); }
}
private void ReportError(string message)
{
if (App.Current is App { ServiceProvider: not null } && !Avalonia.Threading.Dispatcher.UIThread.CheckAccess())
Avalonia.Threading.Dispatcher.UIThread.Post(() => _api.Settings.SetActionStatus(message, StatusSeverity.Error));
else
_api.Settings.SetActionStatus(message, StatusSeverity.Error);
Error?.Invoke(message);
}
private string? GetAccountKey()
{
if (!_api.HasValidSession) return null;
var token = _api.CurrentIdToken ?? _api.CurrentAccessToken;
if (string.IsNullOrEmpty(token)) return null;
var parts = token.Split('.');
if (parts.Length != 3) return null;
try
{
var payload = parts[1].Replace('-', '+').Replace('_', '/');
payload = payload.PadRight((payload.Length + 3) / 4 * 4, '=');
using var json = JsonDocument.Parse(Convert.FromBase64String(payload));
if (!json.RootElement.TryGetProperty("sub", out var subject) ||
subject.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(subject.GetString()))
return null;
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
_api.Settings.Authentication.Authority + "\n" + _api.Settings.ApiUrl + "\n" + subject.GetString())));
}
catch (Exception ex) when (ex is FormatException or JsonException)
{
ReportError("Identite du compte illisible : les salons ne seront pas memorises.");
return null;
}
}
private sealed class RetryPolicy : IRetryPolicy
{
public TimeSpan? NextRetryDelay(RetryContext retryContext)
=> TimeSpan.FromSeconds(Math.Min(60, 2 + retryContext.PreviousRetryCount * 5));
}
}

View file

@ -0,0 +1,10 @@
using System.Threading;
using System.Threading.Tasks;
namespace PostIt.Services;
public interface IBackgroundChatService
{
Task SynchronizeAsync(YavscApiClient api, bool enabled, CancellationToken ct = default);
Task DisableAsync(YavscApiClient api, CancellationToken ct = default);
}

View file

@ -0,0 +1,17 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public interface ILanCallMedia : IAsyncDisposable
{
Control LocalVideo { get; }
Control RemoteVideo { get; }
LanCallEndpoint Endpoint { get; }
Task Completion { get; }
bool HasRemoteMedia { get; }
Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct);
}

View file

@ -0,0 +1,19 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public interface ILanCallSignaling
{
event Action<CallSession>? Invitation;
event Action<CallAccepted>? Accepted;
event Action<CallEnded>? Ended;
event Action<Guid, CallSignal>? Signal;
event Action? Interrupted;
Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default);
Task AcceptAsync(Guid callId, CancellationToken ct = default);
Task EndAsync(Guid callId, CancellationToken ct = default);
Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default);
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Controls;
namespace PostIt.Services;
@ -8,9 +9,10 @@ public sealed record CaptureDevice(string Name, string Value);
public sealed record PodcastCaptureDevices(
IReadOnlyList<CaptureDevice> Cameras, IReadOnlyList<CaptureDevice> Microphones);
/// <summary>A running encoder publishing closed segments and an atomic index.m3u8.</summary>
/// <summary>A running camera/microphone encoder with an optional native preview.</summary>
public interface IPodcastCapture : IAsyncDisposable
{
Task Completion { get; }
Control? Preview => null;
Task StopAsync();
}

View file

@ -0,0 +1,199 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using LibVLCSharp.Shared;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed class LibVlcLanCallMedia : IAsyncDisposable
{
private readonly LibVLC _senderVlc;
private readonly LibVLC _receiverVlc;
private readonly Media _receiverMedia;
private Media? _senderMedia;
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SemaphoreSlim _gate = new(1);
private bool _receiving;
private bool _disposed;
private Task? _stop;
public LanCallEndpoint Endpoint { get; }
public MediaPlayer Sender { get; }
public MediaPlayer Receiver { get; }
public Task Completion => _completion.Task;
public MediaStats Statistics => _receiverMedia.Statistics;
public bool HasRemoteMedia => !_disposed && Statistics.DecodedAudio > 0 && Statistics.DecodedVideo > 0;
public LibVlcLanCallMedia(string localAddress, int port, bool headless = false)
{
if (!OperatingSystem.IsLinux() && !OperatingSystem.IsAndroidVersionAtLeast(26))
throw new PlatformNotSupportedException("Les appels SRTP LAN requierent Linux ou Android 8+.");
Endpoint = new(localAddress, port, Convert.ToHexString(RandomNumberGenerator.GetBytes(16)),
Convert.ToHexString(RandomNumberGenerator.GetBytes(14)));
if (!Endpoint.IsValid())
throw new ArgumentException("Adresse IPv4/IPv6 unicast et port UDP pair (1024-65534) requis.");
var localIp = IPAddress.Parse(localAddress);
using (var reservation = new Socket(localIp.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
using (var rtcp = new Socket(localIp.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
{
reservation.Bind(new IPEndPoint(IPAddress.Parse(localAddress), port));
rtcp.Bind(new IPEndPoint(IPAddress.Parse(localAddress), port + 1));
}
Core.Initialize();
_senderVlc = headless ? CameraStreamer.CreateHeadlessLibVlc()
: new LibVLC("--avcodec-hw=none", "--aout=dummy", "--intf=dummy");
try
{
_receiverVlc = headless ? CameraStreamer.CreateHeadlessLibVlc()
: new LibVLC("--avcodec-hw=none", "--intf=dummy");
try
{
var host = localIp.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{localAddress}]" : localAddress;
_receiverMedia = new Media(_receiverVlc, $"rtp://@{host}:{port}", FromType.FromLocation);
_receiverMedia.AddOption(":network-caching=150");
_receiverMedia.AddOption(":rtcp-port=" + (port + 1));
_receiverMedia.AddOption(":srtp-key=" + Endpoint.Key);
_receiverMedia.AddOption(":srtp-salt=" + Endpoint.Salt);
Receiver = new MediaPlayer(_receiverVlc);
Sender = new MediaPlayer(_senderVlc);
Sender.EncounteredError += OnSenderError;
Receiver.EncounteredError += OnReceiverError;
Sender.EndReached += OnSenderEnded;
}
catch
{
_receiverMedia?.Dispose();
Receiver?.Dispose();
Sender?.Dispose();
_receiverVlc.Dispose();
throw;
}
}
catch
{
_senderVlc.Dispose();
throw;
}
}
public async Task StartReceivingAsync(CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_stop != null) throw new InvalidOperationException("Cet appel est arrete.");
if (_receiving) return;
ct.ThrowIfCancellationRequested();
if (!Receiver.Play(_receiverMedia))
throw new InvalidOperationException("Reception SRTP impossible. Verifiez adresse et port UDP.");
_receiving = true;
}
finally { _gate.Release(); }
}
public Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct) =>
StartSendingAsync(remote, vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), true, ct);
internal async Task StartSendingAsync(LanCallEndpoint remote, Func<LibVLC, Media> source,
bool preview, CancellationToken ct, bool transcode = true)
{
if (!remote.IsValid())
throw new ArgumentException("Destination SRTP LAN invalide.", nameof(remote));
if (remote.Address == Endpoint.Address && remote.Port == Endpoint.Port)
throw new ArgumentException("Les deux pairs doivent avoir des ports distincts sur une meme adresse.");
await _gate.WaitAsync(ct);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_stop != null || _senderMedia != null)
throw new InvalidOperationException("La capture de cet appel est deja demarree ou arretee.");
_senderMedia = source(_senderVlc);
ConfigureOutput(_senderMedia, remote, preview, transcode);
ct.ThrowIfCancellationRequested();
if (!Sender.Play(_senderMedia))
throw new InvalidOperationException("Capture SRTP impossible. Verifiez camera, microphone et encodeurs H.264/AAC.");
}
finally { _gate.Release(); }
}
public Task StartEncodedSendingAsync(LanCallEndpoint remote, int fileDescriptor, CancellationToken ct)
{
if (fileDescriptor < 0) throw new ArgumentOutOfRangeException(nameof(fileDescriptor));
return StartSendingAsync(remote, vlc =>
{
var media = new Media(vlc, $"fd://{fileDescriptor}", FromType.FromLocation);
media.AddOption(":demux=ts");
media.AddOption(":live-caching=100");
media.AddOption(":clock-jitter=0");
return media;
}, false, ct, transcode: false);
}
internal static void ConfigureOutput(Media media, LanCallEndpoint remote, bool preview, bool transcode = true)
{
if (!remote.IsValid()) throw new ArgumentException("Destination SRTP invalide.");
// Same capture/encoders as Podcasts, but no HLS files, segmentation or upload.
var encoding = (transcode ? "transcode{vcodec=h264,venc=x264{preset=ultrafast,tune=zerolatency,keyint=30,bframes=0},"
+ "vb=1200,fps=30,acodec=mp4a,ab=96,channels=1,samplerate=48000}:" : "")
// Android LibVLC 3 crashes formatting the valueless rtcp-mux SDP attribute.
+ $"rtp{{dst={remote.Address},port={remote.Port},mux=ts,"
+ $"key={remote.Key},salt={remote.Salt},caching=50}}";
media.AddOption(":sout=#" + (preview
? $"duplicate{{dst=display{{noaudio}},dst=\"{encoding}\"}}" : encoding));
}
private void OnSenderError(object? sender, EventArgs args) => _completion.TrySetException(
new InvalidOperationException("Capture/encodage SRTP en echec. Verifiez les peripheriques et encodeurs."));
private void OnReceiverError(object? sender, EventArgs args) => _completion.TrySetException(
new InvalidOperationException("Reception/decodage SRTP en echec. Verifiez le reseau LAN/VPN et les ports UDP."));
private void OnSenderEnded(object? sender, EventArgs args) => _completion.TrySetException(
new InvalidOperationException("La source audio-video s'est terminee."));
private Task StopCoreAsync() => _stop ??= Task.Run(() =>
{
try { Sender.Stop(); }
finally { Receiver.Stop(); }
});
public async Task StopAsync()
{
await _gate.WaitAsync();
try
{
if (!_disposed) await StopCoreAsync();
}
finally { _gate.Release(); }
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync();
try
{
if (_disposed) return;
_disposed = true;
Sender.EncounteredError -= OnSenderError;
Receiver.EncounteredError -= OnReceiverError;
Sender.EndReached -= OnSenderEnded;
try { await StopCoreAsync(); }
finally
{
Sender.Dispose();
Receiver.Dispose();
_senderMedia?.Dispose();
_receiverMedia.Dispose();
_senderVlc.Dispose();
_receiverVlc.Dispose();
_completion.TrySetResult();
}
}
finally { _gate.Release(); }
}
}

View file

@ -1,6 +1,8 @@
using System;
using System.Threading.Tasks;
using LibVLCSharp.Shared;
using Avalonia.Controls;
using Avalonia.Threading;
namespace PostIt.Services;
@ -11,24 +13,38 @@ internal sealed class LibVlcPodcastCapture : IPodcastCapture
private readonly MediaPlayer _player;
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _stopped;
private bool _startScheduled;
private readonly LibVLCSharp.Avalonia.VideoView? _preview;
public Task Completion => _completion.Task;
public Control? Preview => _preview;
public LibVlcPodcastCapture(Func<LibVLC, Media> createMedia, string directory)
public LibVlcPodcastCapture(Func<LibVLC, Media> createMedia, string? directory, bool preview = false)
{
Core.Initialize();
_vlc = CameraStreamer.CreatePreferredLibVlc();
// The usual Linux capture instance has a dummy video output; preview needs a drawable.
_vlc = preview ? new LibVLC("--avcodec-hw=none", "--aout=dummy") : CameraStreamer.CreatePreferredLibVlc();
try
{
_media = createMedia(_vlc);
PodcastBroadcaster.ConfigureOutput(_media, directory);
if (directory is not null) PodcastBroadcaster.ConfigureOutput(_media, directory, preview);
else _media.AddOption(":no-audio");
_player = new MediaPlayer(_vlc);
if (preview)
{
_preview = new LibVLCSharp.Avalonia.VideoView { MediaPlayer = _player };
_preview.LayoutUpdated += OnPreviewLayout;
}
_player.EncounteredError += OnError;
if (!_player.Play(_media))
throw new InvalidOperationException("LibVLC ne peut pas demarrer la capture. Verifiez la camera et les encodeurs H.264/AAC.");
if (!preview) StartPlayer();
}
catch
{
if (_preview is not null)
{
_preview.LayoutUpdated -= OnPreviewLayout;
_preview.MediaPlayer = null;
}
_player?.Dispose();
_media?.Dispose();
_vlc.Dispose();
@ -36,14 +52,53 @@ internal sealed class LibVlcPodcastCapture : IPodcastCapture
}
}
private void StartPlayer()
{
if (!_player.Play(_media))
throw new InvalidOperationException("LibVLC ne peut pas demarrer la capture. Verifiez la camera et les encodeurs H.264/AAC.");
}
private void OnPreviewLayout(object? sender, EventArgs e)
{
if (_startScheduled || _stopped || _preview is not { IsEffectivelyVisible: true } view
|| view.Bounds.Width <= 0 || view.Bounds.Height <= 0) return;
_startScheduled = true;
view.LayoutUpdated -= OnPreviewLayout;
// LibVLC must receive its native drawable before the display branch starts.
Dispatcher.UIThread.Post(() =>
{
if (_stopped) return;
try
{
view.TryUpdateNativeControlPosition();
StartPlayer();
}
catch (Exception ex) { _completion.TrySetException(ex); }
}, DispatcherPriority.Loaded);
}
private void OnError(object? sender, EventArgs e)
=> _completion.TrySetException(new InvalidOperationException(
"La capture LibVLC a echoue. Verifiez camera, microphone et encodeurs H.264/AAC."));
public async Task StopAsync()
{
if (_stopped) return;
_stopped = true;
if (_preview is not null)
{
var shouldStop = await Dispatcher.UIThread.InvokeAsync(() =>
{
if (_stopped) return false;
_stopped = true;
_preview.LayoutUpdated -= OnPreviewLayout;
return true;
});
if (!shouldStop) return;
}
else
{
if (_stopped) return;
_stopped = true;
}
await Task.Run(_player.Stop);
_completion.TrySetResult();
}
@ -53,6 +108,8 @@ internal sealed class LibVlcPodcastCapture : IPodcastCapture
try { await StopAsync(); }
finally
{
if (_preview is not null)
await Dispatcher.UIThread.InvokeAsync(() => _preview.MediaPlayer = null);
_player.EncounteredError -= OnError;
_player.Dispose();
_media.Dispose();

View file

@ -0,0 +1,105 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using LibVLCSharp.Avalonia;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed class LinuxLanCallVideo : ILanCallMedia
{
private readonly LibVlcLanCallMedia _media;
private readonly VideoView _local;
private readonly VideoView _remote;
private readonly TaskCompletionSource _localReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _lifetime = new();
private bool _receiverScheduled;
private bool _localScheduled;
private bool _disposed;
private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Control LocalVideo => _local;
public Control RemoteVideo => _remote;
public LanCallEndpoint Endpoint => _media.Endpoint;
public Task Completion { get; }
public bool HasRemoteMedia => !_disposed && _media.HasRemoteMedia;
public LinuxLanCallVideo(string localAddress, int port)
{
_media = new LibVlcLanCallMedia(localAddress, port);
_local = new VideoView { MediaPlayer = _media.Sender, MinHeight = 140 };
_remote = new VideoView { MediaPlayer = _media.Receiver, MinHeight = 260 };
_local.LayoutUpdated += OnLocalLayout;
_remote.LayoutUpdated += OnRemoteLayout;
Completion = ObserveCompletionAsync();
}
private async Task ObserveCompletionAsync()
{
var completed = await Task.WhenAny(_media.Completion, _failure.Task);
await completed;
}
private void OnLocalLayout(object? sender, EventArgs e)
{
if (_localScheduled || _disposed || !_local.IsEffectivelyVisible ||
_local.Bounds.Width <= 0 || _local.Bounds.Height <= 0) return;
_localScheduled = true;
Dispatcher.UIThread.Post(() =>
{
if (_disposed) return;
_local.TryUpdateNativeControlPosition();
_localReady.TrySetResult();
}, DispatcherPriority.Loaded);
}
private void OnRemoteLayout(object? sender, EventArgs e)
{
if (_receiverScheduled || _disposed || !_remote.IsEffectivelyVisible ||
_remote.Bounds.Width <= 0 || _remote.Bounds.Height <= 0) return;
_receiverScheduled = true;
Dispatcher.UIThread.Post(StartReceiver, DispatcherPriority.Loaded);
}
private async void StartReceiver()
{
if (_disposed) return;
try
{
_remote.TryUpdateNativeControlPosition();
await _media.StartReceivingAsync(_lifetime.Token);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
catch (Exception error) { _failure.TrySetException(error); }
}
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
{
await _localReady.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
await _media.StartSendingAsync(remote, camera, microphone, ct);
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
_lifetime.Cancel();
_localReady.TrySetCanceled();
_local.LayoutUpdated -= OnLocalLayout;
_remote.LayoutUpdated -= OnRemoteLayout;
try { await _media.StopAsync(); }
finally
{
_local.MediaPlayer = null;
_remote.MediaPlayer = null;
try { await _media.DisposeAsync(); }
finally
{
_lifetime.Dispose();
_failure.TrySetResult();
}
}
}
}

View file

@ -0,0 +1,178 @@
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
namespace PostIt.Services;
/// <summary>Coordinates process-scoped chat and the optional native background service.</summary>
public sealed class MessagingSession : IAsyncDisposable
{
private readonly YavscApiClient _api;
private readonly SessionStatusViewModel _session;
private readonly ChatViewModel _chat;
private readonly CancellationTokenSource _lifetime = new();
private readonly SemaphoreSlim _gate = new(1);
private bool _started;
private bool _connectOnLogin;
private bool? _servicePreference;
private bool _signingOut;
private Task? _maintenance;
private string? _apiUrl;
private string? _authority;
private CancellationTokenSource? _serviceOperation;
private readonly object _operationGate = new();
public MessagingSession(YavscApiClient api, SessionStatusViewModel session, ChatViewModel chat)
{
_api = api;
_session = session;
_chat = chat;
}
public async Task StartAsync(bool connectOnLogin = true)
{
if (_started) return;
_started = true;
_connectOnLogin = connectOnLogin;
_apiUrl = _api.Settings.ApiUrl;
_authority = _api.Settings.Authentication.Authority;
_api.SigningOut += OnSigningOutAsync;
_session.PropertyChanged += OnSessionChanged;
_api.Settings.Saved += OnSettingsSaved;
_chat.ConnectionRequestedChanged += OnConnectionRequestedChanged;
if (_api.HasValidSession && _connectOnLogin) await _chat.ConnectAsync();
_maintenance = MaintainChatAsync(_lifetime.Token);
await SynchronizeServiceAsync();
}
private async Task MaintainChatAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested)
{
if (!_api.HasValidSession && _chat.ConnectionRequested)
{
try { await OnSigningOutAsync(); }
catch (Exception ex)
{
_api.Settings.SetActionStatus($"Arret du service de messagerie incomplet : {ex.Message}", Models.StatusSeverity.Error);
}
_session.Refresh();
}
if (!_signingOut && _api.HasValidSession && !_chat.IsConnected && _chat.ConnectionRequested)
await _chat.ConnectAsync();
await SynchronizeServiceAsync();
await Task.Delay(TimeSpan.FromSeconds(30), ct);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
}
private async void OnSessionChanged(object? sender, PropertyChangedEventArgs args)
{
if (args.PropertyName != nameof(SessionStatusViewModel.IsLoggedIn)) return;
if (_session.IsLoggedIn) _signingOut = false;
await SynchronizeServiceAsync();
if (_session.IsLoggedIn && (_connectOnLogin || _chat.ConnectionRequested))
{
await _chat.ConnectAsync();
}
}
private async void OnConnectionRequestedChanged()
{
if (_signingOut || _lifetime.IsCancellationRequested) return;
await SynchronizeServiceAsync();
}
private async void OnSettingsSaved(object? sender, EventArgs args)
{
try
{
if (!_api.Settings.AndroidKeepChatConnected) CancelServiceOperation();
if (_apiUrl != _api.Settings.ApiUrl || _authority != _api.Settings.Authentication.Authority)
{
_apiUrl = _api.Settings.ApiUrl;
_authority = _api.Settings.Authentication.Authority;
_servicePreference = null;
var reconnect = _connectOnLogin || _chat.ConnectionRequested;
await _chat.DisconnectAsync();
if (_api.HasValidSession && reconnect) await _chat.ConnectAsync();
}
await SynchronizeServiceAsync();
}
catch (Exception ex)
{
_api.Settings.SetActionStatus($"Mise a jour de la messagerie impossible : {ex.Message}", Models.StatusSeverity.Error);
}
}
private async Task SynchronizeServiceAsync()
{
await _gate.WaitAsync();
try
{
var native = Platform.BackgroundChatService;
if (native == null || !_api.HasValidSession || _api.IsSigningOut || _signingOut) return;
var enabled = _api.Settings.AndroidKeepChatConnected && _chat.ConnectionRequested;
if (_servicePreference == enabled) return;
try
{
using var serviceOperation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
lock (_operationGate) _serviceOperation = serviceOperation;
try
{
await native.SynchronizeAsync(_api, enabled, serviceOperation.Token);
_servicePreference = enabled;
}
finally { lock (_operationGate) _serviceOperation = null; }
}
catch (OperationCanceledException) when (_signingOut || _lifetime.IsCancellationRequested || !_api.Settings.AndroidKeepChatConnected) { }
catch (Exception ex)
{
_api.Settings.SetActionStatus($"Service de messagerie Android indisponible : {ex.Message}", Models.StatusSeverity.Error);
}
}
finally { _gate.Release(); }
}
private async Task OnSigningOutAsync()
{
_signingOut = true;
CancelServiceOperation();
await _gate.WaitAsync();
try
{
_servicePreference = null;
try
{
if (Platform.BackgroundChatService is { } native)
await native.DisableAsync(_api);
}
finally { await _chat.DisconnectAsync(); }
}
finally { _gate.Release(); }
}
public async ValueTask DisposeAsync()
{
_api.SigningOut -= OnSigningOutAsync;
_session.PropertyChanged -= OnSessionChanged;
_api.Settings.Saved -= OnSettingsSaved;
_chat.ConnectionRequestedChanged -= OnConnectionRequestedChanged;
_lifetime.Cancel();
if (_maintenance != null) await _maintenance;
await _chat.DisconnectAsync();
_lifetime.Dispose();
}
private void CancelServiceOperation()
{
lock (_operationGate) _serviceOperation?.Cancel();
}
}

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