using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Windows.Input; using System.Windows.Threading; using Titano.Core.Diagnostics; using Titano.Core.Localization; using Titano.Ui.Controls; using Titano.Ui.Mvvm; using Titano.Uploader.Infrastructure; using Titano.Uploader.Server; using Titano.Uploader.Sources; using Titano.Uploader.Text; using Titano.Uploader.Uploads; using Titano.Uploader.Watching; namespace Titano.Uploader.Shell; /// A sequence offered as upload target. public sealed record SequenceOption(Guid Id, string Title); /// Everything the window works with; the capture mode passes design-time implementations. public sealed record UploaderServices( UploaderSettings Settings, Action SaveSettings, IServerSession Session, UploadQueue Queue, IUploadEngine Engine, IStartupRegistration Startup, IUploaderDialogs Dialogs, WatchFolderService Watch, ProcessedFileMemory Memory, string LogDirectory); /// State of the uploader window (BRIEF §15, mockup Uploader.html). public sealed class MainViewModel : LocalizedViewModel { private readonly UploaderServices _s; private readonly DispatcherTimer _refresh; private UploadTargetMode _target; private SequenceOption? _selectedSequence; private bool _loadingSequences; private string _newTitle; private bool _isSettingsOpen; private bool _startWithWindows; private string _queueText = string.Empty; private string _progressText = string.Empty; private string? _currentFileText; private double _progress; private UploadItem? _currentItem; public MainViewModel(UploaderServices services) { _s = services; _target = services.Settings.Target; _newTitle = services.Settings.NewSequenceTitle ?? string.Empty; _startWithWindows = services.Startup.IsEnabled; Connect = new ConnectViewModel(services.Session, services.Dialogs, services.Settings.ServerUrl, services.Settings.Username); foreach (var w in services.Settings.WatchFolders) WatchFolders.Add(NewWatchFolder(w.Path, w.IntervalSeconds)); OpenSettingsCommand = new RelayCommand(() => IsSettingsOpen = true); CloseSettingsCommand = new RelayCommand(() => IsSettingsOpen = false); SignOutCommand = new AsyncRelayCommand(SignOutAsync); BrowseFilesCommand = new AsyncRelayCommand(() => EnqueueAsync(_s.Dialogs.PickFiles())); BrowseFolderCommand = new AsyncRelayCommand(() => _s.Dialogs.PickFolder() is { } folder ? EnqueueAsync([folder]) : Task.CompletedTask); RefreshSequencesCommand = new AsyncRelayCommand(LoadSequencesAsync); PauseCommand = new RelayCommand(TogglePause, () => HasItems); StopCommand = new RelayCommand(() => _s.Engine.StopAndClear(), () => HasItems); RetryItemCommand = new RelayCommand(p => { if (p is UploadItem item) _s.Engine.Retry(item); }); AddWatchFolderCommand = new RelayCommand(AddWatchFolder); ToggleDeleteAfterUploadCommand = new RelayCommand(ToggleDeleteAfterUpload); _s.Session.PropertyChanged += OnSessionChanged; _s.Session.SessionEnded += OnSessionEnded; _s.Engine.PropertyChanged += (_, _) => RefreshQueue(); _s.Engine.Drained += OnDrained; _s.Queue.Items.CollectionChanged += (_, _) => { OnPropertyChanged(nameof(HasItems)); CommandManager.InvalidateRequerySuggested(); }; _refresh = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(500) }; _refresh.Tick += (_, _) => RefreshQueue(); RefreshQueue(); } /// Raised when the queue finished while work was done, with the number of files the server confirmed. public event Action? UploadsCompleted; public ConnectViewModel Connect { get; } /// In-window notifications; the window forwards them to its . public ObservableCollection PendingToasts { get; } = []; public ICommand OpenSettingsCommand { get; } public ICommand CloseSettingsCommand { get; } public ICommand SignOutCommand { get; } public ICommand BrowseFilesCommand { get; } public ICommand BrowseFolderCommand { get; } public ICommand RefreshSequencesCommand { get; } public ICommand PauseCommand { get; } public ICommand StopCommand { get; } public ICommand RetryItemCommand { get; } public ICommand AddWatchFolderCommand { get; } public ICommand ToggleDeleteAfterUploadCommand { get; } // ---------------- Header ---------------- public string ServerText => _s.Session.State == ConnectionState.NotConfigured ? Loc.L("Uploader.Header.NotConnected") : ConnectViewModel.Display(_s.Session.Address); public string? UserText => _s.Session.State is ConnectionState.Connected or ConnectionState.Offline or ConnectionState.SigningIn ? _s.Session.Username : null; public StatusKind ConnectionKind => _s.Session.State switch { ConnectionState.Connected => StatusKind.Online, ConnectionState.SigningIn => StatusKind.Running, _ => StatusKind.Offline, }; /// Null on first run, when the server line already says "Not connected". public string? ConnectionText => _s.Session.State switch { ConnectionState.Connected => Loc.L("Uploader.Status.Connected"), ConnectionState.SigningIn => Loc.L("Uploader.Status.SigningIn"), ConnectionState.Offline => Loc.L("Uploader.Status.Offline"), ConnectionState.SignedOut => Loc.L("Uploader.Status.SignedOut"), _ => null, }; /// "1.9 TB free of 5 TB"; null without a quota. public string? QuotaText => _s.Session.State == ConnectionState.Connected && _s.Session.QuotaBytes > 0 ? Loc.L("Uploader.Header.Quota", UploaderText.Bytes(Math.Max(0, _s.Session.QuotaBytes - _s.Session.UsedBytes), Loc.Culture), UploaderText.Bytes(_s.Session.QuotaBytes, Loc.Culture)) : null; /// The sign-in form replaces the queue on first run and after signing out. public bool IsConnectVisible => _s.Session.State is ConnectionState.NotConfigured or ConnectionState.SignedOut; public bool IsSettingsOpen { get => _isSettingsOpen; set => Set(ref _isSettingsOpen, value); } // ---------------- Target ---------------- public bool IsSessionsTarget { get => _target == UploadTargetMode.Sessions; set => SetTarget(value, UploadTargetMode.Sessions); } public bool IsSequenceTarget { get => _target == UploadTargetMode.Sequence; set => SetTarget(value, UploadTargetMode.Sequence); } public bool IsNewTarget { get => _target == UploadTargetMode.NewSequence; set => SetTarget(value, UploadTargetMode.NewSequence); } public ObservableCollection Sequences { get; } = []; public SequenceOption? SelectedSequence { get => _selectedSequence; set { if (_loadingSequences || !Set(ref _selectedSequence, value)) return; _s.Settings.TargetSequenceId = value?.Id; _s.SaveSettings(); } } public string NewTitle { get => _newTitle; set { if (!Set(ref _newTitle, value)) return; _s.Settings.NewSequenceTitle = value; _s.SaveSettings(); } } // ---------------- Queue ---------------- public ObservableCollection Items => _s.Queue.Items; public bool HasItems => _s.Queue.Items.Count > 0; /// "4,812 files · 96.2 GB · 38 MB/s · 41 min left". public string QueueText { get => _queueText; private set => Set(ref _queueText, value); } /// "2,214 of 4,812 sent · 2,201 verified by the server · 0 retries". public string ProgressText { get => _progressText; private set => Set(ref _progressText, value); } public string? CurrentFileText { get => _currentFileText; private set => Set(ref _currentFileText, value); } public double Progress { get => _progress; private set => Set(ref _progress, value); } /// The item being uploaded; the list keeps it in view. public UploadItem? CurrentItem { get => _currentItem; private set => Set(ref _currentItem, value); } public bool IsPaused => _s.Queue.IsPaused; public string PauseToolTip => Loc.L(IsPaused ? "Tooltips.Uploader.Resume" : "Tooltips.Uploader.Pause"); /// Accessible name of the pause/resume button (also the tray menu entry). public string PauseLabel => Loc.L(IsPaused ? "Uploader.Action.Resume" : "Uploader.Action.Pause"); /// Upload limit in MB/s as typed; 0 = unlimited. Text that is not a whole number reverts. public string BandwidthLimitText { get => _s.Session.BandwidthLimit.ToString(Loc.Culture); set { if (int.TryParse(value, NumberStyles.Integer, Loc.Culture, out var limit)) { limit = Math.Clamp(limit, 0, 100_000); if (limit != _s.Session.BandwidthLimit) { _s.Session.BandwidthLimit = limit; _s.Settings.BandwidthLimit = limit; _s.SaveSettings(); } } OnPropertyChanged(); } } /// Tray hover text. public string TrayText => Loc.L("Uploader.App.Title") + (HasItems ? " · " + QueueText : string.Empty); // ---------------- Watch folders ---------------- public ObservableCollection WatchFolders { get; } = []; // ---------------- Options ---------------- /// Turned on only through , which asks first. public bool DeleteAfterUpload => _s.Settings.DeleteAfterUpload; public bool StartWithWindows { get => _startWithWindows; set { _s.Startup.SetEnabled(value); // Read back: the registry may refuse the change. _startWithWindows = _s.Startup.IsEnabled; OnPropertyChanged(); } } public bool MinimizeToTray { get => _s.Settings.MinimizeToTray; set { if (_s.Settings.MinimizeToTray == value) return; _s.Settings.MinimizeToTray = value; _s.SaveSettings(); OnPropertyChanged(); } } // ---------------- Actions ---------------- /// Starts the periodic refresh and, when signed in, loads the sequence list. public void Start() { _refresh.Start(); if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync(); } /// Starts watching every configured folder. public void StartWatching() { foreach (var w in WatchFolders) _s.Watch.Watch(w.Path, TimeSpan.FromSeconds(w.IntervalSeconds)); } /// Adds the photos under (files, folders, card roots) to the queue. public async Task EnqueueAsync(IReadOnlyList paths) { if (paths.Count == 0) return; if (_target == UploadTargetMode.Sequence && SelectedSequence is null) { ShowToast(Loc.L("Uploader.Toast.ChooseSequence")); return; } var found = await Task.Run(() => PhotoScanner.Scan(paths)); var fresh = found.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList(); if (fresh.Count == 0) { ShowToast(Loc.L("Uploader.Toast.NothingFound")); return; } var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = _target, SequenceId = _target == UploadTargetMode.Sequence ? SelectedSequence?.Id : null, Title = _target == UploadTargetMode.NewSequence ? NewTitle.Trim() : null, }; var entries = _target == UploadTargetMode.Sessions ? SessionEntries(fresh, null, null, out _) : [.. fresh.OrderBy(f => f.CapturedAt).Select(f => new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, null, null))]; var added = Add(batch, entries); Log.Info("queue", $"{added} file(s) added from {paths.Count} path(s), target {_target}"); ShowToast(Loc.Plural("Uploader.Toast.Added", added)); } /// Queues stable new photos of a watch folder; they join the folder's last session when close in time. public void OnWatchFilesReady(string root, IReadOnlyList files) { var fresh = files.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList(); if (fresh.Count == 0) return; var entries = SessionEntries(fresh, root, _s.Memory.GetSession(root), out var last); Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, entries); _s.Memory.SetSession(root, last); } public void OnWatchAvailabilityChanged(string root, bool available) { var folder = WatchFolders.FirstOrDefault(w => string.Equals(w.Path, root, StringComparison.OrdinalIgnoreCase)); if (folder is not null) folder.IsAvailable = available; } /// Errors are one sentence plus one action (BRIEF §0.2 rule 6). public void ReportError(Exception ex) { Log.Error("ui", "Operation failed", ex); ShowToast(Loc.L("Errors.Unexpected"), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"), new RelayCommand(OpenLogs)); } public void TogglePause() { if (_s.Queue.IsPaused) _s.Engine.Resume(); else _s.Engine.Pause(); RefreshQueue(); } public override void Dispose() { _refresh.Stop(); _s.Session.PropertyChanged -= OnSessionChanged; _s.Session.SessionEnded -= OnSessionEnded; _s.Engine.Drained -= OnDrained; base.Dispose(); } private int Add(UploadBatch batch, IReadOnlyList entries) { // A new batch after a finished one starts a fresh count. if (!_s.Queue.HasPending) _s.Queue.RemoveCompleted(); var added = _s.Queue.Add(batch, entries); _s.Engine.Pump(); RefreshQueue(); return added; } /// Session keys per source folder (BRIEF §13 rules), entries in capture order. private static List SessionEntries(IReadOnlyList files, string? watchRoot, SessionContinuation? previous, out SessionContinuation? last) { var entries = new List(files.Count); last = previous; foreach (var group in files.GroupBy(f => watchRoot ?? f.Root, StringComparer.OrdinalIgnoreCase)) { var ordered = group.OrderBy(f => f.CapturedAt).ToList(); var assignment = SessionGrouper.Assign([.. ordered.Select(f => f.CapturedAt)], SessionGrouper.SourceTag(group.Key), watchRoot is null ? null : previous); for (var i = 0; i < ordered.Count; i++) { var f = ordered[i]; entries.Add(new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, assignment.Keys[i], watchRoot)); } last = assignment.Last; } return entries; } /// Recomputes the queue line, progress and current file (also every 500 ms once started). public void RefreshQueue() { var summary = QueueSummary.From(_s.Queue.Items); var rate = _s.Engine.BytesPerSecond; var activity = summary.Files == 0 ? QueueActivity.Idle : _s.Engine.Status switch { EngineStatus.Paused => QueueActivity.Paused, EngineStatus.WaitingForServer => QueueActivity.WaitingForServer, EngineStatus.Running => QueueActivity.Running, _ => QueueActivity.Done, }; QueueText = UploaderText.QueueLine(summary, activity, rate, RateMeter.TimeLeft(summary.RemainingBytes, rate), Loc.Culture); ProgressText = summary.Files == 0 ? string.Empty : UploaderText.ProgressLine(summary, Loc.Culture); Progress = summary.Progress; CurrentFileText = summary.CurrentFile; CurrentItem = _s.Queue.Items.FirstOrDefault(i => i.State == UploadItemState.Uploading) ?? _s.Queue.Items.FirstOrDefault(i => i.IsActive); OnPropertyChanged(nameof(IsPaused)); OnPropertyChanged(nameof(PauseToolTip)); OnPropertyChanged(nameof(PauseLabel)); OnPropertyChanged(nameof(TrayText)); } private void SetTarget(bool selected, UploadTargetMode mode) { if (!selected || _target == mode) return; _target = mode; _s.Settings.Target = mode; _s.SaveSettings(); OnPropertyChanged(nameof(IsSessionsTarget)); OnPropertyChanged(nameof(IsSequenceTarget)); OnPropertyChanged(nameof(IsNewTarget)); if (mode == UploadTargetMode.Sequence && Sequences.Count == 0) _ = LoadSequencesAsync(); } private async Task LoadSequencesAsync() { var list = await _s.Session.ListSequencesAsync(CancellationToken.None); if (list.Count == 0 && Sequences.Count > 0) return; _loadingSequences = true; try { Sequences.Clear(); foreach (var s in list.OrderBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase)) Sequences.Add(new SequenceOption(s.Id, s.DisplayTitle)); } finally { _loadingSequences = false; } _selectedSequence = Sequences.FirstOrDefault(s => s.Id == _s.Settings.TargetSequenceId); OnPropertyChanged(nameof(SelectedSequence)); } private async Task SignOutAsync() { IsSettingsOpen = false; await _s.Session.SignOutAsync(); } private void ToggleDeleteAfterUpload() { var enable = !_s.Settings.DeleteAfterUpload; if (enable && !_s.Dialogs.ConfirmDeleteAfterUpload()) { // The check box toggled itself; put it back. OnPropertyChanged(nameof(DeleteAfterUpload)); return; } _s.Settings.DeleteAfterUpload = enable; _s.SaveSettings(); Log.Info("settings", "Delete after verified upload " + (enable ? "on" : "off")); OnPropertyChanged(nameof(DeleteAfterUpload)); } private void AddWatchFolder() { if (_s.Dialogs.PickWatchFolder() is not { } path) return; if (WatchFolders.Any(w => string.Equals(w.Path, path, StringComparison.OrdinalIgnoreCase))) return; var interval = (int)WatchFolderService.DefaultInterval(path).TotalSeconds; _s.Settings.WatchFolders.Add(new UploaderSettings.WatchFolderSettings { Path = path, IntervalSeconds = interval }); _s.SaveSettings(); WatchFolders.Add(NewWatchFolder(path, interval)); _s.Watch.Watch(path, TimeSpan.FromSeconds(interval)); } private WatchFolderViewModel NewWatchFolder(string path, int intervalSeconds) => new(path, intervalSeconds, WatchFolderService.IsNetworkPath(path), SetWatchInterval, RemoveWatchFolder); private void SetWatchInterval(WatchFolderViewModel folder, int seconds) { folder.IntervalSeconds = seconds; foreach (var w in _s.Settings.WatchFolders.Where(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase))) w.IntervalSeconds = seconds; _s.SaveSettings(); _s.Watch.Watch(folder.Path, TimeSpan.FromSeconds(seconds)); } private void RemoveWatchFolder(WatchFolderViewModel folder) { _s.Watch.Stop(folder.Path); _s.Memory.RemoveFolder(folder.Path); _s.Settings.WatchFolders.RemoveAll(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase)); _s.SaveSettings(); WatchFolders.Remove(folder); } private void OnSessionChanged(object? sender, PropertyChangedEventArgs e) { OnPropertyChanged(nameof(ServerText)); OnPropertyChanged(nameof(UserText)); OnPropertyChanged(nameof(ConnectionKind)); OnPropertyChanged(nameof(ConnectionText)); OnPropertyChanged(nameof(QuotaText)); OnPropertyChanged(nameof(IsConnectVisible)); OnPropertyChanged(nameof(BandwidthLimitText)); if (e.PropertyName != nameof(IServerSession.State)) return; if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync(); if (IsConnectVisible) { Connect.Address = ConnectViewModel.Display(_s.Session.Address); Connect.Username = _s.Session.Username ?? Connect.Username; } CommandManager.InvalidateRequerySuggested(); } private void OnSessionEnded(object? sender, ServerProblem problem) => ShowToast(Loc.L(problem == ServerProblem.CertificateChanged ? "Uploader.Toast.CertificateChanged" : "Uploader.Toast.SignedOut")); private void OnDrained(object? sender, EventArgs e) { // The queue restarts its count with each new batch, so every confirmed item belongs to this run. var confirmed = _s.Queue.Items.Count(i => i.IsDone); RefreshQueue(); _ = _s.Session.RefreshAsync(); if (confirmed > 0) UploadsCompleted?.Invoke(confirmed); } private void ShowToast(string title, string? actionText = null, string? actionToolTip = null, ICommand? action = null) => PendingToasts.Add(new Toast { Title = title, ActionText = actionText, ActionToolTip = actionToolTip, ActionCommand = action }); private void OpenLogs() { if (Directory.Exists(_s.LogDirectory)) Process.Start(new ProcessStartInfo(_s.LogDirectory) { UseShellExecute = true, Verb = "explore" }); } }