-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReviewViewModel.cs
More file actions
367 lines (312 loc) · 12.9 KB
/
ReviewViewModel.cs
File metadata and controls
367 lines (312 loc) · 12.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
using Playnite.SDK;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
namespace GameSnapPlugin
{
public class UnmatchedFileItem
{
public string FilePath { get; set; } = "";
public string FileName { get; set; } = "";
public string DateText { get; set; } = "";
}
public class ReviewViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string? name = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
private readonly IPlayniteAPI _playniteApi;
private readonly GameSnapSettings _settings;
private readonly DictionaryService _dictionary;
private readonly OrganizerService _organizer;
private readonly GameSnapLogger _logger;
// ── Collections ──
public ObservableCollection<UnmatchedFileItem> UnmatchedFiles { get; } = new();
private List<Game> _allGames = new();
private ObservableCollection<Game> _filteredGames = new();
public ObservableCollection<Game> FilteredGames
{
get => _filteredGames;
set { _filteredGames = value; OnPropertyChanged(); }
}
// ── Selected file ──
private UnmatchedFileItem? _selectedFile;
public UnmatchedFileItem? SelectedFile
{
get => _selectedFile;
set
{
_selectedFile = value;
OnPropertyChanged();
LoadPreview(value?.FilePath);
OnPropertyChanged(nameof(PreviewInfoVisibility));
OnPropertyChanged(nameof(NoPreviewVisibility));
OnPropertyChanged(nameof(PreviewInfo));
OnPropertyChanged(nameof(StatusText));
}
}
// ── Selected game ──
private Game? _selectedGame;
public Game? SelectedGame
{
get => _selectedGame;
set { _selectedGame = value; OnPropertyChanged(); }
}
// ── Preview ──
private BitmapImage? _previewImage;
public BitmapImage? PreviewImage
{
get => _previewImage;
set { _previewImage = value; OnPropertyChanged(); }
}
public Visibility NoPreviewVisibility => PreviewImage == null ? Visibility.Visible : Visibility.Collapsed;
public Visibility PreviewInfoVisibility => PreviewImage != null ? Visibility.Visible : Visibility.Collapsed;
public string PreviewInfo => _selectedFile != null
? $"{_selectedFile.FileName} • {_selectedFile.DateText}"
: "";
// ── Filter ──
private string _gameFilter = "";
public string GameFilter
{
get => _gameFilter;
set
{
_gameFilter = value;
OnPropertyChanged();
ApplyFilter();
OnPropertyChanged(nameof(PlaceholderVisibility));
}
}
public Visibility PlaceholderVisibility =>
string.IsNullOrEmpty(_gameFilter) ? Visibility.Visible : Visibility.Collapsed;
// ── Status ──
public string StatusText =>
$"{UnmatchedFiles.Count} file(s) pending" +
(_selectedFile != null ? $" • {_selectedFile.FileName}" : "");
// ── Commands ──
public ICommand AssignCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand SkipCommand { get; }
public ICommand CloseCommand { get; }
private Action? _closeAction;
public ReviewViewModel(
IPlayniteAPI playniteApi,
GameSnapSettings settings,
DictionaryService dictionary,
OrganizerService organizer,
GameSnapLogger logger)
{
_playniteApi = playniteApi;
_settings = settings;
_dictionary = dictionary;
_organizer = organizer;
_logger = logger;
AssignCommand = new RelayCommand(Assign);
DeleteCommand = new RelayCommand(Delete);
SkipCommand = new RelayCommand(Skip);
CloseCommand = new RelayCommand(() => _closeAction?.Invoke());
LoadUnmatchedFiles();
LoadGames();
}
public void SetCloseAction(Action action) => _closeAction = action;
// ──────────────────────────────────────────────
// Load
// ──────────────────────────────────────────────
private void LoadUnmatchedFiles()
{
UnmatchedFiles.Clear();
if (string.IsNullOrEmpty(_settings.DestinationBase)) return;
var unmatchedDir = Path.Combine(
_settings.DestinationBase,
_settings.UnmatchedFolderName);
if (!Directory.Exists(unmatchedDir)) return;
var allExts = _settings.ImageExtensions
.Concat(_settings.VideoExtensions)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in Directory.GetFiles(unmatchedDir)
.Where(f => allExts.Contains(Path.GetExtension(f).ToLowerInvariant()))
.OrderByDescending(f => new FileInfo(f).LastWriteTime))
{
var info = new FileInfo(file);
UnmatchedFiles.Add(new UnmatchedFileItem
{
FilePath = file,
FileName = info.Name,
DateText = info.LastWriteTime.ToString("yyyy-MM-dd HH:mm")
});
}
OnPropertyChanged(nameof(StatusText));
}
private void LoadGames()
{
_allGames = _playniteApi.Database.Games
.OrderBy(g => g.Name)
.ToList();
ApplyFilter();
}
private void ApplyFilter()
{
var filter = _gameFilter.Trim();
var filtered = string.IsNullOrEmpty(filter)
? _allGames
: _allGames.Where(g =>
g.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
FilteredGames = new ObservableCollection<Game>(filtered);
}
// ──────────────────────────────────────────────
// Preview
// ──────────────────────────────────────────────
private void LoadPreview(string? filePath)
{
if (filePath == null || !File.Exists(filePath))
{
PreviewImage = null;
return;
}
var ext = Path.GetExtension(filePath).ToLowerInvariant();
if (!_settings.ImageExtensions.Contains(ext))
{
PreviewImage = null;
return;
}
try
{
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = new Uri(filePath);
img.DecodePixelWidth = 900; // limita RAM
img.EndInit();
img.Freeze();
PreviewImage = img;
}
catch
{
PreviewImage = null;
}
}
// ──────────────────────────────────────────────
// Actions
// ──────────────────────────────────────────────
private void Assign()
{
if (_selectedFile == null || _selectedGame == null)
{
_playniteApi.Dialogs.ShowMessage(
"Select a file and a game first.", "GameSnap");
return;
}
var gameName = _selectedGame.Name;
var ext = Path.GetExtension(_selectedFile.FilePath).ToLowerInvariant();
// Encontra a pasta do jogo no destino
var normGame = DictionaryService.Normalize(gameName);
string? destDir = null;
if (Directory.Exists(_settings.DestinationBase))
{
foreach (var dir in Directory.GetDirectories(_settings.DestinationBase))
{
var normFolder = DictionaryService.Normalize(Path.GetFileName(dir));
if (normFolder.Contains(normGame) || normGame.Contains(normFolder))
{
destDir = dir;
break;
}
}
}
// Cria a pasta se AutoCreateFolders estiver ativo
if (destDir == null && _settings.AutoCreateFolders)
{
var invalid = Path.GetInvalidFileNameChars();
var folderName = string.Concat(gameName.Split(invalid)).Trim();
destDir = Path.Combine(_settings.DestinationBase, folderName);
Directory.CreateDirectory(destDir);
}
if (destDir == null)
{
_playniteApi.Dialogs.ShowMessage(
$"No folder found for '{gameName}'.\n\nEnable 'Auto-create game folders' in settings, or create the folder manually.",
"GameSnap");
return;
}
// Move o arquivo
var date = new FileInfo(_selectedFile.FilePath).LastWriteTime;
var destName = $"{gameName}_{date:yyyy-MM-dd_HH_mm_ss}{ext}";
var destPath = Path.Combine(destDir, destName);
int i = 1;
while (File.Exists(destPath))
{
destPath = Path.Combine(destDir, $"{gameName}_{date:yyyy-MM-dd_HH_mm_ss}_{i}{ext}");
i++;
}
try
{
PreviewImage = null; // libera o lock do arquivo
File.Move(_selectedFile.FilePath, destPath);
// Aprende o alias
var prefix = Path.GetFileNameWithoutExtension(_selectedFile.FileName)
.Split('_')[0];
_dictionary.SaveAlias(prefix, gameName);
_logger.Write(LogType.Move,
$"Review: {_selectedFile.FileName} → {gameName} (manual)");
RemoveCurrent();
}
catch (Exception ex)
{
_playniteApi.Dialogs.ShowMessage(
$"Failed to move file:\n{ex.Message}", "GameSnap");
}
}
private void Delete()
{
if (_selectedFile == null) return;
var confirm = _playniteApi.Dialogs.ShowMessage(
$"Delete '{_selectedFile.FileName}'?\nThis cannot be undone.",
"GameSnap",
MessageBoxButton.YesNo);
if (confirm != MessageBoxResult.Yes) return;
try
{
PreviewImage = null;
File.Delete(_selectedFile.FilePath);
_logger.Write(LogType.Info, $"Review: deleted {_selectedFile.FileName}");
RemoveCurrent();
}
catch (Exception ex)
{
_playniteApi.Dialogs.ShowMessage(
$"Failed to delete file:\n{ex.Message}", "GameSnap");
}
}
private void Skip()
{
if (_selectedFile == null || UnmatchedFiles.Count == 0) return;
var idx = UnmatchedFiles.IndexOf(_selectedFile);
var next = idx + 1 < UnmatchedFiles.Count ? idx + 1 : 0;
SelectedFile = UnmatchedFiles.Count > 1 ? UnmatchedFiles[next] : null;
}
private void RemoveCurrent()
{
if (_selectedFile == null) return;
var idx = UnmatchedFiles.IndexOf(_selectedFile);
UnmatchedFiles.Remove(_selectedFile);
if (UnmatchedFiles.Count == 0)
{
SelectedFile = null;
_playniteApi.Dialogs.ShowMessage(
"All files reviewed!", "GameSnap");
_closeAction?.Invoke();
return;
}
SelectedFile = UnmatchedFiles[Math.Min(idx, UnmatchedFiles.Count - 1)];
OnPropertyChanged(nameof(StatusText));
}
}
}