Compare commits

...
Author SHA1 Message Date
4f95a8840c
test reorg/filtering
Some checks failed
Dotnet build and test / build (pull_request) Failing after 25s
2026-11-12 14:32:19 +00:00
2e3f1af6f8
WebRTC Android et Linux + Admin refund + User UX @Post del 2026-11-11 16:30:42 +00:00
d812266ee0
feat(postit): add native WebRTC calls with TURN IP masking
Replace the direct chat call panel with native Android and Linux WebRTC engines, enforce relay-only privacy, and cover consent, lifecycle, rendering and coturn interoperability. Document deployment and upgrade Avalonia to 12.1.6.

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

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-10 23:57:26 +00:00
993f1bfadb
icon and soft keyboard usage in Android 2026-11-10 22:51:23 +00:00
144 changed files with 5164 additions and 592 deletions

View file

@ -69,10 +69,7 @@ jobs:
YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION: Host=127.0.0.1;Port=55432;Database=postgres;Username=postgres;Password=postgres;Include Error Detail=true
run: |
echo "🚀 Lancement des tests..."
cd /src/_src && dotnet test \
--report-xunit \
--report-xunit-html \
--report-xunit-html-filename "test-results.html"
cd /src/_src && make test
TEST_EXIT_CODE=$?
echo "Test exit code: $TEST_EXIT_CODE"
if [ $TEST_EXIT_CODE -ne 0 ]; then

View file

@ -1,6 +1,19 @@
# Changelog
## [1.0.8-rc36] - unstable
### Added
* [PostIt/Administration] Add an administrator-only consumption relief page reachable from Administration: select a user at their limit, preview and confirm an arbitrary point erasure up to current consumption. Protect the quota-exempt API with the Administrator policy, serialize adjustments with accounting, reject stale confirmations, preserve technical counters and disk quotas, and audit the actor. Add API, service, client and responsive-page regressions.
* [PostIt] Upgrade Avalonia to 12.1.6 and align the headless and native Skia test rendering packages.
* [PostIt/Calls] Replace the chat's direct VLC/SRTP call panel with native WebRTC on Android and Linux: official libwebrtc/Camera2 and GStreamer webrtcbin, existing consent/SignalR signaling, ICE/STUN/coturn, and fail-closed relay-only IP masking. Cancel pending startup and release media on hangup, navigation, interruption and backgrounding. Add privacy/lifecycle, real Linux media/rendering and debug Android interoperability regressions, coturn deployment instructions and a protected-server-secret configuration example.
* [PostIt/PayPal] Add a native subscription page reachable from Home, profile and About: load server-priced Discovery/Premium offers, prepare or resume checkout with the current bearer session, open only PayPal for approval, reconcile confirmed payments and balances, and cancel with confirmation. Add quota-exempt bearer-only endpoints on Yavsc.Org, sharing checkout/cancellation logic with the existing web flow, and regression coverage. Browser return never confirms payment.
## [1.0.8-rc35] - unstable
### Added

View file

