-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1203 lines (1026 loc) · 37.9 KB
/
MainForm.cs
File metadata and controls
1203 lines (1026 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.Json;
namespace FtpSyncApp;
/// <summary>
/// Fenêtre principale : configuration de la synchro, lancement,
/// suivi en temps réel et export des logs.
/// </summary>
public partial class MainForm : Form
{
private CancellationTokenSource? _cts;
private readonly List<LogEntry> _logEntries = new();
private bool _isUpdatingChecks;
public MainForm()
{
InitializeComponent();
InitDefaultExcludes();
InitDefaultStubExtensions();
Load += MainForm_Load;
Shown += MainForm_Shown;
FormClosing += MainForm_FormClosing;
}
#region Journalisation (logs)
/// <summary>
/// Ajoute une ligne dans le journal et dans le ListView correspondant
/// (Infos, Avertissements, Erreurs).
/// </summary>
private void AppendLog(LogEntry entry)
{
_logEntries.Add(entry);
var target = entry.Level switch
{
LogLevel.Info => lvInfos,
LogLevel.Warning => lvWarnings,
LogLevel.Error => lvErrors,
_ => lvInfos
};
var item = new ListViewItem(entry.Timestamp.ToString("HH:mm:ss"));
item.SubItems.Add(entry.Message);
item.SubItems.Add(entry.FilePath ?? string.Empty);
item.SubItems.Add(entry.Action?.ToString() ?? string.Empty);
item.SubItems.Add(entry.Status?.ToString() ?? string.Empty);
// Mise en couleur simple selon le niveau.
switch (entry.Level)
{
case LogLevel.Warning:
item.ForeColor = System.Drawing.Color.DarkOrange;
break;
case LogLevel.Error:
item.ForeColor = System.Drawing.Color.Red;
break;
}
target.Items.Add(item);
target.EnsureVisible(target.Items.Count - 1);
}
/// <summary>
/// Efface les messages de log actuellement affichés.
/// </summary>
private void ClearLogs()
{
_logEntries.Clear();
lvInfos.Items.Clear();
lvWarnings.Items.Clear();
lvErrors.Items.Clear();
}
/// <summary>
/// Active / désactive les boutons principaux en fonction de l'état
/// (exécution en cours ou non).
/// </summary>
private void ToggleButtons(bool enabled)
{
btnSync.Enabled = enabled;
btnDryRun.Enabled = enabled;
btnCancel.Enabled = !enabled;
}
/// <summary>
/// Met à jour la barre de progression globale et le libellé associé.
/// </summary>
private void UpdateProgress(int current, int total)
{
if (total <= 0)
{
total = 1;
}
progressBarOverall.Maximum = total;
progressBarOverall.Value = Math.Min(current, total);
lblProgress.Text = $"{current} / {total}";
}
/// <summary>
/// Ajoute un résumé global de la synchro dans les logs.
/// </summary>
private void ShowSummary(int total, int ok, int failed, int ignored)
{
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Résumé : {ok} ok, {failed} erreurs, {ignored} ignorés sur {total} fichiers."
});
}
#endregion
#region SaveFile
/// <summary>
/// Méthode pour récupérer le chemin du fichier de settings
/// </summary>
private string GetSettingsFilePath()
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var folder = Path.Combine(appData, "FtpSyncApp");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
return Path.Combine(folder, "settings.json");
}
private void MainForm_Load(object? sender, EventArgs e)
{
LoadSettings();
}
private void MainForm_Shown(object? sender, EventArgs e)
{
var lastLocalRoot = txtLocalRoot.Text.Trim();
if (!string.IsNullOrEmpty(lastLocalRoot) && Directory.Exists(lastLocalRoot))
{
var result = MessageBox.Show(
"Voulez-vous charger le dernier dossier local ?",
"Dossier local",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (result == DialogResult.Yes)
{
LoadTreeView(lastLocalRoot);
}
}
}
private void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
SaveSettings();
}
private void LoadSettings()
{
try
{
var path = GetSettingsFilePath();
if (!File.Exists(path))
return;
var json = File.ReadAllText(path);
var settings = JsonSerializer.Deserialize<AppSettings>(json);
if (settings == null)
return;
txtLocalRoot.Text = settings.LocalRoot ?? string.Empty;
txtRemoteRoot.Text = settings.RemoteRoot ?? string.Empty;
txtHost.Text = settings.Host ?? string.Empty;
txtPort.Text = settings.Port > 0 ? settings.Port.ToString() : "22";
txtUsername.Text = settings.Username ?? string.Empty;
// SFTP / FTP
rbSftp.Checked = settings.UseSftp;
rbFtp.Checked = !settings.UseSftp;
// Mot de passe
chkRememberPassword.Checked = settings.RememberPassword;
if (settings.RememberPassword && !string.IsNullOrEmpty(settings.Password))
{
txtPassword.Text = settings.Password;
}
}
catch
{
// En cas de problème (fichier corrompu, etc.), on ignore silencieusement.
// Option : ajouter un log si tu veux.
}
}
private void SaveSettings()
{
try
{
var settings = new AppSettings
{
LocalRoot = txtLocalRoot.Text.Trim(),
RemoteRoot = txtRemoteRoot.Text.Trim(),
Host = txtHost.Text.Trim(),
Username = txtUsername.Text.Trim(),
UseSftp = rbSftp.Checked,
RememberPassword = chkRememberPassword.Checked
};
if (int.TryParse(txtPort.Text, out var p) && p > 0)
{
settings.Port = p;
}
else
{
settings.Port = 22;
}
if (settings.RememberPassword)
{
settings.Password = txtPassword.Text;
}
else
{
settings.Password = null;
}
var path = GetSettingsFilePath();
var json = JsonSerializer.Serialize(settings, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(path, json);
}
catch
{
// Échec de sauvegarde : on ignore (pas bloquant pour l'utilisateur).
// Option : log erreur si tu veux.
}
}
#endregion
#region Gestion du dossier local et arborescence
private void btnBrowseLocal_Click(object sender, EventArgs e)
{
using var dialog = new FolderBrowserDialog
{
ShowNewFolderButton = false
};
if (dialog.ShowDialog(this) == DialogResult.OK)
{
txtLocalRoot.Text = dialog.SelectedPath;
LoadTreeView(dialog.SelectedPath);
}
}
/// <summary>
/// Charge l'arborescence de dossiers dans le TreeView à partir d'une racine.
/// </summary>
private void LoadTreeView(string rootPath)
{
tvFolders.Nodes.Clear();
if (string.IsNullOrWhiteSpace(rootPath) || !Directory.Exists(rootPath))
return;
var root = new TreeNode
{
Tag = rootPath,
Checked = true
};
SetNodeTextWithFileCount(root);
tvFolders.Nodes.Add(root);
LoadSubDirectories(root);
tvFolders.ExpandAll();
}
/// <summary>
/// Ajoute récursivement les sous-dossiers d'un nœud donné.
/// </summary>
private void LoadSubDirectories(TreeNode node)
{
var path = node.Tag as string;
if (string.IsNullOrEmpty(path))
return;
try
{
foreach (var dir in Directory.GetDirectories(path))
{
var child = new TreeNode
{
Tag = dir,
Checked = true
};
SetNodeTextWithFileCount(child);
node.Nodes.Add(child);
LoadSubDirectories(child);
}
}
catch
{
// Dossiers non accessibles : ignorés silencieusement.
}
}
/// <summary>
/// Gestion du (dé)cochage dans le TreeView :
/// - coche d'un parent → coche tous les enfants
/// - coche d'un enfant → remonte la coche vers tous les parents
/// - décochage → applique uniquement sur les descendants
/// </summary>
private void tvFolders_AfterCheck(object sender, TreeViewEventArgs e)
{
if (_isUpdatingChecks)
return;
_isUpdatingChecks = true;
try
{
var isUserAction = e.Action != TreeViewAction.Unknown;
if (!isUserAction)
{
// Changement initié par le code : aucune propagation.
return;
}
if (e.Node.Checked)
{
// Coche descendante + coche de tous les parents.
SetChildrenChecked(e.Node, true);
SetParentsChecked(e.Node);
}
else
{
// Décoche uniquement les descendants.
SetChildrenChecked(e.Node, false);
}
}
finally
{
_isUpdatingChecks = false;
}
}
/// <summary>
/// Coche ou décoche récursivement tous les enfants d'un nœud.
/// </summary>
private void SetChildrenChecked(TreeNode node, bool isChecked)
{
foreach (TreeNode child in node.Nodes)
{
child.Checked = isChecked;
SetChildrenChecked(child, isChecked);
}
}
/// <summary>
/// Coche tous les parents d'un nœud, sans toucher aux autres enfants.
/// </summary>
private void SetParentsChecked(TreeNode node)
{
var parent = node.Parent;
while (parent != null)
{
if (!parent.Checked)
{
parent.Checked = true;
}
parent = parent.Parent;
}
}
/// <summary>
/// Met à jour le texte du nœud avec le nombre de fichiers
/// (en respectant les exclusions).
/// </summary>
private void SetNodeTextWithFileCount(TreeNode node)
{
var path = node.Tag as string;
if (string.IsNullOrEmpty(path))
return;
// Récupère les motifs d'exclusion courants (*.ini, *.txt, etc.).
var patterns = lstExcludes.Items
.Cast<object>()
.Select(o => o?.ToString() ?? string.Empty)
.ToList();
var fileCount = 0;
try
{
foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly))
{
var fileName = Path.GetFileName(file);
if (IsExcluded(fileName, patterns))
continue;
fileCount++;
}
}
catch
{
// Dossier non accessible : on laisse 0.
}
var dirName = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
if (string.IsNullOrEmpty(dirName))
{
dirName = path;
}
node.Text = $"{dirName} ({fileCount})";
}
/// <summary>
/// Recalcule les nombres de fichiers pour tous les nœuds de l'arbre.
/// Appelé notamment lorsqu'on modifie les exclusions.
/// </summary>
private void RefreshAllNodeCounts()
{
foreach (TreeNode node in tvFolders.Nodes)
{
RefreshNodeCountsRecursive(node);
}
}
private void RefreshNodeCountsRecursive(TreeNode node)
{
SetNodeTextWithFileCount(node);
foreach (TreeNode child in node.Nodes)
{
RefreshNodeCountsRecursive(child);
}
}
#endregion
#region Exclusions de fichiers / Stubs
/// <summary>
/// Initialise les motifs d'exclusion par défaut (*.ini, *.txt).
/// </summary>
private void InitDefaultExcludes()
{
var defaults = new[] { "*.ini", "*.txt" };
foreach (var pattern in defaults)
{
if (!lstExcludes.Items.Contains(pattern))
{
lstExcludes.Items.Add(pattern);
}
}
}
/// <summary>
/// Initialise les extensions stub par défaut (.mp4, .ts) utilisées
/// pour la création de fichiers distants vides (Bunny.net).
/// </summary>
private void InitDefaultStubExtensions()
{
var defaults = new[] { ".mp4", ".ts" };
foreach (var ext in defaults)
{
if (!lstStubExtensions.Items.Contains(ext))
{
lstStubExtensions.Items.Add(ext);
}
}
chkUseStubs.Checked = true;
}
private void btnAddExclude_Click(object sender, EventArgs e)
{
var pattern = txtNewExclude.Text.Trim();
if (pattern.Length == 0)
return;
if (!lstExcludes.Items.Contains(pattern))
{
lstExcludes.Items.Add(pattern);
RefreshAllNodeCounts();
}
txtNewExclude.Clear();
}
private void btnRemoveExclude_Click(object sender, EventArgs e)
{
var selected = lstExcludes.SelectedItem;
if (selected != null)
{
lstExcludes.Items.Remove(selected);
RefreshAllNodeCounts();
}
}
#endregion
#region Construction de la configuration
/// <summary>
/// Construit un objet <see cref="SyncConfig"/> à partir de l'état de l'UI.
/// </summary>
private SyncConfig BuildConfigFromUI()
{
var config = new SyncConfig
{
LocalRoot = txtLocalRoot.Text.Trim(),
RemoteRoot = txtRemoteRoot.Text.Trim(),
Host = txtHost.Text.Trim(),
Port = int.TryParse(txtPort.Text, out var p) ? p : 22,
Username = txtUsername.Text.Trim(),
Password = txtPassword.Text,
UseSftp = rbSftp.Checked,
DeleteRemoteOrphans = true
};
foreach (var item in lstExcludes.Items)
{
config.ExcludedPatterns.Add(item?.ToString() ?? string.Empty);
}
// Stubs Bunny : extensions + activation
config.UseStubForExtensions = chkUseStubs.Checked;
foreach (var item in lstStubExtensions.Items)
{
config.StubExtensions.Add(item?.ToString() ?? string.Empty);
}
// Récupération des sous-dossiers cochés (chemins relatifs).
foreach (TreeNode node in tvFolders.Nodes)
{
CollectCheckedFolders(node, config);
}
return config;
}
private void CollectCheckedFolders(TreeNode node, SyncConfig config)
{
var fullPath = node.Tag as string;
if (node.Checked &&
!string.IsNullOrEmpty(fullPath) &&
Directory.Exists(fullPath) &&
!string.Equals(fullPath, config.LocalRoot, StringComparison.OrdinalIgnoreCase))
{
var rel = Path.GetRelativePath(config.LocalRoot, fullPath);
config.SelectedSubfolders.Add(rel);
}
foreach (TreeNode child in node.Nodes)
{
CollectCheckedFolders(child, config);
}
}
#endregion
#region Lancement de la synchronisation / simulation
/// <summary>
/// Lance une synchronisation complète (ou simulation) en asynchrone.
/// </summary>
private async Task StartSyncAsync(bool dryRun)
{
ToggleButtons(false);
ClearLogs();
_cts = new CancellationTokenSource();
try
{
var config = BuildConfigFromUI();
if (string.IsNullOrWhiteSpace(config.LocalRoot) || !Directory.Exists(config.LocalRoot))
{
AppendLog(new LogEntry
{
Level = LogLevel.Error,
Message = "Dossier local invalide."
});
return;
}
if (string.IsNullOrWhiteSpace(config.RemoteRoot))
{
AppendLog(new LogEntry
{
Level = LogLevel.Error,
Message = "Dossier distant vide."
});
return;
}
// Normalisation du chemin distant.
config.RemoteRoot = NormalizeRemote(config.RemoteRoot);
AppendLog(new LogEntry { Level = LogLevel.Info, Message = "Connexion au serveur..." });
using IRemoteClient client = new SftpClientWrapper(
config.Host,
config.Port,
config.Username,
config.Password);
await client.ConnectAsync();
AppendLog(new LogEntry { Level = LogLevel.Info, Message = "Connecté." });
// 1) Scan local.
var localFiles = ScanLocalFiles(config);
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Fichiers locaux trouvés : {localFiles.Count}"
});
// 2) Scan distant.
var remoteMap = await client.ListFilesRecursiveAsync(config.RemoteRoot, _cts.Token);
var remoteFiles = BuildRemoteRelativeMap(config.RemoteRoot, remoteMap);
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Fichiers distants trouvés : {remoteFiles.Count}"
});
// 3) Construction du plan d'actions.
var plan = BuildSyncPlan(config, localFiles, remoteFiles);
var total = plan.Count;
var current = 0;
var ok = 0;
var failed = 0;
var ignored = 0;
var sequentialErrors = 0;
foreach (var item in plan)
{
_cts.Token.ThrowIfCancellationRequested();
current++;
UpdateProgress(current, total);
// Alerte fichier volumineux.
if (item.LocalSize > 0 && item.LocalSize >= config.LargeFileWarningBytes)
{
AppendLog(new LogEntry
{
Level = LogLevel.Warning,
Message = $"Fichier volumineux (>500Mo) : {item.LocalFullPath}",
FilePath = item.LocalFullPath,
Action = item.Action,
Status = SyncStatus.Pending
});
}
if (dryRun)
{
ignored++;
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"[SIMU] {item.Action} : {item.RelativePath}",
FilePath = item.LocalFullPath ?? item.RemoteFullPath,
Action = item.Action,
Status = SyncStatus.Ignored
});
continue;
}
try
{
switch (item.Action)
{
case SyncAction.UploadNew:
case SyncAction.UploadUpdate:
{
var dir = Path.GetDirectoryName(item.RemoteFullPath) ?? "/";
dir = NormalizeRemote(dir);
await client.EnsureDirectoryAsync(dir, _cts.Token);
if (item.IsStub && config.UseStubForExtensions)
{
// Fichier traité en mode "stub" : on crée un fichier distant vide
await client.CreateEmptyFileAsync(item.RemoteFullPath, _cts.Token);
item.Status = SyncStatus.Success;
ok++;
sequentialErrors = 0;
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Stub créé (fichier vide) : {item.RelativePath}",
FilePath = item.RemoteFullPath,
Action = item.Action,
Status = item.Status
});
}
else
{
// Comportement normal : upload du fichier local
await client.UploadFileAsync(item.LocalFullPath!, item.RemoteFullPath, _cts.Token);
item.Status = SyncStatus.Success;
ok++;
sequentialErrors = 0;
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"{item.Action} : {item.RelativePath}",
FilePath = item.LocalFullPath,
Action = item.Action,
Status = item.Status
});
}
break;
}
case SyncAction.DeleteRemote:
{
await client.DeleteFileAsync(item.RemoteFullPath, _cts.Token);
item.Status = SyncStatus.Success;
ok++;
sequentialErrors = 0;
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Supprimé sur serveur : {item.RelativePath}",
FilePath = item.RemoteFullPath,
Action = item.Action,
Status = item.Status
});
break;
}
case SyncAction.Skip:
{
item.Status = SyncStatus.Ignored;
ignored++;
AppendLog(new LogEntry
{
Level = LogLevel.Info,
Message = $"Ignoré (identique) : {item.RelativePath}",
FilePath = item.LocalFullPath,
Action = item.Action,
Status = item.Status
});
break;
}
}
}
catch (Exception ex)
{
item.Status = SyncStatus.Failed;
failed++;
sequentialErrors++;
AppendLog(new LogEntry
{
Level = LogLevel.Error,
Message = $"Erreur sur {item.RelativePath} : {ex.Message}",
FilePath = item.LocalFullPath ?? item.RemoteFullPath,
Action = item.Action,
Status = item.Status
});
if (sequentialErrors >= config.MaxSequentialErrors)
{
AppendLog(new LogEntry
{
Level = LogLevel.Error,
Message = $"Arrêt : {sequentialErrors} erreurs consécutives."
});
break;
}
}
}
ShowSummary(total, ok, failed, ignored);
}
catch (OperationCanceledException)
{
AppendLog(new LogEntry
{
Level = LogLevel.Warning,
Message = "Synchronisation annulée."
});
}
catch (Exception ex)
{
AppendLog(new LogEntry
{
Level = LogLevel.Error,
Message = "Erreur critique : " + ex.Message
});
}
finally
{
ToggleButtons(true);
}
}
private static string NormalizeRemote(string path)
{
if (string.IsNullOrWhiteSpace(path))
return "/";
var p = path.Replace('\\', '/').Trim();
if (!p.StartsWith("/"))
p = "/" + p;
return p.TrimEnd('/');
}
/// <summary>
/// Scan local basé sur l'état réel des coches dans le TreeView.
/// </summary>
private Dictionary<string, (string FullPath, long Size, DateTime LastWriteUtc)>
ScanLocalFiles(SyncConfig config)
{
var result = new Dictionary<string, (string, long, DateTime)>(StringComparer.OrdinalIgnoreCase);
foreach (TreeNode node in tvFolders.Nodes)
{
ScanNodeFiles(node, config, result);
}
return result;
}
/// <summary>
/// Parcourt un nœud du TreeView :
/// - si le dossier est coché → fichiers directs uniquement
/// - les enfants sont toujours inspectés, chacun décidant via sa propre coche.
/// </summary>
private void ScanNodeFiles(
TreeNode node,
SyncConfig config,
Dictionary<string, (string FullPath, long Size, DateTime LastWriteUtc)> result)
{
var path = node.Tag as string;
if (node.Checked &&
!string.IsNullOrEmpty(path) &&
Directory.Exists(path))
{
foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly))
{
var fileName = Path.GetFileName(file);
if (IsExcluded(fileName, config.ExcludedPatterns))
continue;
try
{
var info = new FileInfo(file);
var relFromRoot = Path.GetRelativePath(config.LocalRoot, file);
var relNorm = relFromRoot.Replace('\\', '/');
result[relNorm] = (file, info.Length, info.LastWriteTimeUtc);
}
catch
{
// Fichier illisible : ignoré.
}
}
}
foreach (TreeNode child in node.Nodes)
{
ScanNodeFiles(child, config, result);
}
}
/// <summary>
/// Retourne true si le fichier doit être exclu selon les patterns fournis.
/// </summary>
private bool IsExcluded(string fileName, List<string> patterns)
{
foreach (var raw in patterns)
{
var pattern = raw.Trim();
if (pattern.Length == 0)
continue;
// Gestion simple des motifs du type "*.ext".
if (pattern.StartsWith("*.", StringComparison.Ordinal))
{
var ext = pattern[1..]; // ex : ".ini"
if (fileName.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
return true;
}
else if (string.Equals(pattern, fileName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Indique si un fichier doit être traité en "stub" (création de fichier distant vide)
/// en fonction des extensions configurées dans <see cref="SyncConfig.StubExtensions"/>.
/// </summary>
private bool IsStubFile(string? fullPath, SyncConfig config)
{
if (!config.UseStubForExtensions)
return false;
if (string.IsNullOrEmpty(fullPath))
return false;
var ext = Path.GetExtension(fullPath);
if (string.IsNullOrEmpty(ext))
return false;
ext = ext.ToLowerInvariant();
foreach (var raw in config.StubExtensions)
{
var pattern = raw?.Trim();
if (string.IsNullOrEmpty(pattern))
continue;
var normalized = pattern.ToLowerInvariant();
// Supporte ".mp4", "mp4", "*.mp4"
if (normalized.StartsWith("*."))
{
normalized = normalized[1..]; // ".mp4"
}
else if (!normalized.StartsWith("."))
{
normalized = "." + normalized; // "mp4" -> ".mp4"
}
if (ext == normalized)
return true;
}
return false;
}
/// <summary>
/// Construit une map "chemin relatif → info distante" à partir des chemins absolus.
/// </summary>
private Dictionary<string, RemoteFileInfo> BuildRemoteRelativeMap(
string remoteRoot,
IDictionary<string, RemoteFileInfo> fullMap)
{
var result = new Dictionary<string, RemoteFileInfo>(StringComparer.OrdinalIgnoreCase);
var root = NormalizeRemote(remoteRoot);
foreach (var (full, info) in fullMap)
{
if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase))
continue;
var rel = full.Substring(root.Length).TrimStart('/');
var relNorm = rel.Replace('\\', '/');
result[relNorm] = info;
}
return result;
}
/// <summary>
/// Construit la liste des actions à effectuer pour aligner le serveur sur le local.