Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
e3b4414ab1 |
|||
|
20a44bfde1 |
|||
|
89d9137884 |
|||
|
9578a9c416 |
|||
|
a676ef3575 |
|||
|
cc28ee8b29 |
|||
|
5e48831d6d |
|||
|
56ca115f50 |
|||
|
e47bc10026 |
|||
|
d8200cb98d |
111 changed files with 16278 additions and 155 deletions
11
CHANGELOG.md
11
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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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`
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
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.
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@
|
|||
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
|
||||
<AndroidPackageFormat>apk</AndroidPackageFormat>
|
||||
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<AndroidResource Include="Icon.png">
|
||||
|
|
@ -32,6 +32,7 @@
|
|||
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<Compile Include="..\PostIt.Tests\AndroidPodcastCaptureTestActivity.cs" Link="Tests\AndroidPodcastCaptureTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidCameraFrameRotationTestActivity.cs" Link="Tests\AndroidCameraFrameRotationTestActivity.cs" />
|
||||
<Compile Include="..\PostIt.Tests\AndroidLanCallTestActivity.cs" Link="Tests\AndroidLanCallTestActivity.cs" />
|
||||
</ItemGroup>
|
||||
<!-- This is an Avalonia app, not a MAUI app: exclude the .NET MAUI VS Code
|
||||
extension's injected HotReload agent (references Microsoft.Maui.*).
|
||||
|
|
|
|||
117
src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs
Normal file
117
src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using PostIt.Services;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
internal sealed class AndroidLanCallMedia : ILanCallMedia
|
||||
{
|
||||
private readonly LibVlcLanCallMedia _media;
|
||||
private readonly ContentControl _local = new();
|
||||
private readonly AndroidVideoSurface _remote;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly TaskCompletionSource _captureEnded = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly Task _receiving;
|
||||
private IPodcastCapture? _capture;
|
||||
private bool _disposed;
|
||||
|
||||
public Control LocalVideo => _local;
|
||||
public Control RemoteVideo => _remote;
|
||||
public LanCallEndpoint Endpoint => _media.Endpoint;
|
||||
public bool HasRemoteMedia => !_disposed && _media.HasRemoteMedia;
|
||||
public Task Completion { get; }
|
||||
|
||||
public static PodcastCaptureDevices GetDevices()
|
||||
{
|
||||
var devices = AndroidPodcastCapture.GetDevices();
|
||||
return new(devices.Cameras.OrderByDescending(c => c.Name == "Camera avant").ToArray(),
|
||||
devices.Microphones.Where(m => m.Value == "microphone").ToArray());
|
||||
}
|
||||
|
||||
public AndroidLanCallMedia(string localAddress, int port)
|
||||
{
|
||||
_media = new LibVlcLanCallMedia(localAddress, port);
|
||||
_remote = new AndroidVideoSurface(_media.Receiver, replay: false);
|
||||
_receiving = ReceiveAsync();
|
||||
Completion = ObserveAsync();
|
||||
}
|
||||
|
||||
private async Task ReceiveAsync()
|
||||
{
|
||||
await _remote.Ready.WaitAsync(TimeSpan.FromSeconds(10), _lifetime.Token);
|
||||
await _media.StartReceivingAsync(_lifetime.Token);
|
||||
}
|
||||
|
||||
private async Task ObserveAsync()
|
||||
{
|
||||
var first = await Task.WhenAny(_media.Completion, _captureEnded.Task, _receiving);
|
||||
await first;
|
||||
if (first == _receiving)
|
||||
{
|
||||
var finished = await Task.WhenAny(_media.Completion, _captureEnded.Task);
|
||||
await finished;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_capture != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
|
||||
_capture = await AndroidPodcastCapture.StartCallAsync(camera, microphone,
|
||||
(fd, token) => _media.StartEncodedSendingAsync(remote, fd, token), _media.StopAsync, linked.Token);
|
||||
_local.Content = _capture.Preview;
|
||||
_ = ObserveCaptureAsync(_capture);
|
||||
}
|
||||
|
||||
private async Task ObserveCaptureAsync(IPodcastCapture capture)
|
||||
{
|
||||
try
|
||||
{
|
||||
await capture.Completion;
|
||||
if (!_disposed)
|
||||
_captureEnded.TrySetException(new InvalidOperationException("Capture de l'appel arretee."));
|
||||
}
|
||||
catch (Exception error) { _captureEnded.TrySetException(error); }
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_lifetime.Cancel();
|
||||
var stop = _capture?.StopAsync();
|
||||
try
|
||||
{
|
||||
if (stop != null) await stop;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_capture != null) await _capture.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_local.Content = null;
|
||||
try { await _media.StopAsync(); }
|
||||
finally
|
||||
{
|
||||
_remote.Dispose();
|
||||
try { await _media.DisposeAsync(); }
|
||||
finally
|
||||
{
|
||||
_lifetime.Dispose();
|
||||
_captureEnded.TrySetResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ using Android.OS;
|
|||
using Android.Views;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using PostIt.Services;
|
||||
using Stream = System.IO.Stream;
|
||||
|
||||
namespace PostIt.Android.Services;
|
||||
|
||||
|
|
@ -33,6 +34,7 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
private ParcelFileDescriptor? _readPipe;
|
||||
private ParcelFileDescriptor? _writePipe;
|
||||
private Task _pump = Task.CompletedTask;
|
||||
private Func<Task>? _stopOutput;
|
||||
private Exception? _failure;
|
||||
private bool _stopped;
|
||||
private bool _stopRequested;
|
||||
|
|
@ -71,16 +73,26 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
}
|
||||
|
||||
public static async Task<IPodcastCapture> StartAsync(string camera, string? microphone, string directory, CancellationToken ct)
|
||||
=> await StartCoreAsync(camera, microphone,
|
||||
(stream, token) => new TransportStreamCapture(directory).RunAsync(stream, token), null, null, ct);
|
||||
|
||||
internal static Task<IPodcastCapture> StartCallAsync(string camera, string microphone,
|
||||
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
|
||||
StartCoreAsync(camera, microphone, null, output, stopOutput, ct);
|
||||
|
||||
private static async Task<IPodcastCapture> StartCoreAsync(string camera, string? microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, Func<Task>? stopOutput, CancellationToken ct)
|
||||
{
|
||||
await RequestPermissionsAsync(microphone, ct);
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
var service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct);
|
||||
var capture = new AndroidPodcastCapture(service);
|
||||
var service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct, pipeOutput != null);
|
||||
var capture = new AndroidPodcastCapture(service) { _stopOutput = stopOutput };
|
||||
service.Capture = capture;
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await capture.StartNativeAsync(camera, microphone is not null, directory, ct);
|
||||
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct);
|
||||
return capture;
|
||||
}
|
||||
catch
|
||||
|
|
@ -90,14 +102,18 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
}
|
||||
}
|
||||
|
||||
private async Task StartNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
|
||||
private async Task StartNativeAsync(string cameraId, bool microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct)
|
||||
{
|
||||
await _stopGate.WaitAsync(ct);
|
||||
try { await ConfigureNativeAsync(cameraId, microphone, directory, ct); }
|
||||
try { await ConfigureNativeAsync(cameraId, microphone, output, pipeOutput, ct); }
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task ConfigureNativeAsync(string cameraId, bool microphone, string directory, CancellationToken ct)
|
||||
private async Task ConfigureNativeAsync(string cameraId, bool microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct)
|
||||
{
|
||||
var manager = GetManager(_service);
|
||||
using var characteristics = manager.GetCameraCharacteristics(cameraId);
|
||||
|
|
@ -179,28 +195,34 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
using var request = _camera.CreateCaptureRequest(CameraTemplate.Record);
|
||||
request.AddTarget(cameraSurface);
|
||||
using var built = request.Build();
|
||||
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
|
||||
var stream = new FileStream(handle, FileAccess.Read);
|
||||
_pump = Task.Run(async () =>
|
||||
if (pipeOutput != null)
|
||||
await pipeOutput(_readPipe.Fd, ct);
|
||||
else
|
||||
{
|
||||
using (handle)
|
||||
using (stream)
|
||||
var consume = output ?? throw new InvalidOperationException("Destination de capture absente.");
|
||||
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
|
||||
var stream = new FileStream(handle, FileAccess.Read);
|
||||
_pump = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
using (handle)
|
||||
using (stream)
|
||||
{
|
||||
await new TransportStreamCapture(directory).RunAsync(stream, CancellationToken.None);
|
||||
if (_failure is not null) throw new IOException("Capture Android interrompue.", _failure);
|
||||
if (!_stopped) throw new IOException("Le flux de capture Android s'est ferme prematurement.");
|
||||
_completion.TrySetResult();
|
||||
try
|
||||
{
|
||||
await consume(stream, CancellationToken.None);
|
||||
if (_failure is not null) throw new IOException("Capture Android interrompue.", _failure);
|
||||
if (!_stopped) throw new IOException("Le flux de capture Android s'est ferme prematurement.");
|
||||
_completion.TrySetResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_completion.TrySetException(ex);
|
||||
// Drain until MediaRecorder stops, so its writer cannot block Stop().
|
||||
await stream.CopyToAsync(Stream.Null);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_completion.TrySetException(ex);
|
||||
// Drain until MediaRecorder stops, so its writer cannot block Stop().
|
||||
await stream.CopyToAsync(System.IO.Stream.Null);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
await Task.Run(_recorder.Start, ct);
|
||||
_started = true;
|
||||
await _rotator.StartAsync();
|
||||
|
|
@ -289,14 +311,48 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
{
|
||||
if (_stopped) return;
|
||||
_stopped = true;
|
||||
if (_preview is not null)
|
||||
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(_preview.Dispose);
|
||||
await Task.Run(StopNative);
|
||||
await _pump;
|
||||
try
|
||||
{
|
||||
if (_preview is not null)
|
||||
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(_preview.Dispose);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { await StopOutputAsync(); }
|
||||
finally
|
||||
{
|
||||
await Task.Run(StopNative);
|
||||
await _pump;
|
||||
}
|
||||
}
|
||||
_completion.TrySetResult();
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
_completion.TrySetException(error);
|
||||
throw;
|
||||
}
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task StopOutputAsync()
|
||||
{
|
||||
if (_stopOutput == null || _readPipe == null) return;
|
||||
try { await _stopOutput(); }
|
||||
finally
|
||||
{
|
||||
// The native sender has released its reader. Drain so the recorder can always stop.
|
||||
var handle = new SafeFileHandle((IntPtr)_readPipe.Fd, ownsHandle: false);
|
||||
var stream = new FileStream(handle, FileAccess.Read);
|
||||
_pump = Task.Run(async () =>
|
||||
{
|
||||
using (handle)
|
||||
using (stream)
|
||||
await stream.CopyToAsync(Stream.Null);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void StopNative()
|
||||
{
|
||||
try
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Android;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform;
|
||||
|
|
@ -18,6 +19,8 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
|
|||
private VideoView? _video;
|
||||
private ReplayLayout? _layout;
|
||||
private bool _disposed;
|
||||
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal Task Ready => _ready.Task;
|
||||
|
||||
protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
|
||||
{
|
||||
|
|
@ -25,6 +28,10 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
|
|||
?? throw new InvalidOperationException("L'activite Android est indisponible.");
|
||||
var video = new VideoView(activity) { MediaPlayer = _disposed ? null : player };
|
||||
_video = video;
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (!_disposed) _ready.TrySetResult();
|
||||
}, Avalonia.Threading.DispatcherPriority.Loaded);
|
||||
if (replay && !_disposed)
|
||||
{
|
||||
_layout = new ReplayLayout(activity, video, player);
|
||||
|
|
@ -45,6 +52,7 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay) : Nat
|
|||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
_ready.TrySetCanceled();
|
||||
_layout?.Stop();
|
||||
if (_video is not null) _video.MediaPlayer = null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,14 +21,16 @@ public sealed class PodcastCaptureService : Service
|
|||
private PowerManager.WakeLock? _wakeLock;
|
||||
internal AndroidPodcastCapture? Capture { get; set; }
|
||||
|
||||
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone, CancellationToken ct)
|
||||
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone,
|
||||
CancellationToken ct, bool call = false)
|
||||
{
|
||||
if (_pending is not null) throw new InvalidOperationException("Un direct Android est deja en cours.");
|
||||
var pending = new TaskCompletionSource<PodcastCaptureService>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_pending = pending;
|
||||
try
|
||||
{
|
||||
var intent = new Intent(activity, typeof(PodcastCaptureService)).PutExtra("microphone", microphone);
|
||||
var intent = new Intent(activity, typeof(PodcastCaptureService))
|
||||
.PutExtra("microphone", microphone).PutExtra("call", call);
|
||||
activity.StartForegroundService(intent);
|
||||
return await pending.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
|
|
@ -65,11 +67,13 @@ public sealed class PodcastCaptureService : Service
|
|||
PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
|
||||
var builder = new NotificationCompat.Builder(this, Channel);
|
||||
builder.SetSmallIcon(global::Android.Resource.Drawable.IcMenuCamera);
|
||||
builder.SetContentTitle("Podcast en direct");
|
||||
builder.SetContentText("Camera active. Toucher pour revenir au direct.");
|
||||
var call = intent?.GetBooleanExtra("call", false) == true;
|
||||
builder.SetContentTitle(call ? "Appel audio-video LAN/VPN" : "Podcast en direct");
|
||||
builder.SetContentText(call ? "Camera et microphone actifs. Toucher pour revenir a l'appel."
|
||||
: "Camera active. Toucher pour revenir au direct.");
|
||||
builder.SetContentIntent(open);
|
||||
builder.SetOngoing(true);
|
||||
builder.AddAction(global::Android.Resource.Drawable.IcMediaPause, "Arreter et publier", stop);
|
||||
builder.AddAction(global::Android.Resource.Drawable.IcMediaPause, call ? "Raccrocher" : "Arreter et publier", stop);
|
||||
var notification = builder.Build();
|
||||
var type = (ForegroundService)0;
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(30))
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@
|
|||
<OutputType>Exe</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Browser" />
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@
|
|||
See https://docs.avaloniaui.net/docs/guides/platforms/platform-specific-code/dotnet for more details.-->
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
|
|
|
|||
|
|
@ -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<CheckBox>(),
|
||||
control => Equals(control.Content, "Masquer mon adresse IP aux autres participants"));
|
||||
Assert.False(checkbox.IsEffectivelyEnabled);
|
||||
await vm.RefreshAsync();
|
||||
Assert.True(checkbox.IsEffectivelyEnabled);
|
||||
Assert.True(checkbox.IsChecked);
|
||||
checkbox.IsChecked = false;
|
||||
Assert.False(vm.HideIpAddressInCalls);
|
||||
Assert.Equal(false, vm.BuildProfileUpdateRequest().HideIpAddressInCalls);
|
||||
vm.IsBusy = true;
|
||||
Assert.False(checkbox.IsEffectivelyEnabled);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Profile_read_failure_prevents_saving_a_default_call_privacy_preference()
|
||||
{
|
||||
await using var api = new ProfileTransport("Performer") { FailProfile = true };
|
||||
var vm = new UserProfilePageViewModel(api);
|
||||
await vm.RefreshAsync();
|
||||
Assert.False(vm.IsProfileLoaded);
|
||||
Assert.False(vm.SaveProfileCommand.CanExecute(null));
|
||||
Assert.Contains("Impossible de charger le profil", vm.StatusMessage);
|
||||
}
|
||||
|
||||
internal sealed class ProfileTransport : YavscApiClient
|
||||
{
|
||||
private readonly string _tokenPath;
|
||||
|
|
@ -188,6 +242,7 @@ public class AdministrationAccessTests
|
|||
public Task<Me>? 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/"))
|
||||
{
|
||||
|
|
|
|||
158
src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs
Normal file
158
src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
#if ANDROID
|
||||
using System;
|
||||
using Stopwatch = System.Diagnostics.Stopwatch;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using LibVLCSharp.Shared;
|
||||
using PostIt.Android;
|
||||
using PostIt.Android.Services;
|
||||
using PostIt.Services;
|
||||
using Path = System.IO.Path;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
/// <summary>Debug-only physical camera/SRTP test; no account, API or media recording.</summary>
|
||||
[Activity(Name = "fr.pschneider.postit.LanCallTestActivity", Exported = true)]
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
public sealed class AndroidLanCallTestActivity : Activity
|
||||
{
|
||||
protected override async void OnCreate(Bundle? state)
|
||||
{
|
||||
base.OnCreate(state);
|
||||
var result = Path.Combine(FilesDir!.AbsolutePath, "lan-call-test-result.txt");
|
||||
File.WriteAllText(result, "RUNNING");
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(55));
|
||||
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true", timeout.Token);
|
||||
File.WriteAllText(result, outcome);
|
||||
}
|
||||
catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
|
||||
finally { Finish(); }
|
||||
}
|
||||
|
||||
private async Task<string> RunAsync(string result, bool wrongKey, CancellationToken ct)
|
||||
{
|
||||
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
|
||||
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View == null)
|
||||
await Task.Delay(100, ct);
|
||||
await Task.Delay(1000, ct);
|
||||
var fixture = Path.Combine(FilesDir!.AbsolutePath, "lan-call-fixture.ts");
|
||||
if (!File.Exists(fixture)) throw new IOException("Explicit H.264/AAC MPEG-TS fixture required.");
|
||||
using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
|
||||
await using var peer = new LibVlcLanCallMedia("127.0.0.1", 35102, headless: true);
|
||||
using var decoded = new DecodedFrames(peer.Receiver);
|
||||
AndroidLanCallMedia? call = null;
|
||||
Task? pump = null;
|
||||
using var sending = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var source = File.OpenRead(fixture);
|
||||
var app = (App)Avalonia.Application.Current!;
|
||||
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
|
||||
?? throw new InvalidOperationException("Main navigation unavailable.");
|
||||
var attached = false;
|
||||
try
|
||||
{
|
||||
await peer.StartReceivingAsync(ct);
|
||||
await Dispatcher.UIThread.InvokeAsync(async () =>
|
||||
{
|
||||
call = new AndroidLanCallMedia("127.0.0.1", 35100);
|
||||
var grid = new Grid { RowDefinitions = new RowDefinitions("*,*") };
|
||||
grid.Children.Add(call.LocalVideo);
|
||||
Grid.SetRow(call.RemoteVideo, 1);
|
||||
grid.Children.Add(call.RemoteVideo);
|
||||
await navigation.PushAsync(new ContentPage { Content = grid });
|
||||
attached = true;
|
||||
});
|
||||
if (call == null) throw new InvalidOperationException("Call UI not created.");
|
||||
File.WriteAllText(result, "RUNNING\nstage=return source pump");
|
||||
pump = Task.Run(async () =>
|
||||
{
|
||||
var buffer = new byte[1316];
|
||||
while (await source.ReadAsync(buffer, sending.Token) is var count && count > 0)
|
||||
{
|
||||
await pipe.WriteAsync(buffer.AsMemory(0, count), sending.Token);
|
||||
await Task.Delay(4, sending.Token);
|
||||
}
|
||||
}, ct);
|
||||
File.WriteAllText(result, "RUNNING\nstage=return SRTP sender");
|
||||
await peer.StartEncodedSendingAsync(call.Endpoint,
|
||||
pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
|
||||
File.WriteAllText(result, "RUNNING\nstage=enumerating cameras");
|
||||
var devices = AndroidLanCallMedia.GetDevices();
|
||||
var front = devices.Cameras.FirstOrDefault(c => c.Name == "Camera avant")
|
||||
?? throw new InvalidOperationException("Front camera required; no rear-camera fallback.");
|
||||
var endpoint = wrongKey ? peer.Endpoint with { Key = new string('0', 32) } : peer.Endpoint;
|
||||
File.WriteAllText(result, "RUNNING\nstage=front camera and SRTP");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => call.StartSendingAsync(endpoint, front.Value, "microphone", ct));
|
||||
File.WriteAllText(result, "RUNNING\nstage=receiving camera and return media");
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 10 : 25))
|
||||
{
|
||||
if (call.Completion.IsCompleted) await call.Completion;
|
||||
if (peer.Completion.IsCompleted) await peer.Completion;
|
||||
if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(10) &&
|
||||
decoded.Frames >= 100 && decoded.Samples > 144000 && call.HasRemoteMedia) break;
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
if (!call.HasRemoteMedia) throw new IOException("Android did not decode return audio/video.");
|
||||
if (wrongKey ? decoded.Frames != 0 || decoded.Samples != 0
|
||||
: decoded.Frames < 100 || decoded.Samples <= 144000)
|
||||
throw new IOException($"Unexpected camera decode: frames={decoded.Frames}, samples={decoded.Samples}.");
|
||||
return $"PASS\nfrontCamera=true\nwrongKey={wrongKey}\n" +
|
||||
$"cameraFrames={decoded.Frames}\ncameraAudioSamples={decoded.Samples}\nelapsedMs={elapsed.ElapsedMilliseconds}\nreturnAudioVideo=true\n" +
|
||||
"transport=SRTP/UDP loopback\npreview=attached\nsource=camera+microphone,return=explicit fixture\ncleanup=complete";
|
||||
}
|
||||
finally
|
||||
{
|
||||
sending.Cancel();
|
||||
File.WriteAllText(result, "RUNNING\nstage=stop return source");
|
||||
if (pump != null)
|
||||
{
|
||||
try { await pump; }
|
||||
catch (System.OperationCanceledException) when (sending.IsCancellationRequested) { }
|
||||
}
|
||||
File.WriteAllText(result, "RUNNING\nstage=dispose call");
|
||||
if (call != null) await Dispatcher.UIThread.InvokeAsync(async () => await call.DisposeAsync());
|
||||
File.WriteAllText(result, "RUNNING\nstage=stop return peer");
|
||||
await peer.StopAsync();
|
||||
source.Dispose();
|
||||
File.WriteAllText(result, "RUNNING\nstage=detach test page");
|
||||
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DecodedFrames : IDisposable
|
||||
{
|
||||
private readonly MediaPlayer _player;
|
||||
private readonly IntPtr _buffer = Marshal.AllocHGlobal(640 * 640 * 4);
|
||||
private int _frames;
|
||||
private long _samples;
|
||||
public int Frames => Volatile.Read(ref _frames);
|
||||
public long Samples => Interlocked.Read(ref _samples);
|
||||
public DecodedFrames(MediaPlayer player)
|
||||
{
|
||||
_player = player;
|
||||
player.SetVideoFormat("RV32", 640, 640, 640 * 4);
|
||||
player.SetVideoCallbacks((_, planes) =>
|
||||
{
|
||||
Marshal.WriteIntPtr(planes, _buffer);
|
||||
return IntPtr.Zero;
|
||||
}, null, (_, _) => Interlocked.Increment(ref _frames));
|
||||
player.SetAudioFormat("S16N", 48000, 1);
|
||||
player.SetAudioCallbacks((_, _, count, _) => Interlocked.Add(ref _samples, count),
|
||||
null, null, null, null);
|
||||
}
|
||||
public void Dispose() { _player.Stop(); Marshal.FreeHGlobal(_buffer); }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
|
@ -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()
|
||||
{
|
||||
|
|
|
|||
60
src/PostIt/PostIt.Tests/CallSignalingClientTests.cs
Normal file
60
src/PostIt/PostIt.Tests/CallSignalingClientTests.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using PostIt.Services;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class CallSignalingClientTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task All_operations_fail_explicitly_without_a_connected_chat_transport()
|
||||
{
|
||||
await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
|
||||
using var client = new CallSignalingClient(connection);
|
||||
var id = Guid.NewGuid();
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.InviteAsync("General", "bob", ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.InviteLanAsync("General", "bob", ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.AcceptAsync(id, ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.EndAsync(id, ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(id, new("offer", "sdp"), ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disposing_call_subscriptions_does_not_dispose_the_chat_connection()
|
||||
{
|
||||
await using var connection = new HubConnectionBuilder().WithUrl("http://127.0.0.1:1/chathub").Build();
|
||||
var client = new CallSignalingClient(connection);
|
||||
client.Dispose();
|
||||
client.Dispose();
|
||||
await Assert.ThrowsAsync<ObjectDisposedException>(() => client.AcceptAsync(Guid.NewGuid(), TestContext.Current.CancellationToken));
|
||||
Assert.Equal(HubConnectionState.Disconnected, connection.State);
|
||||
using var replacement = new CallSignalingClient(connection);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => replacement.InviteAsync("General", "bob", TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Shared_contracts_round_trip_with_signalr_web_json_naming()
|
||||
{
|
||||
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
|
||||
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", true,
|
||||
DateTimeOffset.Parse("2026-10-26T01:00:00Z"));
|
||||
var ready = new CallAccepted(call, [new(["turns:turn.example.test:5349"], "expires:nonce", "credential")]);
|
||||
var json = JsonSerializer.Serialize(ready, options);
|
||||
var read = JsonSerializer.Deserialize<CallAccepted>(json, options);
|
||||
Assert.NotNull(read);
|
||||
Assert.Equal(call, read.Session);
|
||||
Assert.Equal(ready.IceServers[0].Urls, read.IceServers[0].Urls);
|
||||
Assert.Equal(ready.IceServers[0].Username, read.IceServers[0].Username);
|
||||
Assert.Equal(ready.IceServers[0].Credential, read.IceServers[0].Credential);
|
||||
var signal = new CallSignal("candidate", Candidate: "candidate:1 1 udp 100 192.0.2.1 5000 typ relay",
|
||||
SdpMid: "video", SdpMLineIndex: 1);
|
||||
Assert.Equal(signal, JsonSerializer.Deserialize<CallSignal>(JsonSerializer.Serialize(signal, options), options));
|
||||
var lan = call with { RelayOnly = false, Transport = CallTransports.LanSrtp };
|
||||
Assert.Equal(lan, JsonSerializer.Deserialize<CallSession>(JsonSerializer.Serialize(lan, options), options));
|
||||
var endpoint = new CallSignal("rtp-endpoint",
|
||||
Endpoint: new("192.168.1.2", 5004, new string('a', 32), new string('b', 28)));
|
||||
Assert.Equal(endpoint, JsonSerializer.Deserialize<CallSignal>(JsonSerializer.Serialize(endpoint, options), options));
|
||||
}
|
||||
}
|
||||
243
src/PostIt/PostIt.Tests/LanCallViewModelTests.cs
Normal file
243
src/PostIt/PostIt.Tests/LanCallViewModelTests.cs
Normal file
|
|
@ -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<string, int, ILanCallMedia> create)
|
||||
{
|
||||
var vm = new LanCallViewModel(signaling, create)
|
||||
{
|
||||
Address = "127.0.0.1", Camera = new("Camera", "/dev/video0"),
|
||||
Microphone = new("Micro", "default"), AllowAddressDisclosure = true,
|
||||
Room = "General", Target = "bob"
|
||||
};
|
||||
vm.Addresses.Add("127.0.0.1");
|
||||
return vm;
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia();
|
||||
var created = 0;
|
||||
await using var vm = Configure(signaling, (_, _) => { created++; return media; });
|
||||
signaling.Invite(vm, signaling.Call);
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
Assert.Equal(0, created);
|
||||
Assert.Empty(signaling.Sent);
|
||||
await vm.AcceptCommand.ExecuteAsync(null);
|
||||
await WaitAsync(() => vm.LocalVideo != null);
|
||||
Assert.Equal(1, created);
|
||||
Assert.False(media.Sending);
|
||||
Assert.Single(signaling.Sent);
|
||||
Assert.Equal("rtp-endpoint", signaling.Sent[0].Kind);
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await WaitAsync(() => media.Sending);
|
||||
Assert.Same(media.LocalVideo, vm.LocalVideo);
|
||||
Assert.Same(media.RemoteVideo, vm.RemoteVideo);
|
||||
await vm.HangupAsync();
|
||||
Assert.True(media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Null(vm.LocalVideo);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Caller_waits_for_consent_and_interruption_releases_media_without_reconnecting()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia();
|
||||
var created = 0;
|
||||
await using var vm = Configure(signaling, (_, _) => { created++; return media; });
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
Assert.True(vm.Busy);
|
||||
Assert.Equal(0, created);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => vm.LocalVideo != null);
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await WaitAsync(() => media.Sending);
|
||||
signaling.Disconnect();
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Null(vm.RemoteVideo);
|
||||
Assert.Contains("interrompue", vm.Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Missing_disclosure_consent_or_devices_blocks_the_invitation()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
await using var vm = Configure(signaling, (_, _) => throw new Exception("Must not capture"));
|
||||
vm.AllowAddressDisclosure = false;
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
Assert.Equal(0, signaling.Invites);
|
||||
Assert.Contains("Confirmez", vm.Status);
|
||||
vm.AllowAddressDisclosure = true;
|
||||
vm.Camera = null;
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
Assert.Equal(0, signaling.Invites);
|
||||
Assert.Contains("camera", vm.Status);
|
||||
Assert.False(vm.Busy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Refusal_never_creates_media_and_late_signals_cannot_restart_capture()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var created = 0;
|
||||
await using var vm = Configure(signaling, (_, _) => { created++; return new FakeMedia(); });
|
||||
signaling.Invite(vm, signaling.Call);
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
await vm.HangupAsync();
|
||||
signaling.Ready();
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await Task.Delay(30, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0, created);
|
||||
Assert.False(vm.Busy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Platform_devices_and_factory_are_used_and_backgrounding_ends_capture()
|
||||
{
|
||||
var previousDevices = Platform.GetLanCallDevices;
|
||||
var previousFactory = Platform.CreateLanCallMedia;
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia();
|
||||
var creations = 0;
|
||||
try
|
||||
{
|
||||
Platform.GetLanCallDevices = () => new(
|
||||
[new("Camera avant", "front"), new("Camera arriere", "rear")],
|
||||
[new("Sans microphone", ""), new("Microphone Android", "microphone")]);
|
||||
Platform.CreateLanCallMedia = (_, _) => { creations++; return media; };
|
||||
await using var vm = new LanCallViewModel(signaling);
|
||||
vm.RefreshDevicesCommand.Execute(null);
|
||||
Assert.Equal("front", vm.Camera?.Value);
|
||||
Assert.Equal("microphone", vm.Microphone?.Value);
|
||||
Assert.Single(vm.Microphones);
|
||||
Assert.Equal(0, creations);
|
||||
signaling.Invite(vm, signaling.Call);
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
Assert.True(vm.CanConfigure);
|
||||
vm.RefreshDevicesCommand.Execute(null);
|
||||
Assert.Equal("front", vm.Camera?.Value);
|
||||
vm.Address = "127.0.0.1";
|
||||
if (!vm.Addresses.Contains(vm.Address)) vm.Addresses.Add(vm.Address);
|
||||
vm.AllowAddressDisclosure = true;
|
||||
vm.Room = "General";
|
||||
vm.Target = "bob";
|
||||
await vm.AcceptCommand.ExecuteAsync(null);
|
||||
await WaitAsync(() => vm.LocalVideo != null);
|
||||
Assert.Equal(1, creations);
|
||||
Assert.False(vm.CanConfigure);
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await WaitAsync(() => media.Sending);
|
||||
Platform.SuspendPlayback();
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
Platform.ResumePlayback();
|
||||
await Task.Delay(30, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, creations);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Platform.GetLanCallDevices = previousDevices;
|
||||
Platform.CreateLanCallMedia = previousFactory;
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Hangup_cancels_pending_native_start_without_waiting_for_startup_timeout()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia { DelayStartup = true };
|
||||
await using var vm = Configure(signaling, (_, _) => media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => vm.LocalVideo != null);
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await WaitAsync(() => media.Sending);
|
||||
await vm.HangupAsync().WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
|
||||
Assert.True(media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Media_failure_ends_the_call_and_disposes_capture()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia();
|
||||
await using var vm = Configure(signaling, (_, _) => media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => vm.LocalVideo != null);
|
||||
media.Fail();
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains("test media failure", vm.Status);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
private static async Task WaitAsync(Func<bool> condition)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
while (!condition()) await Task.Delay(10, timeout.Token);
|
||||
}
|
||||
|
||||
private sealed class FakeMedia : ILanCallMedia
|
||||
{
|
||||
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Control LocalVideo { get; } = new Border();
|
||||
public Control RemoteVideo { get; } = new Border();
|
||||
public LanCallEndpoint Endpoint { get; } = new("127.0.0.1", 5004, new string('a', 32), new string('b', 28));
|
||||
public Task Completion => _completion.Task;
|
||||
public bool HasRemoteMedia => false;
|
||||
public bool Sending { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
public bool DelayStartup { get; init; }
|
||||
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
|
||||
{
|
||||
Sending = true;
|
||||
if (DelayStartup) await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
public void Fail() => _completion.TrySetException(new IOException("test media failure"));
|
||||
public ValueTask DisposeAsync() { Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
|
||||
private sealed class Signaling : ILanCallSignaling
|
||||
{
|
||||
public event Action<CallSession>? Invitation;
|
||||
public event Action<CallAccepted>? Accepted;
|
||||
public event Action<CallEnded>? Ended;
|
||||
public event Action<Guid, CallSignal>? Signal;
|
||||
public event Action? Interrupted;
|
||||
public CallSession Call { get; } = Session();
|
||||
public List<CallSignal> Sent { get; } = [];
|
||||
public List<Guid> EndedCalls { get; } = [];
|
||||
public int Invites { get; private set; }
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default)
|
||||
{ Invites++; return Task.FromResult(Call); }
|
||||
public Task AcceptAsync(Guid id, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
|
||||
public Task EndAsync(Guid id, CancellationToken ct = default)
|
||||
{ EndedCalls.Add(id); Ended?.Invoke(new(id, "hangup")); return Task.CompletedTask; }
|
||||
public Task SendAsync(Guid id, CallSignal signal, CancellationToken ct = default)
|
||||
{ Sent.Add(signal); return Task.CompletedTask; }
|
||||
public void Invite(LanCallViewModel _, CallSession call) => Invitation?.Invoke(call);
|
||||
public void Ready() => Accepted?.Invoke(new(Call, []));
|
||||
public void RemoteEndpoint(Guid id) => Signal?.Invoke(id, new("rtp-endpoint",
|
||||
Endpoint: new("127.0.0.1", 5006, new string('c', 32), new string('d', 28))));
|
||||
public void Disconnect() => Interrupted?.Invoke();
|
||||
}
|
||||
}
|
||||
190
src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs
Normal file
190
src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs
Normal file
|
|
@ -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<SocketException>(() => 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
72
src/PostIt/PostIt.Tests/PerformerDonationSettingsTests.cs
Normal file
72
src/PostIt/PostIt.Tests/PerformerDonationSettingsTests.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
using Avalonia.Controls;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels;
|
||||
using PostIt.Views;
|
||||
using Yavsc.Abstract.Workflow;
|
||||
using Yavsc.Api.Client;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class PerformerDonationSettingsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("performer@payments.example", "performer@payments.example")]
|
||||
[InlineData(" performer@payments.example ", "performer@payments.example")]
|
||||
[InlineData("", "")]
|
||||
public void Performer_editor_includes_the_paypal_recipient_in_the_save_payload(string value, string expected)
|
||||
{
|
||||
var vm = new PerformerConfigurationPageViewModel { DonationPayPalEmail = value };
|
||||
Assert.Equal(expected, vm.BuildPerformerProfileSettings().DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Performer_editor_loads_displays_edits_and_saves_the_private_recipient()
|
||||
{
|
||||
var tokenPath = Path.Combine(Path.GetTempPath(), "postit-donation-" + Guid.NewGuid().ToString("N") + ".json");
|
||||
try
|
||||
{
|
||||
await using var api = new PerformerApi(tokenPath);
|
||||
var vm = new PerformerConfigurationPageViewModel(api, new ActivityApiClient(api, api.Settings.ApiUrl));
|
||||
await vm.RefreshAsync();
|
||||
Assert.Equal("initial@payments.example", vm.DonationPayPalEmail);
|
||||
var page = new PerformerConfigurationPage { DataContext = vm };
|
||||
var input = page.FindControl<TextBox>("DonationPayPalEmailInput")!;
|
||||
Assert.Equal("initial@payments.example", input.Text);
|
||||
input.Text = "updated@payments.example";
|
||||
Assert.Equal("updated@payments.example", vm.DonationPayPalEmail);
|
||||
await vm.SaveAsync();
|
||||
Assert.Equal("updated@payments.example", api.Saved?.DonationPayPalEmail);
|
||||
input.Text = "";
|
||||
await vm.SaveAsync();
|
||||
Assert.Equal("", api.Saved?.DonationPayPalEmail);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(tokenPath)) File.Delete(tokenPath);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PerformerApi(string tokenPath) : YavscApiClient(new Settings
|
||||
{
|
||||
Authentication = new AuthenticationSettings
|
||||
{
|
||||
Authority = "https://org.example.test", ClientId = "postit", Scopes = ["openid", "api"]
|
||||
}
|
||||
}, new TokenStore(tokenPath))
|
||||
{
|
||||
public PerformerProfileSettings? Saved { get; private set; }
|
||||
|
||||
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
{
|
||||
if (typeof(T) == typeof(List<ActivityInfo>))
|
||||
return Task.FromResult((T)(object)new List<ActivityInfo>());
|
||||
Assert.EndsWith("/account/performer-profile", path);
|
||||
if (method == HttpMethod.Put) Saved = Assert.IsType<PerformerProfileSettings>(body);
|
||||
return Task.FromResult((T)(object)new PerformerProfileSettings
|
||||
{
|
||||
PerformerId = "author", DonationPayPalEmail = "initial@payments.example"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,10 +6,10 @@
|
|||
<IsPackable>false</IsPackable>
|
||||
<RootNamespace>PostIt.Tests</RootNamespace>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@
|
|||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
|
|
|
|||
87
src/PostIt/PostIt/Services/CallSignalingClient.cs
Normal file
87
src/PostIt/PostIt/Services/CallSignalingClient.cs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
public sealed class CallSignalingClient : ILanCallSignaling, IDisposable
|
||||
{
|
||||
private readonly HubConnection _connection;
|
||||
private readonly IDisposable[] _subscriptions;
|
||||
private bool _disposed;
|
||||
|
||||
public event Action<CallSession>? Invitation;
|
||||
public event Action<CallAccepted>? Accepted;
|
||||
public event Action<CallEnded>? Ended;
|
||||
public event Action<Guid, CallSignal>? Signal;
|
||||
public event Action? Interrupted;
|
||||
|
||||
public CallSignalingClient(HubConnection connection)
|
||||
{
|
||||
_connection = connection;
|
||||
_subscriptions =
|
||||
[
|
||||
connection.On<CallSession>(CallHubMethods.Invitation, call => Invitation?.Invoke(call)),
|
||||
connection.On<CallAccepted>(CallHubMethods.Accepted, call => Accepted?.Invoke(call)),
|
||||
connection.On<CallEnded>(CallHubMethods.Ended, call => Ended?.Invoke(call)),
|
||||
connection.On<Guid, CallSignal>(CallHubMethods.SignalReceived,
|
||||
(id, signal) => Signal?.Invoke(id, signal))
|
||||
];
|
||||
connection.Reconnecting += OnInterruptedAsync;
|
||||
connection.Closed += OnInterruptedAsync;
|
||||
}
|
||||
|
||||
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync<CallSession>(CallHubMethods.Invite, room, user, ct);
|
||||
}
|
||||
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLan, room, user, ct);
|
||||
}
|
||||
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync(CallHubMethods.Accept, callId, ct);
|
||||
}
|
||||
|
||||
public Task EndAsync(Guid callId, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync(CallHubMethods.End, callId, ct);
|
||||
}
|
||||
|
||||
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync(CallHubMethods.Signal, callId, signal, ct);
|
||||
}
|
||||
|
||||
private Task OnInterruptedAsync(Exception? error)
|
||||
{
|
||||
Interrupted?.Invoke();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void EnsureConnected()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_connection.State != HubConnectionState.Connected)
|
||||
throw new InvalidOperationException("La connexion de chat est interrompue ; l'appel ne peut pas continuer.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_connection.Reconnecting -= OnInterruptedAsync;
|
||||
_connection.Closed -= OnInterruptedAsync;
|
||||
foreach (var subscription in _subscriptions) subscription.Dispose();
|
||||
}
|
||||
}
|
||||
17
src/PostIt/PostIt/Services/ILanCallMedia.cs
Normal file
17
src/PostIt/PostIt/Services/ILanCallMedia.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
public interface ILanCallMedia : IAsyncDisposable
|
||||
{
|
||||
Control LocalVideo { get; }
|
||||
Control RemoteVideo { get; }
|
||||
LanCallEndpoint Endpoint { get; }
|
||||
Task Completion { get; }
|
||||
bool HasRemoteMedia { get; }
|
||||
Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct);
|
||||
}
|
||||
19
src/PostIt/PostIt/Services/ILanCallSignaling.cs
Normal file
19
src/PostIt/PostIt/Services/ILanCallSignaling.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
public interface ILanCallSignaling
|
||||
{
|
||||
event Action<CallSession>? Invitation;
|
||||
event Action<CallAccepted>? Accepted;
|
||||
event Action<CallEnded>? Ended;
|
||||
event Action<Guid, CallSignal>? Signal;
|
||||
event Action? Interrupted;
|
||||
Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default);
|
||||
Task AcceptAsync(Guid callId, CancellationToken ct = default);
|
||||
Task EndAsync(Guid callId, CancellationToken ct = default);
|
||||
Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -9,7 +9,7 @@ public sealed record CaptureDevice(string Name, string Value);
|
|||
public sealed record PodcastCaptureDevices(
|
||||
IReadOnlyList<CaptureDevice> Cameras, IReadOnlyList<CaptureDevice> Microphones);
|
||||
|
||||
/// <summary>A running encoder publishing closed segments and an atomic index.m3u8.</summary>
|
||||
/// <summary>A running camera/microphone encoder with an optional native preview.</summary>
|
||||
public interface IPodcastCapture : IAsyncDisposable
|
||||
{
|
||||
Task Completion { get; }
|
||||
|
|
|
|||
197
src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs
Normal file
197
src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs
Normal file
|
|
@ -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<LibVLC, Media> source,
|
||||
bool preview, CancellationToken ct, bool transcode = true)
|
||||
{
|
||||
if (!remote.IsValid())
|
||||
throw new ArgumentException("Destination SRTP LAN invalide.", nameof(remote));
|
||||
if (remote.Address == Endpoint.Address && remote.Port == Endpoint.Port)
|
||||
throw new ArgumentException("Les deux pairs doivent avoir des ports distincts sur une meme adresse.");
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_stop != null || _senderMedia != null)
|
||||
throw new InvalidOperationException("La capture de cet appel est deja demarree ou arretee.");
|
||||
_senderMedia = source(_senderVlc);
|
||||
ConfigureOutput(_senderMedia, remote, preview, transcode);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (!Sender.Play(_senderMedia))
|
||||
throw new InvalidOperationException("Capture SRTP impossible. Verifiez camera, microphone et encodeurs H.264/AAC.");
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public Task StartEncodedSendingAsync(LanCallEndpoint remote, int fileDescriptor, CancellationToken ct)
|
||||
{
|
||||
if (fileDescriptor < 0) throw new ArgumentOutOfRangeException(nameof(fileDescriptor));
|
||||
return StartSendingAsync(remote, vlc =>
|
||||
{
|
||||
var media = new Media(vlc, $"fd://{fileDescriptor}", FromType.FromLocation);
|
||||
media.AddOption(":demux=ts");
|
||||
media.AddOption(":live-caching=100");
|
||||
media.AddOption(":clock-jitter=0");
|
||||
return media;
|
||||
}, false, ct, transcode: false);
|
||||
}
|
||||
|
||||
internal static void ConfigureOutput(Media media, LanCallEndpoint remote, bool preview, bool transcode = true)
|
||||
{
|
||||
if (!remote.IsValid()) throw new ArgumentException("Destination SRTP invalide.");
|
||||
// Same capture/encoders as Podcasts, but no HLS files, segmentation or upload.
|
||||
var encoding = (transcode ? "transcode{vcodec=h264,venc=x264{preset=ultrafast,tune=zerolatency,keyint=30,bframes=0},"
|
||||
+ "vb=1200,fps=30,acodec=mp4a,ab=96,channels=1,samplerate=48000}:" : "")
|
||||
// Android LibVLC 3 crashes formatting the valueless rtcp-mux SDP attribute.
|
||||
+ $"rtp{{dst={remote.Address},port={remote.Port},mux=ts,"
|
||||
+ $"key={remote.Key},salt={remote.Salt},caching=50}}";
|
||||
media.AddOption(":sout=#" + (preview
|
||||
? $"duplicate{{dst=display{{noaudio}},dst=\"{encoding}\"}}" : encoding));
|
||||
}
|
||||
|
||||
private void OnSenderError(object? sender, EventArgs args) => _completion.TrySetException(
|
||||
new InvalidOperationException("Capture/encodage SRTP en echec. Verifiez les peripheriques et encodeurs."));
|
||||
|
||||
private void OnReceiverError(object? sender, EventArgs args) => _completion.TrySetException(
|
||||
new InvalidOperationException("Reception/decodage SRTP en echec. Verifiez le reseau LAN/VPN et les ports UDP."));
|
||||
|
||||
private void OnSenderEnded(object? sender, EventArgs args) => _completion.TrySetException(
|
||||
new InvalidOperationException("La source audio-video s'est terminee."));
|
||||
|
||||
private Task StopCoreAsync() => _stop ??= Task.Run(() =>
|
||||
{
|
||||
try { Sender.Stop(); }
|
||||
finally { Receiver.Stop(); }
|
||||
});
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!_disposed) await StopCoreAsync();
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Sender.EncounteredError -= OnSenderError;
|
||||
Receiver.EncounteredError -= OnReceiverError;
|
||||
Sender.EndReached -= OnSenderEnded;
|
||||
try { await StopCoreAsync(); }
|
||||
finally
|
||||
{
|
||||
Sender.Dispose();
|
||||
Receiver.Dispose();
|
||||
_senderMedia?.Dispose();
|
||||
_receiverMedia.Dispose();
|
||||
_senderVlc.Dispose();
|
||||
_receiverVlc.Dispose();
|
||||
_completion.TrySetResult();
|
||||
}
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
}
|
||||
105
src/PostIt/PostIt/Services/LinuxLanCallVideo.cs
Normal file
105
src/PostIt/PostIt/Services/LinuxLanCallVideo.cs
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using LibVLCSharp.Avalonia;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Services;
|
||||
|
||||
public sealed class LinuxLanCallVideo : ILanCallMedia
|
||||
{
|
||||
private readonly LibVlcLanCallMedia _media;
|
||||
private readonly VideoView _local;
|
||||
private readonly VideoView _remote;
|
||||
private readonly TaskCompletionSource _localReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private bool _receiverScheduled;
|
||||
private bool _localScheduled;
|
||||
private bool _disposed;
|
||||
private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public Control LocalVideo => _local;
|
||||
public Control RemoteVideo => _remote;
|
||||
public LanCallEndpoint Endpoint => _media.Endpoint;
|
||||
public Task Completion { get; }
|
||||
public bool HasRemoteMedia => !_disposed && _media.HasRemoteMedia;
|
||||
|
||||
public LinuxLanCallVideo(string localAddress, int port)
|
||||
{
|
||||
_media = new LibVlcLanCallMedia(localAddress, port);
|
||||
_local = new VideoView { MediaPlayer = _media.Sender, MinHeight = 140 };
|
||||
_remote = new VideoView { MediaPlayer = _media.Receiver, MinHeight = 260 };
|
||||
_local.LayoutUpdated += OnLocalLayout;
|
||||
_remote.LayoutUpdated += OnRemoteLayout;
|
||||
Completion = ObserveCompletionAsync();
|
||||
}
|
||||
|
||||
private async Task ObserveCompletionAsync()
|
||||
{
|
||||
var completed = await Task.WhenAny(_media.Completion, _failure.Task);
|
||||
await completed;
|
||||
}
|
||||
|
||||
private void OnLocalLayout(object? sender, EventArgs e)
|
||||
{
|
||||
if (_localScheduled || _disposed || !_local.IsEffectivelyVisible ||
|
||||
_local.Bounds.Width <= 0 || _local.Bounds.Height <= 0) return;
|
||||
_localScheduled = true;
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (_disposed) return;
|
||||
_local.TryUpdateNativeControlPosition();
|
||||
_localReady.TrySetResult();
|
||||
}, DispatcherPriority.Loaded);
|
||||
}
|
||||
|
||||
private void OnRemoteLayout(object? sender, EventArgs e)
|
||||
{
|
||||
if (_receiverScheduled || _disposed || !_remote.IsEffectivelyVisible ||
|
||||
_remote.Bounds.Width <= 0 || _remote.Bounds.Height <= 0) return;
|
||||
_receiverScheduled = true;
|
||||
Dispatcher.UIThread.Post(StartReceiver, DispatcherPriority.Loaded);
|
||||
}
|
||||
|
||||
private async void StartReceiver()
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
_remote.TryUpdateNativeControlPosition();
|
||||
await _media.StartReceivingAsync(_lifetime.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
|
||||
catch (Exception error) { _failure.TrySetException(error); }
|
||||
}
|
||||
|
||||
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
|
||||
{
|
||||
await _localReady.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
await _media.StartSendingAsync(remote, camera, microphone, ct);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_lifetime.Cancel();
|
||||
_localReady.TrySetCanceled();
|
||||
_local.LayoutUpdated -= OnLocalLayout;
|
||||
_remote.LayoutUpdated -= OnRemoteLayout;
|
||||
try { await _media.StopAsync(); }
|
||||
finally
|
||||
{
|
||||
_local.MediaPlayer = null;
|
||||
_remote.MediaPlayer = null;
|
||||
try { await _media.DisposeAsync(); }
|
||||
finally
|
||||
{
|
||||
_lifetime.Dispose();
|
||||
_failure.TrySetResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,8 @@ namespace PostIt.Services;
|
|||
/// </summary>
|
||||
public static class Platform
|
||||
{
|
||||
public static Func<PodcastCaptureDevices>? GetLanCallDevices { get; set; }
|
||||
public static Func<string, int, ILanCallMedia>? CreateLanCallMedia { get; set; }
|
||||
public static Func<PodcastCaptureDevices>? GetPodcastCaptureDevices { get; set; }
|
||||
public static Func<string?, CancellationToken, Task>? RequestPodcastPermissionsAsync { get; set; }
|
||||
public static Func<string, string?, string, CancellationToken, Task<IPodcastCapture>>? CreatePodcastCaptureAsync { get; set; }
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, string, string>("notifyUser", (type, user, msg) =>
|
||||
{
|
||||
|
|
|
|||
332
src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs
Normal file
332
src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs
Normal file
|
|
@ -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<string, int, ILanCallMedia> _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<string> Addresses { get; } = [];
|
||||
public ObservableCollection<CaptureDevice> Cameras { get; } = [];
|
||||
public ObservableCollection<CaptureDevice> 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<string, int, ILanCallMedia>? 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<Task> 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<Task> action) =>
|
||||
Dispatcher.UIThread.Post(async () => await RunAsync(action));
|
||||
|
||||
private async Task RunAsync(Func<Task> 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(); }
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
>
|
||||
<Design.DataContext>
|
||||
<vm:ChatViewModel />
|
||||
</Design.DataContext>
|
||||
|
||||
<Grid Margin="10" RowDefinitions="Auto, *, Auto, Auto">
|
||||
<Grid Margin="10" RowDefinitions="Auto, *, Auto, Auto, Auto">
|
||||
|
||||
<Grid
|
||||
Grid.Row="1"
|
||||
|
|
@ -102,9 +103,55 @@
|
|||
Content="Envoyer" />
|
||||
</Grid>
|
||||
|
||||
<Expander Grid.Row="3" Header="Appel direct (LAN/VPN)" IsVisible="{Binding SupportsLanCalls}" IsExpanded="True"
|
||||
IsEnabled="{Binding IsConnected}" Margin="0,0,0,8">
|
||||
<ScrollViewer MaxHeight="520">
|
||||
<StackPanel DataContext="{Binding LanCall}" x:DataType="vm:LanCallViewModel" Spacing="8">
|
||||
<TextBlock Text="Android et Desktop Linux sur LAN/VPN. SRTP chiffre les medias ; le pair connait votre IP. Ouvrir le port UDP choisi et le suivant. Sans TURN ni traversee NAT. Casque recommande (pas d'annulation d'echo)."
|
||||
TextWrapping="Wrap" />
|
||||
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
|
||||
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
|
||||
<ComboBox Width="160" ItemsSource="{Binding Addresses}" SelectedItem="{Binding Address}"
|
||||
PlaceholderText="Adresse locale LAN/VPN" Margin="0,0,8,4" />
|
||||
<TextBox Width="80" Text="{Binding Port}" PlaceholderText="Port pair" Margin="0,0,8,4" />
|
||||
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
|
||||
PlaceholderText="Camera" Margin="0,0,8,4">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice">
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<ComboBox Width="190" ItemsSource="{Binding Microphones}" SelectedItem="{Binding Microphone}"
|
||||
PlaceholderText="Microphone" Margin="0,0,8,4">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice">
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<TextBox Width="170" Text="{Binding Target}" PlaceholderText="Pseudo du pair" Margin="0,0,8,4" />
|
||||
</WrapPanel>
|
||||
<CheckBox Content="Je consens a partager mon adresse LAN/VPN avec le pair."
|
||||
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
|
||||
IsVisible="{Binding !RemoteVideo}" />
|
||||
<WrapPanel>
|
||||
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
|
||||
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
|
||||
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
|
||||
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
|
||||
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
|
||||
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Expander>
|
||||
|
||||
<postitControls:StatusBar
|
||||
x:Name="StatusBar"
|
||||
Grid.Row="3"
|
||||
Grid.Row="4"
|
||||
DataContext="{Binding Status}" />
|
||||
|
||||
</Grid>
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,16 @@
|
|||
<TextBox Text="{Binding Website, Mode=TwoWay}"
|
||||
PlaceholderText="Site web"/>
|
||||
|
||||
<TextBlock Text="Dons PayPal" FontWeight="SemiBold"/>
|
||||
<TextBlock Text="Adresse e-mail PayPal du bénéficiaire"/>
|
||||
<TextBox x:Name="DonationPayPalEmailInput"
|
||||
Text="{Binding DonationPayPalEmail, Mode=TwoWay}"
|
||||
PlaceholderText="Adresse e-mail de votre compte PayPal"
|
||||
MaxLength="127"
|
||||
IsEnabled="{Binding !IsBusy}"/>
|
||||
<TextBlock Text="Les dons sont versés directement sur ce compte PayPal. Vérifiez l’adresse. Laissez vide pour désactiver les nouveaux dons, puis enregistrez. Le profil doit être actif pour proposer les dons."
|
||||
TextWrapping="Wrap"/>
|
||||
|
||||
<CheckBox Content="Disponible / actif"
|
||||
IsChecked="{Binding Active, Mode=TwoWay}"/>
|
||||
<CheckBox Content="Accepter les notifications"
|
||||
|
|
|
|||
|
|
@ -136,6 +136,16 @@
|
|||
TextWrapping="Wrap"/>
|
||||
</Grid>
|
||||
|
||||
<StackPanel Spacing="4" IsEnabled="{Binding IsProfileLoaded}">
|
||||
<TextBlock Text="Confidentialité des futurs appels audio-vidéo"
|
||||
FontWeight="SemiBold"/>
|
||||
<CheckBox Content="Masquer mon adresse IP aux autres participants"
|
||||
IsChecked="{Binding HideIpAddressInCalls, Mode=TwoWay}"
|
||||
IsEnabled="{Binding !IsBusy}"/>
|
||||
<TextBlock Text="Préférence enregistrée avec le profil et partagée entre vos appareils. Les appels ne sont pas encore disponibles. Lors de leur mise en service, cette option imposera un relais TURN, avec une latence potentiellement accrue ; les serveurs contactés pourront toujours connaître votre adresse IP."
|
||||
TextWrapping="Wrap"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
|
||||
<Button x:Name="ChooseAvatarButton"
|
||||
Content="Choisir un avatar"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,46 @@
|
|||
x:Class="PostIt.Views.PodcastsPage"
|
||||
x:DataType="vm:PodcastsPageViewModel"
|
||||
Header="Podcasts">
|
||||
<ContentPage.Styles>
|
||||
<Style Selector="Border.warning-danger">
|
||||
<Setter Property="Background" Value="#862C05"/>
|
||||
<Setter Property="BorderBrush" Value="#A5EDC2"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="CornerRadius" Value="8"/>
|
||||
<Setter Property="Padding" Value="12"/>
|
||||
</Style>
|
||||
<Style Selector="TextBlock.warning-danger">
|
||||
<Setter Property="Background" Value="#862C05"/>
|
||||
<Setter Property="Foreground" Value="#AAFF00"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="TextBlock.warning-title">
|
||||
<Setter Property="Background" Value="#862C05"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="CheckBox.warning-check">
|
||||
<Setter Property="Background" Value="#862C05"/>
|
||||
<Setter Property="Foreground" Value="#FFF7F4"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Button.delete-danger">
|
||||
<Setter Property="Background" Value="#862C05"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
<Setter Property="CornerRadius" Value="6"/>
|
||||
<Setter Property="Padding" Value="10,8"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Button.delete-danger:pointerover">
|
||||
<Setter Property="Background" Value="#FFCB64"/>
|
||||
<Setter Property="Foreground" Value="#03963E"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Button.delete-danger:disabled">
|
||||
<Setter Property="Opacity" Value="0.55"/>
|
||||
</Style>
|
||||
</ContentPage.Styles>
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="16" Spacing="12" MaxWidth="900">
|
||||
<TextBlock Text="Podcasts : directs et replays" FontSize="22" />
|
||||
|
|
@ -57,10 +97,20 @@
|
|||
<Button Content="Terminer mon direct selectionne" Command="{Binding FinishCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Relancer la preparation MP4" Command="{Binding RetryReplayCommand}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<CheckBox x:Name="ConfirmDelete" Content="Confirmer la suppression du replay selectionne" />
|
||||
<Button Content="Supprimer mon replay" Command="{Binding DeleteCommand}" IsEnabled="{Binding #ConfirmDelete.IsChecked}" />
|
||||
</StackPanel>
|
||||
<Border Classes="warning-danger">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Classes="warning-title" Text="⚠ Suppression du replay" />
|
||||
<TextBlock Text="Cette action supprime définitivement le replay sélectionné. Cette opération est irréversible."
|
||||
TextWrapping="Wrap" />
|
||||
<CheckBox x:Name="ConfirmDelete"
|
||||
Classes="warning-check"
|
||||
Content="Je confirme la suppression du replay sélectionné" />
|
||||
<Button Classes="delete-danger"
|
||||
Content="Supprimer mon replay"
|
||||
Command="{Binding DeleteCommand}"
|
||||
IsEnabled="{Binding #ConfirmDelete.IsChecked}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</ContentPage>
|
||||
|
|
@ -172,15 +172,6 @@ public partial class VideoPage : ContentPage
|
|||
|
||||
private void PodcastFailed(string message) => Dispatcher.UIThread.Post(() => PlaybackStatus.Text = message);
|
||||
|
||||
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)
|
||||
&& !source.AbsolutePath.Contains("/api/", StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.Equals(source.Scheme, "about", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private void Player_EncounteredError(object? sender, EventArgs e)
|
||||
=> Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
|
|
@ -208,15 +199,15 @@ public partial class VideoPage : ContentPage
|
|||
return;
|
||||
try
|
||||
{
|
||||
if (!CanLaunchExternally(vm.Source))
|
||||
if (!vm.CanOpenExternal)
|
||||
{
|
||||
PlaybackStatus.Text = "Ce flux interne ne peut pas être ouvert dans le navigateur.";
|
||||
PlaybackStatus.Text = "Cette ressource ne peut pas être ouverte dans le navigateur.";
|
||||
return;
|
||||
}
|
||||
|
||||
var topLevel = TopLevel.GetTopLevel(this)
|
||||
?? throw new InvalidOperationException("La fenêtre de lecture est indisponible.");
|
||||
if (!await topLevel.Launcher.LaunchUriAsync(vm.Source))
|
||||
if (!await topLevel.Launcher.LaunchUriAsync(vm.ExternalUri))
|
||||
PlaybackStatus.Text = "Impossible d'ouvrir le navigateur.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
61
src/Yavsc.Abstract/Chat/Calls/CallContracts.cs
Normal file
61
src/Yavsc.Abstract/Chat/Calls/CallContracts.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
#nullable enable
|
||||
|
||||
namespace Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
public static class CallHubMethods
|
||||
{
|
||||
public const string Invite = "InviteCall";
|
||||
public const string InviteLan = "InviteLanCall";
|
||||
public const string Accept = "AcceptCall";
|
||||
public const string End = "EndCall";
|
||||
public const string Signal = "SendCallSignal";
|
||||
public const string Invitation = "CallInvitation";
|
||||
public const string Accepted = "CallAccepted";
|
||||
public const string Ended = "CallEnded";
|
||||
public const string SignalReceived = "CallSignal";
|
||||
}
|
||||
|
||||
public sealed record CallSession(
|
||||
Guid Id, string RoomName, string Caller, string Callee, bool RelayOnly,
|
||||
DateTimeOffset ExpiresAt, string Transport = CallTransports.WebRtc);
|
||||
|
||||
public static class CallTransports
|
||||
{
|
||||
public const string WebRtc = "webrtc";
|
||||
public const string LanSrtp = "lan-srtp";
|
||||
}
|
||||
|
||||
public sealed record CallIceServer(string[] Urls, string? Username = null, string? Credential = null);
|
||||
|
||||
public sealed record CallAccepted(CallSession Session, CallIceServer[] IceServers);
|
||||
|
||||
public sealed record CallEnded(Guid CallId, string Reason);
|
||||
|
||||
public sealed record CallSignal(
|
||||
string Kind, string? Sdp = null, string? Candidate = null,
|
||||
string? SdpMid = null, int? SdpMLineIndex = null, LanCallEndpoint? Endpoint = null);
|
||||
|
||||
public sealed record LanCallEndpoint(string Address, int Port, string Key, string Salt)
|
||||
{
|
||||
public override string ToString() => "SRTP endpoint (credentials redacted)";
|
||||
|
||||
public bool IsValid() =>
|
||||
LanCallNetwork.IsPrivateIPv4(Address) && Port is >= 1024 and <= 65534 && Port % 2 == 0 &&
|
||||
Key is { Length: 32 } && Key.All(Uri.IsHexDigit) &&
|
||||
Salt is { Length: 28 } && Salt.All(Uri.IsHexDigit);
|
||||
}
|
||||
|
||||
public static class LanCallNetwork
|
||||
{
|
||||
public static bool IsPrivateIPv4(string address)
|
||||
{
|
||||
if (!System.Net.IPAddress.TryParse(address, out var ip) ||
|
||||
ip.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork ||
|
||||
ip.ToString() != address)
|
||||
return false;
|
||||
var bytes = ip.GetAddressBytes();
|
||||
return bytes[0] == 10 || bytes[0] == 127 ||
|
||||
(bytes[0] == 172 && bytes[1] is >= 16 and <= 31) ||
|
||||
(bytes[0] == 192 && bytes[1] == 168);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ namespace Yavsc.Abstract.Identity {
|
|||
{
|
||||
public bool EmailConfirmed { get; set; }
|
||||
public bool AllowMonthlyEmail { get; set; }
|
||||
public bool HideIpAddressInCalls { get; set; }
|
||||
public bool HasPassword { get; set; }
|
||||
public bool TwoFactorEnabled { get; set; }
|
||||
public int ExternalLoginCount { get; set; }
|
||||
|
|
|
|||
|
|
@ -9,4 +9,5 @@ public class ProfileUpdateRequest
|
|||
public string? Address { get; set; }
|
||||
public string? GoogleCalendarId { get; set; }
|
||||
public string? BankInfoSummary { get; set; }
|
||||
public bool? HideIpAddressInCalls { get; set; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Yavsc.Abstract.Workflow;
|
||||
|
||||
public sealed class PerformerProfileSettings
|
||||
|
|
@ -7,6 +11,9 @@ public sealed class PerformerProfileSettings
|
|||
public string ExerciseCountryCode { get; set; } = "fr";
|
||||
public string SIREN { get; set; } = string.Empty;
|
||||
public string WebSite { get; set; } = string.Empty;
|
||||
/// <summary>Owner-only PayPal recipient. Null preserves the existing setting; empty disables donations.</summary>
|
||||
[MaxLength(127)]
|
||||
public string? DonationPayPalEmail { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public bool AcceptNotifications { get; set; }
|
||||
public bool AcceptPublicContact { get; set; }
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@
|
|||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<Library>true</Library>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
|
@ -15,10 +15,10 @@
|
|||
</Description>
|
||||
<RepositoryUrl>https://github.com/pazof/yavsc</RepositoryUrl>
|
||||
<Library>true</Library>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Yavsc.Abstract/Yavsc.Abstract.csproj" />
|
||||
|
|
|
|||
|
|
@ -39,11 +39,12 @@ namespace Yavsc.WebApi.Controllers
|
|||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly ITrueEmailSender _emailSender;
|
||||
private readonly ICalendarManager _calendarManager;
|
||||
private readonly CallSignalingService _calls;
|
||||
|
||||
public ApiAccountController(
|
||||
ILoggerFactory loggerFactory, ApplicationDbContext dbContext,
|
||||
IOptions<SiteSettings> siteSettings, UserManager<ApplicationUser> userManager,
|
||||
ITrueEmailSender emailSender, ICalendarManager calendarManager)
|
||||
ITrueEmailSender emailSender, ICalendarManager calendarManager, CallSignalingService calls)
|
||||
{
|
||||
_logger = loggerFactory.CreateLogger(nameof(ApiAccountController));
|
||||
_dbContext = dbContext;
|
||||
|
|
@ -51,6 +52,7 @@ namespace Yavsc.WebApi.Controllers
|
|||
_userManager = userManager;
|
||||
_emailSender = emailSender;
|
||||
_calendarManager = calendarManager;
|
||||
_calls = calls;
|
||||
}
|
||||
|
||||
[HttpGet("me")]
|
||||
|
|
@ -86,7 +88,8 @@ namespace Yavsc.WebApi.Controllers
|
|||
Avatar = userData.Avatar,
|
||||
FullName = userData.FullName,
|
||||
Address = userData.PostalAddress?.Address ?? string.Empty,
|
||||
DedicatedGoogleCalendar = userData.DedicatedGoogleCalendar
|
||||
DedicatedGoogleCalendar = userData.DedicatedGoogleCalendar,
|
||||
HideIpAddressInCalls = userData.HideIpAddressInCalls
|
||||
};
|
||||
user.BankInfoSummary = userData.BankInfo is { Count: > 0 }
|
||||
? string.Join(" | ", userData.BankInfo.Select(b => string.IsNullOrWhiteSpace(b.IBAN) ? b.BIC : $"{b.IBAN} / {b.BIC}"))
|
||||
|
|
@ -151,6 +154,11 @@ namespace Yavsc.WebApi.Controllers
|
|||
return BadRequest(new { error = "Payload is required." });
|
||||
}
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (request.BankInfoSummary is not null)
|
||||
{
|
||||
return BadRequest(new { error = "Bank information must be managed through the bank-info endpoint." });
|
||||
|
|
@ -172,6 +180,8 @@ namespace Yavsc.WebApi.Controllers
|
|||
return NotFound();
|
||||
}
|
||||
|
||||
var previousUserName = user.UserName;
|
||||
var privacyActivated = request.HideIpAddressInCalls == true && !user.HideIpAddressInCalls;
|
||||
if (!string.IsNullOrWhiteSpace(request.UserName))
|
||||
{
|
||||
var trimmedUserName = request.UserName.Trim();
|
||||
|
|
@ -212,8 +222,16 @@ namespace Yavsc.WebApi.Controllers
|
|||
user.DedicatedGoogleCalendar = request.GoogleCalendarId.Trim();
|
||||
}
|
||||
|
||||
if (request.HideIpAddressInCalls is bool hideIpAddressInCalls)
|
||||
{
|
||||
user.HideIpAddressInCalls = hideIpAddressInCalls;
|
||||
}
|
||||
|
||||
await _dbContext.SaveChangesAsync(uid);
|
||||
return Ok(new { status = "saved", fullName = user.FullName, address = user.PostalAddress?.Address, googleCalendarId = user.DedicatedGoogleCalendar });
|
||||
if (previousUserName != null &&
|
||||
(privacyActivated || previousUserName != user.UserName))
|
||||
await _calls.EndForUserAsync(previousUserName, "profile-changed");
|
||||
return Ok(new { status = "saved", fullName = user.FullName, address = user.PostalAddress?.Address, googleCalendarId = user.DedicatedGoogleCalendar, hideIpAddressInCalls = user.HideIpAddressInCalls });
|
||||
}
|
||||
|
||||
[HttpPut("preferences/monthly-email")]
|
||||
|
|
@ -555,6 +573,7 @@ namespace Yavsc.WebApi.Controllers
|
|||
}
|
||||
|
||||
[HttpGet("performer-profile")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public async Task<IActionResult> GetPerformerProfile()
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
|
|
@ -580,6 +599,7 @@ namespace Yavsc.WebApi.Controllers
|
|||
ExerciseCountryCode = profile?.ExerciseCountryCode ?? "fr",
|
||||
SIREN = profile?.SIREN ?? string.Empty,
|
||||
WebSite = profile?.WebSite ?? string.Empty,
|
||||
DonationPayPalEmail = profile?.DonationPayPalEmail ?? string.Empty,
|
||||
Active = profile?.Active ?? false,
|
||||
AcceptNotifications = profile?.AcceptNotifications ?? false,
|
||||
AcceptPublicContact = profile?.AcceptPublicContact ?? false,
|
||||
|
|
@ -612,6 +632,20 @@ namespace Yavsc.WebApi.Controllers
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
return ValidationProblem(ModelState);
|
||||
if (model.DonationPayPalEmail is { } email)
|
||||
{
|
||||
model.DonationPayPalEmail = email.Trim();
|
||||
if (model.DonationPayPalEmail.Length > 0
|
||||
&& (model.DonationPayPalEmail.Length > 127
|
||||
|| !new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(model.DonationPayPalEmail)))
|
||||
{
|
||||
ModelState.AddModelError(nameof(model.DonationPayPalEmail), "Une adresse e-mail PayPal valide est requise.");
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
}
|
||||
|
||||
var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == uid);
|
||||
if (user is null)
|
||||
{
|
||||
|
|
@ -637,7 +671,7 @@ namespace Yavsc.WebApi.Controllers
|
|||
AcceptNotifications = model.AcceptNotifications,
|
||||
AcceptPublicContact = model.AcceptPublicContact,
|
||||
UseGeoLocalizationToReduceDistanceWithClients = model.UseGeoLocalizationToReduceDistanceWithClients,
|
||||
OrganizationAddress = new Yavsc.Models.Relationship.Location()
|
||||
OrganizationAddress = new Yavsc.Models.Relationship.Location { Address = string.Empty }
|
||||
};
|
||||
_dbContext.Performers.Add(profile);
|
||||
}
|
||||
|
|
@ -652,6 +686,9 @@ namespace Yavsc.WebApi.Controllers
|
|||
profile.UseGeoLocalizationToReduceDistanceWithClients = model.UseGeoLocalizationToReduceDistanceWithClients;
|
||||
}
|
||||
|
||||
if (model.DonationPayPalEmail != null)
|
||||
profile.DonationPayPalEmail = model.DonationPayPalEmail.Length == 0 ? null : model.DonationPayPalEmail;
|
||||
|
||||
var desiredCodes = (model.SelectedActivityCodes ?? [])
|
||||
.Where(code => !string.IsNullOrWhiteSpace(code))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
|
|
|
|||
|
|
@ -87,6 +87,11 @@ internal class Program
|
|||
.AddJsonProtocol(options =>
|
||||
options.PayloadSerializerOptions.IncludeFields = true);
|
||||
services.AddSingleton<IConnexionManager, HubConnectionManager>();
|
||||
services.Configure<AudioVideoCallOptions>(
|
||||
builder.Configuration.GetSection(AudioVideoCallOptions.SectionName));
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<CallSignalingService>();
|
||||
services.AddHostedService(provider => provider.GetRequiredService<CallSignalingService>());
|
||||
|
||||
// DbContextBuilder
|
||||
services.AddDbContext<ApplicationDbContext>(options =>
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@
|
|||
<UserSecretsId>1c73094f-959f-4211-b1a1-6a69b236c283</UserSecretsId>
|
||||
<RootNamespace>Yavsc.Api</RootNamespace>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@
|
|||
<RootNamespace>Yavsc.Blogs</RootNamespace>
|
||||
<RepositoryUrl>https://forgejo.pschneider.fr/notazof/yavsc</RepositoryUrl>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
|
|
|
|||
|
|
@ -664,8 +664,13 @@ namespace Yavsc.Controllers
|
|||
if (_dbContext.Performers.Any(p=>p.PerformerId == uid))
|
||||
{
|
||||
_dbContext.Update(model);
|
||||
_dbContext.Entry(model).Property(p => p.DonationPayPalEmail).IsModified = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
model.DonationPayPalEmail = null;
|
||||
_dbContext.Performers.Add(model);
|
||||
}
|
||||
else _dbContext.Performers.Add(model);
|
||||
_dbContext.SaveChanges(User.GetUserId());
|
||||
// Give this user the Performer role
|
||||
if (!User.IsInMsRole("Performer"))
|
||||
|
|
@ -716,6 +721,8 @@ namespace Yavsc.Controllers
|
|||
bool existing = _dbContext.Performers.Any(x => x.PerformerId == uid);
|
||||
if (existing)
|
||||
{
|
||||
if (await _dbContext.PerformerDonations.AnyAsync(d => d.PerformerId == uid))
|
||||
return Conflict("Ce profil a recu des dons et doit etre conserve pour leur suivi. Desactivez les nouveaux dons dans les parametres PayPal.");
|
||||
_dbContext.Performers.Remove(
|
||||
_dbContext.Performers.First(x => x.PerformerId == uid)
|
||||
);
|
||||
|
|
|
|||
232
src/Yavsc.Org/Controllers/DonationController.cs
Normal file
232
src/Yavsc.Org/Controllers/DonationController.cs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.ViewModels.Podcast;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[Authorize(Policy = "WebUser")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class DonationController(ApplicationDbContext db, IPayPalDonationGateway paypal,
|
||||
IOptions<SiteSettings> siteOptions, ILogger<DonationController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(CancellationToken ct)
|
||||
=> View(await db.PerformerDonations.AsNoTracking().Where(d => d.DonorId == User.GetUserId())
|
||||
.OrderByDescending(d => d.CreatedAt)
|
||||
.Join(db.Users, d => d.PerformerId, u => u.Id,
|
||||
(d, u) => new DonationDetailsViewModel(d, u.UserName ?? d.PerformerId)).ToArrayAsync(ct));
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Settings(CancellationToken ct)
|
||||
{
|
||||
var performer = await db.Performers.FindAsync([User.GetUserId()], ct);
|
||||
if (performer == null)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
ViewData["PaymentError"] = "Creez d'abord votre profil performer dans Mon compte > Parametres professionnels pour recevoir des dons.";
|
||||
return View("Error");
|
||||
}
|
||||
return View(new DonationSettingsViewModel { PayPalEmail = performer.DonationPayPalEmail });
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Settings(DonationSettingsViewModel model, CancellationToken ct)
|
||||
{
|
||||
var performer = await db.Performers.FindAsync([User.GetUserId()], ct);
|
||||
if (performer == null) return NotFound();
|
||||
if (!ModelState.IsValid) return View(model);
|
||||
performer.DonationPayPalEmail = string.IsNullOrWhiteSpace(model.PayPalEmail) ? null : model.PayPalEmail.Trim();
|
||||
await db.SaveChangesAsync(ct);
|
||||
TempData["DonationSettingsSaved"] = true;
|
||||
return RedirectToAction(nameof(Settings));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Create(string id, CancellationToken ct)
|
||||
{
|
||||
var performer = await RecipientAsync(id, ct);
|
||||
if (performer == null) return NotFound();
|
||||
return View(new CreateDonationViewModel { PerformerId = id, PerformerName = performer.Performer.UserName ?? id });
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create(CreateDonationViewModel model, CancellationToken ct)
|
||||
{
|
||||
var performer = await RecipientAsync(model.PerformerId, ct);
|
||||
if (performer == null) return NotFound();
|
||||
model.PerformerName = performer.Performer.UserName ?? performer.PerformerId;
|
||||
if (decimal.Round(model.Amount, 2) != model.Amount)
|
||||
ModelState.AddModelError(nameof(model.Amount), "Le montant doit avoir au maximum deux decimales.");
|
||||
if (!ModelState.IsValid) return View(model);
|
||||
var urls = PaymentUrls();
|
||||
var donation = new PerformerDonation
|
||||
{
|
||||
Id = Guid.NewGuid(), DonorId = User.GetUserId(), PerformerId = performer.PerformerId,
|
||||
RecipientEmail = performer.DonationPayPalEmail!, Amount = model.Amount, CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.PerformerDonations.Add(donation);
|
||||
await db.SaveChangesAsync(ct);
|
||||
donation.CheckoutToken = await paypal.CreateAsync(donation,
|
||||
urls.Return + donation.Id, urls.Cancel + donation.Id, urls.Notify, ct);
|
||||
donation.State = PerformerDonationState.AwaitingApproval;
|
||||
await SaveAsync(donation, ct);
|
||||
return Redirect(paypal.CheckoutUrl(donation.CheckoutToken));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Return(Guid id, string token, CancellationToken ct)
|
||||
{
|
||||
var donation = await OwnedAsync(id, ct);
|
||||
if (donation == null || string.IsNullOrWhiteSpace(token) || donation.CheckoutToken != token) return NotFound();
|
||||
if (donation.State == PerformerDonationState.AwaitingApproval)
|
||||
await paypal.ApproveAsync(donation, ct);
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
|
||||
{
|
||||
var donation = await OwnedAsync(id, ct);
|
||||
if (donation == null) return NotFound();
|
||||
var name = await db.Users.Where(u => u.Id == donation.PerformerId).Select(u => u.UserName).SingleAsync(ct);
|
||||
return View(new DonationDetailsViewModel(donation, name ?? donation.PerformerId));
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Confirm(Guid id, CancellationToken ct)
|
||||
{
|
||||
var donation = await OwnedAsync(id, ct);
|
||||
if (donation == null) return NotFound();
|
||||
if (donation.State == PerformerDonationState.Completed)
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
if (donation.State != PerformerDonationState.AwaitingApproval)
|
||||
throw new DonationPaymentException(409, "Ce paiement est deja traite ou en cours de verification. Ne creez pas un second don.");
|
||||
var approval = await paypal.ApproveAsync(donation, ct);
|
||||
donation.State = PerformerDonationState.Processing;
|
||||
await SaveAsync(donation, ct);
|
||||
var receipt = await paypal.CaptureAsync(donation, approval.PayerId, ct);
|
||||
// An IPN may have confirmed the payment while the capture request was in flight.
|
||||
await db.Entry(donation).ReloadAsync(ct);
|
||||
if (donation.TransactionId != null && donation.TransactionId != receipt.TransactionId)
|
||||
throw new DonationPaymentException(409, "La reference PayPal ne correspond pas au don.");
|
||||
if (donation.State is PerformerDonationState.Processing or PerformerDonationState.Pending)
|
||||
{
|
||||
donation.TransactionId = receipt.TransactionId;
|
||||
donation.State = receipt.Completed ? PerformerDonationState.Completed : PerformerDonationState.Pending;
|
||||
donation.CompletedAt = receipt.Completed ? DateTimeOffset.UtcNow : null;
|
||||
await SaveAsync(donation, ct);
|
||||
}
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
var donation = await OwnedAsync(id, ct);
|
||||
if (donation == null) return NotFound();
|
||||
return View(donation);
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> CancelConfirm(Guid id, CancellationToken ct)
|
||||
{
|
||||
var donation = await OwnedAsync(id, ct);
|
||||
if (donation == null) return NotFound();
|
||||
if (donation.State == PerformerDonationState.AwaitingApproval)
|
||||
{
|
||||
donation.State = PerformerDonationState.Cancelled;
|
||||
await SaveAsync(donation, ct);
|
||||
}
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
[AllowAnonymous, HttpPost, IgnoreAntiforgeryToken, RawPayPalNotification, RequestSizeLimit(64 * 1024)]
|
||||
public async Task<IActionResult> Notify(CancellationToken ct)
|
||||
{
|
||||
using var reader = new StreamReader(Request.Body, Encoding.UTF8);
|
||||
var body = await reader.ReadToEndAsync(ct);
|
||||
var fields = await paypal.VerifyNotificationAsync(body, ct);
|
||||
if (!Guid.TryParseExact(fields.GetValueOrDefault("invoice"), "N", out var id))
|
||||
throw new DonationPaymentException(400, "Reference de don PayPal invalide.");
|
||||
var donation = await db.PerformerDonations.FindAsync([id], ct);
|
||||
if (donation == null) return NotFound();
|
||||
var transactionId = fields.GetValueOrDefault("txn_id");
|
||||
if (fields.GetValueOrDefault("txn_type") != "express_checkout"
|
||||
|| !string.Equals(fields.GetValueOrDefault("receiver_email"), donation.RecipientEmail, StringComparison.OrdinalIgnoreCase)
|
||||
|| !PayPalDonationGateway.SameAmount(fields.GetValueOrDefault("mc_gross"), donation.Amount)
|
||||
|| fields.GetValueOrDefault("mc_currency") != donation.Currency
|
||||
|| string.IsNullOrWhiteSpace(transactionId) || transactionId.Length > 32
|
||||
|| (donation.TransactionId != null && donation.TransactionId != transactionId)
|
||||
|| donation.State is PerformerDonationState.Created or PerformerDonationState.AwaitingApproval or PerformerDonationState.Cancelled)
|
||||
throw new DonationPaymentException(409, "La notification PayPal ne correspond pas au don.");
|
||||
var paymentState = fields.GetValueOrDefault("payment_status");
|
||||
if (paymentState is not ("Completed" or "Pending" or "Denied" or "Failed" or "Expired" or "Voided"))
|
||||
{
|
||||
logger.LogWarning("PayPal donation {DonationId} notification has unsupported status {Status}", id, paymentState);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
if (donation.State != PerformerDonationState.Completed)
|
||||
{
|
||||
donation.TransactionId = transactionId;
|
||||
donation.State = paymentState switch
|
||||
{
|
||||
"Completed" => PerformerDonationState.Completed,
|
||||
"Pending" => PerformerDonationState.Pending,
|
||||
_ => PerformerDonationState.Failed
|
||||
};
|
||||
donation.CompletedAt = paymentState == "Completed" ? DateTimeOffset.UtcNow : null;
|
||||
await SaveAsync(donation, ct);
|
||||
}
|
||||
return Ok();
|
||||
}
|
||||
|
||||
private Task<PerformerProfile?> RecipientAsync(string id, CancellationToken ct)
|
||||
=> db.Performers.Include(p => p.Performer).SingleOrDefaultAsync(p => p.PerformerId == id
|
||||
&& p.Active && p.DonationPayPalEmail != null && p.DonationPayPalEmail != "", ct);
|
||||
|
||||
private Task<PerformerDonation?> OwnedAsync(Guid id, CancellationToken ct)
|
||||
=> db.PerformerDonations.SingleOrDefaultAsync(d => d.Id == id && d.DonorId == User.GetUserId(), ct);
|
||||
|
||||
private async Task SaveAsync(PerformerDonation donation, CancellationToken ct)
|
||||
{
|
||||
donation.Revision = Guid.NewGuid();
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
private (string Return, string Cancel, string Notify) PaymentUrls()
|
||||
{
|
||||
if (!Uri.TryCreate(siteOptions.Value.ExternalUrl, UriKind.Absolute, out var origin)
|
||||
|| origin.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(origin.UserInfo))
|
||||
throw new DonationPaymentException(503, "L'adresse HTTPS du site n'est pas configuree.");
|
||||
var root = siteOptions.Value.ExternalUrl.TrimEnd('/') + "/";
|
||||
return (root + "Donation/Return?id=", root + "Donation/Cancel?id=", root + "Donation/Notify");
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var executed = await next();
|
||||
var error = executed.Exception;
|
||||
if (error == null || error is not (DonationPaymentException or DbUpdateConcurrencyException) || Response.HasStarted)
|
||||
return;
|
||||
logger.LogError(error, "Donation request failed for {Action}", context.ActionDescriptor.DisplayName);
|
||||
executed.ExceptionHandled = true;
|
||||
Response.StatusCode = error is DonationPaymentException payment ? payment.StatusCode : 409;
|
||||
ViewData["PaymentError"] = error is DonationPaymentException known
|
||||
? known.Message : "Ce don a ete modifie par une autre requete. Consultez son etat avant de recommencer.";
|
||||
if (context.ActionArguments.TryGetValue("id", out var id) && id is Guid donationId)
|
||||
ViewData["DonationId"] = donationId;
|
||||
executed.Result = View("Error");
|
||||
}
|
||||
}
|
||||
104
src/Yavsc.Org/Controllers/PodcastController.cs
Normal file
104
src/Yavsc.Org/Controllers/PodcastController.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Globalization;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.ViewModels.Podcast;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[Authorize(Policy = "WebUser")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class PodcastController(
|
||||
PodcastWebClient api,
|
||||
ApplicationDbContext db,
|
||||
ILogger<PodcastController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(CancellationToken ct)
|
||||
{
|
||||
var podcasts = await api.GetAsync<List<PodcastResponse>>("", ct);
|
||||
var ownerIds = podcasts.Select(p => p.OwnerId).Distinct().ToArray();
|
||||
var performers = await db.Performers.AsNoTracking()
|
||||
.Where(p => ownerIds.Contains(p.PerformerId) && p.Active && p.DonationPayPalEmail != null
|
||||
&& p.DonationPayPalEmail != "")
|
||||
.Select(p => p.PerformerId).ToArrayAsync(ct);
|
||||
return View(new PodcastCatalogueViewModel(
|
||||
podcasts.OrderByDescending(p => p.CreatedAt).ToArray(), performers.ToHashSet(StringComparer.Ordinal)));
|
||||
}
|
||||
|
||||
[HttpGet("Podcast/{id:guid}/index.m3u8")]
|
||||
public async Task<IActionResult> Playlist(Guid id, CancellationToken ct)
|
||||
{
|
||||
var manifest = await api.GetAsync<PodcastManifestResponse>(id.ToString(), ct);
|
||||
var text = new StringBuilder("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:15\n")
|
||||
.Append("#EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:EVENT\n");
|
||||
foreach (var segment in manifest.Segments)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"#EXTINF:{segment.DurationSeconds:0.######},\n");
|
||||
text.Append(Url.Action(nameof(Segment), new { id, sequence = segment.Sequence })).Append('\n');
|
||||
}
|
||||
if (manifest.Podcast.State != PodcastState.Live) text.Append("#EXT-X-ENDLIST\n");
|
||||
return Content(text.ToString(), "application/vnd.apple.mpegurl", Encoding.UTF8);
|
||||
}
|
||||
|
||||
[HttpGet("Podcast/{id:guid}/segments/{sequence:int:min(0)}.ts")]
|
||||
public Task<IActionResult> Segment(Guid id, int sequence, CancellationToken ct)
|
||||
=> ProxyAsync($"{id}/segments/{sequence}.ts", "video/mp2t", ct);
|
||||
|
||||
[HttpGet("Podcast/{id:guid}/replay.mp4")]
|
||||
[HttpHead("Podcast/{id:guid}/replay.mp4")]
|
||||
public Task<IActionResult> Replay(Guid id, CancellationToken ct)
|
||||
=> ProxyAsync($"{id}/replay.mp4", "video/mp4", ct);
|
||||
|
||||
private async Task<IActionResult> ProxyAsync(string path, string contentType, CancellationToken ct)
|
||||
{
|
||||
RangeHeaderValue? range = null;
|
||||
if (Request.Headers.TryGetValue("Range", out var value)
|
||||
&& !RangeHeaderValue.TryParse(value.ToString(), out range))
|
||||
return BadRequest(new ProblemDetails { Status = 400, Title = "Plage de lecture invalide." });
|
||||
|
||||
using var response = await api.SendAsync(HttpMethods.IsHead(Request.Method)
|
||||
? HttpMethod.Head : HttpMethod.Get, path, range, ct);
|
||||
Response.StatusCode = (int)response.StatusCode;
|
||||
Response.ContentType = contentType;
|
||||
Response.Headers.CacheControl = "private, no-store";
|
||||
Response.ContentLength = response.Content.Headers.ContentLength;
|
||||
if (response.Content.Headers.ContentRange != null)
|
||||
Response.Headers.ContentRange = response.Content.Headers.ContentRange.ToString();
|
||||
if (response.Headers.AcceptRanges.Count > 0)
|
||||
Response.Headers.AcceptRanges = string.Join(", ", response.Headers.AcceptRanges);
|
||||
if (!HttpMethods.IsHead(Request.Method))
|
||||
await response.Content.CopyToAsync(Response.Body, ct);
|
||||
return new EmptyResult();
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var executed = await next();
|
||||
var error = executed.Exception;
|
||||
if (error == null || Response.HasStarted || HttpContext.RequestAborted.IsCancellationRequested)
|
||||
return;
|
||||
if (error is not (PodcastException or HttpRequestException or JsonException or TaskCanceledException))
|
||||
return;
|
||||
|
||||
logger.LogError(error, "Podcast web request failed for {Action}", context.ActionDescriptor.DisplayName);
|
||||
var status = error is PodcastException podcastError ? podcastError.StatusCode : 502;
|
||||
var message = error is PodcastException known
|
||||
? known.Message : "Le service de podcasts est indisponible. Reessayez plus tard.";
|
||||
Response.StatusCode = status;
|
||||
executed.ExceptionHandled = true;
|
||||
executed.Result = context.ActionDescriptor.RouteValues["action"] == nameof(Index)
|
||||
? View("Index", new PodcastCatalogueViewModel([], new HashSet<string>(), message))
|
||||
: StatusCode(status, new ProblemDetails { Status = status, Title = message });
|
||||
}
|
||||
}
|
||||
17
src/Yavsc.Org/Controllers/RawPayPalNotificationAttribute.cs
Normal file
17
src/Yavsc.Org/Controllers/RawPayPalNotificationAttribute.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public sealed class RawPayPalNotificationAttribute : Attribute, IResourceFilter
|
||||
{
|
||||
public void OnResourceExecuting(ResourceExecutingContext context)
|
||||
{
|
||||
context.ValueProviderFactories.RemoveType<FormValueProviderFactory>();
|
||||
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
|
||||
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
|
||||
}
|
||||
|
||||
public void OnResourceExecuted(ResourceExecutedContext context) { }
|
||||
}
|
||||
|
|
@ -92,6 +92,10 @@ public static class HostingExtensions
|
|||
// Add the system clock service
|
||||
_ = services.AddSingleton<IConnexionManager, HubConnectionManager>();
|
||||
_ = services.AddSingleton<ILiveProcessor, LiveProcessor>();
|
||||
services.AddHttpClient<Yavsc.Web.Services.PodcastWebClient>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
services.AddHttpClient<Yavsc.Web.Services.IPayPalDonationGateway, Yavsc.Web.Services.PayPalDonationGateway>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
_ = services.AddTransient<IFileSystemAuthManager, FileSystemAuthManager>();
|
||||
|
||||
AddIdentityDBAndStores(builder)
|
||||
|
|
@ -278,6 +282,8 @@ public static class HostingExtensions
|
|||
// options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
|
||||
// options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement()));
|
||||
options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
|
||||
options.AddPolicy("WebUser", new AuthorizationPolicyBuilder(IdentityConstants.ApplicationScheme)
|
||||
.RequireAuthenticatedUser().Build());
|
||||
options.AddPolicy("TheAuthor", policy => policy.Requirements.Add(new EditPermission()));
|
||||
});
|
||||
|
||||
|
|
|
|||
4969
src/Yavsc.Org/Migrations/20261025155604_HideIpAddressInCalls.Designer.cs
generated
Normal file
4969
src/Yavsc.Org/Migrations/20261025155604_HideIpAddressInCalls.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,29 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class HideIpAddressInCalls : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "HideIpAddressInCalls",
|
||||
table: "AspNetUsers",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "HideIpAddressInCalls",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5053
src/Yavsc.Org/Migrations/20261102093713_PerformerPayPalDonations.Designer.cs
generated
Normal file
5053
src/Yavsc.Org/Migrations/20261102093713_PerformerPayPalDonations.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,89 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PerformerPayPalDonations : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "DonationPayPalEmail",
|
||||
table: "Performers",
|
||||
type: "character varying(127)",
|
||||
maxLength: 127,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PerformerDonations",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
DonorId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
PerformerId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
RecipientEmail = table.Column<string>(type: "character varying(127)", maxLength: 127, nullable: false),
|
||||
Amount = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||
Currency = table.Column<string>(type: "character varying(3)", maxLength: 3, nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
State = table.Column<int>(type: "integer", nullable: false),
|
||||
CheckoutToken = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
|
||||
TransactionId = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true),
|
||||
CompletedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
Revision = table.Column<Guid>(type: "uuid", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PerformerDonations", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_PerformerDonations_AspNetUsers_DonorId",
|
||||
column: x => x.DonorId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
table.ForeignKey(
|
||||
name: "FK_PerformerDonations_Performers_PerformerId",
|
||||
column: x => x.PerformerId,
|
||||
principalTable: "Performers",
|
||||
principalColumn: "PerformerId",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PerformerDonations_CheckoutToken",
|
||||
table: "PerformerDonations",
|
||||
column: "CheckoutToken",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PerformerDonations_DonorId",
|
||||
table: "PerformerDonations",
|
||||
column: "DonorId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PerformerDonations_PerformerId",
|
||||
table: "PerformerDonations",
|
||||
column: "PerformerId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PerformerDonations_TransactionId",
|
||||
table: "PerformerDonations",
|
||||
column: "TransactionId",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "PerformerDonations");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DonationPayPalEmail",
|
||||
table: "Performers");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1170,6 +1170,9 @@ namespace Yavsc.Migrations
|
|||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<bool>("HideIpAddressInCalls")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
|
|
@ -2735,6 +2738,71 @@ namespace Yavsc.Migrations
|
|||
b.ToTable("PayPalPayment");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.PerformerDonation", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<decimal>("Amount")
|
||||
.HasColumnType("numeric(18,2)");
|
||||
|
||||
b.Property<string>("CheckoutToken")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTimeOffset?>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Currency")
|
||||
.IsRequired()
|
||||
.HasMaxLength(3)
|
||||
.HasColumnType("character varying(3)");
|
||||
|
||||
b.Property<string>("DonorId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(450)
|
||||
.HasColumnType("character varying(450)");
|
||||
|
||||
b.Property<string>("PerformerId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(450)
|
||||
.HasColumnType("character varying(450)");
|
||||
|
||||
b.Property<string>("RecipientEmail")
|
||||
.IsRequired()
|
||||
.HasMaxLength(127)
|
||||
.HasColumnType("character varying(127)");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("State")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("TransactionId")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CheckoutToken")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("DonorId");
|
||||
|
||||
b.HasIndex("PerformerId");
|
||||
|
||||
b.HasIndex("TransactionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PerformerDonations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
|
|
@ -3263,6 +3331,10 @@ namespace Yavsc.Migrations
|
|||
b.Property<bool>("Active")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("DonationPayPalEmail")
|
||||
.HasMaxLength(127)
|
||||
.HasColumnType("character varying(127)");
|
||||
|
||||
b.Property<string>("ExerciseCountryCode")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
|
@ -4511,6 +4583,21 @@ namespace Yavsc.Migrations
|
|||
b.Navigation("Executor");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.PerformerDonation", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("DonorId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Yavsc.Models.Workflow.PerformerProfile", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("PerformerId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.ApplicationUser", null)
|
||||
|
|
|
|||
174
src/Yavsc.Org/Services/PayPalDonationGateway.cs
Normal file
174
src/Yavsc.Org/Services/PayPalDonationGateway.cs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models.Payment;
|
||||
|
||||
namespace Yavsc.Web.Services;
|
||||
|
||||
public sealed class DonationPaymentException(int statusCode, string message) : Exception(message)
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
}
|
||||
|
||||
public sealed record DonationApproval(string PayerId);
|
||||
public sealed record DonationReceipt(string TransactionId, bool Completed);
|
||||
|
||||
public interface IPayPalDonationGateway
|
||||
{
|
||||
Task<string> CreateAsync(PerformerDonation donation, string returnUrl, string cancelUrl, string notifyUrl, CancellationToken ct);
|
||||
Task<DonationApproval> ApproveAsync(PerformerDonation donation, CancellationToken ct);
|
||||
Task<DonationReceipt> CaptureAsync(PerformerDonation donation, string payerId, CancellationToken ct);
|
||||
Task<IReadOnlyDictionary<string, string>> VerifyNotificationAsync(string body, CancellationToken ct);
|
||||
string CheckoutUrl(string token);
|
||||
}
|
||||
|
||||
public sealed class PayPalDonationGateway(HttpClient http, IOptions<PayPalSettings> options) : IPayPalDonationGateway
|
||||
{
|
||||
private PayPalSettings Settings
|
||||
{
|
||||
get
|
||||
{
|
||||
var settings = options.Value;
|
||||
if (settings.Mode is not ("production" or "sandbox"))
|
||||
throw new DonationPaymentException(503, "Le paiement PayPal n'est pas configure.");
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
public string CheckoutUrl(string token)
|
||||
=> $"https://{(Settings.Mode == "production" ? "www" : "www.sandbox")}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={Uri.EscapeDataString(token)}";
|
||||
|
||||
public async Task<string> CreateAsync(PerformerDonation donation, string returnUrl, string cancelUrl,
|
||||
string notifyUrl, CancellationToken ct)
|
||||
{
|
||||
var fields = PaymentFields(donation);
|
||||
fields["RETURNURL"] = returnUrl;
|
||||
fields["CANCELURL"] = cancelUrl;
|
||||
fields["PAYMENTREQUEST_0_NOTIFYURL"] = notifyUrl;
|
||||
fields["PAYMENTREQUEST_0_DESC"] = "Don au performer sur Yavsc";
|
||||
fields["NOSHIPPING"] = "1";
|
||||
var result = await CallAsync("SetExpressCheckout", fields, ct);
|
||||
var token = Required(result, "TOKEN");
|
||||
return token.Length <= 100 ? token : throw new DonationPaymentException(502, "Jeton PayPal invalide.");
|
||||
}
|
||||
|
||||
public async Task<DonationApproval> ApproveAsync(PerformerDonation donation, CancellationToken ct)
|
||||
{
|
||||
var fields = await CallAsync("GetExpressCheckoutDetails", new()
|
||||
{
|
||||
["TOKEN"] = donation.CheckoutToken ?? throw new InvalidOperationException("Missing donation checkout token.")
|
||||
}, ct);
|
||||
if (Required(fields, "TOKEN") != donation.CheckoutToken
|
||||
|| Required(fields, "PAYMENTREQUEST_0_INVNUM") != donation.Id.ToString("N")
|
||||
|| Required(fields, "PAYMENTREQUEST_0_CURRENCYCODE") != donation.Currency
|
||||
|| !SameAmount(fields.GetValueOrDefault("PAYMENTREQUEST_0_AMT"), donation.Amount)
|
||||
|| !string.Equals(Required(fields, "PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID"),
|
||||
donation.RecipientEmail, StringComparison.OrdinalIgnoreCase))
|
||||
throw new DonationPaymentException(409, "La confirmation PayPal ne correspond pas a ce don.");
|
||||
return new DonationApproval(Required(fields, "PAYERID"));
|
||||
}
|
||||
|
||||
public async Task<DonationReceipt> CaptureAsync(PerformerDonation donation, string payerId, CancellationToken ct)
|
||||
{
|
||||
var fields = PaymentFields(donation);
|
||||
fields["TOKEN"] = donation.CheckoutToken!;
|
||||
fields["PAYERID"] = payerId;
|
||||
fields["MSGSUBID"] = donation.Id.ToString("N");
|
||||
var result = await CallAsync("DoExpressCheckoutPayment", fields, ct);
|
||||
if (!SameAmount(result.GetValueOrDefault("PAYMENTINFO_0_AMT"), donation.Amount)
|
||||
|| Required(result, "PAYMENTINFO_0_CURRENCYCODE") != donation.Currency
|
||||
|| !string.Equals(Required(result, "PAYMENTINFO_0_SELLERPAYPALACCOUNTID"),
|
||||
donation.RecipientEmail, StringComparison.OrdinalIgnoreCase)
|
||||
|| Required(result, "PAYMENTINFO_0_PAYMENTSTATUS") is not ("Completed" or "Pending"))
|
||||
throw new DonationPaymentException(409, "Le paiement PayPal n'est pas confirme pour ce don.");
|
||||
var transactionId = Required(result, "PAYMENTINFO_0_TRANSACTIONID");
|
||||
if (transactionId.Length > 32)
|
||||
throw new DonationPaymentException(502, "Reference de transaction PayPal invalide.");
|
||||
return new DonationReceipt(transactionId,
|
||||
result["PAYMENTINFO_0_PAYMENTSTATUS"] == "Completed");
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyDictionary<string, string>> VerifyNotificationAsync(string body, CancellationToken ct)
|
||||
{
|
||||
var endpoint = Settings.Mode == "production"
|
||||
? "https://ipnpb.paypal.com/cgi-bin/webscr" : "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr";
|
||||
using var content = new StringContent("cmd=_notify-validate&" + body, Encoding.UTF8, "application/x-www-form-urlencoded");
|
||||
using var response = await PostAsync(endpoint, content, ct);
|
||||
if ((await response.Content.ReadAsStringAsync(ct)).Trim() != "VERIFIED")
|
||||
throw new DonationPaymentException(400, "Notification PayPal non verifiee.");
|
||||
return Parse(body);
|
||||
}
|
||||
|
||||
public static bool SameAmount(string? value, decimal amount)
|
||||
=> decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var actual)
|
||||
&& actual == amount;
|
||||
|
||||
private static Dictionary<string, string> PaymentFields(PerformerDonation donation) => new()
|
||||
{
|
||||
["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale",
|
||||
["PAYMENTREQUEST_0_AMT"] = donation.Amount.ToString("F2", CultureInfo.InvariantCulture),
|
||||
["PAYMENTREQUEST_0_CURRENCYCODE"] = donation.Currency,
|
||||
["PAYMENTREQUEST_0_INVNUM"] = donation.Id.ToString("N"),
|
||||
["PAYMENTREQUEST_0_PAYMENTREQUESTID"] = donation.Id.ToString("N"),
|
||||
["PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID"] = donation.RecipientEmail
|
||||
};
|
||||
|
||||
private async Task<Dictionary<string, string>> CallAsync(string method, Dictionary<string, string> fields, CancellationToken ct)
|
||||
{
|
||||
var settings = Settings;
|
||||
var accounts = settings.Accounts?.Where(a => a.ApiUsername == settings.MerchantAccountUserName).ToArray();
|
||||
if (accounts is not { Length: 1 } || string.IsNullOrWhiteSpace(accounts[0].ApiUsername)
|
||||
|| string.IsNullOrWhiteSpace(accounts[0].ApiPassword) || string.IsNullOrWhiteSpace(accounts[0].Signature))
|
||||
throw new DonationPaymentException(503, "Le compte marchand PayPal n'est pas configure.");
|
||||
fields["METHOD"] = method;
|
||||
fields["VERSION"] = "124.0";
|
||||
fields["USER"] = accounts[0].ApiUsername;
|
||||
fields["PWD"] = accounts[0].ApiPassword;
|
||||
fields["SIGNATURE"] = accounts[0].Signature;
|
||||
using var content = new FormUrlEncodedContent(fields);
|
||||
using var response = await PostAsync(settings.Mode == "production"
|
||||
? "https://api-3t.paypal.com/nvp" : "https://api-3t.sandbox.paypal.com/nvp", content, ct);
|
||||
var result = Parse(await response.Content.ReadAsStringAsync(ct));
|
||||
if (result.GetValueOrDefault("ACK") is not ("Success" or "SuccessWithWarning"))
|
||||
throw new DonationPaymentException(502, "PayPal a refuse cette operation. Aucun don n'est marque comme paye.");
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> PostAsync(string endpoint, HttpContent content, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await http.PostAsync(endpoint, content, ct);
|
||||
if (response.IsSuccessStatusCode) return response;
|
||||
response.Dispose();
|
||||
throw new DonationPaymentException(502, "Le service PayPal est indisponible.");
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new DonationPaymentException(502, $"La connexion PayPal a echoue ({ex.HttpRequestError}). Verifiez l'etat du don avant de recommencer.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
throw new DonationPaymentException(504, "La reponse PayPal a expire. Verifiez l'etat du don avant de recommencer.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> Parse(string body)
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in body.Split('&'))
|
||||
{
|
||||
var parts = pair.Split('=', 2);
|
||||
if (parts.Length != 2 || !result.TryAdd(Decode(parts[0]), Decode(parts[1])))
|
||||
throw new DonationPaymentException(502, "Reponse PayPal invalide.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string Decode(string value) => Uri.UnescapeDataString(value.Replace("+", " "));
|
||||
private static string Required(IReadOnlyDictionary<string, string> fields, string name)
|
||||
=> fields.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value)
|
||||
? value : throw new DonationPaymentException(502, "Reponse PayPal incomplete.");
|
||||
}
|
||||
76
src/Yavsc.Org/Services/PodcastWebClient.cs
Normal file
76
src/Yavsc.Org/Services/PodcastWebClient.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Security.Claims;
|
||||
using IdentityServer8;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Server.Helpers;
|
||||
|
||||
namespace Yavsc.Web.Services;
|
||||
|
||||
public sealed class PodcastWebClient(HttpClient http, IOptions<SiteSettings> options,
|
||||
IdentityServerTools authority, IHttpContextAccessor contextAccessor)
|
||||
{
|
||||
private string? _accessToken;
|
||||
|
||||
public async Task<T> GetAsync<T>(string path, CancellationToken ct)
|
||||
{
|
||||
using var response = await SendAsync(HttpMethod.Get, path, null, ct);
|
||||
return await response.Content.ReadFromJsonAsync<T>(ct)
|
||||
?? throw new JsonException("Empty podcast API response.");
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path,
|
||||
RangeHeaderValue? range, CancellationToken ct)
|
||||
{
|
||||
var settings = options.Value;
|
||||
if (!Uri.TryCreate(settings.ApiUrl, UriKind.Absolute, out var address)
|
||||
|| address.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(address.UserInfo))
|
||||
throw new PodcastException(503, "La connexion aux podcasts n'est pas configuree.");
|
||||
|
||||
if (_accessToken == null)
|
||||
{
|
||||
var user = contextAccessor.HttpContext?.User;
|
||||
var userId = user?.GetUserId();
|
||||
if (user?.Identity?.IsAuthenticated != true || string.IsNullOrWhiteSpace(userId))
|
||||
throw new PodcastException(401, "Une connexion est requise pour lire les podcasts.");
|
||||
_accessToken = await authority.IssueJwtAsync(300, new List<Claim>
|
||||
{
|
||||
new("sub", userId),
|
||||
new("name", user.Identity.Name ?? userId),
|
||||
new("scope", "api"),
|
||||
new("aud", "api")
|
||||
});
|
||||
if (string.IsNullOrWhiteSpace(_accessToken))
|
||||
throw new InvalidOperationException("Yavsc.Org did not issue a podcast access token.");
|
||||
}
|
||||
|
||||
address = new Uri(settings.ApiUrl.TrimEnd('/') + "/");
|
||||
if (!address.AbsolutePath.EndsWith("/" + Constants.APIPrefix + "/", StringComparison.Ordinal))
|
||||
address = new Uri(address, Constants.APIPrefix + "/");
|
||||
using var request = new HttpRequestMessage(method, new Uri(address, "podcasts/" + path));
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
|
||||
request.Headers.Range = range;
|
||||
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
|
||||
if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable)
|
||||
{
|
||||
var status = response.StatusCode;
|
||||
response.Dispose();
|
||||
throw new PodcastException(status switch
|
||||
{
|
||||
HttpStatusCode.NotFound => 404,
|
||||
HttpStatusCode.Conflict => 409,
|
||||
_ => 502
|
||||
}, status switch
|
||||
{
|
||||
HttpStatusCode.NotFound => "Podcast introuvable.",
|
||||
HttpStatusCode.Conflict => "Ce replay n'est pas encore disponible.",
|
||||
_ => "Le service de podcasts est indisponible."
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
26
src/Yavsc.Org/ViewModels/Podcast/DonationViewModels.cs
Normal file
26
src/Yavsc.Org/ViewModels/Podcast/DonationViewModels.cs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Yavsc.Models.Payment;
|
||||
|
||||
namespace Yavsc.ViewModels.Podcast;
|
||||
|
||||
public sealed class CreateDonationViewModel
|
||||
{
|
||||
[Required]
|
||||
public string PerformerId { get; set; } = "";
|
||||
[BindNever]
|
||||
public string PerformerName { get; set; } = "";
|
||||
[Range(typeof(decimal), "0.01", "9999999999999999.99",
|
||||
ParseLimitsInInvariantCulture = true, ConvertValueInInvariantCulture = true)]
|
||||
public decimal Amount { get; set; } = 5m;
|
||||
}
|
||||
|
||||
public sealed class DonationSettingsViewModel
|
||||
{
|
||||
[EmailAddress, StringLength(127)]
|
||||
public string? PayPalEmail { get; set; }
|
||||
}
|
||||
|
||||
public sealed record DonationDetailsViewModel(PerformerDonation Donation, string PerformerName);
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
#nullable enable
|
||||
|
||||
using Yavsc.Abstract.Streaming;
|
||||
|
||||
namespace Yavsc.ViewModels.Podcast;
|
||||
|
||||
public sealed record PodcastCatalogueViewModel(
|
||||
IReadOnlyList<PodcastResponse> Podcasts,
|
||||
IReadOnlySet<string> DonationPerformerIds,
|
||||
string? Error = null);
|
||||
10
src/Yavsc.Org/Views/Donation/Cancel.cshtml
Normal file
10
src/Yavsc.Org/Views/Donation/Cancel.cshtml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
@model Yavsc.Models.Payment.PerformerDonation
|
||||
@{
|
||||
ViewBag.Title = Localizer["Annuler le don"];
|
||||
}
|
||||
<h1>@ViewBag.Title</h1>
|
||||
<p>@Localizer["L'annulation est possible tant que le paiement n'a pas été lancé."]</p>
|
||||
<form asp-action="CancelConfirm" asp-route-id="@Model.Id" method="post">
|
||||
<button class="btn btn-outline-danger" type="submit">@Localizer["Confirmer l'annulation"]</button>
|
||||
</form>
|
||||
<a asp-action="Details" asp-route-id="@Model.Id" class="btn btn-outline-secondary mt-3">@Localizer["Voir l'état du don"]</a>
|
||||
18
src/Yavsc.Org/Views/Donation/Create.cshtml
Normal file
18
src/Yavsc.Org/Views/Donation/Create.cshtml
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
@model Yavsc.ViewModels.Podcast.CreateDonationViewModel
|
||||
@{
|
||||
ViewBag.Title = Localizer["Soutenir un performer"];
|
||||
}
|
||||
<h1>@Localizer["Faire un don à {0}", Model.PerformerName]</h1>
|
||||
<p>@Localizer["Votre don sera payé directement sur le compte PayPal du performer. Yavsc ne l'encaisse pas."]</p>
|
||||
<p>@Localizer["Le don est facultatif et indépendant de l'accès aux podcasts. Aucun reçu fiscal n'est délivré."]</p>
|
||||
<form asp-action="Create" method="post">
|
||||
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
<input asp-for="PerformerId" type="hidden" />
|
||||
<div class="mb-3">
|
||||
<label asp-for="Amount" class="form-label">@Localizer["Montant en euros"]</label>
|
||||
<input asp-for="Amount" type="text" inputmode="decimal" class="form-control" />
|
||||
<span asp-validation-for="Amount" class="text-danger"></span>
|
||||
</div>
|
||||
<button class="btn btn-success" type="submit">@Localizer["Continuer avec PayPal"]</button>
|
||||
<a asp-controller="Podcast" asp-action="Index" class="btn btn-outline-secondary">@Localizer["Retour aux podcasts"]</a>
|
||||
</form>
|
||||
36
src/Yavsc.Org/Views/Donation/Details.cshtml
Normal file
36
src/Yavsc.Org/Views/Donation/Details.cshtml
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
@using Yavsc.Models.Payment
|
||||
@model Yavsc.ViewModels.Podcast.DonationDetailsViewModel
|
||||
@{
|
||||
ViewBag.Title = Localizer["Votre don"];
|
||||
var donation = Model.Donation;
|
||||
}
|
||||
<h1>@Localizer["Votre don à {0}", Model.PerformerName]</h1>
|
||||
<p>@donation.Amount.ToString("F2") @donation.Currency</p>
|
||||
<p>@Localizer["Référence"] : @donation.Id</p>
|
||||
@switch (donation.State)
|
||||
{
|
||||
case PerformerDonationState.AwaitingApproval:
|
||||
<p>@Localizer["Après votre accord sur PayPal, confirmez le paiement ci-dessous. Le montant et le bénéficiaire sont vérifiés par Yavsc auprès de PayPal."]</p>
|
||||
<form asp-action="Confirm" asp-route-id="@donation.Id" method="post">
|
||||
<button type="submit" class="btn btn-success">@Localizer["Confirmer le paiement du don"]</button>
|
||||
</form>
|
||||
break;
|
||||
case PerformerDonationState.Completed:
|
||||
<p class="alert alert-success" role="status">@Localizer["Merci ! PayPal a confirmé le paiement de votre don au performer."]</p>
|
||||
<p>@Localizer["Transaction PayPal"] : @donation.TransactionId</p>
|
||||
break;
|
||||
case PerformerDonationState.Cancelled:
|
||||
<p class="alert alert-info" role="status">@Localizer["Ce don a été annulé avant paiement."]</p>
|
||||
break;
|
||||
case PerformerDonationState.Created:
|
||||
<p class="alert alert-warning" role="status">@Localizer["Le paiement de ce don n'a pas été lancé."]</p>
|
||||
break;
|
||||
case PerformerDonationState.Failed:
|
||||
<p class="alert alert-danger" role="status">@Localizer["PayPal a signalé l'échec de ce paiement. Ce don n'est pas payé."]</p>
|
||||
break;
|
||||
default:
|
||||
<p class="alert alert-warning" role="status">@Localizer["Le paiement n'est pas confirmé. Il peut être en cours de traitement par PayPal. Ne créez pas de second don et actualisez cette page. Si cet état persiste, contactez Yavsc avec la référence du don."]</p>
|
||||
break;
|
||||
}
|
||||
<a asp-action="Details" asp-route-id="@donation.Id" class="btn btn-outline-primary mt-3">@Localizer["Actualiser l'état"]</a>
|
||||
<a asp-controller="Podcast" asp-action="Index" class="btn btn-outline-secondary mt-3">@Localizer["Retour aux podcasts"]</a>
|
||||
13
src/Yavsc.Org/Views/Donation/Error.cshtml
Normal file
13
src/Yavsc.Org/Views/Donation/Error.cshtml
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
@{
|
||||
ViewBag.Title = Localizer["Paiement indisponible"];
|
||||
}
|
||||
<h1>@ViewBag.Title</h1>
|
||||
<p class="alert alert-danger" role="alert">@ViewData["PaymentError"]</p>
|
||||
<p>@Localizer["Un retour du navigateur ne prouve pas qu'un paiement a été effectué. Consultez l'état du don avant de recommencer."]</p>
|
||||
@if (ViewData["DonationId"] is Guid id)
|
||||
{
|
||||
<a asp-action="Details" asp-route-id="@id" class="btn btn-outline-primary">@Localizer["Voir l'état du don"]</a>
|
||||
}
|
||||
<a asp-controller="Podcast" asp-action="Index" class="btn btn-outline-secondary">@Localizer["Retour aux podcasts"]</a>
|
||||
<a asp-action="Index" class="btn btn-outline-primary">@Localizer["Mes dons"]</a>
|
||||
<a asp-controller="Manage" asp-action="SetActivity" class="btn btn-outline-secondary">@Localizer["Mon profil performer"]</a>
|
||||
24
src/Yavsc.Org/Views/Donation/Index.cshtml
Normal file
24
src/Yavsc.Org/Views/Donation/Index.cshtml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
@model IReadOnlyList<Yavsc.ViewModels.Podcast.DonationDetailsViewModel>
|
||||
@{
|
||||
ViewBag.Title = Localizer["Mes dons"];
|
||||
}
|
||||
<h1>@ViewBag.Title</h1>
|
||||
@if (Model.Count == 0)
|
||||
{
|
||||
<p>@Localizer["Vous n'avez pas encore initié de don."]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="list-group">
|
||||
@foreach (var entry in Model)
|
||||
{
|
||||
<li class="list-group-item">
|
||||
<a asp-action="Details" asp-route-id="@entry.Donation.Id">
|
||||
@entry.PerformerName · @entry.Donation.Amount.ToString("F2") @entry.Donation.Currency
|
||||
· @entry.Donation.CreatedAt.ToLocalTime().ToString("g")
|
||||
</a>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<a asp-controller="Podcast" asp-action="Index" class="btn btn-outline-secondary mt-3">@Localizer["Retour aux podcasts"]</a>
|
||||
21
src/Yavsc.Org/Views/Donation/Settings.cshtml
Normal file
21
src/Yavsc.Org/Views/Donation/Settings.cshtml
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
@model Yavsc.ViewModels.Podcast.DonationSettingsViewModel
|
||||
@{
|
||||
ViewBag.Title = Localizer["Dons PayPal"];
|
||||
}
|
||||
<h1>@ViewBag.Title</h1>
|
||||
@if (TempData["DonationSettingsSaved"] != null)
|
||||
{
|
||||
<p class="alert alert-success" role="status">@Localizer["Les paramètres de dons ont été enregistrés."]</p>
|
||||
}
|
||||
<p>@Localizer["Configurez votre propre compte PayPal pour recevoir directement les dons. Vérifiez soigneusement cette adresse : elle désigne le bénéficiaire du paiement."]</p>
|
||||
<p>@Localizer["Laissez le champ vide pour désactiver les nouveaux dons. Les dons déjà initiés conservent leur bénéficiaire."]</p>
|
||||
<form asp-action="Settings" method="post">
|
||||
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
<div class="mb-3">
|
||||
<label asp-for="PayPalEmail" class="form-label">@Localizer["Adresse e-mail de votre compte PayPal"]</label>
|
||||
<input asp-for="PayPalEmail" type="email" class="form-control" autocomplete="email" />
|
||||
<span asp-validation-for="PayPalEmail" class="text-danger"></span>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">@Localizer["Enregistrer"]</button>
|
||||
<a asp-controller="Manage" asp-action="Index" class="btn btn-outline-secondary">@Localizer["Mon compte"]</a>
|
||||
</form>
|
||||
|
|
@ -115,6 +115,13 @@ Html.DisplayText("Modify");
|
|||
<dt>Bank info:</dt>
|
||||
<dd>@Html.DisplayFor(m => m.BankInfo) [<a asp-controller="Manage" asp-action="AddBankInfo"
|
||||
>@(Model.BankInfo==null?"Set":"Modify")</a>]</dd>
|
||||
@if (Model.HaveProfessionalSettings)
|
||||
{
|
||||
<dt>@Localizer["Dons PayPal"]</dt>
|
||||
<dd><a asp-controller="Donation" asp-action="Settings">@Localizer["Configurer la réception des dons"]</a></dd>
|
||||
}
|
||||
<dt>@Localizer["Mes dons"]</dt>
|
||||
<dd><a asp-controller="Donation" asp-action="Index">@Localizer["Suivre mes dons aux performers"]</a></dd>
|
||||
|
||||
<dt><a href="/Blog/@Model.UserName">Your posts:</a></dt>
|
||||
<dd>@Model.PostsCounter</dd>
|
||||
|
|
|
|||
|
|
@ -14,6 +14,11 @@
|
|||
|
||||
@Html.DisplayFor(model => model)
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(Model.PerformerId))
|
||||
{
|
||||
<p><a asp-controller="Donation" asp-action="Settings" class="btn btn-outline-primary">@Localizer["Configurer mes dons PayPal"]</a></p>
|
||||
}
|
||||
|
||||
<form id="FrmSetAct" asp-controller="Manage" asp-action="SetActivity" method="post" class="form-horizontal" role="form">
|
||||
<h4>Setup below your activity parameters:</h4>
|
||||
<hr />
|
||||
|
|
|
|||
105
src/Yavsc.Org/Views/Podcast/Index.cshtml
Normal file
105
src/Yavsc.Org/Views/Podcast/Index.cshtml
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
@using Yavsc.Abstract.Streaming
|
||||
@model Yavsc.ViewModels.Podcast.PodcastCatalogueViewModel
|
||||
@{
|
||||
ViewBag.Title = Localizer["Podcasts"];
|
||||
}
|
||||
|
||||
<header class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
|
||||
<div>
|
||||
<h1>@Localizer["Podcasts"]</h1>
|
||||
<p class="text-muted">@Localizer["Retrouvez les directs et les replays de la communauté Yavsc."]</p>
|
||||
<p>@Localizer["Lecture réservée aux utilisateurs connectés. Les flux sont fournis par Yavsc.Api."]</p>
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<a asp-action="Index" class="btn btn-outline-primary">@Localizer["Actualiser"]</a>
|
||||
<a asp-controller="Donation" asp-action="Settings" class="btn btn-outline-success">@Localizer["Configurer mes dons PayPal"]</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@if (Model.Error != null)
|
||||
{
|
||||
<div class="alert alert-danger" role="alert">@Model.Error</div>
|
||||
}
|
||||
else if (Model.Podcasts.Count == 0)
|
||||
{
|
||||
<div class="alert alert-info" role="status">@Localizer["Aucun podcast n'est disponible pour le moment."]</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="row g-4">
|
||||
@foreach (var podcast in Model.Podcasts)
|
||||
{
|
||||
var ready = podcast.State == PodcastState.Completed && podcast.Replay?.State == PodcastReplayState.Ready;
|
||||
var stateLabel = podcast.State switch
|
||||
{
|
||||
PodcastState.Live => Localizer["En direct"],
|
||||
PodcastState.Completed => Localizer["Replay"],
|
||||
_ => Localizer["Direct interrompu"]
|
||||
};
|
||||
<article class="col-12 col-lg-6">
|
||||
<div class="card h-100 shadow-sm">
|
||||
<div class="card-body">
|
||||
<div class="d-flex justify-content-between align-items-start gap-3">
|
||||
<h2 class="h4">@podcast.Title</h2>
|
||||
<span class="badge @(podcast.State == PodcastState.Live ? "bg-danger" : "bg-secondary")">@stateLabel</span>
|
||||
</div>
|
||||
<p class="text-muted">
|
||||
@podcast.OwnerName · <time datetime="@podcast.CreatedAt.ToString("O")">@podcast.CreatedAt.ToLocalTime().ToString("g")</time>
|
||||
</p>
|
||||
<p>@Localizer["Durée : {0} s", podcast.DurationSeconds.ToString("0.##")]</p>
|
||||
@if (podcast.SegmentCount > 0)
|
||||
{
|
||||
<video controls playsinline preload="none" class="w-100"
|
||||
aria-label="@podcast.Title" data-podcast-player
|
||||
data-hls="@(!ready ? "true" : "false")">
|
||||
<source src="@(ready ? Url.Action("Replay", new { id = podcast.Id }) : Url.Action("Playlist", new { id = podcast.Id }))"
|
||||
type="@(ready ? "video/mp4" : "application/vnd.apple.mpegurl")" />
|
||||
@Localizer["Votre navigateur ne prend pas en charge la lecture vidéo."]
|
||||
</video>
|
||||
@if (!ready)
|
||||
{
|
||||
<button type="button" class="btn btn-outline-primary mt-2 d-none" data-start-playback>
|
||||
@Localizer["Lire le podcast"]
|
||||
</button>
|
||||
}
|
||||
<p class="alert alert-warning mt-2 d-none" role="alert" data-playback-error>
|
||||
@Localizer["Lecture indisponible. Actualisez la page ou utilisez PostIt."]
|
||||
</p>
|
||||
@if (!ready && podcast.State == PodcastState.Completed)
|
||||
{
|
||||
<p class="text-muted">
|
||||
@(podcast.Replay?.State == PodcastReplayState.Failed
|
||||
? Localizer["La préparation du replay MP4 a échoué. L'auteur peut la relancer depuis PostIt."]
|
||||
: Localizer["Le replay MP4 est en préparation. La lecture HLS reste disponible."])
|
||||
</p>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="alert alert-info">@Localizer["Aucun segment n'est encore disponible. Actualisez la page pour suivre ce podcast."]</p>
|
||||
}
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<h3 class="h6">@Localizer["Soutenir l'auteur"]</h3>
|
||||
@if (Model.DonationPerformerIds.Contains(podcast.OwnerId))
|
||||
{
|
||||
<a asp-controller="Donation" asp-action="Create" asp-route-id="@podcast.OwnerId" class="btn btn-outline-success">
|
||||
@Localizer["Faire un don à {0}", podcast.OwnerName]
|
||||
</a>
|
||||
<p class="small text-muted mt-2 mb-0">@Localizer["Don facultatif géré par Yavsc, payé via PayPal directement à l'auteur."]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="small text-muted mb-0">@Localizer["Cet auteur n'a pas encore activé les dons PayPal."]</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@section scripts {
|
||||
<script src="~/js/hls.light.min.js" asp-append-version="true"></script>
|
||||
<script src="~/js/podcasts.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@ background-attachment: fixed;">
|
|||
<ul class="navbar-nav me-auto" >
|
||||
<li class="nav-item"><a class="nav-link @PageHelpers.ActivePage(ViewContext, "")" href="/">@Localizer["Home"]</a></li>
|
||||
<li class="nav-item"><a asp-controller="Blogspot" asp-action="Index" class="nav-link @PageHelpers.ActivePage(ViewContext, "Blogspot")">@Localizer["Blogs"]</a></li>
|
||||
<li class="nav-item"><a asp-controller="Podcast" asp-action="Index" class="nav-link @PageHelpers.ActivePage(ViewContext, "Podcast")">@Localizer["Podcasts"]</a></li>
|
||||
<li class="nav-item"><a asp-controller="Home" asp-action="Contact" class="nav-link @PageHelpers.ActivePage(ViewContext, "Home", "Contact")">@Localizer["Contact"]</a></li>
|
||||
<li class="nav-item"><a asp-controller="Home" asp-action="About" class="nav-link @PageHelpers.ActivePage(ViewContext, "Home", "About")">@Localizer["About"]</a></li>
|
||||
<partial name="_LoginPartial" />
|
||||
|
|
|
|||
|
|
@ -7,10 +7,10 @@
|
|||
<RootNamespace>Yavsc</RootNamespace>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<RepositoryUrl>https://github.com/pazof/yavsc</RepositoryUrl>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DotMarkdown" />
|
||||
|
|
|
|||
2
src/Yavsc.Org/wwwroot/js/hls.light.min.js
vendored
Normal file
2
src/Yavsc.Org/wwwroot/js/hls.light.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
32
src/Yavsc.Org/wwwroot/js/podcasts.js
Normal file
32
src/Yavsc.Org/wwwroot/js/podcasts.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
document.querySelectorAll("[data-podcast-player]").forEach(player => {
|
||||
const warning = player.parentElement.querySelector("[data-playback-error]");
|
||||
const showError = () => warning.classList.remove("d-none");
|
||||
const source = player.querySelector("source");
|
||||
if (player.dataset.hls === "true" && !player.canPlayType("application/vnd.apple.mpegurl")) {
|
||||
if (typeof Hls === "undefined" || !Hls.isSupported()) {
|
||||
showError();
|
||||
return;
|
||||
}
|
||||
const url = source.src;
|
||||
source.remove();
|
||||
const start = player.parentElement.querySelector("[data-start-playback]");
|
||||
start.classList.remove("d-none");
|
||||
start.addEventListener("click", () => {
|
||||
start.classList.add("d-none");
|
||||
const hls = new Hls();
|
||||
hls.on(Hls.Events.ERROR, (_event, data) => {
|
||||
if (data.fatal) {
|
||||
showError();
|
||||
hls.destroy();
|
||||
}
|
||||
});
|
||||
hls.loadSource(url);
|
||||
hls.attachMedia(player);
|
||||
player.play().catch(showError);
|
||||
window.addEventListener("pagehide", () => hls.destroy(), { once: true });
|
||||
}, { once: true });
|
||||
} else {
|
||||
source.addEventListener("error", showError);
|
||||
}
|
||||
player.addEventListener("error", showError);
|
||||
});
|
||||
91
src/Yavsc.Server/Hubs/ChatHub.Calls.cs
Normal file
91
src/Yavsc.Server/Hubs/ChatHub.Calls.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
#nullable enable
|
||||
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
using Yavsc.Server.Helpers;
|
||||
|
||||
namespace Yavsc.Server.Hubs;
|
||||
|
||||
public partial class ChatHub
|
||||
{
|
||||
public Task<CallSession> InviteCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.WebRtc);
|
||||
|
||||
public Task<CallSession> InviteLanCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.LanSrtp);
|
||||
|
||||
private async Task<CallSession> InviteCoreAsync(string roomName, string callee, string transport)
|
||||
{
|
||||
var caller = CallUser();
|
||||
RequireSecureLanControl(transport);
|
||||
if (string.IsNullOrWhiteSpace(roomName) || !InputValidator.ValidateRoomName(roomName) ||
|
||||
string.IsNullOrWhiteSpace(callee) || !InputValidator.ValidateUserName(callee))
|
||||
throw new HubException("Invalid call participant or room.");
|
||||
RequireCallPresence(roomName, caller, callee);
|
||||
var relayOnly = await RequiresRelayAsync(caller, callee);
|
||||
return await _calls.InviteAsync(roomName, caller, callee, Context.ConnectionId,
|
||||
_cxManager.GetConnexionIds(callee)?.Distinct().ToArray() ?? [], relayOnly, transport);
|
||||
}
|
||||
|
||||
public async Task AcceptCall(Guid callId)
|
||||
{
|
||||
var user = CallUser();
|
||||
var session = await _calls.GetSessionAsync(callId, user, Context.ConnectionId);
|
||||
RequireSecureLanControl(session.Transport);
|
||||
RequireCallPresence(session.RoomName, session.Caller, session.Callee);
|
||||
await _calls.AcceptAsync(callId, user, Context.ConnectionId,
|
||||
await RequiresRelayAsync(session.Caller, session.Callee));
|
||||
}
|
||||
|
||||
public Task EndCall(Guid callId) => _calls.EndAsync(callId, CallUser(), Context.ConnectionId);
|
||||
|
||||
public async Task SendCallSignal(Guid callId, CallSignal signal)
|
||||
{
|
||||
var user = CallUser();
|
||||
var session = await _calls.GetSessionAsync(callId, user, Context.ConnectionId);
|
||||
RequireSecureLanControl(session.Transport);
|
||||
RequireCallPresence(session.RoomName, session.Caller, session.Callee);
|
||||
if (!session.RelayOnly && await RequiresRelayAsync(session.Caller, session.Callee))
|
||||
{
|
||||
await _calls.EndForUserAsync(user, "privacy-changed");
|
||||
throw new HubException("Call ended because the IP privacy policy changed. Start a new call.");
|
||||
}
|
||||
await _calls.SignalAsync(callId, user, Context.ConnectionId, signal);
|
||||
}
|
||||
|
||||
private string CallUser()
|
||||
{
|
||||
var user = Context.User?.GetUserName();
|
||||
if (string.IsNullOrWhiteSpace(user) || _cxManager.GetUserName(Context.ConnectionId) != user)
|
||||
throw new HubException("An authenticated chat connection is required.");
|
||||
return user;
|
||||
}
|
||||
|
||||
private void RequireSecureLanControl(string transport)
|
||||
{
|
||||
if (transport == CallTransports.LanSrtp && Context.GetHttpContext()?.Request.IsHttps != true)
|
||||
throw new HubException("LAN calls require HTTPS signaling to protect SRTP keys.");
|
||||
}
|
||||
|
||||
private void RequireCallPresence(string room, string caller, string callee)
|
||||
{
|
||||
if (!_cxManager.IsConnected(caller) || !_cxManager.IsConnected(callee) ||
|
||||
!_cxManager.IsPresent(room, caller) || !_cxManager.IsPresent(room, callee))
|
||||
throw new HubException("Both call participants must be present in the chat room.");
|
||||
}
|
||||
|
||||
private async Task<bool> RequiresRelayAsync(string caller, string callee)
|
||||
{
|
||||
var users = await _dbContext.Users.AsNoTracking()
|
||||
.Where(u => u.UserName == caller || u.UserName == callee)
|
||||
.Select(u => new { u.Id, u.HideIpAddressInCalls }).ToArrayAsync(Context.ConnectionAborted);
|
||||
if (users.Length != 2)
|
||||
throw new HubException("Call participants are unavailable.");
|
||||
var ids = users.Select(u => u.Id).ToArray();
|
||||
if (await _dbContext.BlackListed.AnyAsync(
|
||||
b => ids.Contains(b.OwnerId) && ids.Contains(b.UserId), Context.ConnectionAborted))
|
||||
throw new HubException("Calls between these participants are not allowed.");
|
||||
return users.Any(u => u.HideIpAddressInCalls);
|
||||
}
|
||||
}
|
||||
|
|
@ -45,15 +45,17 @@ namespace Yavsc.Server.Hubs
|
|||
private readonly IConnexionManager _cxManager;
|
||||
private readonly IStringLocalizer _localizer;
|
||||
private readonly ILogger _logger;
|
||||
private readonly CallSignalingService _calls;
|
||||
|
||||
public HubInputValidator InputValidator { get; }
|
||||
|
||||
public ChatHub(ApplicationDbContext dbContext,
|
||||
ILoggerFactory loggerFactory,
|
||||
IStringLocalizerFactory stringLocalizerFactory,
|
||||
IConnexionManager connexionManager)
|
||||
IConnexionManager connexionManager, CallSignalingService calls)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_calls = calls;
|
||||
_localizer = stringLocalizerFactory.Create(typeof(ChatHub));
|
||||
|
||||
_cxManager = connexionManager;
|
||||
|
|
@ -96,6 +98,7 @@ namespace Yavsc.Server.Hubs
|
|||
|
||||
public override async Task OnDisconnectedAsync(Exception ex)
|
||||
{
|
||||
await _calls.DisconnectAsync(Context.ConnectionId);
|
||||
string userName = Context.User?.GetUserName();
|
||||
if (userName != null)
|
||||
{
|
||||
|
|
@ -216,6 +219,7 @@ namespace Yavsc.Server.Hubs
|
|||
// in case of Kick returned false, being not allowed to, or for what ever other else failure,
|
||||
// the error handler will send an error message while handling the error.
|
||||
if (!_cxManager.Kick(Context.ConnectionId, userName, roomName, reason)) return;
|
||||
await _calls.EndForUserAsync(userName, "removed-from-room", roomName);
|
||||
}
|
||||
var cxIds = _cxManager.GetConnexionIds(userName);
|
||||
if (cxIds != null) foreach (var cx in cxIds)
|
||||
|
|
@ -240,7 +244,7 @@ namespace Yavsc.Server.Hubs
|
|||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Part(string roomName, string reason)
|
||||
public async Task Part(string roomName, string reason)
|
||||
{
|
||||
if (!InputValidator.ValidateRoomName(roomName)) return;
|
||||
if (!InputValidator.ValidateReason(reason)) return;
|
||||
|
|
@ -249,6 +253,7 @@ namespace Yavsc.Server.Hubs
|
|||
var roomGroupName = ChatHubConstants.HubGroupRoomsPrefix + roomName;
|
||||
var group = Clients.Group(roomGroupName);
|
||||
var userName = _cxManager.GetUserName(Context.ConnectionId);
|
||||
await _calls.EndForUserAsync(userName, "left-room", roomName);
|
||||
group.SendAsync("notifyRoom", NotificationTypes.UserPart, roomName, $"{userName}: {reason}");
|
||||
Groups.RemoveFromGroupAsync(Context.ConnectionId, roomGroupName);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,6 +58,16 @@ namespace Yavsc.Models
|
|||
}
|
||||
builder.UseIdentityByDefaultColumns();
|
||||
|
||||
builder.Entity<PerformerDonation>(entity =>
|
||||
{
|
||||
entity.HasOne<ApplicationUser>().WithMany().HasForeignKey(d => d.DonorId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
entity.HasOne<PerformerProfile>().WithMany().HasForeignKey(d => d.PerformerId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
entity.HasIndex(d => d.CheckoutToken).IsUnique();
|
||||
entity.HasIndex(d => d.TransactionId).IsUnique();
|
||||
});
|
||||
|
||||
builder.Entity<NominativeServiceCommand>()
|
||||
.Property(command => command.AmountPaid)
|
||||
.HasDefaultValue(0m);
|
||||
|
|
@ -458,6 +468,7 @@ namespace Yavsc.Models
|
|||
public DbSet<BankIdentity> BankIdentity { get; set; }
|
||||
|
||||
public DbSet<PayPalPayment> PayPalPayment { get; set; }
|
||||
public DbSet<PerformerDonation> PerformerDonations { get; set; }
|
||||
|
||||
public DbSet<HyperLink> HyperLink { get; set; }
|
||||
|
||||
|
|
|
|||
|
|
@ -104,6 +104,9 @@ namespace Yavsc.Models
|
|||
|
||||
public bool AllowMonthlyEmail { get; set; } = false;
|
||||
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public bool HideIpAddressInCalls { get; set; }
|
||||
|
||||
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
[InverseProperty("Owner")]
|
||||
public virtual List<ChatRoom>? Rooms { get; set; }
|
||||
|
|
|
|||
32
src/Yavsc.Server/Models/Payment/PerformerDonation.cs
Normal file
32
src/Yavsc.Server/Models/Payment/PerformerDonation.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
#nullable enable
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Yavsc.Models.Payment;
|
||||
|
||||
public enum PerformerDonationState { Created, AwaitingApproval, Processing, Pending, Completed, Cancelled, Failed }
|
||||
|
||||
public sealed class PerformerDonation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
[Required, MaxLength(450)]
|
||||
public string DonorId { get; set; } = "";
|
||||
[Required, MaxLength(450)]
|
||||
public string PerformerId { get; set; } = "";
|
||||
[Required, EmailAddress, MaxLength(127)]
|
||||
public string RecipientEmail { get; set; } = "";
|
||||
[Column(TypeName = "numeric(18,2)")]
|
||||
public decimal Amount { get; set; }
|
||||
[Required, MaxLength(3)]
|
||||
public string Currency { get; set; } = "EUR";
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public PerformerDonationState State { get; set; }
|
||||
[MaxLength(100)]
|
||||
public string? CheckoutToken { get; set; }
|
||||
[MaxLength(32)]
|
||||
public string? TransactionId { get; set; }
|
||||
public DateTimeOffset? CompletedAt { get; set; }
|
||||
[ConcurrencyCheck]
|
||||
public Guid Revision { get; set; } = Guid.NewGuid();
|
||||
}
|
||||
|
|
@ -51,6 +51,9 @@ namespace Yavsc.Models.Workflow
|
|||
[Display(Name="Active")]
|
||||
public bool Active { get; set; }
|
||||
|
||||
[EmailAddress, MaxLength(127), ScaffoldColumn(false), JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public string? DonationPayPalEmail { get; set; }
|
||||
|
||||
[Obsolete("Implement and use a new specialization setting")]
|
||||
[Display(Name="Maximal Daily Cost (euro/day)"),DisplayFormat(DataFormatString="{0:C}")]
|
||||
public int? MaxDailyCost { get; set; }
|
||||
|
|
|
|||
79
src/Yavsc.Server/Services/CallSignalValidator.cs
Normal file
79
src/Yavsc.Server/Services/CallSignalValidator.cs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public static class CallSignalValidator
|
||||
{
|
||||
public static void Validate(CallSignal signal, bool relayOnly)
|
||||
{
|
||||
if (signal is null)
|
||||
throw new HubException("A call signal is required.");
|
||||
if (signal.Endpoint != null)
|
||||
throw new HubException("WebRTC signaling cannot carry a LAN endpoint.");
|
||||
if (signal.Kind is "offer" or "answer")
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(signal.Sdp) || Encoding.UTF8.GetByteCount(signal.Sdp) > 24000 ||
|
||||
signal.Sdp.Replace("\r\n", "").Any(c => c is '\r' or '\n') ||
|
||||
!signal.Sdp.StartsWith("v=0\r\n", StringComparison.Ordinal) ||
|
||||
!signal.Sdp.Contains("\r\nm=", StringComparison.Ordinal) ||
|
||||
signal.Candidate != null || signal.SdpMid != null || signal.SdpMLineIndex != null)
|
||||
throw new HubException("Invalid SDP signal.");
|
||||
if (relayOnly) ValidateRelaySdp(signal.Sdp);
|
||||
return;
|
||||
}
|
||||
if (signal.Kind != "candidate" || signal.Sdp != null ||
|
||||
string.IsNullOrWhiteSpace(signal.SdpMid) || signal.SdpMid.Length > 64 ||
|
||||
signal.SdpMid.Any(char.IsControl) || signal.SdpMLineIndex is not (>= 0 and <= 16) ||
|
||||
string.IsNullOrWhiteSpace(signal.Candidate) || Encoding.UTF8.GetByteCount(signal.Candidate) > 2048 ||
|
||||
signal.Candidate.Any(char.IsControl) || !signal.Candidate.StartsWith("candidate:", StringComparison.Ordinal))
|
||||
throw new HubException("Invalid ICE signal.");
|
||||
if (relayOnly && !IsRelayCandidate(signal.Candidate))
|
||||
throw new HubException("Only relay ICE candidates are allowed.");
|
||||
}
|
||||
|
||||
private static bool IsRelayCandidate(string candidate)
|
||||
{
|
||||
var tokens = candidate.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (tokens.Length < 8 || tokens[6] != "typ" || tokens[7] != "relay")
|
||||
return false;
|
||||
for (var i = 8; i < tokens.Length; i++)
|
||||
if (tokens[i] == "raddr" &&
|
||||
(i + 1 >= tokens.Length || !IsUnspecified(tokens[i + 1])))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsUnspecified(string address) => address is "0.0.0.0" or "::";
|
||||
|
||||
private static void ValidateRelaySdp(string sdp)
|
||||
{
|
||||
var lines = sdp.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
|
||||
HashSet<string> relayAddresses = [];
|
||||
foreach (var line in lines.Where(l => l.StartsWith("a=candidate:", StringComparison.Ordinal)))
|
||||
{
|
||||
if (!IsRelayCandidate(line[2..]))
|
||||
throw new HubException("SDP contains a non-relay candidate or a related address.");
|
||||
relayAddresses.Add(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)[4]);
|
||||
}
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line.StartsWith("o=", StringComparison.Ordinal))
|
||||
{
|
||||
var address = line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Last();
|
||||
if (!IsUnspecified(address) && address != "127.0.0.1")
|
||||
throw new HubException("SDP origin must not expose a participant address.");
|
||||
}
|
||||
if (line.StartsWith("c=", StringComparison.Ordinal) ||
|
||||
(line.StartsWith("a=rtcp:", StringComparison.Ordinal) && line.Contains(" IN ", StringComparison.Ordinal)))
|
||||
{
|
||||
var address = line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Last();
|
||||
if (!IsUnspecified(address) && !relayAddresses.Contains(address))
|
||||
throw new HubException("SDP connection address is not an included relay address.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
312
src/Yavsc.Server/Services/CallSignalingService.cs
Normal file
312
src/Yavsc.Server/Services/CallSignalingService.cs
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
#nullable enable
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
using Yavsc.Server.Hubs;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public sealed class CallSignalingService(
|
||||
IHubContext<ChatHub> hub,
|
||||
IOptions<AudioVideoCallOptions> options,
|
||||
TimeProvider clock,
|
||||
ILogger<CallSignalingService> logger) : BackgroundService
|
||||
{
|
||||
private sealed class PendingCall(CallSession session, string callerConnection, string[] calleeConnections)
|
||||
{
|
||||
public CallSession Session { get; set; } = session;
|
||||
public string CallerConnection { get; } = callerConnection;
|
||||
public HashSet<string> CalleeConnections { get; } = [.. calleeConnections];
|
||||
public string? AcceptedConnection { get; set; }
|
||||
public bool Offered { get; set; }
|
||||
public bool Answered { get; set; }
|
||||
public int CandidateCount { get; set; }
|
||||
public HashSet<string> EndpointConnections { get; } = [];
|
||||
public string[] Connections => [CallerConnection, .. CalleeConnections];
|
||||
}
|
||||
|
||||
private readonly SemaphoreSlim _gate = new(1);
|
||||
private readonly Dictionary<Guid, PendingCall> _calls = [];
|
||||
private readonly AudioVideoCallOptions _options = options.Value;
|
||||
|
||||
public async Task<CallSession> InviteAsync(
|
||||
string room, string caller, string callee, string callerConnection,
|
||||
string[] calleeConnections, bool relayOnly, string transport = CallTransports.WebRtc)
|
||||
{
|
||||
EnsureEnabled();
|
||||
if (caller == callee || calleeConnections.Length == 0 ||
|
||||
calleeConnections.Contains(callerConnection))
|
||||
throw new HubException("Call participants are unavailable.");
|
||||
ValidateTransport(transport, relayOnly);
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await ExpireCoreAsync();
|
||||
if (_calls.Count >= 128 || _calls.Values.Any(c =>
|
||||
c.Session.Caller == caller || c.Session.Callee == caller ||
|
||||
c.Session.Caller == callee || c.Session.Callee == callee))
|
||||
throw new HubException("A participant is already in a call.");
|
||||
var session = new CallSession(Guid.NewGuid(), room, caller, callee, relayOnly,
|
||||
clock.GetUtcNow().AddSeconds(45), transport);
|
||||
var call = new PendingCall(session, callerConnection, calleeConnections);
|
||||
_calls.Add(session.Id, call);
|
||||
try
|
||||
{
|
||||
await hub.Clients.Clients(calleeConnections).SendAsync(CallHubMethods.Invitation, session);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_calls.Remove(session.Id);
|
||||
logger.LogWarning("Could not deliver call invitation {CallId}", session.Id);
|
||||
throw;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task AcceptAsync(Guid id, string user, string connection, bool relayOnly)
|
||||
{
|
||||
EnsureEnabled();
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await ExpireCoreAsync();
|
||||
var call = Find(id);
|
||||
if (call.Session.Callee != user || !call.CalleeConnections.Contains(connection))
|
||||
throw new HubException("Only an invited device can accept this call.");
|
||||
if (call.AcceptedConnection != null)
|
||||
throw new HubException("This call was already accepted.");
|
||||
var requireRelay = call.Session.RelayOnly || relayOnly;
|
||||
ValidateTransport(call.Session.Transport, requireRelay);
|
||||
call.AcceptedConnection = connection;
|
||||
call.Session = call.Session with
|
||||
{
|
||||
RelayOnly = requireRelay,
|
||||
ExpiresAt = clock.GetUtcNow().AddHours(1)
|
||||
};
|
||||
var otherDevices = call.CalleeConnections.Where(c => c != connection).ToArray();
|
||||
call.CalleeConnections.IntersectWith([connection]);
|
||||
var accepted = new CallAccepted(call.Session, call.Session.Transport == CallTransports.LanSrtp
|
||||
? [] : CreateIceServers(call.Session));
|
||||
try
|
||||
{
|
||||
if (otherDevices.Length > 0)
|
||||
await hub.Clients.Clients(otherDevices).SendAsync(
|
||||
CallHubMethods.Ended, new CallEnded(id, "answered-elsewhere"));
|
||||
await hub.Clients.Clients([call.CallerConnection, connection])
|
||||
.SendAsync(CallHubMethods.Accepted, accepted);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await FinishCoreAsync(call, "delivery-failed");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task SignalAsync(Guid id, string user, string connection, CallSignal signal)
|
||||
{
|
||||
EnsureEnabled();
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await ExpireCoreAsync();
|
||||
var call = Find(id);
|
||||
var caller = call.CallerConnection == connection && call.Session.Caller == user;
|
||||
var callee = call.AcceptedConnection == connection && call.Session.Callee == user;
|
||||
if ((!caller && !callee) || call.AcceptedConnection == null)
|
||||
throw new HubException("Media signaling requires acceptance on this device.");
|
||||
if (call.Session.Transport == CallTransports.LanSrtp)
|
||||
{
|
||||
ValidateTransport(call.Session.Transport, call.Session.RelayOnly);
|
||||
if (signal is null || signal.Kind != "rtp-endpoint" || signal.Endpoint?.IsValid() != true ||
|
||||
signal.Sdp != null || signal.Candidate != null || signal.SdpMid != null ||
|
||||
signal.SdpMLineIndex != null || call.EndpointConnections.Contains(connection))
|
||||
throw new HubException("A LAN call requires one valid SRTP endpoint per accepted device.");
|
||||
var endpointTarget = caller ? call.AcceptedConnection : call.CallerConnection;
|
||||
await hub.Clients.Client(endpointTarget).SendAsync(CallHubMethods.SignalReceived, id, signal);
|
||||
call.EndpointConnections.Add(connection);
|
||||
return;
|
||||
}
|
||||
CallSignalValidator.Validate(signal, call.Session.RelayOnly);
|
||||
switch (signal.Kind)
|
||||
{
|
||||
case "offer":
|
||||
if (!caller || call.Offered)
|
||||
throw new HubException("Only the caller can send the initial offer once.");
|
||||
break;
|
||||
case "answer":
|
||||
if (!callee || !call.Offered || call.Answered)
|
||||
throw new HubException("An answer requires the initial offer.");
|
||||
break;
|
||||
case "candidate":
|
||||
if ((caller && !call.Offered) || (callee && !call.Answered) || call.CandidateCount >= 256)
|
||||
throw new HubException("ICE candidate is out of sequence or exceeds the call limit.");
|
||||
break;
|
||||
}
|
||||
var target = caller ? call.AcceptedConnection : call.CallerConnection;
|
||||
await hub.Clients.Client(target).SendAsync(CallHubMethods.SignalReceived, id, signal);
|
||||
if (signal.Kind == "offer") call.Offered = true;
|
||||
if (signal.Kind == "answer") call.Answered = true;
|
||||
if (signal.Kind == "candidate") call.CandidateCount++;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task EndAsync(Guid id, string user, string connection)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var call = Find(id);
|
||||
if (!(call.Session.Caller == user && call.CallerConnection == connection) &&
|
||||
!(call.Session.Callee == user && (call.AcceptedConnection == connection ||
|
||||
(call.AcceptedConnection == null && call.CalleeConnections.Contains(connection)))))
|
||||
throw new HubException("This device does not participate in the call.");
|
||||
await FinishCoreAsync(call, call.AcceptedConnection == null ? "cancelled-or-declined" : "hangup");
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<CallSession> GetSessionAsync(Guid id, string user, string connection)
|
||||
{
|
||||
EnsureEnabled();
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await ExpireCoreAsync();
|
||||
var call = Find(id);
|
||||
if (!(call.Session.Caller == user && call.CallerConnection == connection) &&
|
||||
!(call.Session.Callee == user && call.CalleeConnections.Contains(connection)))
|
||||
throw new HubException("This device does not participate in the call.");
|
||||
return call.Session;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task EndForUserAsync(string user, string reason, string? room = null)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
foreach (var call in _calls.Values.Where(c =>
|
||||
(c.Session.Caller == user || c.Session.Callee == user) &&
|
||||
(room == null || c.Session.RoomName == room)).ToArray())
|
||||
await FinishCoreAsync(call, reason);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(string connection)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
foreach (var call in _calls.Values.ToArray())
|
||||
{
|
||||
if (call.CallerConnection == connection || call.AcceptedConnection == connection)
|
||||
await FinishCoreAsync(call, "disconnected");
|
||||
else if (call.CalleeConnections.Remove(connection) && call.CalleeConnections.Count == 0)
|
||||
await FinishCoreAsync(call, "disconnected");
|
||||
}
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task ExpireAsync()
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try { await ExpireCoreAsync(); }
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), clock);
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
await ExpireAsync();
|
||||
}
|
||||
|
||||
private PendingCall Find(Guid id) => _calls.TryGetValue(id, out var call)
|
||||
? call : throw new HubException("Call not found or expired.");
|
||||
|
||||
private async Task ExpireCoreAsync()
|
||||
{
|
||||
foreach (var call in _calls.Values.Where(c => c.Session.ExpiresAt <= clock.GetUtcNow()).ToArray())
|
||||
await FinishCoreAsync(call, "expired");
|
||||
}
|
||||
|
||||
private async Task FinishCoreAsync(PendingCall call, string reason)
|
||||
{
|
||||
_calls.Remove(call.Session.Id);
|
||||
await hub.Clients.Clients(call.Connections)
|
||||
.SendAsync(CallHubMethods.Ended, new CallEnded(call.Session.Id, reason));
|
||||
}
|
||||
|
||||
private void EnsureEnabled()
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
throw new HubException("Audio/video calls are not enabled on this server.");
|
||||
}
|
||||
|
||||
private void ValidateIceConfiguration(bool relayOnly)
|
||||
{
|
||||
if (_options.StunUrls.Any(url => !ValidUrl(url, "stun", "stuns")) ||
|
||||
_options.TurnUrls.Any(url => !ValidUrl(url, "turn", "turns")) ||
|
||||
(_options.TurnUrls.Length > 0 && string.IsNullOrWhiteSpace(_options.TurnSharedSecret)) ||
|
||||
(relayOnly && _options.TurnUrls.Length == 0))
|
||||
throw new HubException("ICE/TURN configuration is unavailable. No direct fallback is allowed.");
|
||||
}
|
||||
|
||||
private void ValidateTransport(string transport, bool relayOnly)
|
||||
{
|
||||
if (transport == CallTransports.LanSrtp)
|
||||
{
|
||||
if (!_options.EnableLanCalls || relayOnly)
|
||||
throw new HubException("LAN calls must be enabled and cannot hide participant IP addresses.");
|
||||
}
|
||||
else if (transport == CallTransports.WebRtc)
|
||||
ValidateIceConfiguration(relayOnly);
|
||||
else
|
||||
throw new HubException("Unsupported call transport.");
|
||||
}
|
||||
|
||||
private static bool ValidUrl(string url, params string[] schemes)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url) || url.Length > 512 || url.Any(char.IsWhiteSpace))
|
||||
return false;
|
||||
var separator = url.IndexOf(':');
|
||||
if (separator <= 0 || !schemes.Contains(url[..separator]))
|
||||
return false;
|
||||
var endpoint = url[(separator + 1)..];
|
||||
if (endpoint.Contains('/') || !Uri.TryCreate("http://" + endpoint, UriKind.Absolute, out var uri) ||
|
||||
string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0 ||
|
||||
uri.UserInfo.Length > 0 || uri.Fragment.Length > 0)
|
||||
return false;
|
||||
return uri.Query.Length == 0 || (url.StartsWith("turn", StringComparison.Ordinal) &&
|
||||
uri.Query is "?transport=udp" or "?transport=tcp");
|
||||
}
|
||||
|
||||
private CallIceServer[] CreateIceServers(CallSession session)
|
||||
{
|
||||
List<CallIceServer> result = [];
|
||||
if (!session.RelayOnly && _options.StunUrls.Length > 0)
|
||||
result.Add(new CallIceServer(_options.StunUrls));
|
||||
if (_options.TurnUrls.Length > 0)
|
||||
{
|
||||
var username = $"{session.ExpiresAt.AddMinutes(5).ToUnixTimeSeconds()}:{Guid.NewGuid():N}";
|
||||
var credential = Convert.ToBase64String(HMACSHA1.HashData(
|
||||
Encoding.UTF8.GetBytes(_options.TurnSharedSecret!), Encoding.UTF8.GetBytes(username)));
|
||||
result.Add(new CallIceServer(_options.TurnUrls, username, credential));
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -91,7 +91,13 @@ namespace Yavsc.Services
|
|||
List<string> cxIds;
|
||||
if (ChatCxIds.TryGetValue(uname, out cxIds))
|
||||
{
|
||||
cxIds.Remove(connectionId);
|
||||
lock (cxIds)
|
||||
{
|
||||
cxIds.Remove(connectionId);
|
||||
// Room presence is account-wide while another device is connected.
|
||||
if (cxIds.Count > 0)
|
||||
return;
|
||||
}
|
||||
foreach (var room in ChatRoomPresence[uname])
|
||||
{
|
||||
Part(connectionId, room, "connexion aborted");
|
||||
|
|
@ -250,7 +256,10 @@ namespace Yavsc.Services
|
|||
|
||||
public IEnumerable<string> GetConnexionIds(string userName)
|
||||
{
|
||||
return ChatCxIds.ContainsKey(userName) ? ChatCxIds[userName] : null;
|
||||
if (!ChatCxIds.TryGetValue(userName, out var connections))
|
||||
return Array.Empty<string>();
|
||||
lock (connections)
|
||||
return connections.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
14
src/Yavsc.Server/Settings/AudioVideoCallOptions.cs
Normal file
14
src/Yavsc.Server/Settings/AudioVideoCallOptions.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#nullable enable
|
||||
|
||||
namespace Yavsc.Settings;
|
||||
|
||||
public sealed class AudioVideoCallOptions
|
||||
{
|
||||
public const string SectionName = "AudioVideoCalls";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
public bool EnableLanCalls { get; set; }
|
||||
public string[] StunUrls { get; set; } = [];
|
||||
public string[] TurnUrls { get; set; } = [];
|
||||
public string? TurnSharedSecret { get; set; }
|
||||
}
|
||||
|
|
@ -7,10 +7,10 @@
|
|||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<RepositoryUrl>https://forgejo.pschneider.fr/notazof/yavsc</RepositoryUrl>
|
||||
<Library>true</Library>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Anthropic.SDK" />
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@
|
|||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>Yavsc.cli</RootNamespace>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Razor" />
|
||||
|
|
|
|||
182
src/test/Yavsc.Api.Tests/AccountCallPreferenceTests.cs
Normal file
182
src/test/Yavsc.Api.Tests/AccountCallPreferenceTests.cs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Yavsc.Abstract.Identity;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
using Yavsc.Api.Test.Fixtures;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Tests.Shared;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Api.Test;
|
||||
|
||||
[Collection("Yavsc Api")]
|
||||
public sealed class AccountCallPreferenceTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
|
||||
{
|
||||
private const string Endpoint = "/api/v1/account/me";
|
||||
|
||||
private HttpClient Client(string? subject, string scope = "api")
|
||||
{
|
||||
var client = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
|
||||
}) { BaseAddress = new Uri(fixture.BaseAddress) };
|
||||
if (subject is not null)
|
||||
{
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(subject, scope));
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
private async Task<string> CreateUserAsync()
|
||||
{
|
||||
var id = "call-preference-" + Guid.NewGuid().ToString("N");
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.Users.Add(new ApplicationUser { Id = id, UserName = id, Email = $"{id}@example.test" });
|
||||
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
return id;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Preference_is_not_exposed_when_a_user_entity_is_serialized()
|
||||
{
|
||||
var user = new ApplicationUser { HideIpAddressInCalls = true };
|
||||
Assert.DoesNotContain(nameof(ApplicationUser.HideIpAddressInCalls), JsonSerializer.Serialize(user));
|
||||
Assert.DoesNotContain(nameof(ApplicationUser.HideIpAddressInCalls), Newtonsoft.Json.JsonConvert.SerializeObject(user));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Preference_defaults_to_false_and_round_trips_across_clients_and_database_contexts()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = await CreateUserAsync();
|
||||
using var firstDevice = Client(id);
|
||||
var initial = await firstDevice.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(initial);
|
||||
Assert.False(initial.HideIpAddressInCalls);
|
||||
|
||||
foreach (var value in new[] { true, false })
|
||||
{
|
||||
using var response = await firstDevice.PutAsJsonAsync(Endpoint,
|
||||
new ProfileUpdateRequest { HideIpAddressInCalls = value }, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var saved = await response.Content.ReadFromJsonAsync<JsonElement>(ct);
|
||||
Assert.Equal(value, saved.GetProperty("hideIpAddressInCalls").GetBoolean());
|
||||
|
||||
using var secondDevice = Client(id);
|
||||
var profile = await secondDevice.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Equal(value, profile.HideIpAddressInCalls);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Equal(value, (await db.Users.AsNoTracking().SingleAsync(u => u.Id == id, ct)).HideIpAddressInCalls);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Omitted_or_null_preference_does_not_reset_an_existing_value(bool explicitNull)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = await CreateUserAsync();
|
||||
using var client = Client(id);
|
||||
using var enabled = await client.PutAsJsonAsync(Endpoint, new { hideIpAddressInCalls = true }, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, enabled.StatusCode);
|
||||
|
||||
using var update = explicitNull
|
||||
? await client.PutAsJsonAsync(Endpoint, new { fullName = "Updated profile", hideIpAddressInCalls = (bool?)null }, ct)
|
||||
: await client.PutAsJsonAsync(Endpoint, new { fullName = "Updated profile" }, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, update.StatusCode);
|
||||
var profile = await client.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(profile);
|
||||
Assert.True(profile.HideIpAddressInCalls);
|
||||
Assert.Equal("Updated profile", profile.FullName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_uses_the_authenticated_account_not_a_user_id_in_the_payload()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var owner = await CreateUserAsync();
|
||||
var other = await CreateUserAsync();
|
||||
using var client = Client(owner);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint,
|
||||
new { userId = other, hideIpAddressInCalls = true }, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using var otherClient = Client(other);
|
||||
var otherProfile = await otherClient.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(otherProfile);
|
||||
Assert.False(otherProfile.HideIpAddressInCalls);
|
||||
var ownProfile = await client.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(ownProfile);
|
||||
Assert.True(ownProfile.HideIpAddressInCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "api", HttpStatusCode.Unauthorized)]
|
||||
[InlineData("unknown-account", "profile", HttpStatusCode.Forbidden)]
|
||||
[InlineData("unknown-account", "api", HttpStatusCode.NotFound)]
|
||||
public async Task Read_and_write_require_an_existing_authenticated_account_and_api_scope(
|
||||
string? subject, string scope, HttpStatusCode expected)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var client = Client(subject, scope);
|
||||
using var read = await client.GetAsync(Endpoint, ct);
|
||||
Assert.Equal(expected, read.StatusCode);
|
||||
using var write = await client.PutAsJsonAsync(Endpoint, new { hideIpAddressInCalls = true }, ct);
|
||||
Assert.Equal(expected, write.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_boolean_is_rejected_without_saving_other_profile_changes()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = await CreateUserAsync();
|
||||
using var client = Client(id);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint,
|
||||
new { fullName = "Must not be saved", hideIpAddressInCalls = "invalid" }, ct);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
var profile = await client.GetFromJsonAsync<Me>(Endpoint, ct);
|
||||
Assert.NotNull(profile);
|
||||
Assert.False(profile.HideIpAddressInCalls);
|
||||
Assert.NotEqual("Must not be saved", profile.FullName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Activating_privacy_ends_an_existing_call_before_returning_success()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = await CreateUserAsync();
|
||||
var other = await CreateUserAsync();
|
||||
var options = fixture.Services.GetRequiredService<IOptions<AudioVideoCallOptions>>().Value;
|
||||
var calls = fixture.Services.GetRequiredService<CallSignalingService>();
|
||||
var delivery = fixture.Services.GetRequiredService<RecordingMessageDelivery>();
|
||||
options.Enabled = true;
|
||||
try
|
||||
{
|
||||
var call = await calls.InviteAsync("General", id, other, "preference-caller", ["preference-callee"], false);
|
||||
await calls.AcceptAsync(call.Id, other, "preference-callee", false);
|
||||
using var client = Client(id);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint, new { hideIpAddressInCalls = true }, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains(delivery.Pushes, p => p.Method == CallHubMethods.Ended &&
|
||||
p.Arguments[0] is CallEnded ended && ended.CallId == call.Id && ended.Reason == "profile-changed");
|
||||
await Assert.ThrowsAsync<HubException>(() => calls.GetSessionAsync(call.Id, id, "preference-caller"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await calls.EndForUserAsync(id, "test-cleanup");
|
||||
options.Enabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -81,8 +81,12 @@ public sealed class ApiWebServerFixture : WebHostFixture
|
|||
builder.Services.AddInvoicing(builder.Configuration);
|
||||
builder.Services.AddSingleton<RecordingMessageDelivery>();
|
||||
builder.Services.AddSingleton<ITrueEmailSender>(sp => sp.GetRequiredService<RecordingMessageDelivery>());
|
||||
builder.Services.AddTransient<ICalendarManager, CalendarManager>();
|
||||
builder.Services.AddSingleton<IHubContext<ChatHub>>(sp => sp.GetRequiredService<RecordingMessageDelivery>());
|
||||
builder.Services.AddSingleton<IConnexionManager, HubConnectionManager>();
|
||||
builder.Services.Configure<Yavsc.Settings.AudioVideoCallOptions>(_ => { });
|
||||
builder.Services.AddSingleton(TimeProvider.System);
|
||||
builder.Services.AddSingleton<CallSignalingService>();
|
||||
builder.Services.AddTransient<IYavscMessageSender, YavscMessageSender>();
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -16,8 +16,8 @@ public sealed class RecordingMessageDelivery : ITrueEmailSender, IHubContext<Cha
|
|||
IGroupManager IHubContext<ChatHub>.Groups => throw new NotSupportedException();
|
||||
public IClientProxy All => throw new NotSupportedException();
|
||||
public IClientProxy AllExcept(IReadOnlyList<string> excludedConnectionIds) => throw new NotSupportedException();
|
||||
public IClientProxy Client(string connectionId) => new RecordingClient(this, connectionId);
|
||||
public IClientProxy Clients(IReadOnlyList<string> connectionIds) => throw new NotSupportedException();
|
||||
public IClientProxy Client(string connectionId) => new RecordingClient(this, [connectionId]);
|
||||
public IClientProxy Clients(IReadOnlyList<string> connectionIds) => new RecordingClient(this, connectionIds);
|
||||
public IClientProxy Group(string groupName) => throw new NotSupportedException();
|
||||
public IClientProxy GroupExcept(string groupName, IReadOnlyList<string> excludedConnectionIds) => throw new NotSupportedException();
|
||||
public IClientProxy Groups(IReadOnlyList<string> groupNames) => throw new NotSupportedException();
|
||||
|
|
@ -36,11 +36,12 @@ public sealed class RecordingMessageDelivery : ITrueEmailSender, IHubContext<Cha
|
|||
Pushes.Clear();
|
||||
}
|
||||
|
||||
private sealed class RecordingClient(RecordingMessageDelivery delivery, string connectionId) : IClientProxy
|
||||
private sealed class RecordingClient(RecordingMessageDelivery delivery, IReadOnlyList<string> connectionIds) : IClientProxy
|
||||
{
|
||||
public Task SendCoreAsync(string method, object?[] args, CancellationToken cancellationToken = default)
|
||||
{
|
||||
delivery.Pushes.Enqueue(new Push(connectionId, method, args));
|
||||
foreach (var connectionId in connectionIds)
|
||||
delivery.Pushes.Enqueue(new Push(connectionId, method, args));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
172
src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs
Normal file
172
src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Yavsc.Abstract.Workflow;
|
||||
using Yavsc.Api.Test.Fixtures;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Relationship;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Tests.Shared;
|
||||
|
||||
namespace Yavsc.Api.Test;
|
||||
|
||||
[Collection("Yavsc Api")]
|
||||
public sealed class PerformerDonationSettingsTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
|
||||
{
|
||||
private const string Endpoint = "/api/v1/account/performer-profile";
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private HttpClient Client(string? subject, string scope = "api")
|
||||
{
|
||||
var client = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
|
||||
}) { BaseAddress = new Uri(fixture.BaseAddress) };
|
||||
if (subject != null)
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
|
||||
TestTokenIssuer.Issue(subject, scope, extraClaims: [new Claim(Yavsc.Constants.RoleClaimType, "Performer")]));
|
||||
return client;
|
||||
}
|
||||
|
||||
private async Task<string> CreatePerformerAsync(bool withProfile = true)
|
||||
{
|
||||
var id = "donation-settings-" + Guid.NewGuid().ToString("N");
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.Users.Add(new ApplicationUser { Id = id, UserName = id, Email = id + "@example.test" });
|
||||
if (withProfile) db.Performers.Add(new PerformerProfile
|
||||
{
|
||||
PerformerId = id, SIREN = "123456789", WebSite = "", Active = true,
|
||||
DonationPayPalEmail = "initial@payments.example",
|
||||
OrganizationAddress = new Location { Address = "Test" }
|
||||
});
|
||||
await db.SaveChangesAsync(Ct);
|
||||
return id;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task New_performer_can_set_a_recipient_when_creating_their_profile()
|
||||
{
|
||||
var id = await CreatePerformerAsync(withProfile: false);
|
||||
using var client = Client(id);
|
||||
var profile = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Equal("", profile.DonationPayPalEmail);
|
||||
profile.DonationPayPalEmail = "new@payments.example";
|
||||
using var response = await client.PutAsJsonAsync(Endpoint, profile, Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("new@payments.example",
|
||||
(await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct))?.DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(" new@payments.example ", "new@payments.example")]
|
||||
[InlineData(" ", "")]
|
||||
public async Task Recipient_is_trimmed_and_whitespace_disables_donations(string input, string expected)
|
||||
{
|
||||
var id = await CreatePerformerAsync();
|
||||
using var client = Client(id);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint, new { donationPayPalEmail = input }, Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(expected,
|
||||
(await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct))?.DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Performer_can_read_update_and_disable_their_paypal_recipient_across_devices()
|
||||
{
|
||||
var id = await CreatePerformerAsync();
|
||||
using var client = Client(id);
|
||||
var profile = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Equal("initial@payments.example", profile.DonationPayPalEmail);
|
||||
using var read = await client.GetAsync(Endpoint, Ct);
|
||||
Assert.True(read.Headers.CacheControl?.NoStore);
|
||||
foreach (var email in new[] { "new@payments.example", "" })
|
||||
{
|
||||
profile.DonationPayPalEmail = email;
|
||||
using var response = await client.PutAsJsonAsync(Endpoint, profile, Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var otherDevice = Client(id);
|
||||
var reloaded = await otherDevice.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
|
||||
Assert.NotNull(reloaded);
|
||||
Assert.Equal(email, reloaded.DonationPayPalEmail);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var stored = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.Performers.AsNoTracking().SingleAsync(p => p.PerformerId == id, Ct);
|
||||
Assert.Equal(email.Length == 0 ? null : email, stored.DonationPayPalEmail);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Older_clients_omitting_or_sending_null_preserve_the_paypal_recipient(bool explicitNull)
|
||||
{
|
||||
var id = await CreatePerformerAsync();
|
||||
using var client = Client(id);
|
||||
using var response = explicitNull
|
||||
? await client.PutAsJsonAsync(Endpoint, new { performerId = id, donationPayPalEmail = (string?)null }, Ct)
|
||||
: await client.PutAsJsonAsync(Endpoint, new { performerId = id }, Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var reloaded = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
|
||||
Assert.Equal("initial@payments.example", reloaded?.DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("invalid")]
|
||||
[InlineData("https://payments.example/donate")]
|
||||
[InlineData("a@b@c.example")]
|
||||
public async Task Invalid_recipient_returns_400_without_changing_the_profile(string email)
|
||||
{
|
||||
var id = await CreatePerformerAsync();
|
||||
using var client = Client(id);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint,
|
||||
new { performerId = id, donationPayPalEmail = email, webSite = "must-not-be-saved" }, Ct);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
var profile = await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct);
|
||||
Assert.Equal("initial@payments.example", profile?.DonationPayPalEmail);
|
||||
Assert.Equal("", profile?.WebSite);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Too_long_recipient_returns_400_without_saving()
|
||||
{
|
||||
var id = await CreatePerformerAsync();
|
||||
using var client = Client(id);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint,
|
||||
new { donationPayPalEmail = new string('a', 128) + "@example.test" }, Ct);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("initial@payments.example",
|
||||
(await client.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct))?.DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Performer_cannot_write_another_accounts_recipient()
|
||||
{
|
||||
var owner = await CreatePerformerAsync();
|
||||
var other = await CreatePerformerAsync();
|
||||
using var client = Client(owner);
|
||||
using var response = await client.PutAsJsonAsync(Endpoint,
|
||||
new { performerId = other, donationPayPalEmail = "attacker@payments.example" }, Ct);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using var otherClient = Client(other);
|
||||
Assert.Equal("initial@payments.example",
|
||||
(await otherClient.GetFromJsonAsync<PerformerProfileSettings>(Endpoint, Ct))?.DonationPayPalEmail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "api", HttpStatusCode.Unauthorized)]
|
||||
[InlineData("anyone", "profile", HttpStatusCode.Forbidden)]
|
||||
public async Task Read_and_write_require_authentication_and_api_scope(string? subject, string scope, HttpStatusCode expected)
|
||||
{
|
||||
using var client = Client(subject, scope);
|
||||
using var read = await client.GetAsync(Endpoint, Ct);
|
||||
using var write = await client.PutAsJsonAsync(Endpoint, new { donationPayPalEmail = "test@payments.example" }, Ct);
|
||||
Assert.Equal(expected, read.StatusCode);
|
||||
Assert.Equal(expected, write.StatusCode);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,10 +6,10 @@
|
|||
<IsPackable>false</IsPackable>
|
||||
<RootNamespace>Yavsc.Api.Tests</RootNamespace>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<AssemblyVersion>1.0.8.0</AssemblyVersion>
|
||||
<FileVersion>1.0.8.0</FileVersion>
|
||||
<InformationalVersion>1.0.8-458+Branch.main.Sha.ad92744a94c829947994ffef5e8a6598f62868f8</InformationalVersion>
|
||||
<Version>1.0.8-458</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
<InformationalVersion>1.1.0-feat-calls.1+472.Branch.feat-calls.Sha.d8200cb98ddef152313ef1f102b866c50f107cbd</InformationalVersion>
|
||||
<Version>1.1.0-feat-calls.1</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue