diff --git a/CHANGELOG.md b/CHANGELOG.md
index d89929c6a..3ee921d5e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,17 @@
### Added
+* [PostIt/API/Yavsc.Org] Expose the private PayPal recipient setting in PostIt's performer editor and authenticated profile API; validate addresses, allow disabling with an empty value and preserve the setting for older clients. Make Web donation settings discoverable from the performer profile and podcast catalogue.
+* [API] Initialize the required address field when creating a performer profile so a first configuration can be saved.
+* [Yavsc.Org] Add an authenticated Razor podcast catalogue with same-origin API-backed HLS/MP4 playback and replay byte-range support. Reuse Site.ApiUrl and the authority's signing credentials to issue short-lived user tokens, without a separate OAuth client or PodcastWeb configuration. Distinguish an empty catalogue from API/configuration failures.
+* [Yavsc.Org] Integrate direct PayPal donations to performers: self-service recipient settings, Yavsc donation pages/history, server-verified checkout and capture, antiforgery/concurrency protection, and validated IPN reconciliation. Reuse the existing merchant settings and persist donation receipts in a dedicated migration; keep uncertain and pending payments distinct from completed donations.
+* [PostIt] Open the Yavsc.Org podcast catalogue in the browser instead of the authenticated API playlist; preserve embedded playback and external blog-video links.
+* [PostIt.Android/Desktop] Extend LAN/VPN SRTP calls to Android 8+ using the existing front-camera/microphone Podcast capture, rotated native preview and embedded LibVLC remote video, without libwebrtc or new dependencies. Pass the live MediaRecorder pipe directly to the shared SRTP engine without HLS files or transcoding; add a call-specific foreground notification, stop on backgrounding, and allow incoming callers to configure devices before acceptance. Use separate RTP/RTCP UDP ports to avoid a diagnosed Android VLC `rtcp-mux` SDP-generation crash. Add debug-only physical camera/SRTP checks and shared control/pipe-input regressions; Internet/TURN/group calls remain outside this transport.
+
+* [PostIt.Desktop/API] Add opt-in Linux LAN/VPN peer calls through the existing ChatHub, reusing Podcast LibVLC camera/microphone capture and H.264/AAC encoding with direct SRTP instead of HLS. Add consent, embedded local/remote video, hangup/interruption cleanup, private IPv4 validation and per-direction ephemeral keys over HTTPS-only signaling. Reject IP-masking accounts rather than silently bypassing TURN; keep this transport disabled by default and separate from the future Internet/group-call design. Test real bidirectional encrypted audio/video, wrong-key rejection, preview output, signaling and UI lifecycle; physical camera/two-machine rendering remains to validate.
+* [PostIt/API] Begin Android/Linux call integration on the existing authenticated ChatHub: typed invitation, single-device consent, bounded SDP/ICE exchange and hangup; derive relay policy from account preferences and issue temporary coturn credentials. Attach the shared PostIt signaling client to the chat connection, end calls on disconnect/room departure/privacy activation, and add targeted regression tests. Calls remain disabled by default; native media adapters and Android/Linux end-to-end validation are not implemented yet.
+* [PostIt] Clarify reuse of the existing ChatHub for call signaling and document the inconclusive Android native WebRTC experiment; discard the isolated laboratory without changing production chat or media behavior.
+* [PostIt/API] Persist the account-level `HideIpAddressInCalls` preference (default false), expose it through the authenticated profile API and PostIt profile editor, and preserve it when older clients omit it. Prepare future TURN-only calls without enabling media transport yet.
* [PostIt] Show a local live capture preview on Android and Desktop without opening a second camera or reading back uploaded segments. Share Android's oriented EGL frames with an aspect-preserving preview surface; duplicate Desktop LibVLC output without local microphone playback.
* [Podcasts] Prepare authenticated, seekable MP4 replays for new and existing Completed broadcasts using server-side FFmpeg stream copy and faststart. Retain MPEG-TS, account for both copies in the owner quota, recover preparation after restarts, and expose owner-only retries plus GET/HEAD byte-range playback.
* [PostIt] Add Android/Desktop native video overlays for MP4 replay position, duration, seeking and play/pause, with three-second auto-hide. Use bounded authenticated range input with token refresh; preserve MPEG-TS live/interrupted playback.
diff --git a/README.md b/README.md
index 6d4784bad..90e7ba5ba 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,8 @@ Pour une prise en main guidee avec agents IA:
## Construction
```bash
- dotnet build
+sudo dotnet workload restore
+dotnet build
```
et, pour execution en environment de développement
diff --git a/doc/Architecture.md b/doc/Architecture.md
index d48dff22b..d8f1406d7 100644
--- a/doc/Architecture.md
+++ b/doc/Architecture.md
@@ -57,6 +57,91 @@ sudo adduser --ingroup yavsc --add-extra-groups www-data \
--disabled-password --system yavsc
```
+## Catalogue Web de podcasts
+
+`/Podcast` (vue `src/Yavsc.Org/Views/Podcast/Index.cshtml`) exige une
+session Identity Yavsc.Org, y compris pour chaque requête de lecture.
+Yavsc.Org interroge Yavsc.Api côté serveur ; aucun jeton n'est transmis
+au navigateur et aucun second catalogue de stockage n'est créé.
+Les replays MP4 prêts prennent en charge GET, HEAD et les plages
+d'octets. Les directs et replays non encore convertis utilisent HLS
+natif ou hls.js (servi localement, installé par `npm install` et copié par
+`npm run build:podcasts`, également inclus dans la copie d'assets de
+`npm run build:js`). Sans support vidéo compatible, la page affiche un
+avertissement et invite à utiliser PostIt. Cette page ne crée ni ne
+supprime de podcast.
+Depuis le lecteur PostIt, « Ouvrir dans le navigateur » ouvre `/Podcast`
+sur l'hôte `Authentication.Authority`, pas la playlist API authentifiée.
+La session Web reste distincte de celle de PostIt : le navigateur peut
+donc demander une connexion.
+
+Il n'y a pas de section de configuration `PodcastWeb`, ni de client OAuth
+technique à enregistrer. L'adresse API est celle de `Site:ApiUrl`, en HTTPS
+(avec ou sans suffixe `/api/v1`). Yavsc.Org est l'autorité : comme pour
+l'envoi d'avatar, `IdentityServerTools.IssueJwtAsync` utilise sa signature
+existante pour émettre un jeton de cinq minutes au nom de l'utilisateur
+connecté (`sub`, audience `api`, scope `api` attendu par Yavsc.Api).
+Ce jeton reste côté serveur. Une adresse API manquante renvoie 503 ;
+une panne de l'API renvoie une erreur explicite, pas un catalogue vide.
+
+### Dons PayPal aux performers
+
+Les dons sont gérés par Yavsc.Org, pas par un lien de paiement externe
+configuré par l'opérateur :
+
+1. Depuis **Mon compte > Dons PayPal**, le performer renseigne l'adresse
+ de son propre compte PayPal (`/Donation/Settings`). Un champ vide
+ désactive les nouveaux dons. Seuls les performers actifs ayant
+ configuré leur compte proposent un bouton de don dans le catalogue.
+ Le formulaire est aussi accessible depuis le catalogue de podcasts et
+ le profil professionnel Web. Dans PostIt : **Mon profil > Gérer mon
+ activité professionnelle > Dons PayPal**, puis **Enregistrer**.
+ L'API privée `GET/PUT /api/v1/account/performer-profile` transporte
+ `DonationPayPalEmail` uniquement pour le compte connecté ; une chaîne
+ vide désactive les dons, une propriété omise ou nulle préserve
+ l'adresse existante pour les anciens clients.
+2. Le donateur connecté choisit un montant en euros (`/Donation/Create`).
+ Yavsc conserve le don et son bénéficiaire avant de créer le checkout.
+3. Yavsc utilise les paramètres marchands existants
+ `Authentication:PayPal` (mode sandbox/production et identifiants NVP).
+ Express Checkout désigne le compte du performer par
+ `PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID` : le paiement va directement
+ au performer ; Yavsc ne collecte pas les fonds et ne les reverse pas.
+4. PayPal recueille l'accord du donateur puis le renvoie dans Yavsc.
+ Une confirmation POST avec protection antiforgery déclenche le
+ paiement, après vérification côté serveur du token, du montant,
+ de la devise, de la référence et du bénéficiaire. Un simple retour
+ du navigateur n'est jamais considéré comme une preuve de paiement.
+5. Seule une réponse PayPal vérifiée permet d'afficher le don comme payé.
+ Les notifications IPN reçues sur `/Donation/Notify` sont revalidées
+ auprès de PayPal, puis rapprochées du bénéficiaire, du montant, de la
+ devise et de la transaction. Elles permettent aussi de confirmer
+ ultérieurement un paiement Pending ou une réponse de capture perdue.
+
+`Site:ExternalUrl` doit être l'URL HTTPS publique de Yavsc.Org, utilisée
+pour les retours et notifications (jamais le Host fourni par le client).
+PayPal doit pouvoir joindre `/Donation/Notify`. Le compte marchand
+doit être autorisé par PayPal pour les paiements directs à un tiers ;
+valider ce parcours en sandbox avec deux comptes distincts avant mise
+en production. Les tests locaux utilisent un serveur PayPal simulé,
+pas de véritables transactions.
+
+`PerformerDonations` conserve la référence, le donateur, le performer,
+le bénéficiaire figé à la création, le montant et l'état du paiement.
+La migration `PerformerPayPalDonations` ajoute ce suivi et l'adresse
+PayPal optionnelle du performer. Les profils ayant un historique de
+dons ne peuvent pas être supprimés. Les rééditions du profil général
+ne remplacent pas la configuration du bénéficiaire.
+
+Le paiement n'est capturé qu'une fois : contrôle de concurrence,
+référence de déduplication PayPal (`MSGSUBID`) et transaction unique.
+En cas de réponse ambiguë, le don reste en vérification sans nouvelle
+capture automatique. Le donateur retrouve son suivi dans **Mon compte >
+Mes dons** (`/Donation`). Si l'IPN ne réconcilie pas cet état, l'opérateur
+doit vérifier la transaction auprès de PayPal avant toute nouvelle
+tentative. Les dons sont facultatifs et n'ouvrent pas droit à un reçu
+fiscal émis par cette page.
+
## À documenter ensuite
- Modèle `ProjetMusical`
diff --git a/doc/architecture/audio-video-calls.md b/doc/architecture/audio-video-calls.md
index 68f5c1e50..4c4ee0f26 100644
--- a/doc/architecture/audio-video-calls.md
+++ b/doc/architecture/audio-video-calls.md
@@ -2,10 +2,14 @@
## Statut et périmètre
-Ce document décrit un **plan d'implémentation**, pas une fonctionnalité déjà
-disponible. Il complète la [topologie de PostIt](postit.md) et les
+Ce document décrit l'architecture cible et l'implémentation commencée.
+La préférence de confidentialité est persistée et éditable dans le profil.
+La signalisation est intégrée au chat, désactivée par défaut. Un premier
+transport natif **Android et Desktop Linux sur LAN/VPN** est raccordé :
+captures Podcast existantes et SRTP direct, sans libwebrtc ni nouvelle
+couche JNI WebRTC. Il ne réalise pas encore la cible Internet, TURN ou groupe.
+Il complète la [topologie de PostIt](postit.md) et les
[mécanismes de notification existants](notifications.md).
-
La cible couvre :
- les appels audio-vidéo bidirectionnels entre deux utilisateurs ;
@@ -14,8 +18,213 @@ La cible couvre :
- les appels de groupe ;
- les clients Browser, Android et Desktop.
+## Première implémentation Android et Desktop Linux : SRTP sur LAN/VPN
+
+Cette tranche réutilise la capture caméra/microphone et les encodeurs des
+Podcasts, mais **pas leur segmentation HLS ni leurs envois de fichiers** :
+
+```text
+PostIt A ----------- ChatHub authentifié / HTTPS ----------- PostIt B
+ invitation, consentement,
+ adresses et clés, fin
+
+PostIt A ========== H.264/AAC, MPEG-TS sur SRTP/UDP ========== PostIt B
+ dans les deux sens
+```
+
+L'implémentation est dans
+[LibVlcLanCallMedia](../../src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs),
+[LinuxLanCallVideo](../../src/PostIt/PostIt/Services/LinuxLanCallVideo.cs) et
+[LanCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs).
+Android utilise
+[AndroidLanCallMedia](../../src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs)
+avec les mêmes contrats et clés SRTP.
+Les contrôles et les deux surfaces vidéo sont intégrés à la page du chat.
+Il n'y a pas de service de salles supplémentaire, d'enregistrement,
+de fichier média temporaire ou de moteur WebRTC Android ajouté.
+
+### Activer et essayer
+
+1. Sur le serveur, activer explicitement les deux options :
+
+ ```json
+ {
+ "AudioVideoCalls": {
+ "Enabled": true,
+ "EnableLanCalls": true
+ }
+ }
+ ```
+
+ Les deux valeurs sont `false` par défaut. Les paramètres TURN ne sont
+ pas nécessaires pour ce mode. Utiliser le ChatHub en **HTTPS** ;
+ invitation, acceptation et échange de clés LAN sont refusés en HTTP.
+ Derrière un proxy TLS, configurer correctement le schéma HTTPS transmis
+ à ASP.NET Core, uniquement depuis les proxys de confiance.
+2. Utiliser deux clients Android 8+ ou Desktop Linux. Linux nécessite LibVLC
+ avec V4L2, PulseAudio, x264, AAC et RTP/SRTP installés. Android réutilise
+ la bibliothèque VLC embarquée pour les Podcasts et MediaRecorder pour
+ H.264/AAC. La version Debian 13 a été utilisée pour les essais Linux.
+ Les deux comptes doivent être présents dans
+ la même salle existante et ne pas se bloquer mutuellement.
+3. Dans « Appel direct (LAN/VPN) », actualiser les périphériques,
+ sélectionner la caméra, le microphone et une IPv4 privée locale
+ accessible depuis le pair. Les adresses RFC1918 et de bouclage sont
+ acceptées ; pas de DNS, IPv6 ou adresse publique. Le bouclage sert aux
+ essais sur un même hôte, pas à joindre un second poste.
+4. Choisir un port UDP **pair entre 1024 et 65534**, par défaut 5004.
+ Autoriser l'entrée UDP sur ce port **et le suivant** depuis le pair dans
+ le pare-feu : RTP sur le port pair, RTCP sur le port impair suivant.
+ Les deux ports doivent être disponibles. Deux clients sur la même
+ adresse doivent utiliser des paires distinctes.
+ Aucun pare-feu n'est modifié automatiquement.
+5. Saisir le pseudo exact du destinataire, confirmer la divulgation de
+ l'adresse LAN/VPN, puis appeler. Le destinataire choisit ses propres
+ périphériques et son adresse, confirme et accepte explicitement.
+ Aucun accès à la caméra/microphone ne commence avant l'acceptation ;
+ l'émission attend également la destination validée du pair.
+6. Utiliser un **casque** : il n'y a pas d'annulation d'écho acoustique.
+ « Refuser / Raccrocher », la sortie de page et la perte de SignalR
+ arrêtent et libèrent les médias. Il n'y a pas de reprise automatique
+ de capture après reconnexion.
+
+### Capture et cycle de vie Android
+
+- La caméra avant est sélectionnée en priorité dans la liste ; une autre
+ caméra reste sélectionnable explicitement. Le microphone est obligatoire.
+- Les permissions caméra, microphone et notifications sont demandées
+ après acceptation et réception de l'endpoint distant, avant la capture.
+ Un refus termine explicitement l'appel, sans tentative de capture de repli.
+- Camera2, MediaRecorder et la rotation EGL sont ceux des Podcasts.
+ Le descripteur du pipe MPEG-TS est lu directement par LibVLC (`fd://`)
+ puis remultiplexé vers SRTP, **sans réencodage**, HLS ou fichier média.
+ Le pipe système assure une mémoire bornée ; il n'y a pas de file de
+ segments ni de lecture de capture par callbacks managés.
+- La prévisualisation réutilise la surface EGL existante. Le retour
+ distant utilise la surface Android LibVLC déjà employée pour les Podcasts.
+- Le service de capture partagé affiche une notification d'appel avec
+ l'action « Raccrocher » ; cette action ne publie aucun Podcast.
+ Un Podcast et un appel ne peuvent pas posséder la capture simultanément.
+- Le passage de PostIt en arrière-plan termine cet appel vidéo ; revenir
+ dans l'application ne le redémarre pas. La sortie de page et la perte
+ SignalR conservent la même règle d'arrêt.
+- À l'arrêt, le lecteur natif libère d'abord son entrée. Le pipe restant
+ est drainé pendant la finalisation de MediaRecorder, pour ne pas bloquer
+ son écrivain, puis caméra, microphone, lecteurs et service sont libérés.
+
+#### Particularité VLC Android : RTCP séparé
+
+L'essai matériel initial a identifié un SIGSEGV dans `libc.__vfprintf`,
+appelé par `vlc_memstream_vprintf` puis `sdp_AddAttribute` pendant la
+création de la sortie RTP. Le code VLC 3 génère l'attribut sans valeur
+`rtcp-mux` avec un format nul ; cette combinaison échoue avec le binaire
+Android embarqué. Ce crash est distinct du précédent essai libwebrtc/JNI.
+
+Les appels utilisent donc une paire RTP/RTCP standard, sans `rtcp-mux`,
+sur Android **et** Linux. Les médias conservent les mêmes codecs, clés et
+port RTP : c'est un changement de configuration du transport, pas
+l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet.
+
+### Confidentialité et limites
+
+- Une clé SRTP aléatoire de 128 bits et un sel de 112 bits sont générés
+ par appel et par direction avec le générateur cryptographique système.
+ Seuls les deux appareils ayant accepté échangent un endpoint chacun
+ via SignalR authentifié. Les représentations diagnostiques masquent
+ adresse, clé et sel.
+- Le chiffrement SRTP est fourni par LibVLC ; les clés passent par
+ le serveur de signalisation, qui **peut donc les connaître**. Ce n'est
+ pas un chiffrement de bout en bout à l'insu du serveur.
+- Si l'un des comptes impose `HideIpAddressInCalls`, le mode LAN est
+ **refusé**, y compris si la préférence change avant l'acceptation.
+ Il n'y a aucun repli direct contournant cette préférence.
+- Pas d'ICE, de STUN, de TURN, de traversée NAT automatique, de groupe,
+ d'interopérabilité Browser, de négociation de codecs ni
+ d'adaptation de débit. Ce mode exige un LAN/VPN routable entre les pairs.
+- H.264 à 30 images/s, cible 1 200 kbit/s ; AAC mono 48 kHz, 96 kbit/s.
+ Ces réglages ne constituent pas une garantie de latence ni de débit.
+ Le retour local n'émet pas le son du microphone.
+- L'absence de première réception audio **et** vidéo provoque l'arrêt
+ après 30 secondes ; les erreurs natives sont affichées et terminent
+ l'appel. Après réception initiale, les compteurs LibVLC ne permettent
+ pas ici de diagnostiquer précisément une panne média silencieuse :
+ l'utilisateur peut raccrocher, et la perte de SignalR arrête toujours
+ la capture. Pas encore de mesure de qualité ou de latence affichée.
+
+### Validation effectuée et restante
+
+Les tests natifs utilisent deux moteurs LibVLC réels, un fichier audio-vidéo
+synthétique fourni explicitement et de vrais sockets UDP de bouclage :
+
+- décodage bidirectionnel de trames vidéo et d'échantillons audio PCM ;
+- refus de décodage avec une mauvaise clé, sans casser l'autre direction ;
+- même échange avec la branche de prévisualisation locale activée
+ (sortie factice dans ce test sans fenêtre).
+- entrée MPEG-TS déjà encodée à travers un pipe, sans transcodage.
+
+Les tests de signalisation couvrent consentement, sélection d'un seul
+appareil, confidentialité, HTTPS, validation des endpoints et arrêt.
+Les tests Avalonia sans fenêtre couvrent l'ordre invitation/acceptation/
+capture, le refus, les événements tardifs, l'interruption, les erreurs média
+et l'annulation d'un démarrage natif en attente. Ils vérifient aussi les
+hooks Android, le choix initial de caméra avant, la configuration lors
+d'une invitation entrante et l'arrêt lors du passage en arrière-plan.
+
+Pour exécuter les tests média, définir `POSTIT_TEST_MEDIA` avec le chemin
+d'un MP4 H.264/AAC de test (640 × 480), puis :
+
+```sh
+dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
+ --filter-class '*LinuxLanCallMediaTests'
+```
+
+Sans cette entrée explicite, ces tests sont ignorés, pas remplacés par un
+succès fictif. Les tests de contrôle s'exécutent sans caméra.
+Le test de pipe utilise `POSTIT_TEST_TS`, un MPEG-TS H.264/AAC explicite.
+
+Une activité **Debug uniquement**,
+[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs),
+teste l'adaptateur réel sur téléphone : caméra avant/microphone, surfaces
+de retour et prévisualisation attachées, deux moteurs SRTP en UDP de
+bouclage, retour synthétique et rejet d'une mauvaise clé. Elle n'utilise
+ni compte ni API ; elle ne valide donc pas à elle seule un appel SignalR
+entre deux comptes. L'activité n'est pas compilée dans l'APK Release.
+
+Pour la lancer sur un appareil de développement dont les permissions
+ont été accordées, installer l'APK Debug et ses assemblies via
+`dotnet build -t:Install`, puis copier un MPEG-TS synthétique de 40 secondes,
+640 × 480 avec audio AAC, sous `files/lan-call-fixture.ts` dans les données
+privées de l'application. Exécuter :
+
+```sh
+adb shell am start -S -n fr.pschneider.postit/fr.pschneider.postit.LanCallTestActivity
+adb shell run-as fr.pschneider.postit cat files/lan-call-test-result.txt
+# Variante : ajouter --es wrongKey true à la commande am start.
+```
+
+Le résultat ne devient `PASS` qu'après vérification des médias et nettoyage
+complet. Le test ne produit aucun enregistrement de caméra.
+Sur le téléphone Android 15 arm64 connecté, l'essai positif a décodé
+158 trames caméra et 399 360 échantillons audio en environ dix secondes,
+avec un retour audio/vidéo décodé simultanément. L'essai avec mauvaise clé
+a produit zéro trame et zéro échantillon dans la direction concernée,
+tout en conservant le retour. Les deux essais ont terminé leur nettoyage,
+sans service de capture restant. La capture Podcast antérieure a également
+été retestée sur caméra avant : quatre segments, environ 11,8 secondes,
+audio AAC présent, capture en arrière-plan puis arrêt par notification.
+
+**La caméra physique, le rendu natif visible dans deux applications, le
+son audible et un appel entre deux machines restent à valider côté Linux** :
+aucune caméra n'était disponible sur cet hôte. La capture matérielle Android
+est testée, mais un appel Android ↔ Linux ou entre deux téléphones distincts
+sur LAN/VPN et la qualité acoustique restent à valider. Les essais de
+bouclage ne prouvent pas une latence conversationnelle.
+
## Choix des protocoles
+La table suivante demeure la **cible multi-plateforme initiale**, distincte
+du premier transport Linux LAN/VPN décrit ci-dessus.
+
| Besoin | Choix | Rôle |
|---|---|---|
| Médias temps réel | WebRTC | Audio-vidéo bidirectionnel à faible latence, adaptation au réseau |
@@ -27,8 +236,11 @@ La cible couvre :
| Appels de groupe | SFU compatible WebRTC | Réception et redistribution sélective des flux |
SignalR transporte les messages de contrôle, **jamais les flux audio-vidéo**.
-La signalisation peut utiliser l'infrastructure SignalR existante, mais les
-contrats d'appel et leurs autorisations doivent être distincts du chat.
+La signalisation doit réutiliser le [ChatHub existant](../../src/Yavsc.Server/Hubs/ChatHub.cs),
+déjà exposé par [Yavsc.Api](../../src/Yavsc.Api/Program.cs), et ses salles de
+discussion. Il n'est pas nécessaire de créer un second service de salles.
+Les contrats d'appel et leurs autorisations restent à définir explicitement :
+l'appartenance à une salle ne vaut pas acceptation d'un appel.
Le choix des bibliothèques natives, du SFU et des codecs effectivement
disponibles reste à valider par un prototype multi-plateforme.
@@ -82,12 +294,17 @@ simplicité d'exploitation prime sur le coût serveur.
### Contrat fonctionnel
-Prévoir un booléen de compte, nommé provisoirement `HideIpAddressInCalls`,
-persisté côté serveur et accessible en lecture/écriture uniquement par
-l'utilisateur concerné via la gestion de son profil. Le réglage est partagé
-entre ses appareils ; une préférence locale seule ne suffit pas.
+Le booléen de compte `HideIpAddressInCalls` est persisté côté serveur et
+accessible en lecture/écriture uniquement par
+l'utilisateur concerné via `GET /api/v1/account/me` et
+`PUT /api/v1/account/me`, ainsi que dans « Mon profil » de PostIt.
+Le réglage est partagé entre ses appareils ; une préférence locale seule
+ne suffit pas.
-Valeur initiale proposée : `false`, à confirmer avant implémentation.
+Valeur initiale : `false`, pour les nouveaux comptes et les comptes existants
+après migration. Le champ de mise à jour est nullable : son absence ou `null`
+conserve la valeur existante, notamment pour les anciens clients ; `false`
+explicite désactive la préférence.
`false` autorise le chemin direct mais n'interdit pas TURN lorsqu'il est
nécessaire à la connectivité. `true` impose un transport relayé.
@@ -96,6 +313,12 @@ en précisant le surcoût potentiel en latence et en bande passante serveur.
Il ne procure pas l'anonymat : les services contactés, notamment l'API, le
serveur de signalisation et TURN, peuvent toujours connaître l'adresse IP.
+La migration EF Core `HideIpAddressInCalls`, dans le projet Yavsc.Org, ajoute
+la colonne booléenne non nullable à `AspNetUsers`. Elle doit être déployée
+avant de servir les nouvelles lectures et écritures de profil. Cette étape
+n'installe ni TURN ni SFU et n'implémente pas encore les règles de négociation
+décrites ci-dessous.
+
### Application à la négociation
- Charger la préférence avant de créer le transport média. Si sa lecture
@@ -199,4 +422,140 @@ la signalisation des premiers appels à deux.
- Activation du masquage pendant un appel : suspension des médias,
remplacement vérifié du transport et retour d'état fidèle dans l'interface.
- Échecs de permissions, de signalisation, de TURN et du SFU visibles,
- ressources caméra/micro et connexions libérées à la fin de l'appel.
\ No newline at end of file
+ ressources caméra/micro et connexions libérées à la fin de l'appel.
+
+## Première tranche intégrée : signalisation Android et Desktop Linux
+
+Le périmètre initial retenu est **Android + Desktop Linux**. Il n'ajoute
+aucun serveur ni aucune salle : les méthodes suivantes appartiennent au
+[ChatHub](../../src/Yavsc.Server/Hubs/ChatHub.Calls.cs) existant.
+Les [contrats partagés](../../src/Yavsc.Abstract/Chat/Calls/CallContracts.cs)
+sont utilisés par le serveur et PostIt.
+
+| Méthode | Effet |
+|---|---|
+| `InviteCall(roomName, callee)` | Invite un autre compte présent dans la salle et retourne un identifiant d'appel |
+| `AcceptCall(callId)` | Accepte sur un seul appareil, notifie les deux pairs et ferme l'invitation sur les autres appareils |
+| `SendCallSignal(callId, signal)` | Transmet l'offre, la réponse ou un candidat ICE uniquement à l'autre appareil accepté |
+| `EndCall(callId)` | Annule, refuse ou termine l'appel depuis un appareil autorisé |
+
+Événements : `CallInvitation`, `CallAccepted`, `CallSignal(callId, signal)`
+et `CallEnded`. **Accepté ne veut pas dire connecté** : l'événement accepté
+exprime le consentement et fournit la politique ICE et les paramètres
+STUN/TURN, pas une réussite de l'échange média.
+
+Le serveur vérifie les comptes, la présence dans la salle et le blocage
+entre utilisateurs. Les appareils d'un compte reçoivent l'invitation ;
+seul le premier qui accepte peut ensuite émettre la réponse et les
+candidats. L'appelant reste lié à sa connexion d'origine. Les médias
+ne sont jamais diffusés au groupe SignalR de la salle.
+
+La préférence persistée est lue à l'invitation et relue à l'acceptation.
+Pour cette première version à deux, si l'un des comptes demande le
+masquage, **les deux transports doivent être relayés**, règle conservatrice
+plus stricte que la politique individuelle cible. L'acceptation ne peut
+pas diminuer la protection annoncée à l'invitation. Sans TURN configuré,
+un appel imposant le relais échoue explicitement.
+
+La signalisation refuse les candidats non relayés, les adresses associées
+non masquées et les adresses directes dans les champs SDP contrôlés lorsque
+le relais est imposé. Ces contrôles de forme ne constituent pas un audit
+exhaustif de toutes les extensions SDP possibles : la non-divulgation doit
+encore être prouvée avec les SDP et statistiques des moteurs réellement
+intégrés. Aucun SDP n'est réécrit.
+
+L'activation du masquage ou le changement de pseudo par l'API de profil
+termine l'appel existant ; le client devra libérer les médias et proposer
+un nouvel appel. La renégociation transparente du transport n'est pas
+implémentée. La déconnexion d'un pair sélectionné, le départ ou l'exclusion
+de la salle terminent également l'appel. Pas de reprise automatique après
+reconnexion : elle crée une nouvelle identité de connexion.
+
+Les appels sont temporaires, en mémoire et **sur une seule instance API**.
+Une invitation expire après 45 secondes, une session acceptée après une
+heure ; les identifiants TURN expirent cinq minutes plus tard. Cette borne
+initiale ne remplace pas un futur renouvellement d'identifiants pour les
+appels longs. Un compte ne peut avoir qu'un appel réservé ou accepté à la
+fois. Le registre est limité à 128 appels et 256 candidats par appel.
+La tranche ne permet qu'une offre initiale de l'appelant et une réponse ;
+les redémarrages ICE et renégociations restent à implémenter.
+
+Configuration serveur, section `AudioVideoCalls` :
+
+- `Enabled` : `false` par défaut, à conserver tant que les moteurs ne sont
+ pas validés ;
+- `StunUrls` : tableau d'URI `stun:` ou `stuns:` ;
+- `TurnUrls` : tableau d'URI `turn:` ou `turns:`, avec transport optionnel ;
+- `TurnSharedSecret` : secret REST coturn, **uniquement côté serveur**,
+ à fournir par le gestionnaire de secrets ou la variable d'environnement
+ `AudioVideoCalls__TurnSharedSecret`, jamais dans le dépôt.
+
+Les credentials TURN temporaires sont calculés côté serveur avec le
+format REST coturn (expiration, nonce aléatoire et HMAC-SHA1). Aucun secret
+de longue durée n'est envoyé aux clients. Aucun service TURN n'a été
+déployé ou configuré par cette tranche.
+
+Le [transport PostIt](../../src/PostIt/PostIt/Services/CallSignalingClient.cs)
+utilise la connexion authentifiée du `ChatViewModel`, sans seconde connexion
+ni interrogation HTTP. Il expose les commandes et événements typés et
+signale les interruptions ; il ne capture aucun média. L'interface ne
+propose pas encore de bouton d'appel ; une éventuelle invitation est
+signalée comme non utilisable faute de moteur natif, sans acceptation
+automatique.
+
+### Travail restant pour la cible Internet multi-plateforme
+
+- Android : l'approche Java/JNI libwebrtc a été écartée à la demande du
+ projet ; aucun adaptateur libwebrtc expérimental n'est conservé.
+ L'adaptateur SRTP LAN réutilise désormais la capture Podcast ; la solution
+ compatible avec la cible Internet reste à choisir.
+- Desktop Linux : le transport SRTP LAN est raccordé, mais ne remplace pas
+ les validations matérielles ni une solution de connectivité Internet.
+- Côté partagé : relier consentement, états réels du moteur, mise en
+ sourdine, arrêt et libération des ressources à la signalisation.
+- Valider un appel Android ↔ Desktop Linux avec caméra avant et microphone
+ réels, rendu et audio distants, VP8/Opus, puis transport TURN sélectionné
+ dans les statistiques, sans repli direct lorsque le masquage est demandé.
+
+Les tests de cette tranche portent sur les contrats, autorisations, courses
+d'acceptation, expirations, limites, interruption et préférence persistée.
+La compilation des applications Android et Desktop ne prouve pas le
+fonctionnement de WebRTC natif : le crash antérieur n'est pas résolu.
+
+## Retour sur l'essai Android du 25 octobre 2026
+
+Le laboratoire indépendant a été supprimé ; il ne constitue pas une base
+de salles de discussion ni une implémentation de PostIt. La suite doit
+réutiliser le ChatHub existant pour la signalisation.
+
+L'essai en échec opposait un téléphone Android 15 arm64 à Chromium,
+en mode TURN uniquement, avec signalisation HTTP locale et TURN/TCP
+accessibles par redirections USB adb. Il n'utilisait ni ChatHub ni
+PostIt.Desktop Linux.
+
+Les observations doivent être distinguées :
+
+- Camera2, la capture audio et un premier rendu EGL local ont démarré.
+ Cela ne valide ni le transport ni le rendu distant.
+- Le processus Android a subi un SIGABRT dans
+ `libjingle_peerconnection_so.so`. Une première pile passait par
+ `PeerConnection.nativeAddIceCandidate` ; après modification du traitement
+ des candidats, un arrêt natif persistait sur `network_thread`.
+- Le test a attendu un échange média qui n'est jamais arrivé. Le dernier
+ rapport Browser indiquait `connection: new`, zéro octet audio/vidéo et
+ aucune paire ICE sélectionnée ; aucun rapport Android n'a validé l'appel.
+- Le problème a été reproduit avec les SDK libwebrtc 150.7871.04 et
+ 144.7559.15. L'attente des descriptions distantes, la résolution du
+ `sdpMid` et l'ajout asynchrone des candidats n'ont pas suffi.
+
+Il s'agit donc d'un **crash natif pendant la tentative d'établissement**,
+pas d'un refus de codec ou d'un échec TURN identifié. Le dernier appel JNI
+visible ne prouve pas la cause du crash. Sans message fatal détaillé ni
+pile native symbolisée, un défaut du code expérimental, de son intégration
+Java/JNI ou de libwebrtc reste à départager. Rien ne démontre une
+impossibilité de WebRTC sur Android ou une défaillance du ChatHub.
+
+Les essais Browser/GStreamer réussis utilisaient des sources synthétiques
+et un décodage sans affichage côté GStreamer : ils ne valident pas
+PostIt.Desktop Linux, ses périphériques réels ou son rendu Avalonia.
+La validation multi-plateforme demeure incomplète.
\ No newline at end of file
diff --git a/doc/testing.md b/doc/testing.md
index fafd89068..7444d3273 100644
--- a/doc/testing.md
+++ b/doc/testing.md
@@ -78,12 +78,15 @@ pour éviter de monter un host complet.
Avec le runner Microsoft.Testing.Platform du depot (.NET 10, xUnit v3) :
```bash
+dotnet test --project src/test/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj \
+ --filter-class '*PodcastWebTests' --filter-class '*PerformerDonationTests'
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj \
--filter-class '*LiveProcessorTests' --filter-class '*PodcastControllerTests' \
- --filter-class '*PodcastReplayTests'
+ --filter-class '*PodcastReplayTests' --filter-class '*PerformerDonationSettingsTests'
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-class '*PodcastTests' --filter-class '*PodcastReplayTests' \
- --filter-class '*YavscApiClientTests' --filter-class '*PodcastNativeCaptureTests'
+ --filter-class '*YavscApiClientTests' --filter-class '*PodcastNativeCaptureTests' \
+ --filter-class '*PerformerDonationSettingsTests'
dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
--filter-method '*Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal'
```
@@ -91,6 +94,9 @@ dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
Les tests serveur couvrent HTTP/authentification, proprietaire, sequences,
reprises idempotentes, limites exactes, concurrence et persistance des replays
apres interruption/redemarrage, dans des dossiers temporaires isoles.
+Les tests de configuration PayPal couvrent la lecture privee, la creation,
+la validation avant toute sauvegarde, l'effacement, la compatibilite des anciens
+clients, ainsi que le chargement, la liaison du champ et l'enregistrement PostIt.
Installer FFmpeg 5+ et ffprobe pour ces tests serveur : ils generent une
source H.264/AAC synthetique de quatre secondes, verifient le remuxage reel
(pistes, duree, faststart, decodage et seek a deux secondes), puis les reponses
diff --git a/dotnet-tools.json b/dotnet-tools.json
index 1762a89de..037b83194 100644
--- a/dotnet-tools.json
+++ b/dotnet-tools.json
@@ -8,6 +8,20 @@
"picket"
],
"rollForward": false
+ },
+ "gitversion.tool": {
+ "version": "6.8.2",
+ "commands": [
+ "dotnet-gitversion"
+ ],
+ "rollForward": false
+ },
+ "dotnet-ef": {
+ "version": "10.0.13",
+ "commands": [
+ "dotnet-ef"
+ ],
+ "rollForward": false
}
}
}
\ No newline at end of file
diff --git a/esbuild.config.mjs b/esbuild.config.mjs
index 7884f601d..4f3edf355 100644
--- a/esbuild.config.mjs
+++ b/esbuild.config.mjs
@@ -48,6 +48,10 @@ const bundleNames = [
// of bootstrap, jquery-ui, etc., which are NOT touched by this
// toolchain).
const staticAssets = [
+ {
+ src: 'node_modules/hls.js/dist/hls.light.min.js',
+ dst: 'hls.light.min.js',
+ },
{
src: 'node_modules/@aspnet/signalr/dist/browser/signalr.min.js',
dst: 'signalr.min.js',
diff --git a/package.json b/package.json
index e419cd0ca..c8d376253 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"description": "Yavsc front-end toolchain (esbuild bundles for Yavsc.Org).",
"scripts": {
"build:js": "node esbuild.config.mjs",
+ "build:podcasts": "node -e \"require('node:fs').copyFileSync('node_modules/hls.js/dist/hls.light.min.js', 'src/Yavsc.Org/wwwroot/js/hls.light.min.js')\"",
"build:js:watch": "node esbuild.config.mjs --watch",
"clean:js": "node esbuild.config.mjs --clean"
},
@@ -13,6 +14,7 @@
"bootstrap": "^4.6.2",
"dropzone": "^5.9.3",
"eonasdan-bootstrap-datetimepicker": "^4.17.49",
+ "hls.js": "1.6.13",
"jquery": "^3.7.1",
"jquery-timepicker": "^1.3.3",
"jquery-ui": "^1.13.3",
diff --git a/src/PostIt/PostIt.Android/PlatformBootstrap.cs b/src/PostIt/PostIt.Android/PlatformBootstrap.cs
index 27efb918d..5b7b30def 100644
--- a/src/PostIt/PostIt.Android/PlatformBootstrap.cs
+++ b/src/PostIt/PostIt.Android/PlatformBootstrap.cs
@@ -24,6 +24,11 @@ internal static class PlatformBootstrap
Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay);
if (System.OperatingSystem.IsAndroidVersionAtLeast(26))
{
+ Platform.GetLanCallDevices = AndroidLanCallMedia.GetDevices;
+ Platform.CreateLanCallMedia = (address, port) =>
+ System.OperatingSystem.IsAndroidVersionAtLeast(26)
+ ? new AndroidLanCallMedia(address, port)
+ : throw new System.PlatformNotSupportedException("Android 8 requis pour les appels LAN.");
Platform.GetPodcastCaptureDevices = AndroidPodcastCapture.GetDevices;
Platform.RequestPodcastPermissionsAsync = AndroidPodcastCapture.RequestPermissionsAsync;
Platform.CreatePodcastCaptureAsync = AndroidPodcastCapture.StartAsync;
diff --git a/src/PostIt/PostIt.Android/PostIt.Android.csproj b/src/PostIt/PostIt.Android/PostIt.Android.csproj
index 5b7f4f968..6cbde4739 100644
--- a/src/PostIt/PostIt.Android/PostIt.Android.csproj
+++ b/src/PostIt/PostIt.Android/PostIt.Android.csproj
@@ -9,10 +9,10 @@
1.0apkfalse
- 1.0.8.0
- 1.0.8.0
- 1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8
- 1.0.8-458
+ 1.1.0.0
+ 1.1.0.0
+ 1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd
+ 1.1.0-feat-calls.1
@@ -32,6 +32,7 @@
+ net10.0enable
- 1.0.8.0
- 1.0.8.0
- 1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8
- 1.0.8-458
+ 1.1.0.0
+ 1.1.0.0
+ 1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd
+ 1.1.0-feat-calls.1app.manifest
diff --git a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs
index 50e64f713..fc733e3f4 100644
--- a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs
+++ b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs
@@ -180,6 +180,60 @@ public class AdministrationAccessTests
Assert.Contains("Impossible de charger mon usage", vm.UsageError);
}
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task My_profile_loads_and_includes_the_call_privacy_preference_in_the_save_payload(bool initial)
+ {
+ await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = initial };
+ var vm = new UserProfilePageViewModel(api);
+ await vm.RefreshAsync();
+ Assert.Equal(initial, vm.HideIpAddressInCalls);
+ vm.HideIpAddressInCalls = !initial;
+ Assert.Equal(!initial, vm.BuildProfileUpdateRequest().HideIpAddressInCalls);
+ Assert.True(vm.SaveProfileCommand.CanExecute(null));
+ Assert.True(vm.IsProfileLoaded);
+ }
+
+ [AvaloniaFact]
+ public async Task My_profile_privacy_checkbox_is_two_way_and_disabled_before_loading()
+ {
+ await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = true };
+ var vm = new UserProfilePageViewModel(api);
+ var page = new UserProfilePage { DataContext = vm };
+ var window = new Window { Content = page };
+ try
+ {
+ window.Show();
+ var checkbox = Assert.Single(page.GetVisualDescendants().OfType(),
+ control => Equals(control.Content, "Masquer mon adresse IP aux autres participants"));
+ Assert.False(checkbox.IsEffectivelyEnabled);
+ await vm.RefreshAsync();
+ Assert.True(checkbox.IsEffectivelyEnabled);
+ Assert.True(checkbox.IsChecked);
+ checkbox.IsChecked = false;
+ Assert.False(vm.HideIpAddressInCalls);
+ Assert.Equal(false, vm.BuildProfileUpdateRequest().HideIpAddressInCalls);
+ vm.IsBusy = true;
+ Assert.False(checkbox.IsEffectivelyEnabled);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [Fact]
+ public async Task Profile_read_failure_prevents_saving_a_default_call_privacy_preference()
+ {
+ await using var api = new ProfileTransport("Performer") { FailProfile = true };
+ var vm = new UserProfilePageViewModel(api);
+ await vm.RefreshAsync();
+ Assert.False(vm.IsProfileLoaded);
+ Assert.False(vm.SaveProfileCommand.CanExecute(null));
+ Assert.Contains("Impossible de charger le profil", vm.StatusMessage);
+ }
+
internal sealed class ProfileTransport : YavscApiClient
{
private readonly string _tokenPath;
@@ -188,6 +242,7 @@ public class AdministrationAccessTests
public Task? PendingProfile { get; set; }
public bool FailProfile { get; set; }
public bool FailUsage { get; set; }
+ public bool HideIpAddressInCalls { get; set; }
public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl);
public ProfileTransport(string role)
@@ -216,7 +271,7 @@ public class AdministrationAccessTests
if (FailProfile)
throw new HttpRequestException("Profile unavailable");
result = PendingProfile is not null ? await PendingProfile
- : new Me { UserId = "alice-id", UserName = "alice", Roles = [_role] };
+ : new Me { UserId = "alice-id", UserName = "alice", Roles = [_role], HideIpAddressInCalls = HideIpAddressInCalls };
}
else if (path.Contains("/resource-usage/"))
{
diff --git a/src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs b/src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs
new file mode 100644
index 000000000..204736434
--- /dev/null
+++ b/src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs
@@ -0,0 +1,158 @@
+#if ANDROID
+using System;
+using Stopwatch = System.Diagnostics.Stopwatch;
+using System.IO;
+using System.IO.Pipes;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Threading;
+using System.Threading.Tasks;
+using Android.App;
+using Android.Content;
+using Android.OS;
+using Avalonia.Controls;
+using Avalonia.Threading;
+using LibVLCSharp.Shared;
+using PostIt.Android;
+using PostIt.Android.Services;
+using PostIt.Services;
+using Path = System.IO.Path;
+
+namespace PostIt.Tests;
+
+/// Debug-only physical camera/SRTP test; no account, API or media recording.
+[Activity(Name = "fr.pschneider.postit.LanCallTestActivity", Exported = true)]
+[SupportedOSPlatform("android26.0")]
+public sealed class AndroidLanCallTestActivity : Activity
+{
+ protected override async void OnCreate(Bundle? state)
+ {
+ base.OnCreate(state);
+ var result = Path.Combine(FilesDir!.AbsolutePath, "lan-call-test-result.txt");
+ File.WriteAllText(result, "RUNNING");
+ try
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(55));
+ var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true", timeout.Token);
+ File.WriteAllText(result, outcome);
+ }
+ catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
+ finally { Finish(); }
+ }
+
+ private async Task RunAsync(string result, bool wrongKey, CancellationToken ct)
+ {
+ StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
+ while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View == null)
+ await Task.Delay(100, ct);
+ await Task.Delay(1000, ct);
+ var fixture = Path.Combine(FilesDir!.AbsolutePath, "lan-call-fixture.ts");
+ if (!File.Exists(fixture)) throw new IOException("Explicit H.264/AAC MPEG-TS fixture required.");
+ using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
+ await using var peer = new LibVlcLanCallMedia("127.0.0.1", 35102, headless: true);
+ using var decoded = new DecodedFrames(peer.Receiver);
+ AndroidLanCallMedia? call = null;
+ Task? pump = null;
+ using var sending = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ var source = File.OpenRead(fixture);
+ var app = (App)Avalonia.Application.Current!;
+ var navigation = app.View!.FindControl("NavRoot")
+ ?? throw new InvalidOperationException("Main navigation unavailable.");
+ var attached = false;
+ try
+ {
+ await peer.StartReceivingAsync(ct);
+ await Dispatcher.UIThread.InvokeAsync(async () =>
+ {
+ call = new AndroidLanCallMedia("127.0.0.1", 35100);
+ var grid = new Grid { RowDefinitions = new RowDefinitions("*,*") };
+ grid.Children.Add(call.LocalVideo);
+ Grid.SetRow(call.RemoteVideo, 1);
+ grid.Children.Add(call.RemoteVideo);
+ await navigation.PushAsync(new ContentPage { Content = grid });
+ attached = true;
+ });
+ if (call == null) throw new InvalidOperationException("Call UI not created.");
+ File.WriteAllText(result, "RUNNING\nstage=return source pump");
+ pump = Task.Run(async () =>
+ {
+ var buffer = new byte[1316];
+ while (await source.ReadAsync(buffer, sending.Token) is var count && count > 0)
+ {
+ await pipe.WriteAsync(buffer.AsMemory(0, count), sending.Token);
+ await Task.Delay(4, sending.Token);
+ }
+ }, ct);
+ File.WriteAllText(result, "RUNNING\nstage=return SRTP sender");
+ await peer.StartEncodedSendingAsync(call.Endpoint,
+ pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
+ File.WriteAllText(result, "RUNNING\nstage=enumerating cameras");
+ var devices = AndroidLanCallMedia.GetDevices();
+ var front = devices.Cameras.FirstOrDefault(c => c.Name == "Camera avant")
+ ?? throw new InvalidOperationException("Front camera required; no rear-camera fallback.");
+ var endpoint = wrongKey ? peer.Endpoint with { Key = new string('0', 32) } : peer.Endpoint;
+ File.WriteAllText(result, "RUNNING\nstage=front camera and SRTP");
+ await Dispatcher.UIThread.InvokeAsync(() => call.StartSendingAsync(endpoint, front.Value, "microphone", ct));
+ File.WriteAllText(result, "RUNNING\nstage=receiving camera and return media");
+ var elapsed = Stopwatch.StartNew();
+ while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 10 : 25))
+ {
+ if (call.Completion.IsCompleted) await call.Completion;
+ if (peer.Completion.IsCompleted) await peer.Completion;
+ if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(10) &&
+ decoded.Frames >= 100 && decoded.Samples > 144000 && call.HasRemoteMedia) break;
+ await Task.Delay(100, ct);
+ }
+ if (!call.HasRemoteMedia) throw new IOException("Android did not decode return audio/video.");
+ if (wrongKey ? decoded.Frames != 0 || decoded.Samples != 0
+ : decoded.Frames < 100 || decoded.Samples <= 144000)
+ throw new IOException($"Unexpected camera decode: frames={decoded.Frames}, samples={decoded.Samples}.");
+ return $"PASS\nfrontCamera=true\nwrongKey={wrongKey}\n" +
+ $"cameraFrames={decoded.Frames}\ncameraAudioSamples={decoded.Samples}\nelapsedMs={elapsed.ElapsedMilliseconds}\nreturnAudioVideo=true\n" +
+ "transport=SRTP/UDP loopback\npreview=attached\nsource=camera+microphone,return=explicit fixture\ncleanup=complete";
+ }
+ finally
+ {
+ sending.Cancel();
+ File.WriteAllText(result, "RUNNING\nstage=stop return source");
+ if (pump != null)
+ {
+ try { await pump; }
+ catch (System.OperationCanceledException) when (sending.IsCancellationRequested) { }
+ }
+ File.WriteAllText(result, "RUNNING\nstage=dispose call");
+ if (call != null) await Dispatcher.UIThread.InvokeAsync(async () => await call.DisposeAsync());
+ File.WriteAllText(result, "RUNNING\nstage=stop return peer");
+ await peer.StopAsync();
+ source.Dispose();
+ File.WriteAllText(result, "RUNNING\nstage=detach test page");
+ if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
+ }
+ }
+
+ private sealed class DecodedFrames : IDisposable
+ {
+ private readonly MediaPlayer _player;
+ private readonly IntPtr _buffer = Marshal.AllocHGlobal(640 * 640 * 4);
+ private int _frames;
+ private long _samples;
+ public int Frames => Volatile.Read(ref _frames);
+ public long Samples => Interlocked.Read(ref _samples);
+ public DecodedFrames(MediaPlayer player)
+ {
+ _player = player;
+ player.SetVideoFormat("RV32", 640, 640, 640 * 4);
+ player.SetVideoCallbacks((_, planes) =>
+ {
+ Marshal.WriteIntPtr(planes, _buffer);
+ return IntPtr.Zero;
+ }, null, (_, _) => Interlocked.Increment(ref _frames));
+ player.SetAudioFormat("S16N", 48000, 1);
+ player.SetAudioCallbacks((_, _, count, _) => Interlocked.Add(ref _samples, count),
+ null, null, null, null);
+ }
+ public void Dispose() { _player.Stop(); Marshal.FreeHGlobal(_buffer); }
+ }
+}
+#endif
diff --git a/src/PostIt/PostIt.Tests/BlogReaderTests.cs b/src/PostIt/PostIt.Tests/BlogReaderTests.cs
index d8e340878..d07cf7a30 100644
--- a/src/PostIt/PostIt.Tests/BlogReaderTests.cs
+++ b/src/PostIt/PostIt.Tests/BlogReaderTests.cs
@@ -82,6 +82,29 @@ public class BlogReaderTests
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
}
+ [Theory]
+ [InlineData("https://org.example.test/files/paul/clip.mp4", true)]
+ [InlineData("https://localhost/files/paul/clip.mp4", false)]
+ public void Video_links_only_open_externally_when_the_source_is_a_real_external_resource(string source, bool expected)
+ {
+ var vm = new VideoPageViewModel(new Uri(source), "video/mp4");
+ Assert.Equal(expected, vm.CanOpenExternal);
+ Assert.Equal(vm.Source, vm.ExternalUri);
+ }
+
+ [Theory]
+ [InlineData("https://org.example.test/Podcast", true)]
+ [InlineData("about:blank", false)]
+ public void Video_external_action_uses_the_web_resource_instead_of_the_playback_stream(string externalUrl, bool expected)
+ {
+ var source = new Uri("https://api.example.test/api/v1/podcasts/123/index.m3u8");
+ var externalUri = new Uri(externalUrl);
+ var vm = new VideoPageViewModel(source, "application/vnd.apple.mpegurl", externalUri);
+ Assert.Equal(source, vm.Source);
+ Assert.Equal(externalUri, vm.ExternalUri);
+ Assert.Equal(expected, vm.CanOpenExternal);
+ }
+
[AvaloniaFact]
public async Task Reader_hides_editor_and_wires_hyperlinks_to_the_application()
{
diff --git a/src/PostIt/PostIt.Tests/CallSignalingClientTests.cs b/src/PostIt/PostIt.Tests/CallSignalingClientTests.cs
new file mode 100644
index 000000000..c3f7945cb
--- /dev/null
+++ b/src/PostIt/PostIt.Tests/CallSignalingClientTests.cs
@@ -0,0 +1,60 @@
+using System.Text.Json;
+using Microsoft.AspNetCore.SignalR.Client;
+using PostIt.Services;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Tests;
+
+public sealed class CallSignalingClientTests
+{
+ [Fact]
+ public async Task All_operations_fail_explicitly_without_a_connected_chat_transport()
+ {
+ await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
+ using var client = new CallSignalingClient(connection);
+ var id = Guid.NewGuid();
+ var ct = TestContext.Current.CancellationToken;
+ await Assert.ThrowsAsync(() => client.InviteAsync("General", "bob", ct));
+ await Assert.ThrowsAsync(() => client.InviteLanAsync("General", "bob", ct));
+ await Assert.ThrowsAsync(() => client.AcceptAsync(id, ct));
+ await Assert.ThrowsAsync(() => client.EndAsync(id, ct));
+ await Assert.ThrowsAsync(() => client.SendAsync(id, new("offer", "sdp"), ct));
+ }
+
+ [Fact]
+ public async Task Disposing_call_subscriptions_does_not_dispose_the_chat_connection()
+ {
+ await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
+ var client = new CallSignalingClient(connection);
+ client.Dispose();
+ client.Dispose();
+ await Assert.ThrowsAsync(() => client.AcceptAsync(Guid.NewGuid(), TestContext.Current.CancellationToken));
+ Assert.Equal(HubConnectionState.Disconnected, connection.State);
+ using var replacement = new CallSignalingClient(connection);
+ await Assert.ThrowsAsync(() => replacement.InviteAsync("General", "bob", TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public void Shared_contracts_round_trip_with_signalr_web_json_naming()
+ {
+ var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
+ var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", true,
+ DateTimeOffset.Parse("2026-10-26T01:00:00Z"));
+ var ready = new CallAccepted(call, [new(["turns:turn.example.test:5349"], "expires:nonce", "credential")]);
+ var json = JsonSerializer.Serialize(ready, options);
+ var read = JsonSerializer.Deserialize(json, options);
+ Assert.NotNull(read);
+ Assert.Equal(call, read.Session);
+ Assert.Equal(ready.IceServers[0].Urls, read.IceServers[0].Urls);
+ Assert.Equal(ready.IceServers[0].Username, read.IceServers[0].Username);
+ Assert.Equal(ready.IceServers[0].Credential, read.IceServers[0].Credential);
+ var signal = new CallSignal("candidate", Candidate: "candidate:1 1 udp 100 192.0.2.1 5000 typ relay",
+ SdpMid: "video", SdpMLineIndex: 1);
+ Assert.Equal(signal, JsonSerializer.Deserialize(JsonSerializer.Serialize(signal, options), options));
+ var lan = call with { RelayOnly = false, Transport = CallTransports.LanSrtp };
+ Assert.Equal(lan, JsonSerializer.Deserialize(JsonSerializer.Serialize(lan, options), options));
+ var endpoint = new CallSignal("rtp-endpoint",
+ Endpoint: new("192.168.1.2", 5004, new string('a', 32), new string('b', 28)));
+ Assert.Equal(endpoint, JsonSerializer.Deserialize(JsonSerializer.Serialize(endpoint, options), options));
+ }
+}
diff --git a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs
new file mode 100644
index 000000000..6afe892a2
--- /dev/null
+++ b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs
@@ -0,0 +1,243 @@
+using Avalonia.Controls;
+using Avalonia.Headless.XUnit;
+using PostIt.Services;
+using PostIt.ViewModels.Chat;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Tests;
+
+public sealed class LanCallViewModelTests
+{
+ private static CallSession Session() => new(Guid.NewGuid(), "General", "alice", "bob", false,
+ DateTimeOffset.UtcNow.AddMinutes(1), CallTransports.LanSrtp);
+
+ private static LanCallViewModel Configure(Signaling signaling, Func create)
+ {
+ var vm = new LanCallViewModel(signaling, create)
+ {
+ Address = "127.0.0.1", Camera = new("Camera", "/dev/video0"),
+ Microphone = new("Micro", "default"), AllowAddressDisclosure = true,
+ Room = "General", Target = "bob"
+ };
+ vm.Addresses.Add("127.0.0.1");
+ return vm;
+ }
+
+ [AvaloniaFact]
+ public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange()
+ {
+ var signaling = new Signaling();
+ var media = new FakeMedia();
+ var created = 0;
+ await using var vm = Configure(signaling, (_, _) => { created++; return media; });
+ signaling.Invite(vm, signaling.Call);
+ await WaitAsync(() => vm.Incoming);
+ Assert.Equal(0, created);
+ Assert.Empty(signaling.Sent);
+ await vm.AcceptCommand.ExecuteAsync(null);
+ await WaitAsync(() => vm.LocalVideo != null);
+ Assert.Equal(1, created);
+ Assert.False(media.Sending);
+ Assert.Single(signaling.Sent);
+ Assert.Equal("rtp-endpoint", signaling.Sent[0].Kind);
+ signaling.RemoteEndpoint(signaling.Call.Id);
+ await WaitAsync(() => media.Sending);
+ Assert.Same(media.LocalVideo, vm.LocalVideo);
+ Assert.Same(media.RemoteVideo, vm.RemoteVideo);
+ await vm.HangupAsync();
+ Assert.True(media.Disposed);
+ Assert.False(vm.Busy);
+ Assert.Null(vm.LocalVideo);
+ Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
+ }
+
+ [AvaloniaFact]
+ public async Task Caller_waits_for_consent_and_interruption_releases_media_without_reconnecting()
+ {
+ var signaling = new Signaling();
+ var media = new FakeMedia();
+ var created = 0;
+ await using var vm = Configure(signaling, (_, _) => { created++; return media; });
+ await vm.InviteCommand.ExecuteAsync(null);
+ Assert.True(vm.Busy);
+ Assert.Equal(0, created);
+ signaling.Ready();
+ await WaitAsync(() => vm.LocalVideo != null);
+ signaling.RemoteEndpoint(signaling.Call.Id);
+ await WaitAsync(() => media.Sending);
+ signaling.Disconnect();
+ await WaitAsync(() => media.Disposed);
+ Assert.False(vm.Busy);
+ Assert.Null(vm.RemoteVideo);
+ Assert.Contains("interrompue", vm.Status);
+ }
+
+ [AvaloniaFact]
+ public async Task Missing_disclosure_consent_or_devices_blocks_the_invitation()
+ {
+ var signaling = new Signaling();
+ await using var vm = Configure(signaling, (_, _) => throw new Exception("Must not capture"));
+ vm.AllowAddressDisclosure = false;
+ await vm.InviteCommand.ExecuteAsync(null);
+ Assert.Equal(0, signaling.Invites);
+ Assert.Contains("Confirmez", vm.Status);
+ vm.AllowAddressDisclosure = true;
+ vm.Camera = null;
+ await vm.InviteCommand.ExecuteAsync(null);
+ Assert.Equal(0, signaling.Invites);
+ Assert.Contains("camera", vm.Status);
+ Assert.False(vm.Busy);
+ }
+
+ [AvaloniaFact]
+ public async Task Refusal_never_creates_media_and_late_signals_cannot_restart_capture()
+ {
+ var signaling = new Signaling();
+ var created = 0;
+ await using var vm = Configure(signaling, (_, _) => { created++; return new FakeMedia(); });
+ signaling.Invite(vm, signaling.Call);
+ await WaitAsync(() => vm.Incoming);
+ await vm.HangupAsync();
+ signaling.Ready();
+ signaling.RemoteEndpoint(signaling.Call.Id);
+ await Task.Delay(30, TestContext.Current.CancellationToken);
+ Assert.Equal(0, created);
+ Assert.False(vm.Busy);
+ }
+
+ [AvaloniaFact]
+ public async Task Platform_devices_and_factory_are_used_and_backgrounding_ends_capture()
+ {
+ var previousDevices = Platform.GetLanCallDevices;
+ var previousFactory = Platform.CreateLanCallMedia;
+ var signaling = new Signaling();
+ var media = new FakeMedia();
+ var creations = 0;
+ try
+ {
+ Platform.GetLanCallDevices = () => new(
+ [new("Camera avant", "front"), new("Camera arriere", "rear")],
+ [new("Sans microphone", ""), new("Microphone Android", "microphone")]);
+ Platform.CreateLanCallMedia = (_, _) => { creations++; return media; };
+ await using var vm = new LanCallViewModel(signaling);
+ vm.RefreshDevicesCommand.Execute(null);
+ Assert.Equal("front", vm.Camera?.Value);
+ Assert.Equal("microphone", vm.Microphone?.Value);
+ Assert.Single(vm.Microphones);
+ Assert.Equal(0, creations);
+ signaling.Invite(vm, signaling.Call);
+ await WaitAsync(() => vm.Incoming);
+ Assert.True(vm.CanConfigure);
+ vm.RefreshDevicesCommand.Execute(null);
+ Assert.Equal("front", vm.Camera?.Value);
+ vm.Address = "127.0.0.1";
+ if (!vm.Addresses.Contains(vm.Address)) vm.Addresses.Add(vm.Address);
+ vm.AllowAddressDisclosure = true;
+ vm.Room = "General";
+ vm.Target = "bob";
+ await vm.AcceptCommand.ExecuteAsync(null);
+ await WaitAsync(() => vm.LocalVideo != null);
+ Assert.Equal(1, creations);
+ Assert.False(vm.CanConfigure);
+ signaling.RemoteEndpoint(signaling.Call.Id);
+ await WaitAsync(() => media.Sending);
+ Platform.SuspendPlayback();
+ await WaitAsync(() => media.Disposed);
+ Assert.False(vm.Busy);
+ Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
+ Platform.ResumePlayback();
+ await Task.Delay(30, TestContext.Current.CancellationToken);
+ Assert.Equal(1, creations);
+ }
+ finally
+ {
+ Platform.GetLanCallDevices = previousDevices;
+ Platform.CreateLanCallMedia = previousFactory;
+ }
+ }
+
+ [AvaloniaFact]
+ public async Task Hangup_cancels_pending_native_start_without_waiting_for_startup_timeout()
+ {
+ var signaling = new Signaling();
+ var media = new FakeMedia { DelayStartup = true };
+ await using var vm = Configure(signaling, (_, _) => media);
+ await vm.InviteCommand.ExecuteAsync(null);
+ signaling.Ready();
+ await WaitAsync(() => vm.LocalVideo != null);
+ signaling.RemoteEndpoint(signaling.Call.Id);
+ await WaitAsync(() => media.Sending);
+ await vm.HangupAsync().WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
+ Assert.True(media.Disposed);
+ Assert.False(vm.Busy);
+ Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
+ }
+
+ [AvaloniaFact]
+ public async Task Media_failure_ends_the_call_and_disposes_capture()
+ {
+ var signaling = new Signaling();
+ var media = new FakeMedia();
+ await using var vm = Configure(signaling, (_, _) => media);
+ await vm.InviteCommand.ExecuteAsync(null);
+ signaling.Ready();
+ await WaitAsync(() => vm.LocalVideo != null);
+ media.Fail();
+ await WaitAsync(() => media.Disposed);
+ Assert.False(vm.Busy);
+ Assert.Contains("test media failure", vm.Status);
+ Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
+ }
+
+ private static async Task WaitAsync(Func condition)
+ {
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
+ timeout.CancelAfter(TimeSpan.FromSeconds(5));
+ while (!condition()) await Task.Delay(10, timeout.Token);
+ }
+
+ private sealed class FakeMedia : ILanCallMedia
+ {
+ private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public Control LocalVideo { get; } = new Border();
+ public Control RemoteVideo { get; } = new Border();
+ public LanCallEndpoint Endpoint { get; } = new("127.0.0.1", 5004, new string('a', 32), new string('b', 28));
+ public Task Completion => _completion.Task;
+ public bool HasRemoteMedia => false;
+ public bool Sending { get; private set; }
+ public bool Disposed { get; private set; }
+ public bool DelayStartup { get; init; }
+ public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
+ {
+ Sending = true;
+ if (DelayStartup) await Task.Delay(Timeout.Infinite, ct);
+ }
+ public void Fail() => _completion.TrySetException(new IOException("test media failure"));
+ public ValueTask DisposeAsync() { Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
+ }
+
+ private sealed class Signaling : ILanCallSignaling
+ {
+ public event Action? Invitation;
+ public event Action? Accepted;
+ public event Action? Ended;
+ public event Action? Signal;
+ public event Action? Interrupted;
+ public CallSession Call { get; } = Session();
+ public List Sent { get; } = [];
+ public List EndedCalls { get; } = [];
+ public int Invites { get; private set; }
+ public Task InviteLanAsync(string room, string user, CancellationToken ct = default)
+ { Invites++; return Task.FromResult(Call); }
+ public Task AcceptAsync(Guid id, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
+ public Task EndAsync(Guid id, CancellationToken ct = default)
+ { EndedCalls.Add(id); Ended?.Invoke(new(id, "hangup")); return Task.CompletedTask; }
+ public Task SendAsync(Guid id, CallSignal signal, CancellationToken ct = default)
+ { Sent.Add(signal); return Task.CompletedTask; }
+ public void Invite(LanCallViewModel _, CallSession call) => Invitation?.Invoke(call);
+ public void Ready() => Accepted?.Invoke(new(Call, []));
+ public void RemoteEndpoint(Guid id) => Signal?.Invoke(id, new("rtp-endpoint",
+ Endpoint: new("127.0.0.1", 5006, new string('c', 32), new string('d', 28))));
+ public void Disconnect() => Interrupted?.Invoke();
+ }
+}
diff --git a/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs b/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs
new file mode 100644
index 000000000..f473dc40c
--- /dev/null
+++ b/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs
@@ -0,0 +1,190 @@
+using System.Diagnostics;
+using System.Net;
+using System.Net.Sockets;
+using System.IO.Pipes;
+using System.Runtime.InteropServices;
+using LibVLCSharp.Shared;
+using PostIt.Services;
+
+namespace PostIt.Tests;
+
+public sealed class LinuxLanCallMediaTests(ITestOutputHelper output)
+{
+ public static bool HasFixture => OperatingSystem.IsLinux() &&
+ File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
+ public static bool HasTsFixture => OperatingSystem.IsLinux() &&
+ File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_TS"));
+
+ [Fact(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
+ public async Task Ports_are_released_and_credentials_regenerated_after_disposal()
+ {
+ var port = FreePort();
+ var first = new LibVlcLanCallMedia("127.0.0.1", port, headless: true);
+ var endpoint = first.Endpoint;
+ await first.StartReceivingAsync(TestContext.Current.CancellationToken);
+ await first.DisposeAsync();
+ await first.DisposeAsync();
+ await using var next = new LibVlcLanCallMedia("127.0.0.1", port, headless: true);
+ Assert.NotEqual(endpoint.Key, next.Endpoint.Key);
+ Assert.NotEqual(endpoint.Salt, next.Endpoint.Salt);
+ await next.StartReceivingAsync(TestContext.Current.CancellationToken);
+ }
+
+ [Fact(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
+ public void Occupied_rtcp_port_is_rejected_before_capture_starts()
+ {
+ var port = FreePort();
+ using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ socket.Bind(new IPEndPoint(IPAddress.Loopback, port + 1));
+ var error = Assert.Throws(() => new LibVlcLanCallMedia("127.0.0.1", port, headless: true));
+ Assert.Equal(SocketError.AddressAlreadyInUse, error.SocketErrorCode);
+ }
+
+ [Fact(Skip = "Set POSTIT_TEST_TS to an H.264/AAC MPEG-TS file.", SkipUnless = nameof(HasTsFixture))]
+ public async Task Already_encoded_capture_is_sent_over_srtp_without_transcoding()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var firstPort = FreePort();
+ await using var sender = new LibVlcLanCallMedia("127.0.0.1", firstPort, headless: true);
+ await using var receiver = new LibVlcLanCallMedia("127.0.0.1", FreePort(firstPort), headless: true);
+ using var decoded = new DecodedVideo(receiver.Receiver);
+ using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
+ await using var source = File.OpenRead(Environment.GetEnvironmentVariable("POSTIT_TEST_TS")!);
+ await receiver.StartReceivingAsync(ct);
+ using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ var pump = Task.Run(async () =>
+ {
+ var buffer = new byte[1316];
+ while (await source.ReadAsync(buffer, lifetime.Token) is var count && count > 0)
+ {
+ await pipe.WriteAsync(buffer.AsMemory(0, count), lifetime.Token);
+ await Task.Delay(4, lifetime.Token);
+ }
+ }, ct);
+ try
+ {
+ await sender.StartEncodedSendingAsync(receiver.Endpoint,
+ pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
+ var elapsed = Stopwatch.StartNew();
+ while (!HasMedia(receiver, decoded) && elapsed.Elapsed < TimeSpan.FromSeconds(20))
+ {
+ if (sender.Completion.IsCompleted) await sender.Completion;
+ if (receiver.Completion.IsCompleted) await receiver.Completion;
+ await Task.Delay(100, ct);
+ }
+ Assert.True(HasMedia(receiver, decoded));
+ }
+ finally
+ {
+ lifetime.Cancel();
+ try { await pump; }
+ catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
+ await sender.StopAsync();
+ }
+ }
+
+ [Theory(Skip = "Set POSTIT_TEST_MEDIA to an audio/video file; requires Linux LibVLC SRTP and H.264/AAC encoders.",
+ SkipUnless = nameof(HasFixture))]
+ [InlineData(false, false)]
+ [InlineData(true, false)]
+ [InlineData(false, true)]
+ public async Task Two_peers_decode_bidirectional_encrypted_audio_video_and_reject_wrong_keys(bool wrongKey, bool preview)
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var firstPort = FreePort();
+ var secondPort = FreePort(firstPort);
+ await using var first = new LibVlcLanCallMedia("127.0.0.1", firstPort, headless: true);
+ await using var second = new LibVlcLanCallMedia("127.0.0.1", secondPort, headless: true);
+ using var firstVideo = new DecodedVideo(first.Receiver);
+ using var secondVideo = new DecodedVideo(second.Receiver);
+ await first.StartReceivingAsync(ct);
+ await second.StartReceivingAsync(ct);
+ await Task.Delay(300, ct);
+ Media Source(LibVLC vlc)
+ {
+ var media = new Media(vlc, new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA")!)));
+ media.AddOption(":input-repeat=5");
+ return media;
+ }
+ await first.StartSendingAsync(wrongKey ? second.Endpoint with { Key = new string('0', 32) } : second.Endpoint,
+ Source, preview, ct);
+ await second.StartSendingAsync(first.Endpoint, Source, preview, ct);
+ var elapsed = Stopwatch.StartNew();
+ while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 8 : 20))
+ {
+ if (first.Completion.IsCompleted) await first.Completion;
+ if (second.Completion.IsCompleted) await second.Completion;
+ if (!wrongKey && HasMedia(first, firstVideo) && HasMedia(second, secondVideo) &&
+ first.HasRemoteMedia && second.HasRemoteMedia) break;
+ await Task.Delay(100, ct);
+ }
+ var a = first.Statistics;
+ var b = second.Statistics;
+ output.WriteLine($"A: audioSamples={firstVideo.AudioSamples}, rendered={firstVideo.Frames}; " +
+ $"B: audioSamples={secondVideo.AudioSamples}, rendered={secondVideo.Frames}; elapsed={elapsed.ElapsedMilliseconds}ms");
+ Assert.True(HasMedia(first, firstVideo), "First peer must decode received audio and video.");
+ Assert.True(first.HasRemoteMedia, "The UI must detect initial audio/video reception.");
+ if (wrongKey)
+ {
+ Assert.Equal(0, b.DecodedVideo);
+ Assert.Equal(0, b.DecodedAudio);
+ Assert.Equal(0, secondVideo.Frames);
+ Assert.Equal(0, secondVideo.AudioSamples);
+ Assert.False(second.HasRemoteMedia);
+ }
+ else
+ {
+ Assert.True(HasMedia(second, secondVideo), "Second peer must decode received audio and video.");
+ Assert.True(second.HasRemoteMedia);
+ }
+ }
+
+ private static bool HasMedia(LibVlcLanCallMedia peer, DecodedVideo video) =>
+ peer.Statistics.DecodedAudio > 0 && video.AudioSamples > 4800 && video.Frames >= 10;
+
+ private static int FreePort(int except = 0)
+ {
+ for (var port = 32000; port < 60000; port += 2)
+ {
+ if (port == except) continue;
+ using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ using var rtcp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ try
+ {
+ socket.Bind(new IPEndPoint(IPAddress.Loopback, port));
+ rtcp.Bind(new IPEndPoint(IPAddress.Loopback, port + 1));
+ return port;
+ }
+ catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse) { }
+ }
+ throw new IOException("No free RTP port available.");
+ }
+
+ private sealed class DecodedVideo : IDisposable
+ {
+ private readonly IntPtr _pixels = Marshal.AllocHGlobal(640 * 480 * 4);
+ private int _frames;
+ private long _audioSamples;
+ public int Frames => Volatile.Read(ref _frames);
+ public long AudioSamples => Interlocked.Read(ref _audioSamples);
+ private readonly MediaPlayer _player;
+ public DecodedVideo(MediaPlayer player)
+ {
+ _player = player;
+ player.SetAudioFormat("S16N", 48000, 1);
+ player.SetAudioCallbacks((_, _, count, _) => Interlocked.Add(ref _audioSamples, count),
+ null, null, null, null);
+ player.SetVideoFormat("RV32", 640, 480, 640 * 4);
+ player.SetVideoCallbacks((_, planes) =>
+ {
+ Marshal.WriteIntPtr(planes, _pixels);
+ return IntPtr.Zero;
+ }, null, (_, _) => Interlocked.Increment(ref _frames));
+ }
+ public void Dispose()
+ {
+ _player.Stop();
+ Marshal.FreeHGlobal(_pixels);
+ }
+ }
+}
diff --git a/src/PostIt/PostIt.Tests/PerformerDonationSettingsTests.cs b/src/PostIt/PostIt.Tests/PerformerDonationSettingsTests.cs
new file mode 100644
index 000000000..3078e401d
--- /dev/null
+++ b/src/PostIt/PostIt.Tests/PerformerDonationSettingsTests.cs
@@ -0,0 +1,72 @@
+using Avalonia.Controls;
+using Avalonia.Headless.XUnit;
+using PostIt.Services;
+using PostIt.ViewModels;
+using PostIt.Views;
+using Yavsc.Abstract.Workflow;
+using Yavsc.Api.Client;
+
+namespace PostIt.Tests;
+
+public sealed class PerformerDonationSettingsTests
+{
+ [Theory]
+ [InlineData("performer@payments.example", "performer@payments.example")]
+ [InlineData(" performer@payments.example ", "performer@payments.example")]
+ [InlineData("", "")]
+ public void Performer_editor_includes_the_paypal_recipient_in_the_save_payload(string value, string expected)
+ {
+ var vm = new PerformerConfigurationPageViewModel { DonationPayPalEmail = value };
+ Assert.Equal(expected, vm.BuildPerformerProfileSettings().DonationPayPalEmail);
+ }
+
+ [AvaloniaFact]
+ public async Task Performer_editor_loads_displays_edits_and_saves_the_private_recipient()
+ {
+ var tokenPath = Path.Combine(Path.GetTempPath(), "postit-donation-" + Guid.NewGuid().ToString("N") + ".json");
+ try
+ {
+ await using var api = new PerformerApi(tokenPath);
+ var vm = new PerformerConfigurationPageViewModel(api, new ActivityApiClient(api, api.Settings.ApiUrl));
+ await vm.RefreshAsync();
+ Assert.Equal("initial@payments.example", vm.DonationPayPalEmail);
+ var page = new PerformerConfigurationPage { DataContext = vm };
+ var input = page.FindControl("DonationPayPalEmailInput")!;
+ Assert.Equal("initial@payments.example", input.Text);
+ input.Text = "updated@payments.example";
+ Assert.Equal("updated@payments.example", vm.DonationPayPalEmail);
+ await vm.SaveAsync();
+ Assert.Equal("updated@payments.example", api.Saved?.DonationPayPalEmail);
+ input.Text = "";
+ await vm.SaveAsync();
+ Assert.Equal("", api.Saved?.DonationPayPalEmail);
+ }
+ finally
+ {
+ if (File.Exists(tokenPath)) File.Delete(tokenPath);
+ }
+ }
+
+ private sealed class PerformerApi(string tokenPath) : YavscApiClient(new Settings
+ {
+ Authentication = new AuthenticationSettings
+ {
+ Authority = "https://org.example.test", ClientId = "postit", Scopes = ["openid", "api"]
+ }
+ }, new TokenStore(tokenPath))
+ {
+ public PerformerProfileSettings? Saved { get; private set; }
+
+ public override Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
+ {
+ if (typeof(T) == typeof(List))
+ return Task.FromResult((T)(object)new List());
+ Assert.EndsWith("/account/performer-profile", path);
+ if (method == HttpMethod.Put) Saved = Assert.IsType(body);
+ return Task.FromResult((T)(object)new PerformerProfileSettings
+ {
+ PerformerId = "author", DonationPayPalEmail = "initial@payments.example"
+ });
+ }
+ }
+}
diff --git a/src/PostIt/PostIt.Tests/PostIt.Tests.csproj b/src/PostIt/PostIt.Tests/PostIt.Tests.csproj
index f710f7319..66b2522b5 100644
--- a/src/PostIt/PostIt.Tests/PostIt.Tests.csproj
+++ b/src/PostIt/PostIt.Tests/PostIt.Tests.csproj
@@ -6,10 +6,10 @@
falsePostIt.Teststrue
- 1.0.8.0
- 1.0.8.0
- 1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8
- 1.0.8-458
+ 1.1.0.0
+ 1.1.0.0
+ 1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd
+ 1.1.0-feat-calls.1
diff --git a/src/PostIt/PostIt/PostIt.csproj b/src/PostIt/PostIt/PostIt.csproj
index 9d4c7e963..e84006554 100644
--- a/src/PostIt/PostIt/PostIt.csproj
+++ b/src/PostIt/PostIt/PostIt.csproj
@@ -3,10 +3,10 @@
net10.0enablelatest
- 1.0.8.0
- 1.0.8.0
- 1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8
- 1.0.8-458
+ 1.1.0.0
+ 1.1.0.0
+ 1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd
+ 1.1.0-feat-calls.1true
diff --git a/src/PostIt/PostIt/Services/CallSignalingClient.cs b/src/PostIt/PostIt/Services/CallSignalingClient.cs
new file mode 100644
index 000000000..7ad171d3b
--- /dev/null
+++ b/src/PostIt/PostIt/Services/CallSignalingClient.cs
@@ -0,0 +1,87 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.SignalR.Client;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Services;
+
+public sealed class CallSignalingClient : ILanCallSignaling, IDisposable
+{
+ private readonly HubConnection _connection;
+ private readonly IDisposable[] _subscriptions;
+ private bool _disposed;
+
+ public event Action? Invitation;
+ public event Action? Accepted;
+ public event Action? Ended;
+ public event Action? Signal;
+ public event Action? Interrupted;
+
+ public CallSignalingClient(HubConnection connection)
+ {
+ _connection = connection;
+ _subscriptions =
+ [
+ connection.On(CallHubMethods.Invitation, call => Invitation?.Invoke(call)),
+ connection.On(CallHubMethods.Accepted, call => Accepted?.Invoke(call)),
+ connection.On(CallHubMethods.Ended, call => Ended?.Invoke(call)),
+ connection.On(CallHubMethods.SignalReceived,
+ (id, signal) => Signal?.Invoke(id, signal))
+ ];
+ connection.Reconnecting += OnInterruptedAsync;
+ connection.Closed += OnInterruptedAsync;
+ }
+
+ public Task InviteAsync(string room, string user, CancellationToken ct = default)
+ {
+ EnsureConnected();
+ return _connection.InvokeAsync(CallHubMethods.Invite, room, user, ct);
+ }
+
+ public Task InviteLanAsync(string room, string user, CancellationToken ct = default)
+ {
+ EnsureConnected();
+ return _connection.InvokeAsync(CallHubMethods.InviteLan, room, user, ct);
+ }
+
+ public Task AcceptAsync(Guid callId, CancellationToken ct = default)
+ {
+ EnsureConnected();
+ return _connection.InvokeAsync(CallHubMethods.Accept, callId, ct);
+ }
+
+ public Task EndAsync(Guid callId, CancellationToken ct = default)
+ {
+ EnsureConnected();
+ return _connection.InvokeAsync(CallHubMethods.End, callId, ct);
+ }
+
+ public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
+ {
+ EnsureConnected();
+ return _connection.InvokeAsync(CallHubMethods.Signal, callId, signal, ct);
+ }
+
+ private Task OnInterruptedAsync(Exception? error)
+ {
+ Interrupted?.Invoke();
+ return Task.CompletedTask;
+ }
+
+ private void EnsureConnected()
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ if (_connection.State != HubConnectionState.Connected)
+ throw new InvalidOperationException("La connexion de chat est interrompue ; l'appel ne peut pas continuer.");
+ }
+
+ public void Dispose()
+ {
+ if (_disposed) return;
+ _disposed = true;
+ _connection.Reconnecting -= OnInterruptedAsync;
+ _connection.Closed -= OnInterruptedAsync;
+ foreach (var subscription in _subscriptions) subscription.Dispose();
+ }
+}
diff --git a/src/PostIt/PostIt/Services/ILanCallMedia.cs b/src/PostIt/PostIt/Services/ILanCallMedia.cs
new file mode 100644
index 000000000..30ff98959
--- /dev/null
+++ b/src/PostIt/PostIt/Services/ILanCallMedia.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Services;
+
+public interface ILanCallMedia : IAsyncDisposable
+{
+ Control LocalVideo { get; }
+ Control RemoteVideo { get; }
+ LanCallEndpoint Endpoint { get; }
+ Task Completion { get; }
+ bool HasRemoteMedia { get; }
+ Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct);
+}
diff --git a/src/PostIt/PostIt/Services/ILanCallSignaling.cs b/src/PostIt/PostIt/Services/ILanCallSignaling.cs
new file mode 100644
index 000000000..9d592299d
--- /dev/null
+++ b/src/PostIt/PostIt/Services/ILanCallSignaling.cs
@@ -0,0 +1,19 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Services;
+
+public interface ILanCallSignaling
+{
+ event Action? Invitation;
+ event Action? Accepted;
+ event Action? Ended;
+ event Action? Signal;
+ event Action? Interrupted;
+ Task InviteLanAsync(string room, string user, CancellationToken ct = default);
+ Task AcceptAsync(Guid callId, CancellationToken ct = default);
+ Task EndAsync(Guid callId, CancellationToken ct = default);
+ Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default);
+}
diff --git a/src/PostIt/PostIt/Services/IPodcastCapture.cs b/src/PostIt/PostIt/Services/IPodcastCapture.cs
index 2d0ca1636..ca0577f63 100644
--- a/src/PostIt/PostIt/Services/IPodcastCapture.cs
+++ b/src/PostIt/PostIt/Services/IPodcastCapture.cs
@@ -9,7 +9,7 @@ public sealed record CaptureDevice(string Name, string Value);
public sealed record PodcastCaptureDevices(
IReadOnlyList Cameras, IReadOnlyList Microphones);
-/// A running encoder publishing closed segments and an atomic index.m3u8.
+/// A running camera/microphone encoder with an optional native preview.
public interface IPodcastCapture : IAsyncDisposable
{
Task Completion { get; }
diff --git a/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs b/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs
new file mode 100644
index 000000000..da7488a46
--- /dev/null
+++ b/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs
@@ -0,0 +1,197 @@
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Threading;
+using System.Threading.Tasks;
+using LibVLCSharp.Shared;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Services;
+
+public sealed class LibVlcLanCallMedia : IAsyncDisposable
+{
+ private readonly LibVLC _senderVlc;
+ private readonly LibVLC _receiverVlc;
+ private readonly Media _receiverMedia;
+ private Media? _senderMedia;
+ private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private readonly SemaphoreSlim _gate = new(1);
+ private bool _receiving;
+ private bool _disposed;
+ private Task? _stop;
+
+ public LanCallEndpoint Endpoint { get; }
+ public MediaPlayer Sender { get; }
+ public MediaPlayer Receiver { get; }
+ public Task Completion => _completion.Task;
+ public MediaStats Statistics => _receiverMedia.Statistics;
+ public bool HasRemoteMedia => !_disposed && Statistics.DecodedAudio > 0 && Statistics.DecodedVideo > 0;
+
+ public LibVlcLanCallMedia(string localAddress, int port, bool headless = false)
+ {
+ if (!OperatingSystem.IsLinux() && !OperatingSystem.IsAndroidVersionAtLeast(26))
+ throw new PlatformNotSupportedException("Les appels SRTP LAN requierent Linux ou Android 8+.");
+ Endpoint = new(localAddress, port, Convert.ToHexString(RandomNumberGenerator.GetBytes(16)),
+ Convert.ToHexString(RandomNumberGenerator.GetBytes(14)));
+ if (!Endpoint.IsValid())
+ throw new ArgumentException("Adresse IPv4 privee et port UDP pair (1024-65534) requis.");
+ using (var reservation = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
+ using (var rtcp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
+ {
+ reservation.Bind(new IPEndPoint(IPAddress.Parse(localAddress), port));
+ rtcp.Bind(new IPEndPoint(IPAddress.Parse(localAddress), port + 1));
+ }
+ Core.Initialize();
+ _senderVlc = headless ? CameraStreamer.CreateHeadlessLibVlc()
+ : new LibVLC("--avcodec-hw=none", "--aout=dummy", "--intf=dummy");
+ try
+ {
+ _receiverVlc = headless ? CameraStreamer.CreateHeadlessLibVlc()
+ : new LibVLC("--avcodec-hw=none", "--intf=dummy");
+ try
+ {
+ _receiverMedia = new Media(_receiverVlc, $"rtp://@{localAddress}:{port}", FromType.FromLocation);
+ _receiverMedia.AddOption(":network-caching=150");
+ _receiverMedia.AddOption(":rtcp-port=" + (port + 1));
+ _receiverMedia.AddOption(":srtp-key=" + Endpoint.Key);
+ _receiverMedia.AddOption(":srtp-salt=" + Endpoint.Salt);
+ Receiver = new MediaPlayer(_receiverVlc);
+ Sender = new MediaPlayer(_senderVlc);
+ Sender.EncounteredError += OnSenderError;
+ Receiver.EncounteredError += OnReceiverError;
+ Sender.EndReached += OnSenderEnded;
+ }
+ catch
+ {
+ _receiverMedia?.Dispose();
+ Receiver?.Dispose();
+ Sender?.Dispose();
+ _receiverVlc.Dispose();
+ throw;
+ }
+ }
+ catch
+ {
+ _senderVlc.Dispose();
+ throw;
+ }
+ }
+
+ public async Task StartReceivingAsync(CancellationToken ct)
+ {
+ await _gate.WaitAsync(ct);
+ try
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ if (_stop != null) throw new InvalidOperationException("Cet appel est arrete.");
+ if (_receiving) return;
+ ct.ThrowIfCancellationRequested();
+ if (!Receiver.Play(_receiverMedia))
+ throw new InvalidOperationException("Reception SRTP impossible. Verifiez adresse et port UDP.");
+ _receiving = true;
+ }
+ finally { _gate.Release(); }
+ }
+
+ public Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct) =>
+ StartSendingAsync(remote, vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), true, ct);
+
+ internal async Task StartSendingAsync(LanCallEndpoint remote, Func source,
+ bool preview, CancellationToken ct, bool transcode = true)
+ {
+ if (!remote.IsValid())
+ throw new ArgumentException("Destination SRTP LAN invalide.", nameof(remote));
+ if (remote.Address == Endpoint.Address && remote.Port == Endpoint.Port)
+ throw new ArgumentException("Les deux pairs doivent avoir des ports distincts sur une meme adresse.");
+ await _gate.WaitAsync(ct);
+ try
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ if (_stop != null || _senderMedia != null)
+ throw new InvalidOperationException("La capture de cet appel est deja demarree ou arretee.");
+ _senderMedia = source(_senderVlc);
+ ConfigureOutput(_senderMedia, remote, preview, transcode);
+ ct.ThrowIfCancellationRequested();
+ if (!Sender.Play(_senderMedia))
+ throw new InvalidOperationException("Capture SRTP impossible. Verifiez camera, microphone et encodeurs H.264/AAC.");
+ }
+ finally { _gate.Release(); }
+ }
+
+ public Task StartEncodedSendingAsync(LanCallEndpoint remote, int fileDescriptor, CancellationToken ct)
+ {
+ if (fileDescriptor < 0) throw new ArgumentOutOfRangeException(nameof(fileDescriptor));
+ return StartSendingAsync(remote, vlc =>
+ {
+ var media = new Media(vlc, $"fd://{fileDescriptor}", FromType.FromLocation);
+ media.AddOption(":demux=ts");
+ media.AddOption(":live-caching=100");
+ media.AddOption(":clock-jitter=0");
+ return media;
+ }, false, ct, transcode: false);
+ }
+
+ internal static void ConfigureOutput(Media media, LanCallEndpoint remote, bool preview, bool transcode = true)
+ {
+ if (!remote.IsValid()) throw new ArgumentException("Destination SRTP invalide.");
+ // Same capture/encoders as Podcasts, but no HLS files, segmentation or upload.
+ var encoding = (transcode ? "transcode{vcodec=h264,venc=x264{preset=ultrafast,tune=zerolatency,keyint=30,bframes=0},"
+ + "vb=1200,fps=30,acodec=mp4a,ab=96,channels=1,samplerate=48000}:" : "")
+ // Android LibVLC 3 crashes formatting the valueless rtcp-mux SDP attribute.
+ + $"rtp{{dst={remote.Address},port={remote.Port},mux=ts,"
+ + $"key={remote.Key},salt={remote.Salt},caching=50}}";
+ media.AddOption(":sout=#" + (preview
+ ? $"duplicate{{dst=display{{noaudio}},dst=\"{encoding}\"}}" : encoding));
+ }
+
+ private void OnSenderError(object? sender, EventArgs args) => _completion.TrySetException(
+ new InvalidOperationException("Capture/encodage SRTP en echec. Verifiez les peripheriques et encodeurs."));
+
+ private void OnReceiverError(object? sender, EventArgs args) => _completion.TrySetException(
+ new InvalidOperationException("Reception/decodage SRTP en echec. Verifiez le reseau LAN/VPN et les ports UDP."));
+
+ private void OnSenderEnded(object? sender, EventArgs args) => _completion.TrySetException(
+ new InvalidOperationException("La source audio-video s'est terminee."));
+
+ private Task StopCoreAsync() => _stop ??= Task.Run(() =>
+ {
+ try { Sender.Stop(); }
+ finally { Receiver.Stop(); }
+ });
+
+ public async Task StopAsync()
+ {
+ await _gate.WaitAsync();
+ try
+ {
+ if (!_disposed) await StopCoreAsync();
+ }
+ finally { _gate.Release(); }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await _gate.WaitAsync();
+ try
+ {
+ if (_disposed) return;
+ _disposed = true;
+ Sender.EncounteredError -= OnSenderError;
+ Receiver.EncounteredError -= OnReceiverError;
+ Sender.EndReached -= OnSenderEnded;
+ try { await StopCoreAsync(); }
+ finally
+ {
+ Sender.Dispose();
+ Receiver.Dispose();
+ _senderMedia?.Dispose();
+ _receiverMedia.Dispose();
+ _senderVlc.Dispose();
+ _receiverVlc.Dispose();
+ _completion.TrySetResult();
+ }
+ }
+ finally { _gate.Release(); }
+ }
+}
diff --git a/src/PostIt/PostIt/Services/LinuxLanCallVideo.cs b/src/PostIt/PostIt/Services/LinuxLanCallVideo.cs
new file mode 100644
index 000000000..5a7974034
--- /dev/null
+++ b/src/PostIt/PostIt/Services/LinuxLanCallVideo.cs
@@ -0,0 +1,105 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using Avalonia.Threading;
+using LibVLCSharp.Avalonia;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.Services;
+
+public sealed class LinuxLanCallVideo : ILanCallMedia
+{
+ private readonly LibVlcLanCallMedia _media;
+ private readonly VideoView _local;
+ private readonly VideoView _remote;
+ private readonly TaskCompletionSource _localReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private readonly CancellationTokenSource _lifetime = new();
+ private bool _receiverScheduled;
+ private bool _localScheduled;
+ private bool _disposed;
+ private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ public Control LocalVideo => _local;
+ public Control RemoteVideo => _remote;
+ public LanCallEndpoint Endpoint => _media.Endpoint;
+ public Task Completion { get; }
+ public bool HasRemoteMedia => !_disposed && _media.HasRemoteMedia;
+
+ public LinuxLanCallVideo(string localAddress, int port)
+ {
+ _media = new LibVlcLanCallMedia(localAddress, port);
+ _local = new VideoView { MediaPlayer = _media.Sender, MinHeight = 140 };
+ _remote = new VideoView { MediaPlayer = _media.Receiver, MinHeight = 260 };
+ _local.LayoutUpdated += OnLocalLayout;
+ _remote.LayoutUpdated += OnRemoteLayout;
+ Completion = ObserveCompletionAsync();
+ }
+
+ private async Task ObserveCompletionAsync()
+ {
+ var completed = await Task.WhenAny(_media.Completion, _failure.Task);
+ await completed;
+ }
+
+ private void OnLocalLayout(object? sender, EventArgs e)
+ {
+ if (_localScheduled || _disposed || !_local.IsEffectivelyVisible ||
+ _local.Bounds.Width <= 0 || _local.Bounds.Height <= 0) return;
+ _localScheduled = true;
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (_disposed) return;
+ _local.TryUpdateNativeControlPosition();
+ _localReady.TrySetResult();
+ }, DispatcherPriority.Loaded);
+ }
+
+ private void OnRemoteLayout(object? sender, EventArgs e)
+ {
+ if (_receiverScheduled || _disposed || !_remote.IsEffectivelyVisible ||
+ _remote.Bounds.Width <= 0 || _remote.Bounds.Height <= 0) return;
+ _receiverScheduled = true;
+ Dispatcher.UIThread.Post(StartReceiver, DispatcherPriority.Loaded);
+ }
+
+ private async void StartReceiver()
+ {
+ if (_disposed) return;
+ try
+ {
+ _remote.TryUpdateNativeControlPosition();
+ await _media.StartReceivingAsync(_lifetime.Token);
+ }
+ catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
+ catch (Exception error) { _failure.TrySetException(error); }
+ }
+
+ public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
+ {
+ await _localReady.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
+ await _media.StartSendingAsync(remote, camera, microphone, ct);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_disposed) return;
+ _disposed = true;
+ _lifetime.Cancel();
+ _localReady.TrySetCanceled();
+ _local.LayoutUpdated -= OnLocalLayout;
+ _remote.LayoutUpdated -= OnRemoteLayout;
+ try { await _media.StopAsync(); }
+ finally
+ {
+ _local.MediaPlayer = null;
+ _remote.MediaPlayer = null;
+ try { await _media.DisposeAsync(); }
+ finally
+ {
+ _lifetime.Dispose();
+ _failure.TrySetResult();
+ }
+ }
+ }
+}
diff --git a/src/PostIt/PostIt/Services/Platform.cs b/src/PostIt/PostIt/Services/Platform.cs
index b3f8904de..77bf4c691 100644
--- a/src/PostIt/PostIt/Services/Platform.cs
+++ b/src/PostIt/PostIt/Services/Platform.cs
@@ -12,6 +12,8 @@ namespace PostIt.Services;
///
public static class Platform
{
+ public static Func? GetLanCallDevices { get; set; }
+ public static Func? CreateLanCallMedia { get; set; }
public static Func? GetPodcastCaptureDevices { get; set; }
public static Func? RequestPodcastPermissionsAsync { get; set; }
public static Func>? CreatePodcastCaptureAsync { get; set; }
diff --git a/src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs
index e8fc1e535..80f6de51a 100644
--- a/src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs
@@ -1,17 +1,28 @@
using System;
+using CommunityToolkit.Mvvm.ComponentModel;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
-public sealed class VideoPageViewModel(Uri source, string mimeType) : ViewModelBase
+public partial class VideoPageViewModel(Uri source, string mimeType, Uri? externalUri = null) : ViewModelBase
{
public Uri Source { get; } = source;
+ public Uri ExternalUri { get; } = externalUri ?? source;
public string MimeType { get; } = mimeType;
public PodcastApiClient? PodcastClient { get; init; }
- public PodcastResponse? Podcast { get; init; }
- public bool CanOpenExternal => Podcast is null;
+ public PodcastResponse? Podcast { get; set; }
+
+ public bool CanOpenExternal => CanLaunchExternally(ExternalUri);
public string Title => Podcast?.Title ?? Uri.UnescapeDataString(System.IO.Path.GetFileName(Source.AbsolutePath));
public override bool CanNavigateNext { get => false; protected set { } }
public override bool CanNavigatePrevious { get => true; protected set { } }
+
+ private static bool CanLaunchExternally(Uri source)
+ => source is { IsAbsoluteUri: true }
+ && (string.Equals(source.Scheme, "http", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(source.Scheme, "https", StringComparison.OrdinalIgnoreCase))
+ && !string.Equals(source.Host, "localhost", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(source.AbsolutePath, "/", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(source.Scheme, "about", StringComparison.OrdinalIgnoreCase);
}
diff --git a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs
index 7d5b516d6..50dacd192 100644
--- a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs
@@ -37,6 +37,14 @@ namespace PostIt.ViewModels.Chat
private HubConnection? _connection;
+ public CallSignalingClient? Calls { get; private set; }
+
+ public bool SupportsLanCalls => Platform.CreateLanCallMedia != null ||
+ (OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid());
+
+ [ObservableProperty]
+ public partial LanCallViewModel? LanCall { get; set; }
+
[ObservableProperty]
public partial string CurrentRoom { get; set; } = "General";
@@ -81,6 +89,7 @@ namespace PostIt.ViewModels.Chat
partial void OnSelectedRoomChanged(string? value)
{
+ if (LanCall != null) LanCall.Room = value ?? "";
FocusedMessages = value != null && _messagesByRoom.TryGetValue(value, out var msgs)
? msgs : _systemMessages;
FocusedUsers = value != null && _usersByRoom.TryGetValue(value, out var users)
@@ -130,6 +139,15 @@ namespace PostIt.ViewModels.Chat
private async Task DisconnectAsync()
{
+ Exception? callError = null;
+ if (LanCall != null)
+ {
+ try { await LanCall.DisposeAsync(); }
+ catch (Exception error) { callError = error; }
+ finally { LanCall = null; }
+ }
+ Calls?.Dispose();
+ Calls = null;
if (_connection != null)
{
await _connection.StopAsync();
@@ -142,7 +160,9 @@ namespace PostIt.ViewModels.Chat
_messagesByRoom.Clear();
_usersByRoom.Clear();
_systemMessages.Clear();
- Status = new StatusNotice("Déconnecté", StatusSeverity.Info,
+ Status = new StatusNotice(callError == null ? "Déconnecté" :
+ "Déconnecté ; erreur de fermeture de l'appel : " + callError.Message,
+ callError == null ? StatusSeverity.Info : StatusSeverity.Error,
new RelayCheckCommand("Connecter", async () => await ConnectAsync()));
}
@@ -150,6 +170,18 @@ namespace PostIt.ViewModels.Chat
{
try
{
+ if (_connection != null)
+ {
+ if (LanCall != null)
+ {
+ await LanCall.DisposeAsync();
+ LanCall = null;
+ }
+ Calls?.Dispose();
+ Calls = null;
+ await _connection.DisposeAsync();
+ _connection = null;
+ }
Status = new StatusNotice("Connexion en cours...", StatusSeverity.Info,
new RelayCheckCommand("Vérifier la connexion", async () => await CheckConnectionAsync()));
@@ -188,6 +220,15 @@ namespace PostIt.ViewModels.Chat
.WithAutomaticReconnect()
.Build();
+ Calls = new CallSignalingClient(_connection);
+ if (SupportsLanCalls)
+ LanCall = new LanCallViewModel(Calls) { Room = SelectedRoom ?? "" };
+ else
+ Calls.Invitation += call => Avalonia.Threading.Dispatcher.UIThread.Post(() =>
+ Log($"Invitation audio-vidéo de {call.Caller} dans {call.RoomName} ; transport non disponible sur cette plateforme."));
+ Calls.Ended += call => Avalonia.Threading.Dispatcher.UIThread.Post(() =>
+ Log($"Appel terminé : {call.Reason}."));
+
// 1. Ecoute des notifications globales (notifyUser)
_connection.On("notifyUser", (type, user, msg) =>
{
diff --git a/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs
new file mode 100644
index 000000000..5753e7b36
--- /dev/null
+++ b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs
@@ -0,0 +1,332 @@
+using System;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using Avalonia.Threading;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using PostIt.Services;
+using Yavsc.Abstract.Chat.Calls;
+
+namespace PostIt.ViewModels.Chat;
+
+public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
+{
+ private readonly ILanCallSignaling _signaling;
+ private readonly Func _createMedia;
+ private readonly SemaphoreSlim _events = new(1);
+ private readonly CancellationTokenSource _lifetime = new();
+ private CancellationTokenSource? _callLifetime;
+ private ILanCallMedia? _media;
+ private CallSession? _call;
+ private bool _disposed;
+ private bool _accepting;
+ private bool _endpointReceived;
+ private string? _activeCamera;
+ private string? _activeMicrophone;
+ private string? _activeAddress;
+ private int _activePort;
+
+ public ObservableCollection Addresses { get; } = [];
+ public ObservableCollection Cameras { get; } = [];
+ public ObservableCollection Microphones { get; } = [];
+
+ [ObservableProperty] public partial string? Address { get; set; }
+ [ObservableProperty] public partial string Port { get; set; } = "5004";
+ [ObservableProperty] public partial CaptureDevice? Camera { get; set; }
+ [ObservableProperty] public partial CaptureDevice? Microphone { get; set; }
+ [ObservableProperty] public partial bool AllowAddressDisclosure { get; set; }
+ [ObservableProperty] public partial string Target { get; set; } = "";
+ [ObservableProperty] public partial string Room { get; set; } = "";
+ [ObservableProperty] public partial string Status { get; set; } = "Appel LAN/VPN : aucun appel.";
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
+ public partial bool Incoming { get; set; }
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
+ public partial bool Busy { get; set; }
+ [ObservableProperty] public partial bool Preparing { get; set; }
+ [ObservableProperty] public partial Control? LocalVideo { get; set; }
+ [ObservableProperty] public partial Control? RemoteVideo { get; set; }
+ public bool CanConfigure => !Busy || Incoming;
+
+ public LanCallViewModel(ILanCallSignaling signaling, Func? createMedia = null)
+ {
+ _signaling = signaling;
+ _createMedia = createMedia ?? Platform.CreateLanCallMedia ??
+ ((address, port) => new LinuxLanCallVideo(address, port));
+ signaling.Invitation += OnInvitation;
+ signaling.Accepted += OnAccepted;
+ signaling.Signal += OnSignal;
+ signaling.Ended += OnEnded;
+ signaling.Interrupted += OnInterrupted;
+ Platform.PlaybackSuspending += OnSuspending;
+ }
+
+ [RelayCommand]
+ private void RefreshDevices()
+ {
+ try
+ {
+ if (!CanConfigure) throw new InvalidOperationException("Terminez l'appel avant de changer les peripheriques.");
+ Addresses.Clear();
+ foreach (var address in NetworkInterface.GetAllNetworkInterfaces()
+ .Where(n => n.OperationalStatus == OperationalStatus.Up)
+ .SelectMany(n => n.GetIPProperties().UnicastAddresses)
+ .Select(a => a.Address.ToString()).Where(LanCallNetwork.IsPrivateIPv4)
+ .Distinct().OrderBy(a => IPAddress.IsLoopback(IPAddress.Parse(a))))
+ Addresses.Add(address);
+ Address = Addresses.FirstOrDefault();
+ Cameras.Clear();
+ Microphones.Clear();
+ if (Platform.GetLanCallDevices is { } getDevices)
+ {
+ var devices = getDevices();
+ foreach (var device in devices.Cameras) Cameras.Add(device);
+ foreach (var device in devices.Microphones.Where(d => !string.IsNullOrEmpty(d.Value)))
+ Microphones.Add(device);
+ }
+ else
+ {
+ LibVLCSharp.Shared.Core.Initialize();
+ using var vlc = CameraStreamer.CreatePreferredLibVlc();
+ var streamer = new CameraStreamer(vlc);
+ foreach (var device in streamer.GetCaptureDevices()) Cameras.Add(new(device.Key, device.Value));
+ foreach (var device in streamer.GetAudioCaptureDevices()) Microphones.Add(new(device.Key, device.Value));
+ }
+ Camera = Cameras.FirstOrDefault();
+ Microphone = Microphones.FirstOrDefault();
+ Status = Cameras.Count == 0 ? "Aucune camera detectee. Verifiez les peripheriques puis actualisez."
+ : Incoming && _call != null
+ ? $"{_call.Caller} propose un appel dans {_call.RoomName}. Selectionnez vos peripheriques puis acceptez ou refusez."
+ : "Selectionnez le pair, l'adresse LAN/VPN et les peripheriques. Utilisez un casque.";
+ }
+ catch (Exception error) { Status = "Peripheriques indisponibles : " + error.Message; }
+ }
+
+ private void ValidateSelection()
+ {
+ if (!AllowAddressDisclosure)
+ throw new InvalidOperationException("Confirmez le partage de votre adresse LAN/VPN avec le pair.");
+ if (Camera == null || Microphone == null)
+ throw new InvalidOperationException("Une camera et un microphone sont requis.");
+ if (Address == null || !Addresses.Contains(Address) || !LanCallNetwork.IsPrivateIPv4(Address) ||
+ !int.TryParse(Port, out var port) || port is < 1024 or > 65534 || port % 2 != 0)
+ throw new InvalidOperationException("Selectionnez une adresse locale et un port UDP pair (1024-65534).");
+ _activeCamera = Camera.Value;
+ _activeMicrophone = Microphone.Value;
+ _activeAddress = Address;
+ _activePort = port;
+ }
+
+ [RelayCommand]
+ private Task InviteAsync() => RunAsync(async () =>
+ {
+ if (Busy) throw new InvalidOperationException("Un appel est deja en cours.");
+ ValidateSelection();
+ if (string.IsNullOrWhiteSpace(Target) || string.IsNullOrWhiteSpace(Room))
+ throw new InvalidOperationException("Selectionnez une salle jointe et un autre utilisateur.");
+ Busy = true;
+ _call = await _signaling.InviteLanAsync(Room, Target.Trim(), _lifetime.Token);
+ Status = $"Invitation envoyee a {_call.Callee} ; attente du consentement.";
+ });
+
+ [RelayCommand]
+ private Task AcceptAsync() => RunAsync(async () =>
+ {
+ if (_call == null || !Incoming)
+ throw new InvalidOperationException("Aucune invitation a accepter.");
+ ValidateSelection();
+ Incoming = false;
+ _accepting = true;
+ await _signaling.AcceptAsync(_call.Id, _lifetime.Token);
+ Status = "Invitation acceptee ; preparation des medias.";
+ });
+
+ [RelayCommand]
+ public Task HangupAsync()
+ {
+ _callLifetime?.Cancel();
+ return RunAsync(() => StopAsync("Appel termine.", true));
+ }
+
+ private void OnInvitation(CallSession call) => Queue(async () =>
+ {
+ if (call.Transport != CallTransports.LanSrtp)
+ {
+ await _signaling.EndAsync(call.Id, _lifetime.Token);
+ Status = "Invitation WebRTC non prise en charge par le mode LAN.";
+ return;
+ }
+ if (_call != null) throw new InvalidOperationException("Invitation concurrente inattendue.");
+ if (call.RelayOnly) throw new InvalidOperationException("Le mode LAN ne peut pas masquer les adresses IP.");
+ _call = call;
+ Busy = true;
+ Incoming = true;
+ Status = $"{call.Caller} propose un appel SRTP dans {call.RoomName}. Acceptez ou refusez.";
+ await Task.CompletedTask;
+ });
+
+ private void OnAccepted(CallAccepted accepted) => Queue(async () =>
+ {
+ if (_call?.Id != accepted.Session.Id) return;
+ if (_media != null) throw new InvalidOperationException("Acceptation repetee.");
+ if (accepted.Session.Transport != CallTransports.LanSrtp || accepted.Session.RelayOnly ||
+ (Incoming && !_accepting))
+ throw new InvalidOperationException("Acceptation ou politique de transport inattendue.");
+ _call = accepted.Session;
+ Incoming = false;
+ _accepting = false;
+ _callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
+ _media = _createMedia(_activeAddress!, _activePort);
+ LocalVideo = _media.LocalVideo;
+ RemoteVideo = _media.RemoteVideo;
+ Status = "Connexion SRTP : attente du pair (30 secondes maximum).";
+ await _signaling.SendAsync(_call.Id, new("rtp-endpoint", Endpoint: _media.Endpoint), _callLifetime.Token);
+ _ = MonitorAsync(_call.Id, _media, _callLifetime.Token);
+ });
+
+ private void OnSignal(Guid id, CallSignal signal) => Queue(async () =>
+ {
+ if (_call?.Id != id) return;
+ if (_media == null || _callLifetime == null || signal.Kind != "rtp-endpoint" ||
+ signal.Endpoint?.IsValid() != true || _endpointReceived)
+ throw new InvalidOperationException("Destination SRTP manquante, invalide ou repetee.");
+ _endpointReceived = true;
+ await _media.StartSendingAsync(signal.Endpoint, _activeCamera!, _activeMicrophone!, _callLifetime.Token);
+ Status = "Emission SRTP demarree ; verification de la reception audio-video.";
+ });
+
+ private void OnEnded(CallEnded ended) => QueueStop(ended.CallId, async () =>
+ {
+ if (_call?.Id == ended.CallId)
+ await StopAsync("Appel termine : " + ended.Reason, false);
+ });
+
+ private void OnInterrupted() => QueueStop(null,
+ () => StopAsync("Connexion SignalR interrompue ; medias arretes.", false));
+
+ private void OnSuspending() => QueueStop(null,
+ () => StopAsync("Application en arriere-plan ; appel termine.", true));
+
+ private void QueueStop(Guid? id, Func action) => Dispatcher.UIThread.Post(async () =>
+ {
+ if (id == null || _call?.Id == id) _callLifetime?.Cancel();
+ await RunAsync(action);
+ });
+
+ private async Task MonitorAsync(Guid id, ILanCallMedia media, CancellationToken ct)
+ {
+ var start = Stopwatch.StartNew();
+ var received = false;
+ try
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ if (media.Completion.IsCompleted) await media.Completion;
+ if (!received && media.HasRemoteMedia)
+ {
+ received = true;
+ await Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ if (_call?.Id == id) Status = "Reception audio-video SRTP etablie (LAN/VPN).";
+ });
+ }
+ if (!received && start.Elapsed > TimeSpan.FromSeconds(30))
+ throw new TimeoutException("Aucun media distant : verifiez adresses, port UDP et pare-feu LAN/VPN.");
+ await Task.Delay(500, ct);
+ }
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
+ catch (Exception error)
+ {
+ Queue(() => _call?.Id == id && ReferenceEquals(_media, media)
+ ? FailAsync(error) : Task.CompletedTask);
+ }
+ }
+
+ private void Queue(Func action) =>
+ Dispatcher.UIThread.Post(async () => await RunAsync(action));
+
+ private async Task RunAsync(Func action)
+ {
+ await _events.WaitAsync();
+ try
+ {
+ if (_disposed) return;
+ Preparing = true;
+ await action();
+ }
+ catch (OperationCanceledException) when (
+ _lifetime.IsCancellationRequested || _callLifetime?.IsCancellationRequested == true) { }
+ catch (Exception error) { await FailAsync(error); }
+ finally
+ {
+ Preparing = false;
+ _events.Release();
+ }
+ }
+
+ private async Task FailAsync(Exception error)
+ {
+ try { await StopAsync("Echec de l'appel : " + error.Message, true); }
+ catch (Exception cleanupError)
+ {
+ Status = $"Echec de l'appel : {error.Message}. Nettoyage/signalisation : {cleanupError.Message}";
+ }
+ }
+
+ private async Task StopAsync(string status, bool notify)
+ {
+ var call = _call;
+ _call = null;
+ Incoming = false;
+ Busy = false;
+ _accepting = false;
+ _endpointReceived = false;
+ _callLifetime?.Cancel();
+ var media = _media;
+ _media = null;
+ try
+ {
+ if (media != null) await media.DisposeAsync();
+ }
+ finally
+ {
+ LocalVideo = null;
+ RemoteVideo = null;
+ _callLifetime?.Dispose();
+ _callLifetime = null;
+ Status = status;
+ }
+ if (notify && call != null)
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ await _signaling.EndAsync(call.Id, timeout.Token);
+ }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_disposed) return;
+ _lifetime.Cancel();
+ await _events.WaitAsync();
+ try
+ {
+ if (_disposed) return;
+ _disposed = true;
+ _signaling.Invitation -= OnInvitation;
+ _signaling.Accepted -= OnAccepted;
+ _signaling.Signal -= OnSignal;
+ _signaling.Ended -= OnEnded;
+ _signaling.Interrupted -= OnInterrupted;
+ Platform.PlaybackSuspending -= OnSuspending;
+ try { await StopAsync("Appel arrete.", true); }
+ finally { _lifetime.Dispose(); }
+ }
+ finally { _events.Release(); }
+ }
+}
diff --git a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs
index 449648ef3..61f071683 100644
--- a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs
@@ -91,6 +91,9 @@ public partial class UserProfilePageViewModel : ViewModelBase
[ObservableProperty]
public partial bool AllowMonthlyEmail { get; set; }
+ [ObservableProperty]
+ public partial bool HideIpAddressInCalls { get; set; }
+
[ObservableProperty]
public partial bool HasPassword { get; set; }
@@ -195,6 +198,7 @@ public partial class UserProfilePageViewModel : ViewModelBase
BankInfoSummary = string.IsNullOrWhiteSpace(me.BankInfoSummary) ? "Aucune information bancaire" : me.BankInfoSummary;
EmailConfirmed = me.EmailConfirmed;
AllowMonthlyEmail = me.AllowMonthlyEmail;
+ HideIpAddressInCalls = me.HideIpAddressInCalls;
HasPassword = me.HasPassword;
TwoFactorEnabled = me.TwoFactorEnabled;
ExternalLoginCount = me.ExternalLoginCount;
@@ -280,7 +284,8 @@ public partial class UserProfilePageViewModel : ViewModelBase
UserName = NormalizeField(UserName, "—"),
FullName = NormalizeField(FullName, "—"),
Address = NormalizeField(Address, "—"),
- GoogleCalendarId = NormalizeField(DedicatedGoogleCalendar, "Non configuré")
+ GoogleCalendarId = NormalizeField(DedicatedGoogleCalendar, "Non configuré"),
+ HideIpAddressInCalls = HideIpAddressInCalls
};
}
diff --git a/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs
index 91b6d0572..0083a38db 100644
--- a/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs
@@ -50,6 +50,9 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase
[ObservableProperty]
public partial string Website { get; set; } = string.Empty;
+ [ObservableProperty]
+ public partial string DonationPayPalEmail { get; set; } = string.Empty;
+
[ObservableProperty]
public partial bool Active { get; set; }
@@ -101,6 +104,7 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase
ExerciseCountryCode = string.IsNullOrWhiteSpace(dto?.ExerciseCountryCode) ? "fr" : dto.ExerciseCountryCode;
SIREN = dto?.SIREN ?? string.Empty;
Website = dto?.WebSite ?? string.Empty;
+ DonationPayPalEmail = dto?.DonationPayPalEmail ?? string.Empty;
Active = dto?.Active ?? false;
AcceptNotifications = dto?.AcceptNotifications ?? false;
AcceptPublicContact = dto?.AcceptPublicContact ?? false;
@@ -142,6 +146,7 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase
ExerciseCountryCode = string.IsNullOrWhiteSpace(ExerciseCountryCode) ? "fr" : ExerciseCountryCode,
SIREN = SIREN,
WebSite = Website,
+ DonationPayPalEmail = DonationPayPalEmail.Trim(),
Active = Active,
AcceptNotifications = AcceptNotifications,
AcceptPublicContact = AcceptPublicContact,
diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs
index 6d9877da8..420024342 100644
--- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs
@@ -263,7 +263,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez un podcast.");
var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible.");
var manifestUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), $"podcasts/{podcast.Id}/index.m3u8");
- await app.PushPageAsync(new VideoPageViewModel(manifestUrl, "application/vnd.apple.mpegurl")
+ var catalogueUrl = new Uri(new Uri(_api.Settings.Authentication.Authority.TrimEnd('/') + "/"), "Podcast");
+ await app.PushPageAsync(new VideoPageViewModel(manifestUrl, "application/vnd.apple.mpegurl", catalogueUrl)
{
PodcastClient = _client, Podcast = podcast
});
diff --git a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml
index 4749736a7..d9e513f97 100644
--- a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml
+++ b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml
@@ -10,13 +10,14 @@
xmlns:postitControls="using:PostIt.Controls"
xmlns:views="using:PostIt.Views.Chat"
xmlns:vm="using:PostIt.ViewModels.Chat"
+ xmlns:services="using:PostIt.Services"
x:DataType="vm:ChatViewModel"
>
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml.cs b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml.cs
index f73e1f827..7f2ca053c 100644
--- a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml.cs
+++ b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml.cs
@@ -1,4 +1,6 @@
+using Avalonia;
using Avalonia.Controls;
+using PostIt.ViewModels.Chat;
namespace PostIt.Views.Chat;
public partial class ChatPage : ContentPage
{
@@ -8,4 +10,10 @@ public partial class ChatPage : ContentPage
InitializeComponent();
}
+ protected override async void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
+ {
+ base.OnDetachedFromVisualTree(e);
+ if (DataContext is ChatViewModel { LanCall: { } call })
+ await call.HangupAsync();
+ }
}
diff --git a/src/PostIt/PostIt/Views/Layout/PerformerConfigurationPage.axaml b/src/PostIt/PostIt/Views/Layout/PerformerConfigurationPage.axaml
index ff9e0fe31..f8d02b32a 100644
--- a/src/PostIt/PostIt/Views/Layout/PerformerConfigurationPage.axaml
+++ b/src/PostIt/PostIt/Views/Layout/PerformerConfigurationPage.axaml
@@ -27,6 +27,16 @@
+
+
+
+
+
+
+
+
+
+
+