// ---------[ VALUE DUPLICATION ]--------- public static EditableModProfile CreateFromProfile(ModProfile profile) { EditableModProfile retVal = new EditableModProfile(); retVal.ApplyBaseProfileChanges(profile); return(retVal); }
public static void GetModGalleryImage(ModProfile profile, string imageFileName, ModGalleryImageSize size, Action <Texture2D> onSuccess, Action <WebRequestError> onError) { var cachedImageTexture = CacheClient.LoadModGalleryImage(profile.id, imageFileName, size); if (cachedImageTexture != null) { if (onSuccess != null) { onSuccess(cachedImageTexture); } } else { // - Fetch from Server - var download = DownloadClient.DownloadModGalleryImage(profile, imageFileName, size); download.succeeded += (d) => { CacheClient.SaveModGalleryImage(profile.id, imageFileName, size, d.imageTexture); }; download.succeeded += (d) => onSuccess(d.imageTexture); download.failed += (d) => onError(d.error); } }
// ---------[ MOD IMAGES ]--------- // TODO(@jackson): Look at reconfiguring params public static void GetModLogo(ModProfile profile, LogoSize size, Action <Texture2D> onSuccess, Action <WebRequestError> onError) { Debug.Assert(onSuccess != null); var logoTexture = CacheClient.LoadModLogo(profile.id, size); if (logoTexture != null) { onSuccess(logoTexture); } var versionInfo = CacheClient.LoadModLogoVersionInfo(profile.id); if (logoTexture == null || versionInfo[size] != profile.logoLocator.GetFileName()) { var textureDownload = DownloadClient.DownloadModLogo(profile, size); textureDownload.succeeded += (d) => { CacheClient.SaveModLogo(profile.id, profile.logoLocator.GetFileName(), size, d.imageTexture); }; textureDownload.succeeded += (d) => onSuccess(d.imageTexture); textureDownload.failed += (d) => onError(d.error); } }
private void ModProfileSubmissionSucceeded(ModProfile updatedProfile, string profileFilePath) { // Update ScriptableModProfile profile.modId = updatedProfile.id; profile.editableModProfile = EditableModProfile.CreateFromProfile(updatedProfile); EditorUtility.SetDirty(profile); AssetDatabase.SaveAssets(); // Upload Build if (System.IO.File.Exists(buildFilePath)) { Action <WebRequestError> onSubmissionFailed = (e) => { EditorUtility.DisplayDialog("Upload Failed", "Failed to upload the mod build to the server.\n" + e.message, "Close"); isAwaitingServerResponse = false; }; ModManager.UploadModBinary_Unzipped(profile.modId, buildProfile, buildFilePath, true, mf => NotifySubmissionSucceeded(updatedProfile.name, updatedProfile.profileURL), onSubmissionFailed); } else { NotifySubmissionSucceeded(updatedProfile.name, updatedProfile.profileURL); } }
public static ModProfile LoadModProfile(int modId) { string profileFilePath = GenerateModProfileFilePath(modId); ModProfile profile = CacheClient.ReadJsonObjectFile <ModProfile>(profileFilePath); return(profile); }
public static IEnumerable <ModProfile> AllModProfiles() { string profileDirectory = CacheClient._cacheDirectory + "mods/"; if (Directory.Exists(profileDirectory)) { string[] modDirectories; try { modDirectories = Directory.GetDirectories(profileDirectory); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to read mod profile directory." + "\nDirectory: " + profileDirectory + "\n\n"); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); modDirectories = new string[0]; } foreach (string modDirectory in modDirectories) { ModProfile profile = CacheClient.ReadJsonObjectFile <ModProfile>(modDirectory + "/profile.data"); if (profile != null) { yield return(profile); } } } }
// TODO(@jackson): Take ModMediaCollection instead of profile public static ImageRequest DownloadModGalleryImage(ModProfile profile, string imageFileName, ModGalleryImageSize size) { Debug.Assert(profile != null, "[mod.io] Profile parameter cannot be null"); Debug.Assert(!String.IsNullOrEmpty(imageFileName), "[mod.io] imageFileName parameter needs to be not null or empty (used as identifier for gallery images)"); ImageRequest request = null; if (profile.media == null) { Debug.LogWarning("[mod.io] The given mod profile has no media information"); } else { GalleryImageLocator locator = profile.media.GetGalleryImageWithFileName(imageFileName); if (locator == null) { Debug.LogWarning("[mod.io] Unable to find mod gallery image with the file name \'" + imageFileName + "\' for the mod profile \'" + profile.name + "\'[" + profile.id + "]"); } else { request = DownloadClient.DownloadModGalleryImage(locator, size); } } return(request); }
/// <summary>Iterates through all of the mod profiles from the given offset.</summary> public static IEnumerable <ModProfile> IterateAllModProfilesFromOffset(int offset) { Debug.Assert(IOUtilities.CombinePath(CacheClient.cacheDirectory, "mods", "0") == CacheClient.GenerateModDirectoryPath(0), "[mod.io] This function relies on mod directory path being a generated in" + " a specific way. Changing CacheClient.GenerateModDirectoryPath()" + " necessitates changes in this function."); Debug.Assert(IOUtilities.CombinePath(CacheClient.GenerateModDirectoryPath(0), "profile.data") == CacheClient.GenerateModProfileFilePath(0), "[mod.io] This function relies on mod directory profile file path being a generated in" + " a specific way. Changing CacheClient.GenerateModProfileFilePath()" + " necessitates changes in this function."); string profileDirectory = IOUtilities.CombinePath(CacheClient.cacheDirectory, "mods"); if (Directory.Exists(profileDirectory)) { string[] modDirectories; try { modDirectories = Directory.GetDirectories(profileDirectory); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to read mod profile directory." + "\nDirectory: " + profileDirectory + "\n\n"); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); modDirectories = new string[0]; } int offsetDirCount = modDirectories.Length - offset; if (offsetDirCount > 0) { string[] offsetModDirectories = new string[offsetDirCount]; Array.Copy(modDirectories, offset, offsetModDirectories, 0, offsetDirCount); foreach (string modDirectory in offsetModDirectories) { string profilePath = IOUtilities.CombinePath(modDirectory, "profile.data"); ModProfile profile = IOUtilities.ReadJsonObjectFile <ModProfile>(profilePath); if (profile != null) { yield return(profile); } else { IOUtilities.DeleteFile(profilePath); } } } } }
/// <summary>Stores a mod's profile in the cache.</summary> public static bool SaveModProfile(ModProfile profile) { Debug.Assert(profile != null); string path = GenerateModProfileFilePath(profile.id); return(LocalDataStorage.WriteJSONFile(path, profile)); }
public static void SaveModProfile(ModProfile profile) { Debug.Assert(profile.id > 0, "[mod.io] Cannot cache a mod without a mod id"); CacheClient.WriteJsonObjectFile(GenerateModProfileFilePath(profile.id), profile); }
public static void DeleteInactiveBuilds(ModProfile profile) { string buildDir = CacheClient.GenerateModBuildsDirectoryPath(profile.id); string[] buildFilePaths = Directory.GetFiles(buildDir, "*.*"); foreach (string buildFile in buildFilePaths) { if (Path.GetFileNameWithoutExtension(buildFile) != profile.activeBuild.id.ToString()) { CacheClient.DeleteFile(buildFile); } } }
/// <summary>Map ModProfiles to id array.</summary> public static int[] MapProfileIds(IList <ModProfile> profiles) { if (profiles == null) { return(null); } int[] retVal = new int[profiles.Count]; for (int i = 0; i < profiles.Count; ++i) { ModProfile profile = profiles[i]; retVal[i] = (profile != null ? profile.id : ModProfile.NULL_ID); } return(retVal); }
public static ImageRequest DownloadModGalleryImage(ModProfile profile, string imageFileName, ModGalleryImageSize size) { ImageRequest request = new ImageRequest(); string imageURL = profile.media.GetGalleryImageWithFileName(imageFileName).GetSizeURL(size); UnityWebRequest webRequest = UnityWebRequest.Get(imageURL); webRequest.downloadHandler = new DownloadHandlerTexture(true); var operation = webRequest.SendWebRequest(); operation.completed += (o) => DownloadClient.OnImageDownloadCompleted(operation, request); return(request); }
// ---------[ IMAGE DOWNLOADS ]--------- public static ImageRequest DownloadModLogo(ModProfile profile, LogoSize size) { ImageRequest request = new ImageRequest(); request.isDone = false; string logoURL = profile.logoLocator.GetSizeURL(size); UnityWebRequest webRequest = UnityWebRequest.Get(logoURL); webRequest.downloadHandler = new DownloadHandlerTexture(true); var operation = webRequest.SendWebRequest(); operation.completed += (o) => DownloadClient.OnImageDownloadCompleted(operation, request); return(request); }
/// <summary>Iterates through all of the mod profiles from the given offset.</summary> public static IEnumerable <ModProfile> IterateAllModProfilesFromOffset(int offset) { string profileDirectory = IOUtilities.CombinePath(CacheClient.cacheDirectory, "mods"); if (Directory.Exists(profileDirectory)) { string[] modDirectories; try { modDirectories = Directory.GetDirectories(profileDirectory); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to read mod profile directory." + "\nDirectory: " + profileDirectory + "\n\n"); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); modDirectories = new string[0]; } int offsetDirCount = modDirectories.Length - offset; if (offsetDirCount > 0) { string[] offsetModDirectories = new string[offsetDirCount]; Array.Copy(modDirectories, offset, offsetModDirectories, 0, offsetDirCount); foreach (string modDirectory in offsetModDirectories) { string profilePath = IOUtilities.CombinePath(modDirectory, "profile.data"); ModProfile profile = IOUtilities.ReadJsonObjectFile <ModProfile>(profilePath); if (profile != null) { yield return(profile); } } } } }
// ------[ INITIALIZATION ]------ public void OnEnable(SerializedProperty serializedEditableModProfile, ModProfile baseProfile, UserProfile user) { this.profile = baseProfile; this.youtubeURLsProp = serializedEditableModProfile.FindPropertyRelative("youtubeURLs"); this.sketchfabURLsProp = serializedEditableModProfile.FindPropertyRelative("sketchfabURLs"); this.galleryImagesProp = serializedEditableModProfile.FindPropertyRelative("galleryImageLocators"); this.isYouTubeExpanded = false; this.isSketchFabExpanded = false; this.isImagesExpanded = false; // Initialize textureCache this.textureCache = new Dictionary <string, Texture2D>(galleryImagesProp.FindPropertyRelative("value").arraySize); for (int i = 0; i < galleryImagesProp.FindPropertyRelative("value").arraySize; ++i) { string imageFileName = GetGalleryImageFileName(i); string imageURL = GetGalleryImageSource(i); if (!String.IsNullOrEmpty(imageFileName) && !String.IsNullOrEmpty(imageURL)) { this.textureCache[imageFileName] = ApplicationImages.LoadingPlaceholder; Texture2D texture = CacheClient.ReadImageFile(imageURL); if (texture != null) { this.textureCache[imageFileName] = texture; } else { ModManager.GetModGalleryImage(baseProfile, imageFileName, IMAGE_PREVIEW_SIZE, (t) => { this.textureCache[imageFileName] = t; isRepaintRequired = true; }, WebRequestError.LogAsWarning); } } } }
// ------[ INITIALIZATION ]------ public void OnEnable(SerializedProperty serializedEditableModProfile, ModProfile baseProfile, UserProfile user) { this.editableProfileProperty = serializedEditableModProfile; this.profile = baseProfile; this.isUndoEnabled = (baseProfile != null); isTagsExpanded = false; isKVPsExpanded = false; // - Game Profile - ModManager.GetGameProfile((g) => { this.gameProfile = g; isRepaintRequired = true; }, null); // - Configure Properties - logoProperty = editableProfileProperty.FindPropertyRelative("logoLocator"); // - Load Textures - if (logoProperty.FindPropertyRelative("isDirty").boolValue == true) { logoLocation = logoProperty.FindPropertyRelative("value.url").stringValue; logoTexture = CacheClient.ReadImageFile(logoLocation); if (logoTexture != null) { lastLogoWriteTime = (new FileInfo(logoLocation)).LastWriteTime; } } else if (profile != null) { logoLocation = profile.logoLocator.GetSizeURL(LOGO_PREVIEW_SIZE); logoTexture = ApplicationImages.LoadingPlaceholder; ModManager.GetModLogo(profile, LOGO_PREVIEW_SIZE, (t) => { logoTexture = t; isRepaintRequired = true; }, WebRequestError.LogAsWarning); } else { logoLocation = string.Empty; logoTexture = null; } }
public static ModBinaryRequest GetActiveModBinary(ModProfile profile) { string zipFilePath = CacheClient.GenerateModBinaryZipFilePath(profile.id, profile.activeBuild.id); ModBinaryRequest request; if (File.Exists(zipFilePath)) { request = new ModBinaryRequest(); request.isDone = true; request.binaryFilePath = zipFilePath; } else { request = DownloadClient.DownloadModBinary(profile.id, profile.activeBuild.id, CacheClient.GenerateModBinaryZipFilePath(profile.id, profile.activeBuild.id)); request.succeeded += (r) => CacheClient.SaveModfile(r.modfile); } return(request); }
public void OnEnable(SerializedProperty editableProfileProperty, ModProfile baseProfile, UserProfile user) { }
protected virtual void LayoutProfileInitialization() { EditorGUILayout.LabelField("Initialize Mod Profile"); // ---[ DISPLAY ]--- EditorGUILayout.Space(); if (GUILayout.Button("Create New")) { EditorApplication.delayCall += () => { ScriptableModProfile smp = this.target as ScriptableModProfile; Undo.RecordObject(smp, "Initialize Mod Profile"); smp.modId = 0; smp.editableModProfile = new EditableModProfile(); OnDisable(); OnEnable(); isRepaintRequired = true; }; } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("---- OR ----"); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.LabelField("Load Existing Profile"); if (user == null) { EditorGUILayout.HelpBox("Log in required to load existing mods", MessageType.Info); if (GUILayout.Button("Log In to mod.io")) { LoginWindow.GetWindow <LoginWindow>("Login to mod.io"); } } else if (modOptions.Length > 0) { using (new EditorGUI.DisabledScope(isModListLoading)) { modInitializationOptionIndex = EditorGUILayout.Popup("Select Mod", modInitializationOptionIndex, modOptions, null); if (GUILayout.Button("Load")) { ModProfile profile = modList[modInitializationOptionIndex]; EditorApplication.delayCall += () => { ScriptableModProfile smp = this.target as ScriptableModProfile; Undo.RecordObject(smp, "Initialize Mod Profile"); smp.modId = profile.id; smp.editableModProfile = EditableModProfile.CreateFromProfile(profile); string smpFilePath = AssetDatabase.GetAssetPath(smp); string smpDir = System.IO.Path.GetDirectoryName(smpFilePath); int profileCount = System.IO.Directory.GetFiles(smpDir, profile.name + "*.asset").Length; string fileNameAddition = (profileCount > 0 ? " (" + profileCount.ToString() + ")" : ""); AssetDatabase.RenameAsset(smpFilePath, profile.name + fileNameAddition + ".asset"); OnDisable(); OnEnable(); isRepaintRequired = true; }; } } } else { EditorGUILayout.HelpBox("No loadable mod profiles detected.", MessageType.Info); } }
// ------[ INITIALIZATION ]------ protected virtual void OnEnable() { // Grab Serialized Properties serializedObject.Update(); modIdProperty = serializedObject.FindProperty("modId"); editableModProfileProperty = serializedObject.FindProperty("editableModProfile"); isModListLoading = false; profileViewParts = new IModProfileViewPart[] { new LoadingProfileViewPart() }; // Profile Initialization if (modIdProperty.intValue == ScriptableModProfile.UNINITIALIZED_MOD_ID) { this.profile = null; string userAuthToken = CacheClient.LoadAuthenticatedUserToken(); if (!String.IsNullOrEmpty(userAuthToken)) { APIClient.userAuthorizationToken = userAuthToken; this.isModListLoading = true; this.modOptions = new string[] { "Loading..." }; Action <WebRequestError> onError = (e) => { WebRequestError.LogAsWarning(e); isModListLoading = false; }; ModManager.GetAuthenticatedUserProfile((userProfile) => { this.user = userProfile; // - Find User Mods - Action <List <ModProfile> > onGetUserMods = (profiles) => { modInitializationOptionIndex = 0; modList = profiles.ToArray(); modOptions = new string[modList.Length]; for (int i = 0; i < modList.Length; ++i) { ModProfile mod = modList[i]; modOptions[i] = mod.name; } isModListLoading = false; }; ModManager.GetAuthenticatedUserMods(onGetUserMods, onError); }, onError); } else { this.modOptions = new string[0]; } modInitializationOptionIndex = 0; } else { // Initialize View profile = null; System.Action <ModProfile> onGetProfile = (p) => { profile = p; profileViewParts = CreateProfileViewParts(); foreach (IModProfileViewPart viewPart in profileViewParts) { viewPart.OnEnable(editableModProfileProperty, p, this.user); } ; profileGetErrorMessage = string.Empty; }; System.Action <WebRequestError> onGetProfileError = (e) => { profile = null; profileViewParts = CreateProfileViewParts(); foreach (IModProfileViewPart viewPart in profileViewParts) { viewPart.OnEnable(editableModProfileProperty, null, this.user); } ; profileGetErrorMessage = ("Unable to fetch the mod profile data on the server.\n" + e.message); }; ModManager.GetModProfile(modIdProperty.intValue, onGetProfile, onGetProfileError); } scrollPos = Vector2.zero; isProfileSyncing = false; // Events EditorApplication.update += OnUpdate; LoginWindow.userLoggedIn += OnUserLogin; }
private static void SubmitModProfileComponents(ModProfile profile, EditableModProfile modEdits, Action <ModProfile> modSubmissionSucceeded, Action <WebRequestError> modSubmissionFailed) { List <Action> submissionActions = new List <Action>(); int nextActionIndex = 0; Action <APIMessage> doNextSubmissionAction = (m) => { if (nextActionIndex < submissionActions.Count) { submissionActions[nextActionIndex++](); } }; // - Media - if (modEdits.logoLocator.isDirty || modEdits.youtubeURLs.isDirty || modEdits.sketchfabURLs.isDirty || modEdits.galleryImageLocators.isDirty) { var addMediaParameters = new AddModMediaParameters(); var deleteMediaParameters = new DeleteModMediaParameters(); if (modEdits.logoLocator.isDirty && File.Exists(modEdits.logoLocator.value.url)) { addMediaParameters.logo = BinaryUpload.Create(Path.GetFileName(modEdits.logoLocator.value.url), File.ReadAllBytes(modEdits.logoLocator.value.url)); } if (modEdits.youtubeURLs.isDirty) { var addedYouTubeLinks = new List <string>(modEdits.youtubeURLs.value); foreach (string youtubeLink in profile.media.youtubeURLs) { addedYouTubeLinks.Remove(youtubeLink); } addMediaParameters.youtube = addedYouTubeLinks.ToArray(); var removedTags = new List <string>(profile.media.youtubeURLs); foreach (string youtubeLink in modEdits.youtubeURLs.value) { removedTags.Remove(youtubeLink); } deleteMediaParameters.youtube = addedYouTubeLinks.ToArray(); } if (modEdits.sketchfabURLs.isDirty) { var addedSketchfabLinks = new List <string>(modEdits.sketchfabURLs.value); foreach (string sketchfabLink in profile.media.sketchfabURLs) { addedSketchfabLinks.Remove(sketchfabLink); } addMediaParameters.sketchfab = addedSketchfabLinks.ToArray(); var removedTags = new List <string>(profile.media.sketchfabURLs); foreach (string sketchfabLink in modEdits.sketchfabURLs.value) { removedTags.Remove(sketchfabLink); } deleteMediaParameters.sketchfab = addedSketchfabLinks.ToArray(); } if (modEdits.galleryImageLocators.isDirty) { var addedImageFilePaths = new List <string>(); foreach (var locator in modEdits.galleryImageLocators.value) { if (File.Exists(locator.url)) { addedImageFilePaths.Add(locator.url); } } // - Create Images.Zip - if (addedImageFilePaths.Count > 0) { string galleryZipLocation = Application.temporaryCachePath + "/modio/imageGallery_" + DateTime.Now.ToFileTime() + ".zip"; try { Directory.CreateDirectory(Path.GetDirectoryName(galleryZipLocation)); using (var zip = new Ionic.Zip.ZipFile()) { foreach (string imageFilePath in addedImageFilePaths) { zip.AddFile(imageFilePath); } zip.Save(galleryZipLocation); } var imageGalleryUpload = BinaryUpload.Create("images.zip", File.ReadAllBytes(galleryZipLocation)); addMediaParameters.galleryImages = imageGalleryUpload; } catch (Exception e) { Debug.LogError("[mod.io] Unable to zip image gallery prior to uploading.\n\n" + Utility.GenerateExceptionDebugString(e)); } } var removedImageFileNames = new List <string>(); foreach (var locator in profile.media.galleryImageLocators) { removedImageFileNames.Add(locator.fileName); } foreach (var locator in modEdits.galleryImageLocators.value) { removedImageFileNames.Remove(locator.fileName); } if (removedImageFileNames.Count > 0) { deleteMediaParameters.images = removedImageFileNames.ToArray(); } } if (addMediaParameters.stringValues.Count > 0 || addMediaParameters.binaryData.Count > 0) { submissionActions.Add(() => { APIClient.AddModMedia(profile.id, addMediaParameters, doNextSubmissionAction, modSubmissionFailed); }); } if (deleteMediaParameters.stringValues.Count > 0) { submissionActions.Add(() => { APIClient.DeleteModMedia(profile.id, deleteMediaParameters, () => doNextSubmissionAction(null), modSubmissionFailed); }); } } // - Tags - if (modEdits.tags.isDirty) { var removedTags = new List <string>(profile.tagNames); foreach (string tag in modEdits.tags.value) { removedTags.Remove(tag); } var addedTags = new List <string>(modEdits.tags.value); foreach (string tag in profile.tagNames) { addedTags.Remove(tag); } if (removedTags.Count > 0) { submissionActions.Add(() => { var parameters = new DeleteModTagsParameters(); parameters.tagNames = removedTags.ToArray(); APIClient.DeleteModTags(profile.id, parameters, doNextSubmissionAction, modSubmissionFailed); }); } if (addedTags.Count > 0) { submissionActions.Add(() => { var parameters = new AddModTagsParameters(); parameters.tagNames = addedTags.ToArray(); APIClient.AddModTags(profile.id, parameters, doNextSubmissionAction, modSubmissionFailed); }); } } // - Metadata KVP - if (modEdits.metadataKVPs.isDirty) { var removedKVPs = MetadataKVP.ArrayToDictionary(profile.metadataKVPs); var addedKVPs = MetadataKVP.ArrayToDictionary(modEdits.metadataKVPs.value); foreach (MetadataKVP kvp in modEdits.metadataKVPs.value) { string profileValue; // if edited kvp is exact match it's not removed if (removedKVPs.TryGetValue(kvp.key, out profileValue) && profileValue == kvp.value) { removedKVPs.Remove(kvp.key); } } foreach (MetadataKVP kvp in profile.metadataKVPs) { string editValue; // if profile kvp is exact match it's not new if (addedKVPs.TryGetValue(kvp.key, out editValue) && editValue == kvp.value) { addedKVPs.Remove(kvp.key); } } if (removedKVPs.Count > 0) { submissionActions.Add(() => { var parameters = new DeleteModKVPMetadataParameters(); parameters.metadataKeys = removedKVPs.Keys.ToArray(); APIClient.DeleteModKVPMetadata(profile.id, parameters, doNextSubmissionAction, modSubmissionFailed); }); } if (addedKVPs.Count > 0) { string[] addedKVPStrings = AddModKVPMetadataParameters.ConvertMetadataKVPsToAPIStrings(MetadataKVP.DictionaryToArray(addedKVPs)); submissionActions.Add(() => { var parameters = new AddModKVPMetadataParameters(); parameters.metadata = addedKVPStrings; APIClient.AddModKVPMetadata(profile.id, parameters, doNextSubmissionAction, modSubmissionFailed); }); } } // - Get Updated Profile - submissionActions.Add(() => APIClient.GetMod(profile.id, modSubmissionSucceeded, modSubmissionFailed)); // - Start submission chain - doNextSubmissionAction(new APIMessage()); }
/// <summary>Iterates through all of the mod profiles returning only those matching the id filter.</summary> public static IEnumerable <ModProfile> IterateFilteredModProfiles(IList <int> idFilter) { if (idFilter == null || idFilter.Count == 0) { yield break; } Debug.Assert(IOUtilities.CombinePath(CacheClient.cacheDirectory, "mods", "0") == CacheClient.GenerateModDirectoryPath(0), "[mod.io] This function relies on mod directory path being a generated in" + " a specific way. Changing CacheClient.GenerateModDirectoryPath()" + " necessitates changes in this function."); Debug.Assert(IOUtilities.CombinePath(CacheClient.GenerateModDirectoryPath(0), "profile.data") == CacheClient.GenerateModProfileFilePath(0), "[mod.io] This function relies on mod directory profile file path being a generated in" + " a specific way. Changing CacheClient.GenerateModProfileFilePath()" + " necessitates changes in this function."); string profileDirectory = IOUtilities.CombinePath(CacheClient.cacheDirectory, "mods"); if (Directory.Exists(profileDirectory)) { string[] modDirectories; try { modDirectories = Directory.GetDirectories(profileDirectory); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to read mod profile directory." + "\nDirectory: " + profileDirectory + "\n\n"); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); modDirectories = new string[0]; } foreach (string modDirectory in modDirectories) { string idPart = modDirectory.Substring(profileDirectory.Length + 1); int modId = ModProfile.NULL_ID; if (!int.TryParse(idPart, out modId)) { modId = ModProfile.NULL_ID; } if (idFilter.Contains(modId)) { string profilePath = IOUtilities.CombinePath(modDirectory, "profile.data"); ModProfile profile = IOUtilities.ReadJsonObjectFile <ModProfile>(profilePath); if (profile != null) { yield return(profile); } else { IOUtilities.DeleteFile(profilePath); } } } } }
/// <summary>Stores a mod's profile in the cache.</summary> public static bool SaveModProfile(ModProfile profile) { Debug.Assert(profile != null); return(IOUtilities.WriteJsonObjectFile(GenerateModProfileFilePath(profile.id), profile)); }
// ------[ GUI ]------ public override void OnInspectorGUI() { if (serializedObject.FindProperty("modId").intValue < 0) { LayoutProfileInitialization(); } else { serializedObject.Update(); bool isProfileSyncRequested = false; if (!String.IsNullOrEmpty(profileGetErrorMessage)) { EditorGUILayout.HelpBox(profileGetErrorMessage, MessageType.Warning); } using (new EditorGUI.DisabledScope(isProfileSyncing)) { if (profileViewParts != null && profileViewParts.Length > 0) { using (new EditorGUI.DisabledScope(modIdProperty.intValue == 0)) { string syncButtonText; if (profile == null) { syncButtonText = "Retry Fetching Server Data"; } else { syncButtonText = "Pull Server Data Updates"; } isProfileSyncRequested = GUILayout.Button(syncButtonText); EditorGUILayout.Space(); } } foreach (IModProfileViewPart viewPart in profileViewParts) { viewPart.OnGUI(); } serializedObject.ApplyModifiedProperties(); } if (isProfileSyncRequested) { isProfileSyncing = true; APIClient.GetMod(modIdProperty.intValue, (modProfile) => { CacheClient.SaveModProfile(modProfile); this.profile = modProfile; ScriptableModProfile smp = this.target as ScriptableModProfile; Undo.RecordObject(smp, "Update Mod Profile"); smp.editableModProfile.ApplyBaseProfileChanges(profile); isProfileSyncing = false; profileGetErrorMessage = null; this.OnDisable(); this.OnEnable(); }, (e) => { isProfileSyncing = false; profileGetErrorMessage = ("Unable to fetch the mod profile data on the server.\n" + e.message); }); } } isRepaintRequired = false; }
public void ApplyBaseProfileChanges(ModProfile profile) { if (!this.status.isDirty) { this.status.value = profile.status; } if (!this.visibility.isDirty) { this.visibility.value = profile.visibility; } if (!this.name.isDirty) { this.name.value = profile.name; } if (!this.nameId.isDirty) { this.nameId.value = profile.nameId; } if (!this.summary.isDirty) { this.summary.value = profile.summary; } if (!this.descriptionAsHTML.isDirty) { this.descriptionAsHTML.value = profile.descriptionAsHTML; } if (!this.homepageURL.isDirty) { this.homepageURL.value = profile.homepageURL; } if (!this.metadataBlob.isDirty) { this.metadataBlob.value = profile.metadataBlob; } if (!this.metadataBlob.isDirty) { this.metadataKVPs.value = profile.metadataKVPs; } if (!this.tags.isDirty) { this.tags.value = profile.tagNames.ToArray(); } // - Media - if (!this.logoLocator.isDirty) { this.logoLocator.value.fileName = profile.logoLocator.fileName; this.logoLocator.value.url = profile.logoLocator.GetURL(); } if (!this.youTubeURLs.isDirty) { this.youTubeURLs.value = profile.media.youTubeURLs; } if (!this.sketchfabURLs.isDirty) { this.sketchfabURLs.value = profile.media.sketchfabURLs; } if (!this.galleryImageLocators.isDirty) { Utility.SafeMapArraysOrZero(profile.media.galleryImageLocators, (l) => { return(ImageLocatorData.CreateFromImageLocator(l)); }, out this.galleryImageLocators.value); } }
/// <summary>Calculates changes made to a mod profile and submits them to the servers.</summary> private void SubmitModChanges_Internal(ModProfile profile) { // early outs if (profile == null) { this.SubmissionError_Local("Profile parameter passed to ModManager_SubmitModOperation.SubmitModChanges_Internal" + " was null. This was an unexpected error, please try submitting the mod again."); return; } if (profile.id == ModProfile.NULL_ID) { this.SubmissionError_Local("Profile parameter passed to ModManager_SubmitModOperation.SubmitModChanges_Internal" + " has a NULL_ID. This was an unexpected error, please try submitting the mod again."); return; } // --- Collect Submission Information --- this.modId = profile.id; // - Media - if (this.eModProfile.logoLocator.isDirty && !string.IsNullOrEmpty(this.eModProfile.logoLocator.value.url)) { this.logoPath = this.eModProfile.logoLocator.value.url; } if (this.eModProfile.galleryImageLocators.isDirty) { this.removedImageFileNames = new List <string>(); foreach (var locator in profile.media.galleryImageLocators) { this.removedImageFileNames.Add(locator.fileName); } foreach (var locator in this.eModProfile.galleryImageLocators.value) { this.removedImageFileNames.Remove(locator.fileName); } this.addedImageFilePaths = new List <string>(); foreach (var locator in this.eModProfile.galleryImageLocators.value) { this.addedImageFilePaths.Add(locator.url); } foreach (var locator in profile.media.galleryImageLocators) { this.addedImageFilePaths.Remove(locator.GetURL()); } } if (this.eModProfile.sketchfabURLs.isDirty) { this.removedSketchfabURLs = new List <string>(profile.media.sketchfabURLs); foreach (string url in this.eModProfile.sketchfabURLs.value) { this.removedSketchfabURLs.Remove(url); } this.addedSketchfabURLs = new List <string>(this.eModProfile.sketchfabURLs.value); foreach (string url in profile.media.sketchfabURLs) { this.addedSketchfabURLs.Remove(url); } } if (this.eModProfile.youTubeURLs.isDirty) { this.removedYouTubeURLs = new List <string>(profile.media.youTubeURLs); foreach (string url in this.eModProfile.youTubeURLs.value) { this.removedYouTubeURLs.Remove(url); } this.addedYouTubeURLs = new List <string>(this.eModProfile.youTubeURLs.value); foreach (string url in profile.media.youTubeURLs) { this.addedYouTubeURLs.Remove(url); } } // - Tags - if (this.eModProfile.tags.isDirty) { this.removedTags = new List <string>(profile.tagNames); foreach (string tag in this.eModProfile.tags.value) { this.removedTags.Remove(tag); } this.addedTags = new List <string>(this.eModProfile.tags.value); foreach (string tag in profile.tagNames) { this.addedTags.Remove(tag); } } // - Metadata KVP - if (this.eModProfile.metadataKVPs.isDirty) { this.removedKVPs = MetadataKVP.ArrayToDictionary(profile.metadataKVPs); foreach (MetadataKVP kvp in this.eModProfile.metadataKVPs.value) { string profileValue; // if edited kvp is exact match it's not removed if (this.removedKVPs.TryGetValue(kvp.key, out profileValue) && profileValue == kvp.value) { this.removedKVPs.Remove(kvp.key); } } this.addedKVPs = MetadataKVP.ArrayToDictionary(this.eModProfile.metadataKVPs.value); foreach (MetadataKVP kvp in profile.metadataKVPs) { string editValue; // if profile kvp is exact match it's not new if (this.addedKVPs.TryGetValue(kvp.key, out editValue) && editValue == kvp.value) { this.addedKVPs.Remove(kvp.key); } } } // - Start submission chain - if (this.logoPath != null) { DataStorage.ReadFile(this.logoPath, this.SubmitModChanges_Internal_OnReadLogo); } else { this.SubmitModChanges_Internal_ZipImages(); } }
/// <summary>Pulls the subscriptions from the server and stores the changes.</summary> public static void PullSubscriptionChanges(Action <List <ModProfile> > onSuccess, Action <WebRequestError> onError) { // early out if (LocalUser.AuthenticationState == AuthenticationState.NoToken) { if (onSuccess != null) { onSuccess(new List <ModProfile>(0)); } return; } // holding vars string userToken = LocalUser.OAuthToken; List <ModProfile> remoteOnlySubscriptions = new List <ModProfile>(); // set filter and initial pagination RequestFilter subscriptionFilter = new RequestFilter(); subscriptionFilter.AddFieldFilter(ModIO.API.GetUserSubscriptionsFilterFields.gameId, new EqualToFilter <int>(PluginSettings.GAME_ID)); APIPaginationParameters pagination = new APIPaginationParameters() { limit = APIPaginationParameters.LIMIT_MAX, offset = 0, }; // define actions Action getNextPage = null; Action <RequestPage <ModProfile> > onPageReceived = null; Action onAllPagesReceived = null; getNextPage = () => { APIClient.GetUserSubscriptions(subscriptionFilter, pagination, (response) => { onPageReceived(response); // check if all pages received if (response != null && response.items != null && response.items.Length > 0 && response.resultTotal > response.size + response.resultOffset) { pagination.offset = response.resultOffset + response.size; getNextPage(); } else { onAllPagesReceived(); if (onSuccess != null) { onSuccess(remoteOnlySubscriptions); } } }, (e) => { if (onError != null) { onError(e); } }); }; onPageReceived = (r) => { foreach (ModProfile profile in r.items) { if (profile != null) { remoteOnlySubscriptions.Add(profile); } } }; onAllPagesReceived = () => { if (userToken != LocalUser.OAuthToken) { return; } List <int> localOnlySubs = new List <int>(LocalUser.SubscribedModIds); // NOTE(@jackson): Unsub actions *should not* be found in activeUser.subscribedModIds foreach (int modId in LocalUser.QueuedUnsubscribes) { #if DEBUG if (localOnlySubs.Contains(modId)) { Debug.LogWarning("[mod.io] A locally subscribed mod was found in the" + " queuedUnsubscribes. This should not occur - please" + " ensure that any mod ids added to" + " activeUser.queuedUnsubscribes are removed from" + " activeUser.subscribedModIds or use" + " UserAccountManagement.UnsubscribeFromMod() to handle" + " this automatically."); } #endif localOnlySubs.Remove(modId); } List <int> newSubs = new List <int>(); // build new subs list for (int i = 0; i < remoteOnlySubscriptions.Count; ++i) { ModProfile profile = remoteOnlySubscriptions[i]; // remove if in queued subs LocalUser.QueuedSubscribes.Remove(profile.id); // if in unsub queue if (LocalUser.QueuedUnsubscribes.Contains(profile.id)) { remoteOnlySubscriptions.RemoveAt(i); --i; } // if locally subbed else if (localOnlySubs.Remove(profile.id)) { remoteOnlySubscriptions.RemoveAt(i); --i; } // if not locally subbed && if not in unsub queue else { newSubs.Add(profile.id); } } // -- update locally -- // remove new unsubs foreach (int modId in localOnlySubs) { // if not in sub queue if (!LocalUser.QueuedSubscribes.Contains(modId)) { LocalUser.SubscribedModIds.Remove(modId); } } LocalUser.SubscribedModIds.AddRange(newSubs); // save LocalUser.Save(); }; // get pages getNextPage(); }
// ---------[ IMAGE DOWNLOADS ]--------- public static ImageRequest DownloadModLogo(ModProfile profile, LogoSize size) { Debug.Assert(profile != null, "[mod.io] Profile parameter cannot be null"); return(DownloadImage(profile.logoLocator.GetSizeURL(size))); }