using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class OnlineAccountHandler : MonoBehaviour { [SerializeField] private NexusModController NMC; [SerializeField] private ModList ML; [SerializeField] private Toggle AutoLogin; [SerializeField] private string AccountName; [SerializeField] public string BearerID; [SerializeField] public bool isAdmin; [SerializeField] public string NMKey; [SerializeField] private RawImage ProfilePic; [SerializeField] private RawImage ProfilePicMain; [SerializeField] private RawImage ProfileBackground; [SerializeField] public bool Loggedin = false; [SerializeField] private string SettingsPath; [SerializeField] public string SecurityKey; [SerializeField] private Transform UserInfoContainer; [SerializeField] private GameObject Prefab; [SerializeField] private GameObject UserInfoBlob; [SerializeField] private List UserInfoList; [SerializeField] private List ThingsToHide; [SerializeField] private List ThingsToShow; private readonly string Key = "9b9128ba9409e791880c93f705f46952"; private readonly string URI = "schakenmods://ModHandler/Login/"; private string Refresh = ""; public string UserID = ""; private string UserURL; public SchakenMods.SMAccountInfo SMSettings; public NexusMods.NMProfile NMSettings; public Settings.AppSettings Setting; // Start is called before the first frame update void Start() { SettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Schaken-ModsĀ®/Singularity"); if (!Directory.Exists(SettingsPath)) Directory.CreateDirectory(SettingsPath); if (!File.Exists($"{SettingsPath}/Settings.json")) { var accountInfo = new Dictionary { { "access_token", "" }, { "refresh_token", "" }, { "StayLoggedIn", false }, }; var settings = new Dictionary { { "SMAccountInfo", accountInfo } }; string json = JsonConvert.SerializeObject(settings, Formatting.Indented); File.WriteAllText($"{SettingsPath}/Settings.json", json); } else { string json = File.ReadAllText($"{SettingsPath}/Settings.json"); JObject jsonObject = JObject.Parse(json); JToken nmProfileToken = jsonObject["NMProfile"]; JToken smProfileToken = jsonObject["SMAccountInfo"]; JToken AppSettings = jsonObject["appSettings"]; // Unused for now, Load App settings here NexusMods.NMProfile NM = JsonConvert.DeserializeObject(nmProfileToken.ToString()); SchakenMods.SMAccountInfo SM = JsonConvert.DeserializeObject(smProfileToken.ToString()); if (AppSettings != null) { Settings.AppSettings Settings = JsonConvert.DeserializeObject(AppSettings.ToString()); if (Settings != null) { Setting = Settings; Controller Con = gameObject.GetComponent(); if (Setting.DownloadsFolder != null) { Con.SetDownloadsFolder(Setting.DownloadsFolder); } if (Setting.ModListOrder != null) { ML.AZOrder = Setting.ModListOrder == 0; ML.DateOrder = Setting.ModListOrder == 1; if (!ML.AZOrder && !ML.DateOrder) ML.AZOrder = true; } else { ML.AZOrder = true; Setting.ModListOrder = 0; } } else { string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+@"\Downloads"; Settings = new() { DownloadsFolder = path, ModListOrder = 0 }; Setting = Settings; } } NMSettings = NM; if (NMSettings != null) { NMKey = NMSettings.Key; NMC.GetUserInfo(NM); } SMSettings = SM; bool Auto = AutoLogin.isOn; if (SM != null) { Debug.Log("SM != null"); BearerID = SM.Access_Token; Refresh = SM.Refresh_Token; if (SM.Stay_Logged_In) { AutoLogin.isOn = true; } Auto = AutoLogin.isOn; if (SM.Expire < DateTime.Now) { Auto = false; AutoLogin.isOn = false; } } else { Debug.Log("SM is null"); } ML.StartList(); if (Auto) { RefreshToken(Refresh); } } } public void SaveSettings(string JSON = "", int A = 2) { if (A == 0) { SMSettings = JsonConvert.DeserializeObject(JSON); } else if (A == 1) { NMSettings = JsonConvert.DeserializeObject(JSON); NMKey = NMSettings.Key; } else if (A == 2) { // We grab all settings on start, so just set the setting, then save here. // Setting = JsonConvert.DeserializeObject(JSON); // gameObject.GetComponent().SetDownloadsFolder(Setting.DownloadsFolder); // Setting.ModListOrder = ML.ResetOrder(); } var wrapper = new { SMAccountInfo = SMSettings, NMProfile = NMSettings, appSettings = Setting }; string updatedJson = JsonConvert.SerializeObject(wrapper, Formatting.Indented); File.WriteAllText($"{SettingsPath}/Settings.json", updatedJson); } public void LogMeIn(bool TF = false) { if (Refresh == "" || TF || BearerID == null) { string scope = "scope"; System.Random random = new(); SecurityKey = random.Next(10000000, 99999999).ToString(); string A = $"https://schaken-mods.com/oauth/authorize?client_id={Key}&response_type=code&state={SecurityKey}&redirect_uri={URI}&scope={scope}"; Application.OpenURL(A); } else { RefreshToken(Refresh); } } // Update is called once per frame void Update() { } private void RefreshToken(string token = "") { Dictionary content = new() { { "grant_type", "refresh_token" }, { "redirect_uri", URI }, { "client_id", Key }, { "refresh_token", token }, { "scope", "scope" } }; StartCoroutine(PassLoginInfo(content)); } public void Login(string A) { Dictionary content = new() { //Fill key and value { "grant_type", "authorization_code" }, { "redirect_uri", URI }, { "client_id", Key }, { "code", A }, { "scope", "scope" }, { "code_verifier", SecurityKey } }; StartCoroutine(PassLoginInfo(content)); } private IEnumerator PassLoginInfo(Dictionary content) { using (UnityWebRequest www = UnityWebRequest.Post("https://schaken-mods.com/oauth/token/", content)) { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.ConnectionError) { string resultContent = www.downloadHandler.text; if (resultContent.Contains("\"access_token\":\"")) { // Debug.Log($"SM User Info Returned: \n{resultContent}"); SchakenMods.SMAccountInfo OAuth = JsonConvert.DeserializeObject(resultContent); SMSettings = OAuth; OAuth.Expire = DateTime.Now.AddSeconds(OAuth.Expires_In); OAuth.Stay_Logged_In = AutoLogin.isOn; string updatedJson = JsonConvert.SerializeObject(OAuth, Formatting.Indented); SaveSettings(updatedJson, 0); BearerID = OAuth.Access_Token; StartCoroutine(GetUserInfo()); } else { LogMeIn(true); } } else { Debug.LogError("Token Failed: " + www.error); } } } private IEnumerator GetUserInfo() { var url = "https://schaken-mods.com/api/core/me"; using (UnityWebRequest uwr = UnityWebRequest.Get(url)) { uwr.SetRequestHeader("Authorization", "Bearer " + BearerID); yield return uwr.SendWebRequest(); if (uwr.result == UnityWebRequest.Result.ConnectionError) { Debug.LogError("Error While Sending for User info: " + uwr.error); } else { string result = uwr.downloadHandler.text; // Debug.Log($"SM User Info Returned: \n{result}"); string FullTXT = result.Replace(@"\", string.Empty); string wrappedResult = "{ \"author\": " + result + " }"; SchakenMods Author = JsonConvert.DeserializeObject(wrappedResult); isAdmin = Author.Author.PrimaryGroup.Name == "Administrators"; if (isAdmin) { gameObject.GetComponent().ActivateAdmin(); } if (FullTXT.Contains("photoUrl") == true) { Loggedin = true; UserInfoBlob.SetActive(true); StartCoroutine(LoadCurrentImage(Author.Author.PhotoUrl, ProfilePic)); StartCoroutine(LoadCurrentImage(Author.Author.PhotoUrl, ProfilePicMain)); StartCoroutine(LoadCurrentImage(Author.Author.CoverPhotoUrl, ProfileBackground)); UserURL = Author.Author.ProfileUrl; UserID = Author.Author.Id.ToString(); Dictionary UserInfo = new() { { "Name", Author.Author.Name }, { "Joined", FormatDate(Author.Author.Joined.ToString()) }, { "Reputation", Author.Author.ReputationPoints.ToString() }, { "Posts", Author.Author.Posts.ToString() }, { "Last Activity", FormatDate(Author.Author.LastActivity.ToString()) }, { "Profile Views", Author.Author.ProfileViews.ToString() }, { "Birthday", (Author.Author.Birthday == null) ? "Undefined" : FormatDate(Author.Author.Birthday.ToString()) }, { "Achievements", Author.Author.AchievementsPoints.ToString() }, { "Last Visit", FormatDate(Author.Author.LastVisit.ToString()) }, { "Last Post", FormatDate(Author.Author.LastPost.ToString()) } }; foreach (KeyValuePair info in UserInfo) { GameObject NewInfo = Instantiate(Prefab, UserInfoContainer); NewInfo.GetComponent().FillMe(info.Key, info.Value); UserInfoList.Add(NewInfo); } for (int i = 0; i < ThingsToHide.Count; i++) { ThingsToHide[i].SetActive(false); } for (int i = 0; i < ThingsToShow.Count; i++) { ThingsToShow[i].SetActive(true); } } } } } private string S(string A) { return A; } public IEnumerator LoadCurrentImage(string imagePath, RawImage TheImage) { using (UnityWebRequest WWW = UnityWebRequestTexture.GetTexture(imagePath)) { yield return WWW.SendWebRequest(); if (WWW.result != UnityWebRequest.Result.ConnectionError) { TheImage.texture = DownloadHandlerTexture.GetContent(WWW); TheImage.SetNativeSize(); TheImage.SizeToParent(); } } } public string FormatDate(string dateString) { if (dateString != null) { if (dateString.Contains(" ")) { return dateString.Split(" ")[0]; } return dateString; } return "Unknown"; } public void GoToProfile() { Application.OpenURL(UserURL); } }