forked from AuriRex/GTFO_TheArchive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArchiveMod.cs
645 lines (544 loc) · 23.3 KB
/
ArchiveMod.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TheArchive.Core;
using TheArchive.Core.FeaturesAPI;
using TheArchive.Core.Managers;
using TheArchive.Core.Models;
using TheArchive.Interfaces;
using TheArchive.Loader;
using TheArchive.Utilities;
using static TheArchive.Utilities.Utils;
[assembly: InternalsVisibleTo("TheArchive.IL2CPP")]
[assembly: InternalsVisibleTo("TheArchive.MONO")]
namespace TheArchive
{
public static class ArchiveMod
{
public const string GUID = "dev." + AUTHOR + ".gtfo." + MOD_NAME;
public const string MOD_NAME = "TheArchive";
public const string ABBREVIATION = "Ar";
public const string AUTHOR = "AuriRex";
public const string VERSION_STRING = ThisAssembly.Git.SemVer.Major + "." + ThisAssembly.Git.SemVer.Minor + "." + ThisAssembly.Git.SemVer.Patch;
public const string GITHUB_LINK = "https://github.com/AuriRex/GTFO_TheArchive";
public static readonly bool GIT_IS_DIRTY = ThisAssembly.Git.IsDirty;
public const string GIT_COMMIT_SHORT_HASH = ThisAssembly.Git.Commit;
public const string GIT_COMMIT_DATE = ThisAssembly.Git.CommitDate;
public const string MTFO_GUID = "com.dak.MTFO";
public static ArchiveSettings Settings { get; private set; } = new ArchiveSettings();
private static JsonSerializerSettings _jsonSerializerSettings = null;
public static JsonSerializerSettings JsonSerializerSettings
{
get
{
if(_jsonSerializerSettings == null)
{
_jsonSerializerSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
};
_jsonSerializerSettings.Converters.Add(new JsonLib.Converters.StringEnumConverter());
_jsonSerializerSettings.Converters.Add(new Core.FeaturesAPI.Components.FButton.FButtonConverter());
}
return _jsonSerializerSettings;
}
}
public static bool IsPlayingModded { get; private set; } = false;
public static RundownID CurrentRundown { get; private set; } = RundownID.RundownUnitialized;
public static GameBuildInfo CurrentBuildInfo { get; private set; }
public static int CurrentGameState { get; private set; }
public static bool IsOnALTBuild { get; private set; }
/// <summary>
/// The currently selected rundown on the rundown screen.<br/>
/// Is equal to <seealso cref="string.Empty"/> on the "Select Rundown" screen.<br/>
/// </summary>
public static string CurrentlySelectedRundownKey
{
get => _currentlySelectedRundownKey;
set
{
_currentlySelectedRundownKey = value;
ArchiveLogger.Debug($"Setting {nameof(CurrentlySelectedRundownKey)} to \"{_currentlySelectedRundownKey}\".");
if(string.IsNullOrEmpty(_currentlySelectedRundownKey))
{
CurrentlySelectedRundownPersistentID = 0;
return;
}
try
{
CurrentlySelectedRundownPersistentID = uint.Parse(_currentlySelectedRundownKey.Replace("Local_", ""));
}
catch(Exception ex)
{
ArchiveLogger.Error($"Failed to parse selected rundown persistentId from {nameof(CurrentlySelectedRundownKey)} \"{CurrentlySelectedRundownKey}\"!");
ArchiveLogger.Exception(ex);
}
}
}
private static string _currentlySelectedRundownKey = string.Empty;
/// <summary>
/// Persistent ID of the currently selected RundownDataBlock on the rundown screen.<br/>
/// </summary>
public static uint CurrentlySelectedRundownPersistentID { get; set; } = 0;
public static event Action<RundownID> GameDataInitialized;
public static event Action DataBlocksReady;
public static event Action<int> GameStateChanged;
public static event Action<bool> ApplicationFocusStateChanged;
internal static event Action<IArchiveModule> OnNewModuleRegistered;
private static IArchiveModule _mainModule;
private static readonly HashSet<Assembly> _inspectedAssemblies = new HashSet<Assembly>();
private static readonly HashSet<Type> _typesToInitOnDataBlocksReady = new HashSet<Type>();
private static readonly HashSet<Type> _typesToInitOnGameDataInit = new HashSet<Type>();
private static readonly HashSet<IInitializable> _iinitializablesToInjectOnGameDataInit = new HashSet<IInitializable>();
private static readonly HashSet<Assembly> _moduleAssemblies = new HashSet<Assembly>();
private static readonly List<Type> _moduleTypes = new List<Type>();
public static List<IArchiveModule> Modules { get; private set; } = new List<IArchiveModule>();
public static Type IL2CPP_BaseType { get; private set; } = null;
private const string kArchiveSettingsFile = "TheArchive_Settings.json";
private static HarmonyLib.Harmony _harmonyInstance;
public static void OnApplicationStart(IArchiveLogger logger, HarmonyLib.Harmony harmonyInstance)
{
ArchiveLogger.logger = logger;
_harmonyInstance = harmonyInstance;
if(GIT_IS_DIRTY)
{
ArchiveLogger.Warning("Git is dirty, this is a development build!");
}
try
{
if(LoaderWrapper.IsGameIL2CPP())
{
IL2CPP_BaseType = ImplementationManager.FindTypeInCurrentAppDomain("Il2CppSystem.Object", exactMatch: true);
ArchiveLogger.Debug($"IL2CPP_BaseType: {IL2CPP_BaseType?.FullName}");
if (IL2CPP_BaseType == null)
throw new Exception();
}
}
catch (Exception ex)
{
ArchiveLogger.Error("IL2CPP base type \"Il2CppSystem.Object\" could not be resolved!");
ArchiveLogger.Exception(ex);
}
LoadConfig();
if(LoaderWrapper.IsModInstalled(MTFO_GUID))
{
IsPlayingModded = true;
}
#if !BepInEx
HarmonyLib.Tools.Logger.ChannelFilter |= HarmonyLib.Tools.Logger.LogChannel.Error;
HarmonyLib.Tools.Logger.MessageReceived += (handler, eventArgs) => ArchiveLogger.Error(eventArgs.Message);
#endif
GTFOLogger.Logger = LoaderWrapper.CreateLoggerInstance("GTFO-Internals", ConsoleColor.DarkGray);
CurrentRundown = BuildDB.GetCurrentRundownID(BuildDB.BuildNumber);
ArchiveLogger.Msg(ConsoleColor.DarkMagenta, $"Current game revision determined to be {BuildDB.BuildNumber}! ({CurrentRundown})");
if (RundownFlags.Latest.ToString() == nameof(RundownFlags.Latest))
{
for(int i = 0; i < 5; i++)
ArchiveLogger.Warning($"{nameof(RundownFlags)} enum is missaligned again!! >:I");
}
CurrentBuildInfo = new GameBuildInfo
{
BuildNumber = BuildDB.BuildNumber,
Rundown = CurrentRundown
};
IsOnALTBuild = CurrentRundown.IsIncludedIn(RundownFlags.RundownAltOne.ToLatest());
var steam_appidtxt = Path.Combine(LoaderWrapper.GameDirectory, "steam_appid.txt");
if(!File.Exists(steam_appidtxt))
{
ArchiveLogger.Notice("Creating \"steam_appid.txt\" in GTFO folder ...");
File.WriteAllText(steam_appidtxt, "493520");
}
FeatureManager.Internal_Init();
var archiveModule = LoadMainArchiveModule(LoaderWrapper.IsGameIL2CPP());
var moduleMainType = archiveModule.GetTypes().First(t => typeof(IArchiveModule).IsAssignableFrom(t));
_mainModule = CreateAndInitModule(moduleMainType);
try
{
ApplyPatches(CurrentRundown);
}
catch (Exception ex)
{
ArchiveLogger.Exception(ex);
}
}
public static void OnApplicationQuit()
{
FeatureManager.Instance.OnApplicationQuit();
}
private static void LoadConfig()
{
var path = Path.Combine(LocalFiles.ModLocalLowPath, kArchiveSettingsFile);
LoadConfig(path);
}
private static void LoadConfig(string path)
{
try
{
ArchiveLogger.Info($"Loading config file ... [{path}]");
if (File.Exists(path))
{
Settings = JsonConvert.DeserializeObject<ArchiveSettings>(File.ReadAllText(path), JsonSerializerSettings);
}
SaveConfig(path);
}
catch (Exception ex)
{
ArchiveLogger.Exception(ex);
}
}
private static void SaveConfig(string path)
{
ArchiveLogger.Debug($"Saving config file ... [{path}]");
File.WriteAllText(path, JsonConvert.SerializeObject(Settings, JsonSerializerSettings));
}
public static void RegisterArchiveModule(Assembly asm)
{
foreach(var type in asm.GetTypes().Where(t => typeof(IArchiveModule).IsAssignableFrom(t)))
{
RegisterArchiveModule(type);
}
}
public static void RegisterArchiveModule(Type moduleType)
{
RegisterModule(moduleType);
}
public static bool RegisterModule(Type moduleType)
{
if (moduleType == null) throw new ArgumentException("Module can't be null!");
if (_moduleTypes.Contains(moduleType)) throw new ArgumentException($"Module \"{moduleType.Name}\" is already registered!");
if (!typeof(IArchiveModule).IsAssignableFrom(moduleType)) throw new ArgumentException($"Type \"{moduleType.Name}\" does not implement {nameof(IArchiveModule)}!");
var module = CreateAndInitModule(moduleType);
OnNewModuleRegistered?.Invoke(module);
if (CurrentRundown != RundownID.RundownUnitialized)
{
module.Patcher?.PatchRundownSpecificMethods(module.GetType().Assembly);
return true;
}
return false;
}
[Obsolete("Do not call!")]
public static void InvokeGameDataInitialized()
{
ArchiveLogger.Info($"GameData has been initialized, invoking event.");
//CurrentRundownInt = rundownId;
try
{
PresenceFormatter.Setup();
}
catch (Exception ex)
{
ArchiveLogger.Exception(ex);
}
foreach (var type in _typesToInitOnGameDataInit)
{
IInitializable instance = null;
try
{
InitInitializables(type, out instance);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Trying to Init \"{type.FullName}\" threw an exception:");
ArchiveLogger.Exception(ex);
}
try
{
InjectInstanceIntoModules(instance);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Trying to Inject \"{type.FullName}\" threw an exception:");
ArchiveLogger.Exception(ex);
}
}
foreach(var iinit in _iinitializablesToInjectOnGameDataInit)
{
try
{
InjectInstanceIntoModules(iinit);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Trying to Inject \"{iinit.GetType().FullName}\" threw an exception:");
ArchiveLogger.Exception(ex);
}
}
FeatureManager.Instance.OnGameDataInitialized();
GameDataInitialized?.Invoke(CurrentRundown);
}
[Obsolete("Do not call!")]
public static void InvokeDataBlocksReady()
{
try
{
DataBlockManager.Setup();
}
catch (Exception ex)
{
ArchiveLogger.Exception(ex);
}
ArchiveLogger.Info($"DataBlocks should be ready to be interacted with, invoking event.");
foreach(var type in _typesToInitOnDataBlocksReady)
{
IInitializable instance = null;
try
{
InitInitializables(type, out instance);
}
catch(Exception ex)
{
ArchiveLogger.Error($"Trying to Init \"{type.FullName}\" threw an exception:");
ArchiveLogger.Exception(ex);
}
try
{
InjectInstanceIntoModules(instance);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Trying to Inject \"{type.FullName}\" threw an exception:");
ArchiveLogger.Exception(ex);
}
}
FeatureManager.Instance.OnDatablocksReady();
DataBlocksReady?.Invoke();
}
[Obsolete("Do not call!")]
public static void InvokeGameStateChanged(int eGameState_state)
{
CurrentGameState = eGameState_state;
GameStateChanged?.Invoke(eGameState_state);
}
[Obsolete("Do not call!")]
public static void InvokeApplicationFocusChanged(bool focus)
{
ApplicationFocusStateChanged?.Invoke(focus);
}
public static void InjectInstanceIntoModules(object instance)
{
if (instance == null) return;
foreach (var module in Modules)
{
InjectInstanceIntoModules(instance, module);
}
}
private static void InjectInstanceIntoModules(object instance, IArchiveModule module)
{
foreach (var prop in module.GetType().GetProperties().Where(p => p.SetMethod != null && !p.SetMethod.IsStatic && p.PropertyType.IsAssignableFrom(instance.GetType())))
{
prop.SetValue(module, instance);
}
}
private static void InitInitializables(Type type, out IInitializable initializable)
{
ArchiveLogger.Debug($"Creating instance of: \"{type.FullName}\".");
var instance = (IInitializable) Activator.CreateInstance(type);
initializable = instance;
bool init = true;
var initSingletonbase_Type = typeof(InitSingletonBase<>).MakeGenericType(type);
if (initSingletonbase_Type.IsAssignableFrom(type))
{
initSingletonbase_Type.GetProperty(nameof(InitSingletonBase<String>.Instance), AnyBindingFlagss).SetValue(null, instance);
}
if (typeof(IInjectLogger).IsAssignableFrom(type))
{
var injectLoggerable = (IInjectLogger)instance;
injectLoggerable.Logger = LoaderWrapper.CreateArSubLoggerInstance(type.Name, ConsoleColor.Green);
}
if (typeof(IInitCondition).IsAssignableFrom(type))
{
var conditional = (IInitCondition)instance;
init = conditional.InitCondition();
}
if (init)
{
try
{
instance.Init();
initSingletonbase_Type.GetProperty(nameof(InitSingletonBase<String>.HasBeenInitialized), AnyBindingFlagss).SetValue(null, true);
}
catch(Exception ex)
{
ArchiveLogger.Error($"{nameof(IInitializable.Init)} method on Type \"{type.FullName}\" failed!");
ArchiveLogger.Exception(ex);
}
}
}
private static void InspectType(Type type)
{
if(typeof(Feature).IsAssignableFrom(type) && type != typeof(Feature))
{
FeatureManager.Instance.InitFeature(type);
return;
}
if (typeof(IInitImmediately).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
{
IInitializable instance = null;
try
{
InitInitializables(type, out instance);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Trying to Init \"{type.FullName}\" (immediately) threw an exception:");
ArchiveLogger.Exception(ex);
}
if(instance != null)
_iinitializablesToInjectOnGameDataInit.Add(instance);
return;
}
if (typeof(IInitAfterGameDataInitialized).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
{
_typesToInitOnGameDataInit.Add(type);
return;
}
if (typeof(IInitAfterDataBlocksReady).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
{
_typesToInitOnDataBlocksReady.Add(type);
return;
}
}
private static IArchiveModule CreateAndInitModule(Type moduleType)
{
if (moduleType == null) throw new ArgumentException($"Parameter {nameof(moduleType)} can not be null!");
var stopwatch = new Stopwatch();
stopwatch.Start();
_moduleTypes.Add(moduleType);
ArchiveLogger.Info($"Initializing module \"{moduleType.FullName}\" ...");
var module = (IArchiveModule) Activator.CreateInstance(moduleType);
foreach(var type in moduleType.Assembly.GetTypes())
{
InspectType(type);
}
_moduleAssemblies.Add(moduleType.Assembly);
if(module.UsesLegacyPatches)
module.Patcher = new ArchiveLegacyPatcher(_harmonyInstance, $"{moduleType.Assembly.GetName().Name}_{moduleType.FullName}_ArchivePatcher");
try
{
module.Init();
if (module.ApplyHarmonyPatches)
{
ArchiveLogger.Warning($"Applying regular Harmony patches on module \"{moduleType.FullName}\" ...");
_harmonyInstance.PatchAll(moduleType.Assembly);
}
}
catch(Exception ex)
{
ArchiveLogger.Error($"Error while trying to init \"{moduleType.FullName}\"!");
ArchiveLogger.Exception(ex);
}
Modules.Add(module);
stopwatch.Stop();
ArchiveLogger.Debug($"Creation of \"{moduleType.FullName}\" took {stopwatch.Elapsed:ss\\.fff} seconds.");
return module;
}
private static void ApplyPatches(RundownID rundownID)
{
if (rundownID != RundownID.RundownUnitialized)
{
foreach (var module in Modules)
{
module.Patcher?.PatchRundownSpecificMethods(module.GetType().Assembly);
}
}
}
internal static void UnpatchAll()
{
foreach (var module in Modules)
{
UnpatchModule(module);
}
}
public static void UnpatchModule(Type moduleType)
{
if (!_moduleTypes.Contains(moduleType)) throw new ArgumentException($"Can't unpatch non patched module \"{moduleType.FullName}\".");
foreach (var module in Modules)
{
if (module.GetType() == moduleType)
{
UnpatchModule(module);
return;
}
}
throw new ArgumentException($"Can't unpatch module \"{moduleType.FullName}\", module not found.");
}
public static void UnpatchModule(IArchiveModule module)
{
try
{
module.Patcher?.Unpatch();
module.OnExit();
}
catch (Exception ex)
{
ArchiveLogger.Error($"Error while trying to unpatch and/or run {nameof(IArchiveModule.OnExit)} in module \"{module?.GetType()?.FullName ?? "Unknown"}\"!");
ArchiveLogger.Exception(ex);
}
Modules.Remove(module);
_moduleTypes.Remove(module.GetType());
}
public static void OnSceneWasLoaded(int buildIndex, string sceneName)
{
foreach(var module in Modules)
{
try
{
module?.OnSceneWasLoaded(buildIndex, sceneName);
}
catch(Exception ex)
{
ArchiveLogger.Error($"Error while trying to run {nameof(OnSceneWasLoaded)} in module \"{module?.GetType()?.FullName ?? "Unknown"}\"!");
ArchiveLogger.Exception(ex);
}
}
}
public static void OnUpdate()
{
FeatureManager.Instance.OnUpdate();
}
public static void OnLateUpdate()
{
foreach (var module in Modules)
{
try
{
module?.OnLateUpdate();
}
catch (Exception ex)
{
ArchiveLogger.Error($"Error while trying to run {nameof(IArchiveModule.OnLateUpdate)} in module \"{module?.GetType()?.FullName ?? "Unknown"}\"!");
ArchiveLogger.Exception(ex);
}
}
FeatureManager.Instance.OnLateUpdate();
}
private static Assembly LoadMainArchiveModule(bool isIl2Cpp)
{
try
{
byte[] bytes;
if(isIl2Cpp)
{
ArchiveLogger.Notice("Loading IL2CPP module ...");
bytes = Utils.LoadFromResource("TheArchive.Resources.TheArchive.IL2CPP.dll");
if (bytes.Length < 100) throw new BadImageFormatException("IL2CPP Module is too small, this version might not contain the module build but a dummy dll!");
return Assembly.Load(bytes);
}
ArchiveLogger.Notice("Loading MONO module ...");
bytes = Utils.LoadFromResource("TheArchive.Resources.TheArchive.MONO.dll");
if (bytes.Length < 100) throw new BadImageFormatException("MONO Module is too small, this version might not contain the module build but a dummy dll!");
return Assembly.Load(bytes);
}
catch (Exception ex)
{
ArchiveLogger.Error($"Could not load {(isIl2Cpp ? "IL2CPP" : "MONO")} module! {ex}: {ex.Message}");
ArchiveLogger.Error($"{ex.StackTrace}");
return null;
}
}
}
}