summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/ModHelpers
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <Pathoschild@users.noreply.github.com>2018-11-19 13:48:19 -0500
committerJesse Plamondon-Willard <Pathoschild@users.noreply.github.com>2018-11-19 13:48:19 -0500
commit593723b7940ba72a786fc4c7366c56f9813d977b (patch)
tree4d23fbef5bc5a20115f10ca04ae3379df78cc8e1 /src/SMAPI/Framework/ModHelpers
parent4f28ea33bd7cc65485402c5e85259083e86b49e1 (diff)
parent3dc27a5681dcfc4ae30e95570d9966f2e14a4dd7 (diff)
downloadSMAPI-593723b7940ba72a786fc4c7366c56f9813d977b.tar.gz
SMAPI-593723b7940ba72a786fc4c7366c56f9813d977b.tar.bz2
SMAPI-593723b7940ba72a786fc4c7366c56f9813d977b.zip
Merge branch 'develop' into stable
Diffstat (limited to 'src/SMAPI/Framework/ModHelpers')
-rw-r--r--src/SMAPI/Framework/ModHelpers/CommandHelper.cs15
-rw-r--r--src/SMAPI/Framework/ModHelpers/DataHelper.cs166
-rw-r--r--src/SMAPI/Framework/ModHelpers/ModHelper.cs26
-rw-r--r--src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs8
-rw-r--r--src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs42
5 files changed, 232 insertions, 25 deletions
diff --git a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs
index bdedb07c..5a3304f3 100644
--- a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs
@@ -8,8 +8,8 @@ namespace StardewModdingAPI.Framework.ModHelpers
/*********
** Accessors
*********/
- /// <summary>The friendly mod name for this instance.</summary>
- private readonly string ModName;
+ /// <summary>The mod using this instance.</summary>
+ private readonly IModMetadata Mod;
/// <summary>Manages console commands.</summary>
private readonly CommandManager CommandManager;
@@ -19,13 +19,12 @@ namespace StardewModdingAPI.Framework.ModHelpers
** Public methods
*********/
/// <summary>Construct an instance.</summary>
- /// <param name="modID">The unique ID of the relevant mod.</param>
- /// <param name="modName">The friendly mod name for this instance.</param>
+ /// <param name="mod">The mod using this instance.</param>
/// <param name="commandManager">Manages console commands.</param>
- public CommandHelper(string modID, string modName, CommandManager commandManager)
- : base(modID)
+ public CommandHelper(IModMetadata mod, CommandManager commandManager)
+ : base(mod?.Manifest?.UniqueID ?? "SMAPI")
{
- this.ModName = modName;
+ this.Mod = mod;
this.CommandManager = commandManager;
}
@@ -38,7 +37,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <exception cref="ArgumentException">There's already a command with that name.</exception>
public ICommandHelper Add(string name, string documentation, Action<string, string[]> callback)
{
- this.CommandManager.Add(this.ModName, name, documentation, callback);
+ this.CommandManager.Add(this.Mod, name, documentation, callback);
return this;
}
diff --git a/src/SMAPI/Framework/ModHelpers/DataHelper.cs b/src/SMAPI/Framework/ModHelpers/DataHelper.cs
new file mode 100644
index 00000000..e5100aed
--- /dev/null
+++ b/src/SMAPI/Framework/ModHelpers/DataHelper.cs
@@ -0,0 +1,166 @@
+using System;
+using System.IO;
+using Newtonsoft.Json;
+using StardewModdingAPI.Toolkit.Serialisation;
+using StardewModdingAPI.Toolkit.Utilities;
+using StardewValley;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides an API for reading and storing local mod data.</summary>
+ internal class DataHelper : BaseHelper, IDataHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Encapsulates SMAPI's JSON file parsing.</summary>
+ private readonly JsonHelper JsonHelper;
+
+ /// <summary>The absolute path to the mod folder.</summary>
+ private readonly string ModFolderPath;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
+ /// <param name="modFolderPath">The absolute path to the mod folder.</param>
+ /// <param name="jsonHelper">The absolute path to the mod folder.</param>
+ public DataHelper(string modID, string modFolderPath, JsonHelper jsonHelper)
+ : base(modID)
+ {
+ this.ModFolderPath = modFolderPath;
+ this.JsonHelper = jsonHelper;
+ }
+
+ /****
+ ** JSON file
+ ****/
+ /// <summary>Read data from a JSON file in the mod's folder.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="path">The file path relative to the mod folder.</param>
+ /// <returns>Returns the deserialised model, or <c>null</c> if the file doesn't exist or is empty.</returns>
+ /// <exception cref="InvalidOperationException">The <paramref name="path"/> is not relative or contains directory climbing (../).</exception>
+ public TModel ReadJsonFile<TModel>(string path) where TModel : class
+ {
+ if (!PathUtilities.IsSafeRelativePath(path))
+ throw new InvalidOperationException($"You must call {nameof(IModHelper.Data)}.{nameof(this.ReadJsonFile)} with a relative path.");
+
+ path = Path.Combine(this.ModFolderPath, PathUtilities.NormalisePathSeparators(path));
+ return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data)
+ ? data
+ : null;
+ }
+
+ /// <summary>Save data to a JSON file in the mod's folder.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="path">The file path relative to the mod folder.</param>
+ /// <param name="data">The arbitrary data to save.</param>
+ /// <exception cref="InvalidOperationException">The <paramref name="path"/> is not relative or contains directory climbing (../).</exception>
+ public void WriteJsonFile<TModel>(string path, TModel data) where TModel : class
+ {
+ if (!PathUtilities.IsSafeRelativePath(path))
+ throw new InvalidOperationException($"You must call {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteJsonFile)} with a relative path (without directory climbing).");
+
+ path = Path.Combine(this.ModFolderPath, PathUtilities.NormalisePathSeparators(path));
+ this.JsonHelper.WriteJsonFile(path, data);
+ }
+
+ /****
+ ** Save file
+ ****/
+ /// <summary>Read arbitrary data stored in the current save slot. This is only possible if a save has been loaded.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="key">The unique key identifying the data.</param>
+ /// <returns>Returns the parsed data, or <c>null</c> if the entry doesn't exist or is empty.</returns>
+ /// <exception cref="InvalidOperationException">The player hasn't loaded a save file yet or isn't the main player.</exception>
+ public TModel ReadSaveData<TModel>(string key) where TModel : class
+ {
+ if (!Context.IsSaveLoaded)
+ throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.ReadSaveData)} when a save file isn't loaded.");
+ if (!Context.IsMainPlayer)
+ throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.ReadSaveData)} because this isn't the main player. (Save files are stored on the main player's computer.)");
+
+ return Game1.CustomData.TryGetValue(this.GetSaveFileKey(key), out string value)
+ ? this.JsonHelper.Deserialise<TModel>(value)
+ : null;
+ }
+
+ /// <summary>Save arbitrary data to the current save slot. This is only possible if a save has been loaded, and the data will be lost if the player exits without saving the current day.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="key">The unique key identifying the data.</param>
+ /// <param name="data">The arbitrary data to save.</param>
+ /// <exception cref="InvalidOperationException">The player hasn't loaded a save file yet or isn't the main player.</exception>
+ public void WriteSaveData<TModel>(string key, TModel data) where TModel : class
+ {
+ if (!Context.IsSaveLoaded)
+ throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteSaveData)} when a save file isn't loaded.");
+ if (!Context.IsMainPlayer)
+ throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.ReadSaveData)} because this isn't the main player. (Save files are stored on the main player's computer.)");
+
+ string internalKey = this.GetSaveFileKey(key);
+ if (data != null)
+ Game1.CustomData[internalKey] = this.JsonHelper.Serialise(data, Formatting.None);
+ else
+ Game1.CustomData.Remove(internalKey);
+ }
+
+ /****
+ ** Global app data
+ ****/
+ /// <summary>Read arbitrary data stored on the local computer, synchronised by GOG/Steam if applicable.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="key">The unique key identifying the data.</param>
+ /// <returns>Returns the parsed data, or <c>null</c> if the entry doesn't exist or is empty.</returns>
+ public TModel ReadGlobalData<TModel>(string key) where TModel : class
+ {
+ string path = this.GetGlobalDataPath(key);
+ return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data)
+ ? data
+ : null;
+ }
+
+ /// <summary>Save arbitrary data to the local computer, synchronised by GOG/Steam if applicable.</summary>
+ /// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
+ /// <param name="key">The unique key identifying the data.</param>
+ /// <param name="data">The arbitrary data to save.</param>
+ public void WriteGlobalData<TModel>(string key, TModel data) where TModel : class
+ {
+ string path = this.GetGlobalDataPath(key);
+ if (data != null)
+ this.JsonHelper.WriteJsonFile(path, data);
+ else
+ File.Delete(path);
+ }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get the unique key for a save file data entry.</summary>
+ /// <param name="key">The unique key identifying the data.</param>
+ private string GetSaveFileKey(string key)
+ {
+ this.AssertSlug(key, nameof(key));
+ return $"smapi/mod-data/{this.ModID}/{key}".ToLower();
+ }
+
+ /// <summary>Get the absolute path for a global data file.</summary>
+ /// <param name="key">The unique key identifying the data.</param>
+ private string GetGlobalDataPath(string key)
+ {
+ this.AssertSlug(key, nameof(key));
+ return Path.Combine(Constants.SavesPath, ".smapi", "mod-data", this.ModID.ToLower(), $"{key}.json".ToLower());
+ }
+
+ /// <summary>Assert that a key contains only characters that are safe in all contexts.</summary>
+ /// <param name="key">The key to check.</param>
+ /// <param name="paramName">The argument name for any assertion error.</param>
+ private void AssertSlug(string key, string paramName)
+ {
+ if (!PathUtilities.IsSlug(key))
+ throw new ArgumentException("The data key is invalid (keys must only contain letters, numbers, underscores, periods, or hyphens).", paramName);
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/ModHelpers/ModHelper.cs b/src/SMAPI/Framework/ModHelpers/ModHelper.cs
index 0ba258b4..5e190e55 100644
--- a/src/SMAPI/Framework/ModHelpers/ModHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/ModHelper.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using StardewModdingAPI.Events;
using StardewModdingAPI.Framework.Input;
using StardewModdingAPI.Toolkit.Serialisation;
@@ -16,11 +15,8 @@ namespace StardewModdingAPI.Framework.ModHelpers
/*********
** Properties
*********/
- /// <summary>Encapsulates SMAPI's JSON file parsing.</summary>
- private readonly JsonHelper JsonHelper;
-
/// <summary>The content packs loaded for this mod.</summary>
- private readonly IContentPack[] ContentPacks;
+ private readonly Lazy<IContentPack[]> ContentPacks;
/// <summary>Create a transitional content pack.</summary>
private readonly Func<string, IManifest, IContentPack> CreateContentPack;
@@ -35,12 +31,18 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <summary>The full path to the mod's folder.</summary>
public string DirectoryPath { get; }
+ /// <summary>Encapsulates SMAPI's JSON file parsing.</summary>
+ private readonly JsonHelper JsonHelper;
+
/// <summary>Manages access to events raised by SMAPI, which let your mod react when something happens in the game.</summary>
public IModEvents Events { get; }
/// <summary>An API for loading content assets.</summary>
public IContentHelper Content { get; }
+ /// <summary>An API for reading and writing persistent mod data.</summary>
+ public IDataHelper Data { get; }
+
/// <summary>An API for checking and changing input state.</summary>
public IInputHelper Input { get; }
@@ -71,6 +73,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <param name="events">Manages access to events raised by SMAPI.</param>
/// <param name="contentHelper">An API for loading content assets.</param>
/// <param name="commandHelper">An API for managing console commands.</param>
+ /// <param name="dataHelper">An API for reading and writing persistent mod data.</param>
/// <param name="modRegistry">an API for fetching metadata about loaded mods.</param>
/// <param name="reflectionHelper">An API for accessing private game code.</param>
/// <param name="multiplayer">Provides multiplayer utilities.</param>
@@ -80,7 +83,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <param name="deprecationManager">Manages deprecation warnings.</param>
/// <exception cref="ArgumentNullException">An argument is null or empty.</exception>
/// <exception cref="InvalidOperationException">The <paramref name="modDirectory"/> path does not exist on disk.</exception>
- public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, SInputState inputState, IModEvents events, IContentHelper contentHelper, ICommandHelper commandHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, IMultiplayerHelper multiplayer, ITranslationHelper translationHelper, IEnumerable<IContentPack> contentPacks, Func<string, IManifest, IContentPack> createContentPack, DeprecationManager deprecationManager)
+ public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, SInputState inputState, IModEvents events, IContentHelper contentHelper, ICommandHelper commandHelper, IDataHelper dataHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, IMultiplayerHelper multiplayer, ITranslationHelper translationHelper, Func<IContentPack[]> contentPacks, Func<string, IManifest, IContentPack> createContentPack, DeprecationManager deprecationManager)
: base(modID)
{
// validate directory
@@ -93,13 +96,14 @@ namespace StardewModdingAPI.Framework.ModHelpers
this.DirectoryPath = modDirectory;
this.JsonHelper = jsonHelper ?? throw new ArgumentNullException(nameof(jsonHelper));
this.Content = contentHelper ?? throw new ArgumentNullException(nameof(contentHelper));
+ this.Data = dataHelper ?? throw new ArgumentNullException(nameof(dataHelper));
this.Input = new InputHelper(modID, inputState);
this.ModRegistry = modRegistry ?? throw new ArgumentNullException(nameof(modRegistry));
this.ConsoleCommands = commandHelper ?? throw new ArgumentNullException(nameof(commandHelper));
this.Reflection = reflectionHelper ?? throw new ArgumentNullException(nameof(reflectionHelper));
this.Multiplayer = multiplayer ?? throw new ArgumentNullException(nameof(multiplayer));
this.Translation = translationHelper ?? throw new ArgumentNullException(nameof(translationHelper));
- this.ContentPacks = contentPacks.ToArray();
+ this.ContentPacks = new Lazy<IContentPack[]>(contentPacks);
this.CreateContentPack = createContentPack;
this.DeprecationManager = deprecationManager;
this.Events = events;
@@ -113,7 +117,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
public TConfig ReadConfig<TConfig>()
where TConfig : class, new()
{
- TConfig config = this.ReadJsonFile<TConfig>("config.json") ?? new TConfig();
+ TConfig config = this.Data.ReadJsonFile<TConfig>("config.json") ?? new TConfig();
this.WriteConfig(config); // create file or fill in missing fields
return config;
}
@@ -124,7 +128,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
public void WriteConfig<TConfig>(TConfig config)
where TConfig : class, new()
{
- this.WriteJsonFile("config.json", config);
+ this.Data.WriteJsonFile("config.json", config);
}
/****
@@ -134,6 +138,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <typeparam name="TModel">The model type.</typeparam>
/// <param name="path">The file path relative to the mod directory.</param>
/// <returns>Returns the deserialised model, or <c>null</c> if the file doesn't exist or is empty.</returns>
+ [Obsolete("Use " + nameof(ModHelper.Data) + "." + nameof(IDataHelper.ReadJsonFile) + " instead")]
public TModel ReadJsonFile<TModel>(string path)
where TModel : class
{
@@ -147,6 +152,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <typeparam name="TModel">The model type.</typeparam>
/// <param name="path">The file path relative to the mod directory.</param>
/// <param name="model">The model to save.</param>
+ [Obsolete("Use " + nameof(ModHelper.Data) + "." + nameof(IDataHelper.WriteJsonFile) + " instead")]
public void WriteJsonFile<TModel>(string path, TModel model)
where TModel : class
{
@@ -197,7 +203,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <summary>Get all content packs loaded for this mod.</summary>
public IEnumerable<IContentPack> GetContentPacks()
{
- return this.ContentPacks;
+ return this.ContentPacks.Value;
}
/****
diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
index 008a80f5..5cc2a20f 100644
--- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
@@ -40,17 +40,17 @@ namespace StardewModdingAPI.Framework.ModHelpers
}
/// <summary>Get metadata for all loaded mods.</summary>
- public IEnumerable<IManifest> GetAll()
+ public IEnumerable<IModInfo> GetAll()
{
- return this.Registry.GetAll().Select(p => p.Manifest);
+ return this.Registry.GetAll();
}
/// <summary>Get metadata for a loaded mod.</summary>
/// <param name="uniqueID">The mod's unique ID.</param>
/// <returns>Returns the matching mod's metadata, or <c>null</c> if not found.</returns>
- public IManifest Get(string uniqueID)
+ public IModInfo Get(string uniqueID)
{
- return this.Registry.Get(uniqueID)?.Manifest;
+ return this.Registry.Get(uniqueID);
}
/// <summary>Get whether a mod has been loaded.</summary>
diff --git a/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs b/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs
index c449a51b..eedad0bc 100644
--- a/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs
@@ -1,4 +1,6 @@
+using System;
using System.Collections.Generic;
+using StardewModdingAPI.Framework.Networking;
using StardewValley;
namespace StardewModdingAPI.Framework.ModHelpers
@@ -25,16 +27,50 @@ namespace StardewModdingAPI.Framework.ModHelpers
this.Multiplayer = multiplayer;
}
+ /// <summary>Get a new multiplayer ID.</summary>
+ public long GetNewID()
+ {
+ return this.Multiplayer.getNewID();
+ }
+
/// <summary>Get the locations which are being actively synced from the host.</summary>
public IEnumerable<GameLocation> GetActiveLocations()
{
return this.Multiplayer.activeLocations();
}
- /// <summary>Get a new multiplayer ID.</summary>
- public long GetNewID()
+ /// <summary>Get a connected player.</summary>
+ /// <param name="id">The player's unique ID.</param>
+ /// <returns>Returns the connected player, or <c>null</c> if no such player is connected.</returns>
+ public IMultiplayerPeer GetConnectedPlayer(long id)
{
- return this.Multiplayer.getNewID();
+ return this.Multiplayer.Peers.TryGetValue(id, out MultiplayerPeer peer)
+ ? peer
+ : null;
+ }
+
+ /// <summary>Get all connected players.</summary>
+ public IEnumerable<IMultiplayerPeer> GetConnectedPlayers()
+ {
+ return this.Multiplayer.Peers.Values;
+ }
+
+ /// <summary>Send a message to mods installed by connected players.</summary>
+ /// <typeparam name="TMessage">The data type. This can be a class with a default constructor, or a value type.</typeparam>
+ /// <param name="message">The data to send over the network.</param>
+ /// <param name="messageType">A message type which receiving mods can use to decide whether it's the one they want to handle, like <c>SetPlayerLocation</c>. This doesn't need to be globally unique, since mods should check the originating mod ID.</param>
+ /// <param name="modIDs">The mod IDs which should receive the message on the destination computers, or <c>null</c> for all mods. Specifying mod IDs is recommended to improve performance, unless it's a general-purpose broadcast.</param>
+ /// <param name="playerIDs">The <see cref="Farmer.UniqueMultiplayerID" /> values for the players who should receive the message, or <c>null</c> for all players. If you don't need to broadcast to all players, specifying player IDs is recommended to reduce latency.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="message"/> or <paramref name="messageType" /> is null.</exception>
+ public void SendMessage<TMessage>(TMessage message, string messageType, string[] modIDs = null, long[] playerIDs = null)
+ {
+ this.Multiplayer.BroadcastModMessage(
+ message: message,
+ messageType: messageType,
+ fromModID: this.ModID,
+ toModIDs: modIDs,
+ toPlayerIDs: playerIDs
+ );
}
}
}