forked from tekgator/GameLib.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOriginGameFactory.cs
More file actions
337 lines (287 loc) · 11.4 KB
/
Copy pathOriginGameFactory.cs
File metadata and controls
337 lines (287 loc) · 11.4 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
using Gamelib.Core.Util;
using GameLib.Core;
using GameLib.Plugin.Origin.Model;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
namespace GameLib.Plugin.Origin;
internal static class OriginGameFactory
{
private static readonly string Os = GetOs();
private static readonly uint OsArch = GetOsArch();
/// <summary>
/// Get games installed for the Origin launcher
/// </summary>
public static IEnumerable<OriginGame> GetGames(ILauncher launcher, CancellationToken cancellationToken = default)
{
var localContentPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Origin", "LocalContent");
if (!Directory.Exists(localContentPath))
{
return Enumerable.Empty<OriginGame>();
}
return Directory.GetFiles(localContentPath, "*.mfst", SearchOption.AllDirectories)
.AsParallel()
.WithCancellation(cancellationToken)
.Select(manifestFile => DeserializeManifest(manifestFile))
.Where(game => game is not null)
.Select(game => AddLauncherId(launcher, game!))
.Select(game => AddExecutables(launcher, game!))
.Select(game => AddLocalCatalogData(game!))
.Select(game => AddOnlineData(launcher, game))
.ToList();
}
/// <summary>
/// Deserialize the Origin Game manifest file into a <see cref="OriginGame"/> object
/// </summary>
private static OriginGame? DeserializeManifest(string manifestFile)
{
var manifestText = File.ReadAllText(manifestFile);
var valueCollection = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(manifestText));
var game = new OriginGame()
{
Id = valueCollection["id"] ?? string.Empty,
InstallDir = PathUtil.Sanitize(valueCollection["dipInstallPath"]) ?? string.Empty,
Locale = valueCollection["locale"] ?? string.Empty,
};
if (string.IsNullOrEmpty(game.Id) || string.IsNullOrEmpty(game.InstallDir))
{
return null;
}
game.LaunchString = $"origin://launchgame/{game.Id}";
game.TotalBytes = long.TryParse(valueCollection["totalbytes"], out long tmpResult) ? tmpResult : 0;
game.InstallDate = PathUtil.GetCreationTime(game.InstallDir) ?? DateTime.MinValue;
return game;
}
/// <summary>
/// Add launcher ID to Game
/// </summary>
private static OriginGame AddLauncherId(ILauncher launcher, OriginGame game)
{
game.LauncherId = launcher.Id;
return game;
}
/// <summary>
/// Find executables within the install directory
/// </summary>
private static OriginGame AddExecutables(ILauncher launcher, OriginGame game)
{
if (launcher.LauncherOptions.SearchExecutables)
{
var executables = PathUtil.GetExecutables(game.InstallDir);
executables.AddRange(game.Executables);
game.Executables = executables.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
return game;
}
/// <summary>
/// Load data from local stored manifest file
/// In case no GameName is found but a content ID the game name is loaded from the registry
/// </summary>
private static OriginGame AddLocalCatalogData(OriginGame game)
{
var installerXmlPath = Path.Combine(game.InstallDir, "__Installer", "installerdata.xml");
List<string> contendIds = new();
if (!AddFromLocalDipManifestData(game, installerXmlPath, contendIds))
{
AddFromLocalGameManifestData(game, installerXmlPath, contendIds);
}
if (string.IsNullOrEmpty(game.Name) && contendIds.Count > 0)
{
game.Name = RegistryUtil.GetValue(RegistryHive.LocalMachine, $@"SOFTWARE\Origin Games\{contendIds[0]}", "DisplayName", string.Empty)!;
}
if (string.IsNullOrEmpty(game.Locale) && contendIds.Count > 0)
{
game.Locale = RegistryUtil.GetValue(RegistryHive.LocalMachine, $@"SOFTWARE\Origin Games\{contendIds[0]}", "Locale", string.Empty)!;
}
if (!string.IsNullOrEmpty(game.Executable))
{
game.WorkingDir = Path.GetDirectoryName(game.Executable) ?? string.Empty;
}
return game;
}
/// <summary>
/// Load data from local manifest file in the DIP XML schema
/// Seems to be the case for newer Origin games
/// </summary>
private static bool AddFromLocalDipManifestData(OriginGame game, string installerXmlPath, List<string> contendIds)
{
OriginDiPManifest? diPManifest = null;
try
{
var ser = new XmlSerializer(typeof(OriginDiPManifest));
diPManifest = ser.Deserialize(XmlReader.Create(installerXmlPath)) as OriginDiPManifest;
}
catch { /* ignore */ }
if (diPManifest is null)
{
return false;
}
if (string.IsNullOrEmpty(game.Name))
{
var gameTitle = diPManifest.gameTitles?.FirstOrDefault(defaultValue: null);
game.Name = gameTitle?.Value ?? game.Name;
}
if (diPManifest.contentIDs is not null)
{
contendIds.AddRange(diPManifest.contentIDs);
}
if (string.IsNullOrEmpty(game.Executable))
{
var filePath = diPManifest.runtime?.FirstOrDefault(defaultValue: null)?.filePath;
if (!string.IsNullOrEmpty(filePath))
{
game.Executable = filePath;
if (filePath.StartsWith('[') && filePath.Contains(']'))
{
game.Executable = PathUtil.Sanitize(Path.Combine(game.InstallDir, filePath[(filePath.LastIndexOf(']') + 1)..]))!;
game.WorkingDir = Path.GetDirectoryName(game.Executable) ?? string.Empty;
}
if (!PathUtil.IsExecutable(game.Executable) && !File.Exists(game.Executable))
{
game.Executable = string.Empty;
game.WorkingDir = string.Empty;
}
}
}
return true;
}
/// <summary>
/// Load data from local manifest file in the Game XML schema
/// Seems to be the case for older Origin games
/// This schema apparently has no information about the executables of a game
/// </summary>
private static void AddFromLocalGameManifestData(OriginGame game, string installerXmlPath, List<string> contendIds)
{
OriginGameManifest? gameManifest = null;
try
{
var ser = new XmlSerializer(typeof(OriginGameManifest));
gameManifest = ser.Deserialize(XmlReader.Create(installerXmlPath)) as OriginGameManifest;
}
catch { /* ignore */ }
if (gameManifest is null)
{
return;
}
if (string.IsNullOrEmpty(game.Name))
{
var gameTitle = gameManifest.metadata?.localeInfo?.FirstOrDefault(defaultValue: null)?.title;
game.Name = gameTitle ?? game.Name;
}
if (gameManifest.contentIDs is not null)
{
contendIds.AddRange(gameManifest.contentIDs);
}
}
/// <summary>
/// Load data from online manifest file in JSON format
/// This is the only method to get the executables for older games it seems
/// </summary>
private static OriginGame AddOnlineData(ILauncher launcher, OriginGame game)
{
if (!launcher.LauncherOptions.QueryOnlineData)
{
return game;
}
if (!string.IsNullOrEmpty(game.Name) && !string.IsNullOrEmpty(game.Executable))
{
return game;
}
OriginOnlineManifest? manifest;
try
{
var manifestJson = GetManifestFromUrl(game.Id, launcher.LauncherOptions.OnlineQueryTimeout);
manifest = JsonConvert.DeserializeObject<OriginOnlineManifest>(manifestJson);
if (manifest is null)
{
throw new ApplicationException("Cannot deserialize JSON stream");
}
}
catch
{
return game;
}
if (string.IsNullOrEmpty(game.Name))
{
game.Name = manifest.LocalizableAttributes?.DisplayName ?? game.Name;
}
if (string.IsNullOrEmpty(game.Name))
{
game.Name = manifest.ItemName ?? game.Name;
}
if (string.IsNullOrEmpty(game.Executable) && manifest.Publishing?.SoftwareList?.Software is not null)
{
foreach (var item in manifest.Publishing.SoftwareList.Software
.Where(p => p.SoftwarePlatform is null || p.SoftwarePlatform.Contains(Os))
.OrderByDescending(p => (p.FulfillmentAttributes?.ProcessorArchitecture ?? string.Empty).Contains(OsArch.ToString())))
{
var filePath = item.FulfillmentAttributes?.ExecutePathOverride ?? game.Executable;
if (!string.IsNullOrEmpty(filePath))
{
game.Executable = filePath;
if (filePath.StartsWith('[') && filePath.Contains(']'))
{
game.Executable = Path.Combine(game.InstallDir, PathUtil.Sanitize(filePath[(filePath.LastIndexOf(']') + 1)..])!);
}
if (PathUtil.IsExecutable(game.Executable) && File.Exists(game.Executable))
{
break;
}
game.Executable = string.Empty;
}
}
if (!string.IsNullOrEmpty(game.Executable))
{
game.WorkingDir = Path.GetDirectoryName(game.Executable) ?? string.Empty;
}
}
return game;
}
/// <summary>
/// Query manifest JSON string from the Origin API URL
/// </summary>
public static string GetManifestFromUrl(string gameId, TimeSpan? queryTimeout = null)
{
using var client = new HttpClient();
if (queryTimeout is not null)
{
client.Timeout = queryTimeout.Value;
}
var url = $"https://api1.origin.com/ecommerce2/public/{gameId}/en_US";
using var webRequest = new HttpRequestMessage(HttpMethod.Get, url);
using var response = client.Send(webRequest);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException("Response is not OK", null, response.StatusCode);
}
using var reader = new StreamReader(response.Content.ReadAsStream());
return reader.ReadToEnd();
}
/// <summary>
/// Return the OS as a valid Origin string (as per manifest)
/// </summary>
private static string GetOs()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return "PCWIN";
}
// TODO: haven't seen a Origin Linux game yet, this line might need to be adjusted
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return "LINUX";
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return "MAC";
}
return string.Empty;
}
/// <summary>
/// Returns the OS architecture as an integer
/// </summary>
private static uint GetOsArch() => (uint)(RuntimeInformation.OSArchitecture == Architecture.X64 ? 64 : 32);
}