-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenScraperClient.cs
More file actions
335 lines (291 loc) · 14 KB
/
Copy pathScreenScraperClient.cs
File metadata and controls
335 lines (291 loc) · 14 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
using Playnite.SDK;
using Playnite.SDK.Data;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RetroReel
{
public class ScreenScraperClient : IDisposable
{
private const string BaseUrl = "https://www.screenscraper.fr/api2/";
private const string DevId = "RetroReel";
// Substitua pelo devpassword obtido no fórum do ScreenScraper (seção API)
private const string DevPassword = "REPLACE_WITH_DEVPASSWORD";
private const string SoftwareName = "RetroReel";
private readonly HttpClient _http;
private readonly ILogger _logger;
public ScreenScraperClient()
{
_logger = LogManager.GetLogger();
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
_http.DefaultRequestHeaders.Add("User-Agent", SoftwareName + "/1.0");
}
public async Task<bool> DownloadVideoAsync(
Game game,
RetroReelSettings settings,
string destPath,
CancellationToken ct)
{
if (string.IsNullOrEmpty(settings.SsUserName) ||
string.IsNullOrEmpty(settings.SsUserPassword))
{
_logger.Warn("RetroReel: credenciais do ScreenScraper não configuradas.");
return false;
}
string systemId = GetSystemId(game, settings);
if (string.IsNullOrEmpty(systemId))
{
_logger.Warn(string.Format(
"RetroReel: plataforma '{0}' não mapeada para ScreenScraper.",
game.Platforms != null && game.Platforms.Count > 0
? game.Platforms[0].Name : "(nenhuma)"));
return false;
}
string romPath = GetRomPath(game);
var gameInfo = await FindGameAsync(game, romPath, systemId, settings, ct);
if (gameInfo == null)
{
_logger.Info(string.Format("RetroReel: '{0}' não encontrado no ScreenScraper.", game.Name));
return false;
}
string videoUrl = ExtractVideoUrl(gameInfo, settings.PreferredRegion);
if (string.IsNullOrEmpty(videoUrl))
{
_logger.Info(string.Format("RetroReel: nenhum vídeo disponível no SS para '{0}'.", game.Name));
return false;
}
return await DownloadFileAsync(videoUrl, destPath, settings, ct);
}
// ── Busca em cascata ─────────────────────────────────────────────────
private async Task<Dictionary<string, object>> FindGameAsync(
Game game, string romPath, string systemId,
RetroReelSettings settings, CancellationToken ct)
{
long limitBytes = (long)settings.HashSizeLimitMb * 1024L * 1024L;
// 1. Hash (só para ROMs pequenas)
if (!string.IsNullOrEmpty(romPath) && File.Exists(romPath))
{
var info = new FileInfo(romPath);
if (info.Length <= limitBytes)
{
string crc = ComputeCrc32(romPath);
string md5 = ComputeMd5(romPath);
string sha1 = ComputeSha1(romPath);
var byHash = await QueryAsync(systemId, settings,
string.Format("romtype=rom&crc={0}&md5={1}&sha1={2}&romtaille={3}",
Uri.EscapeDataString(crc),
Uri.EscapeDataString(md5),
Uri.EscapeDataString(sha1),
info.Length), ct);
if (byHash != null) return byHash;
}
}
// 2-4. Variações de nome
var variants = VideoNameMatcher.GetSearchVariants(romPath, game.Name);
foreach (var variant in variants)
{
if (ct.IsCancellationRequested) break;
var byName = await QueryAsync(systemId, settings,
string.Format("romtype=rom&romnom={0}", Uri.EscapeDataString(variant)), ct);
if (byName != null) return byName;
}
return null;
}
private async Task<Dictionary<string, object>> QueryAsync(
string systemId, RetroReelSettings settings,
string extraParams, CancellationToken ct)
{
try
{
string url = string.Format(
"{0}jeuInfos.php?devid={1}&devpassword={2}&softname={3}&ssid={4}&sspassword={5}&output=json&systemeid={6}&{7}",
BaseUrl,
Uri.EscapeDataString(DevId),
Uri.EscapeDataString(DevPassword),
Uri.EscapeDataString(SoftwareName),
Uri.EscapeDataString(settings.SsUserName),
Uri.EscapeDataString(settings.SsUserPassword),
Uri.EscapeDataString(systemId),
extraParams);
var response = await _http.GetAsync(url, ct);
if (!response.IsSuccessStatusCode) return null;
string json = await response.Content.ReadAsStringAsync();
var root = Serialization.FromJson<Dictionary<string, object>>(json);
if (root == null) return null;
// Verifica erro retornado pela API
if (root.TryGetValue("header", out object headerObj) &&
headerObj is Dictionary<string, object> header &&
header.TryGetValue("Error", out object err) &&
!string.IsNullOrEmpty(err?.ToString()))
{
_logger.Debug("RetroReel SS API erro: " + err);
return null;
}
if (!root.TryGetValue("response", out object responseObj)) return null;
if (!(responseObj is Dictionary<string, object> resp)) return null;
if (!resp.TryGetValue("jeu", out object jeuObj)) return null;
return jeuObj as Dictionary<string, object>;
}
catch (Exception ex)
{
_logger.Warn(ex, "RetroReel: falha na query ao ScreenScraper");
return null;
}
}
private string ExtractVideoUrl(Dictionary<string, object> gameInfo, string preferredRegion)
{
if (!gameInfo.TryGetValue("medias", out object mediasObj)) return null;
if (!(mediasObj is List<object> medias)) return null;
string bestUrl = null;
int bestPriority = int.MaxValue;
foreach (var item in medias)
{
if (!(item is Dictionary<string, object> media)) continue;
string type = media.TryGetValue("type", out object t) ? t?.ToString() : null;
if (type != "video" && type != "video-normalized") continue;
string region = media.TryGetValue("region", out object r) ? r?.ToString() ?? "wor" : "wor";
string url = media.TryGetValue("url", out object u) ? u?.ToString() : null;
if (string.IsNullOrEmpty(url)) continue;
int priority;
if (!string.IsNullOrEmpty(preferredRegion) &&
string.Equals(region, preferredRegion, StringComparison.OrdinalIgnoreCase))
priority = 0;
else if (region == "wor")
priority = 1;
else
priority = 2;
if (priority < bestPriority)
{
bestPriority = priority;
bestUrl = url;
}
}
return bestUrl;
}
private async Task<bool> DownloadFileAsync(
string url, string destPath,
RetroReelSettings settings, CancellationToken ct)
{
try
{
string authUrl = string.Format(
"{0}&ssid={1}&sspassword={2}&devid={3}&devpassword={4}",
url,
Uri.EscapeDataString(settings.SsUserName),
Uri.EscapeDataString(settings.SsUserPassword),
Uri.EscapeDataString(DevId),
Uri.EscapeDataString(DevPassword));
using (var response = await _http.GetAsync(authUrl, HttpCompletionOption.ResponseHeadersRead, ct))
{
response.EnsureSuccessStatusCode();
Directory.CreateDirectory(Path.GetDirectoryName(destPath));
using (var stream = await response.Content.ReadAsStreamAsync())
using (var file = File.Create(destPath))
{
byte[] buffer = new byte[81920];
int read;
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0)
await file.WriteAsync(buffer, 0, read, ct);
}
}
_logger.Info(string.Format("RetroReel: vídeo SS salvo em '{0}'", destPath));
return true;
}
catch (Exception ex)
{
_logger.Error(ex, string.Format("RetroReel: falha ao baixar vídeo de '{0}'", url));
return false;
}
}
// ── Utilitários ──────────────────────────────────────────────────────
private string GetRomPath(Game game) =>
game.Roms != null && game.Roms.Count > 0 ? game.Roms[0].Path : null;
private string GetSystemId(Game game, RetroReelSettings settings)
{
if (game.Platforms == null || game.Platforms.Count == 0) return null;
string platformName = game.Platforms[0].Name;
var cfg = settings.PlatformConfigs.FirstOrDefault(p =>
string.Equals(p.PlatformName, platformName, StringComparison.OrdinalIgnoreCase));
if (cfg != null && !string.IsNullOrEmpty(cfg.SsSystemId))
return cfg.SsSystemId;
return DefaultSystemIds.TryGetValue(platformName, out string id) ? id : null;
}
private string ComputeCrc32(string path)
{
uint[] table = new uint[256];
for (uint i = 0; i < 256; i++)
{
uint c = i;
for (int j = 0; j < 8; j++)
c = (c & 1) != 0 ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
table[i] = c;
}
uint crc = 0xFFFFFFFF;
using (var fs = File.OpenRead(path))
{
byte[] buf = new byte[65536];
int read;
while ((read = fs.Read(buf, 0, buf.Length)) > 0)
for (int i = 0; i < read; i++)
crc = (crc >> 8) ^ table[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ 0xFFFFFFFF).ToString("X8");
}
private string ComputeMd5(string path)
{
using (var md5 = MD5.Create())
using (var fs = File.OpenRead(path))
return BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "").ToUpperInvariant();
}
private string ComputeSha1(string path)
{
using (var sha1 = SHA1.Create())
using (var fs = File.OpenRead(path))
return BitConverter.ToString(sha1.ComputeHash(fs)).Replace("-", "").ToUpperInvariant();
}
private static readonly Dictionary<string, string> DefaultSystemIds =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Sony PlayStation 2", "58" },
{ "Sony PlayStation", "57" },
{ "Sony PSP", "61" },
{ "Nintendo Entertainment System", "3" },
{ "Super Nintendo Entertainment System", "4" },
{ "Nintendo 64", "14" },
{ "Nintendo GameCube", "13" },
{ "Nintendo Wii", "16" },
{ "Nintendo DS", "15" },
{ "Nintendo 3DS", "17" },
{ "Nintendo Wii U", "18" },
{ "Game Boy", "9" },
{ "Game Boy Color", "10" },
{ "Game Boy Advance", "12" },
{ "Sega Genesis", "1" },
{ "Sega Mega Drive", "1" },
{ "Sega Saturn", "22" },
{ "Sega Dreamcast", "23" },
{ "Sega Master System", "2" },
{ "Sega Game Gear", "21" },
{ "Arcade", "75" },
{ "MAME", "75" },
{ "FBNeo", "75" },
{ "Atari 2600", "26" },
{ "Atari 7800", "28" },
{ "Neo Geo", "142" },
{ "PC Engine", "31" },
{ "TurboGrafx-16", "31" },
{ "3DO", "29" },
{ "Atari Jaguar", "27" },
{ "Microsoft Xbox", "32" },
{ "Microsoft Xbox 360", "33" },
};
public void Dispose() => _http?.Dispose();
}
}