Compare commits

...
Author SHA1 Message Date
56f9ad3706
Preserve the shared SQLite schema while resetting
Some checks failed
Dotnet build and test / build (pull_request) Failing after 9m27s
2026-11-23 16:00:31 +00:00
93ffb7a432
version dumps 2026-11-23 14:58:57 +00:00
e62080c7c6
test(blogs): seed mapped JWT authors
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 14:57:51 +00:00
d86ea87d59
fix(postit): preserve newly created blog posts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-22 23:19:45 +00:00
82095f4435
feat(postit): capture écran et audio sous Linux
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 23:19:42 +00:00
3bf7dd88f5
reorg 2026-11-21 21:14:34 +00:00
c745aef6d7
reorg 2026-11-21 20:40:56 +00:00
68a2364de2
refacto App.Name and settings cleanup 2026-11-20 15:53:03 +00:00
852f684d82
Porter l'éditeur du replay sur Android
En portrait, le panneau des marques et des plages passe sous la vidéo
native. La barre native du replay affiche l'image pendant le glissement
(dernière position, au plus toutes les 60 ms). Les miniatures des marques
sont copiées depuis la surface native avec PixelCopy via la nouvelle
interface IVideoFrameCapture, l'instantané LibVLC ne lisant pas le
décodage matériel.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 17:21:38 +00:00
989c782d5c
Publier les marques nommées comme chapitres du replay
Le brouillon accepte un titre facultatif par marque (120 caractères au
plus) ; la publication convertit les temps vers la chronologie du MP4,
intègre les chapitres par FFmpeg sans réencodage et les expose dans
PodcastResponse.Chapters. L'éditeur PostIt nomme les marques, le lecteur
PostIt et la page web des podcasts listent les chapitres cliquables.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 16:33:53 +00:00
b0b81f3632
PostIt: éditeur desktop des marques et plages du replay
L'auteur édite le brouillon d'un replay raffiné depuis PostIt desktop :
navigation image par image, marques au temps courant (Ctrl+M) avec
miniatures locales, plages supprimées entre deux marques, rétablissement,
enregistrement avec contrôle de révision (un conflit conserve les
modifications locales) et publication après enregistrement.

ReplayEditPlan passe dans Yavsc.Abstract pour que le client fusionne et
valide les plages comme le serveur.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 16:18:57 +00:00
de08edaaf9
PostIt: options et contrôles du raffinage du replay
Ajoute à la page podcasts le choix du raffinage et de la conservation des
originaux (émission préparée et direct immédiat), l'état du brouillon et
l'échéance pour l'auteur, la publication du brouillon tel quel et la
suppression confirmée des originaux après publication. La lecture choisit
le MP4 publié, sinon les originaux pour l'auteur, et informe les autres
utilisateurs que le replay est en cours de finalisation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 16:07:14 +00:00
eb02e99872
Icon updated 2026-11-16 15:56:13 +00:00
8ab3c02ebc
test(postit): run all Avalonia UI tests in the shared collection fixture
Replace [AvaloniaFact]/[AvaloniaTheory] and direct GetOrStartForAssembly
dispatches with ui.RunAsync in AvaloniaUiCollection, avoiding a second
headless session that could hang PodcastBroadcasterTests. Add a synchronous
RunAsync overload and update MessagingSessionTests contact-preference
assertions for the audio-only capabilities announced on Linux desktop.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 15:55:32 +00:00
4493ac0149
Add refined replay draft API client
Create lives with RefineReplay and RetentionDays, save and publish drafts,
delete published originals and read the owner-only draft source by bounded,
verified byte ranges. PodcastReplayMediaInput can stream the draft source.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 14:56:39 +00:00
e9ffbc78be
Apply retention to refined replay originals
RetentionDays (0-365, default 7) sets OriginalsExpireAt from the end of
the live, or from publication with 0 days. The replay worker purges the
segments, source and draft of published emissions and deletes emissions
never published by the deadline, marking their flow deleted. Owners can
purge published originals early with DELETE podcasts/{id}/originals.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 14:36:45 +00:00
46fc937443
Add private replay draft for refined podcasts
Emissions opted into RefineReplay (ignored for OBS) get an owner-only
source.mp4 draft after the live or an interruption. The owner saves
revisioned marks and removed ranges, streams the source and queues an
idempotent publication; the worker renders or copies it within quota and
atomically replaces replay.mp4. Originals and drafts stay private until
publication, and the web catalogue shows "Replay en preparation".

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 14:22:14 +00:00
d29124c527
Add frame-accurate server-side replay editing prototype
- ReplayEditPlan turns removed ranges into kept ranges (merge, clamp,
  reject empty, out-of-range, total or excessive removals).
- FfmpegPodcastReplayEditor renders kept ranges with one accurate-seek
  FFmpeg input per range, concat and H.264/AAC re-encoding (faststart).
- Share the FFmpeg runner (FfmpegProcess) with the replay remuxer.
- Tests check exact kept frames, audio/video durations, faststart and
  quota, with and without a start offset.
- Document the server prototype results in doc/video-edition.md.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 14:01:24 +00:00
762fc35b9c
Preview replay frames while dragging the desktop slider
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 13:39:34 +00:00
532ede6830
Add video edition design document
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 13:33:34 +00:00
2f4a7cb4c9
Reuse replay controls for live playback
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 12:12:18 +00:00
d66dd089db
Clean test results 2026-11-16 11:33:28 +00:00
f05dd48ac7
Support avatar video sources for SRTP calls
Use the shared LibVLC audio-video pipeline for camera-free calls on Linux and Android. Add capability signaling, microphone-only Android capture, avatar lifecycle handling and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 10:18:03 +00:00
97e197996f
Add audio-only WebRTC calls
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 01:42:53 +00:00
9e4f9d55ea
Enforce chat contact preferences
Filter video calls and private messages per connection and prepare mode-aware call signaling. Audio-only media remains unimplemented.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 01:16:08 +00:00
9c4cce6840
Add contact preferences announcement
Persist contact options and announce them on chat connection and reconnection. Prepare the audio-only call contract; enforcement and audio-only media remain unimplemented.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 01:10:47 +00:00
0886b5e4e7
Fix PostIt tests after UI refactoring
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 01:04:48 +00:00
7c626efccf
Set OSM tile User-Agent
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-15 01:06:34 +00:00
43b4ae7763
permission field is not supported in Forgejo 2026-11-15 00:09:11 +00:00
189 changed files with 17312 additions and 1181 deletions

View file

@ -2,10 +2,7 @@
# with the PostIt Android APK as an attached asset.
#
# Triggered by a push of a git tag. Validates the tag/changelog pair,
# builds the APK using the existing Dockerfile (--target build-env), then
# publishes a Forgejo release via the Forgejo REST API and uploads the
# APK as an asset.
#
# builds the APK using the existing Dockerfile (--target bupermissions
# Authentication uses ${{ secrets.GITHUB_TOKEN }} (auto-provided by the
# Forgejo runner, scoped to contents: write for the current repo). A
# dedicated PAT (${{ secrets.RELEASE_TOKEN }}) was the preferred option
@ -43,9 +40,6 @@ on:
required: true
type: string
permissions:
contents: write
jobs:
# Job unique : validation tag/CHANGELOG + build APK + publication
# via l'API REST Forgejo (pas d'actions tierces Node).

View file

