diff --git a/SharepointToolbox/Localization/Strings.fr.resx b/SharepointToolbox/Localization/Strings.fr.resx index ccd1a19..0a6f348 100644 --- a/SharepointToolbox/Localization/Strings.fr.resx +++ b/SharepointToolbox/Localization/Strings.fr.resx @@ -583,6 +583,8 @@ Cette action est irréversible. Options d'exportation Fusionner les permissions en double Masquer les noms bruts (SharingLinks, Limited Access) + Exclure les liens de partage + Exclure les groupes système (Limited Access) Enregistrer l'app Supprimer l'app @@ -687,6 +689,7 @@ Cette action est irréversible. Généré Généré : membres indisponibles + Groupe vide Lien (sans ext.) (sans extension) @@ -784,4 +787,84 @@ Cette action est irréversible. utilisateur(s) fichiers sites + entrées + + Mode simplifié + Regroupe les permissions brutes SharePoint en libellés lisibles (Propriétaire, Éditeur, Contributeur, Lecteur, Lecture seule) et colore les lignes par niveau de risque. Utile pour un aperçu rapide de la sécurité sans jargon technique. + Fusionner les permissions + Lorsqu'activé, les entrées de permission multiples pour le même utilisateur ou groupe sont regroupées en une seule ligne dans l'export, réduisant la taille du rapport. Désactivez pour voir chaque permission individuellement. + Masquer les groupes système + Supprime les groupes système créés automatiquement par SharePoint (ex. « Excel Services Viewers », groupes « SharingLinks.* »). Ces groupes sont gérés en interne par SharePoint et ne sont généralement pas pertinents pour les audits d'accès. + Exclure les liens de partage + Supprime les entrées de lien de partage des résultats et des exports (ex. « Tout le monde avec le lien », liens à l'échelle de l'organisation). Utile pour ne conserver que les permissions directes des utilisateurs et groupes. + Exclure les groupes système (Limited Access) + Supprime les entrées « Limited Access System Group For Web/List » des résultats et des exports. SharePoint crée ces groupes automatiquement lorsqu'un utilisateur a accès à un élément spécifique ; ils sont rarement pertinents pour les audits d'accès. + Inclure les permissions héritées + Par défaut, seuls les objets avec des permissions uniques (rompues) sont affichés. Activez pour inclure les objets qui héritent les permissions d'un parent et obtenir une vue complète des accès. + Mode de fractionnement de l'export + Fichier unique : tous les résultats dans un seul fichier CSV ou HTML. + +Fractionner par site : crée un fichier séparé pour chaque collection de sites. Utile pour les grandes tenances multi-sites. + Recherche de fichiers KQL + Recherche des fichiers dans vos sites SharePoint via KQL (Keyword Query Language). Le champ mot-clé est optionnel — laissez-le vide pour retourner tous les fichiers correspondant aux filtres actifs. Combinez les filtres de date, auteur et bibliothèque pour affiner les résultats. + Filtre regex sur le nom de fichier + Filtre les résultats côté client avec une expression régulière .NET appliquée aux noms de fichiers. Exemple : \.pdf$ correspond uniquement aux PDF. Laissez vide pour ignorer ce filtre. L'expression est insensible à la casse. + Politique de nettoyage des versions + Supprime définitivement les anciennes versions de documents des bibliothèques SharePoint. Seules les N versions les plus récentes sont conservées — les versions plus anciennes sont supprimées de façon permanente et ne peuvent pas être récupérées. Effectuez d'abord une analyse pour prévisualiser les suppressions. + Conserver la première version + Conserve toujours la version 1.0 (originale) de chaque document, indépendamment du paramètre « Conserver les N dernières ». Utile pour maintenir une trace de l'état initial du document. + Confirmer avant suppression + Lorsqu'activé, une boîte de dialogue de confirmation apparaît pour chaque fichier avant la suppression des versions. Décochez pour un traitement en lot sans intervention. + Critères de détection des doublons + Deux éléments sont identifiés comme doublons quand leurs noms correspondent ET que tous les critères supplémentaires cochés correspondent également. Plus de critères cochés = moins de groupes, mais plus précis. Nom uniquement : trouve les fichiers avec le même nom, quel que soit leur contenu. + Inclure le dossier source + Lorsqu'activé, le dossier source lui-même est recréé à la destination (ex. transférer « Rapports » crée un dossier « Rapports/ » à la cible). Lorsque désactivé, seul le contenu du dossier est transféré — utile pour fusionner du contenu dans un dossier existant. + Copier uniquement le contenu + Lorsqu'activé, seuls les fichiers et sous-dossiers à l'intérieur du dossier sélectionné sont transférés — le dossier lui-même n'est pas recréé à la destination. + Politique de conflit de fichiers + Définit ce qui se passe quand un fichier du même nom existe déjà à la destination : + +• Ignorer — laisser le fichier destination inchangé. +• Écraser — remplacer le fichier destination par le fichier source. +• Renommer — conserver les deux en ajoutant un suffixe numérique au fichier transféré. + Ajout de membres en masse — Format CSV + Le fichier CSV doit contenir ces colonnes (en-têtes obligatoires, ordre libre) : +• GroupName — le nom exact du groupe SharePoint +• Email — l'adresse e-mail de l'utilisateur +• Role — Member, Owner ou Visitor + +Cliquez sur « Charger l'exemple » pour ouvrir un fichier d'exemple pré-rempli. + Création de sites en masse — Format CSV + Le fichier CSV doit contenir ces colonnes : +• Name — le nom d'affichage du nouveau site +• Alias — alias d'URL (sans espaces ; fait partie de l'URL du site) +• Type — TeamSite ou CommunicationSite +• Owners — liste d'adresses e-mail des propriétaires séparées par des virgules + +Cliquez sur « Charger l'exemple » pour ouvrir un fichier d'exemple pré-rempli. + Créer une structure de dossiers — Format CSV + Crée une hiérarchie de dossiers dans une bibliothèque SharePoint à partir d'un fichier CSV. Chaque ligne définit un chemin avec jusqu'à 4 niveaux (Level1–Level4). Laissez les colonnes des niveaux inférieurs vides pour des chemins plus courts. + +Exemple : Contrats | 2024 | T1 | (vide) +Crée : Bibliothèque / Contrats / 2024 / T1 + Capturer un modèle de site + Enregistre la structure du site sélectionné (bibliothèques, dossiers, permissions, paramètres et logo) comme modèle réutilisable stocké localement. Le site source n'est pas modifié. + +Sélectionnez les éléments à capturer avec les cases à cocher ci-dessus. + Appliquer le modèle à un nouveau site + Crée un nouveau site SharePoint et reproduit la structure du modèle sélectionné — bibliothèques, dossiers, permissions, paramètres et logo. Le modèle source et le site d'origine ne sont pas affectés. + +Fournissez un nom d'affichage et un alias d'URL avant de cliquer sur Appliquer. + Mode Recherche vs Mode Navigation + Mode Recherche : tapez un nom ou e-mail pour trouver un utilisateur via Azure AD. Les résultats apparaissent dans une liste — cliquez pour sélectionner. + +Mode Navigation : charge tous les utilisateurs du répertoire de la tenant. Utilisez le filtre pour trouver un utilisateur, puis double-cliquez pour l'ajouter à l'audit. + Audit d'accès vs Audit des permissions + L'onglet Permissions analyse les objets (bibliothèques, dossiers, éléments) pour montrer qui y a accès. + +Cet onglet fait l'inverse : vous sélectionnez un ou plusieurs utilisateurs et il trouve chaque objet auquel ils peuvent accéder — y compris via des groupes SharePoint ou Active Directory. + Bibliothèques masquées + Analyse les bibliothèques SharePoint cachées dans la navigation normale du site (ex. Site Assets, Style Library, Form Templates). Elles peuvent consommer beaucoup d'espace et sont souvent oubliées dans les audits de routine. + Bibliothèque de conservation + Bibliothèque SharePoint cachée qui stocke les versions de documents modifiés ou supprimés pendant qu'une politique de rétention Microsoft Purview / Microsoft 365 Compliance est active. Elle peut croître considérablement sans être visible pour les utilisateurs du site. diff --git a/SharepointToolbox/Localization/Strings.resx b/SharepointToolbox/Localization/Strings.resx index 74bde2a..403a60e 100644 --- a/SharepointToolbox/Localization/Strings.resx +++ b/SharepointToolbox/Localization/Strings.resx @@ -583,6 +583,8 @@ This cannot be undone. Export Options Merge duplicate permissions Hide raw system group names (SharingLinks, Limited Access) + Exclude sharing links + Exclude system groups (Limited Access) Register App Remove App @@ -687,6 +689,7 @@ This cannot be undone. Generated Generated: members unavailable + Empty group Link (no ext) (no extension) @@ -784,4 +787,84 @@ This cannot be undone. user(s) files sites + entries + + Simplified Permissions Mode + Groups raw SharePoint permissions into readable labels (Owner, Editor, Contributor, Reader, View-Only) and color-codes rows by risk level. Useful for a quick security overview without permission-level jargon. + Merge Permissions + When enabled, multiple permission entries for the same user or group are consolidated into a single row in the export, reducing report size. Disable to see every individual permission assignment separately. + Hide System Groups + Removes automatically-created SharePoint system groups from results (e.g. "Excel Services Viewers", "SharingLinks.*" groups). These groups are managed internally by SharePoint and are typically not relevant for user access audits. + Exclude Sharing Links + Removes sharing link entries from results and exports (e.g. "Anyone with the link", organisation-wide links). Useful when you only care about direct user and group permissions. + Exclude System Groups (Limited Access) + Removes "Limited Access System Group For Web/List" entries from results and exports. SharePoint creates these automatically when a user has item-level access; they are rarely relevant for user access audits. + Include Inherited Permissions + By default only objects with unique (broken) permissions are reported. Enable this to also include objects that inherit permissions from a parent, giving a complete picture of who can access every item. + Export Split Mode + Single File: all results are saved in one CSV or HTML file. + +Split by Site: creates a separate file for each site collection. Useful when auditing large multi-site tenants to keep individual files manageable. + KQL File Search + Searches files across your SharePoint sites using KQL (Keyword Query Language). The keyword field is optional — leave it empty to return all files matching only the active filters. Combine date range, author, and library filters to narrow results. + Filename Regex Filter + Post-filters results client-side using a .NET regular expression matched against file names. Example: \.pdf$ matches only PDF files. Leave blank to skip this filter. The expression is case-insensitive. + Version Cleanup Policy + Permanently deletes old document versions from SharePoint libraries. Only the N most recent versions are kept — older ones are removed permanently and cannot be recovered. Run a preview scan first to see what will be deleted. + Keep First Version + Always preserves version 1.0 (the original) of each document, regardless of the "Keep Last N" setting. Useful to maintain an audit trail of a document's initial state. + Confirm Before Delete + When enabled, a confirmation dialog appears for each file before its versions are deleted. Uncheck for unattended batch processing. + Duplicate Matching Criteria + Two items are flagged as duplicates when their names match AND all checked additional criteria also match. More criteria checked = fewer groups, but more precise matches. Using name only finds files with the same filename anywhere in the site, regardless of content. + Include Source Folder + When enabled, the source folder itself is recreated at the destination (e.g. transferring "Reports" creates a "Reports/" folder at the target). When disabled, only the contents inside the folder are transferred — useful when merging into an existing destination folder. + Copy Folder Contents Only + When enabled, only the files and subfolders inside the selected folder are transferred — the selected folder itself is not recreated at the destination. + File Conflict Policy + Defines what happens when a file with the same name already exists at the destination: + +• Skip — leave the existing destination file unchanged. +• Overwrite — replace the destination file with the source file. +• Rename — keep both by appending a number suffix to the transferred file's name. + Bulk Add Members — CSV Format + The CSV file must contain these columns (headers required, order is flexible): +• GroupName — the exact SharePoint group name +• Email — the user's email address +• Role — Member, Owner, or Visitor + +Click "Load Example" to open a pre-filled sample file. + Bulk Create Sites — CSV Format + The CSV file must contain these columns: +• Name — the display name for the new site +• Alias — URL alias (no spaces; becomes part of the site URL) +• Type — TeamSite or CommunicationSite +• Owners — comma-separated list of owner email addresses + +Click "Load Example" to open a pre-filled sample file. + Create Folder Structure — CSV Format + Creates a folder hierarchy inside a SharePoint library from a CSV file. Each row defines one folder path using up to 4 levels (Level1–Level4). Leave deeper level columns empty for shallower paths. + +Example row: Contracts | 2024 | Q1 | (empty) +Creates: Library / Contracts / 2024 / Q1 + Capture Site Template + Saves the currently selected site's structure (libraries, folder hierarchy, permissions, settings, and logo) as a reusable template stored locally on your machine. The source site is not modified in any way. + +Select which elements to include using the checkboxes above. + Apply Template to New Site + Creates a brand-new SharePoint site and reproduces the structure captured in the selected template — including libraries, folders, permissions, settings, and logo. The source template and original site are not affected. + +Provide a display name and URL alias for the new site before clicking Apply. + Search vs Browse Mode + Search Mode: type a name or email to find a specific user via Azure AD. Matching users appear in a list — click to select them for the audit. + +Browse Mode: loads all users in your tenant directory. Use the filter box to narrow the list, then double-click a row to add the user to the audit. + User Access Audit vs Permissions Audit + The Permissions tab scans objects (libraries, folders, items) and shows who has access to each one. + +This tab does the reverse: you select one or more users and it finds every object they can access — including access granted via SharePoint groups or Active Directory groups. + Hidden Libraries + Scans SharePoint libraries hidden from the site's normal navigation (e.g. Site Assets, Style Library, Form Templates). These can consume significant storage and are often overlooked in routine audits. + Preservation Hold Library + A hidden SharePoint library that stores versions of documents modified or deleted while a Microsoft Purview / Microsoft 365 Compliance retention policy is active. It can grow very large over time without being visible to normal site users. diff --git a/SharepointToolbox/Services/BulkMemberService.cs b/SharepointToolbox/Services/BulkMemberService.cs index c7aacfd..4efc0b0 100644 --- a/SharepointToolbox/Services/BulkMemberService.cs +++ b/SharepointToolbox/Services/BulkMemberService.cs @@ -64,6 +64,7 @@ public class BulkMemberService : IBulkMemberService return; } } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Graph API failed for {GroupUrl}, falling back to CSOM: {Error}", @@ -83,7 +84,7 @@ public class BulkMemberService : IBulkMemberService { // Resolve user by email var user = await graphClient.Users[email].GetAsync(cancellationToken: ct); - if (user == null) + if (user?.Id == null) throw new InvalidOperationException($"User not found: {email}"); var userRef = $"https://graph.microsoft.com/v1.0/directoryObjects/{user.Id}"; @@ -138,13 +139,16 @@ public class BulkMemberService : IBulkMemberService } } } - catch { /* not a group-connected site */ } + catch (OperationCanceledException) { throw; } + catch (Exception ex) { Log.Debug("Group lookup not available for {SiteUrl}: {Error}", siteUrl, ex.Message); } } return null; } - catch + catch (OperationCanceledException) { throw; } + catch (Exception ex) { + Log.Debug("Could not resolve M365 group ID for {SiteUrl}: {Error}", siteUrl, ex.Message); return null; } } diff --git a/SharepointToolbox/Services/BulkSiteService.cs b/SharepointToolbox/Services/BulkSiteService.cs index 40a9936..077618b 100644 --- a/SharepointToolbox/Services/BulkSiteService.cs +++ b/SharepointToolbox/Services/BulkSiteService.cs @@ -54,6 +54,9 @@ public class BulkSiteService : IBulkSiteService var owners = ParseEmails(row.Owners); var members = ParseEmails(row.Members); + if (owners.Count == 0) + throw new InvalidOperationException($"Team site '{row.Name}' requires at least one owner."); + var creationInfo = new TeamSiteCollectionCreationInformation { DisplayName = row.Name, @@ -88,6 +91,7 @@ public class BulkSiteService : IBulkSiteService membersGroup.Users.AddUser(user); await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(siteCtx, progress, ct); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Failed to add member {Email} to {Site}: {Error}", @@ -142,6 +146,7 @@ public class BulkSiteService : IBulkSiteService ownersGroup.Users.AddUser(user); await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(siteCtx, progress, ct); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Failed to add owner {Email} to {Site}: {Error}", @@ -162,6 +167,7 @@ public class BulkSiteService : IBulkSiteService membersGroup.Users.AddUser(user); await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(siteCtx, progress, ct); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Failed to add member {Email} to {Site}: {Error}", diff --git a/SharepointToolbox/Services/Export/HtmlExportService.cs b/SharepointToolbox/Services/Export/HtmlExportService.cs index 4aeb3ca..9fb19c9 100644 --- a/SharepointToolbox/Services/Export/HtmlExportService.cs +++ b/SharepointToolbox/Services/Export/HtmlExportService.cs @@ -122,36 +122,46 @@ public class HtmlExportService AppendFilterInput(sb); AppendTableOpen(sb); sb.AppendLine(""); - sb.AppendLine($" {T["report.col.object"]}{T["report.col.title"]}{T["report.col.url"]}{T["report.badge.unique"]}{T["report.col.users_groups"]}{T["report.col.permission_level"]}{T["report.col.simplified"]}{T["report.col.risk"]}{T["report.col.granted_through"]}"); + sb.AppendLine($" {T["report.col.users_groups"]}{T["report.col.permission_level"]}{T["report.col.simplified"]}{T["report.col.risk"]}{T["report.col.granted_through"]}"); sb.AppendLine(""); sb.AppendLine(""); int grpMemIdx = 0; - foreach (var entry in entries) + int sectionIdx = 0; + var groups = entries.GroupBy(e => (e.ObjectType, e.Title, e.Url)).ToList(); + foreach (var group in groups) { - var typeCss = ObjectTypeCss(entry.ObjectType); - var uniqueCss = entry.HasUniquePermissions ? "badge unique" : "badge inherited"; - var uniqueLbl = entry.HasUniquePermissions ? T["report.badge.unique"] : T["report.badge.inherited"]; - var (riskBg, riskText, riskBorder) = RiskLevelColors(entry.RiskLevel); + var sectionId = $"sec{sectionIdx++}"; + var first = group.First(); + var typeCss = ObjectTypeCss(group.Key.ObjectType); + var uniqueCss = first.HasUniquePermissions ? "badge unique" : "badge inherited"; + var uniqueLbl = first.HasUniquePermissions ? T["report.badge.unique"] : T["report.badge.inherited"]; + var count = group.Count(); - var (pills, subRows) = BuildUserPillsCell( - entry.UserLogins, entry.Inner.Users, entry.Inner.PrincipalType, groupMembers, - colSpan: 9, grpMemIdx: ref grpMemIdx, - targetLabel: entry.TargetLabel, sharingLinkType: entry.SharingLinkType, - hideSystemGroupRaw: hideSystemGroupRaw); - - sb.AppendLine(""); - sb.AppendLine($" {HtmlEncode(entry.ObjectType)}"); - sb.AppendLine($" {HtmlEncode(entry.Title)}"); - sb.AppendLine($" {T["report.text.link"]}"); - sb.AppendLine($" {uniqueLbl}"); - sb.AppendLine($" {pills}"); - sb.AppendLine($" {HtmlEncode(entry.PermissionLevels)}"); - sb.AppendLine($" {HtmlEncode(entry.SimplifiedLabels)}"); - sb.AppendLine($" {HtmlEncode(entry.RiskLevel.ToString())}"); - sb.AppendLine($" {BuildGrantedThroughCell(entry.GrantedThrough, entry.TargetUrl, entry.TargetLabel, entry.SharingLinkType, hideSystemGroupRaw)}"); + sb.AppendLine($""); + sb.AppendLine($" {HtmlEncode(group.Key.ObjectType)} {HtmlEncode(group.Key.Title)} {uniqueLbl}{count} {T["report.text.entries_unit"]}"); sb.AppendLine(""); - if (subRows.Length > 0) sb.Append(subRows); + + foreach (var entry in group) + { + var (riskBg, riskText, riskBorder) = RiskLevelColors(entry.RiskLevel); + + var (pills, subRows) = BuildUserPillsCell( + entry.UserLogins, entry.Inner.Users, entry.Inner.PrincipalType, groupMembers, + colSpan: 5, grpMemIdx: ref grpMemIdx, + targetLabel: entry.TargetLabel, sharingLinkType: entry.SharingLinkType, + hideSystemGroupRaw: hideSystemGroupRaw, + sectionId: sectionId); + + sb.AppendLine($""); + sb.AppendLine($" {pills}"); + sb.AppendLine($" {HtmlEncode(entry.PermissionLevels)}"); + sb.AppendLine($" {HtmlEncode(entry.SimplifiedLabels)}"); + sb.AppendLine($" {HtmlEncode(entry.RiskLevel.ToString())}"); + sb.AppendLine($" {BuildGrantedThroughCell(entry.GrantedThrough, entry.TargetUrl, entry.TargetLabel, entry.SharingLinkType, hideSystemGroupRaw)}"); + sb.AppendLine(""); + if (subRows.Length > 0) sb.Append(subRows); + } } AppendTableClose(sb); diff --git a/SharepointToolbox/Services/Export/PermissionHtmlFragments.cs b/SharepointToolbox/Services/Export/PermissionHtmlFragments.cs index 9719354..3b481ef 100644 --- a/SharepointToolbox/Services/Export/PermissionHtmlFragments.cs +++ b/SharepointToolbox/Services/Export/PermissionHtmlFragments.cs @@ -52,17 +52,62 @@ a:hover { text-decoration: underline; } .risk-card .rlabel { font-size: .8rem; margin-top: 2px; } .risk-card .users { font-size: .7rem; margin-top: 2px; opacity: 0.8; } .risk-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: .75rem; font-weight: 600; border: 1px solid; } +.section-header td { background: #edf2f7; font-weight: 600; cursor: pointer; padding: 8px 14px; border-bottom: 2px solid #cbd5e0; user-select: none; } +.section-header:hover td { background: #e2e8f0; } +.section-header .chevron { margin-right: 8px; display: inline-block; transition: transform 0.15s; } +.section-header.collapsed .chevron { transform: rotate(-90deg); } +.entry-badge { display: inline-block; background: #e2e8f0; color: #4a5568; border-radius: 10px; padding: 1px 8px; font-size: .75rem; font-weight: 600; margin-left: 8px; } "; internal const string InlineJs = @"function filterTable() { var input = document.getElementById('filter').value.toLowerCase(); - var rows = document.querySelectorAll('#permTable tbody tr'); - rows.forEach(function(row) { - if (row.hasAttribute('data-group')) return; - row.style.display = row.textContent.toLowerCase().indexOf(input) > -1 ? '' : 'none'; + var sections = document.querySelectorAll('#permTable tbody tr.section-header'); + if (sections.length === 0) { + document.querySelectorAll('#permTable tbody tr').forEach(function(row) { + if (row.hasAttribute('data-group')) return; + row.style.display = row.textContent.toLowerCase().indexOf(input) > -1 ? '' : 'none'; + }); + return; + } + if (!input) { + sections.forEach(function(hdr) { + hdr.style.display = ''; + var sid = hdr.getAttribute('data-section'); + var collapsed = hdr.classList.contains('collapsed'); + document.querySelectorAll('[data-section-member=' + sid + ']:not([data-group])').forEach(function(r) { + r.style.display = collapsed ? 'none' : ''; + }); + }); + return; + } + sections.forEach(function(hdr) { + var sid = hdr.getAttribute('data-section'); + var members = document.querySelectorAll('[data-section-member=' + sid + ']:not([data-group])'); + var anyMatch = false; + members.forEach(function(r) { + var match = r.textContent.toLowerCase().indexOf(input) > -1; + r.style.display = match ? '' : 'none'; + if (match) anyMatch = true; + }); + if (!anyMatch && hdr.textContent.toLowerCase().indexOf(input) > -1) { + anyMatch = true; + members.forEach(function(r) { r.style.display = ''; }); + } + hdr.style.display = anyMatch ? '' : 'none'; }); } document.addEventListener('click', function(ev) { + var hdr = ev.target.closest('.section-header'); + if (hdr) { + var sid = hdr.getAttribute('data-section'); + hdr.classList.toggle('collapsed'); + var collapsed = hdr.classList.contains('collapsed'); + document.querySelectorAll('[data-section-member=' + sid + ']').forEach(function(r) { + if (r.hasAttribute('data-group')) { r.style.display = 'none'; return; } + r.style.display = collapsed ? 'none' : ''; + }); + return; + } var trigger = ev.target.closest('.group-expandable'); if (!trigger) return; var id = trigger.getAttribute('data-group-target'); @@ -141,7 +186,8 @@ document.addEventListener('click', function(ev) { ref int grpMemIdx, string? targetLabel = null, string? sharingLinkType = null, - bool hideSystemGroupRaw = false) + bool hideSystemGroupRaw = false, + string? sectionId = null) { var T = TranslationSource.Instance; var logins = userLogins.Split(';', StringSplitOptions.RemoveEmptyEntries); @@ -173,35 +219,48 @@ document.addEventListener('click', function(ev) { if (hasResolvedMembers && groupMembers!.TryGetValue(name, out var resolved)) { - var grpId = $"grpmem{grpMemIdx}"; - pills.Append(""); - if (isResolvedSystemGroup) + if (resolved.Count == 0) { - if (!string.IsNullOrEmpty(sharingLinkType)) - pills.Append(BuildSharingLinkBadge(sharingLinkType!)); - pills.Append(HtmlEncode(targetLabel!)); + // Members unavailable — render plain pill, skip expandable sub-row. + var cls2 = isResolvedSystemGroup ? "user-pill\" data-system-group=\"1" : "user-pill"; + pills.Append($""); + if (isResolvedSystemGroup) + { + if (!string.IsNullOrEmpty(sharingLinkType)) + pills.Append(BuildSharingLinkBadge(sharingLinkType!)); + pills.Append(HtmlEncode(targetLabel!)); + } + else + { + pills.Append(HtmlEncode(name)); + } + pills.Append(""); } else { - pills.Append(HtmlEncode(name)); - } - pills.Append(" ▼"); + var grpId = $"grpmem{grpMemIdx}"; + pills.Append(""); + if (isResolvedSystemGroup) + { + if (!string.IsNullOrEmpty(sharingLinkType)) + pills.Append(BuildSharingLinkBadge(sharingLinkType!)); + pills.Append(HtmlEncode(targetLabel!)); + } + else + { + pills.Append(HtmlEncode(name)); + } + pills.Append(" ▼"); - string memberContent; - if (resolved.Count > 0) - { var parts = resolved.Select(m => $"{HtmlEncode(m.DisplayName)} <{HtmlEncode(m.Login)}>"); - memberContent = string.Join(" • ", parts); + var memberContent = string.Join(" • ", parts); + var sectionAttr = sectionId != null ? $" data-section-member=\"{HtmlEncode(sectionId)}\"" : ""; + subRows.AppendLine($"{memberContent}"); + grpMemIdx++; } - else - { - memberContent = $"{T["report.text.members_unavailable"]}"; - } - subRows.AppendLine($"{memberContent}"); - grpMemIdx++; } else if (isResolvedSystemGroup) { diff --git a/SharepointToolbox/Services/FileTransferService.cs b/SharepointToolbox/Services/FileTransferService.cs index 41c9793..221f2bb 100644 --- a/SharepointToolbox/Services/FileTransferService.cs +++ b/SharepointToolbox/Services/FileTransferService.cs @@ -7,14 +7,19 @@ using SharepointToolbox.Core.Models; namespace SharepointToolbox.Services; /// -/// Orchestrates server-side file copy/move between two SharePoint libraries -/// (same or different tenants). Uses for the -/// transfer itself so bytes never round-trip through the local machine. -/// Folder creation and enumeration are done via CSOM; all ambient retries -/// flow through . +/// Orchestrates file copy/move between two SharePoint libraries (same or +/// different tenants). Hybrid strategy: server-side +/// first (zero local bandwidth), then transparent fallback to stream copy +/// (OpenBinaryDirect/SaveBinaryDirect) on a list-view-threshold +/// failure so transfers still succeed against libraries above the 5,000-item +/// cap. Folder enumeration uses paged CAML; folder creation is cached per job +/// to avoid re-checking the same path for every file. /// public class FileTransferService : IFileTransferService { + private const int ListViewThresholdItemCount = 5000; + private const int LargeLibraryPageSize = 500; + /// /// Runs the configured . Enumerates source files /// (unless the job is folder-only), pre-creates destination folders, then @@ -30,12 +35,30 @@ public class FileTransferService : IFileTransferService IProgress progress, CancellationToken ct) { - // 1. Enumerate files from source (unless contents are suppressed). + // 1. Pre-flight: discover library item counts so we can pick a page size + // for source enumeration and warn early that the server-side copy path + // may trip the list-view threshold. The stream fallback in + // TransferSingleFileAsync handles the LVT case transparently, but the + // counts help size-tune enumeration up front. + var srcItemCount = await TryGetListItemCountAsync(sourceCtx, job.SourceLibrary, progress, ct); + var dstItemCount = await TryGetListItemCountAsync(destCtx, job.DestinationLibrary, progress, ct); + Log.Information( + "Transfer pre-flight: source={SrcLib} ({SrcCount} items), dest={DstLib} ({DstCount} items)", + job.SourceLibrary, srcItemCount, job.DestinationLibrary, dstItemCount); + + if (srcItemCount > ListViewThresholdItemCount || dstItemCount > ListViewThresholdItemCount) + { + progress.Report(OperationProgress.Indeterminate( + $"Large library detected (source: {srcItemCount}, dest: {dstItemCount}). " + + "Using paged enumeration and stream-copy fallback when needed.")); + } + + // 2. Enumerate files from source (unless contents are suppressed). IReadOnlyList files; if (job.CopyFolderContents) { progress.Report(new OperationProgress(0, 0, "Enumerating source files...")); - files = await EnumerateFilesAsync(sourceCtx, job, progress, ct); + files = await EnumerateFilesAsync(sourceCtx, job, srcItemCount, progress, ct); } else { @@ -51,7 +74,7 @@ public class FileTransferService : IFileTransferService return new BulkOperationSummary(new List>()); } - // 2. Build source and destination base paths. Resolve library roots via + // 3. Build source and destination base paths. Resolve library roots via // CSOM — constructing from title breaks for localized libraries whose // URL segment differs (e.g. title "Documents" → URL "Shared Documents"), // causing "Access denied" when CSOM tries to touch a non-existent path. @@ -60,6 +83,11 @@ public class FileTransferService : IFileTransferService var dstBasePath = await ResolveLibraryPathAsync( destCtx, job.DestinationLibrary, job.DestinationFolderPath, progress, ct); + // Per-job cache of destination folders we've already ensured. Without + // this, EnsureFolderAsync re-checks .Exists for every file in the same + // folder — thousands of round-trips on a flat directory transfer. + var ensuredFolders = new HashSet(StringComparer.OrdinalIgnoreCase); + // When IncludeSourceFolder is set, recreate the source folder name under // destination so dest/srcFolderName/... mirrors the source tree. When // no SourceFolderPath is set, fall back to the source library name. @@ -74,11 +102,11 @@ public class FileTransferService : IFileTransferService if (!string.IsNullOrEmpty(srcFolderName)) { dstBasePath = $"{dstBasePath}/{srcFolderName}"; - await EnsureFolderAsync(destCtx, dstBasePath, progress, ct); + await EnsureFolderCachedAsync(destCtx, dstBasePath, ensuredFolders, progress, ct); } } - // 3. Transfer each file using BulkOperationRunner + // 4. Transfer each file using BulkOperationRunner return await BulkOperationRunner.RunAsync( files, async (fileRelUrl, idx, token) => @@ -88,13 +116,13 @@ public class FileTransferService : IFileTransferService if (fileRelUrl.StartsWith(srcBasePath, StringComparison.OrdinalIgnoreCase)) relativePart = fileRelUrl.Substring(srcBasePath.Length).TrimStart('/'); - // Ensure destination folder exists + // Ensure destination folder exists (cached) var destFolderRelative = dstBasePath; var fileFolder = Path.GetDirectoryName(relativePart)?.Replace('\\', '/'); if (!string.IsNullOrEmpty(fileFolder)) { destFolderRelative = $"{dstBasePath}/{fileFolder}"; - await EnsureFolderAsync(destCtx, destFolderRelative, progress, token); + await EnsureFolderCachedAsync(destCtx, destFolderRelative, ensuredFolders, progress, token); } var fileName = Path.GetFileName(relativePart); @@ -116,6 +144,32 @@ public class FileTransferService : IFileTransferService TransferJob job, IProgress progress, CancellationToken ct) + { + // Hybrid path: try the server-side MoveCopyUtil first (bytes never + // leave SharePoint). If the destination (or source) library trips the + // list-view threshold, fall back to a stream copy via HTTP-direct APIs + // that bypass list internals. + try + { + await ServerSideTransferAsync(sourceCtx, destCtx, srcFileUrl, dstFileUrl, job, progress, ct); + } + catch (ServerException ex) when (IsListViewThresholdException(ex)) + { + Log.Warning( + "Server-side transfer hit list-view threshold for {File} — falling back to stream copy.", + srcFileUrl); + await StreamTransferAsync(sourceCtx, destCtx, srcFileUrl, dstFileUrl, job, progress, ct); + } + } + + private async Task ServerSideTransferAsync( + ClientContext sourceCtx, + ClientContext destCtx, + string srcFileUrl, + string dstFileUrl, + TransferJob job, + IProgress progress, + CancellationToken ct) { // MoveCopyUtil.CopyFileByPath expects absolute URLs (scheme + host), // not server-relative paths. Passing "/sites/..." silently fails or @@ -153,9 +207,173 @@ public class FileTransferService : IFileTransferService } } + /// + /// Path-based stream copy fallback. Reads the source via + /// and writes + /// to the destination via Folder.Files.Add(FileCreationInformation). + /// Both target a specific folder by path rather than querying list items, + /// so they succeed against libraries that exceed the list-view threshold. + /// Bytes do round-trip through the local machine — this is strictly the + /// fallback when server-side copy is unavailable. + /// + private async Task StreamTransferAsync( + ClientContext sourceCtx, + ClientContext destCtx, + string srcFileUrl, + string dstFileUrl, + TransferJob job, + IProgress progress, + CancellationToken ct) + { + // Resolve the destination file name for conflict handling. Returns null + // when policy=Skip and the file already exists. + var effectiveDestUrl = await ResolveDestinationOnConflictAsync(destCtx, dstFileUrl, job, progress, ct); + if (effectiveDestUrl == null) + { + Log.Warning("Skipped (already exists, stream fallback): {File}", srcFileUrl); + return; + } + + // Rename policy guarantees a free path via ResolveDestinationOnConflictAsync, + // so overwrite is only needed for the explicit Overwrite policy. + bool overwrite = job.ConflictPolicy == ConflictPolicy.Overwrite; + + ct.ThrowIfCancellationRequested(); + + // 1. Download the source bytes into memory. OpenBinaryStream is a + // ClientResult — usable only after ExecuteQuery. + var srcFile = sourceCtx.Web.GetFileByServerRelativeUrl(srcFileUrl); + var streamResult = srcFile.OpenBinaryStream(); + await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(sourceCtx, progress, ct); + + if (streamResult.Value == null) + throw new InvalidOperationException($"Could not open binary stream for: {srcFileUrl}"); + + using var buffer = new MemoryStream(); + await streamResult.Value.CopyToAsync(buffer, 81920, ct); + buffer.Position = 0; + + // 2. Upload to the destination folder. Files.Add with ContentStream + // streams the payload in one request and does not touch list-view + // metadata, so it bypasses LVT. + var slash = effectiveDestUrl.LastIndexOf('/'); + if (slash < 0) + throw new InvalidOperationException($"Invalid destination URL (no slash): {effectiveDestUrl}"); + var destFolderUrl = effectiveDestUrl.Substring(0, slash); + var destFileName = effectiveDestUrl.Substring(slash + 1); + + var destFolder = destCtx.Web.GetFolderByServerRelativeUrl(destFolderUrl); + var creation = new FileCreationInformation + { + Url = destFileName, + Overwrite = overwrite, + ContentStream = buffer, + }; + destFolder.Files.Add(creation); + await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(destCtx, progress, ct); + + if (job.Mode == TransferMode.Move) + { + // Stream copy cannot atomically move; delete the source after a + // successful upload to honour Move semantics. + var srcDelete = sourceCtx.Web.GetFileByServerRelativeUrl(srcFileUrl); + srcDelete.DeleteObject(); + try + { + await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(sourceCtx, progress, ct); + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + Log.Error(ex, + "Move: source delete failed for {Src} after successful upload to {Dst}. " + + "File is duplicated — manually delete the source.", + srcFileUrl, effectiveDestUrl); + throw; + } + } + } + + /// + /// Honours when the destination + /// path already exists. Returns the URL to write to, or null when + /// the file should be skipped. For , + /// probes name (1).ext, name (2).ext, ... until a free slot + /// is found. + /// + private static async Task ResolveDestinationOnConflictAsync( + ClientContext destCtx, + string dstFileUrl, + TransferJob job, + IProgress progress, + CancellationToken ct) + { + if (job.ConflictPolicy == ConflictPolicy.Overwrite) + return dstFileUrl; + + bool exists = await FileExistsAsync(destCtx, dstFileUrl, progress, ct); + if (!exists) return dstFileUrl; + + if (job.ConflictPolicy == ConflictPolicy.Skip) + return null; + + // Rename: keep both. Append " (n)" before the extension. + var dir = dstFileUrl.Substring(0, dstFileUrl.LastIndexOf('/')); + var leaf = dstFileUrl.Substring(dstFileUrl.LastIndexOf('/') + 1); + var stem = Path.GetFileNameWithoutExtension(leaf); + var ext = Path.GetExtension(leaf); + + for (int n = 1; n <= 999; n++) + { + var candidate = $"{dir}/{stem} ({n}){ext}"; + if (!await FileExistsAsync(destCtx, candidate, progress, ct)) + return candidate; + } + // Extremely unlikely; surface as failure rather than silent overwrite. + throw new InvalidOperationException( + $"Could not find an unused destination filename for {dstFileUrl} after 999 attempts."); + } + + private static async Task FileExistsAsync( + ClientContext ctx, + string fileServerRelativeUrl, + IProgress progress, + CancellationToken ct) + { + try + { + var file = ctx.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); + ctx.Load(file, f => f.Exists); + await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(ctx, progress, ct); + return file.Exists; + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + Log.Debug("File existence check failed for {Url}: {Error}", fileServerRelativeUrl, ex.Message); + return false; + } + } + + /// + /// Detects SharePoint's list-view-threshold ServerException across locales. + /// English: "exceeds the list view threshold". French: "depasse le seuil + /// d'affichage de liste". German: "Listenansichtsschwellenwert". + /// + internal static bool IsListViewThresholdException(Exception ex) + { + var msg = ex.Message ?? string.Empty; + return msg.Contains("list view threshold", StringComparison.OrdinalIgnoreCase) + || msg.Contains("seuil d'affichage", StringComparison.OrdinalIgnoreCase) + || msg.Contains("seuil d", StringComparison.OrdinalIgnoreCase) && msg.Contains("liste", StringComparison.OrdinalIgnoreCase) + || msg.Contains("Listenansichtsschwellenwert", StringComparison.OrdinalIgnoreCase) + || msg.Contains("umbral de vista de lista", StringComparison.OrdinalIgnoreCase); + } + private async Task> EnumerateFilesAsync( ClientContext ctx, TransferJob job, + int sourceItemCount, IProgress progress, CancellationToken ct) { @@ -226,6 +444,45 @@ public class FileTransferService : IFileTransferService return false; } + private async Task TryGetListItemCountAsync( + ClientContext ctx, + string libraryTitle, + IProgress progress, + CancellationToken ct) + { + try + { + var list = ctx.Web.Lists.GetByTitle(libraryTitle); + ctx.Load(list, l => l.ItemCount); + await ExecuteQueryRetryHelper.ExecuteQueryRetryAsync(ctx, progress, ct); + return list.ItemCount; + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + // Non-fatal: pre-flight count is purely informational. Treat as + // unknown (-1) so the rest of the pipeline still runs. + Log.Warning("Failed to read ItemCount for {Library}: {Error}", libraryTitle, ex.Message); + return -1; + } + } + + /// + /// EnsureFolderAsync wrapper that records successful checks in a per-job + /// set so the same destination folder isn't re-validated for every file. + /// + private async Task EnsureFolderCachedAsync( + ClientContext ctx, + string folderServerRelativeUrl, + HashSet cache, + IProgress progress, + CancellationToken ct) + { + var normalized = folderServerRelativeUrl.TrimEnd('/'); + if (!cache.Add(normalized)) return; + await EnsureFolderAsync(ctx, normalized, progress, ct); + } + private async Task EnsureFolderAsync( ClientContext ctx, string folderServerRelativeUrl, diff --git a/SharepointToolbox/Services/SharePointGroupResolver.cs b/SharepointToolbox/Services/SharePointGroupResolver.cs index 48da64e..e3fbcfc 100644 --- a/SharepointToolbox/Services/SharePointGroupResolver.cs +++ b/SharepointToolbox/Services/SharePointGroupResolver.cs @@ -23,7 +23,7 @@ namespace SharepointToolbox.Services; /// public class SharePointGroupResolver : ISharePointGroupResolver { - private readonly AppGraphClientFactory? _graphClientFactory; + private readonly AppGraphClientFactory _graphClientFactory; public SharePointGroupResolver(AppGraphClientFactory graphClientFactory) { @@ -57,6 +57,7 @@ public class SharePointGroupResolver : ISharePointGroupResolver foreach (var g in ctx.Web.SiteGroups) groupTitles.Add(g.Title); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Could not enumerate SiteGroups on {Url}: {Error}", ctx.Url, ex.Message); @@ -92,7 +93,7 @@ public class SharePointGroupResolver : ISharePointGroupResolver if (IsAadGroup(user.LoginName)) { // Lazy-create graph client on first AAD group encountered - graphClient ??= await _graphClientFactory!.CreateClientAsync(clientId, ct); + graphClient ??= await _graphClientFactory.CreateClientAsync(clientId, ct); var aadId = ExtractAadGroupId(user.LoginName); var leafUsers = await ResolveAadGroupAsync(graphClient, aadId, ct); @@ -110,6 +111,7 @@ public class SharePointGroupResolver : ISharePointGroupResolver .DistinctBy(m => m.Login, StringComparer.OrdinalIgnoreCase) .ToList(); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Could not resolve SP group '{Group}': {Error}", groupName, ex.Message); @@ -182,6 +184,7 @@ public class SharePointGroupResolver : ISharePointGroupResolver await pageIterator.IterateAsync(ct); return members; } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Warning("Could not resolve AAD group '{Id}' transitively: {Error}", aadGroupId, ex.Message); diff --git a/SharepointToolbox/Services/SystemGroupTargetResolver.cs b/SharepointToolbox/Services/SystemGroupTargetResolver.cs index f222d41..6ac73ed 100644 --- a/SharepointToolbox/Services/SystemGroupTargetResolver.cs +++ b/SharepointToolbox/Services/SystemGroupTargetResolver.cs @@ -42,6 +42,7 @@ public class SystemGroupTargetResolver : ISystemGroupTargetResolver _ => null }; } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Debug("System group target resolution failed for {Kind} on {Site}: {Error}", @@ -97,7 +98,7 @@ public class SystemGroupTargetResolver : ISystemGroupTargetResolver return new SystemGroupTarget(SystemGroupKind.SharingLink, file.Name, url, linkType); } } - catch (ServerException) { /* fall through */ } + catch (ServerException ex) { Log.Debug("File by ID not found for {Id} on {Site}: {Error}", itemUniqueId, ctx.Url, ex.Message); } // 2. Try as folder on current web. try @@ -109,7 +110,7 @@ public class SystemGroupTargetResolver : ISystemGroupTargetResolver var url = BuildAbsoluteUrl(ctx.Url, folder.ServerRelativeUrl); return new SystemGroupTarget(SystemGroupKind.SharingLink, folder.Name, url, linkType); } - catch (ServerException) { /* fall through */ } + catch (ServerException ex) { Log.Debug("Folder by ID not found for {Id} on {Site}: {Error}", itemUniqueId, ctx.Url, ex.Message); } // 3. Search-index fallback — covers items moved to a different subsite or // deleted recently (the index may lag the deletion by minutes/hours). @@ -168,6 +169,7 @@ public class SystemGroupTargetResolver : ISystemGroupTargetResolver path, linkType); } + catch (OperationCanceledException) { throw; } catch (Exception ex) { Log.Debug("UniqueId search fallback failed for {Item} on {Site}: {Error}", diff --git a/SharepointToolbox/Services/VersionCleanupService.cs b/SharepointToolbox/Services/VersionCleanupService.cs index 945b6c5..d6a6315 100644 --- a/SharepointToolbox/Services/VersionCleanupService.cs +++ b/SharepointToolbox/Services/VersionCleanupService.cs @@ -117,6 +117,7 @@ public class VersionCleanupService : IVersionCleanupService IProgress progress, CancellationToken ct) { + int before = 0; try { var file = ctx.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); @@ -131,7 +132,7 @@ public class VersionCleanupService : IVersionCleanupService // file.Versions contains only HISTORICAL versions; the current published // version lives on `file` itself and is never deletable here. var versions = file.Versions.ToList(); - int before = versions.Count; + before = versions.Count; if (before == 0) return null; // Sort by Created ascending so [0] is the oldest historical version. @@ -173,6 +174,7 @@ public class VersionCleanupService : IVersionCleanupService BytesFreed = bytesFreed, }; } + catch (OperationCanceledException) { throw; } catch (Exception ex) { _logger.LogWarning(ex, "Failed to trim versions for {File}", fileServerRelativeUrl); @@ -182,6 +184,7 @@ public class VersionCleanupService : IVersionCleanupService Library = libraryTitle, FileServerRelativeUrl = fileServerRelativeUrl, FileName = System.IO.Path.GetFileName(fileServerRelativeUrl), + VersionsBefore = before, Error = ex.Message, }; } diff --git a/SharepointToolbox/Themes/DarkPalette.xaml b/SharepointToolbox/Themes/DarkPalette.xaml index d051c94..94f5329 100644 --- a/SharepointToolbox/Themes/DarkPalette.xaml +++ b/SharepointToolbox/Themes/DarkPalette.xaml @@ -17,6 +17,8 @@ + + diff --git a/SharepointToolbox/Themes/LightPalette.xaml b/SharepointToolbox/Themes/LightPalette.xaml index 9281e87..e0480e1 100644 --- a/SharepointToolbox/Themes/LightPalette.xaml +++ b/SharepointToolbox/Themes/LightPalette.xaml @@ -17,6 +17,8 @@ + + diff --git a/SharepointToolbox/Themes/ModernTheme.xaml b/SharepointToolbox/Themes/ModernTheme.xaml index 89a18f5..46169b1 100644 --- a/SharepointToolbox/Themes/ModernTheme.xaml +++ b/SharepointToolbox/Themes/ModernTheme.xaml @@ -1357,6 +1357,55 @@ + + + + + diff --git a/SharepointToolbox/ViewModels/Tabs/PermissionsViewModel.cs b/SharepointToolbox/ViewModels/Tabs/PermissionsViewModel.cs index 01edf24..8af6541 100644 --- a/SharepointToolbox/ViewModels/Tabs/PermissionsViewModel.cs +++ b/SharepointToolbox/ViewModels/Tabs/PermissionsViewModel.cs @@ -54,6 +54,14 @@ public partial class PermissionsViewModel : FeatureViewModelBase [ObservableProperty] private bool _hideSystemGroupRaw = true; + /// When true, sharing link entries (SharingLinkType != null) are removed from results and exports. + [ObservableProperty] + private bool _excludeSharingLinks; + + /// When true, "Limited Access System Group For Web/List" entries are removed from results and exports. + [ObservableProperty] + private bool _excludeSystemGroups; + [ObservableProperty] private bool _includeSubsites; @@ -102,6 +110,17 @@ public partial class PermissionsViewModel : FeatureViewModelBase private ReportSplitMode CurrentSplit => SplitModeIndex == 1 ? ReportSplitMode.BySite : ReportSplitMode.Single; private HtmlSplitLayout CurrentLayout => HtmlLayoutIndex == 1 ? HtmlSplitLayout.SingleTabbed : HtmlSplitLayout.SeparateFiles; + /// + /// Results after applying ExcludeSharingLinks / ExcludeSystemGroups filters. + /// Rebuilt when Results changes or filter flags change. + /// + private IReadOnlyList _filteredResults = Array.Empty(); + public IReadOnlyList FilteredResults + { + get => _filteredResults; + private set => SetProperty(ref _filteredResults, value); + } + /// /// Simplified wrappers computed from Results. Rebuilt when Results changes. /// @@ -124,16 +143,37 @@ public partial class PermissionsViewModel : FeatureViewModelBase /// /// The collection the DataGrid actually binds to. Returns: - /// - Results (raw) when simplified mode is OFF + /// - FilteredResults (raw) when simplified mode is OFF /// - SimplifiedResults when simplified mode is ON and detail view is ON /// - (View handles summary display separately via Summaries property) /// public object ActiveItemsSource => IsSimplifiedMode ? (object)SimplifiedResults - : Results; + : FilteredResults; partial void OnFolderDepthChanged(int value) => OnPropertyChanged(nameof(IsMaxDepth)); + partial void OnExcludeSharingLinksChanged(bool value) => RefreshAfterFilterChange(); + partial void OnExcludeSystemGroupsChanged(bool value) => RefreshAfterFilterChange(); + + private void RefreshAfterFilterChange() + { + if (Results.Count == 0) return; + RebuildFilteredResults(); + if (IsSimplifiedMode) RebuildSimplifiedData(); + OnPropertyChanged(nameof(ActiveItemsSource)); + } + + private void RebuildFilteredResults() + { + IEnumerable filtered = Results; + if (ExcludeSharingLinks) + filtered = filtered.Where(e => string.IsNullOrEmpty(e.SharingLinkType)); + if (ExcludeSystemGroups) + filtered = filtered.Where(e => !e.GrantedThrough.Contains("Limited Access System Group", StringComparison.OrdinalIgnoreCase)); + FilteredResults = filtered.ToList(); + } + // ── Commands ──────────────────────────────────────────────────────────── public IAsyncRelayCommand ExportCsvCommand { get; } @@ -172,8 +212,8 @@ public partial class PermissionsViewModel : FeatureViewModelBase _settingsService = settingsService; _ownershipService = ownershipService; - ExportCsvCommand = new AsyncRelayCommand(ExportCsvAsync, CanExport); - ExportHtmlCommand = new AsyncRelayCommand(ExportHtmlAsync, CanExport); + ExportCsvCommand = new AsyncRelayCommand(ct => ExportCsvAsync(ct), CanExport); + ExportHtmlCommand = new AsyncRelayCommand(ct => ExportHtmlAsync(ct), CanExport); } /// @@ -199,8 +239,8 @@ public partial class PermissionsViewModel : FeatureViewModelBase _settingsService = settingsService; _ownershipService = ownershipService; - ExportCsvCommand = new AsyncRelayCommand(ExportCsvAsync, CanExport); - ExportHtmlCommand = new AsyncRelayCommand(ExportHtmlAsync, CanExport); + ExportCsvCommand = new AsyncRelayCommand(ct => ExportCsvAsync(ct), CanExport); + ExportHtmlCommand = new AsyncRelayCommand(ct => ExportHtmlAsync(ct), CanExport); } // ── FeatureViewModelBase implementation ───────────────────────────────── @@ -221,9 +261,18 @@ public partial class PermissionsViewModel : FeatureViewModelBase /// Recomputes SimplifiedResults and Summaries from the current Results collection. /// Called when Results changes or when simplified mode is toggled on. /// + private static bool IsSimplifiedModeNoise(PermissionEntry e) + { + if (e.Users.Contains("SharePointHome", StringComparison.OrdinalIgnoreCase)) return true; + if (e.GrantedThrough.Contains("SharePointHome", StringComparison.OrdinalIgnoreCase)) return true; + if (e.UserLogins.Split(';').Any(l => l.Trim().StartsWith("c:0u.c|tenant|", StringComparison.OrdinalIgnoreCase))) return true; + return false; + } + private void RebuildSimplifiedData() { - SimplifiedResults = SimplifiedPermissionEntry.WrapAll(Results); + var forSimplified = FilteredResults.Where(e => !IsSimplifiedModeNoise(e)); + SimplifiedResults = SimplifiedPermissionEntry.WrapAll(forSimplified); Summaries = PermissionSummaryBuilder.Build(SimplifiedResults); } @@ -303,6 +352,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase await dispatcher.InvokeAsync(() => { Results = new ObservableCollection(allEntries); + RebuildFilteredResults(); if (IsSimplifiedMode) RebuildSimplifiedData(); OnPropertyChanged(nameof(ActiveItemsSource)); @@ -311,6 +361,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase else { Results = new ObservableCollection(allEntries); + RebuildFilteredResults(); if (IsSimplifiedMode) RebuildSimplifiedData(); OnPropertyChanged(nameof(ActiveItemsSource)); @@ -384,6 +435,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase { _currentProfile = profile; Results = new ObservableCollection(); + FilteredResults = Array.Empty(); SimplifiedResults = Array.Empty(); Summaries = Array.Empty(); OnPropertyChanged(nameof(ActiveItemsSource)); @@ -404,7 +456,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase private bool CanExport() => Results.Count > 0; - private async Task ExportCsvAsync() + private async Task ExportCsvAsync(CancellationToken ct) { if (_csvExportService == null || Results.Count == 0) return; var dialog = new SaveFileDialog @@ -418,9 +470,9 @@ public partial class PermissionsViewModel : FeatureViewModelBase try { if (IsSimplifiedMode && SimplifiedResults.Count > 0) - await _csvExportService.WriteAsync(SimplifiedResults.ToList(), dialog.FileName, CurrentSplit, CancellationToken.None); + await _csvExportService.WriteAsync(SimplifiedResults.ToList(), dialog.FileName, CurrentSplit, ct); else - await _csvExportService.WriteAsync((IReadOnlyList)Results, dialog.FileName, CurrentSplit, CancellationToken.None); + await _csvExportService.WriteAsync(FilteredResults, dialog.FileName, CurrentSplit, ct); OpenFile(dialog.FileName); } catch (Exception ex) @@ -430,7 +482,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase } } - private async Task ExportHtmlAsync() + private async Task ExportHtmlAsync(CancellationToken ct) { if (_htmlExportService == null || Results.Count == 0) return; var dialog = new SaveFileDialog @@ -458,7 +510,7 @@ public partial class PermissionsViewModel : FeatureViewModelBase // by the site it was observed on, then resolve against that // site's context. Using the root tenant ctx for a group that // lives on a sub-site makes CSOM fail with "Group not found". - var groupsBySite = Results + var groupsBySite = FilteredResults .Where(r => r.PrincipalType == "SharePointGroup") .SelectMany(r => r.Users .Split(';', StringSplitOptions.RemoveEmptyEntries) @@ -488,9 +540,9 @@ public partial class PermissionsViewModel : FeatureViewModelBase Name = _currentProfile.Name }; var ctx = await _sessionManager.GetOrCreateContextAsync( - siteProfile, CancellationToken.None); + siteProfile, ct); var resolved = await _groupResolver.ResolveGroupsAsync( - ctx, _currentProfile.ClientId, distinctNames, CancellationToken.None); + ctx, _currentProfile.ClientId, distinctNames, ct); foreach (var kv in resolved) merged[kv.Key] = kv.Value; } @@ -507,9 +559,9 @@ public partial class PermissionsViewModel : FeatureViewModelBase } if (IsSimplifiedMode && SimplifiedResults.Count > 0) - await _htmlExportService.WriteAsync(SimplifiedResults.ToList(), dialog.FileName, CurrentSplit, CurrentLayout, CancellationToken.None, branding, groupMembers, HideSystemGroupRaw); + await _htmlExportService.WriteAsync(SimplifiedResults.ToList(), dialog.FileName, CurrentSplit, CurrentLayout, ct, branding, groupMembers, HideSystemGroupRaw); else - await _htmlExportService.WriteAsync((IReadOnlyList)Results, dialog.FileName, CurrentSplit, CurrentLayout, CancellationToken.None, branding, groupMembers, HideSystemGroupRaw); + await _htmlExportService.WriteAsync(FilteredResults, dialog.FileName, CurrentSplit, CurrentLayout, ct, branding, groupMembers, HideSystemGroupRaw); OpenFile(dialog.FileName); } catch (Exception ex) diff --git a/SharepointToolbox/Views/Common/InfoButton.xaml b/SharepointToolbox/Views/Common/InfoButton.xaml new file mode 100644 index 0000000..b5ddd02 --- /dev/null +++ b/SharepointToolbox/Views/Common/InfoButton.xaml @@ -0,0 +1,39 @@ + + +