Decompiled source of RepoRPG KeepProgress v1.0.0

RepoRPGKeepProgress.dll

Decompiled 6 hours ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using RepoRPG;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace RepoRPGKeepProgress;

[BepInPlugin("playw.reporpg.keepprogress", "RepoRPG Keep Progress", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class KeepProgressPlugin : BaseUnityPlugin
{
	public const string Guid = "playw.reporpg.keepprogress";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<bool> KeepClasses;

	internal static ConfigEntry<bool> KeepAttributes;

	internal static ConfigEntry<bool> KeepGear;

	internal static ConfigEntry<bool> KeepPerks;

	internal static ConfigEntry<bool> ForgetSavedProgress;

	internal static string Folder;

	internal static PropertyInfo StoreData;

	internal static PropertyInfo StoreOwner;

	internal static PropertyInfo StoreKey;

	internal static MethodInfo IsTempKey;

	internal static MethodInfo Normalize;

	internal static MethodInfo JsonSerialize;

	internal static MethodInfo JsonDeserialize;

	private void Awake()
	{
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_027c: Expected O, but got Unknown
		//IL_029c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a9: Expected O, but got Unknown
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d7: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep your RepoRPG run progress when a run ends (everyone dies) and a new run starts at level 1.");
		KeepClasses = ((BaseUnityPlugin)this).Config.Bind<bool>("Keep", "ClassLevels", true, "Keep every class's level, XP and spent talent points (skill points), plus your selected class.");
		KeepAttributes = ((BaseUnityPlugin)this).Config.Bind<bool>("Keep", "Attributes", true, "Keep your attribute points.");
		KeepGear = ((BaseUnityPlugin)this).Config.Bind<bool>("Keep", "Gear", false, "Also keep your gear inventory and what you have equipped (makes new runs much easier).");
		KeepPerks = ((BaseUnityPlugin)this).Config.Bind<bool>("Keep", "Perks", false, "Also keep the perks you picked during the run.");
		ForgetSavedProgress = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ForgetSavedProgress", false, "Set to true to delete the kept copy next time the game starts (for a true fresh start). Turns itself back off.");
		Folder = Path.Combine(Paths.ConfigPath, "RepoRPG-KeepProgress");
		Directory.CreateDirectory(Folder);
		if (ForgetSavedProgress.Value)
		{
			string[] files = Directory.GetFiles(Folder, "*.json");
			foreach (string path in files)
			{
				File.Delete(path);
			}
			ForgetSavedProgress.Value = false;
			Log.LogInfo((object)"Kept progress deleted (ForgetSavedProgress was on).");
		}
		Assembly assembly = typeof(RunSave).Assembly;
		Type type = assembly.GetType("RepoRPG.RunStore", throwOnError: true);
		Type type2 = assembly.GetType("RepoRPG.Json", throwOnError: true);
		StoreData = type.GetProperty("Data", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		StoreOwner = type.GetProperty("OwnerId", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		StoreKey = type.GetProperty("RunKey", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		IsTempKey = type.GetMethod("IsTempKey", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		Normalize = type.GetMethod("Normalize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		JsonSerialize = type2.GetMethod("Serialize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		JsonDeserialize = type2.GetMethod("Deserialize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).MakeGenericMethod(typeof(RunSave));
		if (StoreData == null || StoreOwner == null || StoreKey == null || IsTempKey == null || Normalize == null || JsonSerialize == null || JsonDeserialize == null)
		{
			Log.LogError((object)"This RepoRPG version doesn't match what Keep Progress expects; the add-on is off.");
			return;
		}
		Harmony val = new Harmony("playw.reporpg.keepprogress");
		val.Patch((MethodBase)AccessTools.Method(type, "SaveNow", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(KeepProgressPlugin), "AfterSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.Method(type, "Use", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(KeepProgressPlugin), "AfterUse", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Log.LogInfo((object)("RepoRPG Keep Progress loaded. Kept copies live in " + Folder));
	}

	private static void AfterSave(object __instance)
	{
		try
		{
			if (!Enabled.Value)
			{
				return;
			}
			object? value = StoreData.GetValue(__instance, null);
			RunSave val = (RunSave)((value is RunSave) ? value : null);
			string text = StoreOwner.GetValue(__instance, null) as string;
			string key = StoreKey.GetValue(__instance, null) as string;
			if (val == null || string.IsNullOrEmpty(text) || IsTemp(key))
			{
				return;
			}
			string text2 = PathFor(text);
			RunSave val2 = Read(text2);
			bool flag = val2 != null && val2.runId == val.runId && !string.IsNullOrEmpty(val.runId);
			if (val2 == null || flag || Score(val) >= Score(val2))
			{
				string contents = (string)JsonSerialize.Invoke(null, new object[2] { val, false });
				string text3 = text2 + ".tmp";
				File.WriteAllText(text3, contents);
				if (File.Exists(text2))
				{
					File.Delete(text2);
				}
				File.Move(text3, text2);
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Couldn't keep a copy of your progress: " + ex.Message));
		}
	}

	private static void AfterUse(object __instance, string ownerId, string runKey, RunSave data)
	{
		try
		{
			if (!Enabled.Value || data != null || IsTemp(runKey) || string.IsNullOrEmpty(ownerId))
			{
				return;
			}
			object? value = StoreData.GetValue(__instance, null);
			RunSave val = (RunSave)((value is RunSave) ? value : null);
			RunSave val2 = Read(PathFor(ownerId));
			if (val == null || val2 == null || Score(val2) <= 0 || Score(val) >= Score(val2))
			{
				return;
			}
			if (KeepClasses.Value)
			{
				val.classes = val2.classes ?? new List<ClassProgress>();
				val.treeVersion = val2.treeVersion;
				if (!string.IsNullOrEmpty(val2.selectedClass))
				{
					val.selectedClass = val2.selectedClass;
				}
			}
			if (KeepAttributes.Value)
			{
				val.attributes = val2.attributes ?? new List<NodeRank>();
				val.bonusAttributePoints = val2.bonusAttributePoints;
				val.attributeVersion = val2.attributeVersion;
			}
			if (KeepGear.Value)
			{
				val.inventory = val2.inventory;
				val.equipped = val2.equipped;
				val.starterGiven = val2.starterGiven;
				val.starterFor = val2.starterFor;
			}
			if (KeepPerks.Value)
			{
				val.perks = val2.perks;
			}
			Normalize.Invoke(null, new object[1] { val });
			int num = 0;
			if (val.classes != null)
			{
				foreach (ClassProgress @class in val.classes)
				{
					if (@class.classId == val.selectedClass)
					{
						num = @class.level;
					}
				}
			}
			Log.LogInfo((object)("New run: put back your progress (" + ((val.classes != null) ? val.classes.Count : 0) + " class(es), '" + val.selectedClass + "' Lv " + num + ")."));
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Couldn't put your progress back: " + ex.Message));
		}
	}

	private static bool IsTemp(string key)
	{
		if (string.IsNullOrEmpty(key))
		{
			return true;
		}
		return (bool)IsTempKey.Invoke(null, new object[1] { key });
	}

	private static string PathFor(string owner)
	{
		char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
		foreach (char oldChar in invalidFileNameChars)
		{
			owner = owner.Replace(oldChar, '_');
		}
		return Path.Combine(Folder, owner + ".json");
	}

	private static RunSave Read(string path)
	{
		try
		{
			if (!File.Exists(path))
			{
				return null;
			}
			object? obj = JsonDeserialize.Invoke(null, new object[1] { File.ReadAllText(path) });
			return (RunSave)((obj is RunSave) ? obj : null);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Kept progress file unreadable (" + path + "): " + ex.Message));
			return null;
		}
	}

	private static long Score(RunSave s)
	{
		long num = 0L;
		if (s.classes != null)
		{
			foreach (ClassProgress @class in s.classes)
			{
				num += (long)Math.Max(0, @class.level - 1) * 100000L + @class.xp;
			}
		}
		if (s.attributes != null)
		{
			foreach (NodeRank attribute in s.attributes)
			{
				num += attribute.rank;
			}
		}
		return num;
	}
}