-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrganizerService.cs
More file actions
618 lines (518 loc) · 26.3 KB
/
Copy pathOrganizerService.cs
File metadata and controls
618 lines (518 loc) · 26.3 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace GameSnapPlugin
{
public class OrganizerService
{
private readonly GameSnapSettings _settings;
private readonly DictionaryService _dictionary;
private readonly GameSnapLogger _logger;
// Callback para notificações (injetado pelo plugin principal)
public Action<string, string>? OnFileMoved { get; set; }
// Lista de jogos organizados neste ciclo — para notificar ScreenshotsVisualizer
public Action<List<string>>? OnGamesOrganized { get; set; }
// Jogo atual informado pelo Playnite
private string? _currentGame;
// Cache de arquivos já processados nesta sessão
private readonly HashSet<string> _processed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public OrganizerService(GameSnapSettings settings, DictionaryService dictionary, GameSnapLogger logger)
{
_settings = settings;
_dictionary = dictionary;
_logger = logger;
}
public void SetCurrentGame(string? name) => _currentGame = name;
// ──────────────────────────────────────────────
// Entry point — chamado pelo watcher e pelo loop
// ──────────────────────────────────────────────
// Steam service reference (set by plugin)
public SteamService? SteamService { get; set; }
// Emulator service reference (set by plugin)
public EmulatorService? EmulatorService { get; set; }
public void Organize()
{
var dict = _dictionary.Load();
// Steam screenshots
if (_settings.EnableSteamSupport && SteamService != null)
OrganizeSteam();
// Emulator screenshots
if (_settings.EnableEmulatorSupport && EmulatorService != null)
OrganizeEmulators(dict);
var allSources = new List<string>();
if (!string.IsNullOrEmpty(_settings.SourceFolder))
allSources.Add(_settings.SourceFolder);
allSources.AddRange(_settings.AdditionalSourceFolders
.Where(f => !string.IsNullOrEmpty(f) && Directory.Exists(f)));
if (allSources.Count == 0) return;
if (!Directory.Exists(_settings.DestinationBase)) return;
var folders = LoadFolders();
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var source in allSources)
{
if (!Directory.Exists(source)) continue;
foreach (var file in Directory.GetFiles(source))
{
TryOrganizeFile(file, dict, folders, counts);
}
}
if (counts.Count > 0)
{
var summary = string.Join(" | ", counts.Select(kv => $"{kv.Key} ({kv.Value})"));
_logger.Info($"Organized: {summary}");
// Dispara notificação agregada
OnFileMoved?.Invoke(
"GameSnap",
$"Organized {counts.Values.Sum()} screenshot(s): {summary}"
);
// Notifica ScreenshotsVisualizer com a lista de jogos afetados
OnGamesOrganized?.Invoke(counts.Keys.ToList());
}
}
// ──────────────────────────────────────────────
// Steam
// ──────────────────────────────────────────────
private void OrganizeSteam()
{
if (SteamService == null) return;
var steamPath = !string.IsNullOrEmpty(_settings.SteamPath)
? _settings.SteamPath
: SteamService.DetectSteamPath() ?? "";
if (string.IsNullOrEmpty(steamPath)) return;
var pending = SteamService.GetPendingScreenshots(steamPath);
if (pending.Count == 0) return;
var folders = LoadFolders();
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var ss in pending)
{
if (_processed.Contains(ss.FilePath)) continue;
var gameName = SteamService.ResolveGameName(ss.AppId);
if (gameName == null)
{
_logger.Write(LogType.Error,
$"Steam: AppID {ss.AppId} not found in library. File: {Path.GetFileName(ss.FilePath)}");
TryMoveToUnmatched(ss.FilePath, Path.GetExtension(ss.FilePath).ToLowerInvariant());
continue;
}
var normGame = DictionaryService.Normalize(gameName);
var match = folders
.Where(f => f.NameNorm.Contains(normGame) || normGame.Contains(f.NameNorm))
.OrderByDescending(f => f.NameNorm.Length)
.FirstOrDefault();
if (match == null)
{
_logger.Write(LogType.Error,
$"Steam: No folder for '{gameName}'. File: {Path.GetFileName(ss.FilePath)}");
TryMoveToUnmatched(ss.FilePath, Path.GetExtension(ss.FilePath).ToLowerInvariant());
continue;
}
var ext = Path.GetExtension(ss.FilePath).ToLowerInvariant();
var date = GetBestDate(ss.FilePath);
var destName = BuildDestName(match.NameOriginal, date,
Path.GetFileNameWithoutExtension(ss.FilePath), ext);
var destPath = Path.Combine(match.Path, destName);
int i = 1;
while (File.Exists(destPath))
{
var nameNoExt = Path.GetFileNameWithoutExtension(destName);
destPath = Path.Combine(match.Path, $"{nameNoExt}_{i}{ext}");
i++;
}
try
{
File.Move(ss.FilePath, destPath);
if (_settings.EnableBackup && !string.IsNullOrEmpty(_settings.BackupFolder))
TryBackup(destPath, match.NameOriginal, false);
_processed.Add(ss.FilePath);
int current = counts.ContainsKey(match.NameOriginal) ? counts[match.NameOriginal] : 0;
counts[match.NameOriginal] = current + 1;
_logger.Write(LogType.Move,
$"Steam: {Path.GetFileName(ss.FilePath)} → {match.NameOriginal}");
}
catch (Exception ex)
{
_logger.Write(LogType.Error,
$"Steam move failed: {ex.Message}");
}
}
if (counts.Count > 0)
{
var summary = string.Join(" | ", counts.Select(kv => $"{kv.Key} ({kv.Value})"));
OnFileMoved?.Invoke("GameSnap", $"Steam: {counts.Values.Sum()} screenshot(s): {summary}");
}
}
// ──────────────────────────────────────────────
// Emulators
// ──────────────────────────────────────────────
private void OrganizeEmulators(Dictionary<string, string> dict)
{
if (EmulatorService == null) return;
var pending = EmulatorService.GetPendingScreenshots();
if (pending.Count == 0) return;
var folders = LoadFolders();
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var ss in pending)
{
if (_processed.Contains(ss.FilePath)) continue;
// Consulta o dicionário primeiro — resolve nomes internos de ROM
// (ex: "mslug", "garou") que não batem por aproximação com o
// título de exibição do Playnite. Mesmo dicionário usado pelo
// fluxo do ShareX (WindowFallback/Playnite), sem aprendizado
// automático aqui (o resolvedor de emulador já é mais específico).
var resolvedName = ss.GameName;
var normCandidate = DictionaryService.Normalize(ss.GameName);
if (dict.TryGetValue(normCandidate, out var fromDict))
resolvedName = fromDict;
var normGame = DictionaryService.Normalize(resolvedName);
var match = folders
.Where(f => f.NameNorm.Contains(normGame) || normGame.Contains(f.NameNorm))
.OrderByDescending(f => f.NameNorm.Length)
.FirstOrDefault();
if (match == null)
{
// Auto-create if enabled
if (_settings.AutoCreateFolders)
{
var invalid = Path.GetInvalidFileNameChars();
var folderName = string.Concat(resolvedName.Split(invalid)).Trim();
var newPath = Path.Combine(_settings.DestinationBase, folderName);
Directory.CreateDirectory(newPath);
folders = LoadFolders(); // refresh
match = folders.FirstOrDefault(f =>
DictionaryService.Normalize(f.NameOriginal) == DictionaryService.Normalize(folderName));
}
if (match == null)
{
_logger.Write(LogType.Error,
$"Emulator [{ss.Emulator}]: No folder for '{resolvedName}'. File: {Path.GetFileName(ss.FilePath)}");
TryMoveToUnmatched(ss.FilePath, Path.GetExtension(ss.FilePath).ToLowerInvariant());
continue;
}
}
var ext = Path.GetExtension(ss.FilePath).ToLowerInvariant();
var date = GetBestDate(ss.FilePath);
var destName = BuildDestName(match.NameOriginal, date,
Path.GetFileNameWithoutExtension(ss.FilePath), ext);
var destPath = Path.Combine(match.Path, destName);
int i = 1;
while (File.Exists(destPath))
{
var nameNoExt = Path.GetFileNameWithoutExtension(destName);
destPath = Path.Combine(match.Path, $"{nameNoExt}_{i}{ext}");
i++;
}
try
{
File.Move(ss.FilePath, destPath);
if (_settings.EnableBackup && !string.IsNullOrEmpty(_settings.BackupFolder))
TryBackup(destPath, match.NameOriginal, false);
_processed.Add(ss.FilePath);
int current = counts.ContainsKey(match.NameOriginal) ? counts[match.NameOriginal] : 0;
counts[match.NameOriginal] = current + 1;
_logger.Write(LogType.Move,
$"Emulator [{ss.Emulator}]: {Path.GetFileName(ss.FilePath)} → {match.NameOriginal}");
}
catch (Exception ex)
{
_logger.Error($"Emulator move failed: {ex.Message}");
}
}
if (counts.Count > 0)
{
var summary = string.Join(" | ", counts.Select(kv => $"{kv.Key} ({kv.Value})"));
OnFileMoved?.Invoke("GameSnap", $"Emulators: {counts.Values.Sum()} screenshot(s): {summary}");
}
}
// ──────────────────────────────────────────────
// Processa um arquivo individual
// ──────────────────────────────────────────────
private void TryOrganizeFile(
string filePath,
Dictionary<string, string> dict,
List<FolderEntry> folders,
Dictionary<string, int> counts)
{
if (_processed.Contains(filePath)) return;
var ext = Path.GetExtension(filePath).ToLowerInvariant();
bool isImage = _settings.ImageExtensions.Contains(ext);
bool isVideo = _settings.VideoExtensions.Contains(ext);
if (!isImage && !isVideo) return;
// Small delay to ensure file is fully written — non-blocking
System.Threading.Thread.Sleep(800);
var fileName = Path.GetFileName(filePath);
var prefix = GetPrefix(fileName);
var normPfx = DictionaryService.Normalize(prefix);
string? game = null;
string method = "UNKNOWN";
// 0. Bypass de emulador — prefixos como "retroarch" identificam o CORE, não a ROM.
// Um único prefixo serve pra vários jogos diferentes, então dicionário e janela
// ativa não podem ser usados (nem aprendidos) para esses prefixos: a única fonte
// confiável é o jogo que o Playnite diz estar rodando agora.
bool isEmulatorPrefix = _settings.EmulatorPrefixes
.Any(p => normPfx.Equals(DictionaryService.Normalize(p), StringComparison.OrdinalIgnoreCase));
if (isEmulatorPrefix)
{
if (!string.IsNullOrEmpty(_currentGame))
{
game = _currentGame;
method = "EMULATOR-PLAYNITE";
}
else
{
_logger.Write(LogType.Error,
$"File: {fileName}\nReason: Emulator prefix '{prefix}' but no active Playnite game");
TryMoveToUnmatched(filePath, ext);
return;
}
}
// 1. Dicionário
if (game == null && dict.TryGetValue(normPfx, out var fromDict))
{
game = fromDict;
method = "DICTIONARY";
}
// 2. Playnite
if (game == null && _settings.UsePlayniteDetection && !string.IsNullOrEmpty(_currentGame))
{
game = _currentGame;
method = "PLAYNITE";
// Auto-learn: save prefix → game mapping so future files skip detection
if (!string.IsNullOrEmpty(prefix) && prefix.Length > 2)
{
_dictionary.SaveAlias(prefix, _currentGame);
_logger.Write(LogType.Learn, $"Prefix: {prefix}\nGame: {_currentGame}");
}
}
// 3. Janela ativa — nunca roda para prefixos de emulador (isEmulatorPrefix já
// retornou acima quando não há jogo ativo, então chegar aqui com game == null
// e isEmulatorPrefix == true não deveria acontecer, mas o guard abaixo garante isso.
// Opção D: só ativa durante sessão de jogo (entre OnGameStarted e OnGameStopped)
// Opção C: só ativa se o prefixo já existe no dicionário (jogo conhecido fora do Playnite)
bool inGameSession = _currentGame != null;
bool prefixKnown = dict.ContainsKey(normPfx);
bool canUseFallback = _settings.UseWindowFallback && (inGameSession || prefixKnown);
if (game == null && canUseFallback)
{
var win = GetActiveWindowTitle();
if (!string.IsNullOrEmpty(win) && win.Length > 4)
{
var normWin = DictionaryService.Normalize(win);
// Blacklist expandida — rejeita janelas que claramente não são jogos
bool blocked = _settings.WindowBlacklist.Any(b =>
normWin.IndexOf(b, StringComparison.OrdinalIgnoreCase) >= 0);
// Rejeita títulos com padrões típicos de sistema/browser
bool looksLikeSystem =
normWin.Contains("explorador de arquivos") ||
normWin.Contains("file explorer") ||
normWin.Contains("mais guias") || // "e 3 mais guias"
normWin.Contains("more tabs") ||
normWin.Contains("google drive") ||
normWin.Contains("onedrive") ||
normWin.Contains("hotmail") ||
normWin.Contains("playnite") || // "+Playnite", "Playnite", etc.
normWin.Contains("gmail") ||
normWin.Contains("outlook") ||
normWin.Contains(" - explorador") ||
normWin.Contains(" - explorer") ||
normWin.Contains("playnite") || // evita pasta do Playnite
normWin.Length < 3;
if (!blocked && !looksLikeSystem)
{
game = win;
method = "WINDOW";
_logger.Write(LogType.Fallback, $"Prefix: {prefix}\nDetected: {win}");
}
else
{
_logger.Write(LogType.Info,
$"Fallback blocked: {win}\nFile: {fileName}");
}
}
}
// Sem match
if (game == null)
{
_logger.Write(LogType.Error, $"File: {fileName}\nReason: No detection");
TryMoveToUnmatched(filePath, ext);
return;
}
// Encontra pasta de destino
var normGame = DictionaryService.Normalize(game);
var match = folders
.Where(f => f.NameNorm.Contains(normGame) || normGame.Contains(f.NameNorm))
.OrderByDescending(f => f.NameNorm.Length)
.FirstOrDefault();
if (match == null)
{
_logger.Write(LogType.Error, $"File: {fileName}\nGame: {game}\nNo folder found");
TryMoveToUnmatched(filePath, ext);
return;
}
// Destino final
var destDir = isVideo
? EnsureDir(Path.Combine(match.Path, "Videos"))
: match.Path;
var date = GetBestDate(filePath);
var destName = BuildDestName(match.NameOriginal, date, Path.GetFileNameWithoutExtension(fileName), ext);
var destPath = Path.Combine(destDir, destName);
// Evita colisão
int i = 1;
while (File.Exists(destPath))
{
var nameNoExt = Path.GetFileNameWithoutExtension(destName);
destPath = Path.Combine(destDir, $"{nameNoExt}_{i}{ext}");
i++;
}
try
{
File.Move(filePath, destPath);
// Backup opcional
if (_settings.EnableBackup && !string.IsNullOrEmpty(_settings.BackupFolder))
TryBackup(destPath, match.NameOriginal, isVideo);
_processed.Add(filePath);
int current = counts.ContainsKey(match.NameOriginal) ? counts[match.NameOriginal] : 0;
counts[match.NameOriginal] = current + 1;
_logger.Write(LogType.Move, $"File: {fileName}\nGame: {game}\nMethod: {method}");
}
catch (Exception ex)
{
_logger.Write(LogType.Error, $"File: {fileName}\nMove failed: {ex.Message}");
}
}
// ──────────────────────────────────────────────
// Pasta Unmatched
// ──────────────────────────────────────────────
private void TryMoveToUnmatched(string filePath, string ext)
{
if (!_settings.MoveUnmatchedToFolder) return;
if (string.IsNullOrWhiteSpace(_settings.DestinationBase)) return;
try
{
var unmatchedDir = EnsureDir(
Path.Combine(_settings.DestinationBase, _settings.UnmatchedFolderName));
var destPath = Path.Combine(unmatchedDir, Path.GetFileName(filePath));
int i = 1;
while (File.Exists(destPath))
{
var nameNoExt = Path.GetFileNameWithoutExtension(filePath);
destPath = Path.Combine(unmatchedDir, $"{nameNoExt}_{i}{ext}");
i++;
}
File.Move(filePath, destPath);
_processed.Add(filePath);
_logger.Write(LogType.Info, $"Moved to unmatched: {Path.GetFileName(filePath)}");
}
catch (Exception ex)
{
_logger.Write(LogType.Error, $"Unmatched move failed: {ex.Message}");
}
}
// ──────────────────────────────────────────────
// Backup
// ──────────────────────────────────────────────
private void TryBackup(string sourcePath, string gameName, bool isVideo)
{
try
{
var backupGame = EnsureDir(Path.Combine(_settings.BackupFolder, gameName));
var backupDir = isVideo ? EnsureDir(Path.Combine(backupGame, "Videos")) : backupGame;
var destPath = Path.Combine(backupDir, Path.GetFileName(sourcePath));
if (!File.Exists(destPath))
File.Copy(sourcePath, destPath);
}
catch (Exception ex)
{
_logger.Write(LogType.Error, $"Backup failed: {ex.Message}");
}
}
// ──────────────────────────────────────────────
// Renomeação customizável
// ──────────────────────────────────────────────
private string BuildDestName(string gameName, DateTime date, string originalName, string ext)
{
var pattern = string.IsNullOrWhiteSpace(_settings.RenamePattern)
? "{game}_{date}_{time}"
: _settings.RenamePattern;
var result = pattern
.Replace("{game}", SanitizeFileName(gameName))
.Replace("{date}", date.ToString("yyyy-MM-dd"))
.Replace("{time}", date.ToString("HH_mm_ss"))
.Replace("{datetime}", date.ToString("yyyy-MM-dd_HH_mm_ss"))
.Replace("{original}", SanitizeFileName(originalName));
return result + ext;
}
private static string SanitizeFileName(string name)
{
var invalid = Path.GetInvalidFileNameChars();
return string.Concat(name.Split(invalid)).Trim();
}
// ──────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────
private List<FolderEntry> LoadFolders()
{
return Directory.GetDirectories(_settings.DestinationBase)
.Select(d => new FolderEntry
{
NameOriginal = Path.GetFileName(d),
NameNorm = DictionaryService.Normalize(Path.GetFileName(d)),
Path = d
})
.ToList();
}
private static string GetPrefix(string filename)
{
var m = Regex.Match(filename, @"^([^_]+)_");
return m.Success
? m.Groups[1].Value
: Path.GetFileNameWithoutExtension(filename);
}
private static DateTime GetBestDate(string filePath)
{
var name = Path.GetFileNameWithoutExtension(filePath);
var m = Regex.Match(name, @"(\d{4})[-_](\d{2})[-_](\d{2}).*?(\d{2})[-_](\d{2})[-_](\d{2})");
if (m.Success)
{
try
{
return new DateTime(
int.Parse(m.Groups[1].Value),
int.Parse(m.Groups[2].Value),
int.Parse(m.Groups[3].Value),
int.Parse(m.Groups[4].Value),
int.Parse(m.Groups[5].Value),
int.Parse(m.Groups[6].Value));
}
catch { }
}
var info = new FileInfo(filePath);
return info.LastWriteTime != default ? info.LastWriteTime : info.CreationTime;
}
private static string EnsureDir(string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private static string GetActiveWindowTitle()
{
var sb = new StringBuilder(256);
GetWindowText(GetForegroundWindow(), sb, sb.Capacity);
return sb.ToString();
}
private class FolderEntry
{
public string NameOriginal { get; set; } = "";
public string NameNorm { get; set; } = "";
public string Path { get; set; } = "";
}
}
}