Fix all warnings

This commit is contained in:
jvyden 2022-05-01 13:44:41 -04:00
parent 50fdcb2441
commit 396477c05d
No known key found for this signature in database
GPG key ID: 18BCF2BE0262B278
39 changed files with 84 additions and 110 deletions

View file

@ -47,7 +47,7 @@ public class AuthenticationTests : LighthouseServerTest
LoginResult loginResult = await this.Authenticate();
HttpResponseMessage response = await this.AuthenticatedRequest("/LITTLEBIGPLANETPS3_XML/enterLevel/420", loginResult.AuthTicket);
string responseContent = await response.Content.ReadAsStringAsync();
await response.Content.ReadAsStringAsync();
Assert.False(response.StatusCode == HttpStatusCode.Forbidden);
}

View file

@ -1,3 +1,4 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

View file

@ -50,7 +50,7 @@ public class UserEndpoints : ApiEndpointController
[HttpGet("user/{id:int}/status")]
[ProducesResponseType(typeof(UserStatus), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserStatus(int id)
public IActionResult GetUserStatus(int id)
{
UserStatus userStatus = new(this.database, id);

View file

@ -25,7 +25,7 @@ public class ClientConfigurationController : ControllerBase
public async Task<IActionResult> NetworkSettings()
{
GameToken? token = await this.database.GameTokenFromRequest(this.Request);
if (token == null) return null;
if (token == null) return this.StatusCode(403, "");
HostString hostname = this.Request.Host;
return this.Ok

View file

@ -47,7 +47,7 @@ public class SearchController : ControllerBase
(
s => s.Name.ToLower().Contains(keyword) ||
s.Description.ToLower().Contains(keyword) ||
s.Creator.Username.ToLower().Contains(keyword) ||
s.Creator!.Username.ToLower().Contains(keyword) ||
s.SlotId.ToString().Equals(keyword)
);

View file

@ -10,12 +10,6 @@ namespace LBPUnion.ProjectLighthouse.Controllers.GameApi;
[Produces("text/plain")]
public class StatisticsController : ControllerBase
{
private readonly Database database;
public StatisticsController(Database database)
{
this.database = database;
}
[HttpGet("playersInPodCount")]
[HttpGet("totalPlayerCount")]
public async Task<IActionResult> TotalPlayerCount() => this.Ok((await StatisticsHelper.RecentMatches()).ToString()!);

View file

@ -24,7 +24,7 @@ public class AdminUserController : ControllerBase
if (user == null || !user.IsAdmin) return this.NotFound();
User? targetedUser = await this.database.Users.FirstOrDefaultAsync(u => u.UserId == id);
;
if (targetedUser == null) return this.NotFound();
targetedUser.Banned = false;

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading.Tasks;
using LBPUnion.ProjectLighthouse.Types.Settings;
@ -14,6 +15,7 @@ public static class CaptchaHelper
BaseAddress = new Uri("https://hcaptcha.com"),
};
[SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeNotEvident")]
public static async Task<bool> Verify(string token)
{
if (!ServerSettings.Instance.HCaptchaEnabled) return true;

View file

@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
@ -24,7 +23,7 @@ public static class HashHelper
{
byte[] b = new byte[count];
lock (RandomHelper.random)
lock(RandomHelper.random)
{
RandomHelper.random.NextBytes(b);
}
@ -33,7 +32,7 @@ public static class HashHelper
}
/// <summary>
/// Generates a random SHA256 & BCrypted token
/// Generates a random SHA256 and BCrypted token
/// </summary>
/// <returns>The token as a string.</returns>
public static string GenerateAuthToken()
@ -75,7 +74,7 @@ public static class HashHelper
public static string Sha1Hash(string str) => Sha1Hash(Encoding.UTF8.GetBytes(str));
public static string Sha1Hash(byte[] bytes) => BitConverter.ToString(SHA1.Create().ComputeHash(bytes)).Replace("-","");
public static string Sha1Hash(byte[] bytes) => BitConverter.ToString(SHA1.Create().ComputeHash(bytes)).Replace("-", "");
public static string BCryptHash(string str) => BCrypt.Net.BCrypt.HashPassword(str);

View file

@ -30,6 +30,7 @@ public static class ImageHelper
LbpFileType.Texture => TextureToPNG(hash, reader),
LbpFileType.Png => PNGToPNG(hash, data),
LbpFileType.Jpeg => JPGToPNG(hash, data),
// ReSharper disable once UnreachableSwitchArmDueToIntegerAnalysis
_ => false,
};
}
@ -57,16 +58,10 @@ public static class ImageHelper
int[] compressed = new int[chunks];
int[] decompressed = new int[chunks];
int decompressedSize = 0;
int compressedSize = 0;
for(int i = 0; i < chunks; ++i)
{
compressed[i] = reader.ReadUInt16BE();
decompressed[i] = reader.ReadUInt16BE();
decompressedSize += decompressed[i];
compressedSize += compressed[i];
}
using MemoryStream ms = new();

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using InfluxDB.Client;
@ -54,6 +55,7 @@ public static class InfluxHelper
}
}
[SuppressMessage("ReSharper", "FunctionNeverReturns")]
public static async Task StartLogging()
{
await Client.ReadyAsync();

View file

@ -1,9 +1,5 @@
using System;
using System.IO;
using System.Linq;
using Kettu;
using LBPUnion.ProjectLighthouse.Logging;
using LBPUnion.ProjectLighthouse.Types.Settings;
namespace LBPUnion.ProjectLighthouse.Helpers;
@ -11,8 +7,7 @@ public static class ResourceHelper
{
public static string readManifestFile(string fileName)
{
using Stream stream =
typeof(Program).Assembly.GetManifestResourceStream($"{typeof(Program).Namespace}.{fileName}");
using Stream stream = typeof(Program).Assembly.GetManifestResourceStream($"{typeof(Program).Namespace}.{fileName}");
using StreamReader reader = new(stream ?? throw new Exception("The assembly or manifest resource is null."));
return reader.ReadToEnd().Trim();

View file

@ -1,5 +1,3 @@
using System;
using System.IO;
using System.Linq;
using Kettu;
using LBPUnion.ProjectLighthouse.Logging;

View file

@ -89,7 +89,8 @@ public class CleanupBrokenPhotosMaintenanceJob : IMaintenanceJob
$"{nameof(noHashesExist)}: {noHashesExist}, " +
$"{nameof(largeHashIsInvalidFile)}: {largeHashIsInvalidFile}, " +
$"{nameof(tooManyPhotoSubjects)}: {tooManyPhotoSubjects}" +
$"{nameof(duplicatePhotoSubjects)}: {duplicatePhotoSubjects}"
$"{nameof(duplicatePhotoSubjects)}: {duplicatePhotoSubjects}" +
$"{nameof(takenInTheFuture)}: {takenInTheFuture}"
);
this.database.Photos.Remove(photo);

View file

@ -11,10 +11,9 @@ namespace LBPUnion.ProjectLighthouse.Pages.Admin;
public class AdminPanelUsersPage : BaseLayout
{
public int UserCount;
public List<User> Users;
public List<User> Users = new();
public AdminPanelUsersPage(Database database) : base(database)
{}

View file

@ -1,6 +1,5 @@
#nullable enable
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Profiles.Email;
@ -12,10 +11,10 @@ namespace LBPUnion.ProjectLighthouse.Pages;
public class CompleteEmailVerificationPage : BaseLayout
{
public CompleteEmailVerificationPage([NotNull] Database database) : base(database)
public CompleteEmailVerificationPage(Database database) : base(database)
{}
public string? Error = null;
public string? Error;
public async Task<IActionResult> OnGet(string token)
{

View file

@ -1,5 +1,4 @@
#nullable enable
using System.Threading.Tasks;
using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using Microsoft.AspNetCore.Mvc;
@ -11,10 +10,10 @@ public class FilterTestPage : BaseLayout
public FilterTestPage(Database database) : base(database)
{}
public string? FilteredText = null;
public string? Text = null;
public string? FilteredText;
public string? Text;
public async Task<IActionResult> OnGet(string? text = null)
public IActionResult OnGet(string? text = null)
{
#if !DEBUG
return this.NotFound();

View file

@ -50,6 +50,7 @@
<h2>Best rooms for each game version</h2>
@foreach (GameVersion version in Enum.GetValues<GameVersion>())
{
#nullable enable
if (version == GameVersion.LittleBigPlanet1 || version == GameVersion.LittleBigPlanetPSP || version == GameVersion.Unknown) continue;
FindBestRoomResponse? response = RoomHelper.FindBestRoom(null, version, null, null, null);

View file

@ -1,26 +1,21 @@
#nullable enable
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using Microsoft.AspNetCore.Mvc;
namespace LBPUnion.ProjectLighthouse.Pages.Debug;
public class RoomVisualizerPage : BaseLayout
{
public RoomVisualizerPage([NotNull] Database database) : base(database)
public RoomVisualizerPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet()
public IActionResult OnGet()
{
#if !DEBUG
User? user = this.Database.UserFromWebRequest(this.Request);
if (user == null || !user.IsAdmin) return this.NotFound();
#endif
return this.Page();
#else
return this.Page();
#endif
}
}

View file

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Settings;
@ -14,13 +13,13 @@ namespace LBPUnion.ProjectLighthouse.Pages.ExternalAuth;
public class AuthenticationPage : BaseLayout
{
public List<AuthenticationAttempt> AuthenticationAttempts;
public List<AuthenticationAttempt> AuthenticationAttempts = new();
public IPAddress? IpAddress;
public AuthenticationPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet()
public IActionResult OnGet()
{
if (!ServerSettings.Instance.UseExternalAuth) return this.NotFound();
if (this.User == null) return this.StatusCode(403, "");

View file

@ -11,8 +11,8 @@ namespace LBPUnion.ProjectLighthouse.Pages.ExternalAuth;
public class ManageUserApprovedIpAddressesPage : BaseLayout
{
public List<UserApprovedIpAddress> ApprovedIpAddresses = new();
public List<UserApprovedIpAddress> ApprovedIpAddresses;
public ManageUserApprovedIpAddressesPage(Database database) : base(database)
{}

View file

@ -15,7 +15,7 @@ public class LandingPage : BaseLayout
{
public int AuthenticationAttemptsCount;
public List<User> PlayersOnline;
public List<User> PlayersOnline = new();
public int PlayersOnlineCount;
public LandingPage(Database database) : base(database)

View file

@ -21,7 +21,7 @@ public class LoginForm : BaseLayout
public LoginForm(Database database) : base(database)
{}
public string Error { get; private set; }
public string? Error { get; private set; }
[UsedImplicitly]
public async Task<IActionResult> OnPost(string username, string password)
@ -111,9 +111,5 @@ public class LoginForm : BaseLayout
}
[UsedImplicitly]
public async Task<IActionResult> OnGet()
{
this.Error = string.Empty;
return this.Page();
}
public IActionResult OnGet() => this.Page();
}

View file

@ -13,7 +13,7 @@ public class PasswordResetPage : BaseLayout
public PasswordResetPage(Database database) : base(database)
{}
public string Error { get; private set; }
public string? Error { get; private set; }
[UsedImplicitly]
public async Task<IActionResult> OnPost(string password, string confirmPassword)

View file

@ -1,6 +1,4 @@
#nullable enable
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using Microsoft.AspNetCore.Mvc;
@ -9,12 +7,12 @@ namespace LBPUnion.ProjectLighthouse.Pages;
public class PasswordResetRequiredPage : BaseLayout
{
public PasswordResetRequiredPage([NotNull] Database database) : base(database)
public PasswordResetRequiredPage(Database database) : base(database)
{}
public bool WasResetRequest { get; private set; }
public async Task<IActionResult> OnGet()
public IActionResult OnGet()
{
User? user = this.Database.UserFromWebRequest(this.Request);
if (user == null) return this.Redirect("~/login");

View file

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Settings;
@ -21,10 +20,10 @@ public class PhotosPage : BaseLayout
public int PhotoCount;
public List<Photo> Photos;
public List<Photo> Photos = new();
public string SearchValue;
public PhotosPage([NotNull] Database database) : base(database)
public string? SearchValue;
public PhotosPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet([FromRoute] int pageNumber, [FromQuery] string? name)
@ -33,15 +32,18 @@ public class PhotosPage : BaseLayout
this.SearchValue = name.Replace(" ", string.Empty);
this.PhotoCount = await this.Database.Photos.CountAsync(p => p.Creator.Username.Contains(this.SearchValue) || p.PhotoSubjectCollection.Contains(this.SearchValue));
this.PhotoCount = await this.Database.Photos.Include
(p => p.Creator)
.CountAsync(p => p.Creator!.Username.Contains(this.SearchValue) || p.PhotoSubjectCollection.Contains(this.SearchValue));
this.PageNumber = pageNumber;
this.PageAmount = Math.Max(1, (int)Math.Ceiling((double)this.PhotoCount / ServerStatics.PageSize));
if (this.PageNumber < 0 || this.PageNumber >= this.PageAmount) return this.Redirect($"/photos/{Math.Clamp(this.PageNumber, 0, this.PageAmount - 1)}");
this.Photos = await this.Database.Photos.Include(p => p.Creator)
.Where(p => p.Creator.Username.Contains(this.SearchValue) || p.PhotoSubjectCollection.Contains(this.SearchValue))
this.Photos = await this.Database.Photos.Include
(p => p.Creator)
.Where(p => p.Creator!.Username.Contains(this.SearchValue) || p.PhotoSubjectCollection.Contains(this.SearchValue))
.OrderByDescending(p => p.Timestamp)
.Skip(pageNumber * ServerStatics.PageSize)
.Take(ServerStatics.PageSize)

View file

@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Reports;
@ -23,12 +22,12 @@ public class ReportsPage : BaseLayout
public int ReportCount;
public List<GriefReport> Reports;
public List<GriefReport> Reports = new();
public string SearchValue;
public string SearchValue = "";
public ReportsPage([NotNull] Database database) : base(database)
{ }
public ReportsPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet([FromRoute] int pageNumber, [FromQuery] string? name)
{
@ -43,7 +42,7 @@ public class ReportsPage : BaseLayout
this.ReportCount = await this.Database.Reports.Include(r => r.ReportingPlayer).CountAsync(r => r.ReportingPlayer.Username.Contains(this.SearchValue));
this.PageNumber = pageNumber;
this.PageAmount = Math.Max(1, (int) Math.Ceiling((double) this.ReportCount / ServerStatics.PageSize));
this.PageAmount = Math.Max(1, (int)Math.Ceiling((double)this.ReportCount / ServerStatics.PageSize));
if (this.PageNumber < 0 || this.PageNumber >= this.PageAmount)
return this.Redirect($"/admin/reports/{Math.Clamp(this.PageNumber, 0, this.PageAmount - 1)}");
@ -57,11 +56,11 @@ public class ReportsPage : BaseLayout
foreach (GriefReport r in this.Reports)
{
r.XmlPlayers = (ReportPlayer[]) JsonSerializer.Deserialize(r.Players, typeof(ReportPlayer[]))!;
r.XmlPlayers = (ReportPlayer[])JsonSerializer.Deserialize(r.Players, typeof(ReportPlayer[]))!;
r.XmlBounds = new Marqee()
{
Rect = (Rectangle) JsonSerializer.Deserialize(r.Bounds, typeof(Rectangle))!,
Rect = (Rectangle)JsonSerializer.Deserialize(r.Bounds, typeof(Rectangle))!,
};
}

View file

@ -7,7 +7,7 @@
}
<p>An email address on your account has been set, but hasn't been verified yet.</p>
<p>To verify it, check the email sent to <a href="mailto:@Model.User.EmailAddress">@Model.User.EmailAddress</a> and click the link in the email.</p>
<p>To verify it, check the email sent to <a href="mailto:@Model.User?.EmailAddress">@Model.User?.EmailAddress</a> and click the link in the email.</p>
<a href="/login/sendVerificationEmail">
<div class="ui blue button">Resend email</div>

View file

@ -21,7 +21,7 @@
<i class="mail icon"></i>
</div>
<input type="hidden" name="token" id="token" value="@Model.EmailToken.EmailToken">
<input type="hidden" name="token" id="token" value="@Model.EmailToken?.EmailToken">
</div>
}

View file

@ -19,7 +19,7 @@ public class SetEmailForm : BaseLayout
public SetEmailForm(Database database) : base(database)
{}
public EmailSetToken EmailToken;
public EmailSetToken? EmailToken;
public async Task<IActionResult> OnGet(string? token = null)
{

View file

@ -15,13 +15,13 @@ namespace LBPUnion.ProjectLighthouse.Pages;
public class SlotPage : BaseLayout
{
public List<Comment> Comments;
public List<Review> Reviews;
public List<Comment> Comments = new();
public List<Review> Reviews = new();
public readonly bool CommentsEnabled = ServerSettings.Instance.LevelCommentsEnabled;
public readonly bool ReviewsEnabled = ServerSettings.Instance.LevelReviewsEnabled;
public Slot Slot;
public Slot? Slot;
public SlotPage(Database database) : base(database)
{}

View file

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types.Levels;
using LBPUnion.ProjectLighthouse.Types.Settings;
@ -21,11 +20,11 @@ public class SlotsPage : BaseLayout
public int SlotCount;
public List<Slot> Slots;
public List<Slot> Slots = new();
public string SearchValue;
public string? SearchValue;
public SlotsPage([NotNull] Database database) : base(database)
public SlotsPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet([FromRoute] int pageNumber, [FromQuery] string? name)

View file

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Settings;
@ -20,11 +19,11 @@ public class UsersPage : BaseLayout
public int UserCount;
public List<User> Users;
public List<User> Users = new();
public string SearchValue;
public string? SearchValue;
public UsersPage([NotNull] Database database) : base(database)
public UsersPage(Database database) : base(database)
{}
public async Task<IActionResult> OnGet([FromRoute] int pageNumber, [FromQuery] string? name)

View file

@ -19,7 +19,7 @@ public class LbpFile
public readonly string Hash;
public LbpFile(byte[] data, string? hash = null)
public LbpFile(byte[] data)
{
this.Data = data;
@ -34,6 +34,6 @@ public class LbpFile
byte[] data = File.ReadAllBytes(path);
return new LbpFile(data, hash);
return new LbpFile(data);
}
}

View file

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using LBPUnion.ProjectLighthouse.Serialization;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace LBPUnion.ProjectLighthouse.Types.Reports;

View file

@ -14,6 +14,8 @@ public class ServerSettings
{
public const int CurrentConfigVersion = 26; // MUST BE INCREMENTED FOR EVERY CONFIG CHANGE!
private static FileSystemWatcher fileWatcher;
// ReSharper disable once NotNullMemberIsNotInitialized
static ServerSettings()
{
if (ServerStatics.IsUnitTesting) return; // Unit testing, we don't want to read configurations here since the tests will provide their own

View file

@ -26,7 +26,7 @@ public static class ServerStatics
}
}
public static bool IsUnitTesting => AppDomain.CurrentDomain.GetAssemblies().Any(assembly => assembly.FullName.StartsWith("xunit"));
public static bool IsUnitTesting => AppDomain.CurrentDomain.GetAssemblies().Any(assembly => assembly.FullName!.StartsWith("xunit"));
#if DEBUG
public static readonly bool IsDebug = true;

View file

@ -16,9 +16,9 @@ namespace LBPUnion.ProjectLighthouse.Types.Tickets;
/// </summary>
public class NPTicket
{
public string Username { get; set; }
public string? Username { get; set; }
private Version ticketVersion { get; set; }
private Version? ticketVersion { get; set; }
public Platform Platform { get; set; }
@ -26,7 +26,7 @@ public class NPTicket
public ulong IssuedDate { get; set; }
public ulong ExpireDate { get; set; }
private string titleId { get; set; }
private string? titleId { get; set; }
public GameVersion GameVersion { get; set; }
@ -111,6 +111,8 @@ public class NPTicket
default: throw new NotImplementedException();
}
if (npTicket.titleId == null) throw new ArgumentNullException($"{nameof(npTicket)}.{nameof(npTicket.titleId)}");
// We already read the title id, however we need to do some post-processing to get what we want.
// Current data: UP9000-BCUS98245_00
// We need to chop this to get the titleId we're looking for

View file

@ -11,9 +11,11 @@ namespace LBPUnion.ProjectLighthouse.Types;
public class User
{
#nullable enable
[NotMapped]
[JsonIgnore]
private Database? _database;
#nullable disable
[NotMapped]
[JsonIgnore]