@ -28,6 +28,61 @@ dotnet publish -c Release
and then, install the app, from the `src/PostIt/PostIt.Android/bin/Release/net10.0/PostIt.apk`
## PostIt native WebRTC calls (Android and Linux)
Calls are opt-in on the HTTPS chat host. Configure `AudioVideoCalls` there:
```json
{
"AudioVideoCalls": {
"Enabled": true,
"EnableLanCalls": false,
"StunUrls": ["stun:turn.example.org:3478"],
"TurnUrls": [
"turn:turn.example.org:3478?transport=udp",
"turn:turn.example.org:3478?transport=tcp",
"turns:turn.example.org:5349?transport=tcp"
]
}
}
```
Set `AudioVideoCalls__TurnSharedSecret` through the host's protected environment
or secret store, **not** in a committed settings file or in PostIt. Generate
a strong random secret (for example `openssl rand -hex 32`), install coturn and
adapt [coturn.conf.example](contrib/coturn.conf.example) outside the repository.
Set its `static-auth-secret` to the same value. The server issues separate,
short-lived REST/HMAC credentials only after invitation acceptance; clients
never receive the shared secret. Keep clocks synchronized.
Expose TURN on UDP/TCP 3478, TLS/TCP 5349, and the configured **UDP relay range**
(49160–49200 in the example). Use a publicly trusted certificate matching the
TURN hostname and ensure coturn can read its key. TURN is not an HTTP reverse
proxy route. If behind NAT, configure coturn's `external-ip=PUBLIC/PRIVATE`,
`listening-ip` and `relay-ip` for the actual deployment and forward the relay
range without changing port numbers. Restrict relay access to private services,
set bandwidth/capacity limits appropriate to the host, and avoid logging SDP,
credentials or candidates. Do not copy the loopback permissions used by tests.
Android 8+ bundles native libwebrtc from the official Maven AAR. Linux needs
Python 3 GI and GStreamer with `webrtcbin`, libnice, VP8, Opus, JPEG, V4L2 and
PulseAudio/PipeWire support. On Debian/Ubuntu:
```bash
sudo apt install python3-gi python3-gst-1.0 gir1.2-gst-plugins-bad-1.0 \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-nice gstreamer1.0-pulseaudio
```
Join the same chat room, refresh/select camera and microphone, invite a peer,
then accept on the other client. Capture starts only after acceptance.
The profile's IP-masking setting forces **both participants** through TURN;
missing/unreachable TURN fails the call, never falls back to direct media.
Without masking, explicit IP-disclosure consent is required.
TURN still sees each client's address, and masking does not hide addresses
from the signaling host or local network. See the
[architecture and native regression commands](doc/architecture/audio-video-calls.md).
## PostIt.Desktop on Windows (per-user installer)
@ -187,6 +242,21 @@ footer and PostIt's **About** page, using the configured authentication
authority. PostIt displays consumption and remaining points in **My profile**
and the administration usage views.
PostIt **Administration > Effacer des points de consommation** lets an
`Administrator` select an account whose consumption limit is reached, enter
a positive amount (up to eight decimal places), preview the remaining
consumption and explicitly confirm. An amount exceeding current consumption
is rejected: this action grants neither future credit nor additional disk
space, and preserves the technical counters and payment history.
`POST /api/v1/resource-usage/admin/{userId}/erase` accepts `points` and
`expectedCredits` (the displayed `AppliedCredits + CreditBalance`). The
Administrator-only endpoint is quota-exempt, rechecks eligibility under the
shared accounting lock and rejects stale credit snapshots with HTTP 409.
Refresh and confirm again after a conflict or uncertain request outcome.
Successful adjustments record the administrator as the modifying actor and
log the target, amount and remaining consumption. No new migration is needed
beyond the existing resource-subscription credit column.
### Monthly resource subscriptions (PayPal REST)
The free registration keeps the configured cumulative quota without a
@ -227,6 +297,22 @@ any still-paid Discovery period applies.
Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need
the migrated shared database and matching resource weights, not PayPal
credentials. Existing Classic donation settings remain unchanged.
PostIt's **Mon abonnement PayPal** page (Home, profile or About) loads offers
and creates/resumes checkout through `api/v1/resource-subscriptions` on the
configured OIDC **authority**, not the business API host. These routes require
the current bearer token, reject cookie-only requests, and remain accessible
at the resource-consumption limit. Prices, VAT, monthly points and plan IDs
are controlled by the server; no PayPal credentials are shipped to PostIt.
Only approval opens in the browser. The anonymous `/api/v1/resource-subscriptions/return`
landing page asks the user to return to PostIt and press **Actualiser**:
it does not reconcile or grant credit, and requires no second web login.
The authenticated `POST refresh` reconciles verified PayPal transactions;
`POST {id}/cancel` cancels only the caller's subscription. Existing web
checkout and verified webhooks remain supported. Deploy Yavsc.Org with the
new routes before distributing the updated client. Example requests are in
[`resource-subscriptions.http`](src/Yavsc.Org/resource-subscriptions.http).
Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret`
REST settings; keep credentials in user-secrets or environment variables.

View file

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

View file

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

View file

@ -2,12 +2,14 @@
## Statut et périmètre
Ce document décrit l'architecture cible et l'implémentation commencée.
Ce document décrit l'architecture cible, l'implementation native actuelle et
l'historique du transport direct.
La préférence de confidentialité est persistée et éditable dans le profil.
La signalisation est intégrée au chat, désactivée par défaut. Un premier
transport natif **Android et Desktop Linux en IPv4/IPv6 directe (LAN/VPN ou IP publique)** est raccordé :
captures Podcast existantes et SRTP direct, sans libwebrtc ni nouvelle
couche JNI WebRTC. Il ne réalise pas encore la cible Internet, TURN ou groupe.
La signalisation est intégrée au chat, désactivée par défaut. La page du chat
utilise maintenant **WebRTC natif sur Android et Desktop Linux**, avec
ICE/STUN/TURN et masquage IP impose par la politique serveur. L'ancien
transport VLC/SRTP n'est plus raccorde a cette page. Les groupes et les
clients navigateur ne sont pas implementes.
Il complète la [topologie de PostIt](postit.md) et les
[mécanismes de notification existants](notifications.md).
La cible couvre :
@ -18,7 +20,105 @@ La cible couvre :
- les appels de groupe ;
- les clients Browser, Android et Desktop.
## Première implémentation Android et Desktop Linux : SRTP direct IPv4/IPv6
## Implementation actuelle : WebRTC natif Android et Linux
- [WebRtcCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/WebRtcCallViewModel.cs)
conserve invitation/acceptation/fin via SignalR, sans demarrer la capture
avant consentement. Les SDP et candidats ICE utilisent les contrats existants.
- [AndroidWebRtcMedia](../../src/PostIt/PostIt.Android/Services/AndroidWebRtcMedia.cs)
heberge deux surfaces natives. Le pont Java
[WebRtcPeer](../../src/PostIt/PostIt.Android/Services/WebRtcPeer.java) utilise
l'AAR officiel `io.github.webrtc-sdk:android:150.7871.04`, Camera2,
l'audio natif et DTLS-SRTP. Les commandes et callbacks SDP/ICE restent en
Java sur un executeur unique ; pas de WebView ni de binding C# complet du SDK.
- [LinuxWebRtcMedia](../../src/PostIt/PostIt/Services/LinuxWebRtcMedia.cs)
pilote un processus Python GI prive utilisant GStreamer `webrtcbin`,
VP8/Opus, la camera V4L2 et le microphone PulseAudio/PipeWire.
Les trames decodees sont affichees dans Avalonia, l'audio sur la sortie native.
Le protocole JSON utilise uniquement stdin/stdout, pas de serveur local.
- Le serveur impose `RelayOnly` aux deux clients si l'un des comptes masque
son IP. Le client configure la politique native avant capture/negociation,
valide les SDP/candidats sortants et confirme le type du candidat local
de la paire ICE selectionnee. Aucun repli direct ni transport SRTP historique
n'est tente en cas d'echec TURN.
- Avec libnice, les metadonnees ICE `raddr`/`rport` des candidats relais sont
neutralisees a la frontiere de signalisation (RFC 8828), sans modifier
l'adresse du relais ni reecrire le SDP. UPnP est desactive. Les politiques
`relay` de webrtcbin et `force-relay` de libnice sont toutes deux activees.
Un SDP qui expose une adresse non relayee est refuse, pas corrige.
- Raccrocher, sortir de la page/salle, se deconnecter ou passer l'application
en arriere-plan annule aussi un demarrage natif en cours et libere les medias.
Un echec natif, une perte ICE ou 30 secondes sans progression audio/video
terminent l'appel explicitement. Il n'y a pas d'ICE restart/renegociation
automatique ni de migration transparente d'un appel existant.
Le panneau ne demande plus d'adresse ni de port RTP manuel. Sans masquage,
un consentement explicite au partage IP reste requis. Activer le masquage
dans le profil pendant un appel fait terminer cet appel par le serveur :
il faut rappeler pour appliquer la nouvelle politique.
Configuration coturn, certificats, ports et dependances Linux :
[INSTALL](../../INSTALL.md#postit-native-webrtc-calls-android-and-linux).
Les moteurs d'appel sont independants des captures/encodeurs Podcast ;
les Podcasts conservent leur chemin existant.
### Regressions natives
Tests Linux reels, sans compte ni camera, avec sources video/audio synthetiques,
decodage bidirectionnel, selection effective d'un relais coturn, controle des
adresses signalees et panne TURN sans repli :
```bash
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py -v
```
Installer coturn pour ces tests (ou definir `POSTIT_TURN_SERVER` vers son
executable). Ils demarrent un processus local prive, avec secret REST aleatoire
temporaire, et l'arretent en fin de test ; ils ne changent aucun service systeme.
Tests du consentement, de la politique, des interruptions et du rendu de vraies
trames dans Avalonia/Skia :
```bash
XDG_CONFIG_HOME="$(mktemp -d)" POSTIT_TEST_NATIVE_WEBRTC=1 \
dotnet test --project src/PostIt/PostIt.Tests \
--filter-class 'PostIt.Tests.WebRtcCallViewModelTests' \
--filter-class 'PostIt.Tests.LanCallViewModelTests'
```
Le test de rendu natif est ignore sans `POSTIT_TEST_NATIVE_WEBRTC=1`.
Les tests headless ordinaires conservent leur moteur de dessin simule.
Utiliser un dossier de configuration de test sans comptes reels et le supprimer
apres execution.
Le test Android physique est reserve a l'APK **Debug** installe : camera avant,
microphone, deux surfaces natives, pair Linux synthetique et coturn local,
aucun compte ni enregistrement. Il utilise `adb reverse` pour des ports TCP
temporaires et retire uniquement ses propres redirections :
```bash
POSTIT_TEST_ANDROID_WEBRTC=1 POSTIT_ANDROID_SERIAL=SERIAL \
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py \
NativeWebRtcTests.test_android_linux_relay_bidirectional_media -v
```
Ce controle local ne remplace pas un essai sur deux reseaux Internet distincts,
avec DNS/certificats publics et pare-feu de production.
Validation effectuee : 37 tests PostIt (dont rendu Linux avec Skia), 76 tests
serveur de signalisation et 5 regressions natives reussis. Sur le telephone
Android arm64, les deux roles appelant/appele ont recu plus de 100 trames
video et 500 paquets audio pendant au moins 10 secondes, avec deux rendus
natifs confirmes et un candidat local `relay` des deux cotes. La panne TURN
ne produit aucun candidat direct sur Android ou Linux. Les essais utilisent
la camera avant et le microphone Android reels, des sources Linux synthetiques
et un coturn TCP local via USB ; la camera et la sortie audio Linux materielles,
TURN/TLS et les reseaux Internet distincts restent a verifier.
## Historique : premiere implementation SRTP direct IPv4/IPv6
Les paragraphes suivants decrivent le transport precedent, conserve dans le
code et ses tests mais non propose par le panneau d'appel actuel.
Les adresses IPv4 publiques directement assignees a une interface locale active
sont egalement disponibles, avec la meme validation unicast cote client,
@ -508,45 +608,37 @@ les redémarrages ICE et renégociations restent à implémenter.
Configuration serveur, section `AudioVideoCalls` :
- `Enabled` : `false` par défaut, à conserver tant que les moteurs ne sont
pas validés ;
- `Enabled` : `false` par défaut, a activer apres configuration et validation
du deploiement ICE/TURN ;
- `StunUrls` : tableau d'URI `stun:` ou `stuns:` ;
- `TurnUrls` : tableau d'URI `turn:` ou `turns:`, avec transport optionnel ;
- `TurnSharedSecret` : secret REST coturn, **uniquement côté serveur**,
à fournir par le gestionnaire de secrets ou la variable d'environnement
`AudioVideoCalls__TurnSharedSecret`, jamais dans le dépôt.
Linux GStreamer prend en charge `stun:`, mais pas `stuns:` : utiliser TURN/TLS
pour ce dernier besoin.
Les credentials TURN temporaires sont calculés côté serveur avec le
format REST coturn (expiration, nonce aléatoire et HMAC-SHA1). Aucun secret
de longue durée n'est envoyé aux clients. Aucun service TURN n'a été
déployé ou configuré par cette tranche.
de longue durée n'est envoyé aux clients. Aucun service TURN de production
n'est deploye automatiquement ; seuls les tests lancent un coturn isole.
Le [transport PostIt](../../src/PostIt/PostIt/Services/CallSignalingClient.cs)
utilise la connexion authentifiée du `ChatViewModel`, sans seconde connexion
ni interrogation HTTP. Il expose les commandes et événements typés et
signale les interruptions ; il ne capture aucun média. L'interface ne
propose pas encore de bouton d'appel ; une éventuelle invitation est
signalée comme non utilisable faute de moteur natif, sans acceptation
automatique.
signale les interruptions ; il ne capture aucun média.
Le panneau WebRTC de la page du chat et les deux adaptateurs natifs
consomment maintenant cette signalisation, toujours sans acceptation automatique.
### Travail restant pour la cible Internet multi-plateforme
- Android : l'approche Java/JNI libwebrtc a été écartée à la demande du
projet ; aucun adaptateur libwebrtc expérimental n'est conservé.
L'adaptateur SRTP LAN réutilise désormais la capture Podcast ; la solution
compatible avec la cible Internet reste à choisir.
- Desktop Linux : le transport SRTP LAN est raccordé, mais ne remplace pas
les validations matérielles ni une solution de connectivité Internet.
- Côté partagé : relier consentement, états réels du moteur, mise en
sourdine, arrêt et libération des ressources à la signalisation.
- Valider un appel Android ↔ Desktop Linux avec caméra avant et microphone
réels, rendu et audio distants, VP8/Opus, puis transport TURN sélectionné
dans les statistiques, sans repli direct lorsque le masquage est demandé.
Les tests de cette tranche portent sur les contrats, autorisations, courses
d'acceptation, expirations, limites, interruption et préférence persistée.
La compilation des applications Android et Desktop ne prouve pas le
fonctionnement de WebRTC natif : le crash antérieur n'est pas résolu.
- Valider les cameras, microphones et sorties audio Linux materiels.
- Valider les appels sur deux reseaux Internet distincts, UDP/TCP/TLS,
DNS, certificats et politiques de pare-feu de production.
- Ajouter si necessaire les commandes de sourdine, renegociation/ICE restart
et renouvellement des credentials pour les appels longs.
- Les groupes/SFU, Browser et les autres plateformes restent hors perimetre.
## Retour sur l'essai Android du 25 octobre 2026
@ -584,4 +676,9 @@ impossibilité de WebRTC sur Android ou une défaillance du ChatHub.
Les essais Browser/GStreamer réussis utilisaient des sources synthétiques
et un décodage sans affichage côté GStreamer : ils ne valident pas
PostIt.Desktop Linux, ses périphériques réels ou son rendu Avalonia.
La validation multi-plateforme demeure incomplète.
Ces limites de l'ancien laboratoire ne constituent plus le bilan du moteur
actuel : les nouvelles regressions Android/GStreamer ci-dessus verifient
des medias bidirectionnels et des rendus reels via TURN. La cause precise
du crash de cet ancien prototype reste inconnue ; aucun crash natif n'a
ete reproduit pendant les nouveaux essais. Cela ne remplace pas les
validations Internet et materielles encore indiquees.

View file

@ -47,6 +47,21 @@ spécifiques (IntentFilter Android, `app.manifest` Desktop).
Toute la logique (VM, services, navigation, settings, OIDC) est
dans le code-base partagé.
## Abonnements PayPal
La page native **Mon abonnement PayPal** est accessible depuis l'accueil,
le profil et « À propos ». Elle utilise `ResourceSubscriptionsApiClient`
avec l'autorité OIDC configurée pour charger les offres, l'abonnement en
cours et le solde. Les prix HT/TTC, la TVA et les droits proviennent du serveur.
La création ou reprise de souscription utilise la session bearer de PostIt ;
seule l'approbation est ouverte dans le navigateur, sur un domaine PayPal HTTPS.
Après approbation ou abandon, l'utilisateur revient dans PostIt et utilise
**Actualiser les paiements et mon solde**. Ni l'ouverture du navigateur ni
la page de retour ne prouvent un paiement : seul le rapprochement serveur
des transactions vérifiées accorde les droits. La résiliation demande une
confirmation explicite et conserve les droits des périodes déjà payées.
La configuration serveur et les routes sont décrites dans [INSTALL.md](../../INSTALL.md).
## Reprise Android
`IActivityApplicationLifetime.MainViewFactory` crée une nouvelle `MainView`

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

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

View file

@ -10,22 +10,13 @@
"clean:js": "node esbuild.config.mjs --clean"
},
"dependencies": {
"@aspnet/signalr": "^1.0.27",
"bootstrap": "^4.6.2",
"dropzone": "^5.9.3",
"eonasdan-bootstrap-datetimepicker": "^4.17.49",
"hls.js": "1.6.13",
"jquery": "^3.7.1",
"jquery-timepicker": "^1.3.3",
"jquery-ui": "^1.13.3",
"jquery-validation": "^1.20.0",
"jquery-validation-unobtrusive": "^4.0.0",
"moment": "^2.30.1",
"quill": "^1.3.7",
"showdown": "^2.1.0",
"to-markdown": "^3.1.1"
"jquery-validation-unobtrusive": "^4.0.0"
},
"devDependencies": {
"esbuild": "^0.24.0"
"esbuild": "^0.28.2"
}
}

View file

@ -4,18 +4,19 @@
<!-- https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management -->
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AvaloniaVersionBase>12.1.4</AvaloniaVersionBase>
<AvaloniaVersionBase>12.1.6</AvaloniaVersionBase>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Browser" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Android" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless" Version="12.1.4" />
<PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Skia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
<PackageVersion Include="DirectShowLib" Version="1.0.0" />
<PackageVersion Include="LibVLCSharp.Avalonia" Version="3.10.2" />
<PackageVersion Include="LibVLCSharp" Version="3.10.2" />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

View file

@ -16,8 +16,8 @@ namespace PostIt.Android;
Theme = "@style/MyTheme.NoActionBar",
Icon = "@drawable/icon",
MainLauncher = true,
WindowSoftInputMode = SoftInput.AdjustResize,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode)
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode
)
]
public class MainActivity : AvaloniaMainActivity
{

View file

@ -27,6 +27,10 @@ internal static class PlatformBootstrap
Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay);
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
{
Platform.CreateWebRtcMedia = () => System.OperatingSystem.IsAndroidVersionAtLeast(26)
? new AndroidWebRtcMedia()
: throw new System.PlatformNotSupportedException("Android 8 requis pour WebRTC.");
Platform.GetWebRtcDevices = AndroidLanCallMedia.GetDevices;
Platform.GetLanCallDevices = AndroidLanCallMedia.GetDevices;
Platform.CreateLanCallMedia = (address, port) =>
System.OperatingSystem.IsAndroidVersionAtLeast(26)

View file

@ -30,6 +30,10 @@
<PackageReference Include="Xamarin.AndroidX.Core.SplashScreen" />
<PackageReference Include="Xamarin.AndroidX.Browser" />
</ItemGroup>
<ItemGroup>
<AndroidMavenLibrary Include="io.github.webrtc-sdk:android" Version="150.7871.04" Bind="false" VerifyDependencies="false" />
<AndroidJavaSource Update="Services/WebRtcPeer.java" Bind="false" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />
</ItemGroup>
@ -40,6 +44,7 @@
<Compile Include="..\PostIt.Tests\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidPodcastBlurTestActivity.cs" Link="Tests\AndroidPodcastBlurTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidLanCallTestActivity.cs" Link="Tests\AndroidLanCallTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidWebRtcTestActivity.cs" Link="Tests\AndroidWebRtcTestActivity.cs" />
<Compile Include="..\PostIt.Tests\AndroidScreenAwakeTestActivity.cs" Link="Tests\AndroidScreenAwakeTestActivity.cs" />
</ItemGroup>
<!-- This is an Avalonia app, not a MAUI app: exclude the .NET MAUI VS Code

View file

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

View file

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

View file

@ -32,6 +32,7 @@ internal static class PodcastPermissions
if (!await pending.Task.WaitAsync(ct))
throw new UnauthorizedAccessException(notifications
? "Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser."
: microphone ? "Autorisez la camera et le microphone pour l'appel."
: "Autorisez la camera pour la previsualisation.");
}

View file

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

View file

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

View file

@ -2,6 +2,7 @@ using PostIt.ViewModels;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class AboutTermsTests
{
[Fact]

View file

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

View file

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

View file

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

View file

@ -1,4 +1,3 @@
using System.Net.Http;
using System.Text.Json;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
@ -13,6 +12,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationAccessTests
{
[Fact]
@ -41,44 +41,6 @@ public class AdministrationAccessTests
Assert.Contains("les usages restent consultables", model.StatusMessage);
}
[AvaloniaTheory]
[InlineData("Moderator", false)]
[InlineData("Administrator", true)]
[InlineData("administrator", false)]
[InlineData("Performer", false)]
[InlineData("moderator", false)]
[InlineData("", false)]
public async Task Home_administration_visibility_and_command_follow_the_administrator_role(string role, bool allowed)
{
await using var api = new ProfileTransport(role);
var session = new SessionStatusViewModel { Api = api };
var vm = new HomePageViewModel(api, api.Settings, session, null!);
var page = new HomePage { DataContext = vm };
var window = new Window { Content = page };
try
{
window.Show();
var button = Assert.Single(page.GetVisualDescendants().OfType<Button>(),
button => Equals(button.Content, "Administration"));
Assert.False(button.IsVisible);
await session.RefreshAsync();
Assert.Equal(allowed, session.IsAdministrator);
Assert.Equal(allowed, button.IsVisible);
Assert.Equal(allowed, vm.OpenAdministration.CanExecute(null));
Assert.DoesNotContain(page.GetVisualDescendants().OfType<Button>(),
button => Equals(button.Content, "Mon usage / administration"));
session.Api = null;
session.Refresh();
Assert.False(button.IsVisible);
Assert.False(vm.OpenAdministration.CanExecute(null));
}
finally
{
window.Close();
}
}
[Fact]
public async Task Late_role_response_cannot_restore_access_after_logout()
{

View file

@ -1,5 +1,4 @@
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
@ -13,6 +12,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class AdministrationToolsTests
{
[Fact]

View file

@ -12,7 +12,8 @@ namespace PostIt.Tests;
/// Skip conditions: the package is not installed on the connected device,
/// or no device is connected via adb.
/// </summary>
[Trait("Category", "Platform-Android")]
[Trait("Platform", "Android")]
[Trait("Category", "non-reg")]
public class AndroidAppLaunchTests
{
private const string PackageName = "fr.pschneider.postit";

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -21,6 +21,7 @@ using SkiaSharp;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class BlogReaderTests
{
private static BlogPostDto Post(string article = "Texte du billet.") => new()
@ -139,57 +140,6 @@ public class BlogReaderTests
}
}
[AvaloniaFact]
public async Task Reader_initialization_and_empty_selection_do_not_report_binding_errors()
{
var vm = CreateViewModel();
await vm.InitializeAsync();
var post = Post();
vm.Posts.Add(post);
vm.FilteredPosts.Add(post);
var previousSink = Logger.Sink;
var sink = new RecordingLogSink();
Logger.Sink = sink;
Window? window = null;
try
{
var page = new BlogsPage();
var reader = page.FindControl<MarkdownScrollViewer>("ArticleReader")!;
var engine = Assert.IsAssignableFrom<IMarkdownEngine2>(reader.Engine);
Assert.NotNull(engine.HyperlinkCommand);
Assert.False(engine.HyperlinkCommand.CanExecute("https://example.test/"));
page.DataContext = vm;
var nav = new NavigationPage();
await nav.PushAsync(page);
window = new Window { Width = 800, Height = 700, Content = nav };
window.Show();
Dispatcher.UIThread.RunJobs();
Assert.Empty(vm.ReaderTitle);
Assert.Null(vm.ReaderDateModified);
Assert.Same(vm.OpenResourceCommand, engine.HyperlinkCommand);
Assert.IsType<BlogImageResolver>(reader.Plugins.PathResolver);
vm.SelectedPost = post;
Dispatcher.UIThread.RunJobs();
Assert.Equal(post.Title, vm.ReaderTitle);
Assert.Equal(post.DateModified, vm.ReaderDateModified);
vm.SelectedPost = null;
page.DataContext = null;
Dispatcher.UIThread.RunJobs();
Assert.Empty(vm.ReaderTitle);
Assert.Null(vm.ReaderDateModified);
Assert.NotNull(engine.HyperlinkCommand);
Assert.False(engine.HyperlinkCommand.CanExecute("https://example.test/"));
Assert.DoesNotContain(sink.Entries, entry => entry.Area == LogArea.Binding);
}
finally
{
window?.Close();
Logger.Sink = previousSink;
}
}
[AvaloniaTheory]
[InlineData(360, 800, false)]
[InlineData(1000, 420, true)]

View file

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

View file

@ -5,6 +5,7 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CallSignalingClientTests
{
[Fact]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,20 @@
using Avalonia;
using Avalonia.Headless;
[assembly: AvaloniaTestApplication(typeof(PostIt.Tests.TestAppBuilder))]
namespace PostIt.Tests;
public class TestAppBuilder
{
public static AppBuilder BuildAvaloniaApp()
{
var nativeMedia = System.Environment.GetEnvironmentVariable("POSTIT_TEST_NATIVE_WEBRTC") == "1";
var builder = AppBuilder.Configure<PostIt.App>();
if (nativeMedia) builder.UseSkia();
return builder.UseHeadless(new AvaloniaHeadlessPlatformOptions
{
UseHeadlessDrawing = !nativeMedia
});
}
}

View file

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

View file

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

View file

@ -3,6 +3,7 @@ using PostIt.ViewModels;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class HomePageProviderFlowTests
{
[Fact]

View file

@ -1,9 +1,9 @@
using System.Net.Http;
using Yavsc.Api.Client;
using Yavsc.Billing;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class InvoicesApiClientTests
{
[Fact]

View file

@ -7,6 +7,7 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class LanCallViewModelTests
{
[AvaloniaFact]

View file

@ -8,6 +8,9 @@ using PostIt.Services;
namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class LinuxLanCallMediaTests(ITestOutputHelper output)
{
public static bool HasFixture => OperatingSystem.IsLinux() &&

View file

@ -9,7 +9,6 @@ using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Helpers;
namespace PostIt.Tests;
@ -50,6 +49,7 @@ namespace PostIt.Tests;
/// stack.</item>
/// </list>
/// </summary>
[Trait("Category", "non-reg")]
public class MainPageButtonsTests
{
[AvaloniaFact]

View file

@ -4,7 +4,6 @@ using Avalonia.VisualTree;
using Yavsc.Blogspot;
using Yavsc.Api.Client;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
namespace PostIt.Tests;
@ -30,6 +29,7 @@ namespace PostIt.Tests;
/// pass once the VM owns a dedicated <c>Title</c>/<c>Article</c>
/// buffer that the XAML binds to and the Save command consumes.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class MainPageSaveTests
{
[AvaloniaFact]

View file

@ -16,6 +16,7 @@ using PostIt.Views.Blogs;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class MarkdownEditorScrollTests
{
private static readonly string LongArticle =

View file

@ -14,10 +14,10 @@ using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using PostIt.Views;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class MessagingSessionTests
{
[Fact]

View file

@ -47,6 +47,7 @@ namespace PostIt.Tests;
/// <c>ExecutionTask</c> to completion, to avoid blocking on the
/// (platform-dependent) picker.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class MyFilesPageHeadlessTests
{
private static (MyFilesPage page, MyFilesViewModel vm, StubFsApi api) CreatePage()
@ -205,4 +206,4 @@ public class MyFilesPageHeadlessTests
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}

View file

@ -0,0 +1,267 @@
"""Real GStreamer/coturn regression. No camera, account or public service is used."""
import base64
import hashlib
import hmac
import io
import json
import os
from pathlib import Path
import queue
import secrets
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import unittest
ENGINE = Path(__file__).resolve().parents[2] / "PostIt/Services/WebRtc/gstreamer_peer.py"
class AndroidPeer:
"""Debug Activity over an adb-reversed, loopback-only test command socket."""
def __init__(self):
self.adb = [os.environ.get("POSTIT_ADB", "adb")]
if os.environ.get("POSTIT_ANDROID_SERIAL"):
self.adb += ["-s", os.environ["POSTIT_ANDROID_SERIAL"]]
self.exited = threading.Event()
self.reversed = []
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
listener.listen(1)
listener.settimeout(35)
port = listener.getsockname()[1]
self.reverse(port)
try:
subprocess.run(self.adb + ["shell", "am", "start", "-f", "0x18000000", "-n",
"fr.pschneider.postit/.WebRtcTestActivity", "--ei", "port", str(port)],
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=10)
self.socket, _ = listener.accept()
except BaseException:
self.remove_reverses()
raise
self.input = self.socket.makefile("w", encoding="utf-8")
self.output = self.socket.makefile("r", encoding="utf-8")
self.stdin = self.input
self.stdout = self.read()
self.stderr = io.StringIO()
def reverse(self, port):
subprocess.run(self.adb + ["reverse", f"tcp:{port}", f"tcp:{port}"], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10)
self.reversed.append(port)
def remove_reverses(self):
for port in self.reversed:
subprocess.run(self.adb + ["reverse", "--remove", f"tcp:{port}"], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10)
self.reversed.clear()
def read(self):
try:
yield from self.output
finally:
self.output.close()
self.exited.set()
def poll(self):
return 0 if self.exited.is_set() else None
def wait(self, timeout=None):
if not self.exited.wait(timeout):
raise subprocess.TimeoutExpired("Android test peer", timeout)
self.socket.close()
self.remove_reverses()
return 0
def kill(self):
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
class NativeWebRtcTests(unittest.TestCase):
def run_pair(self, relay, unavailable=False, android=False, android_caller=False):
processes = []
events = queue.Queue()
errors = []
server = None
server_log = None
with tempfile.TemporaryDirectory(prefix="postit-turn-") as directory:
try:
servers = []
if relay:
binary = os.environ.get("POSTIT_TURN_SERVER", shutil.which("turnserver"))
self.assertTrue(binary, "Install coturn or set POSTIT_TURN_SERVER")
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
port = reservation.getsockname()[1]
secret = secrets.token_hex(32)
username = str(int(time.time()) + 600) + ":native-test"
password = base64.b64encode(hmac.new(secret.encode(), username.encode(), hashlib.sha1).digest()).decode()
server_log = open(Path(directory) / "coturn.log", "w+")
server = subprocess.Popen([
binary, "-n", "--listening-ip=127.0.0.1", "--relay-ip=127.0.0.1",
"--listening-port=" + str(port), "--min-port=52000", "--max-port=52100",
"--realm=postit-native-test", "--use-auth-secret", "--static-auth-secret=" + secret,
"--allow-loopback-peers", "--no-multicast-peers", "--no-tls", "--no-dtls",
"--no-cli", "--relay-threads=1", "--pidfile=" + directory + "/turn.pid",
"--log-file=stdout"
], stdout=server_log, stderr=subprocess.STDOUT)
deadline = time.monotonic() + 10
while True:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
break
except OSError:
if time.monotonic() > deadline or server.poll() is not None:
server_log.seek(0)
self.fail("coturn failed to start: " + server_log.read()[-2000:])
time.sleep(0.1)
if unavailable:
server.terminate()
server.wait(timeout=5)
servers = [{"urls": [f"turn:127.0.0.1:{port}?transport=tcp"],
"username": username, "credential": password}]
def read(index, process):
for line in process.stdout:
try:
message = json.loads(line)
if message.get("type") == "frame":
events.put((index, {"type": "rendered", "target": message["target"],
"size": len(base64.b64decode(message["data"]))}))
else:
events.put((index, message))
except Exception as error:
errors.append(str(error))
def stderr(process):
for line in process.stderr:
errors.append(line.rstrip())
for index in range(2):
if android and index == 1:
process = AndroidPeer()
if relay:
process.reverse(port)
else:
process = subprocess.Popen([sys.executable, "-X", "faulthandler", "-u", str(ENGINE)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, bufsize=1)
processes.append(process)
threading.Thread(target=read, args=(index, process), daemon=True).start()
threading.Thread(target=stderr, args=(process,), daemon=True).start()
self.send(process, {"command": "start", "configuration": {
"iceServers": servers, "relayOnly": relay,
"caller": index == (1 if android_caller else 0),
"camera": "test", "microphone": "test"}})
stats = {}
rendered = set()
candidates = 0
descriptions = set()
started = time.monotonic()
deadline = started + (12 if unavailable else 35)
while time.monotonic() < deadline:
self.assertTrue(all(p.poll() is None for p in processes),
f"Native peer exited: {[p.poll() for p in processes]}, {errors[-20:]}")
try:
index, message = events.get(timeout=0.5)
except queue.Empty:
self.assertTrue(all(p.poll() is None for p in processes), str(errors[-10:]))
continue
kind = message["type"]
if kind == "error":
self.fail(message["message"] + "\n" + str(errors[-10:]))
if kind == "signal":
signal = message["signal"]
if relay:
candidate = signal.get("candidate")
if candidate:
tokens = candidate.split()
self.assertEqual("relay", tokens[7])
if "raddr" in tokens:
self.assertIn(tokens[tokens.index("raddr") + 1], ("0.0.0.0", "::"))
for line in (signal.get("sdp") or "").splitlines():
if line.startswith("a=candidate:"):
self.assertEqual("relay", line.split()[7])
if line.startswith(("o=", "c=")):
self.assertIn(line.split()[-1], ("0.0.0.0", "::", "127.0.0.1"))
if signal["kind"] == "candidate":
candidates += 1
else:
descriptions.add((index, signal["kind"]))
self.send(processes[1 - index], {"command": "signal", "signal": signal})
if kind == "rendered" and message["size"] > 100:
rendered.add((index, message["target"]))
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(
s["connectionState"] == "connected" and s["audioPackets"] > 100
and s["videoFrames"] >= 100 for s in stats.values()
):
if relay:
self.assertTrue(all(s["localCandidateType"] == "relay" for s in stats.values()))
self.assertGreater(candidates, 0)
print(f"\nMedia verified: relay={relay}, android={android}, "
f"androidCaller={android_caller}, stats={stats}, rendered={len(rendered)}",
flush=True)
return
if unavailable:
caller = 1 if android_caller else 0
self.assertEqual({(caller, "offer"), (1 - caller, "answer")}, descriptions)
self.assertEqual({0, 1}, set(stats))
self.assertTrue(all((index, "local") in rendered for index in range(2)))
self.assertEqual(0, candidates, "TURN failure must never disclose direct candidates")
self.assertFalse(any(target == "remote" for _, target in rendered))
return
self.fail(f"No bidirectional decoded/rendered media: {stats}, {rendered}, {errors[-12:]}")
finally:
for process in processes:
if process.poll() is None:
self.send(process, {"command": "close"})
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
for stream in (process.stdin, process.stdout, process.stderr):
stream.close()
if server is not None and server.poll() is None:
server.terminate()
server.wait(timeout=5)
if server_log is not None:
server_log.close()
@staticmethod
def send(process, message):
process.stdin.write(json.dumps(message) + "\n")
process.stdin.flush()
def test_direct_bidirectional_media(self):
self.run_pair(False)
def test_relay_bidirectional_media_and_no_address_disclosure(self):
self.run_pair(True)
def test_turn_unavailable_never_falls_back_to_direct(self):
self.run_pair(True, unavailable=True)
@unittest.skipUnless(os.environ.get("POSTIT_TEST_ANDROID_WEBRTC") == "1", "Requires installed Debug APK and adb device")
def test_android_linux_relay_bidirectional_media(self):
for caller in (False, True):
with self.subTest(android_caller=caller):
self.run_pair(True, android=True, android_caller=caller)
@unittest.skipUnless(os.environ.get("POSTIT_TEST_ANDROID_WEBRTC") == "1", "Requires installed Debug APK and adb device")
def test_android_turn_unavailable_never_falls_back_to_direct(self):
self.run_pair(True, unavailable=True, android=True)
if __name__ == "__main__":
unittest.main()

View file

@ -4,6 +4,7 @@ using PostIt.Services;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class NominatimReverseGeocodingServiceTests
{
[Fact]
@ -69,4 +70,4 @@ public class NominatimReverseGeocodingServiceTests
});
}
}
}
}

View file

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

View file

@ -10,6 +10,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "not-ending")]
public sealed class PodcastBroadcasterTests
{
[Theory]

View file

@ -1,7 +1,5 @@
using System.Net;
using System.Net.Http;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using LibVLCSharp.Shared;
using PostIt.Services;
@ -10,18 +8,18 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class PodcastNativeCaptureTests(ITestOutputHelper output)
{
public static bool HasFixture => File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
[Theory(Skip = "Set POSTIT_TEST_MEDIA to a local video with audio and install LibVLC with H.264/AAC encoders.", SkipUnless = nameof(HasFixture))]
[InlineData(false)]
[InlineData(true)]
public async Task LibVLC_produces_complete_H264_AAC_HLS_segments_without_external_encoder(bool preview)
[Fact(Skip = "Set POSTIT_TEST_MEDIA to a local video with audio and install LibVLC with H.264/AAC encoders.", SkipUnless = nameof(HasFixture))]
public async Task LibVLC_produces_complete_H264_AAC_HLS_segments_without_external_encoder()
{
var root = Path.Combine(Path.GetTempPath(), $"postit native's hls {Guid.NewGuid():N}");
Directory.CreateDirectory(root);
var pixels = preview ? Marshal.AllocHGlobal(640 * 480 * 4) : IntPtr.Zero;
try
{
Core.Initialize();
@ -29,24 +27,12 @@ public sealed class PodcastNativeCaptureTests(ITestOutputHelper output)
"--avcodec-hw=none", "--avcodec-threads=2");
using var media = new Media(vlc, new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA")!)));
using var player = new MediaPlayer(vlc);
var displayed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (preview)
{
player.SetVideoFormat("RV32", 640, 480, 640 * 4);
player.SetVideoCallbacks((_, planes) =>
{
Marshal.WriteIntPtr(planes, pixels);
return IntPtr.Zero;
}, null, (_, _) => displayed.TrySetResult());
}
PodcastBroadcaster.ConfigureOutput(media, root, preview);
PodcastBroadcaster.ConfigureOutput(media, root);
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
player.EndReached += (_, _) => ended.TrySetResult();
player.EncounteredError += (_, _) => ended.TrySetException(new InvalidOperationException("LibVLC encoding failed."));
Assert.True(player.Play(media));
output.WriteLine($"Encoding started (preview={preview}).");
if (preview)
await displayed.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
output.WriteLine("Encoding started.");
await ended.Task.WaitAsync(TimeSpan.FromSeconds(45), TestContext.Current.CancellationToken);
output.WriteLine("End reached; stopping player.");
player.Stop();
@ -88,7 +74,6 @@ public sealed class PodcastNativeCaptureTests(ITestOutputHelper output)
}
finally
{
if (pixels != IntPtr.Zero) Marshal.FreeHGlobal(pixels);
Directory.Delete(root, recursive: true);
}
}

View file

@ -7,6 +7,7 @@ using Yavsc.Abstract.Streaming;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class PodcastPreferencesTests
{
[AvaloniaFact]

View file

@ -9,6 +9,9 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class PodcastReplayTests
{
private static readonly Guid Id = Guid.NewGuid();

View file

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

View file

@ -8,6 +8,7 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class PodcastTests
{
private static readonly Guid Id = Guid.Parse("9e2f6d47-2b9a-47ae-a870-073980bf2628");

View file

@ -44,6 +44,7 @@ namespace PostIt.Tests;
/// <see cref="BlogAclApiClient"/> / <see cref="CircleApiClient"/>
/// talking to it.</para>
/// </summary>
[Trait("Category", "non-reg")]
public class PostAclDialogTests
{
/// <summary>

View file

@ -18,6 +18,7 @@
<PackageReference Include="coverlet.collector" />
<PackageReference Include="Avalonia.Headless" />
<PackageReference Include="Avalonia.Headless.XUnit" />
<PackageReference Include="Avalonia.Skia" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

View file

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

View file

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

View file

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

View file

@ -2,6 +2,7 @@ using PostIt.Views.Commands;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class RdvPageTests
{
[Fact]
@ -27,4 +28,4 @@ public class RdvPageTests
Assert.False(result);
}
}
}

View file

@ -5,8 +5,22 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class ResourceUsageApiClientTests
{
[Fact]
public async Task Erase_sends_amount_and_expected_credits_to_escaped_user_endpoint()
{
var fake = new FakeYavscApiClient();
var client = new ResourceUsageApiClient(fake, "https://example.invalid/api/v1/");
var request = new EraseResourceUsageRequest { Points = 125.5m, ExpectedCredits = 12m };
await client.EraseAsync("user/name ?#", request, TestContext.Current.CancellationToken);
Assert.Equal("POST", fake.LastMethod);
Assert.Equal("https://example.invalid/api/v1/resource-usage/admin/user%2Fname%20%3F%23/erase", fake.LastPath);
Assert.Same(request, fake.LastBody);
Assert.Equal(TestContext.Current.CancellationToken, fake.LastToken);
}
[Fact]
public async Task Usage_remains_visible_when_the_rest_of_the_profile_is_unavailable()
{
@ -56,11 +70,15 @@ public class ResourceUsageApiClientTests
public HttpClient Http { get; } = new();
public string? LastPath { get; private set; }
public string? LastMethod { get; private set; }
public object? LastBody { get; private set; }
public CancellationToken LastToken { get; private set; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
LastMethod = method.Method;
LastPath = path;
LastBody = body;
LastToken = ct;
if (typeof(T) == typeof(ResourceUsageSummary))
{

View file

@ -0,0 +1,242 @@
using System.Net;
using System.Net.Http;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Resources;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class ResourceUsageReliefPageTests
{
private static ResourceUsageSummary Usage(string id, decimal consumption, decimal credits = 0m) => new()
{
UserId = id, UserName = id + "-name", Consumption = consumption, GrossConsumption = consumption + credits,
AppliedCredits = credits, ConsumptionLimit = 1000m, IsQuotaReached = consumption >= 1000m,
RemainingConsumption = Math.Max(0m, 1000m - consumption)
};
[AvaloniaTheory]
[InlineData("Moderator")]
[InlineData("administrator")]
[InlineData("Performer")]
public async Task Nonadministrators_cannot_load_or_erase_or_open_the_page(string role)
{
await using var profile = new AdministrationAccessTests.ProfileTransport(role);
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport();
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync();
Assert.False(vm.IsAdministrator);
Assert.Empty(transport.Requests);
Assert.Empty(vm.Users);
Assert.False(vm.RefreshCommand.CanExecute(null));
Assert.False(vm.EraseCommand.CanExecute(null));
var administration = new AdministrationPageViewModel(null, session: session);
await administration.OpenResourceUsageReliefCommand.ExecuteAsync(null);
Assert.Contains("Administrator", administration.StatusMessage);
}
[AvaloniaFact]
public async Task Page_loads_only_exhausted_users_and_confirmed_remission_updates_the_result()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport();
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync("alice");
Assert.Equal(2, vm.Users.Count);
Assert.Equal("alice", vm.SelectedUsage?.UserId);
vm.SearchText = "BOB";
Assert.Equal("bob", Assert.Single(vm.FilteredUsers).UserId);
vm.SearchText = "";
vm.PointsText = "125,50";
Assert.Equal(974.5m, vm.ConsumptionAfter);
Assert.False(vm.EraseCommand.CanExecute(null));
await vm.EraseCommand.ExecuteAsync(null);
Assert.Null(transport.Erasure);
vm.ConfirmErasure = true;
Assert.True(vm.EraseCommand.CanExecute(null));
ResourceUsageSummary? updated = null;
vm.UsageUpdated += result => updated = result;
await vm.EraseCommand.ExecuteAsync(null);
Assert.Equal(125.5m, transport.Erasure?.Points);
Assert.Equal(20m, transport.Erasure?.ExpectedCredits);
Assert.Same(updated, vm.SelectedUsage);
Assert.Equal(974.5m, vm.SelectedUsage!.Consumption);
Assert.False(vm.SelectedUsage.IsQuotaReached);
Assert.False(vm.ConfirmErasure);
Assert.False(vm.EraseCommand.CanExecute(null));
Assert.Contains("n’est plus atteinte", vm.StatusMessage);
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);
}
[AvaloniaTheory]
[InlineData("")]
[InlineData("0")]
[InlineData("-1")]
[InlineData("1100.00000001")]
[InlineData("0.000000001")]
[InlineData("1,000.00")]
[InlineData("NaN")]
[InlineData("1e2")]
public async Task Invalid_amounts_never_reach_the_API(string amount)
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport();
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync("alice");
vm.PointsText = amount;
vm.ConfirmErasure = true;
Assert.False(vm.EraseCommand.CanExecute(null));
Assert.NotEmpty(vm.AmountError);
await vm.EraseCommand.ExecuteAsync(null);
Assert.Null(transport.Erasure);
}
[AvaloniaFact]
public async Task Changing_target_or_amount_or_refreshing_invalidates_confirmation()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport();
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync("alice");
vm.PointsText = "10";
vm.ConfirmErasure = true;
vm.PointsText = "20";
Assert.False(vm.ConfirmErasure);
vm.ConfirmErasure = true;
vm.SelectedUsage = vm.Users.Single(u => u.UserId == "bob");
Assert.False(vm.ConfirmErasure);
Assert.Empty(vm.PointsText);
vm.PointsText = "20";
vm.ConfirmErasure = true;
await vm.RefreshCommand.ExecuteAsync(null);
Assert.False(vm.ConfirmErasure);
Assert.Empty(vm.PointsText);
Assert.Equal("bob", vm.SelectedUsage?.UserId);
}
[AvaloniaFact]
public async Task Failure_requires_a_fresh_snapshot_before_retry()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport { FailErase = true };
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync("alice");
vm.PointsText = "100";
vm.ConfirmErasure = true;
await vm.EraseCommand.ExecuteAsync(null);
Assert.Contains("Actualisez", vm.StatusMessage);
Assert.False(vm.ConfirmErasure);
vm.ConfirmErasure = true;
Assert.False(vm.EraseCommand.CanExecute(null));
transport.FailErase = false;
await vm.EraseCommand.ExecuteAsync(null);
Assert.Single(transport.Requests, r => r.StartsWith("POST"));
await vm.RefreshCommand.ExecuteAsync(null);
vm.PointsText = "100";
vm.ConfirmErasure = true;
Assert.True(vm.EraseCommand.CanExecute(null));
}
[AvaloniaFact]
public async Task Logout_clears_private_data_and_a_late_response_cannot_restore_it()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport { Pending = new(TaskCreationOptions.RunContinuationsAsynchronously) };
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
var loading = vm.InitializeAsync("alice");
session.Api = null;
session.Refresh();
transport.Pending.SetResult([Usage("alice", 1100m)]);
await loading;
Assert.Empty(vm.Users);
Assert.Null(vm.SelectedUsage);
Assert.False(vm.IsAdministrator);
Assert.False(vm.EraseCommand.CanExecute(null));
}
[AvaloniaTheory]
[InlineData(400, 800)]
[InlineData(800, 400)]
public async Task Page_displays_target_preview_and_explicit_confirmation_and_disposes_on_exit(int width, int height)
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new Transport();
using var vm = new ResourceUsageReliefPageViewModel(new(transport, "https://example.invalid/api/v1/"), session);
await vm.InitializeAsync("alice");
vm.PointsText = "100";
var page = new ResourceUsageReliefPage { DataContext = vm };
var window = new Window { Content = page, Width = width, Height = height };
try
{
window.Show();
Dispatcher.UIThread.RunJobs();
Assert.Equal("Compte cible : alice", page.FindControl<TextBlock>("ReliefTarget")!.Text);
Assert.Contains("1000", page.FindControl<TextBlock>("ReliefPreview")!.Text);
Assert.Same(vm.EraseCommand, page.FindControl<Button>("ErasePoints")!.Command);
Assert.False(page.FindControl<Button>("ErasePoints")!.IsEffectivelyEnabled);
page.FindControl<CheckBox>("ReliefConfirmation")!.IsChecked = true;
Dispatcher.UIThread.RunJobs();
Assert.True(page.FindControl<Button>("ErasePoints")!.IsEffectivelyEnabled);
var admin = new AdministrationPage { DataContext = new AdministrationPageViewModel() };
Assert.NotNull(admin.FindControl<Button>("OpenResourceUsageRelief")!.Command);
}
finally { window.Close(); }
Assert.False(vm.IsAdministrator);
Assert.Empty(vm.Users);
Assert.False(vm.ConfirmErasure);
}
private sealed class Transport : IYavscApiClient
{
public HttpClient Http { get; } = new();
public List<string> Requests { get; } = [];
public EraseResourceUsageRequest? Erasure { get; private set; }
public bool FailErase { get; set; }
public TaskCompletionSource<List<ResourceUsageSummary>>? Pending { get; init; }
public async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Requests.Add(method + " " + path);
object result;
if (method == HttpMethod.Get)
result = Pending is null ? new List<ResourceUsageSummary>
{ Usage("alice", 1100m, 20m), Usage("bob", 2000m), Usage("carol", 999m) } : await Pending.Task;
else
{
Erasure = Assert.IsType<EraseResourceUsageRequest>(body);
if (FailErase) throw new HttpRequestException("Les crédits ont changé.", null, HttpStatusCode.Conflict);
result = Usage("alice", 1100m - Erasure.Points, 20m + Erasure.Points);
}
return (T)result;
}
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 Task<byte[]> DownloadAsync(HttpMethod method, string path, CancellationToken ct = default)
=> throw new NotSupportedException();
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
}
}

View file

@ -9,6 +9,7 @@ namespace PostIt.Tests;
/// even when Avalonia has not booted, otherwise the 2nd instance
/// flashes its own MainWindow before shutting down.
/// </summary>
[Trait("Category", "non-reg")]
public class SchemeUrlDetectorTests
{
[Fact]

View file

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

View file

@ -1,116 +0,0 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.VisualTree;
using PostIt.ViewModels;
using PostIt.Views;
namespace PostIt.Tests;
/// <summary>
/// UI tests for <see cref="SessionStatusBanner"/>. Mounted inside
/// a real <see cref="MainView"/> via the headless Avalonia
/// platform declared in <c>TestApp.cs</c>.
///
/// <para>The pattern is the one that <c>UnitTest1.MainPage_Should_Load</c>
/// established: a test attribute <c>[AvaloniaFact]</c> (from
/// <c>Avalonia.Headless.XUnit</c>) instead of plain <c>[Fact]</c>,
/// <c>new MainWindow()</c>, <c>window.Show()</c>. The AvaloniaFact
/// attribute schedules the test body inside a dispatcher, which
/// is the precondition for the headless Window's
/// <c>PlatformManager.CreateWindow()</c> to find a registered
/// service. A plain <c>[Fact]</c> test that calls
/// <c>new Window().Show()</c> throws because the harness has not
/// been initialised for that thread.</para>
///
/// <para>These tests set the DataContext directly on the banner
/// mounted in the window. The production code path is exercised
/// end-to-end by the manual launch, not here.</para>
/// </summary>
public class SessionStatusBannerTests : IDisposable
{
private MainWindow? _window;
[AvaloniaFact]
public void Banner_renders_four_buttons_in_the_visual_tree()
{
SessionStatusBanner banner = CreateBanner();
var buttons = banner.GetVisualDescendants()
.OfType<Button>()
.ToList();
Assert.Equal(4, buttons.Count);
Assert.Contains(buttons, b => b.Content as string == "Se déconnecter");
Assert.Contains(buttons, b => b.Content as string == "Se connecter");
Assert.Contains(buttons, b => b.Content as string == "Paramètres");
Assert.Contains(buttons, b => b.Content as string == "À propos");
}
[AvaloniaFact]
public void Banner_login_button_is_visible_when_logged_out()
{
SessionStatusBanner banner = CreateBanner();
var login = banner.GetVisualDescendants()
.OfType<Button>()
.Single(b => b.Content as string == "Se connecter");
// The XAML binds IsVisible to IsLoggedOut. After Show,
// the binding has been evaluated.
Assert.True(login.IsVisible);
}
[AvaloniaFact]
public void Banner_logout_button_is_hidden_when_logged_out()
{
SessionStatusBanner banner = CreateBanner();
Assert.False(Assert.IsType<SessionStatusViewModel>(banner.DataContext).IsLoggedIn);
var logout = banner.GetVisualDescendants()
.OfType<Button>()
.Single(b => b.Content as string == "Se déconnecter");
Assert.False(logout.IsVisible);
}
[AvaloniaFact]
public void Banner_settings_button_is_visible_regardless_of_session()
{
SessionStatusBanner banner = CreateBanner();
var settings = banner.GetVisualDescendants()
.OfType<Button>()
.Single(b => b.Content as string == "Paramètres");
// Paramètres has no IsVisible binding and is always shown.
Assert.True(settings.IsVisible);
}
private SessionStatusBanner CreateBanner()
{
_window = new MainWindow();
_window.Show();
var banner = _window.GetVisualDescendants()
.OfType<SessionStatusBanner>()
.Single();
banner.DataContext = new SessionStatusViewModel();
return banner;
}
public void Dispose() => _window?.Close();
[AvaloniaFact]
public void Banner_session_label_reflects_DataContext()
{
SessionStatusBanner banner = CreateBanner();
var label = banner.GetVisualDescendants()
.OfType<TextBlock>()
.First(t => t.Text == "Déconnecté" || t.Text == "Connecté");
// Default SessionLabel is "Déconnecté" until Refresh()
// is called with a valid session. This pins the default
// so a future refactor that breaks the initial value
// (e.g. by removing the field initialiser) is caught.
Assert.Equal("Déconnecté", label.Text);
}
}

View file

@ -2,6 +2,7 @@ using System.Text.Json;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class SettingsLoadTests
{
/// <summary>

View file

@ -14,6 +14,7 @@ namespace PostIt.Tests;
/// when a template is applied; see
/// <see cref="Pointer_handlers_attach_when_capture_area_is_set"/>.
/// </summary>
[Trait("Category", "non-reg")]
public class SignaturePadControlTests
{
// --- SignaturePadData (pure) ---------------------------------------

View file

@ -11,6 +11,7 @@ namespace PostIt.Tests;
/// control is render-agnostic, and the rendering is plain Polyline
/// reconstruction that we'll exercise manually in PostIt.Desktop.
/// </summary>
[Trait("Category", "non-reg")]
public class SignaturePageViewModelTests
{
[Fact]

View file

@ -17,6 +17,7 @@ namespace PostIt.Tests;
/// 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]

View file

@ -0,0 +1,175 @@
using System.Net.Http;
using System.Text.Json;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Resources;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class SubscriptionsPageTests
{
[AvaloniaFact]
public async Task Page_binds_server_offers_prices_and_balance()
{
await using var api = new FakeApi();
var model = Model(api);
await model.InitializeAsync();
var page = new SubscriptionsPage { DataContext = model };
Assert.IsType<SubscriptionsPage>(new ViewLocator().Build(model));
var selector = page.FindControl<ComboBox>("OfferSelector")!;
Assert.Equal(2, selector.ItemCount);
Assert.Equal(1.2m, model.SelectedOffer?.PriceIncludingTax);
Assert.Equal($"Prix TTC : {1.2m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
selector.SelectedIndex = 1;
Assert.Equal("Premium", model.SelectedOffer?.Pack);
Assert.Equal($"Prix TTC : {2.4m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
Assert.Equal(45m, model.Usage?.Consumption);
Assert.Null(model.StatusMessage);
Assert.True(model.SubscribeCommand.CanExecute(null));
Assert.False(model.CancelSubscriptionCommand.CanExecute(null));
}
[Fact]
public async Task Checkout_uses_authority_and_selected_pack_without_granting_local_credit()
{
await using var api = new FakeApi();
Uri? opened = null;
var authority = "https://first.example/";
var client = new ResourceSubscriptionsApiClient(api, () => authority);
var model = new SubscriptionsPageViewModel(client, uri => { opened = uri; return Task.FromResult(true); });
await model.InitializeAsync();
authority = "https://second.example/instance";
model.SelectedOffer = model.Offers[1];
await model.SubscribeCommand.ExecuteAsync(null);
Assert.Equal("https://second.example/instance/api/v1/resource-subscriptions", api.LastPath);
Assert.Equal("Premium", Assert.IsType<CreateResourceSubscriptionRequest>(api.LastBody).Pack);
Assert.Equal("www.sandbox.paypal.com", opened?.Host);
Assert.Equal("APPROVAL_PENDING", model.CurrentSubscription?.State);
Assert.Equal(45m, model.Usage?.Consumption);
Assert.False(model.IsBusy);
Assert.Contains("Actualiser", model.StatusMessage);
}
[Theory]
[InlineData("https://attacker.example/approve", true)]
[InlineData("http://www.paypal.com/approve", true)]
[InlineData("https://www.paypal.com@attacker.example/approve", true)]
[InlineData("https://www.paypal.com:444/approve", true)]
[InlineData("https://www.sandbox.paypal.com/approve", false)]
public async Task Invalid_link_or_browser_failure_is_explicit_and_checkout_can_be_resumed(string link, bool launchResult)
{
await using var api = new FakeApi { ApprovalUrl = link };
var launches = 0;
var model = new SubscriptionsPageViewModel(new(api, () => "https://org.example"), _ =>
{
launches++;
return Task.FromResult(launchResult);
});
await model.InitializeAsync();
await model.SubscribeCommand.ExecuteAsync(null);
Assert.Contains("impossible", model.StatusMessage);
Assert.Equal(launchResult ? 0 : 1, launches);
Assert.True(model.SubscribeCommand.CanExecute(null));
Assert.Equal(45m, model.Usage?.Consumption);
}
[Fact]
public async Task Active_subscription_blocks_duplicate_checkout_and_cancel_requires_confirmation()
{
await using var api = new FakeApi { State = "ACTIVE" };
var model = Model(api);
await model.InitializeAsync();
Assert.False(model.SubscribeCommand.CanExecute(null));
await model.CancelSubscriptionCommand.ExecuteAsync(null);
Assert.Contains("confirmation", model.StatusMessage);
Assert.Equal(HttpMethod.Get, api.LastMethod);
model.ConfirmCancellation = true;
await model.CancelSubscriptionCommand.ExecuteAsync(null);
Assert.EndsWith($"/{api.Id}/cancel", api.LastPath);
Assert.Null(model.CurrentSubscription);
Assert.False(model.ConfirmCancellation);
Assert.True(model.SubscribeCommand.CanExecute(null));
}
[Fact]
public async Task Refresh_uses_server_reconciliation_and_reports_failures_without_fake_success()
{
await using var api = new FakeApi();
var model = Model(api);
await model.InitializeAsync();
api.Fail = true;
await model.RefreshCommand.ExecuteAsync(null);
Assert.Contains("offline", model.StatusMessage);
Assert.False(model.IsBusy);
Assert.Equal(45m, model.Usage?.Consumption);
api.Fail = false;
await model.RefreshCommand.ExecuteAsync(null);
Assert.EndsWith("/refresh", api.LastPath);
Assert.Equal(HttpMethod.Post, api.LastMethod);
Assert.Equal(0m, model.Usage?.Consumption);
}
[Fact]
public async Task Unavailable_offers_and_changing_an_existing_pack_cannot_start_checkout()
{
await using var api = new FakeApi { State = "APPROVAL_PENDING" };
var model = Model(api);
await model.InitializeAsync();
Assert.False(model.SubscribeCommand.CanExecute(null));
model.SelectedOffer = model.Offers[1];
Assert.True(model.SubscribeCommand.CanExecute(null));
model.SelectedOffer = model.SelectedOffer with { Available = false };
Assert.False(model.SubscribeCommand.CanExecute(null));
}
private static SubscriptionsPageViewModel Model(FakeApi api)
=> new(new(api, () => "https://org.example"), _ => Task.FromResult(true));
private sealed class FakeApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public Guid Id { get; } = Guid.NewGuid();
public string? State { get; set; }
public string ApprovalUrl { get; set; } = "https://www.sandbox.paypal.com/approve";
public bool Fail { get; set; }
public HttpMethod? LastMethod { get; private set; }
public string? LastPath { get; private set; }
public object? LastBody { get; private set; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
LastMethod = method;
LastPath = path;
LastBody = body;
if (Fail) throw new HttpRequestException("offline");
var pack = (body as CreateResourceSubscriptionRequest)?.Pack ?? "Premium";
var subscription = new ResourceSubscriptionResponse(Id, pack, State ?? "APPROVAL_PENDING", 2.4m, 3000m, null);
object result;
if (body is CreateResourceSubscriptionRequest)
result = new ResourceSubscriptionCheckoutResponse(subscription, ApprovalUrl);
else
{
if (path.EndsWith("/cancel")) State = null;
result = new ResourceSubscriptionsResponse(
[new("Discovery", "Découverte", 1m, 20m, 1.2m, 1000m, 2, true),
new("Premium", "Premium", 2m, 20m, 2.4m, 3000m, 5, true)],
State is null ? [] : [subscription],
new ResourceUsageSummary { Consumption = path.EndsWith("/refresh") ? 0m : 45m });
}
return Task.FromResult(JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(result))!);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> factory, CancellationToken ct = default) => throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) => throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> factory, CancellationToken ct = default) => throw new NotSupportedException();
public Task<byte[]> DownloadAsync(HttpMethod method, string path, CancellationToken ct = default) => throw new NotSupportedException();
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
}
}

View file

@ -1,16 +0,0 @@
using Avalonia;
using Avalonia.Headless;
[assembly: AvaloniaTestApplication(typeof(PostIt.Tests.TestAppBuilder))]
namespace PostIt.Tests;
public class TestAppBuilder
{
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<PostIt.App>()
.UseHeadless(new AvaloniaHeadlessPlatformOptions
{
UseHeadlessDrawing = true
});
}

View file

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

View file

@ -1,14 +0,0 @@
using Avalonia.Headless.XUnit;
using PostIt.Views;
namespace PostIt.Tests;
public class MainPageTests
{
[AvaloniaFact]
public void MainPage_Should_Load()
{
var window = new MainView();
Assert.NotNull(window);
}
}

View file

@ -0,0 +1,297 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using PostIt.Services;
using PostIt.ViewModels.Chat;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("DependsOn", "Native")]
[Trait("Speed", "Slow")]
[Trait("Category", "non-reg")]
public sealed class WebRtcCallViewModelTests
{
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]
[InlineData(true)]
[InlineData(false)]
public async Task Outgoing_waits_for_acceptance_and_passes_server_policy_to_native_engine(bool relay)
{
var signaling = new Signaling(relay);
var media = new Media();
await using var vm = Configure(signaling, media);
vm.AllowAddressDisclosure = !relay;
await vm.InviteCommand.ExecuteAsync(null);
Assert.True(vm.Busy);
Assert.Null(media.Configuration);
signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
Assert.Equal(relay, media.Configuration!.RelayOnly);
Assert.True(media.Configuration.Caller);
Assert.Same(Turn, media.Configuration.IceServers);
media.Emit(new("offer", Sdp: Sdp));
await WaitAsync(() => signaling.Sent.Count == 1);
signaling.Receive(new("answer", Sdp: Sdp));
await WaitAsync(() => media.Received.Count == 1);
await vm.HangupAsync();
Assert.True(media.Disposed);
Assert.Null(vm.LocalVideo);
Assert.False(vm.Busy);
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
}
[AvaloniaFact]
public async Task Incoming_relay_needs_acceptance_but_never_requires_IP_disclosure()
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
signaling.Invite();
await WaitAsync(() => vm.Incoming);
Assert.False(vm.AllowAddressDisclosure);
Assert.Null(media.Configuration);
await vm.AcceptCommand.ExecuteAsync(null);
await WaitAsync(() => media.Configuration is not null);
Assert.False(media.Configuration!.Caller);
media.Report(new("connected", "relay", 20, 20));
await WaitAsync(() => vm.Status.Contains("IP masquee"));
}
[AvaloniaFact]
public async Task Direct_call_without_consent_ends_before_any_capture()
{
var signaling = new Signaling(false);
var media = new Media();
await using var vm = Configure(signaling, media);
await vm.InviteCommand.ExecuteAsync(null);
Assert.Null(media.Configuration);
Assert.False(vm.Busy);
Assert.Contains("consentez", vm.Status);
Assert.Single(signaling.EndedCalls);
}
[AvaloniaTheory]
[InlineData(false)]
[InlineData(true)]
public async Task Missing_TURN_or_policy_downgrade_never_creates_a_native_engine(bool downgrade)
{
var signaling = new Signaling(true);
var created = false;
await using var vm = new WebRtcCallViewModel(signaling, () =>
{
created = true;
throw new InvalidOperationException("Should not create media");
})
{ Camera = new("Camera", "camera"), Microphone = new("Mic", "default"), Target = "bob", Room = "General" };
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready(downgrade ? signaling.Call with { RelayOnly = false } : null,
downgrade ? Turn : []);
await WaitAsync(() => !vm.Busy);
Assert.False(created);
Assert.Single(signaling.EndedCalls);
}
[AvaloniaTheory]
[InlineData("hangup")]
[InlineData("interrupted")]
[InlineData("ended")]
[InlineData("background")]
[InlineData("dispose")]
public async Task All_termination_paths_cancel_in_progress_native_startup(string reason)
{
var signaling = new Signaling(true);
var media = new Media { DelayStartup = true };
await using var vm = Configure(signaling, media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
switch (reason)
{
case "hangup": await vm.HangupAsync(); break;
case "interrupted": signaling.Disconnect(); break;
case "ended": signaling.End(); break;
case "background": Platform.SuspendPlayback(); break;
case "dispose": await vm.DisposeAsync(); break;
}
await WaitAsync(() => media.Disposed);
Assert.False(vm.Busy);
Assert.Null(vm.RemoteVideo);
Assert.True(media.StartupCancelled);
}
[AvaloniaTheory]
[InlineData("host")]
[InlineData("srflx")]
[InlineData(null)]
public async Task Nonrelay_selected_path_is_rejected_and_media_is_stopped(string? candidateType)
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
media.Report(new("connected", candidateType, 20, 20));
await WaitAsync(() => media.Disposed);
Assert.Contains("chemin ICE", vm.Status);
}
[AvaloniaFact]
public async Task Leaking_candidate_is_not_sent_and_fails_closed()
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
media.Emit(new("candidate", Candidate: "candidate:1 1 UDP 1 192.0.2.1 1234 typ host",
SdpMid: "0", SdpMLineIndex: 0));
await WaitAsync(() => media.Disposed);
Assert.Empty(signaling.Sent);
Assert.Contains("candidat", vm.Status);
}
//[AvaloniaFact]
public async Task Native_failure_is_visible_and_ends_the_server_call()
{
var signaling = new Signaling(true);
var media = new Media();
await using var vm = Configure(signaling, media);
await vm.InviteCommand.ExecuteAsync(null);
signaling.Ready();
await WaitAsync(() => media.Configuration is not null);
media.Fail();
await WaitAsync(() => media.Disposed);
Assert.Contains("native failure", vm.Status);
Assert.Single(signaling.EndedCalls);
}
[Theory]
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ host")]
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ srflx")]
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ relay raddr 198.51.100.1 rport 1234")]
public void Privacy_rejects_nonrelay_or_related_address_leaks(string candidate) =>
Assert.Throws<InvalidOperationException>(() => WebRtcPrivacy.ValidateSignal(
new("candidate", Candidate: candidate, SdpMid: "0", SdpMLineIndex: 0), true));
// [Fact]
public void Privacy_accepts_redacted_relay_and_rejects_SDP_address_leaks()
{
WebRtcPrivacy.ValidateSignal(new("candidate",
Candidate: "candidate:1 1 UDP 1 192.0.2.1 1234 typ relay raddr 0.0.0.0 rport 0",
SdpMid: "0", SdpMLineIndex: 0), true);
WebRtcPrivacy.ValidateSignal(new("offer", Sdp: Sdp), true);
Assert.Throws<InvalidOperationException>(() =>
WebRtcPrivacy.ValidateSignal(new("offer", Sdp: Sdp.Replace("0.0.0.0", "198.51.100.1")), true));
}
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",
SkipUnless = nameof(NativeMediaAvailable))]
public async Task Linux_native_adapters_render_remote_bitmaps_and_receive_audio_in_both_directions()
{
await using var caller = new LinuxWebRtcMedia();
await using var callee = new LinuxWebRtcMedia();
var errors = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
void Forward(IWebRtcMedia destination, CallSignal signal) => Dispatcher.UIThread.Post(async () =>
{
try { await destination.HandleSignalAsync(signal, timeout.Token); }
catch (Exception error) { errors.TrySetException(error); }
});
caller.Signal += signal => Forward(callee, signal);
callee.Signal += signal => Forward(caller, signal);
WebRtcMediaStatus? callerStatus = null, calleeStatus = null;
caller.StatusChanged += status => callerStatus = status;
callee.StatusChanged += status => calleeStatus = status;
await callee.StartAsync(new([], false, false, "test", "test"), timeout.Token);
await caller.StartAsync(new([], false, true, "test", "test"), timeout.Token);
while (callerStatus is not { HasRemoteMedia: true } || calleeStatus is not { HasRemoteMedia: true } ||
((Image)caller.RemoteVideo).Source is not Bitmap || ((Image)callee.RemoteVideo).Source is not Bitmap)
{
if (errors.Task.IsCompleted) await errors.Task;
if (caller.Completion.IsCompleted) await caller.Completion;
if (callee.Completion.IsCompleted) await callee.Completion;
await Task.Delay(20, timeout.Token);
}
Assert.Equal(640, ((Bitmap)((Image)caller.RemoteVideo).Source!).PixelSize.Width);
Assert.Equal(360, ((Bitmap)((Image)callee.RemoteVideo).Source!).PixelSize.Height);
}
private static WebRtcCallViewModel Configure(Signaling signaling, Media media) => new(signaling, () => media)
{ Camera = new("Camera", "camera"), Microphone = new("Mic", "default"), Target = "bob", Room = "General" };
private static async Task WaitAsync(Func<bool> condition)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
while (!condition()) await Task.Delay(10, timeout.Token);
}
private sealed class Media : IWebRtcMedia
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Control LocalVideo { get; } = new Border();
public Control RemoteVideo { get; } = new Border();
public event Action<CallSignal>? Signal;
public event Action<WebRtcMediaStatus>? StatusChanged;
public Task Completion => _completion.Task;
public WebRtcMediaConfiguration? Configuration { get; private set; }
public bool Disposed { get; private set; }
public bool StartupCancelled { get; private set; }
public bool DelayStartup { get; init; }
public List<CallSignal> Received { get; } = [];
public async Task StartAsync(WebRtcMediaConfiguration configuration, CancellationToken ct)
{
Configuration = configuration;
if (DelayStartup)
{
try { await Task.Delay(Timeout.Infinite, ct); }
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{ StartupCancelled = true; throw; }
}
}
public Task HandleSignalAsync(CallSignal signal, CancellationToken ct)
{ Received.Add(signal); return Task.CompletedTask; }
public void Emit(CallSignal signal) => Signal?.Invoke(signal);
public void Report(WebRtcMediaStatus status) => StatusChanged?.Invoke(status);
public void Fail() => _completion.TrySetException(new IOException("native failure"));
public ValueTask DisposeAsync()
{ Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
}
private sealed class Signaling(bool relay) : IWebRtcCallSignaling
{
public event Action<CallSession>? Invitation;
public event Action<CallAccepted>? Accepted;
public event Action<CallEnded>? Ended;
public event Action<Guid, CallSignal>? Signal;
public event Action? Interrupted;
public CallSession Call { get; } = 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> InviteLanAsync(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 Ready(CallSession? session = null, CallIceServer[]? servers = null) =>
Accepted?.Invoke(new(session ?? Call, servers ?? Turn));
public void Receive(CallSignal signal) => Signal?.Invoke(Call.Id, signal);
public void End() => Ended?.Invoke(new(Call.Id, "ended"));
public void Disconnect() => Interrupted?.Invoke();
}
}

View file

@ -15,6 +15,8 @@ namespace PostIt.Tests;
/// Uses the project's <see cref="OIDCStubAuthority"/> for the IdP and
/// a tiny in-process HTTP listener for the API server side.
/// </summary>
[Trait("Category", "Integration")]
[Trait("Category", "non-reg")]
public class YavscApiClientTests
{
[Theory]

View file

@ -124,6 +124,21 @@ public partial class App : Application, ILiveView, IVMPusherApp
#endif
}
public static async Task<bool> ConfirmAsync(
string title,
string message,
string confirmText = "Confirmer",
string cancelText = "Annuler")
{
var app = Current as App;
if (app is null || app.View is null)
return false;
var vm = new ConfirmationDialogViewModel(title, message, confirmText, cancelText);
await app.PushPageAsync(vm);
return await vm.WaitForResultAsync();
}
public async Task<Page> PushPageAsync(ViewModelBase viewModel)
{
var mainView = View ?? throw new InvalidOperationException("The navigation root is not initialized.");

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

View file

@ -0,0 +1,165 @@
<?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>

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -94,8 +94,10 @@ public static class ServiceCollectionHelpers
services.AddTransient<EstimateValidationPage>();
services.AddTransient<MyFilesPage>();
services.AddTransient<UserProfilePage>();
services.AddTransient<SubscriptionsPage>();
services.AddTransient<PerformerConfigurationPage>();
services.AddTransient<AdministrationPage>();
services.AddTransient<ResourceUsageReliefPage>();
// ViewModels
services.AddSingleton(settings);
@ -110,6 +112,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton(invoicesClient);
services.AddSingleton(frontClient);
services.AddSingleton(resourceUsageClient);
services.AddSingleton(new ResourceSubscriptionsApiClient(api, () => settings.Authentication.Authority));
services.AddSingleton(administrationClient);
services.AddSingleton(notificationsClient);
services.AddSingleton(podcastClient);
@ -120,8 +123,10 @@ public static class ServiceCollectionHelpers
services.AddSingleton<AboutPageViewModel>();
services.AddSingleton<HomePageViewModel>();
services.AddTransient<UserProfilePageViewModel>();
services.AddTransient<SubscriptionsPageViewModel>();
services.AddTransient<PerformerConfigurationPageViewModel>();
services.AddTransient<AdministrationPageViewModel>();
services.AddTransient<ResourceUsageReliefPageViewModel>();
services.AddSingleton<SignaturePageViewModel>();
services.AddSingleton<CirclesPageViewModel>();
services.AddSingleton<ActivitiesPageViewModel>();
@ -135,6 +140,7 @@ public static class ServiceCollectionHelpers
// here — the parametrised ctors stay for direct test wiring.
services.AddTransient<PostAclDialog>();
services.AddTransient<AddCircleMemberDialog>();
services.AddTransient<ConfirmationDialog>();
// Persistent session banner: one instance for the lifetime of
// the app so the same VM survives page navigation.
var sessionStatus = new SessionStatusViewModel { Api = api };

View file

@ -19,6 +19,7 @@
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Services/WebRtc/gstreamer_peer.py" LogicalName="PostIt.WebRtc.gstreamer_peer.py" />
<EmbeddedResource Include="postit-settings.json">
<LogicalName>PostIt.postit-settings.json</LogicalName>
</EmbeddedResource>

View file

@ -6,7 +6,7 @@ using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed class CallSignalingClient : ILanCallSignaling, IDisposable
public sealed class CallSignalingClient : IWebRtcCallSignaling, IDisposable
{
private readonly HubConnection _connection;
private readonly IDisposable[] _subscriptions;

View file

@ -0,0 +1,32 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
public sealed record WebRtcMediaConfiguration(CallIceServer[] IceServers, bool RelayOnly,
bool Caller, string Camera, string Microphone);
public sealed record WebRtcMediaStatus(string ConnectionState, string? LocalCandidateType,
long AudioPackets, long VideoFrames, bool LocalVideoRendered = false, bool RemoteVideoRendered = false)
{
public bool HasRemoteMedia => ConnectionState == "connected" && AudioPackets > 0 && VideoFrames > 0;
}
public interface IWebRtcMedia : IAsyncDisposable
{
Control LocalVideo { get; }
Control RemoteVideo { get; }
event Action<CallSignal>? Signal;
event Action<WebRtcMediaStatus>? StatusChanged;
Task Completion { get; }
Task StartAsync(WebRtcMediaConfiguration configuration, CancellationToken ct);
Task HandleSignalAsync(CallSignal signal, CancellationToken ct);
}
public interface IWebRtcCallSignaling : ILanCallSignaling
{
Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default);
}

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