@ -2,6 +2,56 @@
# Changelog
## [1.0.8-rc38] - unstable
### Added
* [PostIt/Android] Port the replay draft editor to Android: the page stacks the mark and range panel under the native video in portrait, the native replay seek bar previews the dragged position (latest position only, at most every 60 ms, shared `ReplayControlsState`), and mark thumbnails are copied from the native surface with `PixelCopy` through the new `IVideoFrameCapture`, since the LibVLC snapshot cannot read hardware-decoded output.
* [Podcasts] Publish named marks as replay chapters: the draft stores optional mark titles (`Chapters`, at most 120 characters, a title's time is also a mark, titles of removed marks are dropped). Publication converts their times to the published timeline, embeds them in the MP4 with an FFmpeg stream copy (titles only go through an escaped metadata file) and exposes them in `PodcastResponse.Chapters`. The PostIt editor names marks, and the PostIt replay player and the web podcasts page list the chapters as buttons that seek the replay.
* [PostIt/Podcasts] Add the desktop replay draft editor: from the refinement panel, the owner plays the private draft source, steps frame by frame, adds marks at the current time (Ctrl+M) with local thumbnails, picks start and end marks to remove ranges, restores ranges, then saves with the read revision (a conflict keeps local edits and asks for a reload) or publishes after saving pending edits. `ReplayEditPlan` moves to `Yavsc.Abstract` so the editor merges and validates ranges like the server.
* [PostIt/Podcasts] Add the refined replay options and owner controls to the podcasts page: opt into refinement and choose the originals retention (0–365 days) for planned and immediate lives, see the draft state and originals deadline, publish the draft unchanged, and delete the originals after publication with confirmation. Playback now prefers the published MP4, lets the owner play unpublished originals, and tells other viewers the replay is being finalized instead of failing.
* [Yavsc.Api.Client/Podcasts] Add the refined replay client: create a live with `RefineReplay` and `RetentionDays`, save and publish drafts, delete published originals, and read the owner-only draft source by bounded, verified byte ranges. `PodcastReplayMediaInput` can stream the draft source for the upcoming PostIt editor.
* [Yavsc.Server/Podcasts] Apply the retention of refined replays: `RetentionDays` (0–365, default 7; migration `PodcastReplayRetention` adds `LiveFlow.RetentionDays`) sets `OriginalsExpireAt` from the end of the live, or from publication with 0 days. The replay worker then deletes the segments, source and draft of published emissions (`OriginalsDeleted`, the MP4 stays playable but no longer re-editable) and deletes emissions never published by the deadline, marking their flow deleted. The owner can purge published originals early with `DELETE podcasts/{id}/originals`. The web catalogue keeps showing the published MP4 after the purge.
* [Yavsc.Server/Podcasts] Add the private replay draft for emissions opted into refinement (`RefineReplay`, ignored for OBS; migration `PodcastRefineReplay` adds `LiveFlow.RefineReplay`). After the live, or after an interruption, the segments are remuxed into an owner-only `source.mp4` draft (`Preparing`, `Ready`, `Publishing`, `Failed`); the owner saves revisioned marks and removed ranges (`PUT podcasts/{id}/draft`, 409 on stale revision, marks inside removed ranges dropped), streams the source (`GET/HEAD podcasts/{id}/draft/source.mp4`) and queues an idempotent publication (`POST podcasts/{id}/draft/publish`). The worker renders or copies the source within quota and atomically replaces `replay.mp4`, keeping the previous replay on failure; re-edition is supported. Until publication, playlist and segments return 403 to other users, drafts are hidden from listeners, and the web catalogue shows "Replay en préparation". The FFmpeg editor now detects audio itself and keeps the last range open to the real end of the media.
* [Yavsc.Server/Podcasts] Add the frame-accurate replay editing prototype: `ReplayEditPlan` turns removed ranges into kept ranges (merge, clamp, reject empty, out-of-range, total or excessive removals) and `FfmpegPodcastReplayEditor` renders them with one accurate-seek FFmpeg input per range, `concat` and H.264/AAC re-encoding. Share the FFmpeg runner with the replay remuxer. Tests check exact kept frames, audio/video durations, faststart and quota on synthetic sources with and without a start offset; the editor is not wired to the API yet.
* [PostIt/Podcasts] Preview the replay frame while dragging the desktop position slider, coalescing seek requests to the latest position. A native LibVLC test checks frame-accurate paused seeking on a synthetic video; the video edition document records the prototype result.
* [Docs/Podcasts] Add the video edition design document: optional author-only replay refinement (marks, frame-accurate cuts, chapters, timed overlays, re-edition and retention), live credits and overlays, end postponement and server-side "Direct interrompu" handling. Desktop first; OBS broadcasts are out of scope.
* [PostIt/Calls] Allow direct SRTP calls without a camera on Linux and Android by transmitting the user's avatar as repeating video with microphone audio through the existing LibVLC H.264/AAC pipeline. Announce transport-specific support, retain video reception and address-disclosure consent, and capture only microphone audio on Android in avatar mode. Add avatar lifecycle, UI, signaling and real IPv4/IPv6 media regressions; document validation and remaining Android device testing.
* [PostIt/Chat] Add audio-only WebRTC calls on Linux and Android with the user's avatar as a static image, microphone-only capture, dedicated navigation and capability-aware invitations. Keep direct SRTP audio-video only; add signaling, UI and Linux native-media regressions.
* [PostIt/Chat] Filter video invitations and private messages by announced per-connection preferences, stop affected calls when preferences change, and prepare mode-aware audio signaling. Audio-only calls and static images are not implemented yet; legacy clients without preferences remain reachable.
* [PostIt/Chat] Persist audio, audio-video and private-message contact preferences and announce them to ChatHub on connection and reconnection. Add the audio-only call display contract; filtering contacts and audio-only media are not implemented yet.
### Fixed
* [Yavsc.Api/Tests] Preserve the shared SQLite schema while resetting API integration-test data, preventing hosted workers from observing missing `LiveFlow` tables during test-host shutdown.
* [PostIt/Blogs] Keep a newly created post readable when its creation response temporarily omits author details, and include the author in server-side create/detail payloads so relative resource URLs can be resolved after save.
* [PostIt/Capture] Automatically upload finalized screen recordings as `video/mp4` to `Mes fichiers / screencast`, streaming the multipart file from disk and retaining the local copy if the upload fails.
* [PostIt/Capture] Decode the PipeWire node identifier from the ScreenCast portal `streams` array of `(node id, properties)` structures, let the user choose a full screen, a window or the portal picker, and mux system audio from the default output monitor into the H.264/AAC MP4. Stop GStreamer with SIGINT so the muxer receives EOS and writes a valid `moov` atom.
* [PostIt.Tests] Run every Avalonia UI test in the shared `AvaloniaUiCollection` fixture: replace `[AvaloniaFact]`/`[AvaloniaTheory]` and direct `GetOrStartForAssembly` dispatches, which started a second headless session alongside the fixture's and could hang `PodcastBroadcasterTests`, with `ui.RunAsync` (new synchronous overload). Update contact-preference assertions in `MessagingSessionTests` for the audio-only capabilities the Linux desktop announces.
* [PostIt/Podcasts] Reuse the replay playback controls for live video on desktop and Android, remove the duplicate play/pause button, and retain seeking only for replays. Report resume failures and cover playback controls with targeted tests.
* [PostIt] Restore selectable error notification messages and update blog and rendez-vous tests for the current layouts and address editor.
* [PostIt] Set a custom OpenStreetMap User-Agent for the address editor map tiles to satisfy the OSM tile usage policy.
## [1.0.8-rc37] - unstable
### Added

View file

@ -6,8 +6,31 @@
<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="Markdig" Version="1.6.0" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="10.0.3" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="11.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="11.0.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="11.0.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="11.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="11.0.0" />
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.23.0" />
<PackageVersion Include="HigginsSoft.IdentityServer8" Version="$(IdentityServer8Version)" />
<PackageVersion Include="HigginsSoft.IdentityServer8.AspNetIdentity" Version="$(IdentityServer8Version)" />
<PackageVersion Include="HigginsSoft.IdentityServer8.EntityFramework" Version="$(IdentityServer8Version)" />
@ -15,36 +38,15 @@
<PackageVersion Include="HigginsSoft.IdentityServer8.Security" Version="$(IdentityServer8Version)" />
<PackageVersion Include="HigginsSoft.IdentityServer8.Storage" Version="$(IdentityServer8Version)" />
<PackageVersion Include="BouncyCastle.Cryptography" Version="2.7.0" />
<PackageVersion Include="Google.Apis.Compute.v1" Version="1.74.0.4138" />
<PackageVersion Include="Microsoft.AspNetCore.Antiforgery" Version="2.3.13" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR" Version="1.2.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Hosting" Version="2.3.13" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Razor" Version="2.3.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.13" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="10.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.13" />
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.23.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.13" />
<PackageVersion Include="coverlet.collector" Version="10.1.1" />
<PackageVersion Include="Google.Apis.Compute.v1" Version="1.78.0.4327" />
<PackageVersion Include="Microsoft.AspNetCore.Antiforgery" Version="2.3.14" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR" Version="1.2.14" />
<PackageVersion Include="Microsoft.AspNetCore.Hosting" Version="2.3.14" />
<PackageVersion Include="Microsoft.AspNetCore.Razor" Version="2.3.14" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageVersion Include="Microsoft.AspNetCore.Razor.Language" Version="6.0.36" />
<PackageVersion Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.13" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.0" />
<PackageVersion Include="coverlet.collector" Version="10.1.0" />
<PackageVersion Include="IdentityModel.OidcClient" Version="6.0.0" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.23.0" />
<PackageVersion Include="xunit.v3" Version="3.2.2" />
@ -54,18 +56,16 @@
<PackageVersion Include="Anthropic.SDK" Version="5.10.0" />
<PackageVersion Include="Google.Apis.Calendar.v3" Version="1.77.0.4285" />
<PackageVersion Include="Magick.NET-Q8-AnyCPU" Version="15.0.0" />
<PackageVersion Include="MailKit" Version="4.18.1" />
<PackageVersion Include="Google.Apis.Calendar.v3" Version="1.78.0.4320" />
<PackageVersion Include="Magick.NET-Q8-AnyCPU" Version="15.1.0" />
<PackageVersion Include="MailKit" Version="5.0.0" />
<PackageVersion Include="MimeKit" Version="5.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
<PackageVersion Include="Microsoft.AspNetCore.StaticFiles" Version="2.3.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.StaticFiles" Version="2.3.14" />
<PackageVersion Include="Microsoft.Testing.Platform.MSBuild" Version="2.5.1" />
<PackageVersion Include="Microsoft.Testing.Platform.MSBuild" Version="2.5.3" />
<PackageVersion Include="MimeKit" Version="4.18.1" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageVersion Include="PayPalMerchantSDK" Version="2.16.250" />
<PackageVersion Include="pazof.rules" Version="1.1.3" />
<PackageVersion Include="RazorEngine.NetCore" Version="3.1.1" />

View file

@ -9,9 +9,13 @@ UNITTESTEXTRA= --long-running 8 --filter-trait Category=non-reg --filter-not-tra
all:
dotnet build --nologo
clean:
clean: clean-test-results
dotnet clean -c $(CONFIG)
clean-test-results:
rm -rf test-reports/*
brutal_clean:
@find -name "obj" -exec rm -rf {} \;
@find -name "bin" -exec rm -rf {} \;

View file

@ -5,6 +5,14 @@
Ce document décrit l'architecture cible, l'implementation native actuelle et
l'historique du transport direct.
La préférence de confidentialité est persistée et éditable dans le profil.
PostIt conserve aussi trois activations de contact locales (audio, audio-video,
messages prives) et les annonce pour chaque connexion ChatHub, y compris apres
reconnexion. Les modifications prennent effet a la prochaine connexion. Le
serveur filtre les invitations et les messages prives par appareil ;
une autre connexion peut avoir des preferences differentes et les anciens
clients sans annonce restent autorises pour la video et les messages. Les
invitations audio seules exigent en outre une annonce explicite de compatibilite
audio seul sur chaque appareil, pour ne pas solliciter les anciens clients.
La signalisation est intégrée au chat, désactivée par défaut. Une page d'appel
separee propose **WebRTC natif** et le transport direct VLC/SRTP sur Android et
Desktop Linux. WebRTC utilise ICE/STUN/TURN et le masquage IP impose par la
@ -12,7 +20,9 @@ politique serveur. Le mode SRTP direct ne masque pas les adresses IP et exige
que cette preference soit desactivee pour les deux participants. Les groupes
et les clients navigateur ne sont pas implementes.
Depuis le chat textuel, selectionner un membre present puis « Ouvrir l'appel »
prepare le pair sans demarrer les medias. Les invitations entrantes disposent
ou « Ouvrir l'appel audio » prepare le pair sans demarrer les medias. La page
WebRTC et le panneau SRTP proposent les deux modes : un utilisateur autorisant l'audio et la video
peut appeler en audio seul. Les invitations entrantes disposent
d'un bouton pour ouvrir cette meme page sans selection de membre. Passer du
chat a la page d'appel ne raccroche pas ; quitter la page d'appel termine les
medias. Un salon commun reste requis ; les capacites distantes et les appels
@ -31,7 +41,11 @@ La cible couvre :
- [WebRtcCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/WebRtcCallViewModel.cs)
conserve invitation/acceptation/fin via SignalR, sans demarrer la capture
avant consentement. Les SDP et candidats ICE utilisent les contrats existants.
avant consentement. En audio seul, seul le microphone est requis et ouvert :
aucune piste video ni permission camera n'est demandee. L'avatar du
correspondant, choisi dans les parametres PostIt, sert d'image fixe ; une
icone de remplacement est affichee si l'avatar est indisponible.
Les SDP et candidats ICE utilisent les contrats existants.
- [AndroidWebRtcMedia](../../src/PostIt/PostIt.Android/Services/AndroidWebRtcMedia.cs)
heberge deux surfaces natives. Le pont Java
[WebRtcPeer](../../src/PostIt/PostIt.Android/Services/WebRtcPeer.java) utilise
@ -55,13 +69,18 @@ La cible couvre :
Un SDP qui expose une adresse non relayee est refuse, pas corrige.
- Raccrocher, sortir de la page/salle, se deconnecter ou passer l'application
en arriere-plan annule aussi un demarrage natif en cours et libere les medias.
Un echec natif, une perte ICE ou 30 secondes sans progression audio/video
Un echec natif, une perte ICE ou 30 secondes sans progression des medias requis
terminent l'appel explicitement. Il n'y a pas d'ICE restart/renegociation
automatique ni de migration transparente d'un appel existant.
Le panneau WebRTC ne demande pas d'adresse ni de port RTP manuel. Le panneau
SRTP direct demande une adresse locale, un port UDP pair et le consentement au
partage d'adresse ; il requiert HTTPS pour proteger les cles de signalisation.
Son flux reste toujours audio-video H.264/AAC, sur Linux comme sur Android :
le mode « audio » remplace seulement la camera par l'avatar de l'emetteur,
repete en video pendant tout l'appel. Il ne supprime pas la piste video.
La capacite `SupportsLanAudioOnly`, distincte de celle de WebRTC, annonce
ce mode sans camera et exclut les anciens clients qui ne savent pas le lancer.
Les invitations sont dirigees vers le panneau correspondant, sans bascule
automatique entre transports. Sans masquage,
un consentement explicite au partage IP reste requis. Activer le masquage
@ -77,7 +96,8 @@ les Podcasts conservent leur chemin existant.
Tests Linux reels, sans compte ni camera, avec sources video/audio synthetiques,
decodage bidirectionnel, selection effective d'un relais coturn, controle des
adresses signalees et panne TURN sans repli :
adresses signalees et panne TURN sans repli. Les tests audio seuls verifient
egalement l'absence de piste et de trames video, en direct et via TURN :
```bash
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py -v
@ -171,6 +191,24 @@ L'implémentation est dans
Android utilise
[AndroidLanCallMedia](../../src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs)
avec les mêmes contrats et clés SRTP.
### Source video : camera ou avatar
« Appeler en audio » ne requiert aucune camera. Apres acceptation, PostIt
charge le propre avatar du participant depuis son profil, le normalise en
PNG 320 x 320 dans un fichier temporaire propre a l'appel et transmet cette
image avec son microphone via le meme moteur LibVLC. Le correspondant affiche
la video decodee, pas une image telechargee separement. Un avatar indisponible
termine explicitement l'appel, sans ouvrir la camera ni substituer une image
generique. Le fichier temporaire est supprime apres liberation des medias.
Le demultiplexeur `image` de LibVLC genere des trames pendant une duree
illimitee (`image-duration=-1`, 30 images/s), plutot qu'un clip de dix secondes.
L'horloge differe selon la source microphone : sur Linux, l'image en temps reel
pilote l'entree PulseAudio esclave ; pour le pipe ADTS Android, l'audio pilote
l'image esclave sur sa propre chronologie. Encodage H.264/AAC, reception video
et audio, controles de reception et chiffrement SRTP restent communs.
WebRTC conserve son implementation audio seule distincte, sans piste video.
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é.
@ -229,11 +267,18 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté.
- 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.
En mode avatar, seules les permissions microphone et notifications sont
demandees ; le service de premier plan active uniquement le type microphone.
Aucune camera ni surface d'encodage video Android n'est ouverte.
- 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.
En mode avatar, MediaRecorder fournit uniquement le microphone AAC/ADTS
dans un pipe ; LibVLC lit ce pipe et l'image, puis encode le flux audio-video
commun. La preview locale est l'avatar, le retour distant reste une surface
video LibVLC.
- 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
@ -289,6 +334,9 @@ l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet.
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.
Une regression avec preview a aussi observe des compteurs nuls malgre
les callbacks audio/video actifs ; son retest a reussi. Cette limite
intermittente des statistiques natives n'est pas corrigee par le mode avatar.
### Validation effectuée et restante
@ -300,6 +348,10 @@ synthétique fourni explicitement et de vrais sockets UDP de bouclage :
- 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.
- avatar fourni comme image a LibVLC, avec audio bidirectionnel et progression
audio/video apres douze secondes, en IPv4/IPv6, y compris avec mauvaise cle ;
- meme chemin avec une source PulseAudio synthetique isolee et avec un pipe
AAC/ADTS cadence simulant la capture microphone Android.
Les tests de signalisation couvrent consentement, sélection d'un seul
appareil, confidentialité, HTTPS, validation des endpoints et arrêt.
@ -320,14 +372,24 @@ dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
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.
Les tests avatar utilisent `POSTIT_TEST_IMAGE` et `POSTIT_TEST_AUDIO`
(fichier WAV d'au moins vingt secondes), ou `POSTIT_TEST_AUDIO_SOURCE`
(URI d'une source de test, notamment un moniteur PulseAudio isole).
Le test de pipe microphone utilise `POSTIT_TEST_AAC` (AAC/ADTS explicite d'au
moins vingt secondes). Ces tests n'ouvrent aucune camera.
Une activité **Debug uniquement**,
[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs),
[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/Fixtures/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.
L'extra chaine `avatar=true` selectionne l'image de test et le microphone
sans enumerer ni ouvrir de camera. Le chemin avatar Android est compile et
son entree AAC/ADTS est testee avec LibVLC sous Linux ; l'execution de cette
variante sur telephone reste a effectuer. Aucun deploiement automatique n'est
necessaire pour les tests Linux.
Pour la lancer sur un appareil de développement dont les permissions
ont été accordées, installer l'APK Debug et ses assemblies via

View file

@ -284,7 +284,9 @@ affichées dans la barre de statut, sans les masquer par une déduction MIME.
Les types `video/*` ouvrent `VideoPage` via `App.PushPageAsync` sur desktop.
Cette page contient un `LibVLCSharp.Avalonia.VideoView`, lecture/pause et
une action d'ouverture externe. Le lecteur et ses ressources natives sont
une action d'ouverture externe. Les commandes superposées servent aussi à la
lecture/pause du direct ; la position et la durée sont réservées au replay.
Android utilise des commandes natives équivalentes. Le lecteur et ses ressources natives sont
arrêtés et libérés à la sortie de la page. La lecture utilise directement
`new LibVLC()`, `new MediaPlayer(libVlc)` et `Play(media)`, sans options
spécifiques à Linux ni détection VAAPI/VDPAU. Le média est libéré après
@ -298,7 +300,7 @@ Après la navigation, `TryUpdateNativeControlPosition()` synchronise la surface
native à la priorité `Loaded`, une fois la mise en page effectuée :
les transformations de transition ne déclenchent pas de changement de `Bounds`.
Le rappel est ignoré si le lecteur a été libéré ou remplacé entre-temps.
Sur Android et Browser, où ce contrôle natif desktop n'est pas disponible,
Sur Android, une surface native remplace le contrôle desktop. Sur Browser,
les vidéos sont ouvertes dans le navigateur, comme les autres fichiers
(images liées, PDF, téléchargements) et les liens externes.
@ -402,6 +404,15 @@ pour les requetes.
Le document OpenAPI dedie est `/openapi/podcasts.json`, accessible en
developpement aux administrateurs comme les autres documents de l'API.
## PostIt.Desktop - Capture d'écran
### Pré-requis Sur Ubuntu / Debian
````bash
sudo apt install xdg-desktop-portal gstreamer1.0-tools gstreamer1.0-pipewire gstreamer1.0-plugins-good gstreamer1.0-plugins-ugly gstreamer1.0-vaapi
````
## Composition root (`App.axaml.cs`)
`App.OnFrameworkInitializationCompleted` est le seul endroit où

View file

@ -69,8 +69,8 @@ CRUD creent et manipulent leurs propres commandes par identifiant.
## Isolation des tests PostIt
L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans
parallelisme. Les tests `[AvaloniaFact]`/`[AvaloniaTheory]` reinitialisent le
runtime Avalonia entre tests ; des tests ordinaires utilisent aussi
parallelisme. Les tests UI reinitialisent l'application Avalonia entre
dispatchs ; des tests ordinaires utilisent aussi
`App.Current` et les delegates statiques de `Platform`. Leur execution
concurrente peut creer le dispatcher sur un autre thread ou utiliser une
application appartenant a un test headless en cours, avec une erreur de
@ -80,16 +80,31 @@ Conserver provisoirement cette isolation dans `Fixtures/TestApp.cs`. Les tests q
intentionnellement plusieurs operations concurrentes peuvent toujours le faire
dans leur propre methode ; les autres assemblees de tests ne sont pas affectees.
### Migration progressive vers une fixture UI
### Fixture UI partagee
La collection `[Collection(AvaloniaUiCollection.Name)]` fournit
Tous les tests UI de PostIt appartiennent a la collection
`[Collection(AvaloniaUiCollection.Name)]`, qui fournit
`AvaloniaUiFixture` par injection de constructeur. La fixture possede sa
session `HeadlessUnitTestSession`, initialise le runtime sur son thread UI et
arrete ce thread a la fin de la collection. Les tests migres utilisent `[Fact]`
ou `[Theory]`, pas `[AvaloniaFact]` : la fixture assure elle-meme le dispatch.
arrete ce thread a la fin de la collection. Les tests utilisent `[Fact]` ou
`[Theory]`, jamais `[AvaloniaFact]`/`[AvaloniaTheory]` ni
`HeadlessUnitTestSession.GetOrStartForAssembly` : ces deux mecanismes
demarreraient une seconde session headless concurrente de celle de la fixture.
`RunAsync` execute du code sur le thread UI. `WithWindowAsync` cree le contenu
et la fenetre sur ce thread, affiche la fenetre, effectue le layout, puis la
`RunAsync` execute du code sur le thread UI, avec un corps synchrone (`Action`)
ou asynchrone (`Func<Task>`) ; un test UI enveloppe tout son corps dans un seul
appel :
```csharp
[Fact]
public Task Settings_page_binds() => ui.RunAsync(() =>
{
var window = new Window { Content = new SettingsPage() };
// ...
}, TestContext.Current.CancellationToken);
```
`WithWindowAsync` cree le contenu et la fenetre sur ce thread, affiche la fenetre, effectue le layout, puis la
ferme et detache ses bindings en `finally`, meme si une assertion echoue :
```csharp
@ -109,13 +124,12 @@ public sealed class ExampleTests(AvaloniaUiFixture ui)
}
```
Le pilote est `SubscriptionsPageTests`. Le thread est conserve pour la
collection, mais l'application reste isolee **par dispatch** : conserver une
application unique des maintenant changerait l'isolation des anciens tests
Le thread est conserve pour la collection, mais l'application reste isolee
**par dispatch** : conserver une application unique changerait l'isolation des tests
et risquerait de partager navigation, services et preferences. Ne pas conserver
de controles entre dispatchs dans les tests metier. La protection globale
contre le parallelisme reste necessaire tant que les autres consommateurs
d'Avalonia et de l'etat statique ne sont pas migres.
contre le parallelisme reste necessaire : des tests ordinaires, hors de la
collection, utilisent encore `App.Current` et l'etat statique de `Platform`.
## EF Core en test

464
doc/video-edition.md Normal file
View file

@ -0,0 +1,464 @@
# Édition vidéo des directs et des replays
Document de travail à compléter ensemble. Les propositions ci-dessous ne sont
pas encore implémentées ; elles ne constituent pas toutes des décisions.
## Objectifs et décisions déjà prises
- Proposer **avant le début d'une émission** une option de raffinage de son
replay. Sans cette option, conserver la finalisation automatique actuelle.
- Après le direct, permettre à l'auteur de placer des marques temporelles,
d'apercevoir l'image correspondant à la position du curseur et de supprimer
des plages délimitées par ces marques.
- Réaliser les découpes à l'image près, avec réencodage si nécessaire.
- Commencer par **PostIt desktop** (lecteur LibVLC et contrôles Avalonia),
pour le raffinage comme pour la composition live. Android suivra, en
réutilisant le modèle, l'API et le traitement serveur.
- Conserver les segments originaux d'une émission raffinée, mais en réserver
l'accès à son auteur après la fin du direct.
- Envisager des génériques et incrustations **visibles pendant le direct**,
donc également présents dans l'enregistrement de ce direct. Les génériques
pourront utiliser du texte, une image ou une vidéo ; les incrustations
pourront comprendre du texte interprété en tant que Markdown, des images et
des vidéos existantes.
- Le générique de début, s'il est configuré, est joué jusqu'à sa fin
naturelle. Le générique de fin est joué à la fin programmée de l'émission ou
plus tôt, sur commande de l'auteur. L'audio des génériques et des vidéos
incrustées est mélangé au microphone.
- Une émission programmée se termine à son heure de fin, avec ou sans
générique de fin. L'auteur peut repousser cette fin autant de fois qu'il le
souhaite.
- Si un direct programmé s'interrompt avant son générique de fin, le serveur
diffuse un message « Direct interrompu » à la place de l'image, pendant
5 minutes par défaut. L'auteur peut régler cette durée, dans la limite de
15 minutes. Ce message est enregistré dans le replay. Si PostIt se reconnecte
avant la fin du délai, le direct reprend ; sinon, l'émission s'arrête
simplement, sans générique de fin. Un direct immédiat n'a pas ce
comportement.
- Les marques du raffinage servent de repères et deviennent des chapitres du
replay publié, sauf si l'auteur les supprime, une à une ou toutes à la fois.
Une marque située dans un passage supprimé disparaît. Elles permettent aussi
d'attacher au replay des incrustations à durée définie, non prévues avant
le direct.
- Une fois le MP4 publié, l'auteur peut à nouveau éditer le replay et le
remplacer, tant que les originaux sont conservés.
- Avant publication, les auditeurs voient l'émission avec l'état « Replay en
préparation ».
- Les brouillons et les originaux sont conservés 7 jours par défaut. L'auteur
peut choisir une durée comprise entre 0 et 365 jours ; avec 0, ils sont
supprimés dès la publication du MP4. Après publication, leur suppression
explicite est proposée.
Le raffinage du replay et la composition du direct sont deux fonctionnalités
distinctes. Une image ajoutée au direct est déjà intégrée aux segments reçus ;
elle n'est pas modifiable ou retirable lors du raffinage. En revanche, les
incrustations ajoutées pendant le raffinage ne concernent que le replay.
## Situation actuelle
PostIt capture et envoie des segments MPEG-TS au serveur. Lorsqu'un direct est
terminé, le serveur prépare automatiquement un MP4, actuellement par copie des
flux sans réencodage. Il conserve également les segments. Le lecteur de replay
utilise un MP4 navigable et des requêtes authentifiées par plages d'octets.
Le lecteur de direct utilise les segments et rejoint le flux près du direct.
Sur ordinateur, les contrôles du lecteur sont des contrôles Avalonia. Sur
Android, la surface vidéo et ses commandes sont natives. Sur desktop, le
curseur de replay met à jour l'image pendant son déplacement (voir le résultat
du prototype ci-dessous) ; la barre native Android fait de même, avec la même
coalescence des positions (voir « Éditeur Android »).
Les captures PostIt desktop et Android n'utilisent pas le même pipeline média.
### Hors périmètre : émissions OBS
Une émission diffusée avec OBS est entièrement gérée par OBS : scènes,
génériques, incrustations et contenu final. Le raffinage du replay et la
composition live décrits ici ne s'appliquent pas à ce pipeline. L'option de
raffinage n'est pas proposée pour une émission OBS, et son replay conserve la
finalisation automatique actuelle.
Références : [installation et fonctionnement des podcasts](../INSTALL.md),
[contrôles du replay](../src/PostIt/PostIt/Controls/ReplayControls.axaml.cs),
[capture PostIt](../src/PostIt/PostIt/Services/PodcastBroadcaster.cs),
[préparation MP4](../src/Yavsc.Server/Services/FfmpegPodcastReplayRemuxer.cs).
## 1. Raffinage du replay
### Parcours proposé
1. L'auteur active « Raffiner le replay avant publication » lors de la
préparation de l'émission ou avant le démarrage d'un direct immédiat
depuis PostIt.
2. À la fin du direct, le serveur prépare une source navigable privée et ne
publie pas encore le MP4 final. L'auteur peut revenir ultérieurement.
3. Dans un éditeur, l'auteur déplace le curseur et voit l'image correspondant
à la position demandée. Il ajoute des marques et leur aperçu.
4. Il choisit deux marques pour définir une plage à supprimer. Plusieurs
plages peuvent être sélectionnées, revues et retirées avant validation.
5. Il peut attacher à une marque une incrustation (texte Markdown, image ou
vidéo existante) avec une durée définie, en la prévisualisant.
6. L'auteur confirme la finalisation. Le serveur produit le MP4 à partir des
plages conservées et des incrustations, puis le rend accessible aux
auditeurs une fois prêt. Une finalisation sans modification doit aussi
être possible. Jusque-là, les auditeurs voient « Replay en préparation ».
7. Après publication, l'auteur peut rouvrir l'édition et publier une nouvelle
version qui remplace la précédente, tant que les originaux sont conservés.
L'éditeur doit distinguer clairement la source originale de la durée estimée
du résultat. Les marques et les plages sont exprimées dans le temps de la
**source originale**, même après ajout ou retrait d'une autre suppression.
Les modifications ne changent pas la source.
### Marques, aperçu et précision
Proposition pour une première version :
- curseur, temps courant et durée, avec commandes clavier accessibles ;
- image courante mise à jour pendant le déplacement, et état visible si l'image
demandée est encore en cours de chargement ;
- bouton d'ajout de marque, liste des marques ordonnées avec temps et miniature,
et possibilité de les supprimer une à une ou toutes à la fois ;
- sélection explicite d'une marque de début et d'une marque de fin, puis
affichage de la plage à supprimer ; possibilité d'annuler cette sélection ;
- plages non vides et comprises dans la durée réelle ; fusion des plages
qui se chevauchent ou se touchent. Refuser une sélection qui supprimerait
toute la vidéo et expliquer l'erreur ;
- marques nommables, utilisables comme repères de navigation et publiées
comme chapitres du replay. Leur temps est converti vers la durée du MP4
final ; une marque située dans une plage supprimée disparaît et ne produit
pas de chapitre ;
- incrustation attachée à une marque : contenu, durée, position et taille.
Signaler une incrustation dont la marque tombe dans une plage supprimée ou
dont la durée dépasse la vidéo conservée.
L'aperçu doit correspondre à la position effectivement décodée, pas simplement
à la valeur du curseur. Les demandes de recherche rapides doivent être
coalescées ou annulées pour éviter qu'une ancienne image remplace la plus
récente. Il faut vérifier le comportement du lecteur en pause, sur desktop et
Android, avant de choisir entre recherche vidéo directe et extraction
d'images ; ne pas supposer que la recherche actuelle est précise à l'image.
Les miniatures sont dérivées de la source privée et ne doivent pas apparaître
dans un cache public.
**Résultat du prototype desktop** : la recherche vidéo directe suffit.
LibVLC 3, avec sa recherche précise par défaut (sans `--input-fast-seek`),
affiche en pause l'image exacte demandée, y compris entre deux images clés et
en reculant. Un test natif le vérifie sur une vidéo synthétique dont chaque
image a une luminance distincte ; il échoue avec `--input-fast-seek`, qui
retombe sur l'image clé. Pendant le glissement, `ReplayControls` ne garde que
la dernière position demandée et l'envoie au lecteur au plus toutes les 60 ms ;
le relâchement applique la position finale. Restent à mesurer la réactivité
sur un long replay distant (requêtes par plages) et le comportement sur
Android.
Les limites de suppression sont définies sur les images réellement décodées ;
l'interface devra préciser quelle image est conservée à chaque limite. Le
traitement doit couper aussi l'audio, rétablir des horodatages continus et
éviter les désynchronisations. La durée estimée ne remplace pas une mesure du
MP4 final. La faisabilité et le coût doivent être mesurés sur des sources à
cadence variable, sans audio et avec audio.
**Résultat du prototype serveur** : `ReplayEditPlan` convertit les plages
supprimées en plages conservées : il fusionne les plages qui se chevauchent ou
se touchent, les borne à la durée, refuse les plages vides ou hors vidéo, la
suppression totale et plus de 200 plages. `FfmpegPodcastReplayEditor` ouvre la
source une fois par plage conservée, avec une recherche précise
(`-ss`/`-to` en entrée), puis assemble les plages avec le filtre `concat` et
réencode en H.264/AAC avec `+faststart`. Une plage [début, fin) conserve les
images dont l'horodatage est dans l'intervalle ; l'audio est coupé aux mêmes
temps. Seuls des nombres formatés et le chemin de la source, généré par le
serveur, sont transmis à FFmpeg.
- `trim` suivi de `setpts=PTS-STARTPTS` a été écarté : avec FFmpeg 7.1, la
durée de la dernière image est perdue et cette image disparaît du MP4.
- **Origine des temps** : LibVLC et le `-ss` d'entrée de FFmpeg mesurent tous
deux le temps depuis le début du format, c'est-à-dire du premier flux, et non
depuis la première image vidéo. Mesuré : avec une vidéo qui commence 0,52 s
après l'audio, LibVLC affiche à 1 500 ms l'image vidéo de 980 ms. Les marques
prises dans le lecteur sont donc directement utilisables par le serveur.
- Lorsque l'audio commence avant la vidéo (décalage d'encodage AAC, segments
live), chaque plage garde ce léger décalage. La vidéo finale peut ainsi
dépasser d'une image la somme des plages, sans désynchronisation.
- Le test serveur vérifie, sur une source synthétique avec audio, la liste
exacte des images conservées, les durées audio et vidéo, `faststart` et le
refus d'un résultat dépassant le quota, avec et sans décalage de départ.
- Restent à mesurer : le coût du réencodage sur un replay long, et les
sources à cadence variable issues des captures PostIt.
### États et persistance
Proposition, à adapter aux états déjà exposés par l'API :
| Étape | Comportement |
| --- | --- |
| Direct | Les auditeurs autorisés regardent le flux ; l'option de raffinage est déjà enregistrée. |
| Préparation de la source | Les segments sont terminés ; le serveur prépare une source navigable privée. |
| Brouillon | L'auteur peut prévisualiser, enregistrer ses marques, plages et incrustations, puis revenir plus tard. Les auditeurs voient « Replay en préparation ». |
| Finalisation | Une version immuable du montage est traitée en arrière-plan ; l'avancement ou l'état est visible. |
| Publié | Le MP4 final est accessible aux auditeurs ; les originaux restent privés. L'auteur peut rouvrir un brouillon. |
| Réédition | Le MP4 publié reste servi jusqu'à la publication atomique de la nouvelle version. |
| Échec | Une erreur explicite est visible ; source et brouillon restent disponibles pour correction ou nouvel essai. |
Le brouillon doit survivre à la fermeture de PostIt et au redémarrage du
serveur. Les opérations de sauvegarde et de finalisation doivent être
idempotentes ou détecter les conflits entre deux clients. Une finalisation ne
doit pas publier un fichier partiel : écrire dans un fichier temporaire,
vérifier le résultat, puis publier atomiquement. La reprise après interruption,
le nettoyage des fichiers temporaires et la suppression du podcast doivent être
définis pour chaque état.
Un brouillon et les originaux de l'émission sont conservés 7 jours par défaut ;
la durée est un réglage de l'auteur, de 0 à 365 jours. Une tâche de fond
supprime les brouillons et originaux expirés et prévient l'auteur dans
l'interface. Le délai court à partir de la fin du direct (ou de son
interruption), même si aucun replay n'a été publié. Avec une durée de 0 jour,
il commence à la première publication : les originaux sont supprimés dès la
publication du MP4. À l'expiration, les segments originaux, la source
`source.mp4` et le brouillon sont tous supprimés ; le MP4 publié est conservé
mais ne peut plus être réédité. Une émission jamais publiée à l'échéance est
supprimée entièrement. Après publication, PostIt propose explicitement de
supprimer le brouillon et les originaux.
#### Implémentation serveur du brouillon
Le brouillon privé est implémenté côté serveur, et son éditeur sur PostIt desktop.
- **Option** : `RefineReplay` est accepté à la création d'un direct immédiat
et à la préparation d'une émission programmée (colonne `LiveFlow.RefineReplay`).
Il est ignoré pour une émission OBS.
- **États** (`PodcastResponse.Draft.State`) : `Preparing` (remux des segments
vers une source privée `source.mp4`), `Ready` (éditable), `Publishing`
(rendu en file), `Failed` (préparation de la source en échec, relançable par
`POST {id}/replay/retry`). Tant qu'aucune version n'est publiée,
`Replay.State` reste `Pending` : les auditeurs voient « Replay en préparation ».
- **Routes réservées à l'auteur** :
- `PUT podcasts/{id}/draft` enregistre marques (500 au plus) et plages
supprimées (200 au plus) pour la révision courante ; une révision périmée
renvoie 409, des plages ou marques hors de la durée renvoient 400.
Les marques sont dédoublonnées et triées ; celles situées dans une plage
supprimée disparaissent. `Chapters` donne un titre (120 caractères au
plus, caractères de contrôle remplacés, titre vide ignoré) à une marque ;
son temps est ajouté aux marques s'il manque, et deux titres au même temps
renvoient 400. Le titre d'une marque supprimée disparaît avec elle.
- `POST podcasts/{id}/draft/publish` (202) met en file la publication d'une
révision ; répéter la demande pour la même révision est sans effet.
- `GET`/`HEAD podcasts/{id}/draft/source.mp4` sert la source navigable, avec
requêtes de plages.
- **Publication** : sans plage supprimée, la source est copiée ; sinon elle est
découpée comme dans le prototype, la dernière plage conservée restant ouverte
jusqu'à la fin réelle du média. Le quota est vérifié en déduisant le MP4
précédemment publié ; le résultat est écrit en fichier temporaire puis
déplacé atomiquement sur `replay.mp4`. Un échec laisse le brouillon `Ready`
avec son erreur et l'éventuel replay publié intact. Une réédition sert
l'ancien MP4 jusqu'au remplacement ; `PublishedRevision` indique la
révision publiée.
- **Reprise** : préparations et publications en file reprennent après un
redémarrage du serveur. Une émission raffinée interrompue prépare
automatiquement son brouillon.
- **Visibilité** : après le direct, playlist et segments d'une émission
raffinée renvoient 403 aux autres utilisateurs, et le brouillon n'est
jamais exposé dans les listes ou détails destinés aux auditeurs. Le site web
affiche « Replay en préparation » jusqu'à la publication.
- **Limite connue** : la durée éditable est celle déclarée par les segments
(arrondie à la milliseconde supérieure).
- **Rétention** : `RetentionDays` (0 à 365, 7 par défaut) accompagne
`RefineReplay` à la création ou à la préparation (colonne
`LiveFlow.RetentionDays`). `PodcastResponse.OriginalsExpireAt`, visible de
l'auteur seul, donne l'échéance : fin du direct + durée, ou date de
publication pour 0 jour. Le worker des replays applique l'échéance quand il
n'a rien d'autre à traiter, sans toucher une émission en préparation ou en
publication. Une émission publiée perd ses segments, sa source et son
brouillon (`OriginalsDeleted`, seul le MP4 reste compté dans le quota) ; une
émission jamais publiée est supprimée et son `LiveFlow` marqué supprimé.
`DELETE podcasts/{id}/originals` permet à l'auteur la même purge dès qu'un
MP4 est publié (409 sinon, sans effet si déjà faite).
- **Client d'API** : `PodcastApiClient` expose `CreateAsync(CreatePodcastRequest)`
(raffinage et conservation), `SaveDraftAsync`, `PublishDraftAsync`,
`DeleteOriginalsAsync` et `DownloadDraftSourceRangeAsync`, lecture
authentifiée par plages de 256 Kio au plus de la source du brouillon, avec
les mêmes contrôles que le MP4 publié. `PodcastReplayMediaInput` lit cette
source avec `draftSource: true` pour l'éditeur.
- **Interface PostIt** : la page podcasts propose « Raffiner le replay avant
publication » et la durée de conservation (0 à 365 jours) pour une émission
préparée comme pour un direct immédiat. Pour l'auteur, elle affiche l'état du
brouillon, l'échéance des originaux (avec l'avertissement de suppression d'une
émission jamais publiée), puis permet de publier le brouillon tel quel et,
après publication et confirmation, de supprimer les originaux. La lecture
choisit le MP4 publié dès qu'il existe ; sinon l'auteur lit les originaux et
les autres utilisateurs voient « Le replay est en cours de finalisation par
son auteur. ».
- **Éditeur desktop** : « Éditer les marques et plages » ouvre le brouillon
dans un lecteur qui lit la source privée. L'auteur avance image par image,
pose une marque au temps courant (Ctrl+M) avec une miniature locale, choisit
une marque de début et une de fin, et ajoute la plage aux suppressions. Les
plages sont fusionnées et bornées par `ReplayEditPlan` (désormais partagé
dans `Yavsc.Abstract`), comme sur le serveur ; une suppression totale est
refusée. Les marques contenues dans une plage sont signalées puis retirées
par le serveur à l'enregistrement. L'enregistrement envoie la révision lue ;
un conflit conserve les modifications locales et invite à recharger. La
publication enregistre d'abord les modifications en attente.
- **Chapitres** : seules les marques nommées deviennent des chapitres. Dans
l'éditeur, chaque marque a un champ « Titre du chapitre (facultatif) ». À la
publication, leurs temps sont convertis vers la durée du MP4 (cumul des
plages conservées) ; FFmpeg les intègre au MP4 par copie sans réencodage, à
partir d'un fichier de métadonnées où les titres sont échappés (ils ne sont
jamais passés en argument). Sans plage supprimée, ils sont ajoutés à une
copie de la source. `PodcastResponse.Chapters` expose les chapitres publiés
à tous les auditeurs ; le site web les affiche en boutons sous le lecteur du
MP4 et PostIt dans le lecteur du replay, chacun positionnant la lecture.
- **Éditeur Android** : la même page et le même modèle de vue s'ouvrent
depuis les podcasts Android, sur la surface vidéo native. En portrait, le
panneau des marques et des plages passe sous la vidéo et défile seul (la
surface native reste hors du défilement) ; en paysage, il reste à droite.
Pendant le glissement, la barre native n'envoie au lecteur que la dernière
position demandée, au plus toutes les 60 ms (`ReplayControlsState`, partagé
avec desktop), et applique la position finale au relâchement. L'instantané
LibVLC ne lit pas la sortie du décodage matériel : la surface Android
implémente `IVideoFrameCapture` et copie l'image affichée avec `PixelCopy`
(Android 7 et plus ; sans miniature avant), directement en mémoire.
- **Reste à faire** : miniatures des marques rechargées depuis le serveur
(elles ne sont créées qu'à la pose), validation sur de vrais médias et
essais de l'éditeur Android sur appareil (réactivité du glissement sur un
long replay distant, précision du pas image par image).
Une émission interrompue doit rester récupérable par son auteur. Lorsqu'un
direct programmé s'arrête après le délai « Direct interrompu », ou qu'un
direct immédiat est interrompu, une émission optée pour le raffinage passe en
préparation de la source puis en brouillon, comme à une fin normale. Les
originaux ne doivent pas devenir publics à cause d'une interruption ou d'un
redémarrage.
### Accès et sécurité
- Avant la fin du direct, conserver l'accès normal au flux live.
- Après la fin ou l'interruption d'une émission optée pour le raffinage,
réserver à l'auteur les segments originaux, la source navigable, les
miniatures et le brouillon. L'appliquer côté serveur à **toutes** les
routes de médias concernées, pas seulement à l'interface.
- Ne pas servir aux auditeurs le replay provisoire ni une ancienne version
non raffinée. Le MP4 final seul est publié après validation.
- Contrôler à nouveau l'identité et l'autorisation sur chaque requête,
y compris les requêtes de plages ; ne pas inclure de jeton dans les URL.
- Ne pas promettre l'effacement d'images déjà vues ou enregistrées par un
auditeur pendant le direct. La conservation des originaux signifie aussi
que l'auteur peut toujours les consulter.
Limiter les entrées, la taille et la durée des traitements, et ne jamais
construire une commande shell à partir des textes ou chemins fournis par les
utilisateurs. Vérifier les quotas et l'espace pour les segments, la source
privée, les fichiers temporaires et le MP4 final ; conserver les règles de
comptabilisation existantes ou documenter explicitement leur évolution.
## 2. Génériques et incrustations pendant le direct
### Besoin envisagé
- **Début** : si un générique de début est configuré, il est joué jusqu'à sa
fin naturelle avant le contenu principal.
- **Fin** : le générique de fin, s'il est configuré, est lancé :
- automatiquement à la fin programmée de l'émission ;
- plus tôt, par un bouton « Générique de fin », visible seulement si ce
générique est configuré.
Un bouton « Repousser la fin » décale la fin programmée de l'émission, et
donc le lancement automatique du générique s'il existe, d'une durée
configurable (5 minutes par défaut). Il est disponible même sans générique
de fin et peut être utilisé autant de fois que nécessaire.
- **Pendant** : afficher et retirer des textes Markdown, des images ou des
vidéos existantes par-dessus la vidéo, selon les commandes de l'auteur.
- **Audio** : l'audio d'un générique ou d'une vidéo incrustée est mélangé au
microphone.
- **Interruption** : si un direct programmé s'interrompt avant son générique
de fin, le serveur diffuse un message « Direct interrompu » à la place de
l'image, pendant une durée réglable par l'auteur, de 5 minutes par défaut et
15 minutes au plus. Ce message est enregistré dans le replay. Si PostIt se
reconnecte avant la fin du délai, le direct reprend ; sinon, l'émission
s'arrête simplement, sans générique de fin. Un direct immédiat
n'affiche pas ce message.
Les génériques et incrustations doivent être visibles par les auditeurs en
direct et enregistrés dans les segments. Leur rendu dans un futur MP4 découle
donc de la capture. L'interface devrait permettre une prévisualisation avant
diffusion et indiquer clairement ce qui est actuellement à l'antenne.
Pour le texte et les images, des propriétés telles que contenu, position,
taille, durée, transparence et ordre des couches sont envisageables. Pour
une vidéo de générique, il faudra définir formats acceptés, résolution,
cadence, présence d'audio et transition avec la caméra et le microphone.
Les médias fournis doivent être autorisés pour cet usage et contrôlés avant
leur lecture ; aucun service externe n'est requis par cette proposition.
### Pistes techniques à évaluer, non décidées
1. **Composition côté diffuseur PostIt** : intégrer les éléments avant
l'encodage sur chaque plateforme. Android dispose déjà d'un pipeline
graphique pour le flou, tandis que le chemin desktop est différent.
Vérifier prévisualisation, audio, consommation et continuité des segments.
2. **Composition côté serveur** : examiner une chaîne de traitement live en
aval de la réception des segments PostIt. Mesurer son impact sur la
latence, les ressources et la disponibilité ; ne pas l'adopter sans
prototype et limites explicites.
Le message « Direct interrompu » est produit par le serveur, puisque le
diffuseur a justement cessé d'émettre. Le serveur détecte l'absence de
nouveaux segments, génère des segments contenant le message et les insère
dans la playlist et l'enregistrement, avec des horodatages continus. À la
reconnexion de PostIt, les segments reçus reprennent la suite. Le seuil de
détection doit éviter de déclencher le message sur un simple retard réseau.
Les émissions OBS composent leurs propres scènes et ne sont pas concernées.
Une panne de composition ne doit pas produire silencieusement un direct
différent de celui annoncé à l'auteur.
## 3. Ordre de réalisation proposé
1. Valider le parcours, la politique de visibilité et les questions ci-dessous.
2. Prototyper sur desktop la navigation précise et l'aperçu pendant le
glissement (fait, voir « Résultat du prototype desktop »), puis
l'assemblage audio/vidéo précis côté serveur (fait, voir « Résultat du
prototype serveur »).
3. Ajouter le brouillon privé et ses états, les autorisations, les limites et
la reprise après incident (fait côté serveur, voir « Implémentation serveur
du brouillon »), puis l'éditeur de marques et plages desktop (fait).
4. Valider la finalisation sur de vrais médias synthétiques et conserver le
comportement existant pour les émissions sans raffinage.
5. Porter l'éditeur sur Android (surface native), en réutilisant l'API et le
traitement serveur (fait, essais sur appareil à mener).
6. Étudier la composition live, d'abord sur desktop puis sur Android, avant
d'engager les génériques et les incrustations.
## 4. Vérifications attendues
- Sans option de raffinage, le direct et le replay suivent le parcours actuel.
- Avec l'option, aucun auditeur autre que l'auteur ne peut lire les originaux
après le direct, y compris via playlist, segments, aperçu ou requêtes partielles.
- Les marques suivent correctement le curseur ; plusieurs suppressions,
chevauchements, limites et suppression totale sont traités explicitement.
- Sur une vidéo de test à images identifiables, la première et la dernière
image autour de chaque coupe, le son et la durée du MP4 sont vérifiés.
- La fermeture de l'application, une interruption réseau, un redémarrage
serveur, une erreur FFmpeg et un quota insuffisant ne publient pas de
fichier incomplet et ne perdent pas le brouillon.
- Une émission OBS n'expose pas l'option de raffinage et conserve la
finalisation automatique actuelle.
- Générique de fin lancé à l'heure programmée, sur commande et après
plusieurs « Repousser la fin » ; fin automatique sans générique.
- « Direct interrompu » produit par le serveur, borné à sa durée, présent dans
le replay, et remplacé par le direct si PostIt se reconnecte à temps.
- Les marques conservées deviennent des chapitres aux bons temps du MP4 final.
- Une réédition remplace le MP4 publié sans interruption de service ; les
brouillons et originaux expirés sont supprimés selon la durée choisie.
- Les tests couvrent d'abord desktop, puis la surface native Android lors du
portage ; les fonctionnalités live nécessitent aussi des essais sur appareil
et des mesures de latence et de charge.
## 5. Questions à préciser ensemble
Toutes les questions de conception posées jusqu'ici ont reçu une réponse.
Les points encore ouverts sont techniques et seront tranchés par les
prototypes : chaîne FFmpeg d'incrustation, détection d'une interruption côté
serveur et choix de composition live (PostIt ou serveur). L'aperçu à l'image
près sur desktop (recherche directe LibVLC) et la découpe côté serveur
(une entrée FFmpeg par plage conservée, puis `concat`) sont tranchés.

View file

@ -20,16 +20,17 @@
<PackageVersion Include="DirectShowLib" Version="1.0.0" />
<PackageVersion Include="LibVLCSharp.Avalonia" Version="3.10.2" />
<PackageVersion Include="LibVLCSharp" Version="3.10.2" />
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.95.2" />
<PackageVersion Include="VideoLAN.LibVLC.Android" Version="3.7.0-beta" />
<PackageVersion Include="Live.Avalonia" Version="1.4.2" />
<PackageVersion Include="Mapsui" Version="5.1.0" />
<PackageVersion Include="Mapsui.Avalonia12" Version="5.1.0" />
<PackageVersion Include="Mapsui" Version="5.2.0" />
<PackageVersion Include="Mapsui.Avalonia12" Version="5.2.0" />
<PackageVersion Include="MarkdownViewer.Core" Version="1.0.6-47" />
<PackageVersion Include="Markdown.Avalonia.Tight" Version="12.0.2" />
<PackageVersion Include="Material.Avalonia" Version="3.21.0" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Client" Version="11.0.0" />
<PackageVersion Include="Mono.Options" Version="6.12.0.148" />
<PackageVersion Include="PvRecorder" Version="1.2.13" />
<PackageVersion Include="Silk.NET.OpenAL" Version="2.23.0" />
@ -39,7 +40,7 @@
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Common" Version="2.11.0.1" />
<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" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="11.0.0" />
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.32.0" />
</ItemGroup>
</Project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Before After
Before After

View file

@ -48,7 +48,7 @@ public class MainActivity : AvaloniaMainActivity
{
if (Current is not { } activity || !IsForeground)
{
global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a foreground activity.");
global::Android.Util.Log.Warn(App.AppName, "Cannot show the keyboard without a foreground activity.");
return;
}
@ -57,12 +57,12 @@ public class MainActivity : AvaloniaMainActivity
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.");
global::Android.Util.Log.Warn(App.AppName, "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.");
global::Android.Util.Log.Warn(App.AppName, "The input method did not accept the keyboard activation request.");
});
}

View file

@ -24,7 +24,8 @@ internal static class PlatformBootstrap
Platform.BackgroundChatService = AndroidBackgroundChatService.Instance;
Platform.ShowSoftKeyboard = MainActivity.ShowSoftKeyboard;
Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync;
Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay);
Platform.CreateVideoSurface = (player, replay, playbackFailed) =>
new AndroidVideoSurface(player, replay, showControls: true, playbackFailed);
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
{
Platform.CreateWebRtcMedia = () => System.OperatingSystem.IsAndroidVersionAtLeast(26)

View file

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-android</TargetFramework>
<TargetFramework>net11.0-android</TargetFramework>
<SupportedOSPlatformVersion>23</SupportedOSPlatformVersion>
<Nullable>enable</Nullable>
<ApplicationId>fr.pschneider.postit</ApplicationId>

View file

@ -62,17 +62,12 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
{
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);
NotificationService.Instance.Post("SignalR reste actif ; demande d'autorisation des alertes impossible : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
}
}
@ -88,12 +83,6 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
Cancel(epoch);
Log.Error("PostIt.Chat", ex.ToString());
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
try
{
await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error))
.ConfigureAwait(false);
}
catch (Exception statusError) { Log.Error("PostIt.Chat", statusError.ToString()); }
if (ex is BackgroundChatException) throw;
throw new BackgroundChatException(BackgroundChatFailure.StartRejected,
"Android n'a pas pu demarrer le service de messagerie : " + ex.Message, ex);
@ -110,7 +99,7 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
catch (Exception ex)
{
Log.Error("PostIt.Chat", ex.ToString());
AndroidSettings.ReportError(api.Settings, ex.Message);
NotificationService.Instance.Post("Erreur lors de la desactivation du service de messagerie : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
return Task.CompletedTask;
}

View file

@ -2,6 +2,7 @@ using System;
using Android.Content;
using Android.OS;
using Android.Util;
using PostIt.Services;
using PostIt.ViewModels;
using AndroidSettingsIntent = Android.Provider.Settings;
@ -26,8 +27,7 @@ internal static class AndroidBatteryOptimization
if (MainActivity.Current is not { IsFinishing: false, IsDestroyed: false } activity
|| !MainActivity.IsForeground)
{
AndroidSettings.ReportError(settings,
"Ouvrez PostIt pour demander l'exemption d'optimisation batterie.");
NotificationService.Instance.Post("Ouvrez PostIt pour demander l'exemption d'optimisation batterie.", PostIt.Models.StatusSeverity.Error);
return;
}
activity.RunOnUiThread(() =>
@ -43,8 +43,7 @@ internal static class AndroidBatteryOptimization
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Battery optimization settings failed: " + ex);
AndroidSettings.ReportError(settings,
"Impossible d'ouvrir les parametres batterie Android : " + ex.Message);
NotificationService.Instance.Post("Impossible d'ouvrir les parametres batterie Android : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
});
}

View file

@ -4,6 +4,7 @@ using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using PostIt.Services;
using Yavsc.Abstract.Chat.Calls;
@ -19,6 +20,7 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
private readonly TaskCompletionSource _captureEnded = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Task _receiving;
private IPodcastCapture? _capture;
private Bitmap? _avatar;
private bool _disposed;
public Control LocalVideo => _local;
@ -70,6 +72,20 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
_ = ObserveCaptureAsync(_capture);
}
public async Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_capture != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
if (microphone != "microphone") throw new ArgumentException("Microphone Android invalide.", nameof(microphone));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
_avatar = new Bitmap(imagePath);
_local.Content = new Image { Source = _avatar, Height = 140 };
_capture = await AndroidPodcastCapture.StartAvatarCallAsync(
(fd, token) => _media.StartAvatarSendingAsync(remote, imagePath, $"fd/aac://{fd}", token),
_media.StopAsync, linked.Token);
_ = ObserveCaptureAsync(_capture);
}
private async Task ObserveCaptureAsync(IPodcastCapture capture)
{
try
@ -100,6 +116,7 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
finally
{
_local.Content = null;
_avatar?.Dispose();
try { await _media.StopAsync(); }
finally
{

View file

@ -120,16 +120,29 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
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,
internal static Task<IPodcastCapture> StartAvatarCallAsync(
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
StartCoreAsync(null, "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);
if (camera != null)
await RequestPermissionsAsync(microphone, ct);
else
{
var current = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
await PodcastPermissions.EnsureAsync(current, true, ct, camera: false);
if (!MainActivity.IsForeground)
throw new InvalidOperationException("Revenez dans PostIt pour demarrer le microphone.");
}
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.");
throw new InvalidOperationException("La capture 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); }
try { service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct, pipeOutput != null,
camera: camera != null); }
catch
{
CaptureGate.Release();
@ -140,7 +153,11 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
try
{
ct.ThrowIfCancellationRequested();
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
if (camera != null)
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
else
await capture.StartMicrophoneAsync(pipeOutput
?? throw new InvalidOperationException("Sortie microphone de l'appel indisponible."), ct);
return capture;
}
catch
@ -150,6 +167,42 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
}
}
private async Task StartMicrophoneAsync(Func<int, CancellationToken, Task> output, CancellationToken ct)
{
await _stopGate.WaitAsync(ct);
try
{
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
#pragma warning disable CS0618
_recorder = OperatingSystem.IsAndroidVersionAtLeast(31)
? new MediaRecorder(_context) : new MediaRecorder();
#pragma warning restore CS0618
_recorder.Error += OnRecorderError;
_recorder.SetAudioSource(AudioSource.Mic);
_recorder.SetOutputFormat(OutputFormat.AacAdts);
_recorder.SetAudioSamplingRate(48000);
_recorder.SetAudioChannels(1);
_recorder.SetAudioEncodingBitRate(96000);
_recorder.SetAudioEncoder(AudioEncoder.Aac);
var pipe = ParcelFileDescriptor.CreatePipe()
?? throw new IOException("Creation du canal microphone impossible.");
_readPipe = pipe[0];
_writePipe = pipe[1];
_recorder.SetOutputFile(_writePipe.FileDescriptor);
await Task.Run(_recorder.Prepare, ct);
await output(_readPipe.Fd, ct);
ct.ThrowIfCancellationRequested();
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
await Task.Run(_recorder.Start, ct);
_started = true;
_writePipe.Close();
_writePipe.Dispose();
_writePipe = null;
}
finally { _stopGate.Release(); }
}
private async Task StartNativeAsync(string cameraId, bool microphone,
Func<Stream, CancellationToken, Task>? output,
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)

View file

@ -28,7 +28,7 @@ internal static class AndroidServiceProvider
catch (Exception ex)
{
global::Android.Util.Log.Error("PostIt.Chat", ex.ToString());
AndroidSettings.ReportError(api.Settings, ex.Message);
NotificationService.Instance.Post(ex.Message, PostIt.Models.StatusSeverity.Error);
}
return System.Threading.Tasks.Task.CompletedTask;
};

View file

@ -25,14 +25,4 @@ internal static class AndroidSettings
});
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,4 +1,6 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Android;
using Avalonia.Controls;
@ -14,7 +16,8 @@ using Button = Android.Widget.Button;
namespace PostIt.Android.Services;
internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : NativeControlHost, IDisposable
internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool showControls = false, Action? playbackFailed = null)
: NativeControlHost, IDisposable, IVideoFrameCapture
{
private VideoView? _video;
private ReplayLayout? _layout;
@ -44,9 +47,9 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
{
if (!_disposed) _ready.TrySetResult();
}, Avalonia.Threading.DispatcherPriority.Loaded);
if (replay && !_disposed)
if ((replay || showControls) && !_disposed)
{
_layout = new ReplayLayout(activity, video, player);
_layout = new ReplayLayout(activity, video, player, replay, playbackFailed);
return new AndroidViewControlHandle(_layout);
}
return new AndroidViewControlHandle(video);
@ -71,6 +74,30 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
if (_video is not null) _video.MediaPlayer = null;
}
/// <summary>Copies the displayed frame with <see cref="PixelCopy"/>, which also reads hardware-decoded video.</summary>
public async Task<Avalonia.Media.Imaging.Bitmap?> CaptureFrameAsync(int width, CancellationToken ct)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(24) || _disposed
|| _video is not { Width: > 0, Height: > 0, Holder.Surface.IsValid: true } video) return null;
var height = Math.Max(1, (int)Math.Round(width * (double)video.Height / video.Width));
using var bitmap = global::Android.Graphics.Bitmap.CreateBitmap(width, height, global::Android.Graphics.Bitmap.Config.Argb8888!);
using var listener = new PixelCopyListener();
using var registration = ct.Register(() => listener.Result.TrySetCanceled(ct));
using var handler = new Handler(Looper.MainLooper!);
PixelCopy.Request(video, bitmap, listener, handler);
if (await listener.Result.Task != (int)PixelCopyResult.Success) return null;
using var png = new MemoryStream();
if (!bitmap.Compress(global::Android.Graphics.Bitmap.CompressFormat.Png!, 100, png)) return null;
png.Position = 0;
return new Avalonia.Media.Imaging.Bitmap(png);
}
private sealed class PixelCopyListener : Java.Lang.Object, PixelCopy.IOnPixelCopyFinishedListener
{
public TaskCompletionSource<int> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void OnPixelCopyFinished(int copyResult) => Result.TrySetResult(copyResult);
}
private void OnPlaybackChanged(object? sender, EventArgs e)
=> Avalonia.Threading.Dispatcher.UIThread.Post(UpdateScreenAwake);
@ -106,23 +133,28 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
private readonly ReplayControlsState _state = new();
private readonly Handler _handler = new(Looper.MainLooper!);
private readonly Java.Lang.Runnable _tick;
private readonly Java.Lang.Runnable _preview;
private readonly LinearLayout _bar;
private readonly Button _toggle;
private readonly SeekBar _seek;
private readonly TextView _time;
private readonly Action? _playbackFailed;
private bool _stopped;
public ReplayLayout(Context context, VideoView video, MediaPlayer player) : base(context)
public ReplayLayout(Context context, VideoView video, MediaPlayer player, bool replay, Action? playbackFailed) : base(context)
{
_player = player;
_playbackFailed = playbackFailed;
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" };
_toggle = new Button(context) { Text = "Pause", ContentDescription = "Lecture ou pause de la vidéo" };
_seek = new SeekBar(context) { Max = 10000, ContentDescription = "Position dans le replay" };
_time = new TextView(context);
_seek.Visibility = replay ? ViewStates.Visible : ViewStates.Gone;
_time.Visibility = replay ? ViewStates.Visible : ViewStates.Gone;
_time.SetTextColor(global::Android.Graphics.Color.White);
_bar.AddView(_toggle);
_bar.AddView(_seek, new LinearLayout.LayoutParams(0, LayoutParams.WrapContent, 1));
@ -133,6 +165,7 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
_seek.StopTrackingTouch += EndSeek;
_seek.ProgressChanged += ProgressChanged;
_tick = new Java.Lang.Runnable(Update);
_preview = new Java.Lang.Runnable(ApplyPreview);
_handler.Post(_tick);
}
@ -160,23 +193,41 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
private void Toggle(object? sender, EventArgs e)
{
if (_player.IsPlaying) _player.Pause();
else _player.Play();
else if (!_player.Play()) _playbackFailed?.Invoke();
_state.Show();
}
private void BeginSeek(object? sender, SeekBar.StartTrackingTouchEventArgs e) => _state.IsInteracting = true;
private void BeginSeek(object? sender, SeekBar.StartTrackingTouchEventArgs e)
{
_state.IsInteracting = true;
_handler.PostDelayed(_preview, 60);
}
private void EndSeek(object? sender, SeekBar.StopTrackingTouchEventArgs e)
{
_handler.RemoveCallbacks(_preview);
_state.EndPreview();
Seek();
_state.IsInteracting = false;
}
private void ProgressChanged(object? sender, SeekBar.ProgressChangedEventArgs e)
{
if (e.FromUser && !_state.IsInteracting) Seek();
if (!e.FromUser) return;
if (_state.IsInteracting) _state.RequestPreview(PositionOf(_seek.Progress));
else Seek();
}
/// <summary>Shows the frame under the thumb while dragging: only the latest position is sent, at most every 60 ms.</summary>
private void ApplyPreview()
{
if (_stopped || !_state.IsInteracting) return;
if (_player.IsSeekable && _state.TryTakePreview(out var time)) _player.Time = time;
_handler.PostDelayed(_preview, 60);
}
private long PositionOf(int progress) => (long)(_player.Length * (progress / 10000d));
private void Seek()
{
if (_player.IsSeekable) _player.Time = (long)(_player.Length * (_seek.Progress / 10000d));
if (_player.IsSeekable) _player.Time = PositionOf(_seek.Progress);
_state.Show();
}
@ -185,11 +236,13 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
if (_stopped) return;
_stopped = true;
_handler.RemoveCallbacks(_tick);
_handler.RemoveCallbacks(_preview);
_toggle.Click -= Toggle;
_seek.StartTrackingTouch -= BeginSeek;
_seek.StopTrackingTouch -= EndSeek;
_seek.ProgressChanged -= ProgressChanged;
_tick.Dispose();
_preview.Dispose();
_handler.Dispose();
}
}

View file

@ -37,10 +37,12 @@ internal sealed class AndroidWebRtcMedia : WebRtcNativeMedia
protected override async Task StartCoreAsync(WebRtcMediaConfiguration configuration, CancellationToken ct)
{
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activité Android indisponible.");
await PodcastPermissions.EnsureAsync(activity, microphone: true, ct, notifications: false);
await PodcastPermissions.EnsureAsync(activity, microphone: true, ct, notifications: false,
camera: !configuration.AudioOnly);
if (!MainActivity.IsForeground)
throw new InvalidOperationException("Revenez dans PostIt pour demarrer l'appel.");
await Task.WhenAll(_local.Ready, _remote.Ready).WaitAsync(TimeSpan.FromSeconds(10), ct);
if (!configuration.AudioOnly)
await Task.WhenAll(_local.Ready, _remote.Ready).WaitAsync(TimeSpan.FromSeconds(10), ct);
await SendCommandAsync(StartCommand(configuration), ct);
}

View file

@ -36,8 +36,7 @@ public sealed class ChatBootReceiver : BroadcastReceiver
if (api is not null)
{
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
AndroidSettings.ReportError(api.Settings,
"Android a refuse le redemarrage de la messagerie : " + ex.Message);
NotificationService.Instance.Post("Android a refuse le redemarrage de la messagerie : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
}
finally { pending?.Finish(); }

View file

@ -155,7 +155,7 @@ public sealed class ChatConnectionService : Service
{
if (!_destroyed && AndroidBackgroundChatService.IsCurrent(epoch)
&& ChatBootState.CanStart(_api))
s.SetActionStatus(NotificationPermission.IsGranted(this)
PostIt.Services.NotificationService.Instance.Post(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);
@ -219,7 +219,7 @@ public sealed class ChatConnectionService : Service
{
var builder = new NotificationCompat.Builder(this, MessageChannel);
builder.SetSmallIcon(Yavsc.Resource.Drawable.ic_stat_postit);
builder.SetContentTitle("PostIt");
builder.SetContentTitle(App.AppName);
builder.SetContentText(text);
builder.SetVisibility(NotificationCompat.VisibilityPrivate);
builder.SetContentIntent(OpenApp());
@ -254,7 +254,7 @@ public sealed class ChatConnectionService : Service
{
Log.Error("PostIt.Chat", ex.ToString());
_api?.QueueExceptionReport(ex, "PostIt.Android.Chat");
if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message);
if (_api is not null) PostIt.Services.NotificationService.Instance.Post(ex.Message, PostIt.Models.StatusSeverity.Error);
}
private static void CompleteStartup(string epoch)

View file

@ -22,7 +22,7 @@ public sealed class PodcastCaptureService : Service
internal AndroidPodcastCapture? Capture { get; set; }
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone,
CancellationToken ct, bool call = false)
CancellationToken ct, bool call = false, bool camera = true)
{
if (_pending is not null) throw new InvalidOperationException("Un direct Android est deja en cours.");
var pending = new TaskCompletionSource<PodcastCaptureService>(TaskCreationOptions.RunContinuationsAsynchronously);
@ -30,7 +30,7 @@ public sealed class PodcastCaptureService : Service
try
{
var intent = new Intent(activity, typeof(PodcastCaptureService))
.PutExtra("microphone", microphone).PutExtra("call", call);
.PutExtra("microphone", microphone).PutExtra("call", call).PutExtra("camera", camera);
activity.StartForegroundService(intent);
return await pending.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
}
@ -68,8 +68,10 @@ public sealed class PodcastCaptureService : Service
var builder = new NotificationCompat.Builder(this, Channel);
builder.SetSmallIcon(global::Android.Resource.Drawable.IcMenuCamera);
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."
var camera = intent?.GetBooleanExtra("camera", true) != false;
builder.SetContentTitle(call ? camera ? "Appel audio-video LAN/VPN" : "Appel audio LAN/VPN" : "Podcast en direct");
builder.SetContentText(call ? camera ? "Camera et microphone actifs. Toucher pour revenir a l'appel."
: "Avatar et microphone actifs. Toucher pour revenir a l'appel."
: "Camera active. Toucher pour revenir au direct.");
builder.SetContentIntent(open);
builder.SetOngoing(true);
@ -78,7 +80,7 @@ public sealed class PodcastCaptureService : Service
var type = (ForegroundService)0;
if (OperatingSystem.IsAndroidVersionAtLeast(30))
{
type = ForegroundService.TypeCamera;
if (camera) type = ForegroundService.TypeCamera;
if (intent?.GetBooleanExtra("microphone", false) == true) type |= ForegroundService.TypeMicrophone;
}
ServiceCompat.StartForeground(this, NotificationId, notification, (int)type);

View file

@ -17,9 +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, bool notifications = true)
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct,
bool notifications = true, bool camera = true)
{
var requested = new List<string> { Manifest.Permission.Camera };
var requested = new List<string>();
if (camera) requested.Add(Manifest.Permission.Camera);
if (microphone) requested.Add(Manifest.Permission.RecordAudio);
if (notifications && OperatingSystem.IsAndroidVersionAtLeast(33)) requested.Add(Manifest.Permission.PostNotifications);
var permissions = requested.ToArray();
@ -30,7 +32,10 @@ internal static class PodcastPermissions
_pending = pending;
ActivityCompat.RequestPermissions(activity, permissions, RequestCode);
if (!await pending.Task.WaitAsync(ct))
throw new UnauthorizedAccessException(notifications
throw new UnauthorizedAccessException(!camera && microphone
? notifications ? "Autorisez le microphone et les notifications pour l'appel."
: "Autorisez le microphone pour l'appel."
: notifications
? "Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser."
: microphone ? "Autorisez la camera et le microphone pour l'appel."
: "Autorisez la camera pour la previsualisation.");

View file

@ -123,27 +123,32 @@ public final class WebRtcPeer {
rtc.iceTransportsType = relay ? PeerConnection.IceTransportsType.RELAY : PeerConnection.IceTransportsType.ALL;
peer = factory.createPeerConnection(rtc, new Observer());
if (peer == null) throw new IllegalStateException("Cannot create native WebRTC peer");
Camera2Enumerator cameras = new Camera2Enumerator(context);
String camera = configuration.getString("camera");
capturer = cameras.createCapturer(camera, new CameraVideoCapturer.CameraEventsHandler() {
public void onCameraError(String message) { error("Camera: " + message); }
public void onCameraDisconnected() { if (!closed) error("Camera disconnected"); }
public void onCameraFreezed(String message) { error("Camera frozen: " + message); }
public void onCameraOpening(String name) {}
public void onFirstFrameAvailable() {}
public void onCameraClosed() { if (!closed) error("Camera closed unexpectedly"); }
});
if (capturer == null) throw new IllegalArgumentException("Camera unavailable");
texture = SurfaceTextureHelper.create("PostIt-WebRTC-camera", egl.getEglBaseContext());
videoSource = factory.createVideoSource(false);
capturer.initialize(texture, context, videoSource.getCapturerObserver());
videoTrack = factory.createVideoTrack("postit-video", videoSource);
videoTrack.addSink(local);
boolean audioOnly = configuration.optBoolean("audioOnly", false);
if (!audioOnly) {
Camera2Enumerator cameras = new Camera2Enumerator(context);
String camera = configuration.getString("camera");
capturer = cameras.createCapturer(camera, new CameraVideoCapturer.CameraEventsHandler() {
public void onCameraError(String message) { error("Camera: " + message); }
public void onCameraDisconnected() { if (!closed) error("Camera disconnected"); }
public void onCameraFreezed(String message) { error("Camera frozen: " + message); }
public void onCameraOpening(String name) {}
public void onFirstFrameAvailable() {}
public void onCameraClosed() { if (!closed) error("Camera closed unexpectedly"); }
});
if (capturer == null) throw new IllegalArgumentException("Camera unavailable");
texture = SurfaceTextureHelper.create("PostIt-WebRTC-camera", egl.getEglBaseContext());
videoSource = factory.createVideoSource(false);
capturer.initialize(texture, context, videoSource.getCapturerObserver());
videoTrack = factory.createVideoTrack("postit-video", videoSource);
videoTrack.addSink(local);
}
audioSource = factory.createAudioSource(new MediaConstraints());
audioTrack = factory.createAudioTrack("postit-audio", audioSource);
peer.addTrack(audioTrack, Collections.singletonList("postit"));
peer.addTrack(videoTrack, Collections.singletonList("postit"));
capturer.startCapture(640, 480, 24);
if (!audioOnly) {
peer.addTrack(videoTrack, Collections.singletonList("postit"));
capturer.startCapture(640, 480, 24);
}
if (configuration.getBoolean("caller")) peer.createOffer(new CreateDescription("offer"), new MediaConstraints());
}

View file

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
<PropertyGroup>
<TargetFramework>net10.0-browser</TargetFramework>
<TargetFramework>net11.0-browser</TargetFramework>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>

View file

@ -3,7 +3,7 @@
<OutputType>WinExe</OutputType>
<!--If you are willing to use platform-specific APIs, use conditional compilation.
See https://docs.avaloniaui.net/docs/guides/platforms/platform-specific-code/dotnet for more details.-->
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
@ -20,8 +20,9 @@
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
</PackageReference>
<PackageReference Include="Material.Avalonia" />
<PackageReference Include="Tmds.DBus.Protocol" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
</Project>
</Project>

View file

@ -2,6 +2,7 @@ using System;
using Avalonia;
using PostIt.Services;
using PostIt.CLIOptions;
using MonApp.Services.Linux;
namespace PostIt.Desktop;
@ -14,6 +15,13 @@ sealed class Program
public static void Main(string[] args)
{
Platform.IsPodcastSupported = true;
if (OperatingSystem.IsLinux())
{
Platform.IsScreenCaptureSupported = true;
Platform.CreateScreenCaptureService = () => new LinuxScreenCaptureService();
}
Platform.CreateBrowser = () => new CustomSchemeBrowser("postit://callback");
CLIOptionHandler.HandleArgs(args);

View file

@ -0,0 +1,506 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using PostIt.Interfaces;
using Tmds.DBus.Protocol;
namespace MonApp.Services.Linux;
[SupportedOSPlatform("linux")]
public class LinuxScreenCaptureService : IScreenCaptureService
{
private const string PortalBusName = "org.freedesktop.portal.Desktop";
private const string PortalObjectPath = "/org/freedesktop/portal/desktop";
private const string ScreenCastInterface = "org.freedesktop.portal.ScreenCast";
private const string RequestInterface = "org.freedesktop.portal.Request";
private DBusConnection? _dbusConnection;
private Process? _gstProcess;
private Task<string>? _gstErrorOutput;
private SafeFileHandle? _pipewireFd;
private CancellationTokenSource? _timerCts;
public bool IsRecording { get; private set; }
public event EventHandler<TimeSpan>? RecordingDurationUpdated;
[DllImport("libc", SetLastError = true)]
private static extern int fcntl(int fd, int cmd, int arg);
[DllImport("libc", SetLastError = true)]
private static extern int kill(int pid, int sig);
private const int F_GETFD = 1;
private const int F_SETFD = 2;
private const int FD_CLOEXEC = 1;
private const int SIGINT = 2;
public string? LatestRestoreToken { get; private set; }
private static void MakeFdInheritable(int fd)
{
int flags = fcntl(fd, F_GETFD, 0);
if (flags >= 0)
{
fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC);
}
}
public async Task StartRecordingAsync(CaptureOptions options, CancellationToken cancellationToken = default)
{
if (IsRecording) throw new InvalidOperationException("Un enregistrement est déjà en cours.");
LatestRestoreToken = options.RestoreToken;
// 1. Connexion D-Bus avec DBusConnection et DBusAddress
_dbusConnection = new DBusConnection(DBusAddress.Session!);
await _dbusConnection.ConnectAsync();
string senderName = _dbusConnection.UniqueName!.TrimStart(':').Replace('.', '_');
// 2. Création de la session ScreenCast
string sessionToken = $"monapp_sess_{Guid.NewGuid():N}";
string createToken = $"monapp_req_{Guid.NewGuid():N}";
string expectedCreatePath = $"/org/freedesktop/portal/desktop/request/{senderName}/{createToken}";
var createResponse = await SendPortalRequestAsync(
expectedCreatePath,
() => CallCreateSessionAsync(createToken, sessionToken),
cancellationToken
);
string sessionHandle = createResponse["session_handle"].GetString();
// 3. Sélection de la source
ScreenCaptureSource effectiveSource = options.TargetWindowHandle.HasValue
? ScreenCaptureSource.Window
: options.Source;
uint sourceType = effectiveSource switch
{
ScreenCaptureSource.Screen => 1u,
ScreenCaptureSource.Window => 2u,
ScreenCaptureSource.Prompt => 3u,
_ => throw new ArgumentOutOfRangeException(nameof(options), options.Source, "Source de capture inconnue.")
};
uint cursorMode = options.CaptureCursor ? 2u : 1u;
string selectToken = $"monapp_req_{Guid.NewGuid():N}";
string expectedSelectPath = $"/org/freedesktop/portal/desktop/request/{senderName}/{selectToken}";
await SendPortalRequestAsync(
expectedSelectPath,
() => CallSelectSourcesAsync(
sessionHandle,
selectToken,
sourceType,
cursorMode,
effectiveSource == ScreenCaptureSource.Screen ? LatestRestoreToken : null),
cancellationToken
);
// 4. Démarrage du flux (Popup système)
string startToken = $"monapp_req_{Guid.NewGuid():N}";
string expectedStartPath = $"/org/freedesktop/portal/desktop/request/{senderName}/{startToken}";
var startResponse = await SendPortalRequestAsync(
expectedStartPath,
() => CallStartAsync(sessionHandle, startToken),
cancellationToken
);
if (startResponse.TryGetValue("restore_token", out var tokenVariant))
{
LatestRestoreToken = tokenVariant.GetString();
}
var streams = startResponse["streams"];
if (streams.Count == 0)
throw new OperationCanceledException("Aucune source vidéo sélectionnée.");
uint pipewireNodeId = streams.GetItem(0).GetItem(0).GetUInt32();
// 5. Récupération du File Descriptor PipeWire
_pipewireFd = await CallOpenPipeWireRemoteAsync(sessionHandle);
int rawFd = _pipewireFd.DangerousGetHandle().ToInt32();
MakeFdInheritable(rawFd); // Indispensable pour que gst-launch-1.0 voie le flux PipeWire
await StartGStreamerPipelineAsync(rawFd, pipewireNodeId, options);
IsRecording = true;
StartDurationTimer();
}
private void StartDurationTimer()
{
_timerCts = new CancellationTokenSource();
var sw = Stopwatch.StartNew();
_ = Task.Run(async () =>
{
while (!_timerCts.Token.IsCancellationRequested)
{
RecordingDurationUpdated?.Invoke(this, sw.Elapsed);
await Task.Delay(500, _timerCts.Token);
}
});
}
private async Task StartGStreamerPipelineAsync(int fd, uint nodeId, CaptureOptions options)
{
// Pipeline GStreamer :
// pipewiresrc lit directement les textures GPU (DMA-BUF)
// videoconvert adapte le format pixel
// vaapih264enc (encodage matériel Intel/AMD) ou x264enc (fallback CPU)
string encoder = HasVaapiSupport()
? "vaapipostproc ! vaapih264enc rate-control=cbr bitrate=8000"
: "videoconvert ! video/x-raw,format=I420 ! x264enc speed-preset=ultrafast tune=zerolatency";
string args = $"-e pipewiresrc fd={fd} path={nodeId} do-timestamp=true keepalive-time=1000 ! " +
$"videorate ! video/x-raw,framerate={options.Fps}/1 ! " +
$"{encoder} ! h264parse ! queue ! mp4mux name=mux ! " +
$"filesink location=\"{EscapeGStreamerString(options.OutputFilePath)}\"";
if (options.CaptureAudio)
{
string audioDevice = await GetDefaultAudioMonitorAsync();
args += $" pulsesrc device=\"{EscapeGStreamerString(audioDevice)}\" do-timestamp=true ! " +
"queue ! audioconvert ! audioresample ! avenc_aac bitrate=192000 ! " +
"aacparse ! queue ! mux.";
}
_gstProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "gst-launch-1.0",
Arguments = args,
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true
}
};
_gstProcess.Start();
_gstErrorOutput = _gstProcess.StandardError.ReadToEndAsync();
}
private static string EscapeGStreamerString(string value) =>
value.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal);
private static async Task<string> GetDefaultAudioMonitorAsync()
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "pactl",
Arguments = "get-default-sink",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
try
{
process.Start();
Task<string> outputTask = process.StandardOutput.ReadToEndAsync();
Task<string> errorTask = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
string output = (await outputTask).Trim();
if (process.ExitCode != 0 || string.IsNullOrWhiteSpace(output))
{
string error = (await errorTask).Trim();
throw new InvalidOperationException(
$"Impossible de déterminer la sortie audio par défaut.{FormatProcessError(error)}");
}
return output + ".monitor";
}
catch (TimeoutException)
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
await process.WaitForExitAsync();
}
throw new InvalidOperationException("La détection de la sortie audio a expiré.");
}
finally
{
process.Dispose();
}
}
private static bool HasVaapiSupport()
{
try
{
var p = Process.Start(new ProcessStartInfo("gst-inspect-1.0", "vaapih264enc")
{
RedirectStandardOutput = true,
RedirectStandardError = true
});
p?.WaitForExit(1000);
return p?.ExitCode == 0;
}
catch
{
return false;
}
}
private Task CallStartAsync(string sessionHandle, string handleToken)
{
var writer = _dbusConnection!.GetMessageWriter();
writer.WriteMethodCallHeader(
destination: PortalBusName,
path: PortalObjectPath,
@interface: ScreenCastInterface,
member: "Start",
signature: "osa{sv}"
);
writer.WriteObjectPath(sessionHandle);
writer.WriteString(""); // Parent window identifier (optionnel)
writer.WriteDictionary(new Dictionary<string, VariantValue>
{
["handle_token"] = VariantValue.String(handleToken)
});
return _dbusConnection.CallMethodAsync(writer.CreateMessage());
}
public async Task StopRecordingAsync()
{
if (!IsRecording && _gstProcess is null) return;
IsRecording = false;
_timerCts?.Cancel();
_timerCts?.Dispose();
_timerCts = null;
Process? process = _gstProcess;
if (process is null) return;
string errorOutput;
int exitCode;
try
{
if (!process.HasExited && kill(process.Id, SIGINT) != 0)
{
throw new InvalidOperationException(
$"Impossible d'envoyer SIGINT à GStreamer (errno {Marshal.GetLastPInvokeError()}).");
}
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10));
errorOutput = _gstErrorOutput is null ? string.Empty : await _gstErrorOutput;
exitCode = process.ExitCode;
}
catch (TimeoutException)
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
await process.WaitForExitAsync();
}
throw new InvalidOperationException(
"GStreamer n'a pas finalisé le fichier MP4 dans les dix secondes.");
}
catch
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
await process.WaitForExitAsync();
}
throw;
}
finally
{
_pipewireFd?.Dispose();
_pipewireFd = null;
_dbusConnection?.Dispose();
_dbusConnection = null;
process.Dispose();
_gstProcess = null;
_gstErrorOutput = null;
}
if (exitCode != 0)
{
throw new InvalidOperationException(
$"GStreamer s'est arrêté avec le code {exitCode}.{FormatProcessError(errorOutput)}");
}
}
private static string FormatProcessError(string errorOutput) =>
string.IsNullOrWhiteSpace(errorOutput) ? string.Empty : $" Détail : {errorOutput.Trim()}";
private async Task<Dictionary<string, VariantValue>> SendPortalRequestAsync(
string expectedRequestPath,
Func<Task> dbusCall,
CancellationToken ct)
{
var tcs = new TaskCompletionSource<Dictionary<string, VariantValue>>(TaskCreationOptions.RunContinuationsAsynchronously);
var rule = new MatchRule
{
Type = MessageType.Signal,
Interface = RequestInterface,
Member = "Response",
Path = expectedRequestPath
};
using var observer = await _dbusConnection!.AddMatchAsync(
rule,
static (Message message, object? state) =>
{
var reader = message.GetBodyReader();
uint responseCode = reader.ReadUInt32();
var results = reader.ReadDictionaryOfStringToVariantValue();
return (responseCode, results);
},
(Notification<(uint responseCode, Dictionary<string, VariantValue> results)> notification) =>
{
if (notification.HasValue)
{
var (code, results) = notification.Value;
if (code == 0)
tcs.TrySetResult(results);
else
tcs.TrySetException(new OperationCanceledException($"Requête annulée (code {code})."));
}
else if (notification.CompletionReason != null)
{
tcs.TrySetException(new OperationCanceledException($"Requête annulée ({notification.CompletionReason})."));
}
}
);
await dbusCall();
using (ct.Register(() => tcs.TrySetCanceled()))
{
return await tcs.Task;
}
}
// ... (Les méthodes CallCreateSessionAsync, CallSelectSourcesAsync, CallStartAsync, restent identiques à la réponse précédente)
private Task CallCreateSessionAsync(string handleToken, string sessionToken)
{
using var writer = _dbusConnection!.GetMessageWriter();
writer.WriteMethodCallHeader(
destination: PortalBusName,
path: PortalObjectPath,
@interface: ScreenCastInterface,
member: "CreateSession",
signature: "a{sv}"
);
writer.WriteDictionary(new Dictionary<string, VariantValue>
{
["handle_token"] = VariantValue.String(handleToken),
["session_handle_token"] = VariantValue.String(sessionToken)
});
return _dbusConnection.CallMethodAsync(writer.CreateMessage());
}
private Task CallSelectSourcesAsync(
string sessionHandle,
string handleToken,
uint types,
uint cursorMode,
string? restoreToken)
{
using var writer = _dbusConnection!.GetMessageWriter();
writer.WriteMethodCallHeader(
destination: PortalBusName,
path: PortalObjectPath,
@interface: ScreenCastInterface,
member: "SelectSources",
signature: "oa{sv}"
);
var optionsDict = new Dictionary<string, VariantValue>
{
["handle_token"] = VariantValue.String(handleToken),
["types"] = VariantValue.UInt32(types),
["cursor_mode"] = VariantValue.UInt32(cursorMode),
["multiple"] = VariantValue.Bool(false),
// 0 = Ne pas persister
// 1 = Persister tant que l'application reste ouverte
// 2 = Persister de façon permanente (jusqu'à révocation explicite)
["persist_mode"] = VariantValue.UInt32(2)
};
if (!string.IsNullOrEmpty(restoreToken))
{
optionsDict["restore_token"] = VariantValue.String(restoreToken);
}
writer.WriteObjectPath(sessionHandle);
writer.WriteDictionary(optionsDict);
return _dbusConnection.CallMethodAsync(writer.CreateMessage());
}
private Task<SafeFileHandle> CallOpenPipeWireRemoteAsync(string sessionHandle)
{
using var writer = _dbusConnection!.GetMessageWriter();
writer.WriteMethodCallHeader(
destination: PortalBusName,
path: PortalObjectPath,
@interface: ScreenCastInterface,
member: "OpenPipeWireRemote",
signature: "oa{sv}"
);
writer.WriteObjectPath(sessionHandle);
writer.WriteDictionary(new Dictionary<string, VariantValue>());
return _dbusConnection.CallMethodAsync(
writer.CreateMessage(),
static (Message reply, object? state) => reply.GetBodyReader().ReadHandle<SafeFileHandle>()!
);
}
public void Dispose()
{
_timerCts?.Cancel();
_timerCts?.Dispose();
if (_gstProcess is not null)
{
if (!_gstProcess.HasExited)
{
kill(_gstProcess.Id, SIGINT);
if (!_gstProcess.WaitForExit(10_000))
{
_gstProcess.Kill(entireProcessTree: true);
_gstProcess.WaitForExit();
}
}
_gstProcess.Dispose();
}
_pipewireFd?.Dispose();
_dbusConnection?.Dispose();
}
}

View file

@ -1,6 +1,5 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using PostIt.ViewModels;
using PostIt.Views;
@ -8,10 +7,12 @@ using PostIt.Views;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class ActivityNavigationTests
[Collection(AvaloniaUiCollection.Name)]
public class ActivityNavigationTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Activity_recreation_restores_fresh_pages_and_back_navigation()
[Fact]
public Task Activity_recreation_restores_fresh_pages_and_back_navigation()
=> ui.RunAsync(async () =>
{
var app = Assert.IsType<App>(Application.Current);
var previousView = app.View;
@ -57,5 +58,5 @@ public class ActivityNavigationTests
window.Close();
app.AttachMainWindow(previousView ?? new MainView());
}
}
}, TestContext.Current.CancellationToken);
}

View file

@ -1,6 +1,5 @@
using Avalonia;
using Avalonia.Headless.XUnit;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Services;
using PostIt.ViewModels;
@ -29,7 +28,8 @@ namespace PostIt.Tests;
/// any async command before asserting.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class AddCircleMemberDialogTests
[Collection(AvaloniaUiCollection.Name)]
public class AddCircleMemberDialogTests(AvaloniaUiFixture ui)
{
/// <summary>
/// Stand-in <see cref="IUserDirectory"/> that returns an
@ -120,8 +120,9 @@ public class AddCircleMemberDialogTests
/// Click the "Fermer" button on the dialog and assert the
/// nav stack shrinks by exactly one.
/// </summary>
[AvaloniaFact]
public async Task Close_button_pops_dialog_off_nav_stack()
[Fact]
public Task Close_button_pops_dialog_off_nav_stack()
=> ui.RunAsync(async () =>
{
// Arrange: stack starts at 2 (CirclesPage + dialog).
var context = await Mount();
@ -149,5 +150,5 @@ public class AddCircleMemberDialogTests
Assert.True(window.NavRoot.NavigationStack.Count == stackBefore - 1,
$"Click on 'Fermer' must shrink the nav stack by one. Before: {stackBefore}, after: {window.NavRoot.NavigationStack.Count}.");
Assert.IsType<CirclesPage>(window.NavRoot.NavigationStack[^1]);
}
}, TestContext.Current.CancellationToken);
}

View file

@ -1,6 +1,5 @@
using System.Text.Json;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using Avalonia.VisualTree;
using PostIt.Services;
@ -14,7 +13,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationAccessTests
[Collection(AvaloniaUiCollection.Name)]
public class AdministrationAccessTests(AvaloniaUiFixture ui)
{
[Fact]
public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes()
@ -119,8 +119,9 @@ public class AdministrationAccessTests
Assert.Equal(1, vm.UserPage);
}
[AvaloniaFact]
public async Task Administration_displays_both_tabs_and_selected_user_usage()
[Fact]
public Task Administration_displays_both_tabs_and_selected_user_usage()
=> ui.RunAsync(async () =>
{
await using var api = new ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = api };
@ -149,7 +150,7 @@ public class AdministrationAccessTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Administration_denies_moderators_without_requesting_private_data()
@ -220,8 +221,9 @@ public class AdministrationAccessTests
Assert.True(vm.IsProfileLoaded);
}
[AvaloniaFact]
public async Task My_profile_privacy_checkbox_is_two_way_and_disabled_before_loading()
[Fact]
public Task My_profile_privacy_checkbox_is_two_way_and_disabled_before_loading()
=> ui.RunAsync(async () =>
{
await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = true };
var vm = new UserProfilePageViewModel(api);
@ -246,7 +248,7 @@ public class AdministrationAccessTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Profile_read_failure_prevents_saving_a_default_call_privacy_preference()

View file

@ -2,7 +2,6 @@ using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using Avalonia.VisualTree;
using PostIt.ViewModels;
@ -13,7 +12,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationToolsTests
[Collection(AvaloniaUiCollection.Name)]
public class AdministrationToolsTests(AvaloniaUiFixture ui)
{
[Fact]
public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout()
@ -40,10 +40,11 @@ public class AdministrationToolsTests
Assert.Empty(vm.PaymentPurgeReport);
}
[AvaloniaTheory]
[Theory]
[InlineData(400, 800)]
[InlineData(800, 400)]
public void All_administration_tabs_and_typed_forms_are_accessible_in_portrait_and_landscape(int width, int height)
public Task All_administration_tabs_and_typed_forms_are_accessible_in_portrait_and_landscape(int width, int height)
=> ui.RunAsync(() =>
{
var vm = new AdministrationPageViewModel();
var page = new AdministrationPage { DataContext = vm };
@ -71,12 +72,12 @@ public class AdministrationToolsTests
box => box.DataContext is AdministrationFieldViewModel field && field.Name == "ToSend");
}
finally { window.Close(); }
}
}, TestContext.Current.CancellationToken);
[Fact]
public void Client_form_retains_every_scalar_field_and_validates_numeric_input()
{
var settings = new ClientSettings { ClientId = "postit", ClientName = "PostIt", AccessTokenLifetime = 900,
var settings = new ClientSettings { ClientId = "postit", ClientName = App.AppName, AccessTokenLifetime = 900,
ConsentLifetime = null, RequireConsent = true, PairWiseSubjectSalt = null };
var fields = AdministrationFieldViewModel.From(settings);
Assert.Equal(typeof(ClientSettings).GetProperties().Length, fields.Count);

View file

@ -3,7 +3,6 @@ using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Headless;
using Avalonia.Headless.XUnit;
using Avalonia.Input;
using Avalonia.Logging;
using Avalonia.Threading;
@ -22,7 +21,8 @@ using SkiaSharp;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BlogReaderTests
[Collection(AvaloniaUiCollection.Name)]
public class BlogReaderTests(AvaloniaUiFixture ui)
{
private static BlogPostDto Post(string article = "Texte du billet.") => new()
{
@ -106,8 +106,9 @@ public class BlogReaderTests
Assert.Equal(expected, vm.CanOpenExternal);
}
[AvaloniaFact]
public async Task Reader_hides_editor_and_wires_hyperlinks_to_the_application()
[Fact]
public Task Reader_hides_editor_and_wires_hyperlinks_to_the_application()
=> ui.RunAsync(async () =>
{
var vm = CreateViewModel();
await vm.InitializeAsync();
@ -138,16 +139,17 @@ public class BlogReaderTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(360, 800, false)]
[InlineData(1000, 420, true)]
[InlineData(1000, 280, true)]
[InlineData(600, 600, true)]
[InlineData(599, 600, false)]
[InlineData(601, 600, true)]
public async Task Blog_layout_uses_columns_from_the_square_window_threshold(int width, int height, bool wide)
public Task Blog_layout_uses_columns_from_the_square_window_threshold(int width, int height, bool wide)
=> ui.RunAsync(async () =>
{
var vm = CreateViewModel();
await vm.InitializeAsync();
@ -170,7 +172,7 @@ public class BlogReaderTests
var list = page.FindControl<Border>("PostsListBorder")!;
var splitter = page.FindControl<GridSplitter>("PostsSplitter")!;
Assert.Equal(wide ? GridResizeDirection.Columns : GridResizeDirection.Rows, splitter.ResizeDirection);
Assert.Equal(wide ? 36d : (double?)null, NavigationPage.GetBarHeightOverride(page));
Assert.Null(NavigationPage.GetBarHeightOverride(page));
Assert.True(nav.IsBackButtonEffectivelyVisible);
Assert.True(reader.Bounds.Width > 0 && reader.Bounds.Height > 0);
Assert.True(list.Bounds.Width > 0 && list.Bounds.Height > 0);
@ -179,8 +181,8 @@ public class BlogReaderTests
Assert.True(reader.Bounds.Right <= list.Bounds.Left);
Assert.Equal(2, Grid.GetColumn(page.BlogsHeaderPanel));
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);
Assert.Equal(page.MainGrid.Bounds.Height - reader.Margin.Bottom, reader.Bounds.Bottom);
Assert.True(page.TranslatePoint(new Point(), nav)!.Value.Y > 0);
}
else
{
@ -226,56 +228,12 @@ public class BlogReaderTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Resizing_between_portrait_and_landscape_preserves_the_editor_and_draft()
{
var vm = CreateViewModel();
await vm.InitializeAsync();
vm.SelectedPost = Post();
vm.EditPostCommand.Execute(null);
vm.DraftArticle = "Brouillon conservé pendant le redimensionnement.";
var document = vm.DraftArticleDocument;
var page = new BlogsPage { DataContext = vm };
var editor = page.FindControl<Grid>("PostEditor")!;
var nav = new NavigationPage();
await nav.PushAsync(page);
var window = new Window { Width = 360, Height = 800, Content = nav };
try
{
window.Show();
foreach (var size in new[] { new Size(360, 800), new Size(1000, 420), new Size(600, 600), new Size(599, 600), new Size(360, 800) })
{
window.Width = size.Width;
window.Height = size.Height;
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
AvaloniaHeadlessPlatform.ForceRenderTimerTick();
var wide = size.Width >= size.Height;
Assert.Equal(wide ? 0 : 4, Grid.GetRow(editor));
Assert.Equal(wide ? 3 : 1, Grid.GetRowSpan(editor));
Assert.Equal(wide ? 36d : (double?)null, NavigationPage.GetBarHeightOverride(page));
Assert.Same(editor, page.FindControl<Grid>("PostEditor"));
Assert.True(editor.IsVisible);
Assert.False(page.FindControl<Grid>("PostReader")!.IsVisible);
Assert.True(vm.IsEditing);
Assert.True(vm.IsDraftModified);
Assert.Equal("Brouillon conservé pendant le redimensionnement.", vm.DraftArticle);
Assert.Same(document, vm.DraftArticleDocument);
Assert.Equal(42, vm.SelectedPost!.Id);
Assert.True(editor.Bounds.Width > 0 && editor.Bounds.Height > 0);
}
}
finally
{
window.Close();
}
}
[AvaloniaFact]
public async Task Image_http_failure_is_logged_with_its_url_and_is_not_swallowed()
[Fact]
public Task Image_http_failure_is_logged_with_its_url_and_is_not_swallowed()
=> ui.RunAsync(async () =>
{
const string url = "https://org.example.test/files/paul/absent.jpg";
using var client = new HttpClient(new BlogResourceServiceTests.StubHandler(
@ -294,7 +252,7 @@ public class BlogReaderTests
{
Logger.Sink = previousSink;
}
}
}, TestContext.Current.CancellationToken);
private sealed class RecordingLogSink : ILogSink
{
@ -306,8 +264,9 @@ public class BlogReaderTests
=> Entries.Add((area, values));
}
[AvaloniaFact]
public async Task Long_reading_content_scrolls_and_clears_when_selection_is_removed()
[Fact]
public Task Long_reading_content_scrolls_and_clears_when_selection_is_removed()
=> ui.RunAsync(async () =>
{
var vm = CreateViewModel();
await vm.InitializeAsync();
@ -335,7 +294,7 @@ public class BlogReaderTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[Theory]
[InlineData("https://yavsc.pschneider.fr/files/paul/blogs/14/IMG-20260923-WA0001.jpg")]
@ -397,8 +356,9 @@ public class BlogReaderTests
}
}
[AvaloniaFact]
public async Task Clicking_a_user_video_pushes_a_dedicated_video_viewmodel()
[Fact]
public Task Clicking_a_user_video_pushes_a_dedicated_video_viewmodel()
=> ui.RunAsync(async () =>
{
using var client = new HttpClient(new BlogResourceServiceTests.StubHandler(request =>
{
@ -433,19 +393,21 @@ public class BlogReaderTests
{
app.DataTemplates.Remove(template);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public void Video_viewmodel_resolves_to_the_shared_page_with_a_platform_video_surface_slot()
[Fact]
public Task Video_viewmodel_resolves_to_the_shared_page_with_a_platform_video_surface_slot()
=> ui.RunAsync(() =>
{
var vm = new VideoPageViewModel(new Uri("https://org.example.test/files/paul/clip.mp4"), "video/mp4");
var page = Assert.IsType<VideoPage>(new ViewLocator().Build(vm));
Assert.NotNull(page.FindControl<ContentControl>("VideoSurface"));
Assert.NotNull(page.FindControl<Button>("PlayButton"));
}
Assert.Null(page.FindControl<Button>("PlayButton"));
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Video_page_observes_platform_lifecycle_only_while_navigated()
[Fact]
public Task Video_page_observes_platform_lifecycle_only_while_navigated()
=> ui.RunAsync(async () =>
{
var nav = new NavigationPage();
await nav.PushAsync(new ContentPage());
@ -454,14 +416,14 @@ public class BlogReaderTests
var status = page.FindControl<TextBlock>("PlaybackStatus")!;
Platform.SuspendPlayback();
Assert.Equal("Lecture suspendue.", status.Text);
Assert.False(page.FindControl<Button>("PlayButton")!.IsEnabled);
Assert.Null(page.FindControl<ContentControl>("VideoSurface")!.Content);
Platform.ResumePlayback();
Assert.Null(page.FindControl<ContentControl>("VideoSurface")!.Content);
await nav.PopAsync();
status.Text = "No longer active";
Platform.SuspendPlayback();
Assert.Equal("No longer active", status.Text);
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Broken_resource_reports_an_error_and_releases_busy_state()

View file

@ -1,5 +1,5 @@
using Avalonia.Headless.XUnit;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using PostIt.Views.Chat;
using PostIt.Services;
using PostIt.ViewModels;
@ -9,12 +9,14 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CallTransportRoutingTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class CallTransportRoutingTests(AvaloniaUiFixture ui)
{
[AvaloniaTheory]
[Theory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Incoming_calls_are_handled_only_by_the_matching_transport(string transport)
public Task Incoming_calls_are_handled_only_by_the_matching_transport(string transport)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
@ -34,10 +36,66 @@ public sealed class CallTransportRoutingTests
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Unknown_transport_is_rejected_once_without_starting_either_call()
[Fact]
public Task Audio_page_keeps_srtp_avatar_call_and_received_video_available_without_camera_controls()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling, loadAvatar: (_, _) => Task.FromResult<Bitmap?>(null))
{
RemoteVideo = new Border()
};
var chat = new ChatViewModel(settings: new Settings()) { LanCall = lan, IsConnected = true };
var page = new CallPage { DataContext = new AudioCallPageViewModel(chat) };
var window = new Window { Content = page };
try
{
window.Show();
Assert.True(page.FindControl<StackPanel>("LanCallPanel")!.IsVisible);
Assert.False(page.FindControl<ComboBox>("LanCamera")!.IsVisible);
Assert.False(page.FindControl<Button>("LanVideoInvite")!.IsVisible);
Assert.True(page.FindControl<Button>("LanAudioInvite")!.IsEffectivelyVisible);
var video = page.FindControl<ContentControl>("LanRemoteVideo")!;
Assert.True(video.IsEffectivelyVisible);
Assert.Same(lan.RemoteVideo, video.Content);
}
finally { window.Close(); }
}, TestContext.Current.CancellationToken);
[Fact]
public Task Audio_page_shows_static_image_and_hides_video_and_srtp_controls()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var webRtc = new WebRtcCallViewModel(signaling);
var chat = new ChatViewModel(settings: new Settings()) { VideoCall = webRtc, IsConnected = true };
signaling.Invite(new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), DisplayMode: CallDisplayMode.AudioOnly));
await WaitAsync(() => webRtc.Incoming);
var page = new CallPage { DataContext = new AudioCallPageViewModel(chat) };
var window = new Window { Content = page };
try
{
window.Show();
Assert.False(page.FindControl<ComboBox>("WebRtcCamera")!.IsVisible);
Assert.False(page.FindControl<Button>("WebRtcVideoInvite")!.IsVisible);
Assert.False(page.FindControl<StackPanel>("LanCallPanel")!.IsVisible);
var fallback = page.FindControl<Image>("AudioFallbackImage")!;
Assert.True(fallback.IsEffectivelyVisible);
Assert.NotNull(fallback.Source);
var displayedAvatar = page.FindControl<Image>("AudioAvatarImage")!;
Assert.Null(displayedAvatar.Source);
webRtc.RemoteAvatar = Assert.IsType<Bitmap>(fallback.Source);
Assert.Same(webRtc.RemoteAvatar, displayedAvatar.Source);
}
finally { window.Close(); }
}, TestContext.Current.CancellationToken);
[Fact]
public Task Unknown_transport_is_rejected_once_without_starting_either_call()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
@ -51,12 +109,13 @@ public sealed class CallTransportRoutingTests
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Chat_updates_both_rooms_and_disconnects_the_active_transport(string transport)
public Task Chat_updates_both_rooms_and_disconnects_the_active_transport(string transport)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var chat = new ChatViewModel(settings: new Settings());
@ -82,7 +141,7 @@ public sealed class CallTransportRoutingTests
signaling.Invite(call);
Assert.False(lan.Incoming);
Assert.False(webRtc.Incoming);
}
}, TestContext.Current.CancellationToken);
private static async Task WaitAsync(Func<bool> condition)
{
@ -91,8 +150,9 @@ public sealed class CallTransportRoutingTests
while (!condition()) await Task.Delay(10, timeout.Token);
}
[AvaloniaFact]
public async Task Selecting_a_room_member_prepares_both_transports_without_inviting()
[Fact]
public Task Selecting_a_room_member_prepares_both_transports_without_inviting()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
@ -104,8 +164,10 @@ public sealed class CallTransportRoutingTests
};
chat.FocusedUsers.Add("bob");
Assert.False(chat.OpenCallCommand.CanExecute(null));
Assert.False(chat.OpenAudioCallCommand.CanExecute(null));
chat.SelectedUser = "bob";
Assert.True(chat.OpenCallCommand.CanExecute(null));
Assert.True(chat.OpenAudioCallCommand.CanExecute(null));
var page = chat.PrepareCallPage();
Assert.Same(chat, page.Chat);
Assert.Equal("bob", lan.Target);
@ -115,17 +177,19 @@ public sealed class CallTransportRoutingTests
chat.FocusedUsers.Remove("bob");
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
Assert.False(chat.OpenAudioCallCommand.CanExecute(null));
chat.FocusedUsers.Add("bob");
chat.SelectedUser = "bob";
chat.SelectedRoom = "Other";
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Leaving_text_chat_preserves_invitation_and_leaving_call_page_ends_it(string transport)
public Task Leaving_text_chat_preserves_invitation_and_leaving_call_page_ends_it(string transport)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
@ -154,7 +218,7 @@ public sealed class CallTransportRoutingTests
Assert.False(webRtc.Busy);
}
finally { window.Close(); }
}
}, TestContext.Current.CancellationToken);
private sealed class Signaling : IWebRtcCallSignaling
{
@ -168,8 +232,12 @@ public sealed class CallTransportRoutingTests
public void Invite(CallSession call) => Invitation?.Invoke(call);
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task AcceptAsync(Guid callId, CancellationToken ct = default) => throw new NotSupportedException();
public Task EndAsync(Guid callId, CancellationToken ct = default)
{

View file

@ -34,14 +34,15 @@ public sealed class AndroidLanCallTestActivity : Activity
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(55));
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true", timeout.Token);
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true",
Intent?.GetStringExtra("avatar") == "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)
private async Task<string> RunAsync(string result, bool wrongKey, bool avatar, CancellationToken ct)
{
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View == null)
@ -60,6 +61,7 @@ public sealed class AndroidLanCallTestActivity : Activity
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
var attached = false;
var imagePath = Path.Combine(CacheDir!.AbsolutePath, $"lan-call-avatar-{Guid.NewGuid():N}.png");
try
{
await peer.StartReceivingAsync(ct);
@ -87,20 +89,30 @@ public sealed class AndroidLanCallTestActivity : Activity
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));
if (avatar)
{
using var image = PostIt.Helpers.ImageHelper.LoadFromResource(new Uri("avares://PostIt/Assets/Icon.png"));
image.Save(imagePath, Avalonia.Media.Imaging.PngBitmapEncoderOptions.Default);
File.WriteAllText(result, "RUNNING\nstage=avatar, microphone and SRTP without camera");
await Dispatcher.UIThread.InvokeAsync(() => call.StartAvatarSendingAsync(endpoint, imagePath, "microphone", ct));
}
else
{
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.");
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) &&
if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(12) &&
decoded.Frames >= 100 && decoded.Samples > 144000 && call.HasRemoteMedia) break;
await Task.Delay(100, ct);
}
@ -108,9 +120,9 @@ public sealed class AndroidLanCallTestActivity : Activity
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" +
return $"PASS\nfrontCamera={!avatar}\navatar={avatar}\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";
$"transport=SRTP/UDP loopback\npreview=attached\nsource={(avatar ? "avatar" : "camera")}+microphone,return=explicit fixture\ncleanup=complete";
}
finally
{
@ -123,6 +135,7 @@ public sealed class AndroidLanCallTestActivity : Activity
}
File.WriteAllText(result, "RUNNING\nstage=dispose call");
if (call != null) await Dispatcher.UIThread.InvokeAsync(async () => await call.DisposeAsync());
File.Delete(imagePath);
File.WriteAllText(result, "RUNNING\nstage=stop return peer");
await peer.StopAsync();
source.Dispose();

View file

@ -38,6 +38,12 @@ public sealed class AvaloniaUiFixture : IAsyncLifetime
}, ct);
}
public Task RunAsync(Action action, CancellationToken ct) => RunAsync(() =>
{
action();
return Task.CompletedTask;
}, ct);
public Task WithWindowAsync(Func<Control> createContent, Func<Window, Task> test, CancellationToken ct,
double width = 800, double height = 600) => RunAsync(async () =>
{

View file

@ -1,4 +1,3 @@
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using Yavsc.Abstract.Models.Messaging;
@ -7,7 +6,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class HomePageNotificationsTests
[Collection(AvaloniaUiCollection.Name)]
public class HomePageNotificationsTests(AvaloniaUiFixture ui)
{
[Fact]
public async Task Refresh_loads_public_notifications_from_the_business_host()
@ -70,8 +70,9 @@ public class HomePageNotificationsTests
Assert.False(vm.IsLoadingNotifications);
}
[AvaloniaFact]
public async Task Login_and_logout_reload_notifications_and_discard_in_flight_private_data()
[Fact]
public Task Login_and_logout_reload_notifications_and_discard_in_flight_private_data()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-notifications-{Guid.NewGuid():N}.json");
var settings = new Settings();
@ -123,7 +124,7 @@ public class HomePageNotificationsTests
{
File.Delete(tokenPath);
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Anonymous_dismiss_removes_the_notification_without_an_api_call()

View file

@ -1,5 +1,6 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Media.Imaging;
using PostIt.Helpers;
using PostIt.Services;
using PostIt.ViewModels.Chat;
using PostIt.ViewModels;
@ -8,10 +9,12 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class LanCallViewModelTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class LanCallViewModelTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Calls_restore_shared_devices_and_persist_choices_and_network_address()
[Fact]
public Task Calls_restore_shared_devices_and_persist_choices_and_network_address()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json");
var previousDevices = Platform.GetLanCallDevices;
@ -65,10 +68,11 @@ public sealed class LanCallViewModelTests
}
}
finally { Platform.GetLanCallDevices = previousDevices; File.Delete(path); }
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Call_preference_save_failures_are_reported_without_losing_the_choice()
[Fact]
public Task Call_preference_save_failures_are_reported_without_losing_the_choice()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}");
Directory.CreateDirectory(path);
@ -83,10 +87,11 @@ public sealed class LanCallViewModelTests
Assert.True(settings.IsDirty);
}
finally { Directory.Delete(path); }
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Missing_saved_network_address_requires_a_new_selection_and_does_not_restore_consent()
[Fact]
public Task Missing_saved_network_address_requires_a_new_selection_and_does_not_restore_consent()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json");
try
@ -98,7 +103,7 @@ public sealed class LanCallViewModelTests
Assert.Equal("not-a-local-address", settings.LanCallAddress);
}
finally { File.Delete(path); }
}
}, TestContext.Current.CancellationToken);
private static CallSession Session() => new(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), CallTransports.LanSrtp);
@ -115,11 +120,113 @@ public sealed class LanCallViewModelTests
return vm;
}
[AvaloniaTheory]
[Theory]
[InlineData(true)]
[InlineData(false)]
public Task Call_without_camera_sends_own_avatar_and_microphone_and_cleans_up(bool caller)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var media = new FakeMedia();
string? avatarUser = null;
await using var vm = new LanCallViewModel(signaling, (_, _) => media, loadAvatar: (user, _) =>
{
avatarUser = user;
return Task.FromResult<Bitmap?>(ImageHelper.LoadFromResource(new Uri("avares://PostIt/Assets/Icon.png")));
})
{
Address = "127.0.0.1", Microphone = new("Mic", "default"),
AllowAddressDisclosure = true, Room = "General", Target = "bob"
};
vm.Addresses.Add("127.0.0.1");
if (caller) await vm.InviteAudioCommand.ExecuteAsync(null);
else
{
signaling.Invite(vm, signaling.Call with { DisplayMode = CallDisplayMode.AudioOnly });
await WaitAsync(() => vm.Incoming);
await vm.AcceptCommand.ExecuteAsync(null);
}
Assert.True(vm.AudioOnly);
Assert.Null(vm.Camera);
if (caller) signaling.Ready();
await WaitAsync(() => signaling.Sent.Count > 0);
Assert.Equal(caller ? "alice" : "bob", avatarUser);
Assert.Same(media.LocalVideo, vm.LocalVideo);
Assert.Same(media.RemoteVideo, vm.RemoteVideo);
Assert.False(media.Sending);
signaling.RemoteEndpoint(signaling.Call.Id);
await WaitAsync(() => media.Sending);
Assert.Null(media.Camera);
var imagePath = Assert.IsType<string>(media.AvatarPath);
Assert.True(File.Exists(imagePath));
await vm.HangupAsync();
Assert.True(media.Disposed);
Assert.False(File.Exists(imagePath));
}, TestContext.Current.CancellationToken);
[Fact]
public Task Unavailable_own_avatar_ends_call_without_opening_media_or_camera()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var created = false;
await using var vm = new LanCallViewModel(signaling, (_, _) =>
{
created = true;
return new FakeMedia();
}, loadAvatar: (_, _) => Task.FromResult<Bitmap?>(null))
{
Address = "127.0.0.1", Microphone = new("Mic", "default"),
AllowAddressDisclosure = true, Room = "General", Target = "bob"
};
vm.Addresses.Add("127.0.0.1");
await vm.InviteAudioCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => !vm.Busy);
Assert.False(created);
Assert.Empty(signaling.Sent);
Assert.Contains("avatar est indisponible", vm.Status);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Hangup_cancels_pending_avatar_download_without_opening_media()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var loading = false;
var created = false;
await using var vm = new LanCallViewModel(signaling, (_, _) =>
{
created = true;
return new FakeMedia();
}, loadAvatar: async (_, ct) =>
{
loading = true;
await Task.Delay(Timeout.Infinite, ct);
return null;
})
{
Address = "127.0.0.1", Microphone = new("Mic", "default"),
AllowAddressDisclosure = true, Room = "General", Target = "bob"
};
vm.Addresses.Add("127.0.0.1");
await vm.InviteAudioCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => loading);
await vm.HangupAsync().WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
Assert.False(created);
Assert.False(vm.Busy);
Assert.Empty(signaling.Sent);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}, TestContext.Current.CancellationToken);
[Theory]
[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)
public Task Public_or_private_ip_can_be_selected_for_an_explicitly_consented_direct_call(string address)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var vm = Configure(signaling, (_, _) => throw new Exception("No media before acceptance"));
@ -128,10 +235,11 @@ public sealed class LanCallViewModelTests
await vm.InviteCommand.ExecuteAsync(null);
Assert.Equal(1, signaling.Invites);
Assert.True(vm.Busy);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange()
[Fact]
public Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var media = new FakeMedia();
@ -156,10 +264,11 @@ public sealed class LanCallViewModelTests
Assert.False(vm.Busy);
Assert.Null(vm.LocalVideo);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Caller_waits_for_consent_and_interruption_releases_media_without_reconnecting()
[Fact]
public Task Caller_waits_for_consent_and_interruption_releases_media_without_reconnecting()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var media = new FakeMedia();
@ -177,10 +286,11 @@ public sealed class LanCallViewModelTests
Assert.False(vm.Busy);
Assert.Null(vm.RemoteVideo);
Assert.Contains("interrompue", vm.Status);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Missing_disclosure_consent_or_devices_blocks_the_invitation()
[Fact]
public Task Missing_disclosure_consent_or_devices_blocks_the_invitation()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
await using var vm = Configure(signaling, (_, _) => throw new Exception("Must not capture"));
@ -194,10 +304,11 @@ public sealed class LanCallViewModelTests
Assert.Equal(0, signaling.Invites);
Assert.Contains("camera", vm.Status);
Assert.False(vm.Busy);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Refusal_never_creates_media_and_late_signals_cannot_restart_capture()
[Fact]
public Task Refusal_never_creates_media_and_late_signals_cannot_restart_capture()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var created = 0;
@ -210,10 +321,11 @@ public sealed class LanCallViewModelTests
await Task.Delay(30, TestContext.Current.CancellationToken);
Assert.Equal(0, created);
Assert.False(vm.Busy);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Platform_devices_and_factory_are_used_and_backgrounding_ends_capture()
[Fact]
public Task Platform_devices_and_factory_are_used_and_backgrounding_ends_capture()
=> ui.RunAsync(async () =>
{
var previousDevices = Platform.GetLanCallDevices;
var previousFactory = Platform.CreateLanCallMedia;
@ -261,10 +373,11 @@ public sealed class LanCallViewModelTests
Platform.GetLanCallDevices = previousDevices;
Platform.CreateLanCallMedia = previousFactory;
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Hangup_cancels_pending_native_start_without_waiting_for_startup_timeout()
[Fact]
public Task Hangup_cancels_pending_native_start_without_waiting_for_startup_timeout()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var media = new FakeMedia { DelayStartup = true };
@ -278,10 +391,11 @@ public sealed class LanCallViewModelTests
Assert.True(media.Disposed);
Assert.False(vm.Busy);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Media_failure_ends_the_call_and_disposes_capture()
[Fact]
public Task Media_failure_ends_the_call_and_disposes_capture()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling();
var media = new FakeMedia();
@ -294,7 +408,7 @@ public sealed class LanCallViewModelTests
Assert.False(vm.Busy);
Assert.Contains("test media failure", vm.Status);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
private static async Task WaitAsync(Func<bool> condition)
{
@ -314,11 +428,20 @@ public sealed class LanCallViewModelTests
public bool Sending { get; private set; }
public bool Disposed { get; private set; }
public bool DelayStartup { get; init; }
public string? Camera { get; private set; }
public string? AvatarPath { get; private set; }
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
{
Sending = true;
Camera = camera;
if (DelayStartup) await Task.Delay(Timeout.Infinite, ct);
}
public Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
{
Sending = true;
AvatarPath = imagePath;
return Task.CompletedTask;
}
public void Fail() => _completion.TrySetException(new IOException("test media failure"));
public ValueTask DisposeAsync() { Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
}
@ -330,18 +453,24 @@ public sealed class LanCallViewModelTests
public event Action<CallEnded>? Ended;
public event Action<Guid, CallSignal>? Signal;
public event Action? Interrupted;
public CallSession Call { get; } = Session();
public CallSession Call { get; private set; } = 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<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default)
{
Invites++;
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
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 Invite(LanCallViewModel _, CallSession call) { Call = 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))));

View file

@ -17,6 +17,120 @@ public sealed class LinuxLanCallMediaTests(ITestOutputHelper output)
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
public static bool HasTsFixture => OperatingSystem.IsLinux() &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_TS"));
public static bool HasAudioFixture => OperatingSystem.IsLinux() &&
(File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO")) ||
!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO_SOURCE"))) &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE"));
public static bool HasAacFixture => OperatingSystem.IsLinux() &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_AAC")) &&
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE"));
[Theory(Skip = "Set POSTIT_TEST_AAC to ADTS and POSTIT_TEST_IMAGE to an avatar; requires Linux LibVLC SRTP.",
SkipUnless = nameof(HasAacFixture))]
[InlineData("127.0.0.1")]
[InlineData("::1")]
public async Task Avatar_video_and_live_aac_pipe_use_the_same_libvlc_pipeline(string address)
{
var ct = TestContext.Current.CancellationToken;
var port = FreePort(address: address);
await using var sender = new LibVlcLanCallMedia(address, port, headless: true);
await using var receiver = new LibVlcLanCallMedia(address, FreePort(port, 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_AAC")!);
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
var pump = Task.Run(async () =>
{
var buffer = new byte[512];
while (await source.ReadAsync(buffer, lifetime.Token) is var count && count > 0)
{
await pipe.WriteAsync(buffer.AsMemory(0, count), lifetime.Token);
await Task.Delay(40, lifetime.Token);
}
}, ct);
try
{
await receiver.StartReceivingAsync(ct);
await sender.StartAvatarSendingAsync(receiver.Endpoint,
Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE")!,
$"fd/aac://{pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32()}", ct);
await Task.Delay(TimeSpan.FromSeconds(12), ct);
if (sender.Completion.IsCompleted) await sender.Completion;
if (receiver.Completion.IsCompleted) await receiver.Completion;
Assert.True(receiver.HasRemoteMedia);
var frames = decoded.Frames;
var samples = decoded.AudioSamples;
await Task.Delay(1500, ct);
Assert.True(decoded.Frames > frames);
Assert.True(decoded.AudioSamples > samples);
}
finally
{
lifetime.Cancel();
await sender.StopAsync();
try { await pump; }
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
}
}
[Theory(Skip = "Set POSTIT_TEST_AUDIO to WAV and POSTIT_TEST_IMAGE to an avatar; requires Linux LibVLC SRTP.",
SkipUnless = nameof(HasAudioFixture))]
[InlineData("127.0.0.1", false)]
[InlineData("::1", false)]
[InlineData("127.0.0.1", true)]
[InlineData("::1", true)]
public async Task Two_peers_receive_avatar_video_and_audio_beyond_default_image_duration_and_reject_wrong_keys(
string address, bool wrongKey)
{
var ct = TestContext.Current.CancellationToken;
var port = FreePort(address: address);
await using var first = new LibVlcLanCallMedia(address, port, headless: true);
await using var second = new LibVlcLanCallMedia(address, FreePort(port, address), headless: true);
using var firstDecoded = new DecodedVideo(first.Receiver);
using var secondDecoded = new DecodedVideo(second.Receiver);
await first.StartReceivingAsync(ct);
await second.StartReceivingAsync(ct);
var image = Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE")!;
var audio = Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO_SOURCE");
if (string.IsNullOrEmpty(audio))
{
var uri = new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO")!)).AbsoluteUri;
audio = "file/wav:" + uri["file:".Length..];
}
await first.StartAvatarSendingAsync(wrongKey ? second.Endpoint with { Key = new string('0', 32) }
: second.Endpoint, image, audio, ct);
await second.StartAvatarSendingAsync(first.Endpoint, image, audio, ct);
var elapsed = Stopwatch.StartNew();
while (elapsed.Elapsed < TimeSpan.FromSeconds(12))
{
if (first.Completion.IsCompleted) await first.Completion;
if (second.Completion.IsCompleted) await second.Completion;
await Task.Delay(100, ct);
}
var frames = firstDecoded.Frames;
var samples = firstDecoded.AudioSamples;
var secondFrames = secondDecoded.Frames;
var secondSamples = secondDecoded.AudioSamples;
await Task.Delay(1500, ct);
output.WriteLine($"First: decoded={first.Statistics.DecodedAudio}, samples={firstDecoded.AudioSamples}; " +
$"second: decoded={second.Statistics.DecodedAudio}, samples={secondDecoded.AudioSamples}");
Assert.True(first.HasRemoteMedia);
Assert.True(firstDecoded.AudioSamples > 4800);
Assert.True(firstDecoded.Frames > frames);
Assert.True(firstDecoded.AudioSamples > samples);
if (wrongKey)
{
Assert.False(second.HasRemoteMedia);
Assert.Equal(0, secondDecoded.AudioSamples);
Assert.Equal(0, secondDecoded.Frames);
}
else
{
Assert.True(second.HasRemoteMedia);
Assert.True(secondDecoded.AudioSamples > secondSamples);
Assert.True(secondDecoded.Frames > secondFrames);
}
}
[Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
[InlineData("127.0.0.1")]

View file

@ -1,6 +1,5 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Api.Client;
@ -50,10 +49,12 @@ namespace PostIt.Tests;
/// </list>
/// </summary>
[Trait("Category", "non-reg")]
public class MainPageButtonsTests
[Collection(AvaloniaUiCollection.Name)]
public class MainPageButtonsTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Blog_toolbar_uses_page_view_model_in_home_navigation_and_tracks_changes()
[Fact]
public Task Blog_toolbar_uses_page_view_model_in_home_navigation_and_tracks_changes()
=> ui.RunAsync(async () =>
{
var home = new HomePageViewModel();
var root = new MainView { DataContext = home };
@ -90,7 +91,7 @@ public class MainPageButtonsTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
/// <summary>
/// Fake <see cref="YavscApiClient"/> that throws on any
@ -190,8 +191,9 @@ public class MainPageButtonsTests
return stackBefore;
}
[AvaloniaFact]
public async Task Acl_button_click_pushes_a_page_onto_nav_stack()
[Fact]
public Task Acl_button_click_pushes_a_page_onto_nav_stack()
=> ui.RunAsync(async () =>
{
// Arrange: a VM whose SelectedPost is non-null so
// CanManageAcl evaluates to true and the button is
@ -221,10 +223,11 @@ public class MainPageButtonsTests
var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom<Page>(pushed);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Circles_button_click_pushes_a_page_onto_nav_stack()
[Fact]
public Task Circles_button_click_pushes_a_page_onto_nav_stack()
=> ui.RunAsync(async () =>
{
// Arrange: OpenCircles has no CanExecute guard today —
// any click should fire it and push the page.
@ -243,10 +246,11 @@ public class MainPageButtonsTests
var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom<Page>(pushed);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public void Signature_dev_button_click_pushes_a_page_onto_nav_stack()
[Fact]
public Task Signature_dev_button_click_pushes_a_page_onto_nav_stack()
=> ui.RunAsync(() =>
{
// Arrange: the "[DEV] Signature" button is bound to the
// BlogsViewModel.OpenSignatureDevCommand [RelayCommand].
@ -272,5 +276,5 @@ public class MainPageButtonsTests
var pushed = window.NavRoot.NavigationStack.Last();
Assert.NotNull(pushed);
Assert.IsAssignableFrom<Page>(pushed);
}
}, TestContext.Current.CancellationToken);
}

View file

@ -1,5 +1,4 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
using Yavsc.Blogspot;
using Yavsc.Api.Client;
@ -10,7 +9,7 @@ namespace PostIt.Tests;
/// <summary>
/// Headless UI tests for the "Save" flow in <see cref="BlogsPage"/>.
/// The pattern is the one <c>SessionStatusBannerTests</c>
/// established: <c>[AvaloniaFact]</c>, a <see cref="Window"/>
/// established: the <see cref="AvaloniaUiFixture"/> collection, a <see cref="Window"/>
/// hosting the page (via a <see cref="Frame"/> because
/// <c>MainPage</c> is a <c>ContentPage</c>), then drive the
/// controls through their public surface and assert on what
@ -30,10 +29,12 @@ namespace PostIt.Tests;
/// buffer that the XAML binds to and the Save command consumes.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class MainPageSaveTests
[Collection(AvaloniaUiCollection.Name)]
public class MainPageSaveTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Typing_a_title_then_clicking_Save_sends_that_title_in_the_post_body()
[Fact]
public Task Typing_a_title_then_clicking_Save_sends_that_title_in_the_post_body()
=> ui.RunAsync(async () =>
{
// Arrange: VM with a recording API client, mounted in a
// headless window via a Frame (MainPage is a ContentPage,
@ -84,5 +85,5 @@ public class MainPageSaveTests
Assert.Equal("blogspot", path);
var sent = Assert.IsType<BlogPostDto>(body);
Assert.Equal(typed, sent.Title);
}
}, TestContext.Current.CancellationToken);
}

View file

@ -2,7 +2,6 @@ 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;
@ -17,13 +16,15 @@ using PostIt.Views.Blogs;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class MarkdownEditorScrollTests
[Collection(AvaloniaUiCollection.Name)]
public class MarkdownEditorScrollTests(AvaloniaUiFixture ui)
{
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()
[Fact]
public Task Landscape_keyboard_preserves_controls_and_restores_editor_layout()
=> ui.RunAsync(async () =>
{
var root = new MainView();
var page = new BlogsPage { DataContext = new BlogsViewModel { IsEditing = true, DraftArticle = LongArticle } };
@ -47,8 +48,6 @@ public class MarkdownEditorScrollTests
Assert.False(root.AuthenticationModal.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;
@ -75,10 +74,11 @@ public class MarkdownEditorScrollTests
{
CloseWindow(window, page.ArticleEditor);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public void Keyboard_padding_preserves_system_bar_insets_and_restores_them()
[Fact]
public Task Keyboard_padding_preserves_system_bar_insets_and_restores_them()
=> ui.RunAsync(() =>
{
var root = new MainView();
var window = new Window { Width = 600, Height = 800, Content = root };
@ -107,12 +107,13 @@ public class MarkdownEditorScrollTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Resizing_keeps_the_focused_caret_visible_without_changing_selection(bool focused)
public Task Resizing_keeps_the_focused_caret_visible_without_changing_selection(bool focused)
=> ui.RunAsync(() =>
{
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
var other = new TextBox();
@ -166,10 +167,11 @@ public class MarkdownEditorScrollTests
{
CloseWindow(window, editor);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public void Repeated_touch_requests_keyboard_without_losing_focus_and_read_only_does_not()
[Fact]
public Task Repeated_touch_requests_keyboard_without_losing_focus_and_read_only_does_not()
=> ui.RunAsync(() =>
{
var editor = new MarkdownEditorControl { MarkdownText = LongArticle };
var window = new Window { Width = 600, Height = 400, Content = editor };
@ -215,12 +217,13 @@ public class MarkdownEditorScrollTests
Platform.ShowSoftKeyboard = previous;
CloseWindow(window, editor);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Long_article_scrolls_to_the_end_and_adapts_to_resizing(bool preview)
public Task Long_article_scrolls_to_the_end_and_adapts_to_resizing(bool preview)
=> ui.RunAsync(() =>
{
var editor = new MarkdownEditorControl
{
@ -249,12 +252,13 @@ public class MarkdownEditorScrollTests
{
CloseWindow(window, editor);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Blog_page_bounds_the_article_viewport(bool preview)
public Task Blog_page_bounds_the_article_viewport(bool preview)
=> ui.RunAsync(() =>
{
var page = new BlogsPage { DataContext = new PostIt.ViewModels.BlogsViewModel { IsEditing = true } };
var editor = page.GetLogicalDescendants().OfType<MarkdownEditorControl>().Single();
@ -284,12 +288,13 @@ public class MarkdownEditorScrollTests
{
CloseWindow(window, editor);
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Short_article_needs_no_vertical_scrollbar(bool preview)
public Task Short_article_needs_no_vertical_scrollbar(bool preview)
=> ui.RunAsync(() =>
{
var editor = new MarkdownEditorControl
{
@ -312,7 +317,7 @@ public class MarkdownEditorScrollTests
{
CloseWindow(window, editor);
}
}
}, TestContext.Current.CancellationToken);
private static void CloseWindow(Window window, MarkdownEditorControl editor)
{

View file

@ -1,4 +1,3 @@
using Avalonia.Headless.XUnit;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
@ -14,11 +13,13 @@ using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using PostIt.Views;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class MessagingSessionTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class MessagingSessionTests(AvaloniaUiFixture ui)
{
[Fact]
public void Only_explicit_settings_application_raises_Applied_after_successful_save()
@ -78,8 +79,9 @@ public sealed class MessagingSessionTests
=> await PostIt.Android.Tests.ChatServiceEpochTests.VerifyAsync();
#endif
[AvaloniaFact]
public void Settings_page_binds_opt_in_and_hides_it_on_other_platforms()
[Fact]
public Task Settings_page_binds_opt_in_and_hides_it_on_other_platforms()
=> ui.RunAsync(() =>
{
var settings = new Settings();
var page = new SettingsPage { DataContext = settings };
@ -104,7 +106,7 @@ public sealed class MessagingSessionTests
Assert.False(checkbox.IsChecked);
}
finally { window.Close(); }
}
}, TestContext.Current.CancellationToken);
[Fact]
public void Background_chat_service_are_opt_in_and_saved_only_after_persistence()
@ -191,8 +193,9 @@ public sealed class MessagingSessionTests
finally { File.Delete(path); }
}
[AvaloniaFact]
public async Task Disconnect_cancels_an_in_flight_chat_handshake_instead_of_waiting_for_network_timeout()
[Fact]
public Task Disconnect_cancels_an_in_flight_chat_handshake_instead_of_waiting_for_network_timeout()
=> ui.RunAsync(async () =>
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
@ -233,7 +236,7 @@ public sealed class MessagingSessionTests
File.Delete(path);
await server.StopAsync();
}
}
}, TestContext.Current.CancellationToken);
[Theory]
[InlineData("alice", "https://api.example.test/api/v1/", true)]
@ -261,10 +264,11 @@ public sealed class MessagingSessionTests
finally { File.Delete(path); }
}
[AvaloniaTheory]
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Session_uses_one_chat_connection_and_logout_disables_service_before_token_purge(bool connectOnLogin)
public Task Session_uses_one_chat_connection_and_logout_disables_service_before_token_purge(bool connectOnLogin)
=> ui.RunAsync(async () =>
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
@ -308,6 +312,8 @@ public sealed class MessagingSessionTests
await chat.JoinRoomCommand();
Assert.Equal(new[] { "first", "second" }, chat.JoinedRooms);
var counter = server.Services.GetRequiredService<ConnectionCounter>();
settings.AllowVideoCalls = false;
counter.ContactPreferences = null;
counter.Context!.Abort();
var deadline = DateTime.UtcNow.AddSeconds(40);
while (!counter.RoomsRejoined.Task.IsCompleted && DateTime.UtcNow < deadline)
@ -319,6 +325,7 @@ public sealed class MessagingSessionTests
$"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);
Assert.Equal(Announced(true, false, true), counter.ContactPreferences);
Platform.SuspendPlayback();
Assert.True(chat.IsConnected);
@ -350,10 +357,11 @@ public sealed class MessagingSessionTests
File.Delete(path + ".settings");
await server.StopAsync();
}
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Headless_transport_restores_account_rooms_and_the_later_ui_reuses_its_socket()
[Fact]
public Task Headless_transport_restores_account_rooms_and_the_later_ui_reuses_its_socket()
=> ui.RunAsync(async () =>
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
@ -366,7 +374,13 @@ public sealed class MessagingSessionTests
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/" };
var settings = new Settings(path + ".settings")
{
ApiUrl = server.Urls.Single() + "/api/v1/",
AllowAudioCalls = true,
AllowVideoCalls = false,
AllowPrivateMessages = false
};
settings.Authentication.Authority = "https://login.example.test";
var store = CreateStore(path);
var jwt = "e30." + Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"sub\":\"alice\"}")).TrimEnd('=')
@ -376,6 +390,8 @@ public sealed class MessagingSessionTests
await using (var transport = new ChatHubConnection(api))
{
await transport.StartAsync(TestContext.Current.CancellationToken);
Assert.Equal(Announced(true, false, false),
server.Services.GetRequiredService<ConnectionCounter>().ContactPreferences);
await transport.JoinAsync("SavedRoom", TestContext.Current.CancellationToken);
Assert.Single(settings.ChatRoomsByAccount);
}
@ -385,6 +401,8 @@ public sealed class MessagingSessionTests
await using var resumedApi = new YavscApiClient(restored, store);
await using var resumed = new ChatHubConnection(resumedApi);
await resumed.StartAsync(TestContext.Current.CancellationToken);
Assert.Equal(Announced(true, false, false),
server.Services.GetRequiredService<ConnectionCounter>().ContactPreferences);
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);
@ -424,7 +442,11 @@ public sealed class MessagingSessionTests
File.Delete(path + ".settings");
await server.StopAsync();
}
}
}, TestContext.Current.CancellationToken);
// The Linux desktop also announces its audio-only WebRTC and SRTP call support.
private static ContactPreferences Announced(bool audio, bool video, bool messages) =>
new(audio, video, messages, OperatingSystem.IsLinux(), OperatingSystem.IsLinux());
private static TokenStore CreateStore(string path)
{
@ -437,12 +459,14 @@ public sealed class MessagingSessionTests
{
public int Count;
public HubCallerContext? Context;
public ContactPreferences? ContactPreferences;
public List<string> RejoinedRooms { get; } = [];
public TaskCompletionSource RoomsRejoined { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
public sealed class TestChatHub(ConnectionCounter counter) : Hub
{
public void SetContactPreferences(ContactPreferences preferences) => counter.ContactPreferences = preferences;
public int ConnectionCount() => counter.Count;
public ChatRoomInfo Join(string room)
{

View file

@ -1,7 +1,6 @@
using System.Net.Http;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
using CommunityToolkit.Mvvm.Input;
using PostIt.ViewModels;
@ -48,7 +47,8 @@ namespace PostIt.Tests;
/// (platform-dependent) picker.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class MyFilesPageHeadlessTests
[Collection(AvaloniaUiCollection.Name)]
public class MyFilesPageHeadlessTests(AvaloniaUiFixture ui)
{
private static (MyFilesPage page, MyFilesViewModel vm, StubFsApi api) CreatePage()
{
@ -94,8 +94,9 @@ public class MyFilesPageHeadlessTests
.OfType<Button>()
.FirstOrDefault(b => b.Content is string s && s == content);
[AvaloniaFact]
public async Task Download_button_on_a_file_row_is_bound_armed_and_fires_on_click()
[Fact]
public Task Download_button_on_a_file_row_is_bound_armed_and_fires_on_click()
=> ui.RunAsync(async () =>
{
var (page, vm, api) = await MountAsync();
@ -127,10 +128,11 @@ public class MyFilesPageHeadlessTests
}
Assert.True(recorded,
"Clicking Télécharger must invoke GET fs/file/{id} on the API client.");
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Delete_button_on_a_file_row_is_bound_armed_and_fires_on_click()
[Fact]
public Task Delete_button_on_a_file_row_is_bound_armed_and_fires_on_click()
=> ui.RunAsync(async () =>
{
var (page, vm, api) = await MountAsync();
@ -157,7 +159,7 @@ public class MyFilesPageHeadlessTests
}
Assert.True(recorded,
"Clicking Supprimer must invoke DELETE fs/{path} on the API client.");
}
}, TestContext.Current.CancellationToken);
private sealed class StubFsApi : IYavscApiClient
{

View file

@ -82,7 +82,7 @@ class AndroidPeer:
class NativeWebRtcTests(unittest.TestCase):
def run_pair(self, relay, unavailable=False, android=False, android_caller=False):
def run_pair(self, relay, unavailable=False, android=False, android_caller=False, audio_only=False):
processes = []
events = queue.Queue()
errors = []
@ -156,7 +156,8 @@ class NativeWebRtcTests(unittest.TestCase):
self.send(process, {"command": "start", "configuration": {
"iceServers": servers, "relayOnly": relay,
"caller": index == (1 if android_caller else 0),
"camera": "test", "microphone": "test"}})
"camera": "" if audio_only else "test", "microphone": "test",
"audioOnly": audio_only}})
stats = {}
rendered = set()
candidates = 0
@ -176,6 +177,8 @@ class NativeWebRtcTests(unittest.TestCase):
self.fail(message["message"] + "\n" + str(errors[-10:]))
if kind == "signal":
signal = message["signal"]
if audio_only and signal.get("sdp"):
self.assertNotIn("m=video", signal["sdp"])
if relay:
candidate = signal.get("candidate")
if candidate:
@ -195,15 +198,17 @@ class NativeWebRtcTests(unittest.TestCase):
self.send(processes[1 - index], {"command": "signal", "signal": signal})
if kind == "rendered" and message["size"] > 100:
rendered.add((index, message["target"]))
self.assertFalse(audio_only, "Audio-only call produced a video frame")
if kind == "status":
stats[index] = message["status"]
if unavailable:
self.assertNotEqual("connected", message["status"]["connectionState"])
self.assertEqual(0, message["status"]["audioPackets"])
self.assertEqual(0, message["status"]["videoFrames"])
elif time.monotonic() - started >= 10 and len(stats) == 2 and len(rendered) == 4 and all(
elif time.monotonic() - started >= 10 and len(stats) == 2 and (audio_only or len(rendered) == 4) and all(
s["connectionState"] == "connected" and s["audioPackets"] > 100
and s["videoFrames"] >= 100 for s in stats.values()
and (s["videoFrames"] == 0 if audio_only else s["videoFrames"] >= 100)
for s in stats.values()
):
if relay:
self.assertTrue(all(s["localCandidateType"] == "relay" for s in stats.values()))
@ -246,6 +251,12 @@ class NativeWebRtcTests(unittest.TestCase):
def test_direct_bidirectional_media(self):
self.run_pair(False)
def test_audio_only_bidirectional_media(self):
self.run_pair(False, audio_only=True)
def test_audio_only_relay_bidirectional_media(self):
self.run_pair(True, audio_only=True)
def test_relay_bidirectional_media_and_no_address_disclosure(self):
self.run_pair(True)

View file

@ -0,0 +1,32 @@
using Avalonia.Controls;
using PostIt.Models;
using PostIt.Views;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
[Collection(AvaloniaUiCollection.Name)]
public class NotificationModalTests(AvaloniaUiFixture ui)
{
[Fact]
public Task Error_message_is_selectable_in_the_notification_modal()
=> ui.RunAsync(() =>
{
var root = new MainView();
var window = new Window { Content = root };
try
{
window.Show();
root.ShowNotificationModal("Échec de la suppression : boom", StatusSeverity.Error);
var message = root.FindControl<SelectableTextBlock>("NotificationModalMessage");
Assert.NotNull(message);
Assert.True(root.NotificationModal.IsVisible);
Assert.Equal("Échec de la suppression : boom", message.Text);
}
finally
{
window.Close();
}
}, TestContext.Current.CancellationToken);
}

View file

@ -1,5 +1,4 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
@ -9,7 +8,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class PerformerDonationSettingsTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class PerformerDonationSettingsTests(AvaloniaUiFixture ui)
{
[Theory]
[InlineData("performer@payments.example", "performer@payments.example")]
@ -21,8 +21,9 @@ public sealed class PerformerDonationSettingsTests
Assert.Equal(expected, vm.BuildPerformerProfileSettings().DonationPayPalEmail);
}
[AvaloniaFact]
public async Task Performer_editor_loads_displays_edits_and_saves_the_private_recipient()
[Fact]
public Task Performer_editor_loads_displays_edits_and_saves_the_private_recipient()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), "postit-donation-" + Guid.NewGuid().ToString("N") + ".json");
try
@ -46,7 +47,7 @@ public sealed class PerformerDonationSettingsTests
{
if (File.Exists(tokenPath)) File.Delete(tokenPath);
}
}
}, TestContext.Current.CancellationToken);
private sealed class PerformerApi(string tokenPath) : YavscApiClient(new Settings
{

View file

@ -1,5 +1,4 @@
using System.Net;
using Avalonia.Headless.XUnit;
using Avalonia.Headless;
using Avalonia.Controls;
using PostIt.Services;
@ -11,7 +10,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "not-ending")]
public sealed class PodcastBroadcasterTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class PodcastBroadcasterTests(AvaloniaUiFixture ui)
{
[Theory]
[InlineData("stop")]
@ -20,7 +20,7 @@ public sealed class PodcastBroadcasterTests
[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 () =>
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-local-preview-{Guid.NewGuid():N}");
var previousDevices = Platform.GetPodcastCaptureDevices;
@ -97,7 +97,6 @@ public sealed class PodcastBroadcasterTests
Assert.Null(vm.CapturePreview);
if (action == "failure") Assert.Contains("Camera disconnected", vm.Status);
if (action != "broadcast") Assert.Equal(0, transport.CreateCount);
return true;
}
finally
{
@ -113,7 +112,7 @@ public sealed class PodcastBroadcasterTests
[Fact]
public Task Leaving_the_page_during_preview_start_disposes_the_late_camera_without_showing_it()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preview-race-{Guid.NewGuid():N}");
var previous = Platform.CreatePodcastPreviewAsync;
@ -140,7 +139,6 @@ public sealed class PodcastBroadcasterTests
Assert.True(preview.Disposed);
Assert.Null(vm.CapturePreview);
Assert.False(vm.IsPreviewing);
return true;
}
finally
{
@ -181,7 +179,7 @@ public sealed class PodcastBroadcasterTests
[Fact]
public Task Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-preview-{Guid.NewGuid():N}.json");
var devices = Platform.GetPodcastCaptureDevices;
@ -230,7 +228,6 @@ public sealed class PodcastBroadcasterTests
Assert.Null(vm.CapturePreview);
Assert.Null(host.Content);
Assert.True(capture!.Stopped);
return true;
}
finally
{
@ -243,8 +240,9 @@ public sealed class PodcastBroadcasterTests
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Shared_page_uses_platform_devices_and_requests_permissions_before_creating_server_broadcast()
[Fact]
public Task Shared_page_uses_platform_devices_and_requests_permissions_before_creating_server_broadcast()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-podcast-{Guid.NewGuid():N}.json");
var devices = Platform.GetPodcastCaptureDevices;
@ -289,7 +287,7 @@ public sealed class PodcastBroadcasterTests
File.Delete(tokenPath);
File.Delete(tokenPath + ".settings");
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Prepared_broadcast_starts_the_existing_emission_instead_of_creating_another()

View file

@ -1,4 +1,3 @@
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using Yavsc.Api.Client;
@ -8,10 +7,12 @@ using Yavsc.Abstract.Streaming;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class PodcastPreferencesTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class PodcastPreferencesTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Detection_selection_and_title_survive_settings_reload_without_detecting_again()
[Fact]
public Task Detection_selection_and_title_survive_settings_reload_without_detecting_again()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}.json");
var previous = Platform.GetPodcastCaptureDevices;
@ -78,7 +79,7 @@ public sealed class PodcastPreferencesTests
File.Delete(path + ".tokens");
}
}
}, TestContext.Current.CancellationToken);
private sealed class PreferencesApi(Settings settings, TokenStore store) : YavscApiClient(settings, store)
{
@ -90,8 +91,9 @@ public sealed class PodcastPreferencesTests
}
}
[AvaloniaFact]
public async Task Failed_save_is_reported_without_losing_the_title()
[Fact]
public Task Failed_save_is_reported_without_losing_the_title()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}");
Directory.CreateDirectory(path);
@ -106,5 +108,5 @@ public sealed class PodcastPreferencesTests
Assert.True(settings.IsDirty);
}
finally { Directory.Delete(path); File.Delete(path + ".tokens"); }
}
}, TestContext.Current.CancellationToken);
}

View file

@ -4,7 +4,9 @@ using System.Runtime.InteropServices;
using LibVLCSharp.Shared;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Interactivity;
using PostIt.Services;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
namespace PostIt.Tests;
@ -12,7 +14,8 @@ namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class PodcastReplayTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class PodcastReplayTests(AvaloniaUiFixture ui)
{
private static readonly Guid Id = Guid.NewGuid();
private readonly CancellationToken _ct = TestContext.Current.CancellationToken;
@ -67,7 +70,7 @@ public sealed class PodcastReplayTests
[Fact]
public Task Desktop_overlay_has_real_position_pause_and_duration_controls()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastReplayTests).Assembly).Dispatch(() =>
=> ui.RunAsync(() =>
{
var overlay = new PostIt.Controls.ReplayControls();
var window = new Window { Content = overlay, Width = 640, Height = 360 };
@ -81,6 +84,49 @@ public sealed class PodcastReplayTests
finally { window.Close(); }
}, _ct);
[Theory]
[InlineData(true)]
[InlineData(false)]
public Task Desktop_controls_show_seeking_only_for_replay(bool replay)
=> ui.RunAsync(() =>
{
var controls = new PostIt.Controls.ReplayControls(replay);
Assert.NotNull(controls.FindControl<Button>("ToggleButton"));
Assert.Equal(replay, controls.FindControl<Slider>("PositionSlider")!.IsVisible);
Assert.Equal(replay, controls.FindControl<TextBlock>("TimeLabel")!.IsVisible);
}, TestContext.Current.CancellationToken);
[Fact(Skip = "Set POSTIT_TEST_REPLAY to a local MP4 and install LibVLC.", SkipUnless = nameof(HasNativeFixture))]
public Task Desktop_live_controls_pause_and_resume_the_player()
=> ui.RunAsync(async () =>
{
Core.Initialize();
using var vlc = new LibVLC("--vout=dummy", "--aout=dummy", "--no-xlib");
using var player = new MediaPlayer(vlc);
using var media = new Media(vlc, Environment.GetEnvironmentVariable("POSTIT_TEST_REPLAY")!, FromType.FromPath);
media.AddOption(":input-repeat=100");
var controls = new PostIt.Controls.ReplayControls(player, replay: false);
var toggle = controls.FindControl<Button>("ToggleButton")!;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_ct);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
async Task WaitForPlayback(bool playing)
{
while (player.IsPlaying != playing)
await Task.Delay(20, timeout.Token);
}
Assert.True(player.Play(media));
try
{
await WaitForPlayback(true);
toggle.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
await WaitForPlayback(false);
toggle.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
await WaitForPlayback(true);
}
finally { player.Stop(); }
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Ranges_use_authenticated_factory_with_bounded_exact_content_and_no_token_in_URL()
{
@ -95,6 +141,31 @@ public sealed class PodcastReplayTests
api.DownloadReplayRangeAsync(Id, 0, 256 * 1024 + 1, transport.Bytes.Length, _ct));
}
[Fact]
public async Task Draft_client_targets_owner_routes_and_reads_the_draft_source_by_range()
{
await using var transport = new RangeTransport();
var api = new PodcastApiClient(transport, () => "https://api.example/");
var prefix = $"https://api.example/api/v1/podcasts";
await api.CreateAsync(new CreatePodcastRequest { Title = "Live", RefineReplay = true, RetentionDays = 0 }, _ct);
var save = new SavePodcastDraftRequest { Revision = 2, Marks = [1000], RemovedRanges = [new(0, 500)] };
await api.SaveDraftAsync(Id, save, _ct);
await api.PublishDraftAsync(Id, 3, _ct);
await api.DeleteOriginalsAsync(Id, _ct);
Assert.Equal([$"POST {prefix}", $"PUT {prefix}/{Id}/draft", $"POST {prefix}/{Id}/draft/publish",
$"DELETE {prefix}/{Id}/originals"], transport.Calls.Select(call => call.Call));
var create = Assert.IsType<CreatePodcastRequest>(transport.Calls[0].Body);
Assert.True(create.RefineReplay);
Assert.Equal(0, create.RetentionDays);
Assert.Same(save, transport.Calls[1].Body);
Assert.Equal(3, Assert.IsType<PublishPodcastDraftRequest>(transport.Calls[2].Body).Revision);
Assert.Null(transport.Calls[3].Body);
Assert.Equal(transport.Bytes.Skip(5).Take(4), await api.DownloadDraftSourceRangeAsync(Id, 5, 4, transport.Bytes.Length, _ct));
Assert.Equal($"{prefix}/{Id}/draft/source.mp4", transport.Url);
Assert.Equal("bytes=5-8", transport.Range);
}
[Theory]
[InlineData("full")]
[InlineData("range")]
@ -163,6 +234,86 @@ public sealed class PodcastReplayTests
Assert.Equal("1:01:02", ReplayControlsState.FormatTime(3662000));
}
[Fact]
public void Drag_preview_keeps_only_the_latest_new_position()
{
var state = new ReplayControlsState();
Assert.False(state.TryTakePreview(out _));
state.RequestPreview(1000);
state.RequestPreview(2000);
Assert.True(state.TryTakePreview(out var time));
Assert.Equal(2000, time);
Assert.False(state.TryTakePreview(out _));
state.RequestPreview(2000);
Assert.False(state.TryTakePreview(out _));
state.EndPreview();
state.RequestPreview(2000);
Assert.True(state.TryTakePreview(out time));
Assert.Equal(2000, time);
}
public static bool HasFfmpeg => (Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(Path.PathSeparator).Any(dir => File.Exists(Path.Combine(dir, "ffmpeg")));
[Fact(Skip = "Install ffmpeg and LibVLC.", SkipUnless = nameof(HasFfmpeg))]
public async Task LibVLC_shows_the_exact_frame_after_seeking_while_paused()
{
const int Fps = 25, Size = 64;
var path = Path.Combine(Path.GetTempPath(), $"postit-frames-{Guid.NewGuid():N}.mp4");
try
{
// Each frame N has luma 2N; keyframes every 2 s so seeks land between keyframes.
var source = "color=black:s=" + Size + "x" + Size + ":r=" + Fps + ":d=4,format=yuv420p,geq=lum='N*2':cb=128:cr=128";
var start = new System.Diagnostics.ProcessStartInfo("ffmpeg");
foreach (var argument in new[] { "-v", "error", "-f", "lavfi", "-i", source,
"-c:v", "libx264", "-qp", "0", "-g", "50", "-pix_fmt", "yuv420p", path })
start.ArgumentList.Add(argument);
using (var ffmpeg = System.Diagnostics.Process.Start(start))
{
Assert.NotNull(ffmpeg);
await ffmpeg.WaitForExitAsync(_ct);
Assert.Equal(0, ffmpeg.ExitCode);
}
var frame = -1;
var buffer = Marshal.AllocHGlobal(Size * Size * 4);
try
{
using var vlc = new LibVLC("--no-audio");
using var player = new MediaPlayer(vlc);
using var media = new Media(vlc, path, FromType.FromPath);
player.SetVideoFormat("RV32", Size, Size, Size * 4);
player.SetVideoCallbacks((_, planes) => { Marshal.WriteIntPtr(planes, buffer); return IntPtr.Zero; }, null,
(_, _) =>
{
// Undo the limited-range YUV to RGB conversion on the red channel.
var red = Marshal.ReadByte(buffer, (Size * (Size / 2) + Size / 2) * 4 + 2);
Volatile.Write(ref frame, (int)Math.Round((red * 219.0 / 255 + 16) / 2));
});
Assert.True(player.Play(media));
await WaitFor(() => player.IsPlaying && Volatile.Read(ref frame) >= 0);
player.SetPause(true);
await WaitFor(() => !player.IsPlaying);
foreach (var target in new[] { 37, 73, 12, 61 })
{
player.Time = target * 1000L / Fps + 20;
await WaitFor(() => Volatile.Read(ref frame) == target);
Assert.Equal(target, Volatile.Read(ref frame));
Assert.False(player.IsPlaying);
}
player.Stop();
}
finally { Marshal.FreeHGlobal(buffer); }
}
finally { File.Delete(path); }
async Task WaitFor(Func<bool> condition)
{
for (var i = 0; i < 100 && !condition(); i++) await Task.Delay(50, _ct);
}
}
private sealed class Clock : TimeProvider
{
public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow;
@ -192,7 +343,12 @@ public sealed class PodcastReplayTests
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 List<(string Call, object? Body)> Calls { get; } = [];
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Calls.Add(($"{method} {path}", body));
return Task.FromResult(default(T)!);
}
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();

View file

@ -1,4 +1,3 @@
using Avalonia.Headless.XUnit;
using PostIt.Services;
using PostIt.ViewModels;
using Yavsc.Abstract.Identity;
@ -8,10 +7,12 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class PodcastScheduleTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class PodcastScheduleTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
[Fact]
public Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
@ -41,10 +42,11 @@ public sealed class PodcastScheduleTests
Assert.Empty(vm.ObsStreamKey);
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
[Fact]
public Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
@ -85,10 +87,11 @@ public sealed class PodcastScheduleTests
await vm.DeactivateAsync();
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
[Fact]
public Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-plan-{Guid.NewGuid():N}.json");
var store = new TokenStore(tokenPath);
@ -138,12 +141,122 @@ public sealed class PodcastScheduleTests
Assert.Equal("Nouveau titre", vm.Title);
}
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}, TestContext.Current.CancellationToken);
[Fact]
public Task Refinement_options_are_sent_with_the_plan_and_reloaded_on_selection()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-refine-{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", RefineReplay = true, RetentionDays = 30
};
await vm.PrepareCommand.ExecuteAsync(null);
Assert.True(api.Saved?.RefineReplay);
Assert.Equal(30, api.Saved?.RetentionDays);
vm.RefineReplay = false;
vm.RetentionDays = 0;
vm.SelectedPodcast = null;
vm.SelectedPodcast = api.Plan;
Assert.True(vm.RefineReplay);
Assert.Equal(30, vm.RetentionDays);
vm.RetentionDays = 366;
api.Saved = null;
await vm.UpdatePlanCommand.ExecuteAsync(null);
Assert.Null(api.Saved);
Assert.Contains("conservation des originaux", vm.Status);
}
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}, TestContext.Current.CancellationToken);
[Fact]
public Task Owner_publishes_an_unchanged_draft_then_deletes_the_originals()
=> ui.RunAsync(async () =>
{
var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-draft-{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");
api.Plan = api.Plan with
{
State = PodcastState.Completed, SegmentCount = 3, RefineReplay = true, FlowId = null,
Replay = new(PodcastReplayState.Pending), Draft = new(PodcastDraftState.Ready, 2, [], []),
OriginalsExpireAt = DateTimeOffset.UtcNow.AddDays(7)
};
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.Contains("non publie", vm.DraftSummary);
Assert.Contains("sera supprimee", vm.DraftSummary);
Assert.False(vm.DeleteOriginalsCommand.CanExecute(null));
await vm.PublishDraftCommand.ExecuteAsync(null);
var publish = Assert.Single(api.DraftCalls);
Assert.Equal(2, Assert.IsType<PublishPodcastDraftRequest>(publish.Body).Revision);
Assert.Equal(PodcastDraftState.Publishing, vm.SelectedPodcast?.Draft?.State);
Assert.False(vm.PublishDraftCommand.CanExecute(null));
api.Plan = api.Plan with
{
Replay = new(PodcastReplayState.Ready, 100),
Draft = api.Plan.Draft! with { State = PodcastDraftState.Ready, PublishedRevision = 2 }
};
await vm.RefreshCommand.ExecuteAsync(null);
vm.SelectedPodcast = api.Plan;
Assert.Contains("Revision 2 publiee", vm.DraftSummary);
Assert.False(vm.PublishDraftCommand.CanExecute(null));
await vm.DeleteOriginalsCommand.ExecuteAsync(null);
Assert.Equal(HttpMethod.Delete, api.DraftCalls[^1].Method);
Assert.EndsWith($"/podcasts/{api.Plan.Id}/originals", api.DraftCalls[^1].Path);
Assert.True(vm.SelectedPodcast?.OriginalsDeleted);
Assert.Contains("Originaux supprimes", vm.DraftSummary);
Assert.False(vm.DeleteOriginalsCommand.CanExecute(null));
Assert.Equal(PodcastPlaybackSource.PublishedReplay, PodcastPlayback.Choose(vm.SelectedPodcast!).Source);
vm.SelectedPodcast = api.Plan with { OwnerId = "other" };
Assert.Empty(vm.DraftSummary);
await vm.DeactivateAsync();
}
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}, TestContext.Current.CancellationToken);
[Theory]
[InlineData(PodcastState.Live, true, false, false, PodcastPlaybackSource.Originals)]
[InlineData(PodcastState.Completed, false, false, false, PodcastPlaybackSource.Pending)]
[InlineData(PodcastState.Completed, false, false, true, PodcastPlaybackSource.PublishedReplay)]
[InlineData(PodcastState.Completed, true, true, false, PodcastPlaybackSource.Originals)]
[InlineData(PodcastState.Completed, true, false, false, PodcastPlaybackSource.Unavailable)]
[InlineData(PodcastState.Interrupted, true, false, false, PodcastPlaybackSource.Unavailable)]
[InlineData(PodcastState.Interrupted, true, false, true, PodcastPlaybackSource.PublishedReplay)]
[InlineData(PodcastState.Interrupted, false, false, false, PodcastPlaybackSource.Originals)]
public void Playback_hides_unpublished_refined_originals_from_other_viewers(
PodcastState state, bool refine, bool owner, bool published, PodcastPlaybackSource expected)
{
var podcast = new PodcastResponse(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, state, 3, 300, 6)
{
RefineReplay = refine,
Draft = owner ? new(PodcastDraftState.Ready, 0, [], []) : null,
Replay = published ? new(PodcastReplayState.Ready, 100) : new(PodcastReplayState.Pending)
};
Assert.Equal(expected, PodcastPlayback.Choose(podcast).Source);
}
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",
public PodcastResponse Plan { get; 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; }
@ -151,6 +264,7 @@ public sealed class PodcastScheduleTests
public string? SavedPath { get; private set; }
public HttpMethod? SavedMethod { get; private set; }
public TaskCompletionSource<PodcastObsCredentials>? PendingActivation { get; set; }
public List<(HttpMethod Method, string Path, object? Body)> DraftCalls { get; } = [];
public override async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
@ -167,6 +281,14 @@ public sealed class PodcastScheduleTests
}
else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null);
}
else if (path.EndsWith("/draft/publish", StringComparison.Ordinal) || path.EndsWith("/originals", StringComparison.Ordinal))
{
DraftCalls.Add((method, path, body));
Plan = method == HttpMethod.Delete
? Plan with { OriginalsDeleted = true, OriginalsExpireAt = null, Draft = null }
: Plan with { Draft = Plan.Draft! with { State = PodcastDraftState.Publishing } };
response = Plan;
}
else if (method == HttpMethod.Get) response = new List<PodcastResponse> { Plan };
else
{
@ -176,7 +298,8 @@ public sealed class PodcastScheduleTests
Plan = Plan with
{
Title = Saved.Title, ScheduledStartAt = Saved.ScheduledStartAt,
PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement
PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement,
RefineReplay = Saved.RefineReplay, RetentionDays = Saved.RetentionDays
};
response = Plan;
}

View file

@ -2,9 +2,7 @@ using System.Net;
using System.Text;
using System.Text.Json;
using Avalonia;
using Avalonia.Headless.XUnit;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
@ -45,7 +43,8 @@ namespace PostIt.Tests;
/// talking to it.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class PostAclDialogTests
[Collection(AvaloniaUiCollection.Name)]
public class PostAclDialogTests(AvaloniaUiFixture ui)
{
/// <summary>
/// <see cref="HttpMessageHandler"/> that replies 200 with
@ -157,8 +156,9 @@ public class PostAclDialogTests
/// hence two HTTP requests total: GET /blogacl and GET
/// /circle).
/// </summary>
[AvaloniaFact]
public async Task LoadAsync_runs_once_on_DataContext_changed()
[Fact]
public Task LoadAsync_runs_once_on_DataContext_changed()
=> ui.RunAsync(async () =>
{
// Arrange
var (window, aclClient, circleClient, handler) = Mount();
@ -197,7 +197,7 @@ public class PostAclDialogTests
// And the VM's idempotency gate has flipped.
Assert.True(vm.Loaded);
}
}, TestContext.Current.CancellationToken);
/// <summary>
/// The fix exposes a guard on the VM too: a second call to
@ -206,8 +206,9 @@ public class PostAclDialogTests
/// DataContextChanged-firing-twice case (DataContext
/// overwritten mid-life, edge cases in dialog re-use).
/// </summary>
[AvaloniaFact]
public async Task LoadAsync_is_idempotent()
[Fact]
public Task LoadAsync_is_idempotent()
=> ui.RunAsync(async () =>
{
// Arrange
var (_, aclClient, circleClient, handler) = Mount();
@ -221,7 +222,7 @@ public class PostAclDialogTests
// Assert: the second call short-circuited on _loaded.
Assert.Equal(1, handler.RequestCount);
Assert.True(vm.Loaded);
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task LoadAsync_keeps_acl_from_blogpostdto_and_only_loads_circles()

View file

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
@ -33,4 +33,4 @@
<Compile Include="..\PostIt.Android\Services\CameraFrameOrientation.cs" Link="Android\CameraFrameOrientation.cs" />
<Compile Include="..\PostIt.Android\Services\CameraFrameClock.cs" Link="Android\CameraFrameClock.cs" />
</ItemGroup>
</Project>
</Project>

View file

@ -1,7 +1,7 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using Avalonia.VisualTree;
using PostIt.Models;
using Yavsc.Blogspot;
using Yavsc.Api.Client;
using PostIt.Services;
@ -11,7 +11,8 @@ using PostIt.Views.Blogs;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class PostItViewModelTests
[Collection(AvaloniaUiCollection.Name)]
public class PostItViewModelTests(AvaloniaUiFixture ui)
{
[Fact]
public void Draft_modified_tracks_title_body_and_attachments_not_publication()
@ -33,8 +34,9 @@ public class PostItViewModelTests
Assert.True(vm.IsDraftModified);
}
[AvaloniaFact]
public async Task Save_keeps_selection_and_editor_open_and_resets_highlight()
[Fact]
public Task Save_keeps_selection_and_editor_open_and_resets_highlight()
=> ui.RunAsync(async () =>
{
var recorder = new CallRecorder();
var vm = new BlogsViewModel(new BlogApiClient(new RecordingYavscApiClient(recorder),
@ -81,7 +83,7 @@ public class PostItViewModelTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Failed_save_preserves_draft_attachments_and_modified_state()
@ -101,8 +103,34 @@ public class PostItViewModelTests
Assert.False(vm.IsBusy);
}
[AvaloniaFact]
public void Published_badge_tracks_post_publication_state()
[Fact]
public async Task Creating_post_without_author_keeps_article_readable_and_success_status()
{
var recorder = new CallRecorder();
var vm = new BlogsViewModel(new BlogApiClient(new RecordingYavscApiClient(recorder),
"https://blogs.example.test/api/v1/"),
new Settings
{
Authentication = new AuthenticationSettings
{
Authority = "https://org.example.test"
}
});
vm.DraftTitle = "Nouveau billet";
vm.DraftArticle = "Contenu lisible.";
await vm.SaveAsync();
Assert.NotNull(vm.SelectedPost);
Assert.Equal("Contenu lisible.", vm.ReaderArticle);
Assert.Null(vm.ReaderBaseUrl);
Assert.Equal(StatusSeverity.Info, vm.ActionStatus.Severity);
Assert.Equal("Billet 42 créé.", vm.StatusMessage);
}
[Fact]
public Task Published_badge_tracks_post_publication_state()
=> ui.RunAsync(() =>
{
var post = new BlogPostDto { Id = 42, Title = "Test post", IsPublished = true };
var page = new BlogsPage();
@ -130,7 +158,7 @@ public class PostItViewModelTests
{
window.Close();
}
}
}, TestContext.Current.CancellationToken);
[Fact]
public void SearchCommand_filters_posts_by_title_article_or_author()

View file

@ -1,5 +1,4 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.ViewModels;
using PostIt.ViewModels.Commands;
using PostIt.Views.Commands;
@ -9,27 +8,30 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class RdvPageHeadlessTests
[Collection(AvaloniaUiCollection.Name)]
public class RdvPageHeadlessTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
public void Suggested_address_panel_is_hidden_by_default()
[Fact]
public Task Suggested_address_panel_is_hidden_by_default()
=> ui.RunAsync(() =>
{
var page = CreatePage(out _);
var panel = page.FindControl<Grid>("SuggestedAddressPanel");
var panel = page.FindControl<StackPanel>("SuggestedAddressPanel");
var progress = page.FindControl<ProgressBar>("SuggestedAddressProgress");
Assert.NotNull(panel);
Assert.NotNull(progress);
Assert.False(panel!.IsVisible);
Assert.False(progress!.IsVisible);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Suggested_address_panel_and_spinner_follow_viewmodel_state()
[Fact]
public Task Suggested_address_panel_and_spinner_follow_viewmodel_state()
=> ui.RunAsync(async () =>
{
var page = CreatePage(out var vm);
var panel = page.FindControl<Grid>("SuggestedAddressPanel")!;
var panel = page.FindControl<StackPanel>("SuggestedAddressPanel")!;
var progress = page.FindControl<ProgressBar>("SuggestedAddressProgress")!;
var applyButton = page.FindControl<Button>("ApplySuggestedAddressButton")!;
@ -47,17 +49,18 @@ public class RdvPageHeadlessTests
Assert.True(panel.IsVisible);
Assert.False(progress.IsVisible);
Assert.True(applyButton.IsVisible);
}
}, TestContext.Current.CancellationToken);
private static RdvPage CreatePage(out RdvViewModel vm)
private static AddressEditorPage CreatePage(out PhysicalAddressViewModel vm)
{
vm = new RdvViewModel(
var rdv = new RdvViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" },
new BillingApiClient(new RecordingApi(), "https://business.example/api/v1/"));
vm = rdv.PhysicalAddress;
var page = new RdvPage { DataContext = vm };
var page = new AddressEditorPage { DataContext = vm };
var nav = new NavigationPage();
_ = nav.PushAsync(page);
var window = new Window { Content = nav };

View file

@ -1,4 +1,4 @@
using PostIt.Views.Commands;
using PostIt.ViewModels.Commands;
namespace PostIt.Tests;
@ -8,7 +8,7 @@ public class RdvPageTests
[Fact]
public void AreCoordinatesClose_returns_true_for_nearby_points_within_cache_tolerance()
{
var result = RdvPage.AreCoordinatesClose(
var result = PhysicalAddressViewModel.AreCoordinatesClose(
48.8566,
2.3522,
48.85665,
@ -20,7 +20,7 @@ public class RdvPageTests
[Fact]
public void AreCoordinatesClose_returns_false_for_points_outside_cache_tolerance()
{
var result = RdvPage.AreCoordinatesClose(
var result = PhysicalAddressViewModel.AreCoordinatesClose(
48.8566,
2.3522,
48.85685,

View file

@ -0,0 +1,278 @@
using System.Net;
using Avalonia.Controls;
using Avalonia.Threading;
using PostIt.ViewModels;
using PostIt.Views.Blogs;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Collection(AvaloniaUiCollection.Name)]
public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
{
[Fact]
public Task Marks_are_added_at_the_current_time_once_and_ranges_flag_their_marks()
=> ui.RunAsync(() =>
{
var vm = Editor(new DraftApi());
long? seek = null;
vm.SeekRequested += t => seek = t;
vm.CurrentTimeMs = 12_000;
vm.AddMarkCommand.Execute(null);
vm.AddMarkCommand.Execute(null);
Assert.Single(vm.Marks);
Assert.Contains("existe deja", vm.Status);
vm.CurrentTimeMs = 4_000;
vm.AddMarkCommand.Execute(null);
vm.CurrentTimeMs = 20_000;
vm.AddMarkCommand.Execute(null);
Assert.Equal([4_000L, 12_000, 20_000], vm.Marks.Select(m => m.TimeMs));
vm.GoToMarkCommand.Execute(vm.Marks[1]);
Assert.Equal(12_000, seek);
// The end mark may be chosen first: the range is ordered.
vm.SetRangeEndCommand.Execute(vm.Marks[0]);
vm.SetRangeStartCommand.Execute(vm.Marks[2]);
Assert.True(vm.Marks[0].IsSelected);
vm.RemoveSelectionCommand.Execute(null);
var range = Assert.Single(vm.RemovedRanges);
Assert.Equal((4_000L, 20_000L), (range.StartMs, range.EndMs));
Assert.Equal([true, true, false], vm.Marks.Select(m => m.IsRemoved));
Assert.All(vm.Marks, m => Assert.False(m.IsSelected));
Assert.True(vm.IsDirty);
vm.RestoreRangeCommand.Execute(range);
Assert.Empty(vm.RemovedRanges);
Assert.All(vm.Marks, m => Assert.False(m.IsRemoved));
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
[Fact]
public Task Overlapping_ranges_are_merged_and_removing_everything_is_refused()
=> ui.RunAsync(() =>
{
var vm = Editor(new DraftApi());
foreach (var t in new long[] { 0, 10_000, 20_000, 30_000, 60_000 })
{
vm.CurrentTimeMs = t;
vm.AddMarkCommand.Execute(null);
}
RemoveBetween(vm, 10_000, 30_000);
RemoveBetween(vm, 20_000, 60_000);
var merged = Assert.Single(vm.RemovedRanges);
Assert.Equal((10_000L, 60_000L), (merged.StartMs, merged.EndMs));
RemoveBetween(vm, 0, 10_000);
Assert.Contains("Plage refusee", vm.Status);
Assert.Equal(merged, Assert.Single(vm.RemovedRanges));
Assert.Equal(0, vm.RangeStart?.TimeMs);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
[Fact]
public Task Saving_sends_the_read_revision_and_reloads_the_server_draft()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
var vm = Editor(api);
foreach (var t in new long[] { 5_000, 15_000, 25_000 })
{
vm.CurrentTimeMs = t;
await vm.AddMarkCommand.ExecuteAsync(null);
}
RemoveBetween(vm, 5_000, 15_000);
Assert.True(await vm.SaveAsync());
var request = Assert.IsType<SavePodcastDraftRequest>(api.Saved);
Assert.Equal(3, request.Revision);
Assert.Equal([5_000L, 15_000, 25_000], request.Marks);
Assert.Equal([new PodcastDraftRange(5_000, 15_000)], request.RemovedRanges);
// The server drops the marks inside removed ranges.
Assert.Equal([15_000L, 25_000], vm.Marks.Select(m => m.TimeMs));
Assert.Equal(4, vm.Podcast.Draft?.Revision);
Assert.False(vm.IsDirty);
Assert.False(vm.SaveCommand.CanExecute(null));
}, TestContext.Current.CancellationToken);
[Fact]
public Task A_revision_conflict_keeps_local_changes_and_asks_for_a_reload()
=> ui.RunAsync(async () =>
{
var api = new DraftApi { Conflict = true };
var vm = Editor(api);
vm.CurrentTimeMs = 5_000;
await vm.AddMarkCommand.ExecuteAsync(null);
Assert.False(await vm.SaveAsync());
Assert.Contains("Rechargez", vm.Status);
Assert.True(vm.IsDirty);
Assert.Single(vm.Marks);
Assert.Equal(3, vm.Podcast.Draft?.Revision);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Publishing_saves_pending_changes_first_and_publishes_the_saved_revision()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
var vm = Editor(api);
vm.CurrentTimeMs = 5_000;
await vm.AddMarkCommand.ExecuteAsync(null);
await vm.PublishCommand.ExecuteAsync(null);
Assert.Equal([HttpMethod.Put, HttpMethod.Post], api.Calls.Select(c => c.Method));
Assert.Equal(4, Assert.IsType<PublishPodcastDraftRequest>(api.Calls[1].Body).Revision);
Assert.Equal(PodcastDraftState.Publishing, vm.Podcast.Draft?.State);
Assert.False(vm.CanEdit);
Assert.False(vm.AddMarkCommand.CanExecute(null));
}, TestContext.Current.CancellationToken);
[Fact]
public Task Mark_titles_are_loaded_edited_and_saved_as_chapters()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
api.Podcast = api.Podcast with
{
Draft = api.Podcast.Draft! with { Marks = [5_000, 15_000, 25_000], Chapters = [new(15_000, "Invite")] }
};
var vm = Editor(api);
Assert.Equal([null, "Invite", null], vm.Marks.Select(m => m.Title));
Assert.False(vm.IsDirty);
vm.Marks[0].Title = " Ouverture\t";
Assert.True(vm.IsDirty);
vm.Marks[1].Title = "Coupee";
vm.Marks[2].Title = " ";
// [15 s, 25 s) removes the start mark and keeps the end mark.
RemoveBetween(vm, 25_000, 15_000);
Assert.True(await vm.SaveAsync());
Assert.Equal([new PodcastChapter(5_000, "Ouverture"), new PodcastChapter(15_000, "Coupee")], api.Saved!.Chapters);
// The server drops the title of a removed mark.
Assert.Equal([5_000L, 25_000], vm.Marks.Select(m => m.TimeMs));
Assert.Equal(["Ouverture", null], vm.Marks.Select(m => m.Title));
Assert.False(vm.IsDirty);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Published_chapters_seek_the_replay_player()
=> ui.RunAsync(() =>
{
var vm = new VideoPageViewModel(new Uri("https://api.example/replay.mp4"), "video/mp4");
long? seek = null;
vm.SeekRequested += t => seek = t;
Assert.False(vm.HasChapters);
vm.ShowChapters([new(0, "Intro"), new(61_500, "Fin")]);
Assert.True(vm.HasChapters);
Assert.Equal("1:01 Fin", vm.Chapters[1].Label);
vm.GoToChapterCommand.Execute(vm.Chapters[1]);
Assert.Equal(61_500, seek);
vm.ShowChapters([]);
Assert.False(vm.HasChapters);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
[Fact]
public Task The_editor_stacks_its_panel_under_the_video_in_portrait()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
// Without a draft source the page skips the native player.
api.Podcast = api.Podcast with { Draft = api.Podcast.Draft! with { SourceBytes = 0 } };
var page = new ReplayEditorPage { DataContext = Editor(api) };
var nav = new NavigationPage();
await nav.PushAsync(page);
var window = new Window { Width = 360, Height = 800, Content = nav };
try
{
window.Show();
foreach (var (width, height) in new[] { (360, 800), (1000, 500), (360, 800) })
{
window.Width = width;
window.Height = height;
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var wide = width >= height;
var grid = page.FindControl<Grid>("EditorGrid")!;
var panel = page.FindControl<ScrollViewer>("EditPanel")!;
Assert.Equal(wide ? 2 : 1, grid.ColumnDefinitions.Count);
Assert.Equal(wide ? 1 : 0, Grid.GetColumn(panel));
Assert.Equal(wide ? 1 : 4, Grid.GetRow(panel));
Assert.True(panel.Bounds.Top >= (wide ? 0 : page.FindControl<Border>("VideoBorder")!.Bounds.Bottom));
}
Assert.Contains("source du brouillon", page.FindControl<TextBlock>("PlaybackStatus")!.Text);
}
finally { window.Close(); }
}, TestContext.Current.CancellationToken);
private static ReplayEditorPageViewModel Editor(DraftApi api)
=> new(new PodcastApiClient(api, () => "https://api.example/"), api.Podcast);
private static void RemoveBetween(ReplayEditorPageViewModel vm, long start, long end)
{
vm.SetRangeStartCommand.Execute(vm.Marks.Single(m => m.TimeMs == start));
vm.SetRangeEndCommand.Execute(vm.Marks.Single(m => m.TimeMs == end));
vm.RemoveSelectionCommand.Execute(null);
}
private sealed class DraftApi : IYavscApiClient
{
public PodcastResponse Podcast { get; set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Completed, 1, 1024, 60)
{
RefineReplay = true,
Draft = new PodcastDraftResponse(PodcastDraftState.Ready, 3, [], [], 1024)
};
public bool Conflict { get; init; }
public SavePodcastDraftRequest? Saved { get; private set; }
public List<(HttpMethod Method, string Path, object? Body)> Calls { get; } = [];
public HttpClient Http { get; } = new();
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Calls.Add((method, path, body));
if (Conflict) throw new HttpRequestException("conflict", null, HttpStatusCode.Conflict);
var draft = Podcast.Draft!;
if (path.EndsWith("/draft", StringComparison.Ordinal))
{
Saved = Assert.IsType<SavePodcastDraftRequest>(body);
var ranges = Saved.RemovedRanges;
var marks = Saved.Marks.Where(m => !ranges.Any(r => m >= r.StartMs && m < r.EndMs)).ToArray();
Podcast = Podcast with
{
Draft = draft with
{
Revision = draft.Revision + 1, Marks = marks, RemovedRanges = ranges,
Chapters = Saved.Chapters.Where(c => marks.Contains(c.TimeMs)).ToArray()
}
};
}
else if (path.EndsWith("/draft/publish", StringComparison.Ordinal))
Podcast = Podcast with { Draft = draft with { State = PodcastDraftState.Publishing } };
else throw new InvalidOperationException(path);
return Task.FromResult((T)(object)Podcast);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> throw new NotSupportedException();
public ValueTask DisposeAsync()
{
Http.Dispose();
return ValueTask.CompletedTask;
}
}
}

View file

@ -1,7 +1,6 @@
using System.Net;
using System.Net.Http;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using PostIt.ViewModels;
using PostIt.Views;
@ -11,7 +10,8 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class ResourceUsageReliefPageTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class ResourceUsageReliefPageTests(AvaloniaUiFixture ui)
{
private static ResourceUsageSummary Usage(string id, decimal consumption, decimal credits = 0m) => new()
{
@ -20,11 +20,12 @@ public sealed class ResourceUsageReliefPageTests
RemainingConsumption = Math.Max(0m, 1000m - consumption)
};
[AvaloniaTheory]
[Theory]
[InlineData("Moderator")]
[InlineData("administrator")]
[InlineData("Performer")]
public async Task Nonadministrators_cannot_load_or_erase_or_open_the_page(string role)
public Task Nonadministrators_cannot_load_or_erase_or_open_the_page(string role)
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport(role);
var session = new SessionStatusViewModel { Api = profile };
@ -40,10 +41,11 @@ public sealed class ResourceUsageReliefPageTests
var administration = new AdministrationPageViewModel(null, session: session);
await administration.OpenResourceUsageReliefCommand.ExecuteAsync(null);
Assert.Contains("Administrator", administration.StatusMessage);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Page_loads_only_exhausted_users_and_confirmed_remission_updates_the_result()
[Fact]
public Task Page_loads_only_exhausted_users_and_confirmed_remission_updates_the_result()
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -77,9 +79,9 @@ public sealed class ResourceUsageReliefPageTests
Assert.Contains("alice", vm.StatusMessage);
Assert.Contains("GET https://example.invalid/api/v1/resource-usage/admin", transport.Requests);
Assert.Contains("POST https://example.invalid/api/v1/resource-usage/admin/alice/erase", transport.Requests);
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData("")]
[InlineData("0")]
[InlineData("-1")]
@ -88,7 +90,8 @@ public sealed class ResourceUsageReliefPageTests
[InlineData("1,000.00")]
[InlineData("NaN")]
[InlineData("1e2")]
public async Task Invalid_amounts_never_reach_the_API(string amount)
public Task Invalid_amounts_never_reach_the_API(string amount)
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -102,10 +105,11 @@ public sealed class ResourceUsageReliefPageTests
Assert.NotEmpty(vm.AmountError);
await vm.EraseCommand.ExecuteAsync(null);
Assert.Null(transport.Erasure);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Changing_target_or_amount_or_refreshing_invalidates_confirmation()
[Fact]
public Task Changing_target_or_amount_or_refreshing_invalidates_confirmation()
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -127,10 +131,11 @@ public sealed class ResourceUsageReliefPageTests
Assert.False(vm.ConfirmErasure);
Assert.Empty(vm.PointsText);
Assert.Equal("bob", vm.SelectedUsage?.UserId);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Failure_requires_a_fresh_snapshot_before_retry()
[Fact]
public Task Failure_requires_a_fresh_snapshot_before_retry()
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -152,10 +157,11 @@ public sealed class ResourceUsageReliefPageTests
vm.PointsText = "100";
vm.ConfirmErasure = true;
Assert.True(vm.EraseCommand.CanExecute(null));
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Logout_clears_private_data_and_a_late_response_cannot_restore_it()
[Fact]
public Task Logout_clears_private_data_and_a_late_response_cannot_restore_it()
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -171,12 +177,13 @@ public sealed class ResourceUsageReliefPageTests
Assert.Null(vm.SelectedUsage);
Assert.False(vm.IsAdministrator);
Assert.False(vm.EraseCommand.CanExecute(null));
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(400, 800)]
[InlineData(800, 400)]
public async Task Page_displays_target_preview_and_explicit_confirmation_and_disposes_on_exit(int width, int height)
public Task Page_displays_target_preview_and_explicit_confirmation_and_disposes_on_exit(int width, int height)
=> ui.RunAsync(async () =>
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
@ -205,7 +212,7 @@ public sealed class ResourceUsageReliefPageTests
Assert.False(vm.IsAdministrator);
Assert.Empty(vm.Users);
Assert.False(vm.ConfirmErasure);
}
}, TestContext.Current.CancellationToken);
private sealed class Transport : IYavscApiClient
{

View file

@ -147,43 +147,7 @@ public sealed class SessionAuthenticationTests(AvaloniaUiFixture ui)
finally { File.Delete(path); }
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Modal_restores_the_previous_page_and_focus_after_silent_recovery()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
try
{
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddMinutes(10)));
await using var api = new ProfileApi(new Settings(), store);
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
await ui.WithWindowAsync(() => new MainView
{
DataContext = new HomePageViewModel(api, api.Settings, session, null!)
}, async window =>
{
var root = Assert.IsType<MainView>(window.Content);
var editor = new TextBox { Text = "Brouillon conservé" };
var page = new ContentPage { Content = editor };
await root.NavRoot.PushAsync(page, null);
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
Assert.True(editor.Focus());
session.SetError("Session temporairement indisponible");
Dispatcher.UIThread.RunJobs();
Assert.True(root.LoginButton.IsFocused);
session.Refresh();
Dispatcher.UIThread.RunJobs();
Assert.False(root.AuthenticationModal.IsVisible);
Assert.True(root.NavRoot.IsEnabled);
Assert.True(editor.IsFocused);
Assert.Same(page, root.NavRoot.NavigationStack.Last());
Assert.Equal("Brouillon conservé", editor.Text);
}, TestContext.Current.CancellationToken);
}
finally { File.Delete(path); }
}
[Fact]
public Task Revoked_background_session_opens_the_modal_and_login_recovers()

View file

@ -5,6 +5,34 @@ namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class SettingsLoadTests
{
[Fact]
public void Contact_options_survive_save_and_load_and_legacy_settings_keep_defaults()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-contact-{Guid.NewGuid():N}.json");
try
{
File.WriteAllText(path, "{}");
var settings = new PostIt.ViewModels.Settings(path);
settings.Load();
Assert.True(settings.AllowAudioCalls);
Assert.True(settings.AllowVideoCalls);
Assert.True(settings.AllowPrivateMessages);
settings.AllowAudioCalls = false;
settings.AllowPrivateMessages = false;
Assert.True(settings.IsDirty);
settings.Save();
var restored = new PostIt.ViewModels.Settings(path);
restored.Load();
Assert.False(restored.AllowAudioCalls);
Assert.True(restored.AllowVideoCalls);
Assert.False(restored.AllowPrivateMessages);
Assert.False(restored.IsDirty);
}
finally { File.Delete(path); }
}
/// <summary>
/// On the dev machine, the user-level settings file
/// (~/.config/PostIt/postit-settings.json) does not exist, so Load()
@ -17,7 +45,7 @@ public class SettingsLoadTests
// Skip if a user-level file exists (CI / different dev machines).
var userConfigPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt",
App.AppName,
"postit-settings.json");
if (File.Exists(userConfigPath))
{

View file

@ -1,39 +0,0 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
using PostIt.Controls;
using PostIt.Models;
using PostIt.ViewModels;
namespace PostIt.Tests;
/// <summary>
/// The <see cref="StatusBar"/> surfaces the page's action status
/// (success / warning / error message). The user reported being
/// unable to copy these messages — the status text was a
/// <c>TextBlock</c>, which Avalonia does not make selectable. It is
/// now a <see cref="SelectableTextBlock"/> so the message can be
/// selected and copied (Ctrl+C / context menu). This test pins that:
/// if the message control regresses to a plain <c>TextBlock</c>,
/// selectability is lost and the test fails.
/// </summary>
[Trait("Category", "non-reg")]
public class StatusBarTests
{
[AvaloniaFact]
public void Status_message_is_rendered_by_a_SelectableTextBlock()
{
var bar = new StatusBar {
DataContext =
StatusNotice.Error("Échec de la suppression : boom") };
var window = new Window { Content = bar };
window.Show();
var message = bar.GetVisualDescendants()
.OfType<SelectableTextBlock>()
.FirstOrDefault();
Assert.NotNull(message);
Assert.Equal("Échec de la suppression : boom", message!.Text);
}
}

View file

@ -0,0 +1,89 @@
using System.Net.Http;
using System.Text;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class UserFilesApiClientTests
{
[Fact]
public async Task Upload_from_file_streams_video_to_screencast_directory()
{
string filePath = Path.Combine(Path.GetTempPath(), $"postit-{Guid.NewGuid():N}.mp4");
byte[] expected = [0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70];
await File.WriteAllBytesAsync(filePath, expected, TestContext.Current.CancellationToken);
try
{
var api = new UploadApi();
var client = new UserFilesApiClient(api, "https://blogs.example/api/v1/");
var received = await client.UploadAsync(
"screencast",
filePath,
"video/mp4",
TestContext.Current.CancellationToken);
Assert.Single(received);
Assert.Equal(HttpMethod.Post, api.Method);
Assert.Equal("fs/screencast", api.Path);
string multipart = Encoding.UTF8.GetString(api.MultipartBody);
Assert.Contains(Path.GetFileName(filePath), multipart);
Assert.Contains("video/mp4", multipart);
Assert.True(api.MultipartBody.AsSpan().IndexOf(expected) >= 0);
}
finally
{
File.Delete(filePath);
}
}
private sealed class UploadApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public HttpMethod? Method { get; private set; }
public string? Path { get; private set; }
public byte[] MultipartBody { get; private set; } = [];
public async Task<T> CallAsync<T>(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default)
{
Method = method;
Path = path;
using HttpContent content = contentFactory();
MultipartBody = await content.ReadAsByteArrayAsync(ct);
return (T)(object)new List<FileReceivedDto>
{
new() { FileName = Path, ContentType = "video/mp4", Length = MultipartBody.Length }
};
}
public Task<T> CallAsync<T>(
HttpMethod method,
string path,
object? body = null,
CancellationToken ct = default) => throw new NotSupportedException();
public Task CallAsync(
HttpMethod method,
string path,
object? body = null,
CancellationToken ct = default) => throw new NotSupportedException();
public Task CallAsync(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default) => throw new NotSupportedException();
public Task<byte[]> DownloadAsync(
HttpMethod method,
string path,
CancellationToken ct = default) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -11,15 +11,17 @@ namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class WebRtcCallViewModelTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class WebRtcCallViewModelTests(AvaloniaUiFixture ui)
{
private static readonly CallIceServer[] Turn = [new(["turn:localhost:3478"], "temporary", "password")];
private const string Sdp = "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\nc=IN IP4 0.0.0.0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n";
[AvaloniaTheory]
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Outgoing_waits_for_acceptance_and_passes_server_policy_to_native_engine(bool relay)
public Task Outgoing_waits_for_acceptance_and_passes_server_policy_to_native_engine(bool relay)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(relay);
var media = new Media();
@ -42,10 +44,81 @@ public sealed class WebRtcCallViewModelTests
Assert.Null(vm.LocalVideo);
Assert.False(vm.Busy);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Incoming_relay_needs_acceptance_but_never_requires_IP_disclosure()
[Theory]
[InlineData(true)]
[InlineData(false)]
public Task Audio_call_uses_only_microphone_and_monitors_audio(bool outgoing)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
vm.Camera = null;
if (outgoing)
await vm.InviteAudioCommand.ExecuteAsync(null);
else
{
signaling.InviteAudio();
await WaitAsync(() => vm.Incoming);
await vm.AcceptCommand.ExecuteAsync(null);
}
Assert.True(vm.AudioOnly);
if (outgoing) signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
Assert.True(media.Configuration!.AudioOnly);
Assert.Equal("", media.Configuration.Camera);
Assert.Equal("default", media.Configuration.Microphone);
Assert.Null(vm.LocalVideo);
Assert.Null(vm.RemoteVideo);
media.Report(new("connected", "relay", 20, 0));
await WaitAsync(() => vm.Status.Contains("Audio WebRTC etabli"));
}, TestContext.Current.CancellationToken);
[Fact]
public Task Accepted_mode_mismatch_ends_call_without_opening_media()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
await vm.InviteAudioCommand.ExecuteAsync(null);
signaling.Ready(signaling.Call with { DisplayMode = CallDisplayMode.AudioVideo });
await WaitAsync(() => !vm.Busy);
Assert.Null(media.Configuration);
Assert.Single(signaling.EndedCalls);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Audio_call_loads_the_remote_avatar_without_blocking_hangup()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
var avatar = new TaskCompletionSource<Bitmap?>(TaskCreationOptions.RunContinuationsAsynchronously);
string? requestedUser = null;
await using var vm = new WebRtcCallViewModel(signaling, () => media, loadAvatar: user =>
{
requestedUser = user;
return avatar.Task;
})
{ Microphone = new("Mic", "default"), Target = " bob ", Room = "General" };
await vm.InviteAudioCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => requestedUser is not null);
Assert.Equal("bob", requestedUser);
await vm.HangupAsync();
avatar.SetResult(null);
await Task.Delay(20, TestContext.Current.CancellationToken);
Assert.False(vm.Busy);
Assert.Null(vm.RemoteAvatar);
Assert.Equal("", vm.AvatarStatus);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Incoming_relay_needs_acceptance_but_never_requires_IP_disclosure()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
@ -59,10 +132,11 @@ public sealed class WebRtcCallViewModelTests
Assert.False(media.Configuration!.Caller);
media.Report(new("connected", "relay", 20, 20));
await WaitAsync(() => vm.Status.Contains("IP masquee"));
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Direct_call_without_consent_ends_before_any_capture()
[Fact]
public Task Direct_call_without_consent_ends_before_any_capture()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(false);
var media = new Media();
@ -72,12 +146,13 @@ public sealed class WebRtcCallViewModelTests
Assert.False(vm.Busy);
Assert.Contains("consentez", vm.Status);
Assert.Single(signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Missing_TURN_or_policy_downgrade_never_creates_a_native_engine(bool downgrade)
public Task Missing_TURN_or_policy_downgrade_never_creates_a_native_engine(bool downgrade)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var created = false;
@ -93,15 +168,16 @@ public sealed class WebRtcCallViewModelTests
await WaitAsync(() => !vm.Busy);
Assert.False(created);
Assert.Single(signaling.EndedCalls);
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData("hangup")]
[InlineData("interrupted")]
[InlineData("ended")]
[InlineData("background")]
[InlineData("dispose")]
public async Task All_termination_paths_cancel_in_progress_native_startup(string reason)
public Task All_termination_paths_cancel_in_progress_native_startup(string reason)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media { DelayStartup = true };
@ -121,13 +197,14 @@ public sealed class WebRtcCallViewModelTests
Assert.False(vm.Busy);
Assert.Null(vm.RemoteVideo);
Assert.True(media.StartupCancelled);
}
}, TestContext.Current.CancellationToken);
[AvaloniaTheory]
[Theory]
[InlineData("host")]
[InlineData("srflx")]
[InlineData(null)]
public async Task Nonrelay_selected_path_is_rejected_and_media_is_stopped(string? candidateType)
public Task Nonrelay_selected_path_is_rejected_and_media_is_stopped(string? candidateType)
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
@ -138,10 +215,11 @@ public sealed class WebRtcCallViewModelTests
media.Report(new("connected", candidateType, 20, 20));
await WaitAsync(() => media.Disposed);
Assert.Contains("chemin ICE", vm.Status);
}
}, TestContext.Current.CancellationToken);
[AvaloniaFact]
public async Task Leaking_candidate_is_not_sent_and_fails_closed()
[Fact]
public Task Leaking_candidate_is_not_sent_and_fails_closed()
=> ui.RunAsync(async () =>
{
var signaling = new Signaling(true);
var media = new Media();
@ -154,7 +232,7 @@ public sealed class WebRtcCallViewModelTests
await WaitAsync(() => media.Disposed);
Assert.Empty(signaling.Sent);
Assert.Contains("candidat", vm.Status);
}
}, TestContext.Current.CancellationToken);
//[AvaloniaFact]
public async Task Native_failure_is_visible_and_ends_the_server_call()
@ -193,9 +271,10 @@ public sealed class WebRtcCallViewModelTests
public static bool NativeMediaAvailable => OperatingSystem.IsLinux() &&
Environment.GetEnvironmentVariable("POSTIT_TEST_NATIVE_WEBRTC") == "1";
[AvaloniaFact(Skip = "Requires Linux GStreamer/libnice and POSTIT_TEST_NATIVE_WEBRTC=1",
[Fact(Skip = "Requires Linux GStreamer/libnice and POSTIT_TEST_NATIVE_WEBRTC=1",
SkipUnless = nameof(NativeMediaAvailable))]
public async Task Linux_native_adapters_render_remote_bitmaps_and_receive_audio_in_both_directions()
public Task Linux_native_adapters_render_remote_bitmaps_and_receive_audio_in_both_directions()
=> ui.RunAsync(async () =>
{
await using var caller = new LinuxWebRtcMedia();
await using var callee = new LinuxWebRtcMedia();
@ -224,7 +303,7 @@ public sealed class WebRtcCallViewModelTests
}
Assert.Equal(640, ((Bitmap)((Image)caller.RemoteVideo).Source!).PixelSize.Width);
Assert.Equal(360, ((Bitmap)((Image)callee.RemoteVideo).Source!).PixelSize.Height);
}
}, TestContext.Current.CancellationToken);
private static WebRtcCallViewModel Configure(Signaling signaling, Media media) => new(signaling, () => media)
{ Camera = new("Camera", "camera"), Microphone = new("Mic", "default"), Target = "bob", Room = "General" };
@ -275,19 +354,31 @@ public sealed class WebRtcCallViewModelTests
public event Action<CallEnded>? Ended;
public event Action<Guid, CallSignal>? Signal;
public event Action? Interrupted;
public CallSession Call { get; } = new(Guid.NewGuid(), "General", "alice", "bob", relay,
public CallSession Call { get; private set; } = new(Guid.NewGuid(), "General", "alice", "bob", relay,
DateTimeOffset.UtcNow.AddMinutes(1));
public List<CallSignal> Sent { get; } = [];
public List<Guid> EndedCalls { get; } = [];
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) => Task.FromResult(Call);
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default)
{
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
return Task.FromResult(Call);
}
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
throw new InvalidOperationException("Legacy LAN transport must not be used");
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default) =>
throw new InvalidOperationException("Legacy LAN transport must not be used");
public Task AcceptAsync(Guid callId, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
public Task EndAsync(Guid callId, CancellationToken ct = default)
{ EndedCalls.Add(callId); return Task.CompletedTask; }
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
{ Sent.Add(signal); return Task.CompletedTask; }
public void Invite() => Invitation?.Invoke(Call);
public void InviteAudio()
{
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
Invitation?.Invoke(Call);
}
public void Ready(CallSession? session = null, CallIceServer[]? servers = null) =>
Accepted?.Invoke(new(session ?? Call, servers ?? Turn));
public void Receive(CallSignal signal) => Signal?.Invoke(Call.Id, signal);

View file

@ -1,4 +1,7 @@
using System;
using System.Globalization;
using System.Linq;
using System.Reactive;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@ -6,17 +9,14 @@ using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Styling;
using Avalonia.Threading;
using Live.Avalonia;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers;
using PostIt.Interfaces;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Helpers;
using System.Globalization;
using Live.Avalonia;
using System.Diagnostics;
using System.Linq;
using ReactiveUI;
using System.Reactive;
namespace PostIt;
@ -122,19 +122,20 @@ public partial class App : Application, ILiveView, IVMPusherApp
base.OnFrameworkInitializationCompleted();
}
public static string AppName { get; } = "PostIt";
private static void OnUnhandledException(object? sender, UnhandledExceptionEventArgs args)
{
if (args.ExceptionObject is Exception exception && Current is App app)
app.ServiceProvider?.GetService<YavscApiClient>()
?.QueueExceptionReport(exception, "PostIt");
?.QueueExceptionReport(exception, AppName);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
{
if (Current is App app)
app.ServiceProvider?.GetService<YavscApiClient>()
?.QueueExceptionReport(args.Exception, "PostIt");
?.QueueExceptionReport(args.Exception, AppName);
}
private bool IsProduction()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Before After
Before After

View file

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
viewBox="0 0 64 64"
width="128"
height="128"
version="1.1"
id="svg4"
sodipodi:docname="post.svg"
inkscape:export-filename="post.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
inkscape:version="1.4 (e7c3feb100, 2024-10-09)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs4">
<color-profile
name="Iiyama-North-America-24"
xlink:href="../../../../../../.local/share/icc/edid-2d1abd908c88b0dc41a3a48a98bcbd58.icc"
id="color-profile1" />
</defs>
<sodipodi:namedview
id="namedview4"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="false"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="6.40625"
inkscape:cx="64.078049"
inkscape:cy="64.078049"
inkscape:window-width="1311"
inkscape:window-height="866"
inkscape:window-x="410"
inkscape:window-y="97"
inkscape:window-maximized="0"
inkscape:current-layer="svg4"
showborder="false"
borderlayer="false" />
<path
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
d="M32 6 L52 14 V30 C52 44 43 54 32 58 C21 54 12 44 12 30 V14 L32 6 Z"
id="path1"
style="fill:#ff0000" />
<path
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
d="M23 30 A9 9 0 0 1 39 24"
id="path2" />
<polyline
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
points="39 20 39 25 34 25"
id="polyline2" />
<path
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
d="M41 32 A9 9 0 0 1 25 38"
id="path3" />
<polyline
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
points="25 42 25 37 30 37"
id="polyline3" />
<polyline
fill="none"
stroke="#1e293b"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
points="28 31 31 34 37 28"
id="polyline4" />
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View file

@ -1,165 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="2mm"
height="2mm"
viewBox="0 0 2 2"
version="1.1"
id="svg1"
inkscape:version="1.4 (e7c3feb100, 2024-10-09)"
sodipodi:docname="post.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
inkscape:zoom="66.117261"
inkscape:cx="3.9475319"
inkscape:cy="4.1819639"
inkscape:window-width="1530"
inkscape:window-height="860"
inkscape:window-x="345"
inkscape:window-y="117"
inkscape:window-maximized="0"
inkscape:current-layer="layer1"
showguides="true" />
<defs
id="defs1">
<filter
inkscape:collect="always"
style="color-interpolation-filters:sRGB"
id="filter13"
x="-0.057605849"
y="-0.0866385"
width="1.1152117"
height="1.173277">
<feGaussianBlur
inkscape:collect="always"
stdDeviation="0.043600373"
id="feGaussianBlur13" />
</filter>
</defs>
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1">
<ellipse
style="fill:#550000;stroke-width:0.264583"
id="path1"
cx="0.64627916"
cy="0.81235087"
rx="0.28212187"
ry="0.26411408" />
<ellipse
style="fill:#ff0000;stroke-width:0.264583"
id="path2"
cx="1.3305748"
cy="1.3205703"
rx="0.22209594"
ry="0.22809853" />
<ellipse
style="fill:#008080;stroke-width:0.264583"
id="path3"
cx="0.53423077"
cy="1.4526274"
rx="0.18207864"
ry="0.20008641" />
<ellipse
style="fill:#aa0000;stroke-width:0.264583"
id="path4"
cx="0.69229901"
cy="1.356586"
rx="0.19608469"
ry="0.18808123" />
<ellipse
style="fill:#ff9955;stroke-width:0.264583"
id="path5"
cx="0.68229473"
cy="1.2165256"
rx="0.3461495"
ry="0.20408815" />
<ellipse
style="fill:#666666;stroke-width:0.264583"
id="path6"
cx="0.92039758"
cy="1.2945592"
rx="0.35215211"
ry="0.35015127" />
<ellipse
style="fill:#ffff00;stroke-width:0.264583"
id="path7"
cx="1.29656"
cy="0.8783794"
rx="0.34815037"
ry="0.31013396" />
<ellipse
style="fill:#00ff37;stroke-width:0.264583;fill-opacity:1"
id="path8"
cx="1.0024331"
cy="0.84236389"
rx="0.36615816"
ry="0.31813741" />
<ellipse
style="fill:#42ff00;fill-opacity:1;stroke-width:0.264583"
id="path9"
cx="1.2325324"
cy="1.1705056"
rx="0.280121"
ry="0.26611495" />
<ellipse
style="fill:#ff00e8;fill-opacity:1;stroke-width:0.264583"
id="path10"
cx="1.4526274"
cy="0.9404062"
rx="0.29612792"
ry="0.1280553" />
<ellipse
style="fill:#ff0095;fill-opacity:1;stroke-width:0.264583"
id="path11"
cx="1.5866853"
cy="0.99042773"
rx="0.13805965"
ry="0.074031979" />
<ellipse
style="fill:#ff001d;fill-opacity:1;stroke-width:0.264583"
id="path12"
cx="1.5266595"
cy="1.0944728"
rx="0.20208728"
ry="0.098042347" />
<path
style="fill:#eeffaa;fill-opacity:1;stroke-width:0.264583;filter:url(#filter13);opacity:0.73587606"
d="m 0.41217805,0.41617976 c 0.12405357,-0.0360156 0.0960415,-0.12005185 0.24410542,-0.10804668 0.14806396,0.0120052 0.2080899,0.0680294 0.25611063,0.13205706 0.0480207,0.0640277 0.2120916,0.20008641 0.3001296,0.20408815 0.088038,0.004002 0.4521953,0.0480207 0.516223,0.0960415 0.064028,0.0480207 0.1440622,0.18808125 0.1600692,0.26011231 0.016007,0.072031 -0.008,0.236102 -0.064028,0.3121348 -0.056024,0.076033 -0.1600692,0.192083 -0.280121,0.2000865 -0.1200519,0.008 -0.3561538,-0.008 -0.4601988,-0.028012 C 0.98042348,1.4646326 0.69229903,1.3685911 0.59625756,1.3805963 0.50021606,1.3926015 0.4762057,1.4206136 0.33614518,1.3926015 0.1960847,1.3645894 0.15206568,1.29656 0.12805531,1.1805099 0.10404494,1.0644598 0.04802074,0.92039756 0.09604148,0.83235952 0.14406223,0.74432151 0.42818494,0.64828001 0.46019878,0.57624889 0.4922126,0.5042178 0.41217805,0.41617976 0.41217805,0.41617976 Z"
id="path13" />
<path
style="opacity:1;fill:#28170b;fill-opacity:1;stroke-width:0.264583"
d="m 0.36815878,1.2725431 c 0.001648,0 0.0109472,0.00106 0.0120052,0 0.001886,-0.00188 -0.001886,-0.00611 0,-0.008 9.43e-4,-9.419e-4 0.00306,9.419e-4 0.004002,0 0.001886,-0.00188 -0.001193,-0.00561 0,-0.008 0.008442,-0.016884 0.011641,-0.022553 0.016007,-0.040017 0.006945,-0.027778 0.004002,-0.058763 0.004002,-0.088038 0,-0.026679 0,-0.053357 0,-0.080035 0,-0.00937 0.002281,-0.022894 0,-0.032014 -0.004221,-0.016884 -0.009427,-0.027568 -0.016007,-0.044019 -0.004035,-0.0100859 -5.08e-4,-0.0255323 -0.004002,-0.0360156 -0.0137069,-0.0411205 -0.0282181,-0.0764446 -0.0480208,-0.11605011 -0.002668,-0.005336 0.013339,0.013339 0.008003,0.016007 -0.005335,0.002668 -0.005335,-0.010671 -0.008003,-0.016007 0.008032,-0.0133309 0.0743379,-0.007438 0.0880381,-0.0120052 0.007985,-0.002662 0.0270672,-0.008476 0.0360155,-0.004002 0.0103265,0.005163 0.020164,0.008055 0.0320138,0.0120052 0.002531,8.4363e-4 0.005617,-0.001193 0.008003,0 0.004661,0.002331 0.007344,0.005673 0.0120052,0.008003 0.003201,0.001601 0.008804,-0.001601 0.0120052,0 0.004528,0.002264 0.0115165,0.00501 0.0160069,0.008003 0.007732,0.005154 0.0100794,0.0140812 0.0160069,0.0200086 0.002979,0.002979 0.0119739,0.002626 0.0160069,0.008003 0.009995,0.0133271 0.0109317,0.0367967 0.0160069,0.0520225 0.009426,0.0282774 0.003846,0.0642615 -0.0120052,0.088038 -0.0133237,0.019986 -0.0434103,0.027769 -0.0640277,0.036016 -0.0131912,0.00528 -0.0230733,0.011693 -0.0360156,0.016007 -0.00507,0.00169 -0.0667892,0.00662 -0.0720311,0.004 -0.001687,-8.436e-4 -0.002212,-0.00341 -0.004002,-0.004 -0.007329,-0.00244 -0.0240104,3.57e-5 -0.0240104,-0.012005"
id="path14" />
<path
style="opacity:1;fill:#2b0000;fill-opacity:1;stroke-width:0.264583"
d="M 0.83235952,1.0244425 C 0.82871252,1.0099415 0.82391152,0.9839808 0.81235092,0.97242 0.80936792,0.969437 0.80371992,0.970949 0.80034572,0.968418 0.79795872,0.966629 0.79813372,0.962801 0.79634372,0.960415 0.78935272,0.951095 0.77769452,0.9426466 0.76833162,0.9364046 c -0.031756,-0.0211706 -0.09517,-0.0164425 -0.12805531,0 -0.006749,0.003374 -0.0101148,0.0112932 -0.016007,0.016007 -0.003755,0.003004 -0.009119,0.004156 -0.0120052,0.008003 -0.005369,0.007159 -0.007263,0.0164224 -0.0120052,0.0240104 -0.002,0.003199 -0.006316,0.004629 -0.008003,0.008003 -0.006843,0.0136861 -0.0122872,0.0410307 -0.008003,0.0560242 0.001638,0.00574 0.006117,0.010348 0.008003,0.016007 0.0055,0.016501 0.005417,0.035552 0.0120052,0.052022 0.004523,0.011308 0.0108246,0.025651 0.016007,0.036016 0.002983,0.00597 0.009896,0.00968 0.0120052,0.016007 0.003673,0.01102 0.006248,0.029135 0.0200086,0.036016 0.001193,5.953e-4 0.003059,-9.446e-4 0.004002,0 9.4192e-4,9.419e-4 -9.4191e-4,0.00306 0,0.004 9.4192e-4,9.419e-4 0.003059,-9.419e-4 0.004002,0 9.4191e-4,9.419e-4 -9.4456e-4,0.00306 0,0.004 0.002983,0.00298 0.008631,0.00147 0.0120052,0.004 0.006517,0.00489 0.0126595,0.012333 0.0200086,0.016007 0.010899,0.00545 0.0117131,0.00124 0.0200086,0.004 0.005559,0.00185 0.0418744,0.0081 0.0480207,0.004 0.009386,-0.00626 0.0286541,-0.021934 0.0320138,-0.032014 8.4402e-4,-0.00253 -0.001193,-0.00562 0,-0.008 0.004717,-0.00943 0.0207465,-0.01822 0.0240104,-0.028012 8.4402e-4,-0.00253 -4.3921e-4,-0.00537 0,-0.008 0.001333,-0.00534 0.002668,-0.010671 0.004002,-0.016007 0.001333,-0.00133 0.003405,-0.00221 0.004002,-0.004 0.001122,-0.00336 0.003981,-0.02791 0.004002,-0.028012 0.004677,-0.023382 -4.173e-5,-0.063736 0.004002,-0.09204 z"
id="path15" />
<path
style="opacity:1;fill:#2b0000;fill-opacity:1;stroke-width:0.264583"
d="M 1.164503,0.9123941 C 1.159163,0.9110611 1.14983,0.9030571 1.148496,0.9083921 1.147166,0.9137281 1.169839,0.9137281 1.164503,0.9123941 1.134514,0.9048971 1.10496,0.897882 1.076465,0.8883837 1.051899,0.8801947 1.068495,0.88749735 1.040449,0.8843817 1.004255,0.8803597 1.042589,0.8824287 1.012437,0.8723765 1.002212,0.8689685 0.9702208,0.8683745 0.9564128,0.8683745 c -0.0228367,0 -0.0423927,-0.004441 -0.0560242,0.016007 -0.00932,0.0139795 -0.016007,0.0192863 -0.016007,0.0360156 0,0.007151 -0.002625,0.0214487 0,0.0280121 0.003323,0.008308 0.009835,0.0153294 0.0120052,0.0240104 6.4823e-4,0.002588 -0.001193,0.005617 0,0.008003 0.004659,0.009318 0.0118441,0.013603 0.016007,0.0240104 0.002559,0.00639 0.007449,0.027457 0.0120052,0.032014 9.4192e-4,9.42e-4 0.003059,-9.419e-4 0.004002,0 0.00828,0.00828 -0.0126524,-3.227e-4 0.004002,0.008 0.001193,5.953e-4 0.003059,-9.419e-4 0.004002,0 9.4456e-4,9.419e-4 -9.4191e-4,0.00306 0,0.004 0.00436,0.00436 0.0259027,0.00895 0.0320138,0.012005 0.001688,8.44e-4 0.002668,0.00267 0.004002,0.004 0.00667,0.004 0.0128595,0.00894 0.0200086,0.012005 0.002453,0.00105 0.005372,-4.392e-4 0.008003,0 0.016307,0.00272 0.032613,0.00815 0.048021,0.012005 0.029539,0.00738 0.057779,0.00126 0.068029,0.032014 0.00154,0.00463 -0.00215,0.011707 0,0.016007 0.00206,0.00411 0.00918,0.01883 0.004,0.02401 -9.419e-4,9.419e-4 -0.00306,-9.419e-4 -0.004,0 -0.0032,0.0032 -0.00239,0.0078 -0.008,0.012005 -0.012423,0.00932 -0.026778,0.017391 -0.040017,0.02401 -0.00358,0.00179 -0.00812,-9.71e-4 -0.012005,0 -0.00601,0.0015 -0.016857,0.00758 -0.02401,0.004 -0.019865,-0.00993 -0.0455425,-0.016515 -0.0680294,-0.02401 -0.007203,-0.0024 -0.0168074,0.0024 -0.0240104,0 -0.001789,-5.954e-4 -0.002315,-0.00316 -0.004002,-0.004 -0.005854,-0.00293 -0.0163296,0.00184 -0.0280121,-0.004 -0.004367,-0.00218 -0.0256032,-0.0012 -0.0280121,0 -0.00397,0.00198 -0.00786,0.00662 -0.0120052,0.008 -0.005797,0.00193 -0.0220485,-7.79e-5 -0.016007,0.012005 0.009285,0.01857 0.0149429,0.039763 0.0200086,0.060026 0.00263,0.010518 0.0116901,0.015376 0.016007,0.02401 0.001193,0.00239 -8.4402e-4,0.00547 0,0.008 0.001521,0.00456 0.006217,0.00754 0.008003,0.012005 0.003442,0.0086 0.004391,0.016785 0.008003,0.02401 0.0114229,0.022846 0.0456607,0.034425 0.0680294,0.040017 0.0884539,0.022113 -0.0206047,-0.00458 0.0480208,0.016007 0.021907,0.00657 0.07855,0.00806 0.1000432,0 0.00353,-0.00133 0.00486,-0.00591 0.008,-0.008 0.00745,-0.00496 0.017023,-0.00642 0.02401,-0.012005 0.011874,-0.0095 0.012966,-0.016275 0.020009,-0.028012 0.00439,-0.00732 0.012187,-0.012369 0.016007,-0.020009 0.00119,-0.00239 -6.483e-4,-0.00542 0,-0.008 0.00483,-0.019324 0.0019,1.983e-4 0.008,-0.012005 0.00899,-0.017983 0.008,-0.086997 0.008,-0.1080467 0,-0.00999 0.00487,-0.038283 0,-0.048021 -0.00291,-0.00581 -0.00616,-0.00863 -0.008,-0.016007 -6.483e-4,-0.00259 9.895e-4,-0.00553 0,-0.008 -0.00339,-0.00848 -0.0085,-0.012989 -0.012005,-0.020009 -0.00331,-0.00661 0.00222,-0.00771 -0.004,-0.016007 0.00342,-0.018566 -0.0086,-0.0046 -0.012005,-0.008 -0.00185,-0.00185 0.00121,-0.00959 0,-0.012005 -0.00642,-0.012843 -0.014098,-0.014098 -0.02401,-0.02401 -0.00298,-0.00298 -0.00102,-0.00902 -0.004,-0.012005 -9.446e-4,-9.419e-4 -0.00306,9.419e-4 -0.004,0 -9.419e-4,-9.419e-4 9.419e-4,-0.00306 0,-0.004 -9.419e-4,-9.419e-4 -0.00306,9.419e-4 -0.004,0 -9.419e-4,-9.419e-4 0,-0.00267 0,-0.004 -0.004,-0.00267 -0.0077,-0.005853 -0.012005,-0.008003 -0.00449,-0.002246 -0.016911,-9.0487e-4 -0.020008,-0.004002 -9.42e-4,-9.4191e-4 9.419e-4,-0.003059 0,-0.004002 -9.42e-4,-9.4192e-4 -0.004,-0.001333 -0.004,0 0,0.002668 0.00534,0 0.008,0 0.00759,0 0.012777,0.002193 0.020009,0.004002 0.009,0.002249 0.029002,0.019019 0.032014,0.016007 0.00696,-0.00696 -0.00582,-0.043659 -0.008,-0.0480207 -5.953e-4,-0.001193 -0.00306,9.4192e-4 -0.004,0 -0.00101,-0.001005 -8.572e-4,-0.0186367 0,-0.0200086 0.00608,-0.009731 0.024529,-0.0174652 0.020009,-0.0280121 -0.033347,-0.0778116 -0.032013,0.0203975 -0.032013,-0.004002 l 0.028002,0.05202"
id="path16" />
<path
style="opacity:1;fill:#2b0000;fill-opacity:1;stroke-width:0.264583"
d="m 1.2485393,0.94440792 c 0,0.008003 0,0.016007 0,0.0240104 0,0.00155 -0.00421,0.0238022 -0.004,0.0240104 9.419e-4,9.4192e-4 0.00306,-9.4191e-4 0.004,0 0.00211,0.002109 0.00189,0.005894 0.004,0.008003 0.0055,0.0055 0.013812,-0.003362 0.016007,0.012005 0.00156,0.010942 0.0033,0.042131 0,0.052023 -3.916e-4,0.00117 -0.00722,0.00478 -0.004,0.008 0.00283,0.00283 0.008,0 0.012005,0 0.029914,0 0.058794,1.76e-4 0.088038,-0.004 0.00418,-5.953e-4 0.00791,-0.00298 0.012005,-0.004 0.004,-0.001 0.008,0.002 0.012005,0 1.499e-4,-7.49e-5 -0.00145,-0.00945 0.004,-0.004 9.419e-4,9.419e-4 -2.193e-4,0.00269 0,0.004 0.00112,0.00671 0.00316,0.01326 0.004,0.020009 0.00192,0.015375 0,0.032536 0,0.048021 0,0.018945 0.00354,0.048582 0,0.068029 -0.00151,0.0083 -0.00617,0.015775 -0.008,0.02401 -8.679e-4,0.00391 6.588e-4,0.00806 0,0.012005 -0.00412,0.024709 -0.014286,0.051442 -0.028012,0.072031 -0.00534,0.008 -0.010235,0.016315 -0.016007,0.02401 -0.00226,0.00302 -0.00632,0.00463 -0.008,0.008 -0.0034,0.0068 -0.024731,0.068883 -0.020009,0.072031 0.018417,0.012278 0.1295963,0.028419 0.1520656,0.032014 0.1326193,0.024112 -0.032938,-0.00494 0.080035,0.012005 0.014968,0.00225 0.068042,0.014669 0.088038,0.008 0.00895,-0.00298 -0.01291,-0.013798 -0.020009,-0.020009 -0.028351,-0.024807 -0.062706,-0.04056 -0.09204,-0.064027 -0.00104,-8.334e-4 8.016e-4,-0.00293 0,-0.004 -0.00204,-0.00272 -0.026305,-0.034309 -0.028012,-0.036015 -0.00604,-0.00604 -0.013969,-0.00997 -0.020009,-0.016007 -0.025374,-0.025374 -0.089196,-0.1205799 -0.076033,-0.1600691 0.00456,-0.013688 0.013924,-0.027849 0.020009,-0.040017 0.00269,-0.00538 0.00254,-0.014158 0.004,-0.020009 0.00187,-0.00746 0.010773,-0.030781 0.016007,-0.036015 0.00211,-0.00211 0.00589,-0.00189 0.008,-0.004 0.00211,-0.00211 0.00189,-0.00589 0.004,-0.008 9.446e-4,-9.42e-4 0.00306,9.445e-4 0.004,0 9.42e-4,-9.42e-4 -9.419e-4,-0.00306 0,-0.004 0.00892,-0.00892 0.062622,0.0074 0.068029,0.008 0.031535,0.0035 0.0644,-0.00243 0.096041,0 0.00548,4.207e-4 0.010563,0.00322 0.016007,0.004 0.01438,0.00205 0.02964,-0.00205 0.044019,0 0.01402,0.002 0.059625,0.010205 0.072031,0.004 0.00433,-0.00216 -0.010772,-0.044622 -0.012005,-0.052023 -8.784e-4,-0.00526 0.00116,-0.010798 0,-0.016007 -0.00156,-0.007012 -0.00603,-0.0131017 -0.008,-0.0200086 -0.00153,-0.005359 -0.00332,-0.02461 -0.004,-0.0280121 -4.101e-4,-0.002045 0.00138,-0.0106233 0,-0.0120052 -0.00104,-0.001037 -0.07023,0 -0.076033,0 -0.044497,0 -0.09188,0.004909 -0.1360588,0 -0.01369,0.004592 -0.023841,-0.006264 -0.036016,-0.008003 -0.01152,-0.001646 -0.029218,0.00432 -0.040017,0 -0.00447,-0.001786 -0.00754,-0.006217 -0.012005,-0.008003 -0.00763,-0.003052 -0.1250992,-0.002492 -0.1400605,0 -0.013063,0.002178 -0.031656,0.015231 -0.040017,0.0200085 z"
id="path17" />
<path
style="opacity:1;fill:#2b0000;fill-opacity:1;stroke-width:0.264583"
d="m 0.32814175,0.83235952 c -0.005336,-0.001333 -0.014673,-0.009337 -0.016007,-0.004002 -0.001333,0.005336 0.0177461,-0.001217 0.016007,0.004002 -0.005149,0.0154469 -0.0352938,0.025454 -0.0280121,0.0400173 0.00598,0.01196 0.0163637,0.0163637 0.0240104,0.0240104 0.006327,0.006327 0.007566,0.0162412 0.0120052,0.0240104 0.008922,0.0156136 0.0234685,0.0286375 0.0320138,0.044019 0.004797,0.008634 0.0115845,0.0337003 0.016007,0.044019 0.0110673,0.025823 0.0177382,0.079382 0.0120052,0.1080466 -5.8473e-4,0.00292 -0.00358,0.00505 -0.004002,0.008 -9.4191e-4,0.0066 9.4192e-4,0.013406 0,0.020009 -0.001857,0.013002 -0.0119343,0.027799 -0.016007,0.040017 -8.4402e-4,0.00253 8.4402e-4,0.00547 0,0.008 -0.001193,0.00358 -0.006316,0.00463 -0.008003,0.008 -0.004549,0.0091 -0.005902,0.015604 -0.008003,0.02401 -0.003617,0.014468 -0.0164814,0.05555 -0.016007,0.056024 4.8948e-4,4.895e-4 0.0410173,0 0.0480208,0 0.0102571,0 0.0521977,0.00391 0.0600259,0 0.003375,-0.00169 0.004629,-0.00632 0.008003,-0.008 0.007701,-0.00385 0.016352,-0.00818 0.0240104,-0.012005 0.0166542,-0.00833 -0.004278,2.751e-4 0.004002,-0.008 0.001886,-0.00189 0.006117,0.00189 0.008003,0 0.00772,-0.00772 0.002853,-0.035976 0.004002,-0.044019 4.2069e-4,-0.00295 0.00358,-0.00505 0.004002,-0.008 0.004667,-0.032667 0.001672,-0.091026 -0.008003,-0.1200519 -0.001513,-0.00454 -0.0137144,-0.01295 -0.016007,-0.016007 -0.003579,-0.00477 -0.003785,-0.011789 -0.008003,-0.016007 -0.001886,-0.00189 -0.006117,0.00189 -0.008003,0 -9.4191e-4,-9.419e-4 9.4192e-4,-0.00306 0,-0.004 -9.4191e-4,-9.419e-4 -0.003059,9.42e-4 -0.004002,0 -9.4192e-4,-9.419e-4 9.4192e-4,-0.00306 0,-0.004 -0.002109,-0.00211 -0.005894,-0.00189 -0.008003,-0.004 -9.4192e-4,-9.419e-4 9.4192e-4,-0.00306 0,-0.004 -9.4192e-4,-9.419e-4 -0.002668,0 -0.004002,0 -0.001334,-0.00133 -0.002955,-0.00243 -0.004002,-0.004 -0.005793,-0.00869 -0.007454,-0.018909 -0.0120052,-0.028012 -0.006812,-0.013624 -0.0174141,-0.0268246 -0.0240104,-0.0400173 -0.001193,-0.002387 0.001886,-0.006117 0,-0.008003 -9.4192e-4,-9.4192e-4 -0.003059,9.4191e-4 -0.004002,0 -0.002875,-0.002875 -0.00482,-0.0168254 -0.008003,-0.0200086 -9.4192e-4,-9.4191e-4 -0.003059,9.4192e-4 -0.004002,0 -9.4191e-4,-9.4191e-4 5.9532e-4,-0.002809 0,-0.004002 -0.003509,-0.007018 -0.0123971,-0.0127889 -0.016007,-0.0200086 -0.001789,-0.003579 0.001789,-0.008426 0,-0.0120052 -5.9532e-4,-0.001193 -0.003059,9.4192e-4 -0.004002,0 -0.002822,-0.002821 -0.009959,-0.0199188 -0.0120049,-0.0240098 -0.006442,-0.0128841 -0.0256429,-0.0325846 -0.0320138,-0.0400173 z"
id="path18" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 18 KiB

View file

@ -6,7 +6,7 @@
VerticalAlignment="Bottom">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="12">
<Button x:Name="ToggleButton" Content="Pause" Click="Toggle_Click"
AutomationProperties.Name="Lecture ou pause du replay" />
AutomationProperties.Name="Lecture ou pause de la vidéo" />
<Slider x:Name="PositionSlider" Grid.Column="1" Minimum="0" Maximum="1"
ValueChanged="Position_Changed" VerticalAlignment="Center"
AutomationProperties.Name="Position dans le replay" />

View file

@ -14,6 +14,7 @@ public partial class ReplayControls : UserControl
{
private readonly ReplayControlsState _state = new();
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private readonly DispatcherTimer _previewTimer = new() { Interval = TimeSpan.FromMilliseconds(60) };
private MediaPlayer? _player;
private bool _updating;
@ -21,6 +22,7 @@ public partial class ReplayControls : UserControl
{
InitializeComponent();
_timer.Tick += Update;
_previewTimer.Tick += (_, _) => ApplyPreview();
PointerMoved += (_, _) => _state.Show();
PointerPressed += (_, _) => _state.Show();
KeyDown += (_, _) => _state.Show();
@ -32,7 +34,17 @@ public partial class ReplayControls : UserControl
};
}
public ReplayControls(MediaPlayer player) : this() => _player = player;
internal ReplayControls(bool replay) : this()
{
PositionSlider.IsVisible = replay;
TimeLabel.IsVisible = replay;
}
public ReplayControls(MediaPlayer player) : this(player, replay: true) { }
public ReplayControls(MediaPlayer player, bool replay) : this(replay) => _player = player;
public event Action? PlaybackFailed;
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
@ -44,6 +56,7 @@ public partial class ReplayControls : UserControl
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
_timer.Stop();
_previewTimer.Stop();
base.OnDetachedFromVisualTree(e);
}
@ -66,12 +79,21 @@ public partial class ReplayControls : UserControl
{
_state.IsInteracting = true;
_state.Show();
_previewTimer.Start();
}
private void EndSeek(object? sender, PointerReleasedEventArgs e) => CommitSeek();
private void ApplyPreview()
{
if (_player is { IsSeekable: true } player && _state.TryTakePreview(out var time))
player.Time = time;
}
private void CommitSeek()
{
_previewTimer.Stop();
_state.EndPreview();
if (_player is { IsSeekable: true } player) player.Time = (long)PositionSlider.Value;
_state.IsInteracting = false;
_state.Show();
@ -79,14 +101,16 @@ public partial class ReplayControls : UserControl
private void Position_Changed(object? sender, RangeBaseValueChangedEventArgs e)
{
if (!_updating && !_state.IsInteracting) CommitSeek();
if (_updating) return;
if (_state.IsInteracting) _state.RequestPreview((long)e.NewValue);
else CommitSeek();
}
private void Toggle_Click(object? sender, RoutedEventArgs e)
{
if (_player is not { } player) return;
if (player.IsPlaying) player.Pause();
else player.Play();
else if (!player.Play()) PlaybackFailed?.Invoke();
_state.Show();
}
}

View file

@ -0,0 +1,21 @@
using System;
namespace Yavsc.Exceptions;
public class NoTokenException : Exception
{
public NoTokenException()
: base("No token available.")
{
}
public NoTokenException(string message)
: base(message)
{
}
public NoTokenException(string message, Exception innerException)
: base(message, innerException)
{
}
}

View file

@ -0,0 +1,10 @@
using System;
namespace PostIt.Services;
public sealed class RefreshFailedException : Exception
{
public bool IsPermanent { get; }
public RefreshFailedException(string message, bool isPermanent)
: base(message) => IsPermanent = isPermanent;
}

View file

@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
@ -16,13 +17,13 @@ public static class ImageHelper
return new Bitmap(AssetLoader.Open(resourceUri));
}
public static async Task<Bitmap?> LoadFromWeb(Uri url)
public static async Task<Bitmap?> LoadFromWeb(Uri url, CancellationToken ct = default)
{
try
{
var response = await HttpClient.GetAsync(url).ConfigureAwait(false);
using var response = await HttpClient.GetAsync(url, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var data = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
return new Bitmap(new MemoryStream(data));
}
catch (HttpRequestException ex)

View file

@ -2,11 +2,13 @@ using System;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Capture;
using PostIt.ViewModels.Chat;
using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Chat;
using PostIt.Views.Commands;
using PostIt.Views.Video;
using Yavsc.Api.Client;
namespace PostIt.Helpers;
@ -20,7 +22,7 @@ public static class ServiceCollectionHelpers
var tokenStore = new TokenStore(System.IO.Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),
"PostIt", "tokens.json"));
App.AppName, "tokens.json"));
var api = new YavscApiClient(settings, tokenStore);
var client = new BlogApiClient(api, settings.BlogsApiUrl);
@ -48,6 +50,7 @@ public static class ServiceCollectionHelpers
services.AddTransient<MainView>();
services.AddTransient<BlogsPage>();
services.AddTransient<VideoPage>();
services.AddTransient<ReplayEditorPage>();
services.AddTransient<PodcastsPage>();
@ -136,7 +139,8 @@ public static class ServiceCollectionHelpers
services.AddTransient<ContactsPageViewModel>();
services.AddSingleton<ActivitiesPageViewModel>();
services.AddTransient<SelectableHairPrestationItem>();
services.AddSingleton<ScreenCaptureViewModel>();
services.AddSingleton<ScreenCaptureView>();
// Dialogs (modal-light pages): the ViewLocator resolves
// them when a caller pushes a PostAclDialogViewModel or
// AddCircleMemberDialogViewModel via App.PushPageAsync.

View file

@ -0,0 +1,33 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PostIt.Interfaces;
public enum ScreenCaptureSource
{
Screen,
Window,
Prompt
}
public record CaptureOptions(
string OutputFilePath,
int Fps = 60,
IntPtr? TargetWindowHandle = null, // Null = Écran principal complet
bool CaptureCursor = true,
string? RestoreToken = null, // Token sauvegardé de la session précédente
ScreenCaptureSource Source = ScreenCaptureSource.Screen,
bool CaptureAudio = true
);
public interface IScreenCaptureService : IDisposable
{
bool IsRecording { get; }
string? LatestRestoreToken { get; } // Nouveau token à sauvegarder après le démarrage
event EventHandler<TimeSpan>? RecordingDurationUpdated;
Task StartRecordingAsync(CaptureOptions options, CancellationToken cancellationToken = default);
Task StopRecordingAsync();
}

View file

@ -2,7 +2,7 @@ using System.Threading.Tasks;
using PostIt.ViewModels;
using Avalonia.Controls;
namespace PostIt;
namespace PostIt.Interfaces;
internal interface IVMPusherApp
{

View file

@ -0,0 +1,14 @@
using System;
using Avalonia;
using Avalonia.Controls;
namespace PostIt.Interfaces;
public static class VisualExtensions
{
static IntPtr? GetTopLevel(this Visual visual)
{
var topLevel = TopLevel.GetTopLevel(visual);
return topLevel?.TryGetPlatformHandle()?.Handle;
}
}

View file

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
@ -66,4 +66,4 @@
</Compile>
<Watch Include="**\*.xaml" />
</ItemGroup>
</Project>
</Project>

View file

@ -45,6 +45,18 @@ public sealed class CallSignalingClient : IWebRtcCallSignaling, IDisposable
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLan, room, user, ct);
}
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLanAudio, room, user, ct);
}
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default)
{
EnsureConnected();
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteAudio, room, user, ct);
}
public Task AcceptAsync(Guid callId, CancellationToken ct = default)
{
EnsureConnected();

View file

@ -9,6 +9,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using PostIt.ViewModels.Chat;
using PostIt.Models;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
@ -76,8 +77,20 @@ public sealed class ChatHubConnection : IAsyncDisposable
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;
connection.Reconnected += async _ =>
{
if (!ReferenceEquals(Connection, connection) || !IsCurrentConfiguration) return;
try
{
await AnnounceContactPreferencesAsync(connection, CancellationToken.None);
await RestoreRoomsAsync(connection, CancellationToken.None);
}
catch (Exception ex)
{
ReportError($"Impossible d'annoncer les preferences de contact : {ex.Message}");
await connection.StopAsync();
}
};
return connection;
}
@ -112,12 +125,29 @@ public sealed class ChatHubConnection : IAsyncDisposable
if (Connection.State == HubConnectionState.Disconnected)
{
await Connection.StartAsync(ct);
await RestoreRoomsAsync(Connection, ct);
try
{
await AnnounceContactPreferencesAsync(Connection, ct);
await RestoreRoomsAsync(Connection, ct);
}
catch
{
await Connection.StopAsync(CancellationToken.None);
throw;
}
}
}
finally { _gate.Release(); }
}
private Task AnnounceContactPreferencesAsync(HubConnection connection, CancellationToken ct) =>
connection.InvokeAsync(CallHubMethods.SetContactPreferences,
new ContactPreferences(_api.Settings.AllowAudioCalls, _api.Settings.AllowVideoCalls,
_api.Settings.AllowPrivateMessages, Platform.CreateWebRtcMedia != null ||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()),
Platform.CreateLanCallMedia != null ||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid())), ct);
public async Task StopAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
@ -233,10 +263,6 @@ public sealed class ChatHubConnection : IAsyncDisposable
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);
}

View file

@ -14,4 +14,5 @@ public interface ILanCallMedia : IAsyncDisposable
Task Completion { get; }
bool HasRemoteMedia { get; }
Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct);
Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct);
}

View file

@ -13,6 +13,7 @@ public interface ILanCallSignaling
event Action<Guid, CallSignal>? Signal;
event Action? Interrupted;
Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default);
Task<CallSession> InviteLanAudioAsync(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

@ -0,0 +1,15 @@
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
namespace PostIt.Services;
/// <summary>
/// Copies the frame displayed by a native video surface, for platforms where the LibVLC snapshot cannot read
/// hardware-decoded output. The image stays in memory.
/// </summary>
public interface IVideoFrameCapture
{
/// <summary>Returns the displayed frame scaled to <paramref name="width"/> pixels, or null when no frame is available.</summary>
Task<Bitmap?> CaptureFrameAsync(int width, CancellationToken ct);
}

View file

@ -7,7 +7,7 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed record WebRtcMediaConfiguration(CallIceServer[] IceServers, bool RelayOnly,
bool Caller, string Camera, string Microphone);
bool Caller, string Camera, string Microphone, bool AudioOnly = false);
public sealed record WebRtcMediaStatus(string ConnectionState, string? LocalCandidateType,
long AudioPackets, long VideoFrames, bool LocalVideoRendered = false, bool RemoteVideoRendered = false)
@ -29,4 +29,5 @@ public interface IWebRtcMedia : IAsyncDisposable
public interface IWebRtcCallSignaling : ILanCallSignaling
{
Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default);
Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default);
}

View file

@ -1,4 +1,5 @@
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
@ -99,6 +100,28 @@ public sealed class LibVlcLanCallMedia : IAsyncDisposable
public Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct) =>
StartSendingAsync(remote, vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), true, ct);
public Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string audioSource, CancellationToken ct) =>
StartSendingAsync(remote, vlc => CreateAvatarMedia(vlc, imagePath, audioSource), false, ct);
internal static Media CreateAvatarMedia(LibVLC vlc, string imagePath, string audioSource)
{
ArgumentException.ThrowIfNullOrWhiteSpace(imagePath);
ArgumentException.ThrowIfNullOrWhiteSpace(audioSource);
if (!File.Exists(imagePath)) throw new FileNotFoundException("Avatar d'appel introuvable.", imagePath);
var uri = new Uri(Path.GetFullPath(imagePath)).AbsoluteUri;
var imageSource = "file/image:" + uri["file:".Length..];
// Pulse uses wall-clock timestamps; ADTS/file inputs start at zero and clock the image slave.
var realtime = audioSource.StartsWith("pulse://", StringComparison.Ordinal);
var media = new Media(vlc, realtime ? imageSource : audioSource, FromType.FromLocation);
media.AddOption(":image-duration=-1");
media.AddOption(":image-fps=30/1");
media.AddOption(":image-chroma=I420");
if (realtime) media.AddOption(":image-realtime");
media.AddOption(":input-slave=" + (realtime ? audioSource : imageSource));
media.AddOption(":live-caching=200");
return media;
}
internal async Task StartSendingAsync(LanCallEndpoint remote, Func<LibVLC, Media> source,
bool preview, CancellationToken ct, bool transcode = true)
{

View file

@ -2,6 +2,8 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using Avalonia.Layout;
using Avalonia.Threading;
using LibVLCSharp.Avalonia;
using Yavsc.Abstract.Chat.Calls;
@ -12,6 +14,8 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
{
private readonly LibVlcLanCallMedia _media;
private readonly VideoView _local;
private readonly ContentControl _localContent;
private Bitmap? _avatar;
private readonly VideoView _remote;
private readonly TaskCompletionSource _localReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _lifetime = new();
@ -20,7 +24,7 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
private bool _disposed;
private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Control LocalVideo => _local;
public Control LocalVideo => _localContent;
public Control RemoteVideo => _remote;
public LanCallEndpoint Endpoint => _media.Endpoint;
public Task Completion { get; }
@ -30,6 +34,12 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
{
_media = new LibVlcLanCallMedia(localAddress, port);
_local = new VideoView { MediaPlayer = _media.Sender, MinHeight = 140 };
_localContent = new ContentControl
{
Content = _local,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
VerticalContentAlignment = VerticalAlignment.Stretch
};
_remote = new VideoView { MediaPlayer = _media.Receiver, MinHeight = 260 };
_local.LayoutUpdated += OnLocalLayout;
_remote.LayoutUpdated += OnRemoteLayout;
@ -81,6 +91,16 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
await _media.StartSendingAsync(remote, camera, microphone, ct);
}
public async Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_avatar != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
_avatar = new Bitmap(imagePath);
_local.MediaPlayer = null;
_localContent.Content = new Image { Source = _avatar, Height = 140 };
await _media.StartAvatarSendingAsync(remote, imagePath, $"pulse://{microphone}", ct);
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
@ -94,6 +114,8 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
{
_local.MediaPlayer = null;
_remote.MediaPlayer = null;
_localContent.Content = null;
_avatar?.Dispose();
try { await _media.DisposeAsync(); }
finally
{

View file

@ -59,7 +59,7 @@ public sealed class MessagingSession : IAsyncDisposable
try { await OnSigningOutAsync(); }
catch (Exception ex)
{
_api.Settings.SetActionStatus($"Arret du service de messagerie incomplet : {ex.Message}", Models.StatusSeverity.Error);
NotificationService.Instance.Post($"Arret du service de messagerie incomplet : {ex.Message}", Models.StatusSeverity.Error);
}
_session.Refresh();
}
@ -108,7 +108,7 @@ public sealed class MessagingSession : IAsyncDisposable
}
catch (Exception ex)
{
_api.Settings.SetActionStatus($"Mise a jour de la messagerie impossible : {ex.Message}", Models.StatusSeverity.Error);
NotificationService.Instance.Post($"Mise a jour de la messagerie impossible : {ex.Message}", Models.StatusSeverity.Error);
}
}
@ -135,7 +135,7 @@ public sealed class MessagingSession : IAsyncDisposable
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);
NotificationService.Instance.Post($"Service de messagerie Android indisponible : {ex.Message}", Models.StatusSeverity.Error);
}
}
finally { _gate.Release(); }

View file

@ -51,7 +51,7 @@ public sealed class NominatimReverseGeocodingService : IReverseGeocodingService
Timeout = TimeSpan.FromSeconds(10),
};
client.DefaultRequestHeaders.UserAgent.Clear();
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PostIt", "1.1"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(App.AppName, "1.1"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr-FR"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr", 0.9));
return client;
@ -116,4 +116,4 @@ public sealed class NominatimReverseGeocodingService : IReverseGeocodingService
return parts is null || parts.Count == 0 ? null : string.Join(", ", parts);
}
}
}

View file

@ -13,7 +13,10 @@ public sealed class NotificationService
{
}
public void Show(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
public void Post(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
=> Avalonia.Threading.Dispatcher.UIThread.Post(() => Show(message, severity, actionLabel, action));
private void Show(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
=> NotificationRequested?.Invoke(this, new NotificationRequest(message, severity, actionLabel, action));
public void Hide()

View file

@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using LibVLCSharp.Shared;
using PostIt.Interfaces;
namespace PostIt.Services;
@ -40,24 +41,13 @@ public static class Platform
public static Func<string, CancellationToken, Task<IPodcastCapture>>? CreateBlurredPodcastPreviewAsync { get; set; }
/// <summary>Platform-specific video surface inside the shared video page.</summary>
public static Func<MediaPlayer, bool, Control>? CreateVideoSurface { get; set; }
public static Func<MediaPlayer, bool, Action, Control>? CreateVideoSurface { get; set; }
public static event Action? PlaybackSuspending;
public static event Action? PlaybackResuming;
public static void SuspendPlayback() => PlaybackSuspending?.Invoke();
public static void ResumePlayback() => PlaybackResuming?.Invoke();
/// <summary>
/// Default redirect URI for the running platform. The shared
/// default uses a custom URI scheme (<c>postit://callback</c>)
/// so the OAuth2 redirect is delivered to the running instance
/// through the OS scheme handler — no loopback HTTP listener
/// required (see RFC 8252 §7.1). Platform projects may still
/// override this property at startup (e.g. PostIt.Android sets
/// it to <c>android://postit-signin</c>).
/// </summary>
public const string RedirectUri = "postit://callback";
/// <summary>
/// Scheme prefix the <see cref="CustomSchemeBrowser"/> matches
/// against <c>BrowserOptions.EndUrl</c>. Overridable for apps
@ -65,6 +55,7 @@ public static class Platform
/// </summary>
public const string CustomScheme = "postit";
/// <summary>
/// Constructs a fresh <see cref="IBrowser"/> for the running platform.
/// May return <c>null</c> if no browser is wired up; in that case
@ -82,4 +73,6 @@ public static class Platform
_ => Task.FromResult(CurrentLocationResult.Unavailable());
public static bool IsPodcastSupported { get; set; } = false;
public static bool IsScreenCaptureSupported { get; set; } = false;
public static Func<IScreenCaptureService>? CreateScreenCaptureService { get; set; }
}

View file

@ -51,9 +51,9 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
media.AddOption(":sout=#" + (preview ? $"duplicate{{dst=display{{noaudio}},dst=\"{destination}\"}}" : encoding));
}
public static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, string title,
public static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, CreatePodcastRequest request,
string camera, string? microphone, CancellationToken ct, Guid? plannedId = null)
=> await StartAsync(api, title,
=> await StartAsync(api, request,
(directory, _) => Task.FromResult<IPodcastCapture>(new LibVlcPodcastCapture(
vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), directory, preview: true)), ct, plannedId);
@ -62,18 +62,23 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
=> await StartAsync(api, title,
(directory, _) => Task.FromResult<IPodcastCapture>(new LibVlcPodcastCapture(createMedia, directory)), ct);
public static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, string title,
public static Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, string title,
Func<string, CancellationToken, Task<IPodcastCapture>> createCapture, CancellationToken ct, Guid? plannedId = null)
=> StartAsync(api, new CreatePodcastRequest { Title = title }, createCapture, ct, plannedId);
/// <summary>Starts a planned emission, or creates an immediate live with the options of <paramref name="request"/>.</summary>
public static async Task<PodcastBroadcaster> StartAsync(PodcastApiClient api, CreatePodcastRequest request,
Func<string, CancellationToken, Task<IPodcastCapture>> createCapture, CancellationToken ct, Guid? plannedId = null)
{
IPodcastCapture? capture = null;
PodcastBroadcaster? broadcaster = null;
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"PostIt", "podcast-capture", Guid.NewGuid().ToString("N"));
App.AppName, "podcast-capture", Guid.NewGuid().ToString("N"));
PodcastResponse? podcast = null;
try
{
Directory.CreateDirectory(directory);
podcast = plannedId.HasValue ? await api.StartAsync(plannedId.Value, ct) : await api.CreateAsync(title, ct);
podcast = plannedId.HasValue ? await api.StartAsync(plannedId.Value, ct) : await api.CreateAsync(request, ct);
if (podcast.State != PodcastState.Live)
throw new InvalidOperationException("Cette emission est deja terminee. Preparez une nouvelle emission.");
await File.WriteAllTextAsync(Path.Combine(directory, "podcast.json"), JsonSerializer.Serialize(podcast), ct);

View file

@ -0,0 +1,29 @@
using Yavsc.Abstract.Streaming;
namespace PostIt.Services;
public enum PodcastPlaybackSource { Originals, PublishedReplay, Pending, Unavailable }
public readonly record struct PodcastPlaybackChoice(PodcastPlaybackSource Source, string? Message = null);
/// <summary>Chooses what a viewer can play: the published MP4, the HLS originals, or nothing yet.</summary>
public static class PodcastPlayback
{
public static PodcastPlaybackChoice Choose(PodcastResponse podcast)
{
if (podcast.State != PodcastState.Live && podcast.Replay is { State: PodcastReplayState.Ready, Bytes: > 0 })
return new(PodcastPlaybackSource.PublishedReplay);
if (podcast.OriginalsDeleted)
return new(PodcastPlaybackSource.Unavailable, "Les originaux de cette emission ont ete supprimes.");
if (podcast.RefineReplay && podcast.State != PodcastState.Live)
// Only the owner receives the draft; other viewers wait for the publication.
return podcast.Draft is null
? new(PodcastPlaybackSource.Unavailable, "Le replay est en cours de finalisation par son auteur.")
: new(PodcastPlaybackSource.Originals);
if (podcast.State == PodcastState.Completed)
return podcast.Replay is { State: PodcastReplayState.Failed } failed
? new(PodcastPlaybackSource.Unavailable, failed.Error ?? "Preparation du MP4 en echec.")
: new(PodcastPlaybackSource.Pending, "Preparation du replay MP4...");
return new(PodcastPlaybackSource.Originals);
}
}

View file

@ -11,17 +11,20 @@ public sealed class PodcastReplayMediaInput : MediaInput
private readonly PodcastApiClient _api;
private readonly Guid _id;
private readonly long _length;
private readonly bool _draftSource;
private readonly CancellationTokenSource _cancellation = new();
private byte[] _buffer = [];
private long _bufferStart;
private long _position;
public event Action<string>? Failed;
public PodcastReplayMediaInput(PodcastApiClient api, Guid id, long length)
/// <param name="draftSource">Reads the owner-only draft source instead of the published MP4.</param>
public PodcastReplayMediaInput(PodcastApiClient api, Guid id, long length, bool draftSource = false)
{
_api = api;
_id = id;
_length = length;
_draftSource = draftSource;
CanSeek = true;
}
@ -50,7 +53,9 @@ public sealed class PodcastReplayMediaInput : MediaInput
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_cancellation.Token);
timeout.CancelAfter(TimeSpan.FromSeconds(20));
_buffer = _api.DownloadReplayRangeAsync(_id, _position, 256 * 1024, _length, timeout.Token)
_buffer = (_draftSource
? _api.DownloadDraftSourceRangeAsync(_id, _position, 256 * 1024, _length, timeout.Token)
: _api.DownloadReplayRangeAsync(_id, _position, 256 * 1024, _length, timeout.Token))
.GetAwaiter().GetResult();
_bufferStart = _position;
}

View file

@ -6,8 +6,25 @@ public sealed class ReplayControlsState(TimeProvider? clock = null)
{
private readonly TimeProvider _clock = clock ?? TimeProvider.System;
private DateTimeOffset _lastInteraction = (clock ?? TimeProvider.System).GetUtcNow();
private long? _pendingPreview;
private long? _appliedPreview;
public bool IsInteracting { get; set; }
public void Show() => _lastInteraction = _clock.GetUtcNow();
/// <summary>Records the latest position requested while dragging; older requests are dropped.</summary>
public void RequestPreview(long milliseconds) => _pendingPreview = Math.Max(0, milliseconds);
/// <summary>Returns the latest unapplied preview position, if any.</summary>
public bool TryTakePreview(out long milliseconds)
{
milliseconds = _pendingPreview ?? 0;
var take = _pendingPreview is { } pending && pending != _appliedPreview;
_pendingPreview = null;
if (take) _appliedPreview = milliseconds;
return take;
}
public void EndPreview() => _pendingPreview = _appliedPreview = null;
public bool IsVisible(bool playing, bool focused)
=> !playing || focused || IsInteracting || _clock.GetUtcNow() - _lastInteraction < TimeSpan.FromSeconds(3);
@ -17,4 +34,12 @@ public sealed class ReplayControlsState(TimeProvider? clock = null)
return time.TotalHours >= 1 ? $"{(int)time.TotalHours}:{time.Minutes:00}:{time.Seconds:00}"
: $"{(int)time.TotalMinutes}:{time.Seconds:00}";
}
/// <summary>Formats a source time to the millisecond, as used by edit marks.</summary>
public static string FormatPreciseTime(long milliseconds)
{
var time = TimeSpan.FromMilliseconds(Math.Max(0, milliseconds));
return time.TotalHours >= 1 ? $"{(int)time.TotalHours}:{time.Minutes:00}:{time.Seconds:00}.{time.Milliseconds:000}"
: $"{(int)time.TotalMinutes}:{time.Seconds:00}.{time.Milliseconds:000}";
}
}

View file

@ -71,27 +71,33 @@ class Peer:
def start(self, configuration):
if self.pipeline is not None:
raise RuntimeError("WebRTC already started")
for plugin in ("webrtcbin", "nicesrc", "vp8enc", "opusenc", "jpegenc"):
audio_only = configuration.get("audioOnly", False)
plugins = ("webrtcbin", "nicesrc", "opusenc") if audio_only else (
"webrtcbin", "nicesrc", "vp8enc", "opusenc", "jpegenc")
for plugin in plugins:
if not Gst.ElementFactory.find(plugin):
raise RuntimeError("Missing GStreamer plugin: " + plugin)
synthetic = configuration["camera"] == "test"
synthetic = (configuration["microphone"] == "test" if audio_only
else configuration["camera"] == "test")
camera = "videotestsrc is-live=true" if synthetic else "v4l2src name=camera"
microphone = "audiotestsrc is-live=true" if synthetic else "pulsesrc name=microphone"
self.pipeline = Gst.parse_launch(
"webrtcbin name=rtc bundle-policy=max-bundle latency=100 "
+ camera + " ! videoconvert ! videoscale ! videorate ! "
video = "" if audio_only else (
camera + " ! videoconvert ! videoscale ! videorate ! "
"video/x-raw,width=640,height=360,framerate=15/1 ! tee name=local "
"local. ! queue leaky=downstream max-size-buffers=2 ! "
"vp8enc deadline=1 target-bitrate=900000 keyframe-max-dist=30 ! "
"rtpvp8pay pt=96 ! application/x-rtp,media=video,encoding-name=VP8,payload=96 ! rtc. "
"local. ! queue leaky=downstream max-size-buffers=1 ! videorate ! "
"video/x-raw,framerate=10/1 ! jpegenc ! appsink name=local_frames "
"emit-signals=true sync=false max-buffers=1 drop=true "
+ microphone + " ! audioconvert ! audioresample ! audio/x-raw,rate=48000,channels=1 ! "
"emit-signals=true sync=false max-buffers=1 drop=true ")
self.pipeline = Gst.parse_launch(
"webrtcbin name=rtc bundle-policy=max-bundle latency=100 "
+ video + microphone + " ! audioconvert ! audioresample ! audio/x-raw,rate=48000,channels=1 ! "
"opusenc ! rtpopuspay pt=111 ! application/x-rtp,media=audio,encoding-name=OPUS,payload=111 ! rtc."
)
if not synthetic:
self.pipeline.get_by_name("camera").set_property("device", configuration["camera"])
if not audio_only:
self.pipeline.get_by_name("camera").set_property("device", configuration["camera"])
if configuration["microphone"] != "default":
self.pipeline.get_by_name("microphone").set_property("device", configuration["microphone"])
self.synthetic = synthetic
@ -117,7 +123,8 @@ class Peer:
self.rtc.set_property("stun-server", url.replace(":", "://", 1))
elif not configuration["relayOnly"] and url.startswith("stuns:"):
raise RuntimeError("GStreamer does not support STUN/TLS; configure STUN or TURN/TLS")
self.pipeline.get_by_name("local_frames").connect("new-sample", self.frame, "local")
if not audio_only:
self.pipeline.get_by_name("local_frames").connect("new-sample", self.frame, "local")
self.rtc.connect("on-ice-candidate", self.candidate)
self.rtc.connect("pad-added", self.incoming)
bus = self.pipeline.get_bus()

View file

@ -11,6 +11,7 @@ using IdentityModel.OidcClient;
using PostIt.ViewModels;
using Yavsc.ApiControllers;
using Yavsc.Api.Client;
using Yavsc.Exceptions;
namespace PostIt.Services;
@ -136,7 +137,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
var report = new BugReport
{
Component = component,
FeatureShortName = "PostIt",
FeatureShortName = App.AppName,
ExceptionObjectJson = exceptionJson
};
await CallAsync(HttpMethod.Post, endpoint.ToString(), report, ct).ConfigureAwait(false);
@ -230,7 +231,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
{
Console.Error.WriteLine($"Session maintenance failed: {ex}");
SessionChanged?.Invoke($"Renouvellement automatique de la session impossible : {ex.Message}");
Settings.SetActionStatus($"Renouvellement automatique de la session impossible : {ex.Message}",
NotificationService.Instance.Post($"Renouvellement automatique de la session impossible : {ex.Message}",
PostIt.Models.StatusSeverity.Error);
await _maintenanceChanged.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
}
@ -547,10 +548,10 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
try
{
if (IsSigningOut)
throw new InvalidOperationException("Deconnexion en cours.");
throw new NoTokenException("Deconnexion en cours.");
var tokens = _tokens;
if (tokens is null)
throw new InvalidOperationException("Session expirée. Veuillez vous reconnecter.");
throw new NoTokenException("Session expirée. Veuillez vous reconnecter.");
if (string.IsNullOrEmpty(tokens.RefreshToken))
{
_store.Clear();
@ -852,10 +853,3 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
}
}
}
public sealed class RefreshFailedException : Exception
{
public bool IsPermanent { get; }
public RefreshFailedException(string message, bool isPermanent)
: base(message) => IsPermanent = isPermanent;
}

View file

@ -10,6 +10,8 @@ using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Chat;
using PostIt.Views.Commands;
using PostIt.ViewModels.Capture;
using PostIt.Views.Video;
namespace PostIt;
@ -41,8 +43,10 @@ public class ViewLocator : IDataTemplate
var services = app!.ServiceProvider!;
return data switch
{
ScreenCaptureViewModel => services.GetRequiredService<ScreenCaptureView>(),
BlogsViewModel => services.GetRequiredService<BlogsPage>(),
VideoPageViewModel => services.GetRequiredService<VideoPage>(),
ReplayEditorPageViewModel => services.GetRequiredService<ReplayEditorPage>(),
PodcastsPageViewModel => services.GetRequiredService<PodcastsPage>(),
Settings => services.GetRequiredService<SettingsPage>(),
AboutPageViewModel => services.GetRequiredService<AboutPage>(),
@ -71,6 +75,7 @@ public class ViewLocator : IDataTemplate
AdministrationPageViewModel => services.GetRequiredService<AdministrationPage>(),
ResourceUsageReliefPageViewModel => services.GetRequiredService<ResourceUsageReliefPage>(),
ChatViewModel => services.GetRequiredService<ChatPage>(),
AudioCallPageViewModel => services.GetRequiredService<CallPage>(),
CallPageViewModel => services.GetRequiredService<CallPage>(),
null => new TextBlock { Text = "No view for <null>" },
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" }

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