diff --git a/CHANGELOG.md b/CHANGELOG.md index 79684a2c7..41b544604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,22 +1,10 @@ # Changelog -## [1.0.8-rc35] - unstable - -### Added - -* [PostIt] Schedule silent OIDC renewal independently of API traffic and SignalR reconnects, while the app is active or background chat is enabled. Derive the wait from the access-token expiration minus the existing 60-second safety margin instead of polling; recalculate after token rotation, login/logout, activity and preference changes. Persist rotated tokens and serialize with request-driven renewal/logout. Run the same maintenance in headless Android chat; background execution and absolute refresh-token lifetime remain subject to Android/identity-provider limits. -* [PostIt.Android] Request Android's battery optimization exemption when explicitly saving settings with background chat enabled, only if not already exempt. Keep automatic settings saves and reconnects free of prompts; refusal does not disable SignalR. -* [PostIt.Android] Add an opt-in ordinary background service for the existing SignalR ChatHub connection, without a permanent notification; show native alerts only for received messages/events and attempt restart after phone startup where Android permits it. Reuse one process-wide connection between service, pages and calls, restore locally remembered rooms per account/host and clean up on opt-out/logout. No Firebase, Google push configuration or server push migration; explain background-data/battery settings and Android execution limits. -* [PostIt/Calls] Support direct IPv6 SRTP calls using global, ULA and loopback addresses, shared endpoint validation, IPv6 UDP sockets and bracketed reception URLs. Exclude scoped/link-local, multicast, unspecified and IPv4-mapped addresses; verify real bidirectional IPv6 audio/video, wrong-key rejection and port lifecycle with LibVLC. -* [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal. -* [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. - ## [1.0.8-rc34] - unstable ### Added -* [PostIt] Share podcast camera/microphone preferences with chat-room calls and persist the selected LAN/VPN address. Restore only currently available network addresses without remembering address-disclosure consent; require an explicit microphone choice for calls when podcasts use no microphone. * [PostIt] Remember detected podcast cameras/microphones, selected devices (including no microphone) and the default title in user settings; restore them when reopening the page and report persistence failures. * [Podcasts] Reuse persisted LiveFlow entities to prepare, edit and delete emissions from PostIt with a title, scheduled start and estimated duration. Keep start/stop manual and plans private; optionally publish presentation-only announcements on Yavsc.Org without opening anonymous playback. Preserve broadcast identifiers, legacy recordings and authenticated HLS/MP4 access; add a scheduling migration and lifecycle/privacy regressions. * [PostIt/API/Yavsc.Org] Expose the private PayPal recipient setting in PostIt's performer editor and authenticated profile API; validate addresses, allow disabling with an empty value and preserve the setting for older clients. Make Web donation settings discoverable from the performer profile and podcast catalogue. diff --git a/doc/Architecture.md b/doc/Architecture.md index 820cd37d0..17df96891 100644 --- a/doc/Architecture.md +++ b/doc/Architecture.md @@ -23,7 +23,6 @@ Chaque sujet est détaillé dans sa propre page (sous | Dictionnaires métier (héritage en arbre) | [dictionnaires-metier.md](architecture/dictionnaires-metier.md) | | Offre fournisseur + frontmatter (`ClasseFormulaire`, `ClasseDevis`, parsing) | [offres-frontmatter.md](architecture/offres-frontmatter.md) | | PostIt / OIDC (client desktop, custom URI scheme, silent refresh) | [postit-oidc.md](architecture/postit-oidc.md) | -| Notifications Web/PostIt, ChatHub et service Android SignalR | [notifications.md](architecture/notifications.md) | ## Stack technique @@ -94,14 +93,6 @@ le materiel disponible en conservant les choix encore presents. Le choix « sans microphone » est memorise lui aussi. Charger le titre d'une emission preparee ne remplace pas le titre par defaut ; une saisie explicite le modifie. Les erreurs de sauvegarde sont affichees dans la page. -Les appels des salons de discussion reutilisent ces memes choix camera/micro -et enregistrent leurs changements dans les memes parametres. La page Podcasts -les recharge a son activation. Les appels exigent toujours un microphone : -le choix podcast « sans microphone » laisse donc le micro d'appel non selectionne. -L'adresse LAN/VPN choisie pour les appels est aussi memorisee, mais restauree -uniquement si elle est encore presente sur une interface locale active. -Sinon, une nouvelle selection est requise. Le consentement au partage -d'adresse avec le pair n'est jamais memorise. PostIt permet de preparer, modifier et supprimer une emission avant son demarrage : titre, date/heure locale, duree entiere positive en minutes et diff --git a/doc/architecture/audio-video-calls.md b/doc/architecture/audio-video-calls.md index 0a15880f1..4c4ee0f26 100644 --- a/doc/architecture/audio-video-calls.md +++ b/doc/architecture/audio-video-calls.md @@ -5,7 +5,7 @@ Ce document décrit l'architecture cible et l'implémentation commencée. La préférence de confidentialité est persistée et éditable dans le profil. La signalisation est intégrée au chat, désactivée par défaut. Un premier -transport natif **Android et Desktop Linux en IPv4/IPv6 directe (LAN/VPN ou IP publique)** est raccordé : +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 @@ -18,28 +18,7 @@ La cible couvre : - les appels de groupe ; - les clients Browser, Android et Desktop. -## Première implémentation Android et Desktop Linux : SRTP direct IPv4/IPv6 - -Les adresses IPv4 publiques directement assignees a une interface locale active -sont egalement disponibles, avec la meme validation unicast cote client, -media et signalisation serveur. Les IPv6 globales (2000::/3), privees ULA -(fc00::/7) et de boucle locale (::1) sont aussi acceptees. Les sockets UDP -utilisent la famille de l'adresse locale et les URL de reception encadrent -les IPv6 de crochets. Les adresses non specifiees, link-local, multicast, -reservees IPv4 (240/4), IPv4-mapped IPv6 et les formes non canoniques ou -avec identifiant de zone sont refusees. Une zone link-local du premier -pair n'est pas reutilisable telle quelle par le second. -Il faut autoriser en entree les deux ports UDP consecutifs choisis et assurer -la joignabilite entre les pairs. Ce support n'ajoute ni ICE/TURN ni traversee -NAT automatique : l'adresse publique d'un routeur ne remplace pas une adresse -assignee a la machine. Le consentement explicite au partage d'IP et le refus -du mode direct pour les comptes masquant leur IP restent inchanges. -Les pairs doivent disposer de routes vers leurs adresses respectives ; -aucune traduction automatique IPv4/IPv6 n'est fournie. Les tests natifs -Linux verifient sur ::1 la reception audio/video bidirectionnelle chiffree, -le rejet d'une mauvaise cle et le cycle de vie des ports RTP/RTCP. -Un appel IPv6 entre deux machines et le transport IPv6 Android restent -a valider en conditions reelles. +## 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** : @@ -88,7 +67,7 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté. H.264/AAC. La version Debian 13 a été utilisée pour les essais Linux. Les deux comptes doivent être présents dans la même salle existante et ne pas se bloquer mutuellement. -3. Dans « Appel direct IPv4/IPv6 (LAN/VPN ou IP publique) », actualiser les périphériques, +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 @@ -100,7 +79,7 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté. adresse doivent utiliser des paires distinctes. Aucun pare-feu n'est modifié automatiquement. 5. Saisir le pseudo exact du destinataire, confirmer la divulgation de - l'adresse IP locale (LAN/VPN ou publique), puis appeler. Le destinataire choisit ses propres + 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. @@ -161,8 +140,7 @@ l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet. Il n'y a aucun repli direct contournant cette préférence. - Pas d'ICE, de STUN, de TURN, de traversée NAT automatique, de groupe, d'interopérabilité Browser, de négociation de codecs ni - d'adaptation de débit. Ce mode exige une connectivite IP directe entre les pairs - (LAN/VPN ou adresse publique assignee), avec les ports UDP ouverts. + 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. diff --git a/doc/architecture/notifications.md b/doc/architecture/notifications.md index a8024d7f7..8cf85cfb8 100644 --- a/doc/architecture/notifications.md +++ b/doc/architecture/notifications.md @@ -20,13 +20,12 @@ clients. | Annonce persistée | Entité `Notification` en base, API HTTP | Affichée dans le layout et masquable | Liste sur `HomePage`, chargée par HTTP et masquable | | Message d'interface | Liste de portée requête dans `ViewBag.Notify` | Affichée comme alerte dans le layout | Non consommé | | Événement de chat | Hub SignalR authentifié à `/chathub` | Le site Web n'en consomme pas dans ses vues MVC | `notifyUser` et `notifyRoom` alimentent les journaux du chat | -| Événement métier `push` | SignalR vers les connexions actives, plus e-mail | Pas de consommateur identifié dans les vues Web | Alerte native par le service Android ; liste persistée sur l'accueil via HTTP | -| Alerte native Android | Connexion SignalR existante | Sans objet | Service de fond facultatif ; notification seulement à réception d'un événement | +| Événement métier `push` | SignalR vers les connexions actives, plus e-mail | Pas de consommateur identifié dans les vues Web | Pas de gestionnaire `push` dans le client PostIt actuel | Les notifications persistées sont donc différentes d'une notification système native (notification du navigateur ou du système d'exploitation). Le client -PostIt affiche une liste dans sa page d'accueil. Sur Android, le service de -messagerie peut aussi afficher des notifications natives, après autorisation. +PostIt affiche une liste dans sa page d'accueil ; il ne demande pas de +permission de notification native. ## 1. Annonces persistées @@ -174,7 +173,6 @@ Les événements de notification émis par le hub comprennent notamment : | `notifyRoom` | `type`, salon, utilisateur ou détail | Ajout au journal du salon ; met à jour la liste d'utilisateurs sur `UserJoin` | | `joint` | `ChatRoomInfo` | Initialise la vue du salon rejoint | | `ReceiveMessage` | message avec nom, salon et corps | Ajoute le message à l'historique du salon | -| `addPV` | expéditeur, texte privé | Ajoute le message privé au journal système ; alerte native Android en arrière-plan | | `notifyUserInRoom` | `type`, salon, message | Pas de gestionnaire correspondant dans `ChatViewModel` actuellement | Les constantes de types du chat sont déclarées dans @@ -183,171 +181,23 @@ Les messages `notifyUser` et `notifyRoom` ne sont pas enregistrés en base : ils décrivent l'état temps réel de connexion, de salon ou les erreurs de conversation. -Le singleton -[`ChatHubConnection`](../../src/PostIt/PostIt/Services/ChatHubConnection.cs) +Le [`ChatViewModel`](../../src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs) ouvre le hub avec le jeton d'accès PostIt, tente un renouvellement silencieux -du jeton et active la reconnexion automatique. Il est partagé par le service -Android, le -[`ChatViewModel`](../../src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs) -et la signalisation des appels : ouvrir la page ne crée pas une seconde -connexion. - -Le transport conserve en mémoire les 500 dernières livraisons de messages -privés et de salon pour les présenter si l'interface s'ouvre après le -démarrage du service. Ce tampon est borné, non persisté sur disque et vidé -à l'arrêt de la connexion ou au changement de compte. Il ne permet pas de -récupérer les messages envoyés lorsque le socket était déconnecté. - -Les salons sont mémorisés localement, par hôte et compte, dans -`Settings.ChatRoomsByAccount`. Le transport les rejoint à nouveau après une -reconnexion ou un redémarrage du processus, sans dépendre de l'interface -Avalonia. « Quitter le salon » supprime cette mémorisation. Cela n'ajoute pas -d'abonnement serveur hors ligne ni d'historique des messages manqués. -Les callbacks destinés aux collections de l'interface sont dispatchés sur -le thread UI et les callbacks obsolètes sont ignorés après déconnexion. +du jeton, et active la reconnexion automatique. Après reconnexion, il rejoint +à nouveau le salon sélectionné, car la connexion SignalR précédente et ses +groupes ne sont plus actifs. Les callbacks mettent à jour les collections sur +le thread UI d'Avalonia. ### Événement métier `push` En plus des événements du chat, `YavscMessageSender` utilise le même contexte SignalR pour émettre `push` avec le topic et une charge utile sérialisée. Ce -nom d'événement est distinct de `notifyUser` et `notifyRoom`. Le service -Android peut en afficher une alerte native ; les annonces métier persistées -restent visibles dans PostIt lors du prochain chargement ou rafraîchissement -HTTP. +nom d'événement est distinct de `notifyUser` et `notifyRoom`. Aucun +gestionnaire `push` n'est présent dans le client PostIt actuel : les annonces +métier persistées sont visibles dans PostIt lors du prochain chargement ou +rafraîchissement HTTP. -## 5. Android : connexion SignalR en arrière-plan - -### Réglage utilisateur et durée de vie - -`AndroidKeepChatConnected`, désactivé par défaut, est éditable dans les -paramètres Android : -« Garder la connexion au serveur active et la reprendre au démarrage du -téléphone ». Enregistrer les paramètres pour appliquer le changement. - -Lorsque l'utilisateur clique sur « Sauver » avec cette option activée, -PostIt vérifie `PowerManager.IsIgnoringBatteryOptimizations` : -- si l'application n'est pas exemptée, ouvrir - `ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` avec l'URI `package:...` ; -- si elle est déjà exemptée, ne rien ouvrir ni demander. - -La permission `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` est déclarée pour -cette demande explicite. Android conserve la décision finale ; refuser -ne désactive ni l'option ni SignalR. Les sauvegardes internes (jetons, -salons), reconnexions et démarrages du téléphone n'ouvrent pas cet écran. -Cette demande directe d'exemption est soumise aux règles Google Play -applicables à l'usage de cette permission ; sa présence ne vaut pas -approbation pour la publication. - -- **Désactivé** : le chat reste connecté pendant la vie du processus PostIt, - même si l'activité est masquée, mais rien ne garantit que ce processus - survive en arrière-plan. Les messages alimentent le journal ; les alertes - natives en arrière-plan nécessitent le service activé. -- **Activé** : un service Android ordinaire héberge la même connexion - SignalR, **sans notification permanente**. Un récepteur - `BOOT_COMPLETED` tente de reprendre ce service si l'option et une session - enregistrée sont encore disponibles. -- La fermeture d'une page ou de l'activité ne ferme pas la messagerie. - La déconnexion du compte arrête le service et la connexion avant la - suppression des jetons. Les appels et captures caméra/micro restent - soumis à leur propre cycle de vie. -- Le service peut démarrer sans construire l'interface Avalonia. L'ouverture - ultérieure de l'application réutilise le même conteneur et le même - transport, sans connexion doublonnée. - -Le service n'appelle ni `StartForegroundService` ni `StartForeground` et ne -publie aucune notification de connexion/reconnexion. Pour l'arrêter, -désactiver l'option et enregistrer les paramètres, ou déconnecter le compte. -Les notifications ne sont créées que lors de nouveaux messages ou événements ; -elles disparaissent à leur ouverture et ne sont pas marquées permanentes. -Android 13+ demande l'autorisation `POST_NOTIFICATIONS` pour ces alertes -visibles. Un refus empêche les alertes, **pas la connexion SignalR**. -Les échecs de démarrage sont signalés, sans basculer silencieusement vers -un service de premier plan et sans répéter une permission refusée. - -### Renouvellement de session - -Une maintenance unique par client API démarre avec l'interface et aussi -avec le service Android démarré sans interface. Elle programme une attente -à partir de `AccessTokenExpiresAt` (échéance calculée depuis la durée fournie -par le serveur OIDC, ou le claim JWT `exp`), moins la marge de sécurité de -60 secondes, indépendamment des appels HTTP et des reconnexions SignalR : -- pendant l'activité Android visible (sur desktop, pendant l'exécution - de l'application), même si « Garder la connexion » est désactivé ; -- ou avec « Garder la connexion » activé, même si l'activité est masquée. - -Le renouvellement utilise le `refresh_token` lorsque l'**access token** -entre dans sa marge d'expiration de 60 secondes. Les renouvellements -concurrents partagent le même verrou ; les jetons tournants sont -enregistrés et aucun renouvellement n'est engagé pendant la déconnexion. -Après chaque renouvellement, l'attente est recalculée avec la nouvelle -échéance. Connexion, déconnexion, changement d'activité ou de l'option -réveillent aussi l'ordonnanceur. Sans session ou lorsque les deux conditions -d'activité sont fausses, il attend un changement, sans contrôle périodique. -Un échec transitoire est signalé et retenté après 30 secondes ; un rejet -définitif exige une nouvelle connexion. - -Le serveur ne fournit pas ici d'échéance du refresh token au client : -PostIt n'en invente pas et ne peut pas repousser sa durée de vie absolue. -La rotation régulière ne garantit pas de prolonger une session révoquée -ou arrivée à sa limite absolue. Un processus suspendu ou arrêté par Android -ne peut pas exécuter ce timer ; au retour, le renouvellement reprend si la -session reste renouvelable. - -### Notifications et limites - -Le service écoute les messages privés, les messages des salons rejoints et -l'événement métier SignalR `push`. En arrière-plan, il affiche des alertes -locales génériques pour ne pas exposer de contenu privé sur l'écran -verrouillé. Il ne faut pas confondre cet événement SignalR nommé `push` avec -un service de push externe. - -**Aucun Firebase/FCM, serveur Google de notifications, jeton d'appareil, -configuration de projet ou migration push n'est requis.** Les API métier et -le ChatHub existants restent les seuls services réseau utilisés pour la -messagerie. - -Cette solution est de type *best effort*, pas une connexion immortelle : - -- Android, Doze, l'absence de réseau et les politiques des constructeurs - peuvent interrompre le socket ou empêcher le redémarrage du service. - Autoriser les données en arrière-plan permet le trafic réseau ; désactiver - manuellement l'optimisation de batterie pour PostIt assouplit les limites - de Doze. Ces réglages ne garantissent pas la survie du processus ou du - service et ne suppriment pas les autres limites d'exécution Android. -- Android 8+ peut arrêter un service ordinaire lorsque l'application reste - en arrière-plan, ou refuser `StartService` depuis le récepteur de démarrage. - Dans ce cas, PostIt signale le refus et attend une nouvelle ouverture de - l'application ; aucune tentative de contournement par service de premier - plan, tâche périodique ou exemption sans consentement n'est ajoutée. -- Après un arrêt forcé par l'utilisateur, rouvrir PostIt ; le démarrage du - téléphone n'est pas un contournement de cet arrêt. -- Le renouvellement nécessite une session encore valide. Une session - révoquée ou sans jeton de renouvellement exige une reconnexion. -- Les messages de chat sont éphémères : les messages envoyés pendant une - interruption ne sont pas récupérés par cette fonctionnalité. Les - notifications métier persistées restent accessibles par l'API. -- Aucun type `specialUse` ni permission `FOREGROUND_SERVICE_SPECIAL_USE` - n'est déclaré pour la messagerie. Les services de premier plan des appels - et captures caméra/micro restent inchangés : ils ne sont pas utilisés pour - maintenir le chat. - -### Validation sur téléphone - -Les tests locaux vérifient le partage de connexion, la restauration des -salons et le nettoyage de session. Ils ne remplacent pas une validation -Android réelle : absence de notification lors de l'activation et des -reconnexions, notification seulement à réception d'un événement activité -masquée, retour dans l'interface sans second socket, désactivation dans les -paramètres, déconnexion/reconnexion, coupure et retour réseau, veille -prolongée, redémarrage du téléphone et refus de permission sans arrêt du chat. - -Une activité de vérification est incluse uniquement dans l'APK Debug : -`fr.pschneider.postit.ChatServiceTestActivity`. Son résultat est écrit dans -le fichier privé de l'application `files/chat-service-test-result.txt`. -Elle vérifie la composition du conteneur partagé, pas la réception réelle -après un démarrage ou une longue veille. - -## 6. Points d'attention pour les évolutions +## 5. Points d'attention pour les évolutions - Conserver les règles d'audience alignées entre l'API et le site Web ; en particulier, appliquer un filtrage `Target` côté Web avant d'exposer les diff --git a/src/PostIt/PostIt.Android/MainActivity.cs b/src/PostIt/PostIt.Android/MainActivity.cs index 687b8bf51..4cf0947eb 100644 --- a/src/PostIt/PostIt.Android/MainActivity.cs +++ b/src/PostIt/PostIt.Android/MainActivity.cs @@ -71,28 +71,14 @@ public class MainActivity : AvaloniaMainActivity { base.OnResume(); IsForeground = true; - PostIt.Services.Platform.IsApplicationActive = true; } protected override void OnPause() { IsForeground = false; - PostIt.Services.Platform.IsApplicationActive = false; base.OnPause(); } - protected override void OnDestroy() - { - if (ReferenceEquals(Current, this)) - { - Current = null; - IsForeground = false; - PostIt.Services.Platform.IsApplicationActive = false; - PostIt.Android.Services.NotificationPermission.OnActivityDestroyed(); - } - base.OnDestroy(); - } - protected override void OnRestart() { base.OnRestart(); @@ -101,8 +87,7 @@ public class MainActivity : AvaloniaMainActivity public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { - if (PostIt.Android.Services.NotificationPermission.HandleResult(requestCode, permissions, grantResults) - || PostIt.Android.Services.PodcastPermissions.HandleResult(requestCode, permissions, grantResults) + if (PostIt.Android.Services.PodcastPermissions.HandleResult(requestCode, permissions, grantResults) || PostIt.Android.Services.AndroidCurrentLocationProvider .HandlePermissionResult(requestCode, grantResults)) { diff --git a/src/PostIt/PostIt.Android/PlatformBootstrap.cs b/src/PostIt/PostIt.Android/PlatformBootstrap.cs index ca07591a7..5b7b30def 100644 --- a/src/PostIt/PostIt.Android/PlatformBootstrap.cs +++ b/src/PostIt/PostIt.Android/PlatformBootstrap.cs @@ -20,8 +20,6 @@ internal static class PlatformBootstrap return activity is null ? null : new AndroidSystemBrowser(activity); }; - Platform.CreateServiceProvider = AndroidServiceProvider.GetOrCreate; - Platform.BackgroundChatService = AndroidBackgroundChatService.Instance; Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync; Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay); if (System.OperatingSystem.IsAndroidVersionAtLeast(26)) diff --git a/src/PostIt/PostIt.Android/PostIt.Android.csproj b/src/PostIt/PostIt.Android/PostIt.Android.csproj index 8742f0b38..6cbde4739 100644 --- a/src/PostIt/PostIt.Android/PostIt.Android.csproj +++ b/src/PostIt/PostIt.Android/PostIt.Android.csproj @@ -30,7 +30,6 @@ - diff --git a/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml b/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml index 2b3834bb5..730d6eec1 100644 --- a/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml +++ b/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml @@ -1,12 +1,9 @@  - - - diff --git a/src/PostIt/PostIt.Android/Resources/drawable/ic_stat_postit.xml b/src/PostIt/PostIt.Android/Resources/drawable/ic_stat_postit.xml deleted file mode 100644 index e055d1b42..000000000 --- a/src/PostIt/PostIt.Android/Resources/drawable/ic_stat_postit.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs deleted file mode 100644 index ddefc4cf3..000000000 --- a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Android.App; -using Android.Content; -using Android.Util; -using PostIt.Models; -using PostIt.Services; - -namespace PostIt.Android.Services; - -internal enum BackgroundChatFailure { SessionRequired, StartRejected, ConnectionFailed } - -internal sealed class BackgroundChatException(BackgroundChatFailure failure, string message, Exception? inner = null) - : InvalidOperationException(message, inner) -{ - internal BackgroundChatFailure Failure { get; } = failure; -} - -internal sealed class AndroidBackgroundChatService : IBackgroundChatService -{ - internal static readonly AndroidBackgroundChatService Instance = new(); - internal static readonly ChatServiceEpoch Epoch = new(); - internal const string EpochExtra = "postit-chat-epoch"; - internal const string IdentityExtra = "postit-chat-identity"; - private readonly SemaphoreSlim _gate = new(1, 1); - - public async Task SynchronizeAsync(YavscApiClient api, bool enabled, CancellationToken ct = default) - { - // This runs before the first await: cancellation cannot queue a stop - // behind an in-flight permission dialog or a native start. - if (!enabled || !api.Settings.AndroidKeepChatConnected) - { - Invalidate(); - return; - } - ct.ThrowIfCancellationRequested(); - if (api.IsSigningOut) - { - Invalidate(); - throw new BackgroundChatException(BackgroundChatFailure.SessionRequired, "Deconnexion en cours."); - } - var epoch = Epoch.Begin(); - var identity = ChatBootState.Identity(api); - var entered = false; - try - { - await _gate.WaitAsync(ct).ConfigureAwait(false); - entered = true; - Validate(api, epoch, identity, ct); - if (!Epoch.Run(epoch, () => ChatBootState.Save(api))) throw new OperationCanceledException(ct); - if (!ChatBootState.CanStart(api)) - throw new BackgroundChatException(BackgroundChatFailure.SessionRequired, "Connectez-vous avant d'activer la connexion de fond."); - var context = global::Android.App.Application.Context; - await ChatConnectionService.StartAndWaitAsync(context, epoch, identity!, ct).ConfigureAwait(false); - Validate(api, epoch, identity, ct); - if (!NotificationPermission.IsGranted(context)) - { - if (MainActivity.Current is { } activity && MainActivity.IsForeground) - { - try - { - var granted = await NotificationPermission.RequestAsync(activity, ct).ConfigureAwait(false); - Validate(api, epoch, identity, ct); - await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(granted - ? "Connexion de fond active sans notification permanente. Android peut l'interrompre." - : "Notifications refusees : SignalR reste actif, mais les alertes ne seront pas affichees.", - granted ? StatusSeverity.Info : StatusSeverity.Warning)).ConfigureAwait(false); - } - catch (OperationCanceledException) { throw; } - catch (Exception ex) - { - Log.Error("PostIt.Chat", "Notification permission request failed: " + ex); - AndroidSettings.ReportError(api.Settings, - "SignalR reste actif ; demande d'autorisation des alertes impossible : " + ex.Message); - } - } - } - Validate(api, epoch, identity, ct); - } - catch (OperationCanceledException) - { - Cancel(epoch); - throw; - } - catch (Exception ex) - { - Cancel(epoch); - Log.Error("PostIt.Chat", ex.ToString()); - try - { - await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error)) - .ConfigureAwait(false); - } - catch (Exception statusError) { Log.Error("PostIt.Chat", statusError.ToString()); } - if (ex is BackgroundChatException) throw; - throw new BackgroundChatException(BackgroundChatFailure.StartRejected, - "Android n'a pas pu demarrer le service de messagerie : " + ex.Message, ex); - } - finally { if (entered) _gate.Release(); } - } - - public Task DisableAsync(YavscApiClient api, CancellationToken ct = default) - { - Invalidate(); - // Logout calls this before deleting tokens. Never stop the shared - // socket here: the process-owned messaging session manages it. - try { ChatBootState.MarkSignedOut(); } - catch (Exception ex) - { - Log.Error("PostIt.Chat", ex.ToString()); - AndroidSettings.ReportError(api.Settings, ex.Message); - } - return Task.CompletedTask; - } - - private static void Validate(YavscApiClient api, string epoch, string? identity, CancellationToken ct) - { - ct.ThrowIfCancellationRequested(); - if (!Epoch.IsCurrent(epoch) || api.IsSigningOut || !api.Settings.AndroidKeepChatConnected - || !api.HasValidSession || identity is null || identity != ChatBootState.Identity(api)) - throw new OperationCanceledException("Demarrage de messagerie obsolete.", ct); - } - - internal static bool StartNative(Context context, string epoch, string identity) => - Epoch.Run(epoch, () => - { - var intent = new Intent(context, typeof(ChatConnectionService)) - .PutExtra(EpochExtra, epoch).PutExtra(IdentityExtra, identity); - context.StartService(intent); - }); - - internal static void Invalidate() => Epoch.Invalidate(Stop); - internal static void Cancel(string epoch) => Epoch.Cancel(epoch, Stop); - - internal static bool IsCurrent(string? epoch) => Epoch.IsCurrent(epoch); - - private static void Stop() - { - ChatConnectionService.Suspend(); - global::Android.App.Application.Context.StopService( - new Intent(global::Android.App.Application.Context, typeof(ChatConnectionService))); - } -} diff --git a/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs b/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs deleted file mode 100644 index c3b5bb39e..000000000 --- a/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Android.Content; -using Android.OS; -using Android.Util; -using PostIt.ViewModels; -using AndroidSettingsIntent = Android.Provider.Settings; - -namespace PostIt.Android.Services; - -internal static class AndroidBatteryOptimization -{ - internal static Intent? CreateIntent(Context context) - { - var packageName = context.PackageName - ?? throw new InvalidOperationException("Identifiant de l'application Android indisponible."); - var power = context.GetSystemService(Context.PowerService) as PowerManager - ?? throw new InvalidOperationException("Gestion de la batterie Android indisponible."); - return power.IsIgnoringBatteryOptimizations(packageName) - ? null - : new Intent(AndroidSettingsIntent.ActionRequestIgnoreBatteryOptimizations) - .SetData(global::Android.Net.Uri.Parse("package:" + packageName)); - } - - internal static void Request(Settings settings) - { - if (MainActivity.Current is not { IsFinishing: false, IsDestroyed: false } activity - || !MainActivity.IsForeground) - { - AndroidSettings.ReportError(settings, - "Ouvrez PostIt pour demander l'exemption d'optimisation batterie."); - return; - } - activity.RunOnUiThread(() => - { - try - { - if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed) - throw new InvalidOperationException("PostIt doit etre visible pour ouvrir les parametres batterie."); - if (!settings.AndroidKeepChatConnected) return; - using var intent = CreateIntent(activity); - if (intent is not null) activity.StartActivity(intent); - } - catch (Exception ex) - { - Log.Error("PostIt.Chat", "Battery optimization settings failed: " + ex); - AndroidSettings.ReportError(settings, - "Impossible d'ouvrir les parametres batterie Android : " + ex.Message); - } - }); - } -} diff --git a/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs b/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs deleted file mode 100644 index a4af45f45..000000000 --- a/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; -using PostIt.Helpers; -using PostIt.Services; - -namespace PostIt.Android.Services; - -internal static class AndroidServiceProvider -{ - private static readonly Lazy Provider = new(() => - { - var provider = new ServiceCollection().BuildPostItServices(); - var api = provider.GetRequiredService(); - api.Settings.Saved += (_, _) => - { - if (!api.Settings.AndroidKeepChatConnected) AndroidBackgroundChatService.Invalidate(); - ChatBootState.Save(api); - }; - api.Settings.Applied += (_, _) => - { - if (api.Settings.AndroidKeepChatConnected) - AndroidBatteryOptimization.Request(api.Settings); - }; - api.SigningOut += () => - { - AndroidBackgroundChatService.Invalidate(); - try { ChatBootState.MarkSignedOut(); } - catch (Exception ex) - { - global::Android.Util.Log.Error("PostIt.Chat", ex.ToString()); - AndroidSettings.ReportError(api.Settings, ex.Message); - } - return System.Threading.Tasks.Task.CompletedTask; - }; - return provider; - }); - - internal static IServiceProvider GetOrCreate() => Provider.Value; -} diff --git a/src/PostIt/PostIt.Android/Services/AndroidSettings.cs b/src/PostIt/PostIt.Android/Services/AndroidSettings.cs deleted file mode 100644 index e710c0c85..000000000 --- a/src/PostIt/PostIt.Android/Services/AndroidSettings.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Threading.Tasks; -using PostIt.ViewModels; - -namespace PostIt.Android.Services; - -internal static class AndroidSettings -{ - internal static Task UpdateAsync(Settings settings, Action update) - { - if (MainActivity.Current is not { IsDestroyed: false, IsFinishing: false } activity) - { - update(settings); - return Task.CompletedTask; - } - var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - activity.RunOnUiThread(() => - { - try - { - update(settings); - completion.TrySetResult(); - } - catch (Exception ex) { completion.TrySetException(ex); } - }); - return completion.Task; - } - - internal static void ReportError(Settings settings, string message) - { - _ = ReportAsync(); - async Task ReportAsync() - { - try { await UpdateAsync(settings, s => s.SetActionStatus(message, PostIt.Models.StatusSeverity.Error)); } - catch (Exception ex) { global::Android.Util.Log.Error("PostIt.Chat", ex.ToString()); } - } - } -} diff --git a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs deleted file mode 100644 index c38d46c0f..000000000 --- a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Threading.Tasks; -using Android.App; -using Android.Content; -using Android.Util; -using Microsoft.Extensions.DependencyInjection; -using PostIt.Models; -using PostIt.Services; - -namespace PostIt.Android.Services; - -[BroadcastReceiver(Name = "fr.pschneider.postit.ChatBootReceiver", Enabled = true, Exported = true)] -[IntentFilter([Intent.ActionBootCompleted])] -public sealed class ChatBootReceiver : BroadcastReceiver -{ - public override void OnReceive(Context? context, Intent? intent) - { - if (context is null || intent?.Action != Intent.ActionBootCompleted || !ChatBootState.OptedIn) return; - var epoch = AndroidBackgroundChatService.Epoch.Restore(); - if (epoch is null) return; - var pending = GoAsync(); - _ = Task.Run(() => - { - YavscApiClient? api = null; - try - { - api = AndroidServiceProvider.GetOrCreate().GetRequiredService(); - if (!ChatBootState.CanStart(api)) return; - var identity = ChatBootState.Identity(api); - if (identity is null || !AndroidBackgroundChatService.StartNative(context, epoch, identity)) return; - Log.Info("PostIt.Chat", "Best-effort chat restart requested after boot."); - } - catch (Exception ex) - { - Log.Error("PostIt.Chat", "Boot restart rejected: " + ex); - if (api is not null) - AndroidSettings.ReportError(api.Settings, - "Android a refuse le redemarrage de la messagerie : " + ex.Message); - } - finally { pending?.Finish(); } - }); - } -} diff --git a/src/PostIt/PostIt.Android/Services/ChatBootState.cs b/src/PostIt/PostIt.Android/Services/ChatBootState.cs deleted file mode 100644 index 160a30781..000000000 --- a/src/PostIt/PostIt.Android/Services/ChatBootState.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.IO; -using System.Text; -using System.Text.Json; -using Android.Content; -using PostIt.Services; - -namespace PostIt.Android.Services; - -internal static class ChatBootState -{ - private static ISharedPreferences Preferences => - global::Android.App.Application.Context.GetSharedPreferences("postit-chat-service", FileCreationMode.Private)!; - - internal static bool OptedIn => Preferences.GetBoolean("enabled", false); - - internal static void Save(YavscApiClient api) - { - var identity = Identity(api); - var saved = Preferences.Edit()! - .PutBoolean("enabled", api.Settings.AndroidKeepChatConnected)! - .PutBoolean("signed-in", !api.IsSigningOut && api.HasValidSession && identity is not null)! - .PutString("identity", identity)!.Commit(); - if (!saved) throw new IOException("Impossible d'enregistrer l'etat Android de la messagerie."); - } - - internal static void MarkSignedOut() - { - if (!Preferences.Edit()!.PutBoolean("signed-in", false)!.Commit()) - throw new IOException("Impossible d'enregistrer la deconnexion Android."); - } - - internal static bool CanStart(YavscApiClient api) => - OptedIn && Preferences.GetBoolean("signed-in", false) - && api.Settings.AndroidKeepChatConnected && !api.IsSigningOut && api.HasValidSession - && Identity(api) is { } identity && identity == Preferences.GetString("identity", null); - - internal static string? Identity(YavscApiClient api) - { - var token = api.CurrentIdToken ?? api.CurrentAccessToken; - if (string.IsNullOrEmpty(token)) return null; - try - { - var parts = token.Split('.'); - if (parts.Length != 3) return null; - var payload = parts[1].Replace('-', '+').Replace('_', '/'); - payload = payload.PadRight((payload.Length + 3) / 4 * 4, '='); - using var json = JsonDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload))); - if (!json.RootElement.TryGetProperty("sub", out var subject) - || string.IsNullOrEmpty(subject.GetString())) return null; - return $"{api.Settings.ApiUrl.TrimEnd('/')}\n{api.Settings.Authentication.Authority.TrimEnd('/')}\n{subject.GetString()}"; - } - catch (Exception ex) when (ex is FormatException or JsonException or InvalidOperationException) - { - global::Android.Util.Log.Warn("PostIt.Chat", "Session identity unavailable for boot restart."); - return null; - } - } -} diff --git a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs deleted file mode 100644 index f887a7d31..000000000 --- a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs +++ /dev/null @@ -1,295 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; -using Android.App; -using Android.Content; -using Android.OS; -using Android.Util; -using AndroidX.Core.App; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.DependencyInjection; -using PostIt.Models; -using PostIt.Services; -using PostIt.ViewModels.Chat; -using OperationCanceledException = System.OperationCanceledException; - -namespace PostIt.Android.Services; - -[Service(Name = "fr.pschneider.postit.ChatConnectionService", Exported = false)] -public sealed class ChatConnectionService : Service -{ - private const string MessageChannel = "postit-chat-messages"; - private const int MessageNotificationId = 4053; - private static readonly ConcurrentDictionary> Startups = new(); - private static volatile ChatConnectionService? _current; - private CancellationTokenSource _stop = new(); - private string? _epoch; - private readonly List _subscriptions = []; - private readonly object _observerGate = new(); - private YavscApiClient? _api; - private ChatHubConnection? _transport; - private HubConnection? _observedConnection; - private Task? _loop; - private volatile bool _destroyed; - private bool _wasConnected; - - internal static async Task StartAndWaitAsync(Context context, string epoch, string identity, CancellationToken ct) - { - var pending = Startups.GetOrAdd(epoch, - _ => new(TaskCreationOptions.RunContinuationsAsynchronously)); - try - { - ct.ThrowIfCancellationRequested(); - if (!AndroidBackgroundChatService.StartNative(context, epoch, identity)) - throw new OperationCanceledException("Demarrage de messagerie obsolete.", ct); - await pending.Task.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); - } - catch - { - // Cancel only the owner of this attempt, never a later re-enable. - AndroidBackgroundChatService.Cancel(epoch); - throw; - } - finally - { - Startups.TryRemove(epoch, out _); - } - } - - internal static void Suspend() - { - foreach (var startup in Startups) - if (!AndroidBackgroundChatService.IsCurrent(startup.Key)) - startup.Value.TrySetException(new OperationCanceledException("Demarrage de messagerie annule.")); - if (_current is not { } current) return; - current._stop.Cancel(); - current.FailStartup(new OperationCanceledException("Demarrage de messagerie annule.")); - } - - public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId) - { - var epoch = intent is null - ? AndroidBackgroundChatService.Epoch.Restore() - : intent.GetStringExtra(AndroidBackgroundChatService.EpochExtra); - try - { - if (!AndroidBackgroundChatService.IsCurrent(epoch)) - { - if (_current == this && AndroidBackgroundChatService.IsCurrent(_epoch)) - return StartCommandResult.Sticky; - StopSelfResult(startId); - return StartCommandResult.NotSticky; - } - EnsureChannels(); - var provider = AndroidServiceProvider.GetOrCreate(); - _api = provider.GetRequiredService(); - _transport = provider.GetRequiredService(); - var identity = intent is null ? ChatBootState.Identity(_api) - : intent.GetStringExtra(AndroidBackgroundChatService.IdentityExtra); - if (!ChatBootState.CanStart(_api) || identity is null || identity != ChatBootState.Identity(_api)) - throw new BackgroundChatException(BackgroundChatFailure.SessionRequired, - "Connexion de fond inactive : option ou session absente."); - _api.StartSessionMaintenance(); - if (!AndroidBackgroundChatService.Epoch.Run(epoch, () => - { - if (_epoch == epoch && _loop is { IsCompleted: false } && !_stop.IsCancellationRequested) - { - if (_transport.Connection.State == HubConnectionState.Connected) CompleteStartup(epoch!); - return; - } - _stop.Cancel(); - _stop = new CancellationTokenSource(); - _epoch = epoch; - _current = this; - _wasConnected = false; - _loop = RunAsync(epoch!, _stop.Token); - })) - { - StopSelfResult(startId); - return StartCommandResult.NotSticky; - } - return StartCommandResult.Sticky; - } - catch (Exception ex) - { - ReportError(ex); - if (epoch is not null) - { - if (Startups.TryGetValue(epoch, out var pending)) pending.TrySetException(ex); - AndroidBackgroundChatService.Cancel(epoch); - } - if (!AndroidBackgroundChatService.IsCurrent(_epoch)) StopSelfResult(startId); - return StartCommandResult.NotSticky; - } - } - - private async Task RunAsync(string epoch, CancellationToken ct) - { - while (!ct.IsCancellationRequested && AndroidBackgroundChatService.IsCurrent(epoch)) - { - if (_api is null || _transport is null || !ChatBootState.CanStart(_api)) - { - FailStartup(new BackgroundChatException(BackgroundChatFailure.SessionRequired, - "La connexion de fond necessite une session active."), epoch); - AndroidBackgroundChatService.Cancel(epoch); - return; - } - try - { - var connection = await _transport.GetConnectionAsync().ConfigureAwait(false); - if (ct.IsCancellationRequested || !AndroidBackgroundChatService.IsCurrent(epoch)) return; - Observe(connection); - if (connection.State == HubConnectionState.Disconnected) - { - using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct); - attempt.CancelAfter(TimeSpan.FromSeconds(20)); - await _transport.StartAsync(attempt.Token).ConfigureAwait(false); - } - if (connection.State == HubConnectionState.Connected) - { - if (!_wasConnected) - await AndroidSettings.UpdateAsync(_api.Settings, - s => - { - if (!_destroyed && AndroidBackgroundChatService.IsCurrent(epoch) - && ChatBootState.CanStart(_api)) - s.SetActionStatus(NotificationPermission.IsGranted(this) - ? "Connexion de fond active sans notification permanente. Android peut l'interrompre." - : "SignalR actif sans notification permanente. Alertes desactivees dans Android.", - NotificationPermission.IsGranted(this) ? StatusSeverity.Info : StatusSeverity.Warning); - }) - .ConfigureAwait(false); - ct.ThrowIfCancellationRequested(); - if (!AndroidBackgroundChatService.IsCurrent(epoch)) return; - if (!ChatBootState.CanStart(_api)) { AndroidBackgroundChatService.Cancel(epoch); return; } - _wasConnected = true; - CompleteStartup(epoch); - } - else - { - _wasConnected = false; - } - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } - catch (Exception ex) - { - if (!AndroidBackgroundChatService.IsCurrent(epoch)) return; - _wasConnected = false; - var failure = new BackgroundChatException(BackgroundChatFailure.ConnectionFailed, - "Connexion de fond indisponible ; nouvelle tentative automatique. " + ex.Message, ex); - ReportError(failure); - FailStartup(failure, epoch); - } - try { await Task.Delay(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } - } - } - - private void Observe(HubConnection connection) - { - lock (_observerGate) - { - if (_destroyed || ReferenceEquals(connection, _observedConnection)) return; - ClearSubscriptions(); - _observedConnection = connection; - _subscriptions.Add(connection.On("notifyUser", (type, _, _) => - { - if (type is "pv" or "private" or "private_message" or "PrivateMessage") - NotifyMessage("Nouveau message prive. Ouvrez PostIt."); - })); - // The current Yavsc hub delivers private chat under addPV. - _subscriptions.Add(connection.On("addPV", (_, _) => - NotifyMessage("Nouveau message prive. Ouvrez PostIt."))); - _subscriptions.Add(connection.On("ReceiveMessage", _ => - NotifyMessage("Nouveau message dans un salon. Ouvrez PostIt."))); - _subscriptions.Add(connection.On("push", (_, _) => - NotifyMessage("Nouvelle notification d'activite. Ouvrez PostIt."))); - } - } - - private void NotifyMessage(string text) - { - if (_destroyed || _stop.IsCancellationRequested || !AndroidBackgroundChatService.IsCurrent(_epoch) - || MainActivity.IsForeground - || _api is null || !ChatBootState.CanStart(_api) - || !NotificationPermission.IsGranted(this)) return; - try - { - var builder = new NotificationCompat.Builder(this, MessageChannel); - builder.SetSmallIcon(Yavsc.Resource.Drawable.ic_stat_postit); - builder.SetContentTitle("PostIt"); - builder.SetContentText(text); - builder.SetVisibility(NotificationCompat.VisibilityPrivate); - builder.SetContentIntent(OpenApp()); - builder.SetAutoCancel(true); - builder.SetOnlyAlertOnce(false); - GetNotificationManager().Notify(MessageNotificationId, builder.Build()); - } - catch (Exception ex) { ReportError(ex); } - } - - private void EnsureChannels() - { - if (!OperatingSystem.IsAndroidVersionAtLeast(26)) return; - var manager = (NotificationManager?)GetSystemService(NotificationService) - ?? throw new InvalidOperationException("Notifications Android indisponibles."); - manager.CreateNotificationChannel(new NotificationChannel(MessageChannel, - "Messages et activite", NotificationImportance.Default)); - } - - private PendingIntent? OpenApp() - { - var launch = PackageManager?.GetLaunchIntentForPackage(PackageName!); - return launch is null ? null : PendingIntent.GetActivity(this, 4053, launch, - PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable); - } - - private NotificationManagerCompat GetNotificationManager() => - NotificationManagerCompat.From(this) - ?? throw new InvalidOperationException("Notifications Android indisponibles."); - - private void ReportError(Exception ex) - { - Log.Error("PostIt.Chat", ex.ToString()); - if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message); - } - - private static void CompleteStartup(string epoch) - { - if (Startups.TryGetValue(epoch, out var pending)) pending.TrySetResult(true); - } - - private void FailStartup(Exception ex, string? epoch = null) - { - epoch ??= _epoch; - if (epoch is not null && Startups.TryGetValue(epoch, out var pending)) pending.TrySetException(ex); - } - - private void ClearSubscriptions() - { - lock (_observerGate) - { - foreach (var subscription in _subscriptions) subscription.Dispose(); - _subscriptions.Clear(); - _observedConnection = null; - } - } - - public override void OnDestroy() - { - _destroyed = true; - _stop.Cancel(); - ClearSubscriptions(); - if (ReferenceEquals(_current, this)) - { - _current = null; - FailStartup(new OperationCanceledException("Service de messagerie arrete.")); - } - // The socket belongs to the shared process session, not this service. - base.OnDestroy(); - } - - public override IBinder? OnBind(Intent? intent) => null; -} diff --git a/src/PostIt/PostIt.Android/Services/ChatServiceEpoch.cs b/src/PostIt/PostIt.Android/Services/ChatServiceEpoch.cs deleted file mode 100644 index 9b083aa16..000000000 --- a/src/PostIt/PostIt.Android/Services/ChatServiceEpoch.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; - -namespace PostIt.Android.Services; - -/// Serializes native launch ownership, including intents delivered after cancellation. -internal sealed class ChatServiceEpoch -{ - private readonly object _gate = new(); - private readonly string _process = Guid.NewGuid().ToString("N"); - private long _epoch; - private bool _enabled; - - internal string Begin() - { - lock (_gate) - { - if (!_enabled) { ++_epoch; _enabled = true; } - return Current; - } - } - - internal string? Restore() - { - lock (_gate) - { - // Only a genuinely fresh process may restore without a new user request. - if (_epoch == 0) { ++_epoch; _enabled = true; } - return _enabled ? Current : null; - } - } - - internal bool IsCurrent(string? epoch) - { - lock (_gate) return _enabled && epoch == Current; - } - - internal bool Run(string? epoch, Action action) - { - lock (_gate) - { - if (!_enabled || epoch != Current) return false; - action(); - return true; - } - } - - internal void Invalidate(Action stop) - { - lock (_gate) - { - ++_epoch; - _enabled = false; - stop(); - } - } - - internal bool Cancel(string epoch, Action stop) - { - lock (_gate) - { - if (!_enabled || epoch != Current) return false; - ++_epoch; - _enabled = false; - stop(); - return true; - } - } - - private string Current => $"{_process}:{_epoch}"; -} diff --git a/src/PostIt/PostIt.Android/Services/NotificationPermission.cs b/src/PostIt/PostIt.Android/Services/NotificationPermission.cs deleted file mode 100644 index 5348f7130..000000000 --- a/src/PostIt/PostIt.Android/Services/NotificationPermission.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Android.App; -using Android.Content; -using Android.Content.PM; -using AndroidX.Core.App; -using AndroidX.Core.Content; - -namespace PostIt.Android.Services; - -/// Runtime POST_NOTIFICATIONS request (Android 13+), routed through MainActivity. -internal static class NotificationPermission -{ - private const int RequestCode = 4051; - private const string AskedKey = "notification-permission-asked"; - private const string PermissionName = "android.permission.POST_NOTIFICATIONS"; - private static TaskCompletionSource? _pending; - - internal static bool IsGranted(Context context) - => (!OperatingSystem.IsAndroidVersionAtLeast(33) - || ContextCompat.CheckSelfPermission(context, PermissionName) == Permission.Granted) - && NotificationManagerCompat.From(context)?.AreNotificationsEnabled() == true; - - internal static async Task RequestAsync(Activity activity, CancellationToken ct) - { - if (IsGranted(activity)) return true; - if (!OperatingSystem.IsAndroidVersionAtLeast(33)) - return false; // Disabled from system settings: no runtime prompt exists. - - if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed) - return false; - ct.ThrowIfCancellationRequested(); - if (_pending is { } existing) - return await existing.Task.WaitAsync(ct).ConfigureAwait(false); - var preferences = activity.GetSharedPreferences("postit-chat-service", FileCreationMode.Private)!; - if (preferences.GetBoolean(AskedKey, false)) - return false; // Subsequent retries must use Android notification settings. - - var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - if (Interlocked.CompareExchange(ref _pending, pending, null) is { } inFlight) - return await inFlight.Task.WaitAsync(ct).ConfigureAwait(false); - - activity.RunOnUiThread(() => - { - try - { - if (!MainActivity.IsForeground || activity.IsFinishing || activity.IsDestroyed) - { - Interlocked.CompareExchange(ref _pending, null, pending); - pending.TrySetResult(false); - return; - } - if (!preferences.Edit()!.PutBoolean(AskedKey, true)!.Commit()) - throw new System.IO.IOException("Impossible d'enregistrer la demande d'autorisation Android."); - ActivityCompat.RequestPermissions(activity, [PermissionName], RequestCode); - } - catch (Exception ex) - { - Interlocked.CompareExchange(ref _pending, null, pending); - pending.TrySetException(ex); - } - }); - - // Cancellation cancels only this waiter, not the OS request. Retain the - // request until its callback so retries cannot open a second dialog. - return await pending.Task.WaitAsync(ct).ConfigureAwait(false); - } - - internal static bool HandleResult(int requestCode, string[]? permissions, Permission[]? results) - { - if (requestCode != RequestCode) return false; - var granted = false; - if (permissions is not null && results is not null) - { - var index = Array.IndexOf(permissions, PermissionName); - granted = index >= 0 && index < results.Length && results[index] == Permission.Granted; - } - Interlocked.Exchange(ref _pending, null)?.TrySetResult(granted); - return true; - } - - internal static void OnActivityDestroyed() => - Interlocked.Exchange(ref _pending, null)?.TrySetResult(false); -} diff --git a/src/PostIt/PostIt.Android/Tests/ChatServiceEpochTests.cs b/src/PostIt/PostIt.Android/Tests/ChatServiceEpochTests.cs deleted file mode 100644 index f79589b72..000000000 --- a/src/PostIt/PostIt.Android/Tests/ChatServiceEpochTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -#if DEBUG -using System; -using System.Threading; -using System.Threading.Tasks; -using PostIt.Android.Services; - -namespace PostIt.Android.Tests; - -/// Platform-free deterministic launch/disable races; also invoked by the Android debug activity. -internal static class ChatServiceEpochTests -{ - internal static async Task VerifyAsync() - { - foreach (var reason in new[] { "Sync(false)", "logout", "saved opt-out" }) - { - var policy = new ChatServiceEpoch(); - var queued = policy.Begin(); - var stopped = 0; - policy.Invalidate(() => stopped++); - Require(!policy.Run(queued, () => throw new Exception("Stale launch executed")), reason); - Require(policy.Restore() is null, reason + " restored in same process"); - Require(stopped == 1, reason + " did not stop synchronously"); - } - - var owner = new ChatServiceEpoch(); - var old = owner.Begin(); - owner.Invalidate(() => { }); - var newer = owner.Begin(); - var laterStopped = false; - Require(!owner.Cancel(old, () => laterStopped = true), "old timeout cancelled later enable"); - Require(!laterStopped && owner.IsCurrent(newer), "new generation lost"); - Require(owner.Cancel(newer, () => laterStopped = true), "current cancellation not applied"); - Require(laterStopped && !owner.IsCurrent(newer), "timed-out generation still launchable"); - Require(!owner.Run(newer, () => throw new Exception("Timed-out intent executed")), "timeout leak"); - - var firstProcess = new ChatServiceEpoch(); - var staleIntent = firstProcess.Begin(); - var freshProcess = new ChatServiceEpoch(); - var restored = freshProcess.Restore(); - Require(restored is not null && freshProcess.IsCurrent(restored), "fresh boot restore failed"); - Require(!freshProcess.IsCurrent(staleIntent), "previous-process intent accepted"); - - var queuedPolicy = new ChatServiceEpoch(); - var beforeSemaphore = queuedPolicy.Begin(); - using var release = new SemaphoreSlim(0, 1); - var launched = false; - var delayedLaunch = Task.Run(async () => - { - await release.WaitAsync(); - queuedPolicy.Run(beforeSemaphore, () => launched = true); - }); - queuedPolicy.Invalidate(() => { }); - release.Release(); - await delayedLaunch; - Require(!launched, "queued semaphore/permission continuation launched after disable"); - - var concurrent = new ChatServiceEpoch(); - var concurrentEpoch = concurrent.Begin(); - var nativeLaunch = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var finishLaunch = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var launch = Task.Run(() => concurrent.Run(concurrentEpoch, () => - { - nativeLaunch.TrySetResult(); - finishLaunch.Task.GetAwaiter().GetResult(); - })); - await nativeLaunch.Task.WaitAsync(TimeSpan.FromSeconds(5)); - var stop = Task.Run(() => concurrent.Invalidate(() => { })); - finishLaunch.TrySetResult(); - await Task.WhenAll(launch, stop).WaitAsync(TimeSpan.FromSeconds(5)); - Require(!concurrent.IsCurrent(concurrentEpoch), "native launch escaped concurrent disable"); - Require(!concurrent.Run(concurrentEpoch, () => throw new Exception("Delayed Android intent executed")), - "delayed Android intent accepted"); - } - - private static void Require(bool value, string message) - { - if (!value) throw new InvalidOperationException(message); - } -} -#endif diff --git a/src/PostIt/PostIt.Tests/AndroidChatServiceTestActivity.cs b/src/PostIt/PostIt.Tests/AndroidChatServiceTestActivity.cs deleted file mode 100644 index cde74694f..000000000 --- a/src/PostIt/PostIt.Tests/AndroidChatServiceTestActivity.cs +++ /dev/null @@ -1,70 +0,0 @@ -#if ANDROID -using System; -using System.IO; -using Android.App; -using Android.Content; -using Android.Content.PM; -using Android.OS; -using Microsoft.Extensions.DependencyInjection; -using PostIt.Android; -using PostIt.Android.Services; -using PostIt.Services; -using PostIt.ViewModels; - -namespace PostIt.Tests; - -/// Debug-only boot composition test, without Avalonia or network startup. -[Activity(Name = "fr.pschneider.postit.ChatServiceTestActivity", Exported = true)] -public sealed class AndroidChatServiceTestActivity : Activity -{ - protected override async void OnCreate(Bundle? state) - { - base.OnCreate(state); - var resultPath = Path.Combine(FilesDir!.AbsolutePath, "chat-service-test-result.txt"); - try - { - await PostIt.Android.Tests.ChatServiceEpochTests.VerifyAsync(); - var boot = AndroidServiceProvider.GetOrCreate(); - PlatformBootstrap.InitPlatform(); - var ui = Platform.CreateServiceProvider!.Invoke(); - Require(ReferenceEquals(boot, ui), "boot and UI providers differ"); - Require(ReferenceEquals(boot.GetRequiredService(), - ui.GetRequiredService()), "API client differs"); - Require(ReferenceEquals(boot.GetRequiredService(), - ui.GetRequiredService()), "chat transport differs"); - Require(ReferenceEquals(boot.GetRequiredService(), - ui.GetRequiredService().Settings), "settings differ"); - Require(ReferenceEquals(Platform.BackgroundChatService, AndroidBackgroundChatService.Instance), - "native adapter missing"); - using (var battery = AndroidBatteryOptimization.CreateIntent(this)) - { - var power = (PowerManager)GetSystemService(PowerService)!; - var exempt = power.IsIgnoringBatteryOptimizations(PackageName!); - Require(exempt ? battery is null - : battery?.Action == global::Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations, - "battery exemption must not prompt when already granted"); - Require(battery?.DataString == (exempt ? null : "package:" + PackageName), - "battery settings package mismatch"); - Require(CheckSelfPermission("android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS") - == Permission.Granted, "battery exemption request permission missing"); - } - if (OperatingSystem.IsAndroidVersionAtLeast(29)) - { - var name = new ComponentName(this, Java.Lang.Class.FromType(typeof(ChatConnectionService))); - var service = PackageManager!.GetServiceInfo(name, PackageInfoFlags.MetaData)!; - Require(service.ForegroundServiceType == (ForegroundService)0, - "chat must not be a foreground service"); - Require(!service.Exported, "chat service must not be exported"); - } - File.WriteAllText(resultPath, "PASS\nepoch-races=passed\nprovider=shared\napi=shared\nsettings=shared\ntransport=shared\nAvalonia=not-initialized"); - } - catch (Exception ex) { File.WriteAllText(resultPath, $"FAIL\n{ex}"); } - finally { Finish(); } - } - - private static void Require(bool condition, string message) - { - if (!condition) throw new InvalidOperationException(message); - } -} -#endif diff --git a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs index 8ac92ba43..6afe892a2 100644 --- a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs @@ -2,103 +2,12 @@ using Avalonia.Controls; using Avalonia.Headless.XUnit; using PostIt.Services; using PostIt.ViewModels.Chat; -using PostIt.ViewModels; using Yavsc.Abstract.Chat.Calls; namespace PostIt.Tests; public sealed class LanCallViewModelTests { - [AvaloniaFact] - public async Task Calls_restore_shared_devices_and_persist_choices_and_network_address() - { - var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json"); - var previousDevices = Platform.GetLanCallDevices; - try - { - var settings = new Settings(path) - { - PodcastCameras = [new("Front", "front"), new("Rear", "rear")], - PodcastMicrophones = [new("None", ""), new("USB", "usb"), new("Built-in", "built-in")], - PodcastCameraId = "rear", PodcastMicrophoneId = "usb" - }; - await using (var vm = new LanCallViewModel(new Signaling(), settings: settings)) - { - Assert.Equal("rear", vm.Camera?.Value); - Assert.Equal("usb", vm.Microphone?.Value); - Assert.False(vm.AllowAddressDisclosure); - vm.Camera = vm.Cameras[0]; - vm.Microphone = vm.Microphones[1]; - Assert.Equal("front", settings.PodcastCameraId); - Assert.Equal("built-in", settings.PodcastMicrophoneId); - Assert.NotEmpty(vm.Addresses); - vm.Address = vm.Addresses.Last(); - settings.Save(); - var preferred = vm.Address; - Platform.GetLanCallDevices = () => new( - [new("Rear", "rear"), new("Front", "front")], - [new("Built-in", "built-in"), new("USB", "usb")]); - vm.RefreshDevicesCommand.Execute(null); - Assert.Equal("front", vm.Camera?.Value); - Assert.Equal("built-in", vm.Microphone?.Value); - Assert.Equal(preferred, vm.Address); - Assert.Contains(settings.PodcastMicrophones, d => d.Value == ""); - - var reloaded = new Settings(path); - reloaded.Authentication.Authority = ""; - reloaded.Load(); - await using var restored = new LanCallViewModel(new Signaling(), settings: reloaded); - Assert.Equal(preferred, restored.Address); - Assert.Equal("front", restored.Camera?.Value); - Assert.Equal("built-in", restored.Microphone?.Value); - Assert.False(restored.AllowAddressDisclosure); - settings.PodcastCameraId = "rear"; - Assert.Equal("rear", vm.Camera?.Value); - settings.PodcastMicrophoneId = ""; - Assert.Null(vm.Microphone); - vm.AllowAddressDisclosure = true; - vm.Room = "General"; - vm.Target = "bob"; - await vm.InviteCommand.ExecuteAsync(null); - Assert.Contains("microphone", vm.Status); - } - } - finally { Platform.GetLanCallDevices = previousDevices; File.Delete(path); } - } - - [AvaloniaFact] - public async Task Call_preference_save_failures_are_reported_without_losing_the_choice() - { - var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}"); - Directory.CreateDirectory(path); - try - { - var settings = new Settings(path); - await using var vm = new LanCallViewModel(new Signaling(), settings: settings); - vm.Address = null; - vm.Address = "127.0.0.1"; - Assert.Equal("127.0.0.1", settings.LanCallAddress); - Assert.Contains("sauvegarde impossible", vm.Status); - Assert.True(settings.IsDirty); - } - finally { Directory.Delete(path); } - } - - [AvaloniaFact] - public async Task Missing_saved_network_address_requires_a_new_selection_and_does_not_restore_consent() - { - var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json"); - try - { - var settings = new Settings(path) { LanCallAddress = "not-a-local-address" }; - await using var vm = new LanCallViewModel(new Signaling(), settings: settings); - Assert.Null(vm.Address); - Assert.False(vm.AllowAddressDisclosure); - Assert.Equal("not-a-local-address", settings.LanCallAddress); - } - finally { File.Delete(path); } - } - private static CallSession Session() => new(Guid.NewGuid(), "General", "alice", "bob", false, DateTimeOffset.UtcNow.AddMinutes(1), CallTransports.LanSrtp); @@ -114,21 +23,6 @@ public sealed class LanCallViewModelTests return vm; } - [AvaloniaTheory] - [InlineData("8.8.8.8")] - [InlineData("2001:db8::1")] - [InlineData("fd00::1")] - public async Task Public_or_private_ip_can_be_selected_for_an_explicitly_consented_direct_call(string address) - { - var signaling = new Signaling(); - await using var vm = Configure(signaling, (_, _) => throw new Exception("No media before acceptance")); - vm.Addresses.Add(address); - vm.Address = address; - await vm.InviteCommand.ExecuteAsync(null); - Assert.Equal(1, signaling.Invites); - Assert.True(vm.Busy); - } - [AvaloniaFact] public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange() { diff --git a/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs b/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs index 8e0e51b65..f473dc40c 100644 --- a/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs +++ b/src/PostIt/PostIt.Tests/LinuxLanCallMediaTests.cs @@ -15,45 +15,38 @@ public sealed class LinuxLanCallMediaTests(ITestOutputHelper output) public static bool HasTsFixture => OperatingSystem.IsLinux() && File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_TS")); - [Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))] - [InlineData("127.0.0.1")] - [InlineData("::1")] - public async Task Ports_are_released_and_credentials_regenerated_after_disposal(string address) + [Fact(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))] + public async Task Ports_are_released_and_credentials_regenerated_after_disposal() { - var port = FreePort(address: address); - var first = new LibVlcLanCallMedia(address, port, headless: true); + 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(address, port, headless: true); + 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); } - [Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))] - [InlineData("127.0.0.1")] - [InlineData("::1")] - public void Occupied_rtcp_port_is_rejected_before_capture_starts(string address) + [Fact(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))] + public void Occupied_rtcp_port_is_rejected_before_capture_starts() { - var port = FreePort(address: address); - var ip = IPAddress.Parse(address); - using var socket = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp); - socket.Bind(new IPEndPoint(ip, port + 1)); - var error = Assert.Throws(() => new LibVlcLanCallMedia(address, port, headless: true)); + var port = FreePort(); + using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, port + 1)); + var error = Assert.Throws(() => new LibVlcLanCallMedia("127.0.0.1", port, headless: true)); Assert.Equal(SocketError.AddressAlreadyInUse, error.SocketErrorCode); } - [Theory(Skip = "Set POSTIT_TEST_TS to an H.264/AAC MPEG-TS file.", SkipUnless = nameof(HasTsFixture))] - [InlineData("127.0.0.1")] - [InlineData("::1")] - public async Task Already_encoded_capture_is_sent_over_srtp_without_transcoding(string address) + [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(address: address); - await using var sender = new LibVlcLanCallMedia(address, firstPort, headless: true); - await using var receiver = new LibVlcLanCallMedia(address, FreePort(firstPort, address), headless: true); + 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")!); @@ -95,16 +88,13 @@ public sealed class LinuxLanCallMediaTests(ITestOutputHelper output) [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] - [InlineData(false, false, "::1")] - [InlineData(true, false, "::1")] - public async Task Two_peers_decode_bidirectional_encrypted_audio_video_and_reject_wrong_keys( - bool wrongKey, bool preview, string address = "127.0.0.1") + 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(address: address); - var secondPort = FreePort(firstPort, address); - await using var first = new LibVlcLanCallMedia(address, firstPort, headless: true); - await using var second = new LibVlcLanCallMedia(address, secondPort, headless: true); + 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); @@ -152,18 +142,17 @@ public sealed class LinuxLanCallMediaTests(ITestOutputHelper output) private static bool HasMedia(LibVlcLanCallMedia peer, DecodedVideo video) => peer.Statistics.DecodedAudio > 0 && video.AudioSamples > 4800 && video.Frames >= 10; - private static int FreePort(int except = 0, string address = "127.0.0.1") + private static int FreePort(int except = 0) { - var ip = IPAddress.Parse(address); for (var port = 32000; port < 60000; port += 2) { if (port == except) continue; - using var socket = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp); - using var rtcp = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + 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(ip, port)); - rtcp.Bind(new IPEndPoint(ip, port + 1)); + 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) { } diff --git a/src/PostIt/PostIt.Tests/MessagingSessionTests.cs b/src/PostIt/PostIt.Tests/MessagingSessionTests.cs deleted file mode 100644 index 10e699e50..000000000 --- a/src/PostIt/PostIt.Tests/MessagingSessionTests.cs +++ /dev/null @@ -1,501 +0,0 @@ -using Avalonia.Headless.XUnit; -using Avalonia.Controls; -using Avalonia.Threading; -using Avalonia.VisualTree; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.SignalR; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System.Text; -using System.Security.Cryptography; -using PostIt.Services; -using PostIt.ViewModels; -using PostIt.ViewModels.Chat; -using PostIt.Views; -using Yavsc.Api.Client; - -namespace PostIt.Tests; - -public sealed class MessagingSessionTests -{ - [Fact] - public void Only_explicit_settings_application_raises_Applied_after_successful_save() - { - var path = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}.json"); - try - { - var settings = new Settings(path); - var saves = 0; - var applications = 0; - settings.Saved += (_, _) => saves++; - settings.Applied += (_, _) => - { - Assert.False(settings.IsDirty); - Assert.True(File.Exists(path)); - applications++; - }; - settings.AndroidKeepChatConnected = true; - settings.Save(); - Assert.Equal(0, applications); - settings.DarkMode = true; - Assert.True(settings.ApplyCommand.CanExecute(null)); - settings.ApplyCommand.Execute(null); - Assert.Equal(1, applications); - Assert.Equal(2, saves); - Assert.False(settings.ApplyCommand.CanExecute(null)); - settings.AndroidKeepChatConnected = false; - Assert.True(settings.ApplyCommand.CanExecute(null)); - settings.Apply(); - Assert.Equal(2, applications); - } - finally { File.Delete(path); } - } - - [Fact] - public void Failed_settings_save_does_not_raise_Applied() - { - var directory = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}"); - Directory.CreateDirectory(directory); - try - { - var settings = new Settings(directory); - var applied = false; - settings.Applied += (_, _) => applied = true; - settings.AndroidKeepChatConnected = true; - var failure = Record.Exception(() => settings.Apply()); - Assert.True(failure is IOException or UnauthorizedAccessException); - Assert.False(applied); - Assert.True(settings.IsDirty); - } - finally { Directory.Delete(directory); } - } - -#if DEBUG - [Fact] - public async Task Native_start_generations_reject_stale_requests_after_stop_and_timeout() - => await PostIt.Android.Tests.ChatServiceEpochTests.VerifyAsync(); -#endif - - [AvaloniaFact] - public void Settings_page_binds_opt_in_and_hides_it_on_other_platforms() - { - var settings = new Settings(); - var page = new SettingsPage { DataContext = settings }; - var window = new Window { Content = page }; - try - { - window.Show(); - var checkbox = page.FindControl("BackgroundChatCheckBox")!; - var container = checkbox.GetVisualAncestors().OfType().First(); - Assert.Equal(OperatingSystem.IsAndroid(), container.IsVisible); - var explanation = Assert.Single(container.Children.OfType()).Text!; - Assert.Contains("sans notification permanente", explanation); - Assert.Contains("ne garantissent pas", explanation); - Assert.False(checkbox.IsChecked); - var save = Assert.Single(window.GetVisualDescendants().OfType