-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalProviderService.cs
More file actions
314 lines (283 loc) · 12.7 KB
/
LocalProviderService.cs
File metadata and controls
314 lines (283 loc) · 12.7 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
using Playnite.SDK;
using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace GameSnapPlugin
{
/// <summary>
/// Integração com o Screenshots Utilities Local Provider (HerrKnarz).
/// Registra automaticamente a pasta de destino do GameSnap no config.json do Local Provider.
/// </summary>
public class LocalProviderService
{
private readonly IPlayniteAPI _playniteApi;
private readonly GameSnapLogger _logger;
public LocalProviderService(IPlayniteAPI playniteApi, GameSnapLogger logger)
{
_playniteApi = playniteApi;
_logger = logger;
}
// ──────────────────────────────────────────────
// Detecta se o Local Provider está instalado
// ──────────────────────────────────────────────
public bool IsInstalled()
{
var configPath = GetConfigPath();
return configPath != null && File.Exists(configPath);
}
// ──────────────────────────────────────────────
// Registra a pasta de destino no Local Provider
// ──────────────────────────────────────────────
public bool RegisterDestinationFolder(string destinationBase)
{
var configPath = GetConfigPath();
if (configPath == null)
{
_logger.Info("Local Provider: config.json not found — plugin may not be installed.");
return false;
}
try
{
var json = File.ReadAllText(configPath, Encoding.UTF8);
var config = SimpleJson.Deserialize(json);
if (config == null)
{
_logger.Error("Local Provider: failed to parse config.json.");
return false;
}
// Path que o GameSnap quer registrar: DestinationBase\{Name}\
var targetPath = destinationBase.TrimEnd('\\') + "\\{Name}\\";
// Encontra o perfil global (GameId = 00000000-...)
var profiles = config.GameProfiles;
LocalProviderGameProfile? globalProfile = null;
foreach (var p in profiles)
{
if (p.GameId == "00000000-0000-0000-0000-000000000000")
{
globalProfile = p;
break;
}
}
// Cria o perfil global se não existir
if (globalProfile == null)
{
globalProfile = new LocalProviderGameProfile
{
GameId = "00000000-0000-0000-0000-000000000000",
OverrideGlobalConfigs = false,
FolderConfigs = new List<LocalProviderFolderConfig>()
};
config.GameProfiles.Add(globalProfile);
}
// Verifica se a entrada já existe
foreach (var fc in globalProfile.FolderConfigs)
{
if (string.Equals(fc.Path, targetPath, StringComparison.OrdinalIgnoreCase))
{
_logger.Info($"Local Provider: path already registered: {targetPath}");
return true;
}
}
// Adiciona nova entrada
globalProfile.FolderConfigs.Add(new LocalProviderFolderConfig
{
Active = true,
FileMask = "*.png;*.jpg;*.jpeg",
InvalidCharReplacement = "_",
Name = "GameSnap",
Path = targetPath,
RemoveDiacritics = false,
RemoveEditionSuffix = false,
RemoveHyphens = false,
RemoveSpecialChars = false,
RemoveWhitespaces = false,
UnderscoresToWhitespaces = false,
WhitespacesToHyphens = false,
WhitespacesToUnderscores = false
});
// Serializa e salva
var newJson = SimpleJson.Serialize(config);
File.WriteAllText(configPath, newJson, Encoding.UTF8);
_logger.Info($"Local Provider: registered path: {targetPath}");
return true;
}
catch (Exception ex)
{
_logger.Error($"Local Provider: registration failed: {ex.Message}");
return false;
}
}
// ──────────────────────────────────────────────
// Remove a entrada do GameSnap do Local Provider
// ──────────────────────────────────────────────
public bool UnregisterDestinationFolder(string destinationBase)
{
var configPath = GetConfigPath();
if (configPath == null || !File.Exists(configPath)) return false;
try
{
var json = File.ReadAllText(configPath, Encoding.UTF8);
var config = SimpleJson.Deserialize(json);
if (config == null) return false;
var targetPath = destinationBase.TrimEnd('\\') + "\\{Name}\\";
foreach (var p in config.GameProfiles)
{
p.FolderConfigs.RemoveAll(fc =>
string.Equals(fc.Path, targetPath, StringComparison.OrdinalIgnoreCase)
&& fc.Name == "GameSnap");
}
var newJson = SimpleJson.Serialize(config);
File.WriteAllText(configPath, newJson, Encoding.UTF8);
_logger.Info($"Local Provider: unregistered path: {targetPath}");
return true;
}
catch (Exception ex)
{
_logger.Error($"Local Provider: unregistration failed: {ex.Message}");
return false;
}
}
// ──────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────
private string? GetConfigPath()
{
var dataRoot = _playniteApi.Paths.ExtensionsDataPath;
// Tenta encontrar a pasta do Local Provider por prefixo de nome
if (!Directory.Exists(dataRoot)) return null;
foreach (var dir in Directory.GetDirectories(dataRoot))
{
var name = Path.GetFileName(dir);
if (name.IndexOf("LocalProvider", StringComparison.OrdinalIgnoreCase) >= 0 ||
name.IndexOf("ScreenshotsUtilities", StringComparison.OrdinalIgnoreCase) >= 0)
{
var candidate = Path.Combine(dir, "config.json");
if (File.Exists(candidate)) return candidate;
}
}
return null;
}
}
// ──────────────────────────────────────────────
// Modelos do config.json do Local Provider
// ──────────────────────────────────────────────
[DataContract]
public class LocalProviderConfig
{
[DataMember]
public List<LocalProviderGameProfile> GameProfiles { get; set; } = new List<LocalProviderGameProfile>();
}
[DataContract]
public class LocalProviderGameProfile
{
[DataMember]
public string GameId { get; set; } = "";
[DataMember]
public bool OverrideGlobalConfigs { get; set; } = false;
[DataMember]
public List<LocalProviderFolderConfig> FolderConfigs { get; set; } = new List<LocalProviderFolderConfig>();
}
[DataContract]
public class LocalProviderFolderConfig
{
[DataMember]
public bool Active { get; set; } = true;
[DataMember]
public string FileMask { get; set; } = "*.png;*.jpg";
[DataMember]
public string InvalidCharReplacement { get; set; } = "_";
[DataMember]
public string Name { get; set; } = "";
[DataMember]
public string Path { get; set; } = "";
[DataMember]
public bool RemoveDiacritics { get; set; } = false;
[DataMember]
public bool RemoveEditionSuffix { get; set; } = false;
[DataMember]
public bool RemoveHyphens { get; set; } = false;
[DataMember]
public bool RemoveSpecialChars { get; set; } = false;
[DataMember]
public bool RemoveWhitespaces { get; set; } = false;
[DataMember]
public bool UnderscoresToWhitespaces { get; set; } = false;
[DataMember]
public bool WhitespacesToHyphens { get; set; } = false;
[DataMember]
public bool WhitespacesToUnderscores { get; set; } = false;
}
// ──────────────────────────────────────────────
// JSON via System.Runtime.Serialization
// ──────────────────────────────────────────────
internal static class SimpleJson
{
public static LocalProviderConfig? Deserialize(string json)
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(
typeof(LocalProviderConfig));
using var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
return serializer.ReadObject(ms) as LocalProviderConfig;
}
public static string Serialize(LocalProviderConfig config)
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(
typeof(LocalProviderConfig),
new System.Runtime.Serialization.Json.DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
});
using var ms = new System.IO.MemoryStream();
serializer.WriteObject(ms, config);
var json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
// Pretty print manually
return PrettyPrint(json);
}
private static string PrettyPrint(string json)
{
var sb = new System.Text.StringBuilder();
int indent = 0;
bool inString = false;
foreach (var c in json)
{
if (c == '"' && (sb.Length == 0 || sb[sb.Length - 1] != '\\'))
inString = !inString;
if (!inString)
{
if (c == '{' || c == '[')
{
sb.Append(c);
sb.Append("\n");
indent++;
sb.Append(new string(' ', indent * 2));
continue;
}
if (c == '}' || c == ']')
{
sb.Append("\n");
indent--;
sb.Append(new string(' ', indent * 2));
sb.Append(c);
continue;
}
if (c == ',')
{
sb.Append(c);
sb.Append("\n");
sb.Append(new string(' ', indent * 2));
continue;
}
if (c == ':')
{
sb.Append(": ");
continue;
}
}
sb.Append(c);
}
return sb.ToString();
}
}
}