diff options
author | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-05-01 18:16:09 -0400 |
---|---|---|
committer | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-05-01 18:16:09 -0400 |
commit | c8ad50dad1d706a1901798f9396f6becfea36c0e (patch) | |
tree | 28bd818a5db39ec5ece1bd141a28de955950463b /src/SMAPI.Web | |
parent | 451b70953ff4c0b1b27ae0de203ad99379b45b2a (diff) | |
parent | f78093bdb58d477b400cde3f19b70ffd6ddf833d (diff) | |
download | SMAPI-c8ad50dad1d706a1901798f9396f6becfea36c0e.tar.gz SMAPI-c8ad50dad1d706a1901798f9396f6becfea36c0e.tar.bz2 SMAPI-c8ad50dad1d706a1901798f9396f6becfea36c0e.zip |
Merge branch 'develop' into stable
Diffstat (limited to 'src/SMAPI.Web')
87 files changed, 2284 insertions, 719 deletions
diff --git a/src/SMAPI.Web/BackgroundService.cs b/src/SMAPI.Web/BackgroundService.cs index 64bd5ca5..49356f76 100644 --- a/src/SMAPI.Web/BackgroundService.cs +++ b/src/SMAPI.Web/BackgroundService.cs @@ -19,13 +19,17 @@ namespace StardewModdingAPI.Web ** Fields *********/ /// <summary>The background task server.</summary> - private static BackgroundJobServer JobServer; + private static BackgroundJobServer? JobServer; /// <summary>The cache in which to store wiki metadata.</summary> - private static IWikiCacheRepository WikiCache; + private static IWikiCacheRepository? WikiCache; /// <summary>The cache in which to store mod data.</summary> - private static IModCacheRepository ModCache; + private static IModCacheRepository? ModCache; + + /// <summary>Whether the service has been started.</summary> + [MemberNotNullWhen(true, nameof(BackgroundService.JobServer), nameof(BackgroundService.WikiCache), nameof(BackgroundService.ModCache))] + private static bool IsStarted { get; set; } /********* @@ -59,6 +63,8 @@ namespace StardewModdingAPI.Web RecurringJob.AddOrUpdate(() => BackgroundService.UpdateWikiAsync(), "*/10 * * * *"); // every 10 minutes RecurringJob.AddOrUpdate(() => BackgroundService.RemoveStaleModsAsync(), "0 * * * *"); // hourly + BackgroundService.IsStarted = true; + return Task.CompletedTask; } @@ -66,6 +72,8 @@ namespace StardewModdingAPI.Web /// <param name="cancellationToken">Tracks whether the shutdown process should no longer be graceful.</param> public async Task StopAsync(CancellationToken cancellationToken) { + BackgroundService.IsStarted = false; + if (BackgroundService.JobServer != null) await BackgroundService.JobServer.WaitForShutdownAsync(cancellationToken); } @@ -73,6 +81,8 @@ namespace StardewModdingAPI.Web /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { + BackgroundService.IsStarted = false; + BackgroundService.JobServer?.Dispose(); } @@ -83,6 +93,9 @@ namespace StardewModdingAPI.Web [AutomaticRetry(Attempts = 3, DelaysInSeconds = new[] { 30, 60, 120 })] public static async Task UpdateWikiAsync() { + if (!BackgroundService.IsStarted) + throw new InvalidOperationException($"Must call {nameof(BackgroundService.StartAsync)} before scheduling tasks."); + WikiModList wikiCompatList = await new ModToolkit().GetWikiCompatibilityListAsync(); BackgroundService.WikiCache.SaveWikiData(wikiCompatList.StableVersion, wikiCompatList.BetaVersion, wikiCompatList.Mods); } @@ -90,6 +103,9 @@ namespace StardewModdingAPI.Web /// <summary>Remove mods which haven't been requested in over 48 hours.</summary> public static Task RemoveStaleModsAsync() { + if (!BackgroundService.IsStarted) + throw new InvalidOperationException($"Must call {nameof(BackgroundService.StartAsync)} before scheduling tasks."); + BackgroundService.ModCache.RemoveStaleMods(TimeSpan.FromHours(48)); return Task.CompletedTask; } diff --git a/src/SMAPI.Web/Controllers/IndexController.cs b/src/SMAPI.Web/Controllers/IndexController.cs index f2f4c342..522d77cd 100644 --- a/src/SMAPI.Web/Controllers/IndexController.cs +++ b/src/SMAPI.Web/Controllers/IndexController.cs @@ -57,8 +57,8 @@ namespace StardewModdingAPI.Web.Controllers { // choose versions ReleaseVersion[] versions = await this.GetReleaseVersionsAsync(); - ReleaseVersion stableVersion = versions.LastOrDefault(version => !version.IsForDevs); - ReleaseVersion stableVersionForDevs = versions.LastOrDefault(version => version.IsForDevs); + ReleaseVersion? stableVersion = versions.LastOrDefault(version => !version.IsForDevs); + ReleaseVersion? stableVersionForDevs = versions.LastOrDefault(version => version.IsForDevs); // render view IndexVersionModel stableVersionModel = stableVersion != null @@ -89,14 +89,14 @@ namespace StardewModdingAPI.Web.Controllers entry.AbsoluteExpiration = DateTimeOffset.UtcNow.Add(this.CacheTime); // get latest stable release - GitRelease release = await this.GitHub.GetLatestReleaseAsync(this.RepositoryName, includePrerelease: false); + GitRelease? release = await this.GitHub.GetLatestReleaseAsync(this.RepositoryName, includePrerelease: false); // strip 'noinclude' blocks from release description if (release != null) { - HtmlDocument doc = new HtmlDocument(); + HtmlDocument doc = new(); doc.LoadHtml(release.Body); - foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*[@class='noinclude']")?.ToArray() ?? new HtmlNode[0]) + foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*[@class='noinclude']")?.ToArray() ?? Array.Empty<HtmlNode>()) node.Remove(); release.Body = doc.DocumentNode.InnerHtml.Trim(); } @@ -111,7 +111,7 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Get a parsed list of SMAPI downloads for a release.</summary> /// <param name="release">The GitHub release.</param> - private IEnumerable<ReleaseVersion> ParseReleaseVersions(GitRelease release) + private IEnumerable<ReleaseVersion> ParseReleaseVersions(GitRelease? release) { if (release?.Assets == null) yield break; @@ -122,7 +122,7 @@ namespace StardewModdingAPI.Web.Controllers continue; Match match = Regex.Match(asset.FileName, @"SMAPI-(?<version>[\d\.]+(?:-.+)?)-installer(?<forDevs>-for-developers)?.zip"); - if (!match.Success || !SemanticVersion.TryParse(match.Groups["version"].Value, out ISemanticVersion version)) + if (!match.Success || !SemanticVersion.TryParse(match.Groups["version"].Value, out ISemanticVersion? version)) continue; bool isForDevs = match.Groups["forDevs"].Success; diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index e06c1236..c551a805 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -64,7 +64,7 @@ namespace StardewModdingAPI.Web.Controllers [Route("json/{schemaName}")] [Route("json/{schemaName}/{id}")] [Route("json/{schemaName}/{id}/{operation}")] - public async Task<ViewResult> Index(string schemaName = null, string id = null, string operation = null) + public async Task<ViewResult> Index(string? schemaName = null, string? id = null, string? operation = null) { // parse arguments schemaName = this.NormalizeSchemaName(schemaName); @@ -79,7 +79,7 @@ namespace StardewModdingAPI.Web.Controllers return this.View("Index", result); // fetch raw JSON - StoredFileInfo file = await this.Storage.GetAsync(id, renew); + StoredFileInfo file = await this.Storage.GetAsync(id!, renew); if (string.IsNullOrWhiteSpace(file.Content)) return this.View("Index", result.SetUploadError("The JSON file seems to be empty.")); result.SetContent(file.Content, expiry: file.Expiry, uploadWarning: file.Warning); @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Web.Controllers } catch (JsonReaderException ex) { - return this.View("Index", result.AddErrors(new JsonValidatorErrorModel(ex.LineNumber, ex.Path, ex.Message, ErrorType.None))); + return this.View("Index", result.AddErrors(new JsonValidatorErrorModel(ex.LineNumber, ex.Path!, ex.Message, ErrorType.None))); } // format JSON @@ -119,10 +119,10 @@ namespace StardewModdingAPI.Web.Controllers // load schema JSchema schema; { - FileInfo schemaFile = this.FindSchemaFile(schemaName); + FileInfo? schemaFile = this.FindSchemaFile(schemaName); if (schemaFile == null) return this.View("Index", result.SetParseError($"Invalid schema '{schemaName}'.")); - schema = JSchema.Parse(System.IO.File.ReadAllText(schemaFile.FullName)); + schema = JSchema.Parse(await System.IO.File.ReadAllTextAsync(schemaFile.FullName)); } // get format doc URL @@ -142,7 +142,7 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Save raw JSON data.</summary> [HttpPost, AllowLargePosts] [Route("json")] - public async Task<ActionResult> PostAsync(JsonValidatorRequestModel request) + public async Task<ActionResult> PostAsync(JsonValidatorRequestModel? request) { if (request == null) return this.View("Index", this.GetModel(null, null, isEditView: true).SetUploadError("The request seems to be invalid.")); @@ -151,7 +151,7 @@ namespace StardewModdingAPI.Web.Controllers string schemaName = this.NormalizeSchemaName(request.SchemaName); // get raw text - string input = request.Content; + string? input = request.Content; if (string.IsNullOrWhiteSpace(input)) return this.View("Index", this.GetModel(null, schemaName, isEditView: true).SetUploadError("The JSON file seems to be empty.")); @@ -161,7 +161,7 @@ namespace StardewModdingAPI.Web.Controllers return this.View("Index", this.GetModel(result.ID, schemaName, isEditView: true).SetContent(input, null).SetUploadError(result.UploadError)); // redirect to view - return this.Redirect(this.Url.PlainAction("Index", "JsonValidator", new { schemaName = schemaName, id = result.ID })); + return this.Redirect(this.Url.PlainAction("Index", "JsonValidator", new { schemaName, id = result.ID })!); } @@ -172,14 +172,14 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="pasteID">The stored file ID.</param> /// <param name="schemaName">The schema name with which the JSON was validated.</param> /// <param name="isEditView">Whether to show the edit view.</param> - private JsonValidatorModel GetModel(string pasteID, string schemaName, bool isEditView) + private JsonValidatorModel GetModel(string? pasteID, string? schemaName, bool isEditView) { return new JsonValidatorModel(pasteID, schemaName, this.SchemaFormats, isEditView); } /// <summary>Get a normalized schema name, or the <see cref="DefaultSchemaID"/> if blank.</summary> /// <param name="schemaName">The raw schema name to normalize.</param> - private string NormalizeSchemaName(string schemaName) + private string NormalizeSchemaName(string? schemaName) { schemaName = schemaName?.Trim().ToLower(); return !string.IsNullOrWhiteSpace(schemaName) @@ -189,7 +189,7 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Get the schema file given its unique ID.</summary> /// <param name="id">The schema ID.</param> - private FileInfo FindSchemaFile(string id) + private FileInfo? FindSchemaFile(string? id) { // normalize ID id = id?.Trim().ToLower(); @@ -197,7 +197,7 @@ namespace StardewModdingAPI.Web.Controllers return null; // get matching file - DirectoryInfo schemaDir = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schemas")); + DirectoryInfo schemaDir = new(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schemas")); foreach (FileInfo file in schemaDir.EnumerateFiles("*.json")) { if (file.Name.Equals($"{id}.json")) @@ -214,13 +214,13 @@ namespace StardewModdingAPI.Web.Controllers // skip through transparent errors if (this.IsTransparentError(error)) { - foreach (var model in error.ChildErrors.SelectMany(this.GetErrorModels)) + foreach (JsonValidatorErrorModel model in error.ChildErrors.SelectMany(this.GetErrorModels)) yield return model; yield break; } // get message - string message = this.GetOverrideError(error); + string? message = this.GetOverrideError(error); if (message == null || message == this.TransparentToken) message = this.FlattenErrorMessage(error); @@ -234,7 +234,7 @@ namespace StardewModdingAPI.Web.Controllers private string FlattenErrorMessage(ValidationError error, int indent = 0) { // get override - string message = this.GetOverrideError(error); + string? message = this.GetOverrideError(error); if (message != null && message != this.TransparentToken) return message; @@ -255,7 +255,7 @@ namespace StardewModdingAPI.Web.Controllers break; case ErrorType.Required: - message = $"Missing required fields: {string.Join(", ", (List<string>)error.Value)}."; + message = $"Missing required fields: {string.Join(", ", (List<string>)error.Value!)}."; break; } @@ -272,7 +272,7 @@ namespace StardewModdingAPI.Web.Controllers if (!error.ChildErrors.Any()) return false; - string @override = this.GetOverrideError(error); + string? @override = this.GetOverrideError(error); return @override == this.TransparentToken || (error.ErrorType == ErrorType.Then && @override == null); @@ -280,18 +280,18 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Get an override error from the JSON schema, if any.</summary> /// <param name="error">The schema validation error.</param> - private string GetOverrideError(ValidationError error) + private string? GetOverrideError(ValidationError error) { - string GetRawOverrideError() + string? GetRawOverrideError() { // get override errors - IDictionary<string, string> errors = this.GetExtensionField<Dictionary<string, string>>(error.Schema, "@errorMessages"); + IDictionary<string, string?>? errors = this.GetExtensionField<Dictionary<string, string?>>(error.Schema, "@errorMessages"); if (errors == null) return null; - errors = new Dictionary<string, string>(errors, StringComparer.OrdinalIgnoreCase); + errors = new Dictionary<string, string?>(errors, StringComparer.OrdinalIgnoreCase); // match error by type and message - foreach ((string target, string errorMessage) in errors) + foreach ((string target, string? errorMessage) in errors) { if (!target.Contains(":")) continue; @@ -302,7 +302,7 @@ namespace StardewModdingAPI.Web.Controllers } // match by type - return errors.TryGetValue(error.ErrorType.ToString(), out string message) + return errors.TryGetValue(error.ErrorType.ToString(), out string? message) ? message?.Trim() : null; } @@ -315,15 +315,12 @@ namespace StardewModdingAPI.Web.Controllers /// <typeparam name="T">The field type.</typeparam> /// <param name="schema">The schema whose extension fields to search.</param> /// <param name="key">The case-insensitive field key.</param> - private T GetExtensionField<T>(JSchema schema, string key) + private T? GetExtensionField<T>(JSchema schema, string key) { - if (schema.ExtensionData != null) + foreach ((string curKey, JToken value) in schema.ExtensionData) { - foreach ((string curKey, JToken value) in schema.ExtensionData) - { - if (curKey.Equals(key, StringComparison.OrdinalIgnoreCase)) - return value.ToObject<T>(); - } + if (curKey.Equals(key, StringComparison.OrdinalIgnoreCase)) + return value.ToObject<T>(); } return default; @@ -331,7 +328,7 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Format a schema value for display.</summary> /// <param name="value">The value to format.</param> - private string FormatValue(object value) + private string FormatValue(object? value) { return value switch { diff --git a/src/SMAPI.Web/Controllers/LogParserController.cs b/src/SMAPI.Web/Controllers/LogParserController.cs index db53d942..33af5a81 100644 --- a/src/SMAPI.Web/Controllers/LogParserController.cs +++ b/src/SMAPI.Web/Controllers/LogParserController.cs @@ -45,7 +45,7 @@ namespace StardewModdingAPI.Web.Controllers [HttpGet] [Route("log")] [Route("log/{id}")] - public async Task<ActionResult> Index(string id = null, LogViewFormat format = LogViewFormat.Default, bool renew = false) + public async Task<ActionResult> Index(string? id = null, LogViewFormat format = LogViewFormat.Default, bool renew = false) { // fresh page if (string.IsNullOrWhiteSpace(id)) @@ -69,7 +69,7 @@ namespace StardewModdingAPI.Web.Controllers case LogViewFormat.RawDownload: { - string content = file.Error ?? file.Content; + string content = file.Error ?? file.Content ?? string.Empty; return this.File(Encoding.UTF8.GetBytes(content), "plain/text", $"SMAPI log ({id}).txt"); } @@ -87,7 +87,7 @@ namespace StardewModdingAPI.Web.Controllers public async Task<ActionResult> PostAsync() { // get raw log text - string input = this.Request.Form["input"].FirstOrDefault(); + string? input = this.Request.Form["input"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(input)) return this.View("Index", this.GetModel(null, uploadError: "The log file seems to be empty.")); @@ -97,7 +97,7 @@ namespace StardewModdingAPI.Web.Controllers return this.View("Index", this.GetModel(null, uploadError: uploadResult.UploadError)); // redirect to view - return this.Redirect(this.Url.PlainAction("Index", "LogParser", new { id = uploadResult.ID })); + return this.Redirect(this.Url.PlainAction("Index", "LogParser", new { id = uploadResult.ID })!); } @@ -109,7 +109,7 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="expiry">When the uploaded file will no longer be available.</param> /// <param name="uploadWarning">A non-blocking warning while uploading the log.</param> /// <param name="uploadError">An error which occurred while uploading the log.</param> - private LogParserModel GetModel(string pasteID, DateTime? expiry = null, string uploadWarning = null, string uploadError = null) + private LogParserModel GetModel(string? pasteID, DateTimeOffset? expiry = null, string? uploadWarning = null, string? uploadError = null) { Platform? platform = this.DetectClientPlatform(); diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index 37d763cc..401bba4f 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -76,10 +77,10 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="model">The mod search criteria.</param> /// <param name="version">The requested API version.</param> [HttpPost] - public async Task<IEnumerable<ModEntryModel>> PostAsync([FromBody] ModSearchModel model, [FromRoute] string version) + public async Task<IEnumerable<ModEntryModel>> PostAsync([FromBody] ModSearchModel? model, [FromRoute] string version) { if (model?.Mods == null) - return new ModEntryModel[0]; + return Array.Empty<ModEntryModel>(); ModUpdateCheckConfig config = this.Config.Value; @@ -92,16 +93,16 @@ namespace StardewModdingAPI.Web.Controllers continue; // special case: if this is an update check for the official SMAPI repo, check the Nexus mod page for beta versions - if (mod.ID == config.SmapiInfo.ID && mod.UpdateKeys?.Any(key => key == config.SmapiInfo.DefaultUpdateKey) == true && mod.InstalledVersion?.IsPrerelease() == true) - mod.UpdateKeys = mod.UpdateKeys.Concat(config.SmapiInfo.AddBetaUpdateKeys).ToArray(); + if (mod.ID == config.SmapiInfo.ID && mod.UpdateKeys.Any(key => key == config.SmapiInfo.DefaultUpdateKey) && mod.InstalledVersion?.IsPrerelease() == true) + mod.AddUpdateKeys(config.SmapiInfo.AddBetaUpdateKeys); // fetch result ModEntryModel result = await this.GetModData(mod, wikiData, model.IncludeExtendedMetadata, model.ApiVersion); if (!model.IncludeExtendedMetadata && (model.ApiVersion == null || mod.InstalledVersion == null)) { - var errors = new List<string>(result.Errors); - errors.Add($"This API can't suggest an update because {nameof(model.ApiVersion)} or {nameof(mod.InstalledVersion)} are null, and you didn't specify {nameof(model.IncludeExtendedMetadata)} to get other info. See the SMAPI technical docs for usage."); - result.Errors = errors.ToArray(); + result.Errors = result.Errors + .Concat(new[] { $"This API can't suggest an update because {nameof(model.ApiVersion)} or {nameof(mod.InstalledVersion)} are null, and you didn't specify {nameof(model.IncludeExtendedMetadata)} to get other info. See the SMAPI technical docs for usage." }) + .ToArray(); } mods[mod.ID] = result; @@ -121,26 +122,26 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="includeExtendedMetadata">Whether to include extended metadata for each mod.</param> /// <param name="apiVersion">The SMAPI version installed by the player.</param> /// <returns>Returns the mod data if found, else <c>null</c>.</returns> - private async Task<ModEntryModel> GetModData(ModSearchEntryModel search, WikiModEntry[] wikiData, bool includeExtendedMetadata, ISemanticVersion apiVersion) + private async Task<ModEntryModel> GetModData(ModSearchEntryModel search, WikiModEntry[] wikiData, bool includeExtendedMetadata, ISemanticVersion? apiVersion) { // cross-reference data - ModDataRecord record = this.ModDatabase.Get(search.ID); - WikiModEntry wikiEntry = wikiData.FirstOrDefault(entry => entry.ID.Contains(search.ID.Trim(), StringComparer.OrdinalIgnoreCase)); + ModDataRecord? record = this.ModDatabase.Get(search.ID); + WikiModEntry? wikiEntry = wikiData.FirstOrDefault(entry => entry.ID.Contains(search.ID.Trim(), StringComparer.OrdinalIgnoreCase)); UpdateKey[] updateKeys = this.GetUpdateKeys(search.UpdateKeys, record, wikiEntry).ToArray(); - ModOverrideConfig overrides = this.Config.Value.ModOverrides.FirstOrDefault(p => p.ID.Equals(search.ID?.Trim(), StringComparison.OrdinalIgnoreCase)); + ModOverrideConfig? overrides = this.Config.Value.ModOverrides.FirstOrDefault(p => p.ID.Equals(search.ID.Trim(), StringComparison.OrdinalIgnoreCase)); bool allowNonStandardVersions = overrides?.AllowNonStandardVersions ?? false; // SMAPI versions with a '-beta' tag indicate major changes that may need beta mod versions. // This doesn't apply to normal prerelease versions which have an '-alpha' tag. - bool isSmapiBeta = apiVersion.IsPrerelease() && apiVersion.PrereleaseTag.StartsWith("beta"); + bool isSmapiBeta = apiVersion != null && apiVersion.IsPrerelease() && apiVersion.PrereleaseTag.StartsWith("beta"); // get latest versions - ModEntryModel result = new ModEntryModel { ID = search.ID }; + ModEntryModel result = new(search.ID); IList<string> errors = new List<string>(); - ModEntryVersionModel main = null; - ModEntryVersionModel optional = null; - ModEntryVersionModel unofficial = null; - ModEntryVersionModel unofficialForBeta = null; + ModEntryVersionModel? main = null; + ModEntryVersionModel? optional = null; + ModEntryVersionModel? unofficial = null; + ModEntryVersionModel? unofficialForBeta = null; foreach (UpdateKey updateKey in updateKeys) { // validate update key @@ -160,9 +161,9 @@ namespace StardewModdingAPI.Web.Controllers // handle versions if (this.IsNewer(data.Version, main?.Version)) - main = new ModEntryVersionModel(data.Version, data.Url); + main = new ModEntryVersionModel(data.Version, data.Url!); if (this.IsNewer(data.PreviewVersion, optional?.Version)) - optional = new ModEntryVersionModel(data.PreviewVersion, data.Url); + optional = new ModEntryVersionModel(data.PreviewVersion, data.Url!); } // get unofficial version @@ -170,7 +171,7 @@ namespace StardewModdingAPI.Web.Controllers unofficial = new ModEntryVersionModel(wikiEntry.Compatibility.UnofficialVersion, $"{this.Url.PlainAction("Index", "Mods", absoluteUrl: true)}#{wikiEntry.Anchor}"); // get unofficial version for beta - if (wikiEntry?.HasBetaInfo == true) + if (wikiEntry is { HasBetaInfo: true }) { if (wikiEntry.BetaCompatibility.Status == WikiCompatibilityStatus.Unofficial) { @@ -196,13 +197,13 @@ namespace StardewModdingAPI.Web.Controllers if (overrides?.SetUrl != null) { if (main != null) - main.Url = overrides.SetUrl; + main = new(main.Version, overrides.SetUrl); if (optional != null) - optional.Url = overrides.SetUrl; + optional = new(optional.Version, overrides.SetUrl); } // get recommended update (if any) - ISemanticVersion installedVersion = this.ModSites.GetMappedVersion(search.InstalledVersion?.ToString(), wikiEntry?.Overrides?.ChangeLocalVersions, allowNonStandard: allowNonStandardVersions); + ISemanticVersion? installedVersion = this.ModSites.GetMappedVersion(search.InstalledVersion?.ToString(), wikiEntry?.Overrides?.ChangeLocalVersions, allowNonStandard: allowNonStandardVersions); if (apiVersion != null && installedVersion != null) { // get newer versions @@ -217,7 +218,7 @@ namespace StardewModdingAPI.Web.Controllers updates.Add(unofficialForBeta); // get newest version - ModEntryVersionModel newest = null; + ModEntryVersionModel? newest = null; foreach (ModEntryVersionModel update in updates) { if (newest == null || update.Version.IsNewerThan(newest.Version)) @@ -243,7 +244,7 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="currentVersion">The current semantic version.</param> /// <param name="newVersion">The target semantic version.</param> /// <param name="useBetaChannel">Whether the user enabled the beta channel and should be offered prerelease updates.</param> - private bool IsRecommendedUpdate(ISemanticVersion currentVersion, ISemanticVersion newVersion, bool useBetaChannel) + private bool IsRecommendedUpdate(ISemanticVersion currentVersion, [NotNullWhen(true)] ISemanticVersion? newVersion, bool useBetaChannel) { return newVersion != null @@ -254,7 +255,7 @@ namespace StardewModdingAPI.Web.Controllers /// <summary>Get whether a <paramref name="current"/> version is newer than an <paramref name="other"/> version.</summary> /// <param name="current">The current version.</param> /// <param name="other">The other version.</param> - private bool IsNewer(ISemanticVersion current, ISemanticVersion other) + private bool IsNewer([NotNullWhen(true)] ISemanticVersion? current, ISemanticVersion? other) { return current != null && (other == null || other.IsOlderThan(current)); } @@ -263,17 +264,20 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="updateKey">The namespaced update key.</param> /// <param name="allowNonStandardVersions">Whether to allow non-standard versions.</param> /// <param name="mapRemoteVersions">The changes to apply to remote versions for update checks.</param> - private async Task<ModInfoModel> GetInfoForUpdateKeyAsync(UpdateKey updateKey, bool allowNonStandardVersions, ChangeDescriptor mapRemoteVersions) + private async Task<ModInfoModel> GetInfoForUpdateKeyAsync(UpdateKey updateKey, bool allowNonStandardVersions, ChangeDescriptor? mapRemoteVersions) { + if (!updateKey.LooksValid) + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"Invalid update key '{updateKey}'."); + // get mod page IModPage page; { bool isCached = - this.ModCache.TryGetMod(updateKey.Site, updateKey.ID, out Cached<IModPage> cachedMod) + this.ModCache.TryGetMod(updateKey.Site, updateKey.ID, out Cached<IModPage>? cachedMod) && !this.ModCache.IsStale(cachedMod.LastUpdated, cachedMod.Data.Status == RemoteModStatus.TemporaryError ? this.Config.Value.ErrorCacheMinutes : this.Config.Value.SuccessCacheMinutes); if (isCached) - page = cachedMod.Data; + page = cachedMod!.Data; else { page = await this.ModSites.GetModPageAsync(updateKey); @@ -289,7 +293,7 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="specifiedKeys">The specified update keys.</param> /// <param name="record">The mod's entry in SMAPI's internal database.</param> /// <param name="entry">The mod's entry in the wiki list.</param> - private IEnumerable<UpdateKey> GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) + private IEnumerable<UpdateKey> GetUpdateKeys(string[]? specifiedKeys, ModDataRecord? record, WikiModEntry? entry) { // get unique update keys List<UpdateKey> updateKeys = this.GetUnfilteredUpdateKeys(specifiedKeys, record, entry) @@ -308,7 +312,7 @@ namespace StardewModdingAPI.Web.Controllers // if the list has both an update key (like "Nexus:2400") and subkey (like "Nexus:2400@subkey") for the same page, the subkey takes priority { var removeKeys = new HashSet<UpdateKey>(); - foreach (var key in updateKeys) + foreach (UpdateKey key in updateKeys) { if (key.Subkey != null) removeKeys.Add(new UpdateKey(key.Site, key.ID, null)); @@ -324,7 +328,7 @@ namespace StardewModdingAPI.Web.Controllers /// <param name="specifiedKeys">The specified update keys.</param> /// <param name="record">The mod's entry in SMAPI's internal database.</param> /// <param name="entry">The mod's entry in the wiki list.</param> - private IEnumerable<string> GetUnfilteredUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) + private IEnumerable<string> GetUnfilteredUpdateKeys(string[]? specifiedKeys, ModDataRecord? record, WikiModEntry? entry) { // specified update keys foreach (string key in specifiedKeys ?? Array.Empty<string>()) @@ -335,7 +339,7 @@ namespace StardewModdingAPI.Web.Controllers // default update key { - string defaultKey = record?.GetDefaultUpdateKey(); + string? defaultKey = record?.GetDefaultUpdateKey(); if (!string.IsNullOrWhiteSpace(defaultKey)) yield return defaultKey; } diff --git a/src/SMAPI.Web/Controllers/ModsController.cs b/src/SMAPI.Web/Controllers/ModsController.cs index c62ed605..919afa5b 100644 --- a/src/SMAPI.Web/Controllers/ModsController.cs +++ b/src/SMAPI.Web/Controllers/ModsController.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Mvc; @@ -52,8 +53,8 @@ namespace StardewModdingAPI.Web.Controllers public ModListModel FetchData() { // fetch cached data - if (!this.Cache.TryGetWikiMetadata(out Cached<WikiMetadata> metadata)) - return new ModListModel(); + if (!this.Cache.TryGetWikiMetadata(out Cached<WikiMetadata>? metadata)) + return new ModListModel(null, null, Array.Empty<ModModel>(), lastUpdated: DateTimeOffset.UtcNow, isStale: true); // build model return new ModListModel( diff --git a/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs b/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs index 864aa215..bd414ea2 100644 --- a/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs +++ b/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs @@ -40,7 +40,7 @@ namespace StardewModdingAPI.Web.Framework public void OnAuthorization(AuthorizationFilterContext context) { IFeatureCollection features = context.HttpContext.Features; - IFormFeature formFeature = features.Get<IFormFeature>(); + IFormFeature? formFeature = features.Get<IFormFeature>(); if (formFeature?.Form == null) { diff --git a/src/SMAPI.Web/Framework/Caching/Cached.cs b/src/SMAPI.Web/Framework/Caching/Cached.cs index 52041a16..b393e1e1 100644 --- a/src/SMAPI.Web/Framework/Caching/Cached.cs +++ b/src/SMAPI.Web/Framework/Caching/Cached.cs @@ -10,21 +10,18 @@ namespace StardewModdingAPI.Web.Framework.Caching ** Accessors *********/ /// <summary>The cached data.</summary> - public T Data { get; set; } + public T Data { get; } /// <summary>When the data was last updated.</summary> - public DateTimeOffset LastUpdated { get; set; } + public DateTimeOffset LastUpdated { get; } /// <summary>When the data was last requested through the mod API.</summary> - public DateTimeOffset LastRequested { get; set; } + public DateTimeOffset LastRequested { get; internal set; } /********* ** Public methods *********/ - /// <summary>Construct an empty instance.</summary> - public Cached() { } - /// <summary>Construct an instance.</summary> /// <param name="data">The cached data.</param> public Cached(T data) diff --git a/src/SMAPI.Web/Framework/Caching/Mods/IModCacheRepository.cs b/src/SMAPI.Web/Framework/Caching/Mods/IModCacheRepository.cs index 0d912c7b..fb74e9da 100644 --- a/src/SMAPI.Web/Framework/Caching/Mods/IModCacheRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Mods/IModCacheRepository.cs @@ -1,6 +1,6 @@ using System; +using System.Diagnostics.CodeAnalysis; using StardewModdingAPI.Toolkit.Framework.UpdateData; -using StardewModdingAPI.Web.Framework.Clients; namespace StardewModdingAPI.Web.Framework.Caching.Mods { @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods /// <param name="id">The mod's unique ID within the <paramref name="site"/>.</param> /// <param name="mod">The fetched mod.</param> /// <param name="markRequested">Whether to update the mod's 'last requested' date.</param> - bool TryGetMod(ModSiteKey site, string id, out Cached<IModPage> mod, bool markRequested = true); + bool TryGetMod(ModSiteKey site, string id, [NotNullWhen(true)] out Cached<IModPage>? mod, bool markRequested = true); /// <summary>Save data fetched for a mod.</summary> /// <param name="site">The mod site on which the mod is found.</param> diff --git a/src/SMAPI.Web/Framework/Caching/Mods/ModCacheMemoryRepository.cs b/src/SMAPI.Web/Framework/Caching/Mods/ModCacheMemoryRepository.cs index 9769793c..4ba0bd20 100644 --- a/src/SMAPI.Web/Framework/Caching/Mods/ModCacheMemoryRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Mods/ModCacheMemoryRepository.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Toolkit.Framework.UpdateData; -using StardewModdingAPI.Web.Framework.Clients; namespace StardewModdingAPI.Web.Framework.Caching.Mods { @@ -24,7 +24,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods /// <param name="id">The mod's unique ID within the <paramref name="site"/>.</param> /// <param name="mod">The fetched mod.</param> /// <param name="markRequested">Whether to update the mod's 'last requested' date.</param> - public bool TryGetMod(ModSiteKey site, string id, out Cached<IModPage> mod, bool markRequested = true) + public bool TryGetMod(ModSiteKey site, string id, [NotNullWhen(true)] out Cached<IModPage>? mod, bool markRequested = true) { // get mod if (!this.Mods.TryGetValue(this.GetKey(site, id), out var cachedMod)) diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs b/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs index 2ab7ea5a..b8a0df34 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; namespace StardewModdingAPI.Web.Framework.Caching.Wiki @@ -12,16 +13,16 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki *********/ /// <summary>Get the cached wiki metadata.</summary> /// <param name="metadata">The fetched metadata.</param> - bool TryGetWikiMetadata(out Cached<WikiMetadata> metadata); + bool TryGetWikiMetadata([NotNullWhen(true)] out Cached<WikiMetadata>? metadata); /// <summary>Get the cached wiki mods.</summary> /// <param name="filter">A filter to apply, if any.</param> - IEnumerable<Cached<WikiModEntry>> GetWikiMods(Func<WikiModEntry, bool> filter = null); + IEnumerable<Cached<WikiModEntry>> GetWikiMods(Func<WikiModEntry, bool>? filter = null); /// <summary>Save data fetched from the wiki compatibility list.</summary> /// <param name="stableVersion">The current stable Stardew Valley version.</param> /// <param name="betaVersion">The current beta Stardew Valley version.</param> /// <param name="mods">The mod data.</param> - void SaveWikiData(string stableVersion, string betaVersion, IEnumerable<WikiModEntry> mods); + void SaveWikiData(string? stableVersion, string? betaVersion, IEnumerable<WikiModEntry> mods); } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/WikiCacheMemoryRepository.cs b/src/SMAPI.Web/Framework/Caching/Wiki/WikiCacheMemoryRepository.cs index 064a7c3c..8b4338e2 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/WikiCacheMemoryRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/WikiCacheMemoryRepository.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; @@ -12,10 +13,10 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki ** Fields *********/ /// <summary>The saved wiki metadata.</summary> - private Cached<WikiMetadata> Metadata; + private Cached<WikiMetadata>? Metadata; /// <summary>The cached wiki data.</summary> - private Cached<WikiModEntry>[] Mods = new Cached<WikiModEntry>[0]; + private Cached<WikiModEntry>[] Mods = Array.Empty<Cached<WikiModEntry>>(); /********* @@ -23,7 +24,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki *********/ /// <summary>Get the cached wiki metadata.</summary> /// <param name="metadata">The fetched metadata.</param> - public bool TryGetWikiMetadata(out Cached<WikiMetadata> metadata) + public bool TryGetWikiMetadata([NotNullWhen(true)] out Cached<WikiMetadata>? metadata) { metadata = this.Metadata; return metadata != null; @@ -31,7 +32,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// <summary>Get the cached wiki mods.</summary> /// <param name="filter">A filter to apply, if any.</param> - public IEnumerable<Cached<WikiModEntry>> GetWikiMods(Func<WikiModEntry, bool> filter = null) + public IEnumerable<Cached<WikiModEntry>> GetWikiMods(Func<WikiModEntry, bool>? filter = null) { foreach (var mod in this.Mods) { @@ -44,7 +45,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// <param name="stableVersion">The current stable Stardew Valley version.</param> /// <param name="betaVersion">The current beta Stardew Valley version.</param> /// <param name="mods">The mod data.</param> - public void SaveWikiData(string stableVersion, string betaVersion, IEnumerable<WikiModEntry> mods) + public void SaveWikiData(string? stableVersion, string? betaVersion, IEnumerable<WikiModEntry> mods) { this.Metadata = new Cached<WikiMetadata>(new WikiMetadata(stableVersion, betaVersion)); this.Mods = mods.Select(mod => new Cached<WikiModEntry>(mod)).ToArray(); diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/WikiMetadata.cs b/src/SMAPI.Web/Framework/Caching/Wiki/WikiMetadata.cs index c04de4a5..f53ea201 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/WikiMetadata.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/WikiMetadata.cs @@ -7,22 +7,19 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki ** Accessors *********/ /// <summary>The current stable Stardew Valley version.</summary> - public string StableVersion { get; set; } + public string? StableVersion { get; } /// <summary>The current beta Stardew Valley version.</summary> - public string BetaVersion { get; set; } + public string? BetaVersion { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public WikiMetadata() { } - - /// <summary>Construct an instance.</summary> /// <param name="stableVersion">The current stable Stardew Valley version.</param> /// <param name="betaVersion">The current beta Stardew Valley version.</param> - public WikiMetadata(string stableVersion, string betaVersion) + public WikiMetadata(string? stableVersion, string? betaVersion) { this.StableVersion = stableVersion; this.BetaVersion = betaVersion; diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs index b8b05878..ce0f1122 100644 --- a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs @@ -42,7 +42,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - public async Task<IModPage> GetModData(string id) + public async Task<IModPage?> GetModData(string id) { IModPage page = new GenericModPage(this.SiteKey, id); @@ -51,14 +51,14 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish return page.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); // fetch HTML - string html; + string? html; try { html = await this.Client .GetAsync(string.Format(this.ModPageUrlFormat, parsedId)) .AsString(); } - catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound || ex.Status == HttpStatusCode.Forbidden) + catch (ApiException ex) when (ex.Status is HttpStatusCode.NotFound or HttpStatusCode.Forbidden) { return page.SetError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); } @@ -67,7 +67,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish // extract mod info string url = this.GetModUrl(parsedId); - string version = doc.DocumentNode.SelectSingleNode("//h1/span")?.InnerText; + string? version = doc.DocumentNode.SelectSingleNode("//h1/span")?.InnerText; string name = doc.DocumentNode.SelectSingleNode("//h1").ChildNodes[0].InnerText.Trim(); if (name.StartsWith("[SMAPI]")) name = name.Substring("[SMAPI]".Length).TrimStart(); @@ -79,7 +79,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { - this.Client?.Dispose(); + this.Client.Dispose(); } @@ -90,7 +90,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish /// <param name="id">The mod ID.</param> private string GetModUrl(uint id) { - UriBuilder builder = new UriBuilder(this.Client.BaseClient.BaseAddress); + UriBuilder builder = new(this.Client.BaseClient.BaseAddress!); builder.Path += string.Format(this.ModPageUrlFormat, id); return builder.Uri.ToString(); } diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs index d8008721..d351b42d 100644 --- a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs @@ -17,7 +17,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge private readonly IClient Client; /// <summary>A regex pattern which matches a version number in a CurseForge mod file name.</summary> - private readonly Regex VersionInNamePattern = new Regex(@"^(?:.+? | *)v?(\d+\.\d+(?:\.\d+)?(?:-.+?)?) *(?:\.(?:zip|rar|7z))?$", RegexOptions.Compiled); + private readonly Regex VersionInNamePattern = new(@"^(?:.+? | *)v?(\d+\.\d+(?:\.\d+)?(?:-.+?)?) *(?:\.(?:zip|rar|7z))?$", RegexOptions.Compiled); /********* @@ -40,7 +40,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - public async Task<IModPage> GetModData(string id) + public async Task<IModPage?> GetModData(string id) { IModPage page = new GenericModPage(this.SiteKey, id); @@ -49,9 +49,9 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge return page.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid CurseForge mod ID, must be an integer ID."); // get raw data - ModModel mod = await this.Client + ModModel? mod = await this.Client .GetAsync($"addon/{parsedId}") - .As<ModModel>(); + .As<ModModel?>(); if (mod == null) return page.SetError(RemoteModStatus.DoesNotExist, "Found no CurseForge mod with this ID."); @@ -71,7 +71,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { - this.Client?.Dispose(); + this.Client.Dispose(); } @@ -80,9 +80,9 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge *********/ /// <summary>Get a raw version string for a mod file, if available.</summary> /// <param name="file">The file whose version to get.</param> - private string GetRawVersion(ModFileModel file) + private string? GetRawVersion(ModFileModel file) { - Match match = this.VersionInNamePattern.Match(file.DisplayName); + Match match = this.VersionInNamePattern.Match(file.DisplayName ?? ""); if (!match.Success) match = this.VersionInNamePattern.Match(file.FileName); diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs index 9de74847..e9adcf20 100644 --- a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs @@ -3,10 +3,26 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge.ResponseModels /// <summary>Metadata from the CurseForge API about a mod file.</summary> public class ModFileModel { + /********* + ** Accessors + *********/ /// <summary>The file name as downloaded.</summary> - public string FileName { get; set; } + public string FileName { get; } /// <summary>The file display name.</summary> - public string DisplayName { get; set; } + public string? DisplayName { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="fileName">The file name as downloaded.</param> + /// <param name="displayName">The file display name.</param> + public ModFileModel(string fileName, string? displayName) + { + this.FileName = fileName; + this.DisplayName = displayName; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs index 48cd185b..fd7796f2 100644 --- a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs @@ -3,16 +3,36 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge.ResponseModels /// <summary>An mod from the CurseForge API.</summary> public class ModModel { + /********* + ** Accessors + *********/ /// <summary>The mod's unique ID on CurseForge.</summary> - public int ID { get; set; } + public int ID { get; } /// <summary>The mod name.</summary> - public string Name { get; set; } + public string Name { get; } /// <summary>The web URL for the mod page.</summary> - public string WebsiteUrl { get; set; } + public string WebsiteUrl { get; } /// <summary>The available file downloads.</summary> - public ModFileModel[] LatestFiles { get; set; } + public ModFileModel[] LatestFiles { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="id">The mod's unique ID on CurseForge.</param> + /// <param name="name">The mod name.</param> + /// <param name="websiteUrl">The web URL for the mod page.</param> + /// <param name="latestFiles">The available file downloads.</param> + public ModModel(int id, string name, string websiteUrl, ModFileModel[] latestFiles) + { + this.ID = id; + this.Name = name; + this.WebsiteUrl = websiteUrl; + this.LatestFiles = latestFiles; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/GenericModDownload.cs b/src/SMAPI.Web/Framework/Clients/GenericModDownload.cs index f08b471c..548f17c3 100644 --- a/src/SMAPI.Web/Framework/Clients/GenericModDownload.cs +++ b/src/SMAPI.Web/Framework/Clients/GenericModDownload.cs @@ -7,26 +7,23 @@ namespace StardewModdingAPI.Web.Framework.Clients ** Accessors *********/ /// <summary>The download's display name.</summary> - public string Name { get; set; } + public string Name { get; } /// <summary>The download's description.</summary> - public string Description { get; set; } + public string? Description { get; } /// <summary>The download's file version.</summary> - public string Version { get; set; } + public string? Version { get; } /********* ** Public methods *********/ - /// <summary>Construct an empty instance.</summary> - public GenericModDownload() { } - /// <summary>Construct an instance.</summary> /// <param name="name">The download's display name.</param> /// <param name="description">The download's description.</param> /// <param name="version">The download's file version.</param> - public GenericModDownload(string name, string description, string version) + public GenericModDownload(string name, string? description, string? version) { this.Name = name; this.Description = description; diff --git a/src/SMAPI.Web/Framework/Clients/GenericModPage.cs b/src/SMAPI.Web/Framework/Clients/GenericModPage.cs index 622e6c56..5353c7e1 100644 --- a/src/SMAPI.Web/Framework/Clients/GenericModPage.cs +++ b/src/SMAPI.Web/Framework/Clients/GenericModPage.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Toolkit.Framework.UpdateData; @@ -17,30 +19,31 @@ namespace StardewModdingAPI.Web.Framework.Clients public string Id { get; set; } /// <summary>The mod name.</summary> - public string Name { get; set; } + public string? Name { get; set; } /// <summary>The mod's semantic version number.</summary> - public string Version { get; set; } + public string? Version { get; set; } /// <summary>The mod's web URL.</summary> - public string Url { get; set; } + public string? Url { get; set; } /// <summary>The mod downloads.</summary> - public IModDownload[] Downloads { get; set; } = new IModDownload[0]; + public IModDownload[] Downloads { get; set; } = Array.Empty<IModDownload>(); /// <summary>The mod availability status on the remote site.</summary> - public RemoteModStatus Status { get; set; } = RemoteModStatus.Ok; + public RemoteModStatus Status { get; set; } = RemoteModStatus.InvalidData; /// <summary>A user-friendly error which indicates why fetching the mod info failed (if applicable).</summary> - public string Error { get; set; } + public string? Error { get; set; } + + /// <summary>Whether the mod data is valid.</summary> + [MemberNotNullWhen(true, nameof(IModPage.Name), nameof(IModPage.Url))] + public bool IsValid => this.Status == RemoteModStatus.Ok; /********* ** Public methods *********/ - /// <summary>Construct an empty instance.</summary> - public GenericModPage() { } - /// <summary>Construct an instance.</summary> /// <param name="site">The mod site containing the mod.</param> /// <param name="id">The mod's unique ID within the site.</param> @@ -55,12 +58,13 @@ namespace StardewModdingAPI.Web.Framework.Clients /// <param name="version">The mod's semantic version number.</param> /// <param name="url">The mod's web URL.</param> /// <param name="downloads">The mod downloads.</param> - public IModPage SetInfo(string name, string version, string url, IEnumerable<IModDownload> downloads) + public IModPage SetInfo(string name, string? version, string url, IEnumerable<IModDownload> downloads) { this.Name = name; this.Version = version; this.Url = url; this.Downloads = downloads.ToArray(); + this.Status = RemoteModStatus.Ok; return this; } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs index 73ce4025..dbce9368 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs @@ -5,16 +5,34 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>A GitHub download attached to a release.</summary> internal class GitAsset { + /********* + ** Accessors + *********/ /// <summary>The file name.</summary> [JsonProperty("name")] - public string FileName { get; set; } + public string FileName { get; } /// <summary>The file content type.</summary> [JsonProperty("content_type")] - public string ContentType { get; set; } + public string ContentType { get; } /// <summary>The download URL.</summary> [JsonProperty("browser_download_url")] - public string DownloadUrl { get; set; } + public string DownloadUrl { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="fileName">The file name.</param> + /// <param name="contentType">The file content type.</param> + /// <param name="downloadUrl">The download URL.</param> + public GitAsset(string fileName, string contentType, string downloadUrl) + { + this.FileName = fileName; + this.ContentType = contentType; + this.DownloadUrl = downloadUrl; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs index 671f077c..785979a5 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs @@ -33,26 +33,26 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <param name="acceptHeader">The Accept header value expected by the GitHub API.</param> /// <param name="username">The username with which to authenticate to the GitHub API.</param> /// <param name="password">The password with which to authenticate to the GitHub API.</param> - public GitHubClient(string baseUrl, string userAgent, string acceptHeader, string username, string password) + public GitHubClient(string baseUrl, string userAgent, string acceptHeader, string? username, string? password) { this.Client = new FluentClient(baseUrl) .SetUserAgent(userAgent) .AddDefault(req => req.WithHeader("Accept", acceptHeader)); if (!string.IsNullOrWhiteSpace(username)) - this.Client = this.Client.SetBasicAuthentication(username, password); + this.Client = this.Client.SetBasicAuthentication(username, password!); } /// <summary>Get basic metadata for a GitHub repository, if available.</summary> /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> /// <returns>Returns the repository info if it exists, else <c>null</c>.</returns> - public async Task<GitRepo> GetRepositoryAsync(string repo) + public async Task<GitRepo?> GetRepositoryAsync(string repo) { this.AssertKeyFormat(repo); try { return await this.Client .GetAsync($"repos/{repo}") - .As<GitRepo>(); + .As<GitRepo?>(); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) { @@ -64,7 +64,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> /// <param name="includePrerelease">Whether to return a prerelease version if it's latest.</param> /// <returns>Returns the release if found, else <c>null</c>.</returns> - public async Task<GitRelease> GetLatestReleaseAsync(string repo, bool includePrerelease = false) + public async Task<GitRelease?> GetLatestReleaseAsync(string repo, bool includePrerelease = false) { this.AssertKeyFormat(repo); try @@ -79,7 +79,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub return await this.Client .GetAsync($"repos/{repo}/releases/latest") - .As<GitRelease>(); + .As<GitRelease?>(); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) { @@ -89,7 +89,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - public async Task<IModPage> GetModData(string id) + public async Task<IModPage?> GetModData(string id) { IModPage page = new GenericModPage(this.SiteKey, id); @@ -97,15 +97,15 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub return page.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/SMAPI'."); // fetch repo info - GitRepo repository = await this.GetRepositoryAsync(id); + GitRepo? repository = await this.GetRepositoryAsync(id); if (repository == null) return page.SetError(RemoteModStatus.DoesNotExist, "Found no GitHub repository for this ID."); string name = repository.FullName; string url = $"{repository.WebUrl}/releases"; // get releases - GitRelease latest; - GitRelease preview; + GitRelease? latest; + GitRelease? preview; { // get latest release (whether preview or stable) latest = await this.GetLatestReleaseAsync(id, includePrerelease: true); @@ -116,7 +116,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub preview = null; if (latest.IsPrerelease) { - GitRelease release = await this.GetLatestReleaseAsync(id, includePrerelease: false); + GitRelease? release = await this.GetLatestReleaseAsync(id, includePrerelease: false); if (release != null) { preview = latest; @@ -127,8 +127,8 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub // get downloads IModDownload[] downloads = new[] { latest, preview } - .Where(release => release != null) - .Select(release => (IModDownload)new GenericModDownload(release.Name, release.Body, release.Tag)) + .Where(release => release is not null) + .Select(release => (IModDownload)new GenericModDownload(release!.Name, release.Body, release.Tag)) .ToArray(); // return info @@ -138,7 +138,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { - this.Client?.Dispose(); + this.Client.Dispose(); } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs index 736efbe6..24d6c3c5 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs @@ -5,16 +5,34 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>The license info for a GitHub project.</summary> internal class GitLicense { + /********* + ** Accessors + *********/ /// <summary>The license display name.</summary> [JsonProperty("name")] - public string Name { get; set; } + public string Name { get; } /// <summary>The SPDX ID for the license.</summary> [JsonProperty("spdx_id")] - public string SpdxId { get; set; } + public string SpdxId { get; } /// <summary>The URL for the license info.</summary> [JsonProperty("url")] - public string Url { get; set; } + public string Url { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="name">The license display name.</param> + /// <param name="spdxId">The SPDX ID for the license.</param> + /// <param name="url">The URL for the license info.</param> + public GitLicense(string name, string spdxId, string url) + { + this.Name = name; + this.SpdxId = spdxId; + this.Url = url; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs index d0db5297..9de6f020 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs @@ -1,3 +1,4 @@ +using System; using Newtonsoft.Json; namespace StardewModdingAPI.Web.Framework.Clients.GitHub @@ -10,24 +11,45 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub *********/ /// <summary>The display name.</summary> [JsonProperty("name")] - public string Name { get; set; } + public string Name { get; } /// <summary>The semantic version string.</summary> [JsonProperty("tag_name")] - public string Tag { get; set; } + public string Tag { get; } /// <summary>The Markdown description for the release.</summary> - public string Body { get; set; } + public string Body { get; internal set; } /// <summary>Whether this is a draft version.</summary> [JsonProperty("draft")] - public bool IsDraft { get; set; } + public bool IsDraft { get; } /// <summary>Whether this is a prerelease version.</summary> [JsonProperty("prerelease")] - public bool IsPrerelease { get; set; } + public bool IsPrerelease { get; } /// <summary>The attached files.</summary> - public GitAsset[] Assets { get; set; } + public GitAsset[] Assets { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="name">The display name.</param> + /// <param name="tag">The semantic version string.</param> + /// <param name="body">The Markdown description for the release.</param> + /// <param name="isDraft">Whether this is a draft version.</param> + /// <param name="isPrerelease">Whether this is a prerelease version.</param> + /// <param name="assets">The attached files.</param> + public GitRelease(string name, string tag, string? body, bool isDraft, bool isPrerelease, GitAsset[]? assets) + { + this.Name = name; + this.Tag = tag; + this.Body = body ?? string.Empty; + this.IsDraft = isDraft; + this.IsPrerelease = isPrerelease; + this.Assets = assets ?? Array.Empty<GitAsset>(); + } } } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs index 7d80576e..879b5e49 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs @@ -5,16 +5,34 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>Basic metadata about a GitHub project.</summary> internal class GitRepo { + /********* + ** Accessors + *********/ /// <summary>The full repository name, including the owner.</summary> [JsonProperty("full_name")] - public string FullName { get; set; } + public string FullName { get; } /// <summary>The URL to the repository web page, if any.</summary> [JsonProperty("html_url")] - public string WebUrl { get; set; } + public string? WebUrl { get; } /// <summary>The code license, if any.</summary> [JsonProperty("license")] - public GitLicense License { get; set; } + public GitLicense? License { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="fullName">The full repository name, including the owner.</param> + /// <param name="webUrl">The URL to the repository web page, if any.</param> + /// <param name="license">The code license, if any.</param> + public GitRepo(string fullName, string? webUrl, GitLicense? license) + { + this.FullName = fullName; + this.WebUrl = webUrl; + this.License = license; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs index 0d6f4643..886e32d3 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs @@ -12,12 +12,12 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// <summary>Get basic metadata for a GitHub repository, if available.</summary> /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> /// <returns>Returns the repository info if it exists, else <c>null</c>.</returns> - Task<GitRepo> GetRepositoryAsync(string repo); + Task<GitRepo?> GetRepositoryAsync(string repo); /// <summary>Get the latest release for a GitHub repository.</summary> /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> /// <param name="includePrerelease">Whether to return a prerelease version if it's latest.</param> /// <returns>Returns the release if found, else <c>null</c>.</returns> - Task<GitRelease> GetLatestReleaseAsync(string repo, bool includePrerelease = false); + Task<GitRelease?> GetLatestReleaseAsync(string repo, bool includePrerelease = false); } } diff --git a/src/SMAPI.Web/Framework/Clients/IModSiteClient.cs b/src/SMAPI.Web/Framework/Clients/IModSiteClient.cs index 33277711..3697ffae 100644 --- a/src/SMAPI.Web/Framework/Clients/IModSiteClient.cs +++ b/src/SMAPI.Web/Framework/Clients/IModSiteClient.cs @@ -18,6 +18,6 @@ namespace StardewModdingAPI.Web.Framework.Clients *********/ /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - Task<IModPage> GetModData(string id); + Task<IModPage?> GetModData(string id); } } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropClient.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropClient.cs index 3a1c5b9d..c60b2c90 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropClient.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropClient.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Pathoschild.Http.Client; using StardewModdingAPI.Toolkit.Framework.UpdateData; @@ -41,9 +42,10 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - public async Task<IModPage> GetModData(string id) + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "The nullability is validated in this method.")] + public async Task<IModPage?> GetModData(string id) { - var page = new GenericModPage(this.SiteKey, id); + IModPage page = new GenericModPage(this.SiteKey, id); if (!long.TryParse(id, out long parsedId)) return page.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid ModDrop mod ID, must be an integer ID."); @@ -58,9 +60,11 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop Mods = true }) .As<ModListModel>(); - ModModel mod = response.Mods[parsedId]; - if (mod.Mod?.Title == null || mod.Mod.ErrorCode.HasValue) - return null; + + if (!response.Mods.TryGetValue(parsedId, out ModModel? mod) || mod?.Mod is null) + return page.SetError(RemoteModStatus.DoesNotExist, "Found no ModDrop page with this ID."); + if (mod.Mod.ErrorCode is not null) + return page.SetError(RemoteModStatus.InvalidData, $"ModDrop returned error code {mod.Mod.ErrorCode} for mod ID '{id}'."); // get files var downloads = new List<IModDownload>(); @@ -75,7 +79,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop } // return info - string name = mod.Mod?.Title; + string name = mod.Mod.Title; string url = string.Format(this.ModUrlFormat, id); return page.SetInfo(name: name, version: null, url: url, downloads: downloads); } @@ -83,7 +87,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { - this.Client?.Dispose(); + this.Client.Dispose(); } } } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/FileDataModel.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/FileDataModel.cs index b01196f4..31905338 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/FileDataModel.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/FileDataModel.cs @@ -5,27 +5,53 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop.ResponseModels /// <summary>Metadata from the ModDrop API about a mod file.</summary> public class FileDataModel { + /********* + ** Accessors + *********/ /// <summary>The file title.</summary> [JsonProperty("title")] - public string Name { get; set; } + public string Name { get; } /// <summary>The file description.</summary> [JsonProperty("desc")] - public string Description { get; set; } + public string Description { get; } /// <summary>The file version.</summary> - public string Version { get; set; } + public string Version { get; } /// <summary>Whether the file is deleted.</summary> - public bool IsDeleted { get; set; } + public bool IsDeleted { get; } /// <summary>Whether the file is hidden from users.</summary> - public bool IsHidden { get; set; } + public bool IsHidden { get; } /// <summary>Whether this is the default file for the mod.</summary> - public bool IsDefault { get; set; } + public bool IsDefault { get; } /// <summary>Whether this is an archived file.</summary> - public bool IsOld { get; set; } + public bool IsOld { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="name">The file title.</param> + /// <param name="description">The file description.</param> + /// <param name="version">The file version.</param> + /// <param name="isDeleted">Whether the file is deleted.</param> + /// <param name="isHidden">Whether the file is hidden from users.</param> + /// <param name="isDefault">Whether this is the default file for the mod.</param> + /// <param name="isOld">Whether this is an archived file.</param> + public FileDataModel(string name, string description, string version, bool isDeleted, bool isHidden, bool isDefault, bool isOld) + { + this.Name = name; + this.Description = description; + this.Version = version; + this.IsDeleted = isDeleted; + this.IsHidden = isHidden; + this.IsDefault = isDefault; + this.IsOld = isOld; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModDataModel.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModDataModel.cs index cfdd6a4e..0654b576 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModDataModel.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModDataModel.cs @@ -3,13 +3,31 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop.ResponseModels /// <summary>Metadata about a mod from the ModDrop API.</summary> public class ModDataModel { + /********* + ** Accessors + *********/ /// <summary>The mod's unique ID on ModDrop.</summary> public int ID { get; set; } + /// <summary>The mod name.</summary> + public string Title { get; set; } + /// <summary>The error code, if any.</summary> public int? ErrorCode { get; set; } - /// <summary>The mod name.</summary> - public string Title { get; set; } + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="id">The mod's unique ID on ModDrop.</param> + /// <param name="title">The mod name.</param> + /// <param name="errorCode">The error code, if any.</param> + public ModDataModel(int id, string title, int? errorCode) + { + this.ID = id; + this.Title = title; + this.ErrorCode = errorCode; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModListModel.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModListModel.cs index 7f692ca1..cb4be35c 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModListModel.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModListModel.cs @@ -5,7 +5,10 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop.ResponseModels /// <summary>A list of mods from the ModDrop API.</summary> public class ModListModel { + /********* + ** Accessors + *********/ /// <summary>The mod data.</summary> - public IDictionary<long, ModModel> Mods { get; set; } + public IDictionary<long, ModModel> Mods { get; } = new Dictionary<long, ModModel>(); } } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModModel.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModModel.cs index 9f4b2c6f..60b818d6 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModModel.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ResponseModels/ModModel.cs @@ -3,10 +3,26 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop.ResponseModels /// <summary>An entry in a mod list from the ModDrop API.</summary> public class ModModel { + /********* + ** Accessors + *********/ /// <summary>The available file downloads.</summary> - public FileDataModel[] Files { get; set; } + public FileDataModel[] Files { get; } /// <summary>The mod metadata.</summary> - public ModDataModel Mod { get; set; } + public ModDataModel Mod { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="files">The available file downloads.</param> + /// <param name="mod">The mod metadata.</param> + public ModModel(FileDataModel[] files, ModDataModel mod) + { + this.Files = files; + this.Mod = mod; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/DisabledNexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/DisabledNexusClient.cs new file mode 100644 index 00000000..6edd5f64 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Nexus/DisabledNexusClient.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; +using StardewModdingAPI.Toolkit.Framework.UpdateData; + +namespace StardewModdingAPI.Web.Framework.Clients.Nexus +{ + /// <summary>A client for the Nexus website which does nothing, used for local development.</summary> + internal class DisabledNexusClient : INexusClient + { + /********* + ** Accessors + *********/ + /// <inheritdoc /> + public ModSiteKey SiteKey => ModSiteKey.Nexus; + + + /********* + ** Public methods + *********/ + /// <summary>Get update check info about a mod.</summary> + /// <param name="id">The mod ID.</param> + public Task<IModPage?> GetModData(string id) + { + return Task.FromResult<IModPage?>( + new GenericModPage(ModSiteKey.Nexus, id).SetError(RemoteModStatus.TemporaryError, "The Nexus client is currently disabled due to the configuration.") + ); + } + + /// <inheritdoc /> + public void Dispose() { } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs index 4ba94f81..23b25f95 100644 --- a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs @@ -59,7 +59,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus /// <summary>Get update check info about a mod.</summary> /// <param name="id">The mod ID.</param> - public async Task<IModPage> GetModData(string id) + public async Task<IModPage?> GetModData(string id) { IModPage page = new GenericModPage(this.SiteKey, id); @@ -70,25 +70,25 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus // adult content are hidden for anonymous users, so fall back to the API in that case. // Note that the API has very restrictive rate limits which means we can't just use it // for all cases. - NexusMod mod = await this.GetModFromWebsiteAsync(parsedId); + NexusMod? mod = await this.GetModFromWebsiteAsync(parsedId); if (mod?.Status == NexusModStatus.AdultContentForbidden) mod = await this.GetModFromApiAsync(parsedId); // page doesn't exist - if (mod == null || mod.Status == NexusModStatus.Hidden || mod.Status == NexusModStatus.NotPublished) + if (mod == null || mod.Status is NexusModStatus.Hidden or NexusModStatus.NotPublished) return page.SetError(RemoteModStatus.DoesNotExist, "Found no Nexus mod with this ID."); // return info - page.SetInfo(name: mod.Name, url: mod.Url, version: mod.Version, downloads: mod.Downloads); + page.SetInfo(name: mod.Name ?? parsedId.ToString(), url: mod.Url ?? this.GetModUrl(parsedId), version: mod.Version, downloads: mod.Downloads); if (mod.Status != NexusModStatus.Ok) - page.SetError(RemoteModStatus.TemporaryError, mod.Error); + page.SetError(RemoteModStatus.TemporaryError, mod.Error!); return page; } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { - this.WebClient?.Dispose(); + this.WebClient.Dispose(); } @@ -98,7 +98,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus /// <summary>Get metadata about a mod by scraping the Nexus website.</summary> /// <param name="id">The Nexus mod ID.</param> /// <returns>Returns the mod info if found, else <c>null</c>.</returns> - private async Task<NexusMod> GetModFromWebsiteAsync(uint id) + private async Task<NexusMod?> GetModFromWebsiteAsync(uint id) { // fetch HTML string html; @@ -114,35 +114,38 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus } // parse HTML - var doc = new HtmlDocument(); + HtmlDocument doc = new(); doc.LoadHtml(html); // handle Nexus error message - HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'site-notice')][contains(@class, 'warning')]"); + HtmlNode? node = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'site-notice')][contains(@class, 'warning')]"); if (node != null) { string[] errorParts = node.InnerText.Trim().Split(new[] { '\n' }, 2, System.StringSplitOptions.RemoveEmptyEntries); string errorCode = errorParts[0]; - string errorText = errorParts.Length > 1 ? errorParts[1] : null; + string? errorText = errorParts.Length > 1 ? errorParts[1] : null; switch (errorCode.Trim().ToLower()) { case "not found": return null; default: - return new NexusMod { Error = $"Nexus error: {errorCode} ({errorText}).", Status = this.GetWebStatus(errorCode) }; + return new NexusMod( + status: this.GetWebStatus(errorCode), + error: $"Nexus error: {errorCode} ({errorText})." + ); } } // extract mod info string url = this.GetModUrl(id); - string name = doc.DocumentNode.SelectSingleNode("//div[@id='pagetitle']//h1")?.InnerText.Trim(); - string version = doc.DocumentNode.SelectSingleNode("//ul[contains(@class, 'stats')]//li[@class='stat-version']//div[@class='stat']")?.InnerText.Trim(); - SemanticVersion.TryParse(version, out ISemanticVersion parsedVersion); + string? name = doc.DocumentNode.SelectSingleNode("//div[@id='pagetitle']//h1")?.InnerText.Trim(); + string? version = doc.DocumentNode.SelectSingleNode("//ul[contains(@class, 'stats')]//li[@class='stat-version']//div[@class='stat']")?.InnerText.Trim(); + SemanticVersion.TryParse(version, out ISemanticVersion? parsedVersion); // extract files var downloads = new List<IModDownload>(); - foreach (var fileSection in doc.DocumentNode.SelectNodes("//div[contains(@class, 'files-tabs')]")) + foreach (HtmlNode fileSection in doc.DocumentNode.SelectNodes("//div[contains(@class, 'files-tabs')]")) { string sectionName = fileSection.Descendants("h2").First().InnerText; if (sectionName != "Main files" && sectionName != "Optional files") @@ -152,7 +155,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus { string fileName = container.GetDataAttribute("name").Value; string fileVersion = container.GetDataAttribute("version").Value; - string description = container.SelectSingleNode("following-sibling::*[1][self::dd]//div").InnerText?.Trim(); // get text of next <dd> tag; derived from https://stackoverflow.com/a/25535623/262123 + string? description = container.SelectSingleNode("following-sibling::*[1][self::dd]//div").InnerText?.Trim(); // get text of next <dd> tag; derived from https://stackoverflow.com/a/25535623/262123 downloads.Add( new GenericModDownload(fileName, description, fileVersion) @@ -161,13 +164,12 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus } // yield info - return new NexusMod - { - Name = name, - Version = parsedVersion?.ToString() ?? version, - Url = url, - Downloads = downloads.ToArray() - }; + return new NexusMod( + name: name ?? id.ToString(), + version: parsedVersion?.ToString() ?? version, + url: url, + downloads: downloads.ToArray() + ); } /// <summary>Get metadata about a mod from the Nexus API.</summary> @@ -180,22 +182,21 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus ModFileList files = await this.ApiClient.ModFiles.GetModFiles("stardewvalley", (int)id, FileCategory.Main, FileCategory.Optional); // yield info - return new NexusMod - { - Name = mod.Name, - Version = SemanticVersion.TryParse(mod.Version, out ISemanticVersion version) ? version?.ToString() : mod.Version, - Url = this.GetModUrl(id), - Downloads = files.Files + return new NexusMod( + name: mod.Name, + version: SemanticVersion.TryParse(mod.Version, out ISemanticVersion? version) ? version.ToString() : mod.Version, + url: this.GetModUrl(id), + downloads: files.Files .Select(file => (IModDownload)new GenericModDownload(file.Name, file.Description, file.FileVersion)) .ToArray() - }; + ); } /// <summary>Get the full mod page URL for a given ID.</summary> /// <param name="id">The mod ID.</param> private string GetModUrl(uint id) { - UriBuilder builder = new UriBuilder(this.WebClient.BaseClient.BaseAddress); + UriBuilder builder = new(this.WebClient.BaseClient.BaseAddress!); builder.Path += string.Format(this.WebModUrlFormat, id); return builder.Uri.ToString(); } diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/ResponseModels/NexusMod.cs b/src/SMAPI.Web/Framework/Clients/Nexus/ResponseModels/NexusMod.cs index aef90ede..3155cfda 100644 --- a/src/SMAPI.Web/Framework/Clients/Nexus/ResponseModels/NexusMod.cs +++ b/src/SMAPI.Web/Framework/Clients/Nexus/ResponseModels/NexusMod.cs @@ -1,3 +1,4 @@ +using System; using Newtonsoft.Json; namespace StardewModdingAPI.Web.Framework.Clients.Nexus.ResponseModels @@ -9,25 +10,53 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus.ResponseModels ** Accessors *********/ /// <summary>The mod name.</summary> - public string Name { get; set; } + public string? Name { get; } /// <summary>The mod's semantic version number.</summary> - public string Version { get; set; } + public string? Version { get; } /// <summary>The mod's web URL.</summary> [JsonProperty("mod_page_uri")] - public string Url { get; set; } + public string? Url { get; } /// <summary>The mod's publication status.</summary> [JsonIgnore] - public NexusModStatus Status { get; set; } = NexusModStatus.Ok; + public NexusModStatus Status { get; } /// <summary>The files available to download.</summary> [JsonIgnore] - public IModDownload[] Downloads { get; set; } + public IModDownload[] Downloads { get; } /// <summary>A custom user-friendly error which indicates why fetching the mod info failed (if applicable).</summary> [JsonIgnore] - public string Error { get; set; } + public string? Error { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="name">The mod name</param> + /// <param name="version">The mod's semantic version number.</param> + /// <param name="url">The mod's web URL.</param> + /// <param name="downloads">The files available to download.</param> + public NexusMod(string name, string? version, string url, IModDownload[] downloads) + { + this.Name = name; + this.Version = version; + this.Url = url; + this.Status = NexusModStatus.Ok; + this.Downloads = downloads; + } + + /// <summary>Construct an instance.</summary> + /// <param name="status">The mod's publication status.</param> + /// <param name="error">A custom user-friendly error which indicates why fetching the mod info failed (if applicable).</param> + public NexusMod(NexusModStatus status, string error) + { + this.Status = status; + this.Error = error; + this.Downloads = Array.Empty<IModDownload>(); + } } } diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs index 813ea115..7f40e713 100644 --- a/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs @@ -1,15 +1,35 @@ +using System.Diagnostics.CodeAnalysis; + namespace StardewModdingAPI.Web.Framework.Clients.Pastebin { /// <summary>The response for a get-paste request.</summary> internal class PasteInfo { + /********* + ** Accessors + *********/ /// <summary>Whether the log was successfully fetched.</summary> - public bool Success { get; set; } + [MemberNotNullWhen(true, nameof(PasteInfo.Content))] + [MemberNotNullWhen(false, nameof(PasteInfo.Error))] + public bool Success => this.Error == null || this.Content != null; /// <summary>The fetched paste content (if <see cref="Success"/> is <c>true</c>).</summary> - public string Content { get; set; } + public string? Content { get; internal set; } + + /// <summary>The error message (if <see cref="Success"/> is <c>false</c>).</summary> + public string? Error { get; } + - /// <summary>The error message if saving failed.</summary> - public string Error { get; set; } + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="content">The fetched paste content.</param> + /// <param name="error">The error message, if it failed.</param> + public PasteInfo(string? content, string? error) + { + this.Content = content; + this.Error = error; + } } } diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs index 1be00be7..0e00f071 100644 --- a/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs @@ -33,24 +33,24 @@ namespace StardewModdingAPI.Web.Framework.Clients.Pastebin try { // get from API - string content = await this.Client + string? content = await this.Client .GetAsync($"raw/{id}") .AsString(); // handle Pastebin errors if (string.IsNullOrWhiteSpace(content)) - return new PasteInfo { Error = "Received an empty response from Pastebin." }; + return new PasteInfo(null, "Received an empty response from Pastebin."); if (content.StartsWith("<!DOCTYPE")) - return new PasteInfo { Error = $"Received a captcha challenge from Pastebin. Please visit https://pastebin.com/{id} in a new window to solve it." }; - return new PasteInfo { Success = true, Content = content }; + return new PasteInfo(null, $"Received a captcha challenge from Pastebin. Please visit https://pastebin.com/{id} in a new window to solve it."); + return new PasteInfo(content, null); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) { - return new PasteInfo { Error = "There's no log with that ID." }; + return new PasteInfo(null, "There's no log with that ID."); } catch (Exception ex) { - return new PasteInfo { Error = $"Pastebin error: {ex}" }; + return new PasteInfo(null, $"Pastebin error: {ex}"); } } diff --git a/src/SMAPI.Web/Framework/Compression/GzipHelper.cs b/src/SMAPI.Web/Framework/Compression/GzipHelper.cs index 676d660d..e7a2df13 100644 --- a/src/SMAPI.Web/Framework/Compression/GzipHelper.cs +++ b/src/SMAPI.Web/Framework/Compression/GzipHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Compression; using System.Text; @@ -29,9 +30,9 @@ namespace StardewModdingAPI.Web.Framework.Compression // compressed byte[] compressedData; - using (MemoryStream stream = new MemoryStream()) + using (MemoryStream stream = new()) { - using (GZipStream zipStream = new GZipStream(stream, CompressionLevel.Optimal, leaveOpen: true)) + using (GZipStream zipStream = new(stream, CompressionLevel.Optimal, leaveOpen: true)) zipStream.Write(buffer, 0, buffer.Length); stream.Position = 0; @@ -51,8 +52,12 @@ namespace StardewModdingAPI.Web.Framework.Compression /// <summary>Decompress a string.</summary> /// <param name="rawText">The compressed text.</param> /// <remarks>Derived from <a href="https://stackoverflow.com/a/17993002/262123"/>.</remarks> - public string DecompressString(string rawText) + [return: NotNullIfNotNull("rawText")] + public string? DecompressString(string? rawText) { + if (rawText is null) + return rawText; + // get raw bytes byte[] zipBuffer; try @@ -69,7 +74,7 @@ namespace StardewModdingAPI.Web.Framework.Compression return rawText; // decompress - using MemoryStream memoryStream = new MemoryStream(); + using MemoryStream memoryStream = new(); { // read length prefix int dataLength = BitConverter.ToInt32(zipBuffer, 0); @@ -78,7 +83,7 @@ namespace StardewModdingAPI.Web.Framework.Compression // read data byte[] buffer = new byte[dataLength]; memoryStream.Position = 0; - using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) + using (GZipStream gZipStream = new(memoryStream, CompressionMode.Decompress)) gZipStream.Read(buffer, 0, buffer.Length); // return original string diff --git a/src/SMAPI.Web/Framework/Compression/IGzipHelper.cs b/src/SMAPI.Web/Framework/Compression/IGzipHelper.cs index a000865e..ef2d5696 100644 --- a/src/SMAPI.Web/Framework/Compression/IGzipHelper.cs +++ b/src/SMAPI.Web/Framework/Compression/IGzipHelper.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace StardewModdingAPI.Web.Framework.Compression { /// <summary>Handles GZip compression logic.</summary> @@ -12,6 +14,7 @@ namespace StardewModdingAPI.Web.Framework.Compression /// <summary>Decompress a string.</summary> /// <param name="rawText">The compressed text.</param> - string DecompressString(string rawText); + [return: NotNullIfNotNull("rawText")] + string? DecompressString(string? rawText); } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs index 878130bf..b582b2b0 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs @@ -10,17 +10,17 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels ** Generic ****/ /// <summary>The user agent for API clients, where {0} is the SMAPI version.</summary> - public string UserAgent { get; set; } + public string UserAgent { get; set; } = null!; /**** ** Azure ****/ /// <summary>The connection string for the Azure Blob storage account.</summary> - public string AzureBlobConnectionString { get; set; } + public string? AzureBlobConnectionString { get; set; } /// <summary>The Azure Blob container in which to store temporary uploaded logs.</summary> - public string AzureBlobTempContainer { get; set; } + public string AzureBlobTempContainer { get; set; } = null!; /// <summary>The number of days since the blob's last-modified date when it will be deleted.</summary> public int AzureBlobTempExpiryDays { get; set; } @@ -30,65 +30,65 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels ** Chucklefish ****/ /// <summary>The base URL for the Chucklefish mod site.</summary> - public string ChucklefishBaseUrl { get; set; } + public string ChucklefishBaseUrl { get; set; } = null!; /// <summary>The URL for a mod page on the Chucklefish mod site excluding the <see cref="GitHubBaseUrl"/>, where {0} is the mod ID.</summary> - public string ChucklefishModPageUrlFormat { get; set; } + public string ChucklefishModPageUrlFormat { get; set; } = null!; /**** ** CurseForge ****/ /// <summary>The base URL for the CurseForge API.</summary> - public string CurseForgeBaseUrl { get; set; } + public string CurseForgeBaseUrl { get; set; } = null!; /**** ** GitHub ****/ /// <summary>The base URL for the GitHub API.</summary> - public string GitHubBaseUrl { get; set; } + public string GitHubBaseUrl { get; set; } = null!; /// <summary>The Accept header value expected by the GitHub API.</summary> - public string GitHubAcceptHeader { get; set; } + public string GitHubAcceptHeader { get; set; } = null!; /// <summary>The username with which to authenticate to the GitHub API (if any).</summary> - public string GitHubUsername { get; set; } + public string? GitHubUsername { get; set; } /// <summary>The password with which to authenticate to the GitHub API (if any).</summary> - public string GitHubPassword { get; set; } + public string? GitHubPassword { get; set; } /**** ** ModDrop ****/ /// <summary>The base URL for the ModDrop API.</summary> - public string ModDropApiUrl { get; set; } + public string ModDropApiUrl { get; set; } = null!; /// <summary>The URL for a ModDrop mod page for the user, where {0} is the mod ID.</summary> - public string ModDropModPageUrl { get; set; } + public string ModDropModPageUrl { get; set; } = null!; /**** ** Nexus Mods ****/ /// <summary>The base URL for the Nexus Mods API.</summary> - public string NexusBaseUrl { get; set; } + public string NexusBaseUrl { get; set; } = null!; /// <summary>The URL for a Nexus mod page for the user, excluding the <see cref="NexusBaseUrl"/>, where {0} is the mod ID.</summary> - public string NexusModUrlFormat { get; set; } + public string NexusModUrlFormat { get; set; } = null!; /// <summary>The URL for a Nexus mod page to scrape for versions, excluding the <see cref="NexusBaseUrl"/>, where {0} is the mod ID.</summary> - public string NexusModScrapeUrlFormat { get; set; } + public string NexusModScrapeUrlFormat { get; set; } = null!; /// <summary>The Nexus API authentication key.</summary> - public string NexusApiKey { get; set; } + public string? NexusApiKey { get; set; } /**** ** Pastebin ****/ /// <summary>The base URL for the Pastebin API.</summary> - public string PastebinBaseUrl { get; set; } + public string PastebinBaseUrl { get; set; } = null!; } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/ModOverrideConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ModOverrideConfig.cs index f382d7b5..e46ecf2b 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ModOverrideConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ModOverrideConfig.cs @@ -4,12 +4,12 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels internal class ModOverrideConfig { /// <summary>The unique ID from the mod's manifest.</summary> - public string ID { get; set; } + public string ID { get; set; } = null!; /// <summary>Whether to allow non-standard versions.</summary> public bool AllowNonStandardVersions { get; set; } /// <summary>The mod page URL to use regardless of which site has the update, or <c>null</c> to use the site URL.</summary> - public string SetUrl { get; set; } + public string? SetUrl { get; set; } } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs index aea695b8..c3b136e8 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs @@ -1,3 +1,5 @@ +using System; + namespace StardewModdingAPI.Web.Framework.ConfigModels { /// <summary>The config settings for mod update checks.</summary> @@ -6,16 +8,16 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels /********* ** Accessors *********/ - /// <summary>The number of minutes successful update checks should be cached before refetching them.</summary> + /// <summary>The number of minutes successful update checks should be cached before re-fetching them.</summary> public int SuccessCacheMinutes { get; set; } - /// <summary>The number of minutes failed update checks should be cached before refetching them.</summary> + /// <summary>The number of minutes failed update checks should be cached before re-fetching them.</summary> public int ErrorCacheMinutes { get; set; } /// <summary>Update-check metadata to override.</summary> - public ModOverrideConfig[] ModOverrides { get; set; } + public ModOverrideConfig[] ModOverrides { get; set; } = Array.Empty<ModOverrideConfig>(); /// <summary>The update-check config for SMAPI's own update checks.</summary> - public SmapiInfoConfig SmapiInfo { get; set; } + public SmapiInfoConfig SmapiInfo { get; set; } = null!; } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/SiteConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/SiteConfig.cs index 664dbef3..62685e47 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/SiteConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/SiteConfig.cs @@ -7,9 +7,9 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels ** Accessors *********/ /// <summary>A message to show below the download button (e.g. for details on downloading a beta version), in Markdown format.</summary> - public string OtherBlurb { get; set; } + public string? OtherBlurb { get; set; } /// <summary>A list of supports to credit on the main page, in Markdown format.</summary> - public string SupporterList { get; set; } + public string? SupporterList { get; set; } } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/SmapiInfoConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/SmapiInfoConfig.cs index d69fabb3..a95e0048 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/SmapiInfoConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/SmapiInfoConfig.cs @@ -1,15 +1,17 @@ +using System; + namespace StardewModdingAPI.Web.Framework.ConfigModels { /// <summary>The update-check config for SMAPI's own update checks.</summary> internal class SmapiInfoConfig { /// <summary>The mod ID used for SMAPI update checks.</summary> - public string ID { get; set; } + public string ID { get; set; } = null!; /// <summary>The default update key used for SMAPI update checks.</summary> - public string DefaultUpdateKey { get; set; } + public string DefaultUpdateKey { get; set; } = null!; /// <summary>The update keys to add for SMAPI update checks when the player has a beta version installed.</summary> - public string[] AddBetaUpdateKeys { get; set; } + public string[] AddBetaUpdateKeys { get; set; } = Array.Empty<string>(); } } diff --git a/src/SMAPI.Web/Framework/Extensions.cs b/src/SMAPI.Web/Framework/Extensions.cs index 5305b142..62a23155 100644 --- a/src/SMAPI.Web/Framework/Extensions.cs +++ b/src/SMAPI.Web/Framework/Extensions.cs @@ -26,10 +26,10 @@ namespace StardewModdingAPI.Web.Framework /// <param name="values">An object that contains route values.</param> /// <param name="absoluteUrl">Get an absolute URL instead of a server-relative path/</param> /// <returns>The generated URL.</returns> - public static string PlainAction(this IUrlHelper helper, [AspMvcAction] string action, [AspMvcController] string controller, object values = null, bool absoluteUrl = false) + public static string? PlainAction(this IUrlHelper helper, [AspMvcAction] string action, [AspMvcController] string controller, object? values = null, bool absoluteUrl = false) { // get route values - RouteValueDictionary valuesDict = new RouteValueDictionary(values); + RouteValueDictionary valuesDict = new(values); foreach (var value in helper.ActionContext.RouteData.Values) { if (!valuesDict.ContainsKey(value.Key)) @@ -37,7 +37,7 @@ namespace StardewModdingAPI.Web.Framework } // get relative URL - string url = helper.Action(action, controller, valuesDict); + string? url = helper.Action(action, controller, valuesDict); if (url == null && action.EndsWith("Async")) url = helper.Action(action[..^"Async".Length], controller, valuesDict); @@ -45,7 +45,7 @@ namespace StardewModdingAPI.Web.Framework if (absoluteUrl) { HttpRequest request = helper.ActionContext.HttpContext.Request; - Uri baseUri = new Uri($"{request.Scheme}://{request.Host}"); + Uri baseUri = new($"{request.Scheme}://{request.Host}"); url = new Uri(baseUri, url).ToString(); } @@ -57,7 +57,7 @@ namespace StardewModdingAPI.Web.Framework /// <param name="value">The value to serialize.</param> /// <returns>The serialized JSON.</returns> /// <remarks>This bypasses unnecessary validation (e.g. not allowing null values) in <see cref="IJsonHelper.Serialize"/>.</remarks> - public static IHtmlContent ForJson(this RazorPageBase page, object value) + public static IHtmlContent ForJson(this RazorPageBase page, object? value) { string json = JsonConvert.SerializeObject(value); return new HtmlString(json); diff --git a/src/SMAPI.Web/Framework/IModDownload.cs b/src/SMAPI.Web/Framework/IModDownload.cs index dc058bcb..fe171785 100644 --- a/src/SMAPI.Web/Framework/IModDownload.cs +++ b/src/SMAPI.Web/Framework/IModDownload.cs @@ -3,13 +3,16 @@ namespace StardewModdingAPI.Web.Framework /// <summary>Generic metadata about a file download on a mod page.</summary> internal interface IModDownload { + /********* + ** Accessors + *********/ /// <summary>The download's display name.</summary> string Name { get; } /// <summary>The download's description.</summary> - string Description { get; } + string? Description { get; } /// <summary>The download's file version.</summary> - string Version { get; } + string? Version { get; } } } diff --git a/src/SMAPI.Web/Framework/IModPage.cs b/src/SMAPI.Web/Framework/IModPage.cs index e66d401f..4d0a8d61 100644 --- a/src/SMAPI.Web/Framework/IModPage.cs +++ b/src/SMAPI.Web/Framework/IModPage.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using StardewModdingAPI.Toolkit.Framework.UpdateData; namespace StardewModdingAPI.Web.Framework @@ -16,13 +17,13 @@ namespace StardewModdingAPI.Web.Framework string Id { get; } /// <summary>The mod name.</summary> - string Name { get; } + string? Name { get; } /// <summary>The mod's semantic version number.</summary> - string Version { get; } + string? Version { get; } /// <summary>The mod's web URL.</summary> - string Url { get; } + string? Url { get; } /// <summary>The mod downloads.</summary> IModDownload[] Downloads { get; } @@ -31,7 +32,12 @@ namespace StardewModdingAPI.Web.Framework RemoteModStatus Status { get; } /// <summary>A user-friendly error which indicates why fetching the mod info failed (if applicable).</summary> - string Error { get; } + string? Error { get; } + + /// <summary>Whether the mod data is valid.</summary> + [MemberNotNullWhen(true, nameof(IModPage.Name), nameof(IModPage.Url))] + [MemberNotNullWhen(false, nameof(IModPage.Error))] + bool IsValid { get; } /********* @@ -42,7 +48,7 @@ namespace StardewModdingAPI.Web.Framework /// <param name="version">The mod's semantic version number.</param> /// <param name="url">The mod's web URL.</param> /// <param name="downloads">The mod downloads.</param> - IModPage SetInfo(string name, string version, string url, IEnumerable<IModDownload> downloads); + IModPage SetInfo(string name, string? version, string url, IEnumerable<IModDownload> downloads); /// <summary>Set a mod fetch error.</summary> /// <param name="status">The mod availability status on the remote site.</param> diff --git a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs index 385c0c91..3c1405eb 100644 --- a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs +++ b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs @@ -9,7 +9,7 @@ namespace StardewModdingAPI.Web.Framework ** Fields *********/ /// <summary>An authorization filter that allows local requests.</summary> - private static readonly LocalRequestsOnlyAuthorizationFilter LocalRequestsOnlyFilter = new LocalRequestsOnlyAuthorizationFilter(); + private static readonly LocalRequestsOnlyAuthorizationFilter LocalRequestsOnlyFilter = new(); /********* diff --git a/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs b/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs index 992876ef..a1384b8f 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Text; using StardewModdingAPI.Web.Framework.LogParsing.Models; @@ -11,7 +12,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing ** Fields *********/ /// <summary>The local time when the next log was posted.</summary> - public string Time { get; set; } + public string? Time { get; set; } /// <summary>The log level for the next log message.</summary> public LogLevel Level { get; set; } @@ -20,16 +21,17 @@ namespace StardewModdingAPI.Web.Framework.LogParsing public int ScreenId { get; set; } /// <summary>The mod name for the next log message.</summary> - public string Mod { get; set; } + public string? Mod { get; set; } /// <summary>The text for the next log message.</summary> - private readonly StringBuilder Text = new StringBuilder(); + private readonly StringBuilder Text = new(); /********* ** Accessors *********/ /// <summary>Whether the next log message has been started.</summary> + [MemberNotNullWhen(true, nameof(LogMessageBuilder.Time), nameof(LogMessageBuilder.Mod))] public bool Started { get; private set; } @@ -70,19 +72,18 @@ namespace StardewModdingAPI.Web.Framework.LogParsing } /// <summary>Get a log message for the accumulated values.</summary> - public LogMessage Build() + public LogMessage? Build() { if (!this.Started) return null; - return new LogMessage - { - Time = this.Time, - Level = this.Level, - ScreenId = this.ScreenId, - Mod = this.Mod, - Text = this.Text.ToString() - }; + return new LogMessage( + time: this.Time, + level: this.Level, + screenId: this.ScreenId, + mod: this.Mod, + text: this.Text.ToString() + ); } /// <summary>Reset to start a new log message.</summary> diff --git a/src/SMAPI.Web/Framework/LogParsing/LogParseException.cs b/src/SMAPI.Web/Framework/LogParsing/LogParseException.cs index 5d4c8c08..3f815e3e 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogParseException.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogParseException.cs @@ -10,6 +10,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing *********/ /// <summary>Construct an instance.</summary> /// <param name="message">The user-friendly error message.</param> - public LogParseException(string message) : base(message) { } + public LogParseException(string message) + : base(message) { } } } diff --git a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs index 887d0105..55272b23 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs @@ -14,38 +14,38 @@ namespace StardewModdingAPI.Web.Framework.LogParsing ** Fields *********/ /// <summary>A regex pattern matching the start of a SMAPI message.</summary> - private readonly Regex MessageHeaderPattern = new Regex(@"^\[(?<time>\d\d[:\.]\d\d[:\.]\d\d) (?<level>[a-z]+)(?: +screen_(?<screen>\d+))? +(?<modName>[^\]]+)\] ", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex MessageHeaderPattern = new(@"^\[(?<time>\d\d[:\.]\d\d[:\.]\d\d) (?<level>[a-z]+)(?: +screen_(?<screen>\d+))? +(?<modName>[^\]]+)\] ", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's initial platform info message.</summary> - private readonly Regex InfoLinePattern = new Regex(@"^SMAPI (?<apiVersion>.+) with Stardew Valley (?<gameVersion>.+) on (?<os>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex InfoLinePattern = new(@"^SMAPI (?<apiVersion>.+) with Stardew Valley (?<gameVersion>.+) on (?<os>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's mod folder path line.</summary> - private readonly Regex ModPathPattern = new Regex(@"^Mods go here: (?<path>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModPathPattern = new(@"^Mods go here: (?<path>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's log timestamp line.</summary> - private readonly Regex LogStartedAtPattern = new Regex(@"^Log started at (?<timestamp>.+) UTC", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex LogStartedAtPattern = new(@"^Log started at (?<timestamp>.+) UTC", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's mod list.</summary> - private readonly Regex ModListStartPattern = new Regex(@"^Loaded \d+ mods:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModListStartPattern = new(@"^Loaded \d+ mods:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's mod list.</summary> /// <remarks>The author name and description are optional.</remarks> - private readonly Regex ModListEntryPattern = new Regex(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))?(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModListEntryPattern = new(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))?(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's content pack list.</summary> - private readonly Regex ContentPackListStartPattern = new Regex(@"^Loaded \d+ content packs:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ContentPackListStartPattern = new(@"^Loaded \d+ content packs:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's content pack list.</summary> - private readonly Regex ContentPackListEntryPattern = new Regex(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))? \| for (?<for>[^\|]+)(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ContentPackListEntryPattern = new(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))? \| for (?<for>[^\|]+)(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's mod update list.</summary> - private readonly Regex ModUpdateListStartPattern = new Regex(@"^You can update \d+ mods?:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModUpdateListStartPattern = new(@"^You can update \d+ mods?:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's mod update list.</summary> - private readonly Regex ModUpdateListEntryPattern = new Regex(@"^ (?<name>.+) (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModUpdateListEntryPattern = new(@"^ (?<name>.+) (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's update line.</summary> - private readonly Regex SmapiUpdatePattern = new Regex(@"^You can update SMAPI to (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex SmapiUpdatePattern = new(@"^You can update SMAPI to (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /********* @@ -53,7 +53,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing *********/ /// <summary>Parse SMAPI log text.</summary> /// <param name="logText">The SMAPI log text.</param> - public ParsedLog Parse(string logText) + public ParsedLog Parse(string? logText) { try { @@ -69,7 +69,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing } // init log - ParsedLog log = new ParsedLog + ParsedLog log = new() { IsValid = true, RawText = logText, @@ -77,8 +77,8 @@ namespace StardewModdingAPI.Web.Framework.LogParsing }; // parse log messages - LogModInfo smapiMod = new LogModInfo { Name = "SMAPI", Author = "Pathoschild", Description = "", Loaded = true }; - LogModInfo gameMod = new LogModInfo { Name = "game", Author = "", Description = "", Loaded = true }; + LogModInfo smapiMod = new(name: "SMAPI", author: "Pathoschild", version: "", description: "", loaded: true); + LogModInfo gameMod = new(name: "game", author: "", version: "", description: "", loaded: true); IDictionary<string, List<LogModInfo>> mods = new Dictionary<string, List<LogModInfo>>(); bool inModList = false; bool inContentPackList = false; @@ -101,7 +101,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing default: if (mods.TryGetValue(message.Mod, out var entries)) { - foreach (var entry in entries) + foreach (LogModInfo entry in entries) entry.Errors++; } break; @@ -131,9 +131,9 @@ namespace StardewModdingAPI.Web.Framework.LogParsing string author = match.Groups["author"].Value; string description = match.Groups["description"].Value; - if (!mods.TryGetValue(name, out List<LogModInfo> entries)) + if (!mods.TryGetValue(name, out List<LogModInfo>? entries)) mods[name] = entries = new List<LogModInfo>(); - entries.Add(new LogModInfo { Name = name, Author = author, Version = version, Description = description, Loaded = true }); + entries.Add(new LogModInfo(name: name, author: author, version: version, description: description, loaded: true)); message.Section = LogSection.ModsList; } @@ -154,9 +154,9 @@ namespace StardewModdingAPI.Web.Framework.LogParsing string description = match.Groups["description"].Value; string forMod = match.Groups["for"].Value; - if (!mods.TryGetValue(name, out List<LogModInfo> entries)) + if (!mods.TryGetValue(name, out List<LogModInfo>? entries)) mods[name] = entries = new List<LogModInfo>(); - entries.Add(new LogModInfo { Name = name, Author = author, Version = version, Description = description, ContentPackFor = forMod, Loaded = true }); + entries.Add(new LogModInfo(name: name, author: author, version: version, description: description, contentPackFor: forMod, loaded: true)); message.Section = LogSection.ContentPackList; } @@ -177,23 +177,19 @@ namespace StardewModdingAPI.Web.Framework.LogParsing if (mods.TryGetValue(name, out var entries)) { - foreach (var entry in entries) - { - entry.UpdateLink = link; - entry.UpdateVersion = version; - } + foreach (LogModInfo entry in entries) + entry.SetUpdate(version, link); } message.Section = LogSection.ModUpdateList; } - else if (message.Level == LogLevel.Alert && this.SmapiUpdatePattern.IsMatch(message.Text)) { Match match = this.SmapiUpdatePattern.Match(message.Text); string version = match.Groups["version"].Value; string link = match.Groups["link"].Value; - smapiMod.UpdateVersion = version; - smapiMod.UpdateLink = link; + + smapiMod.SetUpdate(version, link); } // platform info line @@ -203,7 +199,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing log.ApiVersion = match.Groups["apiVersion"].Value; log.GameVersion = match.Groups["gameVersion"].Value; log.OperatingSystem = match.Groups["os"].Value; - smapiMod.Version = log.ApiVersion; + smapiMod.OverrideVersion(log.ApiVersion); } // mod path line @@ -211,9 +207,9 @@ namespace StardewModdingAPI.Web.Framework.LogParsing { Match match = this.ModPathPattern.Match(message.Text); log.ModPath = match.Groups["path"].Value; - int lastDelimiterPos = log.ModPath.LastIndexOfAny(new char[] { '/', '\\' }); + int lastDelimiterPos = log.ModPath.LastIndexOfAny(new[] { '/', '\\' }); log.GamePath = lastDelimiterPos >= 0 - ? log.ModPath.Substring(0, lastDelimiterPos) + ? log.ModPath[..lastDelimiterPos] : log.ModPath; } @@ -227,7 +223,8 @@ namespace StardewModdingAPI.Web.Framework.LogParsing } // finalize log - gameMod.Version = log.GameVersion; + if (log.GameVersion != null) + gameMod.OverrideVersion(log.GameVersion); log.Mods = new[] { gameMod, smapiMod }.Concat(mods.Values.SelectMany(p => p).OrderBy(p => p.Name)).ToArray(); return log; } @@ -259,7 +256,8 @@ namespace StardewModdingAPI.Web.Framework.LogParsing /// <param name="messages">The messages to filter.</param> private IEnumerable<LogMessage> CollapseRepeats(IEnumerable<LogMessage> messages) { - LogMessage next = null; + LogMessage? next = null; + foreach (LogMessage message in messages) { // new message @@ -280,7 +278,9 @@ namespace StardewModdingAPI.Web.Framework.LogParsing yield return next; next = message; } - yield return next; + + if (next != null) + yield return next; } /// <summary>Split a SMAPI log into individual log messages.</summary> @@ -288,12 +288,12 @@ namespace StardewModdingAPI.Web.Framework.LogParsing /// <exception cref="LogParseException">The log text can't be parsed successfully.</exception> private IEnumerable<LogMessage> GetMessages(string logText) { - LogMessageBuilder builder = new LogMessageBuilder(); - using StringReader reader = new StringReader(logText); + LogMessageBuilder builder = new(); + using StringReader reader = new(logText); while (true) { // read line - string line = reader.ReadLine(); + string? line = reader.ReadLine(); if (line == null) break; @@ -306,17 +306,17 @@ namespace StardewModdingAPI.Web.Framework.LogParsing { if (builder.Started) { - yield return builder.Build(); + yield return builder.Build()!; builder.Clear(); } - var screenGroup = header.Groups["screen"]; + Group screenGroup = header.Groups["screen"]; builder.Start( time: header.Groups["time"].Value, level: Enum.Parse<LogLevel>(header.Groups["level"].Value, ignoreCase: true), screenId: screenGroup.Success ? int.Parse(screenGroup.Value) : 0, // main player is always screen ID 0 mod: header.Groups["modName"].Value, - text: line.Substring(header.Length) + text: line[header.Length..] ); } else @@ -330,7 +330,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing // end last message if (builder.Started) - yield return builder.Build(); + yield return builder.Build()!; } } } diff --git a/src/SMAPI.Web/Framework/LogParsing/Models/LogMessage.cs b/src/SMAPI.Web/Framework/LogParsing/Models/LogMessage.cs index 1e08be78..7a5f32e0 100644 --- a/src/SMAPI.Web/Framework/LogParsing/Models/LogMessage.cs +++ b/src/SMAPI.Web/Framework/LogParsing/Models/LogMessage.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace StardewModdingAPI.Web.Framework.LogParsing.Models { /// <summary>A parsed log message.</summary> @@ -7,19 +9,19 @@ namespace StardewModdingAPI.Web.Framework.LogParsing.Models ** Accessors *********/ /// <summary>The local time when the log was posted.</summary> - public string Time { get; set; } + public string Time { get; } /// <summary>The log level.</summary> - public LogLevel Level { get; set; } + public LogLevel Level { get; } /// <summary>The screen ID in split-screen mode.</summary> - public int ScreenId { get; set; } + public int ScreenId { get; } /// <summary>The mod name.</summary> - public string Mod { get; set; } + public string Mod { get; } /// <summary>The log text.</summary> - public string Text { get; set; } + public string Text { get; } /// <summary>The number of times this message was repeated consecutively.</summary> public int Repeated { get; set; } @@ -28,6 +30,32 @@ namespace StardewModdingAPI.Web.Framework.LogParsing.Models public LogSection? Section { get; set; } /// <summary>Whether this message is the first one of its section.</summary> + [MemberNotNullWhen(true, nameof(LogMessage.Section))] public bool IsStartOfSection { get; set; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance/</summary> + /// <param name="time">The local time when the log was posted.</param> + /// <param name="level">The log level.</param> + /// <param name="screenId">The screen ID in split-screen mode.</param> + /// <param name="mod">The mod name.</param> + /// <param name="text">The log text.</param> + /// <param name="repeated">The number of times this message was repeated consecutively.</param> + /// <param name="section">The section that this log message belongs to.</param> + /// <param name="isStartOfSection">Whether this message is the first one of its section.</param> + public LogMessage(string time, LogLevel level, int screenId, string mod, string text, int repeated = 0, LogSection? section = null, bool isStartOfSection = false) + { + this.Time = time; + this.Level = level; + this.ScreenId = screenId; + this.Mod = mod; + this.Text = text; + this.Repeated = repeated; + this.Section = section; + this.IsStartOfSection = isStartOfSection; + } } } diff --git a/src/SMAPI.Web/Framework/LogParsing/Models/LogModInfo.cs b/src/SMAPI.Web/Framework/LogParsing/Models/LogModInfo.cs index 067e4df4..a6b9165c 100644 --- a/src/SMAPI.Web/Framework/LogParsing/Models/LogModInfo.cs +++ b/src/SMAPI.Web/Framework/LogParsing/Models/LogModInfo.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace StardewModdingAPI.Web.Framework.LogParsing.Models { /// <summary>Metadata about a mod or content pack in the log.</summary> @@ -7,33 +9,81 @@ namespace StardewModdingAPI.Web.Framework.LogParsing.Models ** Accessors *********/ /// <summary>The mod name.</summary> - public string Name { get; set; } + public string Name { get; } /// <summary>The mod author.</summary> - public string Author { get; set; } - - /// <summary>The update version.</summary> - public string UpdateVersion { get; set; } - - /// <summary>The update link.</summary> - public string UpdateLink { get; set; } + public string Author { get; } /// <summary>The mod version.</summary> - public string Version { get; set; } + public string Version { get; private set; } /// <summary>The mod description.</summary> - public string Description { get; set; } + public string Description { get; } + + /// <summary>The update version.</summary> + public string? UpdateVersion { get; private set; } + + /// <summary>The update link.</summary> + public string? UpdateLink { get; private set; } /// <summary>The name of the mod for which this is a content pack (if applicable).</summary> - public string ContentPackFor { get; set; } + public string? ContentPackFor { get; } /// <summary>The number of errors logged by this mod.</summary> public int Errors { get; set; } /// <summary>Whether the mod was loaded into the game.</summary> - public bool Loaded { get; set; } + public bool Loaded { get; } /// <summary>Whether the mod has an update available.</summary> + [MemberNotNullWhen(true, nameof(LogModInfo.UpdateVersion), nameof(LogModInfo.UpdateLink))] public bool HasUpdate => this.UpdateVersion != null && this.Version != this.UpdateVersion; + + /// <summary>Whether the mod is a content pack for another mod.</summary> + [MemberNotNullWhen(true, nameof(LogModInfo.ContentPackFor))] + public bool IsContentPack => !string.IsNullOrWhiteSpace(this.ContentPackFor); + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="name">The mod name.</param> + /// <param name="author">The mod author.</param> + /// <param name="version">The mod version.</param> + /// <param name="description">The mod description.</param> + /// <param name="updateVersion">The update version.</param> + /// <param name="updateLink">The update link.</param> + /// <param name="contentPackFor">The name of the mod for which this is a content pack (if applicable).</param> + /// <param name="errors">The number of errors logged by this mod.</param> + /// <param name="loaded">Whether the mod was loaded into the game.</param> + public LogModInfo(string name, string author, string version, string description, string? updateVersion = null, string? updateLink = null, string? contentPackFor = null, int errors = 0, bool loaded = true) + { + this.Name = name; + this.Author = author; + this.Version = version; + this.Description = description; + this.UpdateVersion = updateVersion; + this.UpdateLink = updateLink; + this.ContentPackFor = contentPackFor; + this.Errors = errors; + this.Loaded = loaded; + } + + /// <summary>Add an update alert for this mod.</summary> + /// <param name="updateVersion">The update version.</param> + /// <param name="updateLink">The update link.</param> + public void SetUpdate(string updateVersion, string updateLink) + { + this.UpdateVersion = updateVersion; + this.UpdateLink = updateLink; + } + + /// <summary>Override the version number, for cases like SMAPI itself where the version is only known later during parsing.</summary> + /// <param name="version">The new mod version.</param> + public void OverrideVersion(string version) + { + this.Version = version; + } } } diff --git a/src/SMAPI.Web/Framework/LogParsing/Models/ParsedLog.cs b/src/SMAPI.Web/Framework/LogParsing/Models/ParsedLog.cs index 87b20eb0..6951e434 100644 --- a/src/SMAPI.Web/Framework/LogParsing/Models/ParsedLog.cs +++ b/src/SMAPI.Web/Framework/LogParsing/Models/ParsedLog.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace StardewModdingAPI.Web.Framework.LogParsing.Models { @@ -12,39 +13,40 @@ namespace StardewModdingAPI.Web.Framework.LogParsing.Models ** Metadata ****/ /// <summary>Whether the log file was successfully parsed.</summary> + [MemberNotNullWhen(true, nameof(ParsedLog.RawText))] public bool IsValid { get; set; } /// <summary>An error message indicating why the log file is invalid.</summary> - public string Error { get; set; } + public string? Error { get; set; } /// <summary>The raw log text.</summary> - public string RawText { get; set; } + public string? RawText { get; set; } /**** ** Log data ****/ /// <summary>The SMAPI version.</summary> - public string ApiVersion { get; set; } + public string? ApiVersion { get; set; } /// <summary>The game version.</summary> - public string GameVersion { get; set; } + public string? GameVersion { get; set; } /// <summary>The player's operating system.</summary> - public string OperatingSystem { get; set; } + public string? OperatingSystem { get; set; } /// <summary>The game install path.</summary> - public string GamePath { get; set; } + public string? GamePath { get; set; } /// <summary>The mod folder path.</summary> - public string ModPath { get; set; } + public string? ModPath { get; set; } /// <summary>The ISO 8601 timestamp when the log was started.</summary> public DateTimeOffset Timestamp { get; set; } /// <summary>Metadata about installed mods and content packs.</summary> - public LogModInfo[] Mods { get; set; } = new LogModInfo[0]; + public LogModInfo[] Mods { get; set; } = Array.Empty<LogModInfo>(); /// <summary>The log messages.</summary> - public LogMessage[] Messages { get; set; } + public LogMessage[] Messages { get; set; } = Array.Empty<LogMessage>(); } } diff --git a/src/SMAPI.Web/Framework/ModInfoModel.cs b/src/SMAPI.Web/Framework/ModInfoModel.cs index 7845b8c5..e70b60bf 100644 --- a/src/SMAPI.Web/Framework/ModInfoModel.cs +++ b/src/SMAPI.Web/Framework/ModInfoModel.cs @@ -1,4 +1,5 @@ -using StardewModdingAPI.Web.Framework.Clients; +using System.Diagnostics.CodeAnalysis; +using Newtonsoft.Json; namespace StardewModdingAPI.Web.Framework { @@ -9,22 +10,22 @@ namespace StardewModdingAPI.Web.Framework ** Accessors *********/ /// <summary>The mod name.</summary> - public string Name { get; set; } + public string? Name { get; private set; } + + /// <summary>The mod's web URL.</summary> + public string? Url { get; private set; } /// <summary>The mod's latest version.</summary> - public ISemanticVersion Version { get; set; } + public ISemanticVersion? Version { get; private set; } /// <summary>The mod's latest optional or prerelease version, if newer than <see cref="Version"/>.</summary> - public ISemanticVersion PreviewVersion { get; set; } - - /// <summary>The mod's web URL.</summary> - public string Url { get; set; } + public ISemanticVersion? PreviewVersion { get; private set; } /// <summary>The mod availability status on the remote site.</summary> - public RemoteModStatus Status { get; set; } = RemoteModStatus.Ok; + public RemoteModStatus Status { get; private set; } /// <summary>The error message indicating why the mod is invalid (if applicable).</summary> - public string Error { get; set; } + public string? Error { get; private set; } /********* @@ -35,19 +36,24 @@ namespace StardewModdingAPI.Web.Framework /// <summary>Construct an instance.</summary> /// <param name="name">The mod name.</param> + /// <param name="url">The mod's web URL.</param> /// <param name="version">The semantic version for the mod's latest release.</param> /// <param name="previewVersion">The semantic version for the mod's latest preview release, if available and different from <see cref="Version"/>.</param> - /// <param name="url">The mod's web URL.</param> - public ModInfoModel(string name, ISemanticVersion version, string url, ISemanticVersion previewVersion = null) + /// <param name="status">The mod availability status on the remote site.</param> + /// <param name="error">The error message indicating why the mod is invalid (if applicable).</param> + [JsonConstructor] + public ModInfoModel(string name, string url, ISemanticVersion? version, ISemanticVersion? previewVersion = null, RemoteModStatus status = RemoteModStatus.Ok, string? error = null) { this .SetBasicInfo(name, url) - .SetVersions(version, previewVersion); + .SetVersions(version!, previewVersion) + .SetError(status, error!); } /// <summary>Set the basic mod info.</summary> /// <param name="name">The mod name.</param> /// <param name="url">The mod's web URL.</param> + [MemberNotNull(nameof(ModInfoModel.Name), nameof(ModInfoModel.Url))] public ModInfoModel SetBasicInfo(string name, string url) { this.Name = name; @@ -59,7 +65,8 @@ namespace StardewModdingAPI.Web.Framework /// <summary>Set the mod version info.</summary> /// <param name="version">The semantic version for the mod's latest release.</param> /// <param name="previewVersion">The semantic version for the mod's latest preview release, if available and different from <see cref="Version"/>.</param> - public ModInfoModel SetVersions(ISemanticVersion version, ISemanticVersion previewVersion = null) + [MemberNotNull(nameof(ModInfoModel.Version))] + public ModInfoModel SetVersions(ISemanticVersion version, ISemanticVersion? previewVersion = null) { this.Version = version; this.PreviewVersion = previewVersion; diff --git a/src/SMAPI.Web/Framework/ModSiteManager.cs b/src/SMAPI.Web/Framework/ModSiteManager.cs index a2b92aa4..674b9ffc 100644 --- a/src/SMAPI.Web/Framework/ModSiteManager.cs +++ b/src/SMAPI.Web/Framework/ModSiteManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -34,12 +35,15 @@ namespace StardewModdingAPI.Web.Framework /// <param name="updateKey">The namespaced update key.</param> public async Task<IModPage> GetModPageAsync(UpdateKey updateKey) { + if (!updateKey.LooksValid) + return new GenericModPage(updateKey.Site, updateKey.ID!).SetError(RemoteModStatus.DoesNotExist, $"Invalid update key '{updateKey}'."); + // get site - if (!this.ModSites.TryGetValue(updateKey.Site, out IModSiteClient client)) + if (!this.ModSites.TryGetValue(updateKey.Site, out IModSiteClient? client)) return new GenericModPage(updateKey.Site, updateKey.ID).SetError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{updateKey.Site}'. Expected one of [{string.Join(", ", this.ModSites.Keys)}]."); // fetch mod - IModPage mod; + IModPage? mod; try { mod = await client.GetModData(updateKey.ID); @@ -58,39 +62,42 @@ namespace StardewModdingAPI.Web.Framework /// <param name="subkey">The optional update subkey to match in available files. (If no file names or descriptions contain the subkey, it'll be ignored.)</param> /// <param name="mapRemoteVersions">The changes to apply to remote versions for update checks.</param> /// <param name="allowNonStandardVersions">Whether to allow non-standard versions.</param> - public ModInfoModel GetPageVersions(IModPage page, string subkey, bool allowNonStandardVersions, ChangeDescriptor mapRemoteVersions) + public ModInfoModel GetPageVersions(IModPage page, string? subkey, bool allowNonStandardVersions, ChangeDescriptor? mapRemoteVersions) { // get base model - ModInfoModel model = new ModInfoModel() - .SetBasicInfo(page.Name, page.Url) - .SetError(page.Status, page.Error); - if (page.Status != RemoteModStatus.Ok) + ModInfoModel model = new(); + if (page.IsValid) + model.SetBasicInfo(page.Name, page.Url); + else + { + model.SetError(page.Status, page.Error); return model; + } // fetch versions - bool hasVersions = this.TryGetLatestVersions(page, subkey, allowNonStandardVersions, mapRemoteVersions, out ISemanticVersion mainVersion, out ISemanticVersion previewVersion); + bool hasVersions = this.TryGetLatestVersions(page, subkey, allowNonStandardVersions, mapRemoteVersions, out ISemanticVersion? mainVersion, out ISemanticVersion? previewVersion); if (!hasVersions && subkey != null) hasVersions = this.TryGetLatestVersions(page, null, allowNonStandardVersions, mapRemoteVersions, out mainVersion, out previewVersion); if (!hasVersions) return model.SetError(RemoteModStatus.InvalidData, $"The {page.Site} mod with ID '{page.Id}' has no valid versions."); // return info - return model.SetVersions(mainVersion, previewVersion); + return model.SetVersions(mainVersion!, previewVersion); } /// <summary>Get a semantic local version for update checks.</summary> /// <param name="version">The version to parse.</param> /// <param name="map">Changes to apply to the raw version, if any.</param> /// <param name="allowNonStandard">Whether to allow non-standard versions.</param> - public ISemanticVersion GetMappedVersion(string version, ChangeDescriptor map, bool allowNonStandard) + public ISemanticVersion? GetMappedVersion(string? version, ChangeDescriptor? map, bool allowNonStandard) { // try mapped version - string rawNewVersion = this.GetRawMappedVersion(version, map, allowNonStandard); - if (SemanticVersion.TryParse(rawNewVersion, allowNonStandard, out ISemanticVersion parsedNew)) + string? rawNewVersion = this.GetRawMappedVersion(version, map); + if (SemanticVersion.TryParse(rawNewVersion, allowNonStandard, out ISemanticVersion? parsedNew)) return parsedNew; // return original version - return SemanticVersion.TryParse(version, allowNonStandard, out ISemanticVersion parsedOld) + return SemanticVersion.TryParse(version, allowNonStandard, out ISemanticVersion? parsedOld) ? parsedOld : null; } @@ -106,31 +113,31 @@ namespace StardewModdingAPI.Web.Framework /// <param name="mapRemoteVersions">The changes to apply to remote versions for update checks.</param> /// <param name="main">The main mod version.</param> /// <param name="preview">The latest prerelease version, if newer than <paramref name="main"/>.</param> - private bool TryGetLatestVersions(IModPage mod, string subkey, bool allowNonStandardVersions, ChangeDescriptor mapRemoteVersions, out ISemanticVersion main, out ISemanticVersion preview) + private bool TryGetLatestVersions(IModPage? mod, string? subkey, bool allowNonStandardVersions, ChangeDescriptor? mapRemoteVersions, [NotNullWhen(true)] out ISemanticVersion? main, out ISemanticVersion? preview) { main = null; preview = null; // parse all versions from the mod page - IEnumerable<(string name, string description, ISemanticVersion version)> GetAllVersions() + IEnumerable<(string? name, string? description, ISemanticVersion? version)> GetAllVersions() { if (mod != null) { - ISemanticVersion ParseAndMapVersion(string raw) + ISemanticVersion? ParseAndMapVersion(string? raw) { raw = this.NormalizeVersion(raw); return this.GetMappedVersion(raw, mapRemoteVersions, allowNonStandardVersions); } // get mod version - ISemanticVersion modVersion = ParseAndMapVersion(mod.Version); + ISemanticVersion? modVersion = ParseAndMapVersion(mod.Version); if (modVersion != null) yield return (name: null, description: null, version: ParseAndMapVersion(mod.Version)); // get file versions foreach (IModDownload download in mod.Downloads) { - ISemanticVersion cur = ParseAndMapVersion(download.Version); + ISemanticVersion? cur = ParseAndMapVersion(download.Version); if (cur != null) yield return (download.Name, download.Description, cur); } @@ -141,15 +148,15 @@ namespace StardewModdingAPI.Web.Framework .ToArray(); // get main + preview versions - void TryGetVersions(out ISemanticVersion mainVersion, out ISemanticVersion previewVersion, Func<(string name, string description, ISemanticVersion version), bool> filter = null) + void TryGetVersions([NotNullWhen(true)] out ISemanticVersion? mainVersion, out ISemanticVersion? previewVersion, Func<(string? name, string? description, ISemanticVersion? version), bool>? filter = null) { mainVersion = null; previewVersion = null; // get latest main + preview version - foreach (var entry in versions) + foreach ((string? name, string? description, ISemanticVersion? version) entry in versions) { - if (filter?.Invoke(entry) == false) + if (entry.version is null || filter?.Invoke(entry) == false) continue; if (entry.version.IsPrerelease()) @@ -158,7 +165,7 @@ namespace StardewModdingAPI.Web.Framework mainVersion ??= entry.version; if (mainVersion != null) - break; // any other values will be older + break; // any others will be older since entries are sorted by version } // normalize values @@ -181,8 +188,7 @@ namespace StardewModdingAPI.Web.Framework /// <summary>Get a semantic local version for update checks.</summary> /// <param name="version">The version to map.</param> /// <param name="map">Changes to apply to the raw version, if any.</param> - /// <param name="allowNonStandard">Whether to allow non-standard versions.</param> - private string GetRawMappedVersion(string version, ChangeDescriptor map, bool allowNonStandard) + private string? GetRawMappedVersion(string? version, ChangeDescriptor? map) { if (version == null || map?.HasChanges != true) return version; @@ -195,7 +201,7 @@ namespace StardewModdingAPI.Web.Framework /// <summary>Normalize a version string.</summary> /// <param name="version">The version to normalize.</param> - private string NormalizeVersion(string version) + private string? NormalizeVersion(string? version) { if (string.IsNullOrWhiteSpace(version)) return null; diff --git a/src/SMAPI.Web/Framework/RedirectRules/RedirectHostsToUrlsRule.cs b/src/SMAPI.Web/Framework/RedirectRules/RedirectHostsToUrlsRule.cs index d75ee791..7b8f0ec9 100644 --- a/src/SMAPI.Web/Framework/RedirectRules/RedirectHostsToUrlsRule.cs +++ b/src/SMAPI.Web/Framework/RedirectRules/RedirectHostsToUrlsRule.cs @@ -11,7 +11,7 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules ** Fields *********/ /// <summary>Maps a lowercase hostname to the resulting redirect URL.</summary> - private readonly Func<string, string> Map; + private readonly Func<string, string?> Map; /********* @@ -20,7 +20,7 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <summary>Construct an instance.</summary> /// <param name="statusCode">The status code to use for redirects.</param> /// <param name="map">Hostnames mapped to the resulting redirect URL.</param> - public RedirectHostsToUrlsRule(HttpStatusCode statusCode, Func<string, string> map) + public RedirectHostsToUrlsRule(HttpStatusCode statusCode, Func<string, string?> map) { this.StatusCode = statusCode; this.Map = map ?? throw new ArgumentNullException(nameof(map)); @@ -33,12 +33,10 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <summary>Get the new redirect URL.</summary> /// <param name="context">The rewrite context.</param> /// <returns>Returns the redirect URL, or <c>null</c> if the redirect doesn't apply.</returns> - protected override string GetNewUrl(RewriteContext context) + protected override string? GetNewUrl(RewriteContext context) { // get requested host - string host = context.HttpContext.Request.Host.Host; - if (host == null) - return null; + string? host = context.HttpContext.Request.Host.Host; // get new host host = this.Map(host); diff --git a/src/SMAPI.Web/Framework/RedirectRules/RedirectMatchRule.cs b/src/SMAPI.Web/Framework/RedirectRules/RedirectMatchRule.cs index 6e81c4ca..b46e8f69 100644 --- a/src/SMAPI.Web/Framework/RedirectRules/RedirectMatchRule.cs +++ b/src/SMAPI.Web/Framework/RedirectRules/RedirectMatchRule.cs @@ -22,7 +22,7 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <param name="context">The rewrite context.</param> public void ApplyRule(RewriteContext context) { - string newUrl = this.GetNewUrl(context); + string? newUrl = this.GetNewUrl(context); if (newUrl == null) return; @@ -39,7 +39,7 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <summary>Get the new redirect URL.</summary> /// <param name="context">The rewrite context.</param> /// <returns>Returns the redirect URL, or <c>null</c> if the redirect doesn't apply.</returns> - protected abstract string GetNewUrl(RewriteContext context); + protected abstract string? GetNewUrl(RewriteContext context); /// <summary>Get the full request URL.</summary> /// <param name="request">The request.</param> diff --git a/src/SMAPI.Web/Framework/RedirectRules/RedirectPathsToUrlsRule.cs b/src/SMAPI.Web/Framework/RedirectRules/RedirectPathsToUrlsRule.cs index d9d44641..e691ffba 100644 --- a/src/SMAPI.Web/Framework/RedirectRules/RedirectPathsToUrlsRule.cs +++ b/src/SMAPI.Web/Framework/RedirectRules/RedirectPathsToUrlsRule.cs @@ -37,9 +37,9 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <summary>Get the new redirect URL.</summary> /// <param name="context">The rewrite context.</param> /// <returns>Returns the redirect URL, or <c>null</c> if the redirect doesn't apply.</returns> - protected override string GetNewUrl(RewriteContext context) + protected override string? GetNewUrl(RewriteContext context) { - string path = context.HttpContext.Request.Path.Value; + string? path = context.HttpContext.Request.Path.Value; if (!string.IsNullOrWhiteSpace(path)) { diff --git a/src/SMAPI.Web/Framework/RedirectRules/RedirectToHttpsRule.cs b/src/SMAPI.Web/Framework/RedirectRules/RedirectToHttpsRule.cs index 2a503ae3..01807608 100644 --- a/src/SMAPI.Web/Framework/RedirectRules/RedirectToHttpsRule.cs +++ b/src/SMAPI.Web/Framework/RedirectRules/RedirectToHttpsRule.cs @@ -20,9 +20,9 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules *********/ /// <summary>Construct an instance.</summary> /// <param name="except">Matches requests which should be ignored.</param> - public RedirectToHttpsRule(Func<HttpRequest, bool> except = null) + public RedirectToHttpsRule(Func<HttpRequest, bool>? except = null) { - this.Except = except ?? (req => false); + this.Except = except ?? (_ => false); this.StatusCode = HttpStatusCode.RedirectKeepVerb; } @@ -33,7 +33,7 @@ namespace StardewModdingAPI.Web.Framework.RedirectRules /// <summary>Get the new redirect URL.</summary> /// <param name="context">The rewrite context.</param> /// <returns>Returns the redirect URL, or <c>null</c> if the redirect doesn't apply.</returns> - protected override string GetNewUrl(RewriteContext context) + protected override string? GetNewUrl(RewriteContext context) { HttpRequest request = context.HttpContext.Request; if (request.IsHttps || this.Except(request)) diff --git a/src/SMAPI.Web/Framework/Storage/StorageProvider.cs b/src/SMAPI.Web/Framework/Storage/StorageProvider.cs index c6f8bac1..effbbc9f 100644 --- a/src/SMAPI.Web/Framework/Storage/StorageProvider.cs +++ b/src/SMAPI.Web/Framework/Storage/StorageProvider.cs @@ -63,11 +63,11 @@ namespace StardewModdingAPI.Web.Framework.Storage BlobClient blob = this.GetAzureBlobClient(id); await blob.UploadAsync(stream); - return new UploadResult(true, id, null); + return new UploadResult(id, null); } catch (Exception ex) { - return new UploadResult(false, null, ex.Message); + return new UploadResult(null, ex.Message); } } @@ -75,10 +75,10 @@ namespace StardewModdingAPI.Web.Framework.Storage else { string path = this.GetDevFilePath(id); - Directory.CreateDirectory(Path.GetDirectoryName(path)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, content); - return new UploadResult(true, id, null); + return new UploadResult(id, null); } } @@ -103,26 +103,20 @@ namespace StardewModdingAPI.Web.Framework.Storage // fetch file Response<BlobDownloadInfo> response = await blob.DownloadAsync(); using BlobDownloadInfo result = response.Value; - using StreamReader reader = new StreamReader(result.Content); + using StreamReader reader = new(result.Content); DateTimeOffset expiry = result.Details.LastModified + TimeSpan.FromDays(this.ExpiryDays); string content = this.GzipHelper.DecompressString(reader.ReadToEnd()); // build model - return new StoredFileInfo - { - Success = true, - Content = content, - Expiry = expiry.UtcDateTime - }; + return new StoredFileInfo(content, expiry); } catch (RequestFailedException ex) { - return new StoredFileInfo - { - Error = ex.ErrorCode == "BlobNotFound" + return new StoredFileInfo( + error: ex.ErrorCode == "BlobNotFound" ? "There's no file with that ID." : $"Could not fetch that file from storage ({ex.ErrorCode}: {ex.Message})." - }; + ); } } @@ -130,15 +124,12 @@ namespace StardewModdingAPI.Web.Framework.Storage else { // get file - FileInfo file = new FileInfo(this.GetDevFilePath(id)); + FileInfo file = new(this.GetDevFilePath(id)); if (file.Exists && file.LastWriteTimeUtc.AddDays(this.ExpiryDays) < DateTime.UtcNow) // expired file.Delete(); if (!file.Exists) { - return new StoredFileInfo - { - Error = "There's no file with that ID." - }; + return new StoredFileInfo(error: "There's no file with that ID."); } // renew @@ -149,13 +140,11 @@ namespace StardewModdingAPI.Web.Framework.Storage } // build model - return new StoredFileInfo - { - Success = true, - Content = File.ReadAllText(file.FullName), - Expiry = DateTime.UtcNow.AddDays(this.ExpiryDays), - Warning = "This file was saved temporarily to the local computer. This should only happen in a local development environment." - }; + return new StoredFileInfo( + content: File.ReadAllText(file.FullName), + expiry: DateTime.UtcNow.AddDays(this.ExpiryDays), + warning: "This file was saved temporarily to the local computer. This should only happen in a local development environment." + ); } } @@ -164,12 +153,7 @@ namespace StardewModdingAPI.Web.Framework.Storage { PasteInfo response = await this.Pastebin.GetAsync(id); response.Content = this.GzipHelper.DecompressString(response.Content); - return new StoredFileInfo - { - Success = response.Success, - Content = response.Content, - Error = response.Error - }; + return new StoredFileInfo(response.Content, null, error: response.Error); } } @@ -177,8 +161,8 @@ namespace StardewModdingAPI.Web.Framework.Storage /// <param name="id">The file ID.</param> private BlobClient GetAzureBlobClient(string id) { - var azure = new BlobServiceClient(this.ClientsConfig.AzureBlobConnectionString); - var container = azure.GetBlobContainerClient(this.ClientsConfig.AzureBlobTempContainer); + BlobServiceClient azure = new(this.ClientsConfig.AzureBlobConnectionString); + BlobContainerClient container = azure.GetBlobContainerClient(this.ClientsConfig.AzureBlobTempContainer); return container.GetBlobClient($"uploads/{id}"); } diff --git a/src/SMAPI.Web/Framework/Storage/StoredFileInfo.cs b/src/SMAPI.Web/Framework/Storage/StoredFileInfo.cs index 30676c88..bbbcf2a9 100644 --- a/src/SMAPI.Web/Framework/Storage/StoredFileInfo.cs +++ b/src/SMAPI.Web/Framework/Storage/StoredFileInfo.cs @@ -1,23 +1,52 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace StardewModdingAPI.Web.Framework.Storage { /// <summary>The response for a get-file request.</summary> internal class StoredFileInfo { + /********* + ** Accessors + *********/ /// <summary>Whether the file was successfully fetched.</summary> - public bool Success { get; set; } + [MemberNotNullWhen(true, nameof(StoredFileInfo.Content))] + public bool Success => this.Content != null && this.Error == null; /// <summary>The fetched file content (if <see cref="Success"/> is <c>true</c>).</summary> - public string Content { get; set; } + public string? Content { get; } /// <summary>When the file will no longer be available.</summary> - public DateTime? Expiry { get; set; } + public DateTimeOffset? Expiry { get; } /// <summary>The error message if saving succeeded, but a non-blocking issue was encountered.</summary> - public string Warning { get; set; } + public string? Warning { get; } /// <summary>The error message if saving failed.</summary> - public string Error { get; set; } + public string? Error { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="content">The fetched file content (if <see cref="Success"/> is <c>true</c>).</param> + /// <param name="expiry">When the file will no longer be available.</param> + /// <param name="warning">The error message if saving succeeded, but a non-blocking issue was encountered.</param> + /// <param name="error">The error message if saving failed.</param> + public StoredFileInfo(string? content, DateTimeOffset? expiry, string? warning = null, string? error = null) + { + this.Content = content; + this.Expiry = expiry; + this.Warning = warning; + this.Error = error; + } + + /// <summary>Construct an instance.</summary> + /// <param name="error">The error message if saving failed.</param> + public StoredFileInfo(string error) + { + this.Error = error; + } } } diff --git a/src/SMAPI.Web/Framework/Storage/UploadResult.cs b/src/SMAPI.Web/Framework/Storage/UploadResult.cs index 483c1769..92993d42 100644 --- a/src/SMAPI.Web/Framework/Storage/UploadResult.cs +++ b/src/SMAPI.Web/Framework/Storage/UploadResult.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace StardewModdingAPI.Web.Framework.Storage { /// <summary>The result of an attempt to upload a file.</summary> @@ -7,25 +9,25 @@ namespace StardewModdingAPI.Web.Framework.Storage ** Accessors *********/ /// <summary>Whether the file upload succeeded.</summary> - public bool Succeeded { get; } + [MemberNotNullWhen(true, nameof(UploadResult.ID))] + [MemberNotNullWhen(false, nameof(UploadResult.UploadError))] + public bool Succeeded => this.ID != null && this.UploadError == null; /// <summary>The file ID, if applicable.</summary> - public string ID { get; } + public string? ID { get; } /// <summary>The upload error, if any.</summary> - public string UploadError { get; } + public string? UploadError { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - /// <param name="succeeded">Whether the file upload succeeded.</param> /// <param name="id">The file ID, if applicable.</param> /// <param name="uploadError">The upload error, if any.</param> - public UploadResult(bool succeeded, string id, string uploadError) + public UploadResult(string? id, string? uploadError) { - this.Succeeded = succeeded; this.ID = id; this.UploadError = uploadError; } diff --git a/src/SMAPI.Web/Framework/VersionConstraint.cs b/src/SMAPI.Web/Framework/VersionConstraint.cs index f0c57c41..1b1abd81 100644 --- a/src/SMAPI.Web/Framework/VersionConstraint.cs +++ b/src/SMAPI.Web/Framework/VersionConstraint.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Web.Framework /// <param name="values">A dictionary that contains the parameters for the URL.</param> /// <param name="routeDirection">An object that indicates whether the constraint check is being performed when an incoming request is being handled or when a URL is being generated.</param> /// <returns><c>true</c> if the URL parameter contains a valid value; otherwise, <c>false</c>.</returns> - public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) + public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (routeKey == null) throw new ArgumentNullException(nameof(routeKey)); @@ -26,7 +26,7 @@ namespace StardewModdingAPI.Web.Framework throw new ArgumentNullException(nameof(values)); return - values.TryGetValue(routeKey, out object routeValue) + values.TryGetValue(routeKey, out object? routeValue) && routeValue is string routeStr && SemanticVersion.TryParse(routeStr, allowNonStandard: true, out _); } diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index d8561172..2693aa90 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -81,7 +81,7 @@ namespace StardewModdingAPI.Web // init Hangfire services - .AddHangfire((serv, config) => + .AddHangfire((_, config) => { config .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) @@ -100,7 +100,7 @@ namespace StardewModdingAPI.Web // init API clients { ApiClientsConfig api = this.Configuration.GetSection("ApiClients").Get<ApiClientsConfig>(); - string version = this.GetType().Assembly.GetName().Version.ToString(3); + string version = this.GetType().Assembly.GetName().Version!.ToString(3); string userAgent = string.Format(api.UserAgent, version); services.AddSingleton<IChucklefishClient>(new ChucklefishClient( @@ -128,14 +128,21 @@ namespace StardewModdingAPI.Web modUrlFormat: api.ModDropModPageUrl )); - services.AddSingleton<INexusClient>(new NexusClient( - webUserAgent: userAgent, - webBaseUrl: api.NexusBaseUrl, - webModUrlFormat: api.NexusModUrlFormat, - webModScrapeUrlFormat: api.NexusModScrapeUrlFormat, - apiAppVersion: version, - apiKey: api.NexusApiKey - )); + if (!string.IsNullOrWhiteSpace(api.NexusApiKey)) + { + services.AddSingleton<INexusClient>(new NexusClient( + webUserAgent: userAgent, + webBaseUrl: api.NexusBaseUrl, + webModUrlFormat: api.NexusModUrlFormat, + webModScrapeUrlFormat: api.NexusModScrapeUrlFormat, + apiAppVersion: version, + apiKey: api.NexusApiKey + )); + } + else + { + services.AddSingleton<INexusClient>(new DisabledNexusClient()); + } services.AddSingleton<IPastebinClient>(new PastebinClient( baseUrl: api.PastebinBaseUrl, diff --git a/src/SMAPI.Web/ViewModels/IndexModel.cs b/src/SMAPI.Web/ViewModels/IndexModel.cs index d8d2d27f..098f18cc 100644 --- a/src/SMAPI.Web/ViewModels/IndexModel.cs +++ b/src/SMAPI.Web/ViewModels/IndexModel.cs @@ -7,26 +7,23 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The latest stable SMAPI version.</summary> - public IndexVersionModel StableVersion { get; set; } + public IndexVersionModel StableVersion { get; } /// <summary>A message to show below the download button (e.g. for details on downloading a beta version), in Markdown format.</summary> - public string OtherBlurb { get; set; } + public string? OtherBlurb { get; } /// <summary>A list of supports to credit on the main page, in Markdown format.</summary> - public string SupporterList { get; set; } + public string? SupporterList { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public IndexModel() { } - - /// <summary>Construct an instance.</summary> /// <param name="stableVersion">The latest stable SMAPI version.</param> /// <param name="otherBlurb">A message to show below the download button (e.g. for details on downloading a beta version), in Markdown format.</param> /// <param name="supporterList">A list of supports to credit on the main page, in Markdown format.</param> - internal IndexModel(IndexVersionModel stableVersion, string otherBlurb, string supporterList) + internal IndexModel(IndexVersionModel stableVersion, string? otherBlurb, string? supporterList) { this.StableVersion = stableVersion; this.OtherBlurb = otherBlurb; diff --git a/src/SMAPI.Web/ViewModels/IndexVersionModel.cs b/src/SMAPI.Web/ViewModels/IndexVersionModel.cs index 4f63b979..a76a5924 100644 --- a/src/SMAPI.Web/ViewModels/IndexVersionModel.cs +++ b/src/SMAPI.Web/ViewModels/IndexVersionModel.cs @@ -7,30 +7,27 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The release version.</summary> - public string Version { get; set; } + public string Version { get; } /// <summary>The Markdown description for the release.</summary> - public string Description { get; set; } + public string Description { get; } /// <summary>The main download URL.</summary> - public string DownloadUrl { get; set; } + public string DownloadUrl { get; } /// <summary>The for-developers download URL (not applicable for prerelease versions).</summary> - public string DevDownloadUrl { get; set; } + public string? DevDownloadUrl { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public IndexVersionModel() { } - - /// <summary>Construct an instance.</summary> /// <param name="version">The release number.</param> /// <param name="description">The Markdown description for the release.</param> /// <param name="downloadUrl">The main download URL.</param> /// <param name="devDownloadUrl">The for-developers download URL (not applicable for prerelease versions).</param> - internal IndexVersionModel(string version, string description, string downloadUrl, string devDownloadUrl) + internal IndexVersionModel(string version, string description, string downloadUrl, string? devDownloadUrl) { this.Version = version; this.Description = description; diff --git a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorErrorModel.cs b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorErrorModel.cs index 62b95501..4d37d449 100644 --- a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorErrorModel.cs +++ b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorErrorModel.cs @@ -9,30 +9,27 @@ namespace StardewModdingAPI.Web.ViewModels.JsonValidator ** Accessors *********/ /// <summary>The line number on which the error occurred.</summary> - public int Line { get; set; } + public int Line { get; } /// <summary>The field path in the JSON file where the error occurred.</summary> - public string Path { get; set; } + public string? Path { get; } /// <summary>A human-readable description of the error.</summary> - public string Message { get; set; } + public string Message { get; } /// <summary>The schema error type.</summary> - public ErrorType SchemaErrorType { get; set; } + public ErrorType SchemaErrorType { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public JsonValidatorErrorModel() { } - - /// <summary>Construct an instance.</summary> /// <param name="line">The line number on which the error occurred.</param> /// <param name="path">The field path in the JSON file where the error occurred.</param> /// <param name="message">A human-readable description of the error.</param> /// <param name="schemaErrorType">The schema error type.</param> - public JsonValidatorErrorModel(int line, string path, string message, ErrorType schemaErrorType) + public JsonValidatorErrorModel(int line, string? path, string message, ErrorType schemaErrorType) { this.Line = line; this.Path = path; diff --git a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorModel.cs b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorModel.cs index 0ea69911..85c2f44d 100644 --- a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorModel.cs +++ b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorModel.cs @@ -11,51 +11,48 @@ namespace StardewModdingAPI.Web.ViewModels.JsonValidator ** Accessors *********/ /// <summary>Whether to show the edit view.</summary> - public bool IsEditView { get; set; } + public bool IsEditView { get; } /// <summary>The paste ID.</summary> - public string PasteID { get; set; } + public string? PasteID { get; } /// <summary>The schema name with which the JSON was validated.</summary> - public string SchemaName { get; set; } + public string? SchemaName { get; } /// <summary>The supported JSON schemas (names indexed by ID).</summary> - public readonly IDictionary<string, string> SchemaFormats; + public IDictionary<string, string> SchemaFormats { get; } /// <summary>The validated content.</summary> - public string Content { get; set; } + public string? Content { get; set; } /// <summary>The schema validation errors, if any.</summary> - public JsonValidatorErrorModel[] Errors { get; set; } = new JsonValidatorErrorModel[0]; + public JsonValidatorErrorModel[] Errors { get; set; } = Array.Empty<JsonValidatorErrorModel>(); /// <summary>A non-blocking warning while uploading the file.</summary> - public string UploadWarning { get; set; } + public string? UploadWarning { get; set; } /// <summary>When the uploaded file will no longer be available.</summary> - public DateTime? Expiry { get; set; } + public DateTimeOffset? Expiry { get; set; } /// <summary>An error which occurred while uploading the JSON.</summary> - public string UploadError { get; set; } + public string? UploadError { get; set; } /// <summary>An error which occurred while parsing the JSON.</summary> - public string ParseError { get; set; } + public string? ParseError { get; set; } /// <summary>A web URL to the user-facing format documentation.</summary> - public string FormatUrl { get; set; } + public string? FormatUrl { get; set; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public JsonValidatorModel() { } - - /// <summary>Construct an instance.</summary> /// <param name="pasteID">The stored file ID.</param> /// <param name="schemaName">The schema name with which the JSON was validated.</param> /// <param name="schemaFormats">The supported JSON schemas (names indexed by ID).</param> /// <param name="isEditView">Whether to show the edit view.</param> - public JsonValidatorModel(string pasteID, string schemaName, IDictionary<string, string> schemaFormats, bool isEditView) + public JsonValidatorModel(string? pasteID, string? schemaName, IDictionary<string, string> schemaFormats, bool isEditView) { this.PasteID = pasteID; this.SchemaName = schemaName; @@ -67,7 +64,7 @@ namespace StardewModdingAPI.Web.ViewModels.JsonValidator /// <param name="content">The validated content.</param> /// <param name="expiry">When the uploaded file will no longer be available.</param> /// <param name="uploadWarning">A non-blocking warning while uploading the log.</param> - public JsonValidatorModel SetContent(string content, DateTime? expiry, string uploadWarning = null) + public JsonValidatorModel SetContent(string content, DateTimeOffset? expiry, string? uploadWarning = null) { this.Content = content; this.Expiry = expiry; diff --git a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorRequestModel.cs b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorRequestModel.cs index c8e851bf..1313264f 100644 --- a/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorRequestModel.cs +++ b/src/SMAPI.Web/ViewModels/JsonValidator/JsonValidatorRequestModel.cs @@ -7,9 +7,9 @@ namespace StardewModdingAPI.Web.ViewModels.JsonValidator ** Accessors *********/ /// <summary>The schema name with which to validate the JSON.</summary> - public string SchemaName { get; set; } + public string? SchemaName { get; set; } /// <summary>The raw content to validate.</summary> - public string Content { get; set; } + public string? Content { get; set; } } } diff --git a/src/SMAPI.Web/ViewModels/LogParserModel.cs b/src/SMAPI.Web/ViewModels/LogParserModel.cs index bea79eae..c39a9b0a 100644 --- a/src/SMAPI.Web/ViewModels/LogParserModel.cs +++ b/src/SMAPI.Web/ViewModels/LogParserModel.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; +using Newtonsoft.Json; using StardewModdingAPI.Toolkit.Utilities; using StardewModdingAPI.Web.Framework.LogParsing.Models; @@ -14,47 +16,48 @@ namespace StardewModdingAPI.Web.ViewModels ** Fields *********/ /// <summary>A regex pattern matching characters to remove from a mod name to create the slug ID.</summary> - private readonly Regex SlugInvalidCharPattern = new Regex("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex SlugInvalidCharPattern = new("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase); /********* ** Accessors *********/ /// <summary>The paste ID.</summary> - public string PasteID { get; set; } + public string? PasteID { get; } /// <summary>The viewer's detected OS, if known.</summary> - public Platform? DetectedPlatform { get; set; } + public Platform? DetectedPlatform { get; } /// <summary>The parsed log info.</summary> - public ParsedLog ParsedLog { get; set; } + public ParsedLog? ParsedLog { get; private set; } /// <summary>Whether to show the raw unparsed log.</summary> - public bool ShowRaw { get; set; } + public bool ShowRaw { get; private set; } /// <summary>A non-blocking warning while uploading the log.</summary> - public string UploadWarning { get; set; } + public string? UploadWarning { get; set; } /// <summary>An error which occurred while uploading the log.</summary> - public string UploadError { get; set; } + public string? UploadError { get; set; } /// <summary>An error which occurred while parsing the log file.</summary> - public string ParseError => this.ParsedLog?.Error; + public string? ParseError => this.ParsedLog?.Error; /// <summary>When the uploaded file will no longer be available.</summary> - public DateTime? Expiry { get; set; } + public DateTimeOffset? Expiry { get; set; } + + /// <summary>Whether parsed log data is available.</summary> + [MemberNotNullWhen(true, nameof(LogParserModel.PasteID), nameof(LogParserModel.ParsedLog))] + public bool HasLog => this.ParsedLog != null; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> - public LogParserModel() { } - - /// <summary>Construct an instance.</summary> /// <param name="pasteID">The paste ID.</param> /// <param name="platform">The viewer's detected OS, if known.</param> - public LogParserModel(string pasteID, Platform? platform) + public LogParserModel(string? pasteID, Platform? platform) { this.PasteID = pasteID; this.DetectedPlatform = platform; @@ -62,6 +65,26 @@ namespace StardewModdingAPI.Web.ViewModels this.ShowRaw = false; } + /// <summary>Construct an instance.</summary> + /// <param name="pasteId">The paste ID.</param> + /// <param name="detectedPlatform">The viewer's detected OS, if known.</param> + /// <param name="parsedLog">The parsed log info.</param> + /// <param name="showRaw">Whether to show the raw unparsed log.</param> + /// <param name="uploadWarning">A non-blocking warning while uploading the log.</param> + /// <param name="uploadError">An error which occurred while uploading the log.</param> + /// <param name="expiry">When the uploaded file will no longer be available.</param> + [JsonConstructor] + public LogParserModel(string pasteId, Platform? detectedPlatform, ParsedLog? parsedLog, bool showRaw, string? uploadWarning, string? uploadError, DateTime? expiry) + { + this.PasteID = pasteId; + this.DetectedPlatform = detectedPlatform; + this.ParsedLog = parsedLog; + this.ShowRaw = showRaw; + this.UploadWarning = uploadWarning; + this.UploadError = uploadError; + this.Expiry = expiry; + } + /// <summary>Set the log parser result.</summary> /// <param name="parsedLog">The parsed log info.</param> /// <param name="showRaw">Whether to show the raw unparsed log.</param> @@ -77,14 +100,14 @@ namespace StardewModdingAPI.Web.ViewModels public IDictionary<string, LogModInfo[]> GetContentPacksByMod() { // get all mods & content packs - LogModInfo[] mods = this.ParsedLog?.Mods; + LogModInfo[]? mods = this.ParsedLog?.Mods; if (mods == null || !mods.Any()) return new Dictionary<string, LogModInfo[]>(); // group by mod return mods - .Where(mod => mod.ContentPackFor != null) - .GroupBy(mod => mod.ContentPackFor) + .Where(mod => mod.IsContentPack) + .GroupBy(mod => mod.ContentPackFor!) .ToDictionary(group => group.Key, group => group.ToArray()); } diff --git a/src/SMAPI.Web/ViewModels/ModCompatibilityModel.cs b/src/SMAPI.Web/ViewModels/ModCompatibilityModel.cs index 85bf1e46..36ea891d 100644 --- a/src/SMAPI.Web/ViewModels/ModCompatibilityModel.cs +++ b/src/SMAPI.Web/ViewModels/ModCompatibilityModel.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; namespace StardewModdingAPI.Web.ViewModels @@ -9,22 +10,36 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The compatibility status, as a string like <c>"Broken"</c>.</summary> - public string Status { get; set; } + public string Status { get; } /// <summary>The human-readable summary, as an HTML block.</summary> - public string Summary { get; set; } + public string? Summary { get; } /// <summary>The game or SMAPI version which broke this mod (if applicable).</summary> - public string BrokeIn { get; set; } + public string? BrokeIn { get; } /// <summary>A link to the unofficial version which fixes compatibility, if any.</summary> - public ModLinkModel UnofficialVersion { get; set; } + public ModLinkModel? UnofficialVersion { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="status">The compatibility status, as a string like <c>"Broken"</c>.</param> + /// <param name="summary">The human-readable summary, as an HTML block.</param> + /// <param name="brokeIn">The game or SMAPI version which broke this mod (if applicable).</param> + /// <param name="unofficialVersion">A link to the unofficial version which fixes compatibility, if any.</param> + [JsonConstructor] + public ModCompatibilityModel(string status, string? summary, string? brokeIn, ModLinkModel? unofficialVersion) + { + this.Status = status; + this.Summary = summary; + this.BrokeIn = brokeIn; + this.UnofficialVersion = unofficialVersion; + } + + /// <summary>Construct an instance.</summary> /// <param name="info">The mod metadata.</param> public ModCompatibilityModel(WikiCompatibilityInfo info) { @@ -34,7 +49,7 @@ namespace StardewModdingAPI.Web.ViewModels this.Summary = info.Summary; this.BrokeIn = info.BrokeIn; if (info.UnofficialVersion != null) - this.UnofficialVersion = new ModLinkModel(info.UnofficialUrl, info.UnofficialVersion.ToString()); + this.UnofficialVersion = new ModLinkModel(info.UnofficialUrl!, info.UnofficialVersion.ToString()); } } } diff --git a/src/SMAPI.Web/ViewModels/ModLinkModel.cs b/src/SMAPI.Web/ViewModels/ModLinkModel.cs index 97dd215c..96f14d48 100644 --- a/src/SMAPI.Web/ViewModels/ModLinkModel.cs +++ b/src/SMAPI.Web/ViewModels/ModLinkModel.cs @@ -7,10 +7,10 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The URL of the linked page.</summary> - public string Url { get; set; } + public string Url { get; } /// <summary>The suggested link text.</summary> - public string Text { get; set; } + public string Text { get; } /********* diff --git a/src/SMAPI.Web/ViewModels/ModListModel.cs b/src/SMAPI.Web/ViewModels/ModListModel.cs index 6b8279c1..be9f973a 100644 --- a/src/SMAPI.Web/ViewModels/ModListModel.cs +++ b/src/SMAPI.Web/ViewModels/ModListModel.cs @@ -11,37 +11,34 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The current stable version of the game.</summary> - public string StableVersion { get; set; } + public string? StableVersion { get; } /// <summary>The current beta version of the game (if any).</summary> - public string BetaVersion { get; set; } + public string? BetaVersion { get; } /// <summary>The mods to display.</summary> - public ModModel[] Mods { get; set; } + public ModModel[] Mods { get; } /// <summary>When the data was last updated.</summary> - public DateTimeOffset LastUpdated { get; set; } + public DateTimeOffset LastUpdated { get; } /// <summary>Whether the data hasn't been updated in a while.</summary> - public bool IsStale { get; set; } + public bool IsStale { get; } /// <summary>Whether the mod metadata is available.</summary> - public bool HasData => this.Mods?.Any() == true; + public bool HasData => this.Mods.Any(); /********* ** Public methods *********/ - /// <summary>Construct an empty instance.</summary> - public ModListModel() { } - /// <summary>Construct an instance.</summary> /// <param name="stableVersion">The current stable version of the game.</param> /// <param name="betaVersion">The current beta version of the game (if any).</param> /// <param name="mods">The mods to display.</param> /// <param name="lastUpdated">When the data was last updated.</param> /// <param name="isStale">Whether the data hasn't been updated in a while.</param> - public ModListModel(string stableVersion, string betaVersion, IEnumerable<ModModel> mods, DateTimeOffset lastUpdated, bool isStale) + public ModListModel(string? stableVersion, string? betaVersion, IEnumerable<ModModel> mods, DateTimeOffset lastUpdated, bool isStale) { this.StableVersion = stableVersion; this.BetaVersion = betaVersion; diff --git a/src/SMAPI.Web/ViewModels/ModModel.cs b/src/SMAPI.Web/ViewModels/ModModel.cs index 575d596a..929bf682 100644 --- a/src/SMAPI.Web/ViewModels/ModModel.cs +++ b/src/SMAPI.Web/ViewModels/ModModel.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using Newtonsoft.Json; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; namespace StardewModdingAPI.Web.ViewModels @@ -11,43 +12,43 @@ namespace StardewModdingAPI.Web.ViewModels ** Accessors *********/ /// <summary>The mod name.</summary> - public string Name { get; set; } + public string? Name { get; } /// <summary>The mod's alternative names, if any.</summary> - public string AlternateNames { get; set; } + public string AlternateNames { get; } /// <summary>The mod author's name.</summary> - public string Author { get; set; } + public string? Author { get; } /// <summary>The mod author's alternative names, if any.</summary> - public string AlternateAuthors { get; set; } + public string AlternateAuthors { get; } /// <summary>The GitHub repo, if any.</summary> - public string GitHubRepo { get; set; } + public string? GitHubRepo { get; } /// <summary>The URL to the mod's source code, if any.</summary> - public string SourceUrl { get; set; } + public string? SourceUrl { get; } /// <summary>The compatibility status for the stable version of the game.</summary> - public ModCompatibilityModel Compatibility { get; set; } + public ModCompatibilityModel Compatibility { get; } /// <summary>The compatibility status for the beta version of the game.</summary> - public ModCompatibilityModel BetaCompatibility { get; set; } + public ModCompatibilityModel? BetaCompatibility { get; } /// <summary>Links to the available mod pages.</summary> - public ModLinkModel[] ModPages { get; set; } + public ModLinkModel[] ModPages { get; } /// <summary>The human-readable warnings for players about this mod.</summary> - public string[] Warnings { get; set; } + public string[] Warnings { get; } /// <summary>The URL of the pull request which submits changes for an unofficial update to the author, if any.</summary> - public string PullRequestUrl { get; set; } + public string? PullRequestUrl { get; } - /// <summary>Special notes intended for developers who maintain unofficial updates or submit pull requests. </summary> - public string DevNote { get; set; } + /// <summary>Special notes intended for developers who maintain unofficial updates or submit pull requests.</summary> + public string? DevNote { get; } /// <summary>A unique identifier for the mod that can be used in an anchor URL.</summary> - public string Slug { get; set; } + public string? Slug { get; } /// <summary>The sites where the mod can be downloaded.</summary> public string[] ModPageSites => this.ModPages.Select(p => p.Text).ToArray(); @@ -57,6 +58,38 @@ namespace StardewModdingAPI.Web.ViewModels ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="name">The mod name.</param> + /// <param name="alternateNames">The mod's alternative names, if any.</param> + /// <param name="author">The mod author's name.</param> + /// <param name="alternateAuthors">The mod author's alternative names, if any.</param> + /// <param name="gitHubRepo">The GitHub repo, if any.</param> + /// <param name="sourceUrl">The URL to the mod's source code, if any.</param> + /// <param name="compatibility">The compatibility status for the stable version of the game.</param> + /// <param name="betaCompatibility">The compatibility status for the beta version of the game.</param> + /// <param name="modPages">Links to the available mod pages.</param> + /// <param name="warnings">The human-readable warnings for players about this mod.</param> + /// <param name="pullRequestUrl">The URL of the pull request which submits changes for an unofficial update to the author, if any.</param> + /// <param name="devNote">Special notes intended for developers who maintain unofficial updates or submit pull requests.</param> + /// <param name="slug">A unique identifier for the mod that can be used in an anchor URL.</param> + [JsonConstructor] + public ModModel(string? name, string alternateNames, string author, string alternateAuthors, string gitHubRepo, string sourceUrl, ModCompatibilityModel compatibility, ModCompatibilityModel betaCompatibility, ModLinkModel[] modPages, string[] warnings, string pullRequestUrl, string devNote, string slug) + { + this.Name = name; + this.AlternateNames = alternateNames; + this.Author = author; + this.AlternateAuthors = alternateAuthors; + this.GitHubRepo = gitHubRepo; + this.SourceUrl = sourceUrl; + this.Compatibility = compatibility; + this.BetaCompatibility = betaCompatibility; + this.ModPages = modPages; + this.Warnings = warnings; + this.PullRequestUrl = pullRequestUrl; + this.DevNote = devNote; + this.Slug = slug; + } + + /// <summary>Construct an instance.</summary> /// <param name="entry">The mod metadata.</param> public ModModel(WikiModEntry entry) { @@ -82,7 +115,7 @@ namespace StardewModdingAPI.Web.ViewModels *********/ /// <summary>Get the web URL for the mod's source code repository, if any.</summary> /// <param name="entry">The mod metadata.</param> - private string GetSourceUrl(WikiModEntry entry) + private string? GetSourceUrl(WikiModEntry entry) { if (!string.IsNullOrWhiteSpace(entry.GitHubRepo)) return $"https://github.com/{entry.GitHubRepo}"; diff --git a/src/SMAPI.Web/Views/Index/Index.cshtml b/src/SMAPI.Web/Views/Index/Index.cshtml index 669cfd99..acb8df78 100644 --- a/src/SMAPI.Web/Views/Index/Index.cshtml +++ b/src/SMAPI.Web/Views/Index/Index.cshtml @@ -24,7 +24,7 @@ <div id="call-to-action"> <div class="cta-dropdown"> - <a href="@Model.StableVersion.DownloadUrl" class="main-cta download">Download SMAPI @Model.StableVersion.Version</a><br /> + <a href="@Model!.StableVersion.DownloadUrl" class="main-cta download">Download SMAPI @Model.StableVersion.Version</a><br /> <div class="dropdown-content"> <a href="https://www.nexusmods.com/stardewvalley/mods/2400"><img src="Content/images/nexus-icon.png" /> Download from Nexus</a> <a href="@Model.StableVersion.DownloadUrl"><img src="Content/images/direct-download-icon.png" /> Direct download</a> diff --git a/src/SMAPI.Web/Views/JsonValidator/Index.cshtml b/src/SMAPI.Web/Views/JsonValidator/Index.cshtml index 1db79857..f5ec0f7a 100644 --- a/src/SMAPI.Web/Views/JsonValidator/Index.cshtml +++ b/src/SMAPI.Web/Views/JsonValidator/Index.cshtml @@ -5,10 +5,10 @@ @{ // get view data - string curPageUrl = this.Url.PlainAction("Index", "JsonValidator", new { schemaName = Model.SchemaName, id = Model.PasteID }, absoluteUrl: true); - string newUploadUrl = this.Url.PlainAction("Index", "JsonValidator", new { schemaName = Model.SchemaName }); - string schemaDisplayName = null; - bool isValidSchema = Model.SchemaName != null && Model.SchemaFormats.TryGetValue(Model.SchemaName, out schemaDisplayName) && schemaDisplayName?.ToLower() != "none"; + string curPageUrl = this.Url.PlainAction("Index", "JsonValidator", new { schemaName = Model!.SchemaName, id = Model.PasteID }, absoluteUrl: true)!; + string newUploadUrl = this.Url.PlainAction("Index", "JsonValidator", new { schemaName = Model.SchemaName })!; + string? schemaDisplayName = null; + bool isValidSchema = Model.SchemaName != null && Model.SchemaFormats.TryGetValue(Model.SchemaName, out schemaDisplayName) && schemaDisplayName.ToLower() != "none"; // build title ViewData["Title"] = "JSON validator"; diff --git a/src/SMAPI.Web/Views/LogParser/Index.cshtml b/src/SMAPI.Web/Views/LogParser/Index.cshtml index 91fc3535..5e55906d 100644 --- a/src/SMAPI.Web/Views/LogParser/Index.cshtml +++ b/src/SMAPI.Web/Views/LogParser/Index.cshtml @@ -7,15 +7,25 @@ @{ ViewData["Title"] = "SMAPI log parser"; + + ParsedLog? log = Model!.ParsedLog; + IDictionary<string, LogModInfo[]> contentPacks = Model.GetContentPacksByMod(); IDictionary<string, bool> defaultFilters = Enum - .GetValues(typeof(LogLevel)) - .Cast<LogLevel>() + .GetValues<LogLevel>() .ToDictionary(level => level.ToString().ToLower(), level => level != LogLevel.Trace); - string curPageUrl = this.Url.PlainAction("Index", "LogParser", new { id = Model.PasteID }, absoluteUrl: true); + IDictionary<int, string> logLevels = Enum + .GetValues<LogLevel>() + .ToDictionary(level => (int)level, level => level.ToString().ToLower()); + + IDictionary<int, string> logSections = Enum + .GetValues<LogSection>() + .ToDictionary(section => (int)section, section => section.ToString()); - ISet<int> screenIds = new HashSet<int>(Model.ParsedLog?.Messages?.Select(p => p.ScreenId) ?? new int[0]); + string curPageUrl = this.Url.PlainAction("Index", "LogParser", new { id = Model.PasteID }, absoluteUrl: true)!; + + ISet<int> screenIds = new HashSet<int>(log?.Messages.Select(p => p.ScreenId) ?? Array.Empty<int>()); } @section Head { @@ -24,31 +34,81 @@ <meta name="robots" content="noindex" /> } <link rel="stylesheet" href="~/Content/css/file-upload.css" /> - <link rel="stylesheet" href="~/Content/css/log-parser.css" /> + <link rel="stylesheet" href="~/Content/css/log-parser.css?r=20220409" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tabbyjs@12.0.3/dist/css/tabby-ui-vertical.min.css" /> <script src="https://cdn.jsdelivr.net/npm/tabbyjs@12.0.3" crossorigin="anonymous"></script> - <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11" crossorigin="anonymous"></script> + <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1" crossorigin="anonymous"></script> <script src="~/Content/js/file-upload.js"></script> - <script src="~/Content/js/log-parser.js"></script> + <script src="~/Content/js/log-parser.js?r=20220409"></script> + + <script id="serializedData" type="application/json"> + @if (!Model.ShowRaw) + { + <text> + { + "messages": @this.ForJson(log?.Messages), + "sections": @this.ForJson(logSections), + "logLevels": @this.ForJson(logLevels), + "modSlugs": @this.ForJson(log?.Mods.DistinctBy(p => p.Name).Select(p => new {p.Name, Slug = Model.GetSlug(p.Name)}).Where(p => p.Name != p.Slug).ToDictionary(p => p.Name, p => p.Slug)), + "screenIds": @this.ForJson(screenIds) + } + </text> + } + else + { + <text> + { + "messages": [], + "sections": {}, + "logLevels": {}, + "modSlugs": {}, + "screenIds": [] + } + </text> + } + </script> + <script> $(function() { - smapi.logParser({ - logStarted: new Date(@this.ForJson(Model.ParsedLog?.Timestamp)), - showPopup: @this.ForJson(Model.ParsedLog == null), - showMods: @this.ForJson(Model.ParsedLog?.Mods?.Select(p => Model.GetSlug(p.Name)).Distinct().ToDictionary(slug => slug, slug => true)), - showSections: @this.ForJson(Enum.GetNames(typeof(LogSection)).ToDictionary(section => section, section => false)), - showLevels: @this.ForJson(defaultFilters), - enableFilters: @this.ForJson(!Model.ShowRaw), - screenIds: @this.ForJson(screenIds) - }, '@this.Url.PlainAction("Index", "LogParser", values: null)'); + smapi.logParser( + { + logStarted: new Date(@this.ForJson(log?.Timestamp)), + dataElement: "script#serializedData", + showPopup: @this.ForJson(log == null), + showMods: @this.ForJson(log?.Mods.Where(p => p.Loaded && !p.IsContentPack).Select(p => Model.GetSlug(p.Name)).Distinct().ToDictionary(slug => slug, _ => true)), + showSections: @this.ForJson(Enum.GetNames(typeof(LogSection)).ToDictionary(section => section, _ => false)), + showLevels: @this.ForJson(defaultFilters), + enableFilters: @this.ForJson(!Model.ShowRaw) + } + ); - new Tabby('[data-tabs]'); + @if (log == null) + { + <text> + new Tabby("[data-tabs]"); + </text> + } }); </script> } +@* quick navigation links *@ +@section SidebarExtra { + @if (log != null) + { + <nav id="quickNav"> + <h4>Scroll to...</h4> + <ul> + <li><a href="#content">Top</a></li> + <li><a href="#filterHolder">Log start</a></li> + <li><a href="#footer">Bottom</a></li> + </ul> + </nav> + } +} + @* upload result banner *@ @if (Model.UploadError != null) { @@ -67,7 +127,7 @@ else if (Model.ParseError != null) <small v-pre>Error details: @Model.ParseError</small> </div> } -else if (Model.ParsedLog?.IsValid == true) +else if (log?.IsValid == true) { <div class="banner success" v-pre> <strong>Share this link to let someone else see the log:</strong> <code>@curPageUrl</code><br /> @@ -92,7 +152,7 @@ else if (Model.ParsedLog?.IsValid == true) } @* upload new log *@ -@if (Model.ParsedLog == null) +@if (log == null) { <h2>Where do I find my SMAPI log?</h2> <div id="os-instructions"> @@ -157,7 +217,7 @@ else if (Model.ParsedLog?.IsValid == true) </div> <h2>How do I share my log?</h2> - <form action="@this.Url.PlainAction("PostAsync", "LogParser")" method="post"> + <form action="@this.Url.PlainAction("Post", "LogParser")" method="post"> <input id="inputFile" type="file" /> <ol> <li> @@ -174,10 +234,10 @@ else if (Model.ParsedLog?.IsValid == true) } @* parsed log *@ -@if (Model.ParsedLog?.IsValid == true) +@if (log?.IsValid == true) { <div id="output"> - @if (Model.ParsedLog.Mods.Any(mod => mod.HasUpdate)) + @if (log.Mods.Any(mod => mod.HasUpdate)) { <h2>Suggested fixes</h2> <ul id="fix-list"> @@ -185,12 +245,12 @@ else if (Model.ParsedLog?.IsValid == true) Consider updating these mods to fix problems: <table id="updates" class="table"> - @foreach (LogModInfo mod in Model.ParsedLog.Mods.Where(mod => (mod.HasUpdate && mod.ContentPackFor == null) || (contentPacks != null && contentPacks.TryGetValue(mod.Name, out LogModInfo[] contentPackList) && contentPackList.Any(pack => pack.HasUpdate)))) + @foreach (LogModInfo mod in log.Mods.Where(mod => (mod.HasUpdate && !mod.IsContentPack) || (contentPacks.TryGetValue(mod.Name, out LogModInfo[]? contentPackList) && contentPackList.Any(pack => pack.HasUpdate)))) { <tr class="mod-entry"> <td> <strong class=@(!mod.HasUpdate ? "hidden" : "")>@mod.Name</strong> - @if (contentPacks != null && contentPacks.TryGetValue(mod.Name, out LogModInfo[] contentPackList)) + @if (contentPacks != null && contentPacks.TryGetValue(mod.Name, out LogModInfo[]? contentPackList)) { <div class="content-packs"> @foreach (LogModInfo contentPack in contentPackList.Where(pack => pack.HasUpdate)) @@ -204,7 +264,7 @@ else if (Model.ParsedLog?.IsValid == true) @if (mod.HasUpdate) { <a href="@mod.UpdateLink" target="_blank"> - @(mod.Version == null ? @mod.UpdateVersion : $"{mod.Version} → {mod.UpdateVersion}") + @(mod.Version == null ? mod.UpdateVersion : $"{mod.Version} → {mod.UpdateVersion}") </a> } else @@ -230,23 +290,33 @@ else if (Model.ParsedLog?.IsValid == true) } <h2>Log info</h2> - <table id="metadata" class="table"> + <table + id="metadata" + class="table" + data-code-mods="@log.Mods.Count(p => !p.IsContentPack)" + data-content-packs="@log.Mods.Count(p => p.IsContentPack)" + data-os="@log.OperatingSystem" + data-game-version="@log.GameVersion" + data-game-path="@log.GamePath" + data-smapi-version="@log.ApiVersion" + data-log-started="@log.Timestamp.UtcDateTime.ToString("O")" + > <caption>Game info:</caption> <tr> <th>Stardew Valley:</th> - <td v-pre>@Model.ParsedLog.GameVersion on @Model.ParsedLog.OperatingSystem</td> + <td v-pre>@log.GameVersion on @log.OperatingSystem</td> </tr> <tr> <th>SMAPI:</th> - <td v-pre>@Model.ParsedLog.ApiVersion</td> + <td v-pre>@log.ApiVersion</td> </tr> <tr> <th>Folder:</th> - <td v-pre>@Model.ParsedLog.GamePath</td> + <td v-pre>@log.GamePath</td> </tr> <tr> <th>Log started:</th> - <td>@Model.ParsedLog.Timestamp.UtcDateTime.ToString("yyyy-MM-dd HH:mm") UTC ({{localTimeStarted}} your time)</td> + <td>@log.Timestamp.UtcDateTime.ToString("yyyy-MM-dd HH:mm") UTC ({{localTimeStarted}} your time)</td> </tr> </table> <br /> @@ -258,29 +328,34 @@ else if (Model.ParsedLog?.IsValid == true) <span class="notice txt"><i>click any mod to filter</i></span> <span class="notice btn txt" v-on:click="showAllMods" v-bind:class="{ invisible: !anyModsHidden }">show all</span> <span class="notice btn txt" v-on:click="hideAllMods" v-bind:class="{ invisible: !anyModsShown || !anyModsHidden }">hide all</span> + <span class="notice btn txt" v-on:click="toggleContentPacks">toggle content packs in list</span> } </caption> - @foreach (var mod in Model.ParsedLog.Mods.Where(p => p.Loaded && p.ContentPackFor == null)) + @foreach (var mod in log.Mods.Where(p => p.Loaded && !p.IsContentPack)) { + if (contentPacks == null || !contentPacks.TryGetValue(mod.Name, out LogModInfo[]? contentPackList)) + contentPackList = null; + <tr v-on:click="toggleMod('@Model.GetSlug(mod.Name)')" class="mod-entry" v-bind:class="{ hidden: !showMods['@Model.GetSlug(mod.Name)'] }"> <td><input type="checkbox" v-bind:checked="showMods['@Model.GetSlug(mod.Name)']" v-bind:class="{ invisible: !anyModsHidden }" /></td> - <td v-pre> - <strong>@mod.Name</strong> @mod.Version - @if (contentPacks != null && contentPacks.TryGetValue(mod.Name, out LogModInfo[] contentPackList)) + <td> + <strong v-pre>@mod.Name</strong> @mod.Version + @if (contentPackList != null) { - <div class="content-packs"> + <div v-if="!hideContentPacks" class="content-packs"> @foreach (var contentPack in contentPackList) { <text>+ @contentPack.Name @contentPack.Version</text><br /> } </div> + <span v-else class="content-packs-collapsed"> (+ @contentPackList.Length content packs)</span> } </td> - <td v-pre> + <td> @mod.Author - @if (contentPacks != null && contentPacks.TryGetValue(mod.Name, out contentPackList)) + @if (contentPackList != null) { - <div class="content-packs"> + <div v-if="!hideContentPacks" class="content-packs"> @foreach (var contentPack in contentPackList) { <text>+ @contentPack.Author</text><br /> @@ -306,61 +381,75 @@ else if (Model.ParsedLog?.IsValid == true) @if (!Model.ShowRaw) { + <div id="filterHolder"></div> <div id="filters"> - Filter messages: - <span v-bind:class="{ active: showLevels['trace'] }" v-on:click="toggleLevel('trace')">TRACE</span> | - <span v-bind:class="{ active: showLevels['debug'] }" v-on:click="toggleLevel('debug')">DEBUG</span> | - <span v-bind:class="{ active: showLevels['info'] }" v-on:click="toggleLevel('info')">INFO</span> | - <span v-bind:class="{ active: showLevels['alert'] }" v-on:click="toggleLevel('alert')">ALERT</span> | - <span v-bind:class="{ active: showLevels['warn'] }" v-on:click="toggleLevel('warn')">WARN</span> | - <span v-bind:class="{ active: showLevels['error'] }" v-on:click="toggleLevel('error')">ERROR</span> + <div class="toggles"> + <div> + Filter messages: + </div> + <div> + <span role="button" v-bind:class="{ active: showLevels['trace'] }" v-on:click="toggleLevel('trace')">TRACE</span> | + <span role="button" v-bind:class="{ active: showLevels['debug'] }" v-on:click="toggleLevel('debug')">DEBUG</span> | + <span role="button" v-bind:class="{ active: showLevels['info'] }" v-on:click="toggleLevel('info')">INFO</span> | + <span role="button" v-bind:class="{ active: showLevels['alert'] }" v-on:click="toggleLevel('alert')">ALERT</span> | + <span role="button" v-bind:class="{ active: showLevels['warn'] }" v-on:click="toggleLevel('warn')">WARN</span> | + <span role="button" v-bind:class="{ active: showLevels['error'] }" v-on:click="toggleLevel('error')">ERROR</span> + <div class="filter-text"> + <input + type="text" + v-bind:class="{ active: !!filterText }" + v-model="filterText" + v-on:input="updateFilterText" + placeholder="search to filter log..." + /> + <span role="button" v-bind:class="{ active: filterUseRegex }" v-on:click="toggleFilterUseRegex" title="Use regular expression syntax.">.*</span> + <span role="button" v-bind:class="{ active: !filterInsensitive }" v-on:click="toggleFilterInsensitive" title="Match exact capitalization only.">aA</span> + <span role="button" v-bind:class="{ active: filterUseWord, 'whole-word': true }" v-on:click="toggleFilterWord" title="Match whole word only."><i>“ ”</i></span> + <span role="button" v-bind:class="{ active: shouldHighlight }" v-on:click="toggleHighlight" title="Highlight matches in the log text.">HL</span> + <div + v-if="filterError" + class="filter-error" + > + {{ filterError }} + </div> + </div> + <filter-stats + v-bind:start="start" + v-bind:end="end" + v-bind:pages="totalPages" + v-bind:filtered="filteredMessages.total" + v-bind:total="totalMessages" + /> + </div> + </div> + <pager + v-bind:page="page" + v-bind:pages="totalPages" + v-bind:prevPage="prevPage" + v-bind:nextPage="nextPage" + /> </div> - <table id="log"> - @foreach (var message in Model.ParsedLog.Messages) - { - string levelStr = message.Level.ToString().ToLower(); - string sectionStartClass = message.IsStartOfSection ? "section-start" : null; - string sectionFilter = message.Section != null && !message.IsStartOfSection ? $"&& sectionsAllow('{message.Section}')" : null; // filter the message by section if applicable + <noscript> + <div> + This website uses JavaScript to display a filterable table. To view this log, please enable JavaScript or <a href="@this.Url.PlainAction("Index", "LogParser", new { id = Model.PasteID, format = LogViewFormat.RawView })">view the raw log</a>. + </div> + <br/> + </noscript> - <tr class="mod @levelStr @sectionStartClass" - @if (message.IsStartOfSection) { <text> v-on:click="toggleSection('@message.Section')" </text> } - v-show="filtersAllow('@Model.GetSlug(message.Mod)', '@levelStr') @sectionFilter"> - <td v-pre>@message.Time</td> - @if (screenIds.Count > 1) - { - <td v-pre>screen_@message.ScreenId</td> - } - <td v-pre>@message.Level.ToString().ToUpper()</td> - <td v-pre data-title="@message.Mod">@message.Mod</td> - <td> - <span v-pre class="log-message-text">@message.Text</span> - @if (message.IsStartOfSection) - { - <span class="section-toggle-message"> - <template v-if="sectionsAllow('@message.Section')"> - This section is shown. Click here to hide it. - </template> - <template v-else> - This section is hidden. Click here to show it. - </template> - </span> - } - </td> - </tr> - if (message.Repeated > 0) - { - <tr class="@levelStr mod mod-repeat" v-show="filtersAllow('@Model.GetSlug(message.Mod)', '@levelStr') @sectionFilter"> - <td colspan="4"></td> - <td v-pre><i>repeats [@message.Repeated] times.</i></td> - </tr> - } - } - </table> + <log-table> + <log-line + v-for="msg in visibleMessages" + v-bind:key="msg.id" + v-bind:showScreenId="showScreenId" + v-bind:message="msg" + v-bind:highlight="shouldHighlight" + /> + </log-table> } else { - <pre v-pre>@Model.ParsedLog.RawText</pre> + <pre v-pre>@log.RawText</pre> } <small> @@ -377,8 +466,8 @@ else if (Model.ParsedLog?.IsValid == true) </small> </div> } -else if (Model.ParsedLog?.IsValid == false) +else if (log?.IsValid == false) { <h3>Raw log</h3> - <pre v-pre>@Model.ParsedLog.RawText</pre> + <pre v-pre>@log.RawText</pre> } diff --git a/src/SMAPI.Web/Views/Mods/Index.cshtml b/src/SMAPI.Web/Views/Mods/Index.cshtml index 8a764803..78eabad7 100644 --- a/src/SMAPI.Web/Views/Mods/Index.cshtml +++ b/src/SMAPI.Web/Views/Mods/Index.cshtml @@ -6,7 +6,7 @@ @{ ViewData["Title"] = "Mod compatibility"; - TimeSpan staleAge = DateTimeOffset.UtcNow - Model.LastUpdated; + TimeSpan staleAge = DateTimeOffset.UtcNow - Model!.LastUpdated; bool hasBeta = Model.BetaVersion != null; string betaLabel = $"SDV {Model.BetaVersion} only"; @@ -19,7 +19,7 @@ <script src="~/Content/js/mods.js?r=20210929"></script> <script> $(function() { - var data = @this.ForJson(Model.Mods ?? new ModModel[0]); + var data = @(this.ForJson(Model.Mods ?? Array.Empty<ModModel>())); var enableBeta = @this.ForJson(hasBeta); smapi.modList(data, enableBeta); }); diff --git a/src/SMAPI.Web/Views/Shared/_Layout.cshtml b/src/SMAPI.Web/Views/Shared/_Layout.cshtml index 67dcd3b3..1e82ab5f 100644 --- a/src/SMAPI.Web/Views/Shared/_Layout.cshtml +++ b/src/SMAPI.Web/Views/Shared/_Layout.cshtml @@ -26,6 +26,8 @@ <li><a href="@Url.PlainAction("Index", "LogParser", values: null)">Log parser</a></li> <li><a href="@Url.PlainAction("Index", "JsonValidator", values: null)">JSON validator</a></li> </ul> + + @RenderSection("SidebarExtra", required: false) </div> <div id="content-column"> <div id="content"> diff --git a/src/SMAPI.Web/Views/_ViewStart.cshtml b/src/SMAPI.Web/Views/_ViewStart.cshtml index a5f10045..820a2f6e 100644 --- a/src/SMAPI.Web/Views/_ViewStart.cshtml +++ b/src/SMAPI.Web/Views/_ViewStart.cshtml @@ -1,3 +1,3 @@ -@{ +@{ Layout = "_Layout"; } diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index 0265a928..1231f824 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -17,7 +17,8 @@ "Site": { "BetaEnabled": false, - "OtherBlurb": null + "OtherBlurb": null, + "SupporterList": null }, "ApiClients": { diff --git a/src/SMAPI.Web/wwwroot/Content/css/file-upload.css b/src/SMAPI.Web/wwwroot/Content/css/file-upload.css index ff170691..f29d46aa 100644 --- a/src/SMAPI.Web/wwwroot/Content/css/file-upload.css +++ b/src/SMAPI.Web/wwwroot/Content/css/file-upload.css @@ -11,7 +11,7 @@ border-radius: 5px; border: 1px solid #000088; outline: none; - box-shadow: inset 0px 0px 1px 1px rgba(0, 0, 192, .2); + box-shadow: inset 0 0 1px 1px rgba(0, 0, 192, .2); } #submit { diff --git a/src/SMAPI.Web/wwwroot/Content/css/log-parser.css b/src/SMAPI.Web/wwwroot/Content/css/log-parser.css index 8c3acceb..1d457e35 100644 --- a/src/SMAPI.Web/wwwroot/Content/css/log-parser.css +++ b/src/SMAPI.Web/wwwroot/Content/css/log-parser.css @@ -113,7 +113,7 @@ table caption { } .table tr { - background: #eee + background: #eee; } #mods span.notice { @@ -148,18 +148,79 @@ table caption { font-style: italic; } +.table .content-packs-collapsed { + opacity: 0.75; + font-size: 0.9em; + font-style: italic; +} + #metadata td:first-child { padding-right: 5px; } .table tr:nth-child(even) { - background: #fff + background: #fff; } #filters { margin: 1em 0 0 0; - padding: 0; + padding: 0 0 0.5em; + display: flex; + justify-content: space-between; + width: calc(100vw - 16em); +} + +#filters > div { + align-self: center; +} + +#filters .toggles { + display: flex; +} + +#filters .toggles > div:first-child { font-weight: bold; + padding: 0.2em 1em 0 0; +} + +#filters .filter-text { + margin-top: 0.5em; +} + +#filters .filter-error { + color: #880000; +} + +#filters .filter-error, +#filters .stats { + margin-top: 0.5em; + font-size: 0.75em; +} + +#filters.sticky { + position: fixed; + top: 0; + left: 0em; + background: #fff; + margin: 0; + padding: 0.5em; + width: calc(100% - 1em); +} + +@media (min-width: 1020px) and (max-width: 1199px) { + #filters:not(.sticky) { + width: calc(100vw - 13em); + } +} + +@media (max-width: 1019px) { + #filters:not(.sticky) { + width: calc(100vw - 5em); + } + + #filters { + display: block; + } } #filters span { @@ -173,6 +234,17 @@ table caption { color: #000; border-color: #880000; background-color: #fcc; + + user-select: none; +} + +#filters .filter-text span { + padding: 3px 0.5em; +} + +#filters .whole-word i { + padding: 0 1px; + border: 1px dashed; } #filters span:hover { @@ -188,11 +260,48 @@ table caption { background: #efe; } +#filters .pager { + margin-top: 0.5em; + text-align: right; +} + +#filters .pager div { + margin-top: 0.5em; +} + +#filters .pager div span { + padding: 0 0.5em; + margin: 0 1px; +} + +#filters .pager span { + background-color: #eee; + border-color: #888; +} + +#filters .pager span.active { + font-weight: bold; + border-color: transparent; + background: transparent; + cursor: unset; +} + +#filters .pager span.disabled { + opacity: 0.3; + cursor: unset; +} + +#filters .pager span:not(.disabled):hover { + background-color: #fff; +} + + /********* ** Log *********/ #log .mod-repeat { font-size: 0.85em; + font-style: italic; } #log .trace { @@ -237,6 +346,11 @@ table caption { white-space: pre-wrap; } +#log .log-message-text strong { + background-color: yellow; + font-weight: normal; +} + #log { border-spacing: 0; } diff --git a/src/SMAPI.Web/wwwroot/Content/css/main.css b/src/SMAPI.Web/wwwroot/Content/css/main.css index dcc7a798..a0a407d8 100644 --- a/src/SMAPI.Web/wwwroot/Content/css/main.css +++ b/src/SMAPI.Web/wwwroot/Content/css/main.css @@ -97,6 +97,22 @@ a { margin-left: 1em; } +/* quick navigation */ + +#quickNav { + position: fixed; + bottom: 3em; + width: 12em; +} + +@media (max-height: 400px) { + #quickNav { + position: unset; + width: auto; + } +} + + /* footer */ #footer { margin: 1em; @@ -111,11 +127,16 @@ a { /* mobile fixes */ @media (min-width: 1020px) and (max-width: 1199px) { + #quickNav, #sidebar { width: 7em; background: none; } + #quickNav h4 { + width: unset; + } + #content-column { left: 7em; } @@ -138,4 +159,9 @@ a { top: inherit; left: inherit; } + + #quickNav { + position: unset; + width: auto; + } } diff --git a/src/SMAPI.Web/wwwroot/Content/js/log-parser.js b/src/SMAPI.Web/wwwroot/Content/js/log-parser.js index 90715375..fccd00be 100644 --- a/src/SMAPI.Web/wwwroot/Content/js/log-parser.js +++ b/src/SMAPI.Web/wwwroot/Content/js/log-parser.js @@ -1,56 +1,922 @@ -/* globals $ */ +/* globals $, Vue */ +/** + * The global SMAPI module. + */ var smapi = smapi || {}; + +/** + * The Vue app for the current page. + * @type {Vue} + */ var app; -smapi.logParser = function (data, sectionUrl) { + +// Use a scroll event to apply a sticky effect to the filters / pagination +// bar. We can't just use "position: sticky" due to how the page is structured +// but this works well enough. +$(function () { + let sticking = false; + + document.addEventListener("scroll", function () { + const filters = document.getElementById("filters"); + const holder = document.getElementById("filterHolder"); + if (!filters || !holder) + return; + + const offset = holder.offsetTop; + const shouldStick = window.pageYOffset > offset; + if (shouldStick === sticking) + return; + + sticking = shouldStick; + if (sticking) { + holder.style.marginBottom = `calc(1em + ${filters.offsetHeight}px)`; + filters.classList.add("sticky"); + } + else { + filters.classList.remove("sticky"); + holder.style.marginBottom = ""; + } + }); +}); + +/** + * Initialize a log parser view on the current page. + * @param {object} state The state options to use. + * @returns {void} + */ +smapi.logParser = function (state) { + if (!state) + state = {}; + + // internal helpers + const helpers = { + /** + * Get a handler which invokes the callback after a set delay, resetting the delay each time it's called. + * @param {(...*) => void} action The callback to invoke when the delay ends. + * @param {number} delay The number of milliseconds to delay the action after each call. + * @returns {() => void} + */ + getDebouncedHandler(action, delay) { + let timeoutId = null; + + return function () { + clearTimeout(timeoutId); + + const args = arguments; + const self = this; + + timeoutId = setTimeout( + function () { + action.apply(self, args); + }, + delay + ); + } + }, + + /** + * Escape regex special characters in the given string. + * @param {string} text + * @returns {string} + */ + escapeRegex(text) { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + }, + + /** + * Format a number for the user's locale. + * @param {number} value The number to format. + * @returns {string} + */ + formatNumber(value) { + const formatter = window.Intl && Intl.NumberFormat && new Intl.NumberFormat(); + return formatter && formatter.format + ? formatter.format(value) + : `${value}`; + }, + + /** + * Try parsing the value as a base-10 integer. + * @param {string} value The value to parse. + * @param {number} defaultValue The value to return if parsing fails. + * @param {() => boolean} criteria An optional callback to check whether a parsed number is valid. + * @returns {number} The parsed number if it's valid, else the default value. + */ + tryParseNumber(value, defaultValue, criteria = null) { + value = parseInt(value, 10); + return !isNaN(value) && isFinite(value) && (!criteria || criteria(value)) + ? value + : defaultValue; + }, + + /** + * Get whether two objects are equivalent based on their top-level properties. + * @param {Object} left The first value to compare. + * @param {Object} right The second value to compare. + * @returns {Boolean} + */ + shallowEquals(left, right) { + if (typeof left !== "object" || typeof right !== "object") + return left === right; + + if (left == null || right == null) + return left == null && right == null; + + if (Array.isArray(left) !== Array.isArray(right)) + return false; + + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + + if (leftKeys.length != rightKeys.length) + return false; + + for (const key of leftKeys) { + if (!rightKeys.includes(key) || left[key] !== right[key]) + return false; + } + + return true; + } + }; + + // internal event handlers + const handlers = { + /** + * Method called when the user clicks a log line to toggle the visibility of a section. Binding methods is problematic with functional components so we just use the `data-section` parameter and our global reference to the app. + * @param {any} event + * @returns {false} + */ + clickLogLine(event) { + app.toggleSection(event.currentTarget.dataset.section); + event.preventDefault(); + return false; + }, + + /** + * Navigate to the previous page of messages in the log. + * @returns {void} + */ + prevPage() { + app.prevPage(); + }, + + /** + * Navigate to the next page of messages in the log. + * @returns {void} + */ + nextPage() { + app.nextPage(); + }, + + /** + * Handle a click on a page number element. + * @param {number | Event} event + * @returns {void} + */ + changePage(event) { + if (typeof event === "number") + app.changePage(event); + else if (event) { + const page = parseInt(event.currentTarget.dataset.page); + if (!isNaN(page) && isFinite(page)) + app.changePage(page); + } + } + }; + // internal filter counts - var stats = data.stats = { + const stats = state.stats = { modsShown: 0, modsHidden: 0 }; - function updateModFilters() { - // counts - stats.modsShown = 0; - stats.modsHidden = 0; - for (var key in data.showMods) { - if (data.showMods.hasOwnProperty(key)) { - if (data.showMods[key]) - stats.modsShown++; - else - stats.modsHidden++; + + // load raw log data + { + const dataElement = document.querySelector(state.dataElement); + state.data = JSON.parse(dataElement.textContent.trim()); + dataElement.remove(); // let browser unload the data element since we won't need it anymore + } + + // preprocess data for display + state.messages = state.data.messages || []; + if (state.messages.length) { + const levels = state.data.logLevels; + const sections = state.data.sections; + const modSlugs = state.data.modSlugs; + + for (let i = 0, length = state.messages.length; i < length; i++) { + const message = state.messages[i]; + + // add unique ID + message.id = i; + + // add display values + message.LevelName = levels[message.Level]; + message.SectionName = sections[message.Section]; + message.ModSlug = modSlugs[message.Mod] || message.Mod; + + // For repeated messages, since our <log-line /> component + // can't return two rows, just insert a second message + // which will display as the message repeated notice. + if (message.Repeated > 0 && !message.isRepeated) { + const repeatNote = { + id: i + 1, + Level: message.Level, + Section: message.Section, + Mod: message.Mod, + Repeated: message.Repeated, + isRepeated: true + }; + + state.messages.splice(i + 1, 0, repeatNote); + length++; } + + // let Vue know the message won't change, so it doesn't need to monitor it + Object.freeze(message); } } + Object.freeze(state.messages); // set local time started - if (data) - data.localTimeStarted = ("0" + data.logStarted.getHours()).slice(-2) + ":" + ("0" + data.logStarted.getMinutes()).slice(-2); + if (state.logStarted) + state.localTimeStarted = ("0" + state.logStarted.getHours()).slice(-2) + ":" + ("0" + state.logStarted.getMinutes()).slice(-2); + + // add the properties we're passing to Vue + const defaultPerPage = 1000; + state.totalMessages = state.messages.length; + state.filterText = ""; + state.filterRegex = null; + state.filterError = null; + state.showContentPacks = true; + state.useHighlight = true; + state.useRegex = false; + state.useInsensitive = true; + state.useWord = false; + state.perPage = defaultPerPage; + state.page = 1; + + state.defaultMods = { ...state.showMods }; + state.defaultSections = { ...state.showSections }; + state.defaultLevels = { ...state.showLevels }; + + // load saved values, if any + if (localStorage.settings) { + try { + const saved = JSON.parse(localStorage.settings); + + state.showContentPacks = saved.showContentPacks ?? state.showContentPacks; + state.useHighlight = saved.useHighlight ?? state.useHighlight; + state.useRegex = saved.useRegex ?? state.useRegex; + state.useInsensitive = saved.useInsensitive ?? state.useInsensitive; + state.useWord = saved.useWord ?? state.useWord; + } + catch (error) { + // ignore settings if invalid + } + } + + // add a number formatter so our numbers look nicer + Vue.filter("number", handlers.formatNumber); + + // Strictly speaking, we don't need this. However, due to the way our + // Vue template is living in-page the browser is "helpful" and moves + // our <log-line />s outside of a basic <table> since obviously they + // aren't table rows and don't belong inside a table. By using another + // Vue component, we avoid that. + Vue.component("log-table", { + functional: true, + render: function (createElement, context) { + return createElement( + "table", + { + attrs: { + id: "log" + } + }, + context.children + ); + } + }); + + // The <filter-stats /> component draws a nice message under the filters + // telling a user how many messages match their filters, and also expands + // on how many of them they're seeing because of pagination. + Vue.component("filter-stats", { + functional: true, + render: function (createElement, context) { + const props = context.props; + return createElement( + "div", + { class: "stats" }, + [ + createElement( + "abbr", + { + attrs: { + title: "These numbers may be inaccurate when using filtering with sections collapsed." + } + }, + [ + "showing ", + createElement("strong", helpers.formatNumber(props.start + 1)), + " to ", + createElement("strong", helpers.formatNumber(props.end)), + " of ", + createElement("strong", helpers.formatNumber(props.filtered)) + ] + ), + " (total: ", + createElement("strong", helpers.formatNumber(props.total)), + ")" + ] + ); + } + }); + + // Next up we have <pager /> which renders the pagination list. This has a + // helper method to make building the list of links easier. + function addPageLink(page, links, visited, createElement, currentPage) { + if (visited.has(page)) + return; + + if (page > 1 && !visited.has(page - 1)) + links.push(" … "); + + visited.add(page); + links.push(createElement( + "span", + { + class: page === currentPage ? "active" : null, + attrs: { + "data-page": page + }, + on: { + click: handlers.changePage + } + }, + helpers.formatNumber(page) + )); + } + + Vue.component("pager", { + functional: true, + render: function (createElement, context) { + const props = context.props; + if (props.pages <= 1) + return null; + + const visited = new Set(); + const pageLinks = []; + + for (let i = 1; i <= 2; i++) + addPageLink(i, pageLinks, visited, createElement, props.page); + + for (let i = props.page - 2; i <= props.page + 2; i++) { + if (i >= 1 && i <= props.pages) + addPageLink(i, pageLinks, visited, createElement, props.page); + } + + for (let i = props.pages - 2; i <= props.pages; i++) { + if (i >= 1) + addPageLink(i, pageLinks, visited, createElement, props.page); + } + + return createElement( + "div", + { class: "pager" }, + [ + createElement( + "span", + { + class: props.page <= 1 ? "disabled" : null, + on: { + click: handlers.prevPage + } + }, + "Prev" + ), + " ", + "Page ", + helpers.formatNumber(props.page), + " of ", + helpers.formatNumber(props.pages), + " ", + createElement( + "span", + { + class: props.page >= props.pages ? "disabled" : null, + on: { + click: handlers.nextPage + } + }, + "Next" + ), + createElement("div", {}, pageLinks) + ] + ); + } + }); + + // Our <log-line /> functional component draws each log line. + Vue.component("log-line", { + functional: true, + props: { + showScreenId: { + type: Boolean, + required: true + }, + message: { + type: Object, + required: true + }, + highlight: { + type: Boolean, + required: false + } + }, + render: function (createElement, context) { + const message = context.props.message; + const level = message.LevelName; + + if (message.isRepeated) + return createElement( + "tr", + { + class: [ + "mod", + level, + "mod-repeat" + ] + }, + [ + createElement( + "td", + { + attrs: { + colspan: context.props.showScreenId ? 4 : 3 + } + }, + "" + ), + createElement("td", `repeats ${message.Repeated} times`) + ] + ); + + const events = {}; + let toggleMessage; + if (message.IsStartOfSection) { + const visible = message.SectionName && window.app && app.sectionsAllow(message.SectionName); + events.click = handlers.clickLogLine; + toggleMessage = visible + ? "This section is shown. Click here to hide it." + : "This section is hidden. Click here to show it."; + } + + let text = message.Text; + const filter = window.app && app.filterRegex; + if (text && filter && context.props.highlight) { + text = []; + let match; + let consumed = 0; + let index = 0; + filter.lastIndex = -1; + + // Our logic to highlight the text is a bit funky because we + // want to group consecutive matches to avoid a situation + // where a ton of single characters are in their own elements + // if the user gives us bad input. + + while (true) { + match = filter.exec(message.Text); + if (!match) + break; + + // Do we have an area of non-matching text? This + // happens if the new match's index is further + // along than the last index. + if (match.index > index) { + // Alright, do we have a previous match? If + // we do, we need to consume some text. + if (consumed < index) + text.push(createElement("strong", {}, message.Text.slice(consumed, index))); + + text.push(message.Text.slice(index, match.index)); + consumed = match.index; + } + + index = match.index + match[0].length; + + // In the event of a zero-length match, forcibly increment + // the last index of the regular expression to ensure we + // aren't stuck in an infinite loop. + if (match[0].length == 0) + filter.lastIndex++; + } + + // Add any trailing text after the last match was found. + if (consumed < message.Text.length) { + if (consumed < index) + text.push(createElement("strong", {}, message.Text.slice(consumed, index))); + + if (index < message.Text.length) + text.push(message.Text.slice(index)); + } + } + + return createElement( + "tr", + { + class: [ + "mod", + level, + message.IsStartOfSection ? "section-start" : null + ], + attrs: { + "data-section": message.SectionName + }, + on: events + }, + [ + createElement("td", message.Time), + context.props.showScreenId ? createElement("td", message.ScreenId) : null, + createElement("td", level.toUpperCase()), + createElement( + "td", + { + attrs: { + "data-title": message.Mod + } + }, + message.Mod + ), + createElement( + "td", + [ + createElement( + "span", + { class: "log-message-text" }, + text + ), + message.IsStartOfSection + ? createElement( + "span", + { class: "section-toggle-message" }, + [ + " ", + toggleMessage + ] + ) + : null + ] + ) + ] + ); + } + }); // init app app = new Vue({ - el: '#output', - data: data, + el: "#output", + data: state, computed: { anyModsHidden: function () { return stats.modsHidden > 0; }, anyModsShown: function () { return stats.modsShown > 0; + }, + showScreenId: function () { + return this.data.screenIds.length > 1; + }, + + // Maybe not strictly necessary, but the Vue template is being + // weird about accessing data entries on the app rather than + // computed properties. + hideContentPacks: function () { + return !state.showContentPacks; + }, + + // Filter messages for visibility. + filterUseRegex: function () { + return state.useRegex; + }, + filterInsensitive: function () { + return state.useInsensitive; + }, + filterUseWord: function () { + return state.useWord; + }, + shouldHighlight: function () { + return state.useHighlight; + }, + + filteredMessages: function () { + if (!state.messages) + return []; + + //const start = performance.now(); + const filtered = []; + + let total = 0; + + // This is slightly faster than messages.filter(), which is + // important when working with absolutely huge logs. + for (let i = 0, length = state.messages.length; i < length; i++) { + const msg = state.messages[i]; + if (!this.filtersAllow(msg.ModSlug, msg.LevelName)) + continue; + + if (this.filterRegex) { + const text = msg.Text || (i > 0 ? state.messages[i - 1].Text : null); + this.filterRegex.lastIndex = -1; + if (!text || !this.filterRegex.test(text)) + continue; + } + + total++; + + if (msg.SectionName && !msg.IsStartOfSection && !this.sectionsAllow(msg.SectionName)) + continue; + + filtered.push(msg); + } + + filtered.total = total; + + Object.freeze(filtered); + + //const end = performance.now(); + //console.log(`applied ${(this.useRegex ? "regex" : "text")} filter '${this.filterRegex}' in ${end - start}ms`); + + return filtered; + }, + + // And the rest are about pagination. + start: function () { + return (this.page - 1) * state.perPage; + }, + end: function () { + return this.start + this.visibleMessages.length; + }, + totalPages: function () { + return Math.ceil(this.filteredMessages.length / state.perPage); + }, + // + visibleMessages: function () { + if (this.totalPages <= 1) + return this.filteredMessages; + + const start = this.start; + const end = start + state.perPage; + + return this.filteredMessages.slice(start, end); } }, + created: function () { + window.addEventListener("popstate", () => this.loadFromUrl()); + this.loadFromUrl(); + }, methods: { + loadFromUrl: function () { + const params = new URL(location).searchParams; + + state.perPage = helpers.tryParseNumber(params.get("PerPage"), defaultPerPage, n => n > 0); + this.page = helpers.tryParseNumber(params.get("Page"), 1, n => n > 0); + state.filterText = params.get("Filter") || ""; + + if (params.has("FilterMode")) { + const values = params.get("FilterMode").split("~"); + state.useRegex = values.includes("Regex"); + state.useInsensitive = !values.includes("Sensitive"); + state.useWord = values.includes("Word"); + } + else { + state.useRegex = false; + state.useInsensitive = true; + state.useWord = false; + } + + if (params.has("Mods")) { + const value = params.get("Mods").split("~"); + for (const key of Object.keys(this.showMods)) + this.showMods[key] = value.includes(key); + + } + else { + for (const key of Object.keys(this.showMods)) + this.showMods[key] = state.defaultMods[key]; + } + + if (params.has("Levels")) { + const values = params.get("Levels").split("~"); + for (const key of Object.keys(this.showLevels)) + this.showLevels[key] = values.includes(key); + + } + else { + const keys = Object.keys(this.showLevels); + for (const key of Object.keys(this.showLevels)) + this.showLevels[key] = state.defaultLevels[key]; + } + + if (params.has("Sections")) { + const values = params.get("Sections").split("~"); + for (const key of Object.keys(this.showSections)) + this.showSections[key] = values.includes(key); + + } + else { + for (const key of Object.keys(this.showSections)) + this.showSections[key] = state.defaultSections[key]; + } + + this.updateModFilters(); + this.updateFilterText(); + }, + + /** + * Update the page URL to track non-default filter values. + */ + updateUrl: function () { + const url = new URL(location); + + if (state.page != 1 || state.perPage != defaultPerPage) { + url.searchParams.set("Page", state.page); + url.searchParams.set("PerPage", state.perPage); + } + else { + url.searchParams.delete("Page"); + url.searchParams.delete("PerPage"); + } + + if (!helpers.shallowEquals(this.showMods, state.defaultMods)) + url.searchParams.set("Mods", Object.entries(this.showMods).filter(p => p[1]).map(p => p[0]).join("~")); + else + url.searchParams.delete("Mods"); + + if (!helpers.shallowEquals(this.showLevels, state.defaultLevels)) + url.searchParams.set("Levels", Object.entries(this.showLevels).filter(p => p[1]).map(p => p[0]).join("~")); + else + url.searchParams.delete("Levels"); + + if (!helpers.shallowEquals(this.showSections, state.defaultSections)) + url.searchParams.set("Sections", Object.entries(this.showSections).filter(p => p[1]).map(p => p[0]).join("~")); + else + url.searchParams.delete("Sections"); + + if (state.filterText?.length) { + url.searchParams.set("Filter", state.filterText); + + const modes = []; + if (state.useRegex) + modes.push("Regex"); + if (!state.useInsensitive) + modes.push("Sensitive"); + if (state.useWord) + modes.push("Word"); + + if (modes.length) + url.searchParams.set("FilterMode", modes.join("~")); + else + url.searchParams.delete("FilterMode"); + + } + else { + url.searchParams.delete("Filter"); + url.searchParams.delete("FilterMode"); + } + + window.history.replaceState(null, document.title, url.toString()); // use replaceState instead of pushState to avoid filling the tab history with history steps the user probably doesn't care about + }, + toggleLevel: function (id) { - if (!data.enableFilters) + if (!state.enableFilters) return; this.showLevels[id] = !this.showLevels[id]; + this.updateUrl(); + }, + + toggleContentPacks: function () { + state.showContentPacks = !state.showContentPacks; + this.saveSettings(); + }, + + toggleFilterUseRegex: function () { + state.useRegex = !state.useRegex; + this.saveSettings(); + this.updateFilterText(); + }, + + toggleFilterInsensitive: function () { + state.useInsensitive = !state.useInsensitive; + this.saveSettings(); + this.updateFilterText(); + }, + + toggleFilterWord: function () { + state.useWord = !state.useWord; + this.saveSettings(); + this.updateFilterText(); + }, + + toggleHighlight: function () { + state.useHighlight = !state.useHighlight; + this.saveSettings(); + }, + + prevPage: function () { + if (this.page <= 1) + return; + this.page--; + this.updateUrl(); + }, + + nextPage: function () { + if (this.page >= this.totalPages) + return; + this.page++; + this.updateUrl(); + }, + + changePage: function (page) { + if (page < 1 || page > this.totalPages) + return; + this.page = page; + this.updateUrl(); + }, + + /** + * Persist settings into localStorage for use the next time the user opens a log. + */ + saveSettings: function () { + localStorage.settings = JSON.stringify({ + showContentPacks: state.showContentPacks, + useRegex: state.useRegex, + useInsensitive: state.useInsensitive, + useWord: state.useWord, + useHighlight: state.useHighlight + }); + }, + + // We don't want to update the filter text often, so use a debounce with + // a quarter second delay. We basically always build a regular expression + // since we use it for highlighting, and it also make case insensitivity + // much easier. + updateFilterText: helpers.getDebouncedHandler( + function () { + // reset + this.filterError = null; + this.filterRegex = null; + + // apply search + let text = state.filterText; + if (!text) + this.filterText = ""; + else { + if (!state.useRegex) + text = helpers.escapeRegex(text); + + const flags = state.useInsensitive ? "ig" : "g"; + + try { + this.filterRegex = new RegExp(text, flags); + } + catch (err) { + this.filterError = err.message; + } + + if (this.filterRegex && state.useWord) + this.filterRegex = new RegExp(`\\b(?:${text})\\b`, flags); + } + + this.updateUrl(); + }, + 250 + ), + + updateModFilters: function () { + // counts + stats.modsShown = 0; + stats.modsHidden = 0; + for (let key in state.showMods) { + if (state.showMods.hasOwnProperty(key)) { + if (state.showMods[key]) + stats.modsShown++; + else + stats.modsHidden++; + } + } }, toggleMod: function (id) { - if (!data.enableFilters) + if (!state.enableFilters) return; - var curShown = this.showMods[id]; + const curShown = this.showMods[id]; // first filter: only show this by default if (stats.modsHidden === 0) { @@ -66,38 +932,42 @@ smapi.logParser = function (data, sectionUrl) { else this.showMods[id] = !this.showMods[id]; - updateModFilters(); + this.updateModFilters(); + this.updateUrl(); }, toggleSection: function (name) { - if (!data.enableFilters) + if (!state.enableFilters) return; this.showSections[name] = !this.showSections[name]; + this.updateUrl(); }, showAllMods: function () { - if (!data.enableFilters) + if (!state.enableFilters) return; - for (var key in this.showMods) { + for (let key in this.showMods) { if (this.showMods.hasOwnProperty(key)) { this.showMods[key] = true; } } - updateModFilters(); + this.updateModFilters(); + this.updateUrl(); }, hideAllMods: function () { - if (!data.enableFilters) + if (!state.enableFilters) return; - for (var key in this.showMods) { + for (let key in this.showMods) { if (this.showMods.hasOwnProperty(key)) { this.showMods[key] = false; } } - updateModFilters(); + this.updateModFilters(); + this.updateUrl(); }, filtersAllow: function (modId, level) { @@ -113,7 +983,7 @@ smapi.logParser = function (data, sectionUrl) { /********** ** Upload form *********/ - var input = $("#input"); + const input = $("#input"); if (input.length) { // file upload smapi.fileUpload({ diff --git a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json index 6b80f260..4975a973 100644 --- a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json +++ b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json @@ -14,9 +14,9 @@ "title": "Format version", "description": "The format version. You should always use the latest version to enable the latest features, avoid obsolete behavior, and reduce load times.", "type": "string", - "const": "1.24.0", + "const": "1.25.0", "@errorMessages": { - "const": "Incorrect value '@value'. You should always use the latest format version (currently 1.24.0) to enable the latest features, avoid obsolete behavior, and reduce load times." + "const": "Incorrect value '@value'. You should always use the latest format version (currently 1.25.0) to enable the latest features, avoid obsolete behavior, and reduce load times." } }, "ConfigSchema": { @@ -159,6 +159,14 @@ "additionalProperties": false } }, + "AliasTokenNames": { + "title": "Alias token names", + "description": "Defines optional alternate name for existing tokens. This only affects your content pack, and you can use both the alias name and the original token name. This is mostly useful for custom tokens provided by other mods, which often have longer names. Each entry key is the alias name, and the value is the original token name.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "Changes": { "title": "Changes", "description": "The changes you want to make. Each entry is called a patch, and describes a specific action to perform: replace this file, copy this image into the file, etc. You can list any number of patches.", @@ -187,22 +195,6 @@ "description": "A name for this patch shown in log messages. This is very useful for understanding errors; if not specified, will default to a name like 'entry #14 (EditImage Animals/Dinosaurs)'.", "type": "string" }, - "Enabled": { - "title": "Enabled", - "description": "Whether to apply this patch. Default true. This field does not allow tokens.", - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "string", - "enum": [ "true", "false" ] - } - ], - "@errorMessages": { - "anyOf": "Invalid value; must be true, false, or a single token which evaluates to true or false." - } - }, "Update": { "title": "Update", "description": "When the patch should update if it changed. The possible values are 'OnDayStart', 'OnLocationChange', or 'OnTimeChange' (defaults to OnDayStart).", @@ -241,6 +233,14 @@ "description": "The part of the target image to replace. Defaults to the FromArea size starting from the top-left corner.", "$ref": "#/definitions/Rectangle" }, + "TargetField": { + "title": "Target field", + "description": "The path to the field within the value to set as the root scope. See 'target field' in the EditData documentation for more info. This field supports tokens.", + "type": "array", + "items": { + "type": "string" + } + }, "Fields": { "title": "Fields", "description": "The individual fields you want to change for existing entries. This field supports tokens in field keys and values. The key for each field is the field index (starting at zero) for a slash-delimited string, or the field name for an object.", @@ -408,7 +408,6 @@ "propertyNames": { "enum": [ "Action", - "Enabled", "FromFile", "LogName", "Target", @@ -438,7 +437,6 @@ "propertyNames": { "enum": [ "Action", - "Enabled", "FromFile", "LogName", "Target", @@ -462,12 +460,12 @@ "propertyNames": { "enum": [ "Action", - "Enabled", "LogName", "Target", "Update", "When", + "TargetField", "Entries", "Fields", "MoveEntries", @@ -504,7 +502,6 @@ "propertyNames": { "enum": [ "Action", - "Enabled", "FromFile", "LogName", "Target", @@ -533,7 +530,6 @@ "propertyNames": { "enum": [ "Action", - "Enabled", "FromFile", "LogName", "Update", diff --git a/src/SMAPI.Web/wwwroot/schemas/manifest.json b/src/SMAPI.Web/wwwroot/schemas/manifest.json index b6722347..7457b993 100644 --- a/src/SMAPI.Web/wwwroot/schemas/manifest.json +++ b/src/SMAPI.Web/wwwroot/schemas/manifest.json @@ -103,7 +103,7 @@ "type": "array", "items": { "type": "string", - "pattern": "^(?i)(Chucklefish:\\d+|Nexus:\\d+|GitHub:[A-Za-z0-9_\\-]+/[A-Za-z0-9_\\-]+|ModDrop:\\d+)(?: *@ *[a-zA-Z0-9_]+ *)$", + "pattern": "^(?i)(Chucklefish:\\d+|Nexus:\\d+|GitHub:[A-Za-z0-9_\\-]+/[A-Za-z0-9_\\-]+|ModDrop:\\d+)(?: *@ *[a-zA-Z0-9_]+ *)?$", "@errorMessages": { "pattern": "Invalid update key; see https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest#Update_checks for more info." } |