forked from rommapp/playnite-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomM.cs
More file actions
667 lines (579 loc) · 28 KB
/
Copy pathRomM.cs
File metadata and controls
667 lines (579 loc) · 28 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
using Newtonsoft.Json;
using Playnite.SDK;
using Playnite.SDK.Events;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using RomM.Games;
using RomM.Downloads;
using RomM.VersionSelector;
using RomM.Models.RomM.Collection;
using RomM.Models.RomM.Rom;
using RomM.Settings;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace RomM
{
public static class HttpClientSingleton
{
private static readonly HttpClient httpClient = new HttpClient();
static HttpClientSingleton()
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static void ConfigureBasicAuth(string username, string password)
{
var base64Credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials);
}
public static void ConfigureAPIAuth(string apiToken)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
}
public static HttpClient Instance => httpClient;
}
public static class JsonSerializerSingleton
{
public static JsonSerializer Instance { get; } = new JsonSerializer();
}
public class RomM : LibraryPlugin, IRomM
{
private const string s_pluginName = "RomM";
internal static readonly string Icon = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"icon.png");
internal static readonly Guid PluginId = Guid.Parse("9700aa21-447d-41b4-a989-acd38f407d9f");
internal static readonly MetadataNameProperty SourceName = new MetadataNameProperty(s_pluginName);
public override Guid Id { get; } = PluginId;
public override string Name { get; } = s_pluginName;
public override string LibraryIcon { get; } = Icon;
public ILogger Logger => LogManager.GetLogger();
public IPlayniteAPI Playnite { get; private set; }
public SettingsViewModel Settings { get; private set; }
public string ROMDataPath { get; private set; }
public MetadataProperty Source { get; private set; }
public DownloadQueueController DownloadQueueController { get; private set; }
internal RomMDownloadsSidebarItem DownloadsSidebar { get; private set; }
private readonly DownloadQueueViewModel downloadsVm;
// Game ids whose next ItemUpdated was caused by the importer itself, so OnItemUpdated must
// not echo the change back to the RomM server.
private readonly ConcurrentDictionary<Guid, byte> ignoredGameIds = new ConcurrentDictionary<Guid, byte>();
public void SuppressSync(Guid gameId) => ignoredGameIds[gameId] = 0;
// Implementing Client adds ability to open it via special menu in playnite
public override LibraryClient Client { get; } = new RomMClient();
public RomM(IPlayniteAPI api) : base(api)
{
Playnite = api;
Properties = new LibraryPluginProperties
{
HasSettings = true,
HasCustomizedGameImport = true,
};
ROMDataPath = $"{Playnite.Paths.ExtensionsDataPath}\\{Id}\\Games\\";
// Initialise the download queue
downloadsVm = new DownloadQueueViewModel();
// Limit to 10 concurrent downloads for the moment
DownloadQueueController = new DownloadQueueController(Playnite, downloadsVm, maxConcurrent: 10);
// Initialise the sidebar only in desktop mode
if (API.Instance.ApplicationInfo.Mode == ApplicationMode.Desktop)
{
DownloadsSidebar = new RomMDownloadsSidebarItem(this);
}
}
#region Helper functions
public string CombineUrl(string baseUrl, string relativePath) => RomMUrl.Combine(baseUrl, relativePath);
public RomMRom FetchRom(string romId)
{
string romUrl = CombineUrl(Settings.RomMHost, $"api/roms/{romId}");
try
{
HttpResponseMessage response = HttpClientSingleton.Instance.GetAsync(romUrl).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
string body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonConvert.DeserializeObject<RomMRom>(body);
}
catch (HttpRequestException e)
{
Logger.Error($"Request exception: {e.Message}");
return null;
}
}
// Playnite url is in the format playnite://romm/<action>/<platform_igdb_id>/<rom_id>
internal void HandleRommUri(PlayniteUriEventArgs args)
{
var action = args.Arguments[0];
var platformIgdbId = args.Arguments[1];
var romId = args.Arguments[2];
Logger.Debug($"Received Playnite URI: {action}/{platformIgdbId}/{romId}");
RomMRom rom = FetchRom(romId);
if (rom == null)
{
Logger.Warn($"Game {romId} not found in RomM.");
return;
}
foreach (var mapping in SettingsViewModel.Instance.Mappings?.Where(m => m.Enabled))
{
if (mapping.RomMPlatform.IgdbId.ToString() == platformIgdbId)
{
var gameName = rom.Name;
var game = Playnite.Database.Games.FirstOrDefault(g => g.Source.Name == SourceName.ToString() &&
g.Platforms.Any(p => p.Name == mapping.RomMPlatform.Name) &&
g.Name == gameName);
if (game == null)
{
Logger.Warn($"Game {gameName} not found in Playnite database.");
return;
}
PlayniteApi.MainView.SwitchToLibraryView();
PlayniteApi.MainView.SelectGame(game.Id);
switch (action)
{
case "view":
// We always open the game in the webview
return;
case "play":
PlayniteApi.StartGame(game.Id);
break;
}
}
}
}
// New-style overload (used by DownloadQueueController)
public static Task<HttpResponseMessage> GetAsync(string url, HttpCompletionOption completionOption, CancellationToken ct)
{
return HttpClientSingleton.Instance.GetAsync(url, completionOption, ct);
}
#endregion
#region Playnite functions
public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
base.OnApplicationStarted(args);
if (!Directory.Exists($"{ROMDataPath}"))
Directory.CreateDirectory($"{ROMDataPath}");
Settings = new SettingsViewModel(this, this);
if (Settings.UseBasicAuth && !string.IsNullOrEmpty(Settings.RomMUsername) && !string.IsNullOrEmpty(Settings.RomMPassword))
{
HttpClientSingleton.ConfigureBasicAuth(Settings.RomMUsername, Settings.RomMPassword);
}
else if(SettingsViewModel.ApiTokenPattern.IsMatch(Settings.RomMClientToken))
{
HttpClientSingleton.ConfigureAPIAuth(Settings.RomMClientToken);
}
Playnite.UriHandler.RegisterSource("romm", HandleRommUri);
Source = SourceName;
// Portable path fix: expand "{PlayniteDir}" to absolute paths in DB on startup
if (Playnite.Paths.IsPortable)
{
using (PlayniteApi.Database.BufferedUpdate())
{
var games = PlayniteApi.Database.Games.Where(g =>
g.PluginId == Id &&
g.InstallDirectory != null &&
g.InstallDirectory.Contains(ExpandableVariables.PlayniteDirectory));
foreach (var game in games)
{
game.InstallDirectory = PlayniteApi.ExpandGameVariables(game, game.InstallDirectory);
if (game.Roms != null && game.Roms.Count > 0)
{
var roms = game.Roms.Where(r => r.Path.Contains(ExpandableVariables.PlayniteDirectory));
foreach (var rom in roms)
{
rom.Path = PlayniteApi.ExpandGameVariables(game, rom.Path);
}
}
PlayniteApi.Database.Games.Update(game);
}
}
}
Playnite.Database.Games.ItemUpdated += OnItemUpdated;
PlayniteApi.Database.Games.ItemCollectionChanged += (_, argus) =>
{
// Remove json file if game is removed from playnite
if (argus.RemovedItems.Count > 0)
{
foreach (var item in argus.RemovedItems)
{
if (item.PluginId == PluginId)
{
if (RomMGameId.TryParse(item.GameId, out int _, out var sha1))
{
var romDataFile = $"{ROMDataPath}{sha1}.json";
if (File.Exists(romDataFile))
{
File.Delete(romDataFile);
}
}
else
{
Logger.Error($"Game {item.Name} id is malformed!");
}
}
}
}
};
}
public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
base.OnApplicationStopped(args);
Playnite.Database.Games.ItemUpdated -= OnItemUpdated;
// Portable path fix: restore "{PlayniteDir}" tokens before exiting
if (Playnite.Paths.IsPortable)
{
using (PlayniteApi.Database.BufferedUpdate())
{
var games = PlayniteApi.Database.Games.Where(g =>
g.PluginId == Id &&
g.InstallDirectory != null &&
g.InstallDirectory.StartsWith(PlayniteApi.Paths.ApplicationPath));
foreach (var game in games)
{
game.InstallDirectory = game.InstallDirectory.Replace(
PlayniteApi.Paths.ApplicationPath,
ExpandableVariables.PlayniteDirectory);
if (game.Roms != null && game.Roms.Count > 0)
{
foreach (var rom in game.Roms)
{
rom.Path = rom.Path.Replace(
PlayniteApi.Paths.ApplicationPath,
ExpandableVariables.PlayniteDirectory);
}
}
PlayniteApi.Database.Games.Update(game);
}
}
}
}
public override IEnumerable<Game> ImportGames(LibraryImportGamesArgs args)
{
if (Playnite.ApplicationInfo.Mode == ApplicationMode.Fullscreen && !Settings.ScanGamesInFullScreen)
{
return new List<Game>();
}
// Import only needs connectivity + server version, not the profile/avatar.
if(!Settings.TestConnection(false, false))
{
return new List<Game>();
}
return new RomMImportController(this).Import(args);
}
public override ISettings GetSettings(bool firstRunSettings)
{
return Settings;
}
public override UserControl GetSettingsView(bool firstRunSettings)
{
return new SettingsView();
}
public override IEnumerable<SidebarItem> GetSidebarItems()
{
if (DownloadsSidebar != null)
{
yield return DownloadsSidebar;
}
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
List<GameMenuItem> gameMenuItems = new List<GameMenuItem>();
var game = args.Games.First();
if (game.PluginId == PluginId && RomMGameId.TryParse(game.GameId, out int _, out var sha1))
{
string romDataFile = $"{ROMDataPath}{sha1}.json";
if (Settings.MergeRevisions && File.Exists(romDataFile) && game.IsInstalled)
{
try
{
string json = File.ReadAllText(romDataFile);
var gameData = JsonConvert.DeserializeObject<RomMRomLocal>(json);
if(gameData.ROMVersions.Count > 1)
{
gameMenuItems.Add(new GameMenuItem
{
//MenuSection = "@",
Description = "Switch ROM Version!",
Action = (gameMenuItem) =>
{
Playnite.InstallGame(args.Games.First().Id);
}
});
}
}
catch (Exception)
{
Logger.Error($"{args.Games.First().Name} GameID is malformed or json file is corrupted!");
}
}
}
return gameMenuItems;
}
public override IEnumerable<InstallController> GetInstallActions(GetInstallActionsArgs args)
{
if (args.Game.PluginId == Id)
{
string gameID = args.Game.GameId;
GameInstallInfo romData = new GameInstallInfo();
RomMRomLocal gameData = new RomMRomLocal();
if (gameID == null || !gameID.Contains(':') || gameID.StartsWith("!0"))
{
PlayniteApi.Notifications.Add(new NotificationMessage(PluginId.ToString(), "Old ID detected run update game library before installing!", NotificationType.Error));
romData.Id = (int)InstallStatus.Cancelled;
yield return new RomMInstallController(args.Game, this, romData);
yield break;
}
else
{
// Pull game file from RomM data directory
if (!RomMGameId.TryParse(gameID, out int _, out string romMSHA1) || !File.Exists($"{ROMDataPath}{romMSHA1}.json"))
{
Logger.Error($"{args.Game.Name} GameID is malformed!");
romData.Id = (int)InstallStatus.Cancelled;
yield return new RomMInstallController(args.Game, this, romData);
yield break;
}
try
{
string json = File.ReadAllText($"{ROMDataPath}{romMSHA1}.json");
gameData = JsonConvert.DeserializeObject<RomMRomLocal>(json);
}
catch (Exception)
{
Logger.Error($"{args.Game.Name} GameID is malformed or {romMSHA1} json file is corrupted!");
romData.Id = (int)InstallStatus.Cancelled;
}
if (romData.Id == (int)InstallStatus.Cancelled || gameData?.ROMVersions == null || gameData.ROMVersions.Count == 0)
{
romData.Id = (int)InstallStatus.Cancelled;
yield return new RomMInstallController(args.Game, this, romData);
yield break;
}
// Set ROM data to base ROM
romData = new GameInstallInfo
{
Id = gameData.ROMVersions[0].Id,
FileName = gameData.ROMVersions[0].FileName,
HasMultipleFiles = gameData.ROMVersions[0].HasMultipleFiles,
DownloadURL = gameData.ROMVersions[0].DownloadURL,
Mapping = Settings.Mappings.FirstOrDefault(x => x.MappingId == gameData.MappingID)
};
// If Siblings are avaiable prompt user with version selection
if (Settings.MergeRevisions && gameData.ROMVersions?.Count > 1)
{
RomMVersionSelector VersionSelectorControl = new RomMVersionSelector(gameData.ROMVersions);
var window = Playnite.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = false,
ShowCloseButton = false,
});
window.Height = 215;
window.Width = 600;
window.Title = "Select Version to install!";
window.ShowInTaskbar = false;
window.ResizeMode = ResizeMode.NoResize;
window.Owner = API.Instance.Dialogs.GetCurrentAppWindow();
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Content = VersionSelectorControl;
window.ShowDialog();
if (VersionSelectorControl.Cancelled)
{
romData.Id = (int)InstallStatus.Cancelled;
}
else
{
// Uninstall old ROM before installing new one
if (args.Game.IsInstalled)
{
Playnite.UninstallGame(args.Game.Id);
args.Game.IsInstalling = true;
Playnite.Database.Games.Update(args.Game);
}
var selectedrevision = VersionSelectorControl.RomVersions.First(x => x.IsSelected);
romData.Id = selectedrevision.Id;
romData.FileName = selectedrevision.FileName;
romData.HasMultipleFiles = selectedrevision.HasMultipleFiles;
romData.DownloadURL = selectedrevision.DownloadURL;
gameData.ROMVersions = VersionSelectorControl.RomVersions.ToList();
}
}
else
{
gameData.ROMVersions[0].IsSelected = true;
}
File.WriteAllText($"{ROMDataPath}{romMSHA1}.json", JsonConvert.SerializeObject(gameData));
}
yield return new RomMInstallController(args.Game, this, romData);
}
}
public override IEnumerable<UninstallController> GetUninstallActions(GetUninstallActionsArgs args)
{
if (args.Game.PluginId == Id)
{
yield return new RomMUninstallController(args.Game, this);
}
}
public override void OnGameInstalled(OnGameInstalledEventArgs args)
{
base.OnGameInstalled(args);
if (args.Game.PluginId == PluginId && Settings.NotifyOnInstallComplete)
{
Playnite.Notifications.Add(args.Game.GameId, $"Download of \"{args.Game.Name}\" is complete", NotificationType.Info);
}
}
public override LibraryMetadataProvider GetMetadataDownloader()
{
return new RomMMetadataProvider(this);
}
#endregion
#region RomM Status Syncing
public IList<RomMCollection> FetchFavorites()
{
string apiFavoriteUrl = CombineUrl(Settings.RomMHost, "api/collections");
try
{
// Make the request and get the response
HttpResponseMessage response = HttpClientSingleton.Instance.GetAsync(apiFavoriteUrl).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
// Assuming the response is in JSON format
string body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonConvert.DeserializeObject<List<RomMCollection>>(body);
}
catch (HttpRequestException e)
{
Logger.Error($"Request exception: {e.Message}");
return new List<RomMCollection>();
}
}
internal RomMCollection CreateFavorites()
{
string apiCollectionUrl = CombineUrl(Settings.RomMHost, "api/collections?is_favorite=true&is_public=false");
try
{
var formData = new MultipartFormDataContent();
formData.Add(new StringContent("Favorites"), "name");
HttpResponseMessage postResponse = HttpClientSingleton.Instance.PostAsync(apiCollectionUrl, formData).GetAwaiter().GetResult();
postResponse.EnsureSuccessStatusCode();
string body = postResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonConvert.DeserializeObject<RomMCollection>(body);
}
catch (HttpRequestException e)
{
Logger.Error($"Request exception: {e.Message}");
return null;
}
}
internal void UpdateFavorites(RomMCollection favoriteCollection, List<int> romIds)
{
if (favoriteCollection == null)
{
Logger.Error($"Can't update favorites, collection is null");
return;
}
string apiCollectionUrl = CombineUrl(Settings.RomMHost, "api/collections");
try
{
var formData = new MultipartFormDataContent();
formData.Add(new StringContent(JsonConvert.SerializeObject(romIds)), "rom_ids");
HttpResponseMessage putResponse = HttpClientSingleton.Instance.PutAsync($"{apiCollectionUrl}/{favoriteCollection.Id}", formData).GetAwaiter().GetResult();
putResponse.EnsureSuccessStatusCode();
}
catch (HttpRequestException e)
{
Logger.Error($"Request exception: {e.Message}");
}
}
private void OnItemUpdated(object sender, ItemUpdatedEventArgs<Game> e)
{
Task.Run(async () =>
{
foreach (var update in e.UpdatedItems)
{
var oldGame = update.OldData;
var newGame = update.NewData;
// Ignore non-RomM games
if (newGame.PluginId != Id)
{
continue;
}
// This is the cancel signal
if (oldGame.IsInstalling && !newGame.IsInstalling)
{
DownloadQueueController?.Cancel(newGame.Id);
}
if (Settings.KeepRomMSynced == true)
{
// The importer wrote the server's own values into this game; don't push them back.
if (ignoredGameIds.TryRemove(newGame.Id, out byte _))
{
continue;
}
if(!RomMGameId.TryParse(newGame.GameId, out int romMId, out string _))
{
Logger.Error($"{newGame.Name} GameID is malformed!");
continue;
}
if (oldGame.Favorite != newGame.Favorite)
{
Logger.Info($"Favorites changed for {romMId}.");
try
{
IList<RomMCollection> favoriteCollections = FetchFavorites();
var favoriteCollection = favoriteCollections.FirstOrDefault(c => c.IsFavorite) ?? CreateFavorites();
var romIds = favoriteCollection?.RomIds ?? new List<int>();
if (newGame.Favorite == false)
{
romIds.Remove(romMId);
}
else
{
romIds.Add(romMId);
}
UpdateFavorites(favoriteCollection, romIds);
}
catch (Exception ex)
{
Logger.Error(ex, "RomM Favorite Sync Failed");
}
}
if (oldGame.CompletionStatus != newGame.CompletionStatus)
{
try
{
// This would be easier if status would be merged: https://github.com/rommapp/romm/issues/2971
// For now we check if it is either "playing" or "plan to play" and set the booleans, otherwise we set the status
// If this issue is accepted and fixed, we can just reverse the CompletionStatusMap dictionary
if (newGame.CompletionStatus == null) continue;
var status = newGame.CompletionStatus.Name;
var updatePayload = new
{
data = new
{
backlogged = status == "Plan to Play",
now_playing = status == "Playing",
status = RomMRomUser.CompletionStatusMap.FirstOrDefault((kv) => kv.Value == status && kv.Value != "Playing" && kv.Value != "Plan to Play" && kv.Value != "Not Played").Key
}
};
string apiRomMRomUserProps = CombineUrl(Settings.RomMHost, $"api/roms/{romMId}/props");
HttpResponseMessage response = HttpClientSingleton.Instance.PutAsync(apiRomMRomUserProps, new StringContent(JsonConvert.SerializeObject(updatePayload), Encoding.UTF8, "application/json")).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
Logger.Error(ex, $"RomM Status Sync Failed for {romMId}");
}
}
}
}
});
}
#endregion
}
}