Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions API/Controller/Admin/GetOnlineDevices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task<IActionResult> GetOnlineDevices()
{
var devicesOnline = _redis.RedisCollection<DeviceOnline>(false);

var allOnlineDevices = await devicesOnline.ToListAsync();
var allOnlineDevices = await devicesOnline.ToArrayAsync();
var dbLookup = await _db.Devices.Where(x => allOnlineDevices.Select(y => y.Id)
.Contains(x.Id)).Select(
x =>
Expand All @@ -39,7 +39,7 @@ public async Task<IActionResult> GetOnlineDevices()
Image = x.OwnerNavigation.GetImageUrl(),
Name = x.OwnerNavigation.Name
}
}).ToListAsync();
}).ToArrayAsync();

return RespondSuccessLegacy(allOnlineDevices.Select(x =>
{
Expand Down
2 changes: 1 addition & 1 deletion API/Controller/Admin/GetUsers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public async Task<IActionResult> GetUsers(

return Ok(new Paginated<AdminUsersView>
{
Data = await deferredUsers.ToListAsync(),
Data = await deferredUsers.ToArrayAsync(),
Offset = offset,
Limit = limit,
Total = await deferredCount.ValueAsync(),
Expand Down
4 changes: 2 additions & 2 deletions API/Controller/Devices/DevicesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public sealed partial class DevicesController
/// </summary>
/// <response code="200">All devices for the current user</response>
[HttpGet]
[ProducesResponseType<BaseResponse<IEnumerable<Models.Response.ResponseDevice>>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<BaseResponse<Models.Response.ResponseDevice[]>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[MapToApiVersion("1")]
public async Task<IActionResult> ListDevices()
{
Expand All @@ -33,7 +33,7 @@ public async Task<IActionResult> ListDevices()
Id = x.Id,
Name = x.Name,
CreatedOn = x.CreatedOn
}).ToListAsync();
}).ToArrayAsync();

return RespondSuccessLegacy(devices);
}
Expand Down
5 changes: 3 additions & 2 deletions API/Controller/Devices/ShockersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ public sealed partial class DevicesController
/// <response code="200">All shockers for the device</response>
/// <response code="404">Device does not exists or you do not have access to it.</response>
[HttpGet("{deviceId}/shockers")]
[ProducesResponseType<BaseResponse<IEnumerable<ShockerResponse>>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<BaseResponse<ShockerResponse[]>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // DeviceNotFound
[MapToApiVersion("1")]
public async Task<IActionResult> GetShockers([FromRoute] Guid deviceId)
{
var deviceExists = await _db.Devices.AnyAsync(x => x.Owner == CurrentUser.Id && x.Id == deviceId);
if (!deviceExists) return Problem(DeviceError.DeviceNotFound);

var shockers = await _db.Shockers.Where(x => x.Device == deviceId).Select(x => new ShockerResponse
{
Id = x.Id,
Expand All @@ -34,7 +35,7 @@ public async Task<IActionResult> GetShockers([FromRoute] Guid deviceId)
CreatedOn = x.CreatedOn,
Model = x.Model,
IsPaused = x.Paused
}).ToListAsync();
}).ToArrayAsync();

return RespondSuccessLegacy(shockers);
}
Expand Down
4 changes: 2 additions & 2 deletions API/Controller/Shares/Links/ListShareLinks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ public sealed partial class ShareLinksController
/// </summary>
/// <response code="200">All share links for the current user</response>
[HttpGet]
[ProducesResponseType<BaseResponse<IEnumerable<ShareLinkResponse>>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<BaseResponse<ShareLinkResponse[]>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
public async Task<IActionResult> List()
{
var ownShareLinks = await _db.ShockerSharesLinks.Where(x => x.OwnerId == CurrentUser.Id)
.Select(x => ShareLinkResponse.GetFromEf(x)).ToListAsync();
.Select(x => ShareLinkResponse.GetFromEf(x)).ToArrayAsync();

return RespondSuccessLegacy(ownShareLinks);
}
Expand Down
10 changes: 5 additions & 5 deletions API/Controller/Shares/V2GetShares.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,20 @@ public sealed partial class SharesController
[HttpGet]
[ProducesResponseType<IEnumerable<GenericIni>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ApiVersion("2")]
public async Task<IEnumerable<GenericIni>> GetSharesByUsers()
public async Task<GenericIni[]> GetSharesByUsers()
{
var sharedToUsers = await _db.ShockerShares.Where(x => x.Shocker.DeviceNavigation.Owner == CurrentUser.Id)
.Select(x => new GenericIni
{
Id = x.SharedWithNavigation.Id,
Image = x.SharedWithNavigation.GetImageUrl(),
Name = x.SharedWithNavigation.Name
}).OrderBy(x => x.Name).Distinct().ToListAsync();
}).OrderBy(x => x.Name).Distinct().ToArrayAsync();
return sharedToUsers;
}

[HttpGet("{userId:guid}")]
[ProducesResponseType<ShareInfo>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<UserShareInfo[]>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // UserNotFound
[ApiVersion("2")]
public async Task<IActionResult> GetSharesToUser(Guid userId)
Expand All @@ -54,9 +54,9 @@ public async Task<IActionResult> GetSharesToUser(Guid userId)
Intensity = x.LimitIntensity
},
Paused = x.Paused
}).ToListAsync();
}).ToArrayAsync();

if(sharedWithUser.Count == 0)
if(sharedWithUser.Length == 0)
{
return Problem(ShareError.ShareGetNoShares);
}
Expand Down
12 changes: 6 additions & 6 deletions API/Controller/Shares/V2Requests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ namespace OpenShock.API.Controller.Shares;
public sealed partial class SharesController
{
[HttpGet("requests/outstanding")]
[ProducesResponseType<IEnumerable<ShareRequestBaseItem>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<ShareRequestBaseItem[]>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ApiVersion("2")]
public async Task<IEnumerable<ShareRequestBaseItem>> GetOutstandingRequestsList()
public async Task<ShareRequestBaseItem[]> GetOutstandingRequestsList()
{
var outstandingShares = await _db.ShareRequests.Where(x => x.Owner == CurrentUser.Id)
.Select(x => new ShareRequestBaseItem()
Expand All @@ -43,15 +43,15 @@ public async Task<IEnumerable<ShareRequestBaseItem>> GetOutstandingRequestsList(
{
Shockers = x.ShareRequestsShockers.Count
}
}).ToListAsync();
}).ToArrayAsync();

return outstandingShares;
}

[HttpGet("requests/incoming")]
[ProducesResponseType<IEnumerable<ShareRequestBaseItem>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<ShareRequestBaseItem[]>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ApiVersion("2")]
public async Task<IEnumerable<ShareRequestBaseItem>> GetIncomingRequestsList()
public async Task<ShareRequestBaseItem[]> GetIncomingRequestsList()
{
var outstandingShares = await _db.ShareRequests.Where(x => x.User == CurrentUser.Id)
.Select(x => new ShareRequestBaseItem
Expand All @@ -76,7 +76,7 @@ public async Task<IEnumerable<ShareRequestBaseItem>> GetIncomingRequestsList()
{
Shockers = x.ShareRequestsShockers.Count
}
}).ToListAsync();
}).ToArrayAsync();

return outstandingShares;
}
Expand Down
2 changes: 1 addition & 1 deletion API/Controller/Shockers/ControlLogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ [FromQuery] [Range(1, 500)] uint limit = 100)
Image = x.ControlledByNavigation.GetImageUrl(),
CustomName = x.CustomName
}
}).ToListAsync();
}).ToArrayAsync();

return RespondSuccessLegacy(logs);
}
Expand Down
2 changes: 1 addition & 1 deletion API/Controller/Shockers/OwnShockerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public async Task<IActionResult> ListShockers()
Model = y.Model,
IsPaused = y.Paused
})
}).ToListAsync();
}).ToArrayAsync();

return RespondSuccessLegacy(shockers);
}
Expand Down
4 changes: 2 additions & 2 deletions API/Controller/Shockers/ShareShockerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task<IActionResult> GetShockerShares([FromRoute] Guid shockerId)
Intensity = x.LimitIntensity
}
}
).ToListAsync();
).ToArrayAsync();

return RespondSuccessLegacy(shares);
}
Expand All @@ -82,7 +82,7 @@ public async Task<IActionResult> ShockerShareCodeList([FromRoute] Guid shockerId
CreatedOn = x.CreatedOn,
Id = x.Id
}
).ToListAsync();
).ToArrayAsync();

return RespondSuccessLegacy(shares);
}
Expand Down
2 changes: 1 addition & 1 deletion API/Controller/Shockers/SharedShockersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public async Task<IActionResult> ListSharedShockers()
Intensity = x.LimitIntensity
}
}
}).ToListAsync();
}).ToArrayAsync();

var shared = new Dictionary<Guid, OwnerShockerResponse>();
foreach (var shocker in sharedShockersRaw)
Expand Down
10 changes: 4 additions & 6 deletions API/Controller/Tokens/TokenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ public sealed partial class TokensController
/// <response code="200">All tokens for the current user</response>
[HttpGet]
[Authorize(Policy = OpenShockAuthPolicies.UserAccess)]
[ProducesResponseType<IEnumerable<TokenResponse>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
public async Task<IEnumerable<TokenResponse>> ListTokens()
[ProducesResponseType<TokenResponse[]>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
public async Task<TokenResponse[]> ListTokens()
{
var apiTokens = await _db.ApiTokens
return await _db.ApiTokens
.Where(x => x.UserId == CurrentUser.Id && (x.ValidUntil == null || x.ValidUntil > DateTime.UtcNow))
.OrderBy(x => x.CreatedOn)
.Select(x => new TokenResponse
Expand All @@ -40,9 +40,7 @@ public async Task<IEnumerable<TokenResponse>> ListTokens()
Permissions = x.Permissions,
Name = x.Name,
Id = x.Id
}).ToListAsync();

return apiTokens;
}).ToArrayAsync();
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@
Log.Information("Running database migrations...");
using var scope = app.Services.CreateScope();
var openShockContext = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var pendingMigrations = openShockContext.Database.GetPendingMigrations().ToList();
var pendingMigrations = openShockContext.Database.GetPendingMigrations().ToArray();

if (pendingMigrations.Count > 0)
if (pendingMigrations.Length > 0)
{
Log.Information("Found pending migrations, applying [{@Migrations}]", pendingMigrations);
openShockContext.Database.Migrate();
Expand Down
5 changes: 3 additions & 2 deletions Common/DeviceControl/ControlLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static async Task<OneOf<Success, ShockerNotFoundOrNoAccess, ShockerPaused
Duration = x.LimitDuration,
Intensity = x.LimitIntensity
}
}).ToListAsync();
}).ToArrayAsync();

ownShockers.AddRange(sharedShockers);

Expand Down Expand Up @@ -77,7 +77,8 @@ public static async Task<OneOf<Success, ShockerNotFoundOrNoAccess, ShockerPaused
Duration = x.LimitDuration,
Intensity = x.LimitIntensity
}
}).ToListAsync();
}).ToArrayAsync();

return await ControlInternal(shocks, db, sender, hubClients, shareLinkShockers, redisPubService);
}

Expand Down
2 changes: 1 addition & 1 deletion Common/Models/PermissionType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private static IEnumerable<PermissionTypeRecord> Init()
var parents = field.GetCustomAttributes<ParentPermissionAttribute>().Select(x => x.PermissionType);
var name = field.GetCustomAttribute<PgNameAttribute>()!.PgName;

yield return new PermissionTypeRecord(permissionType, name, parents.ToList());
yield return new PermissionTypeRecord(permissionType, name, parents.ToArray());
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Common/OpenShockServiceHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ public static class OpenShockServiceHelper
// TODO: this is temporary while we still rely on enums for user ranks
static bool HandleRankCheck(AuthorizationHandlerContext context, RankType requiredRank)
{
var ranks = context.User.Identities.SelectMany(ident => ident.Claims.Where(claim => claim.Type == ident.RoleClaimType)).Select(claim => Enum.Parse<RankType>(claim.Value)).ToList();
var ranks = context.User.Identities.SelectMany(ident => ident.Claims.Where(claim => claim.Type == ident.RoleClaimType)).Select(claim => Enum.Parse<RankType>(claim.Value)).ToArray();

// Has any rank that is higher than required rank
return ranks.Count != 0 && ranks.Max() >= requiredRank;
return ranks.Length != 0 && ranks.Max() >= requiredRank;
}

/// <summary>
Expand Down
12 changes: 6 additions & 6 deletions Common/Swagger/AttributeFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,21 @@ public void Apply(OpenApiOperation operation, OperationFilterContext context)
var attributes = context.MethodInfo?.DeclaringType?.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>()
.ToList() ?? [];
.ToArray() ?? [];

if (attributes.Count != 0)
if (attributes.Length != 0)
{
if (attributes.Count(attr => !string.IsNullOrEmpty(attr.AuthenticationSchemes)) > 1) throw new Exception("Dunno what to apply to this method (multiple authentication attributes with schemes set)");

var scheme = attributes.Select(attr => attr.AuthenticationSchemes).SingleOrDefault(scheme => !string.IsNullOrEmpty(scheme));
var roles = attributes.Select(attr => attr.Roles).Where(roles => !string.IsNullOrEmpty(roles)).SelectMany(roles => roles!.Split(',')).Select(role => role.Trim()).ToList();
var policies = attributes.Select(attr => attr.Policy).Where(policies => !string.IsNullOrEmpty(policies)).SelectMany(policies => policies!.Split(',')).Select(policy => policy.Trim()).ToList();
var roles = attributes.Select(attr => attr.Roles).Where(roles => !string.IsNullOrEmpty(roles)).SelectMany(roles => roles!.Split(',')).Select(role => role.Trim()).ToArray();
var policies = attributes.Select(attr => attr.Policy).Where(policies => !string.IsNullOrEmpty(policies)).SelectMany(policies => policies!.Split(',')).Select(policy => policy.Trim()).ToArray();

// Add what should be show inside the security section
List<string> securityInfos = [];
if (!string.IsNullOrEmpty(scheme)) securityInfos.Add($"{nameof(AuthorizeAttribute.AuthenticationSchemes)}:{scheme}");
if (roles.Count > 0) securityInfos.Add($"{nameof(AuthorizeAttribute.Roles)}:{string.Join(',', roles)}");
if (policies.Count > 0) securityInfos.Add($"{nameof(AuthorizeAttribute.Policy)}:{string.Join(',', policies)}");
if (roles.Length > 0) securityInfos.Add($"{nameof(AuthorizeAttribute.Roles)}:{string.Join(',', roles)}");
if (policies.Length > 0) securityInfos.Add($"{nameof(AuthorizeAttribute.Policy)}:{string.Join(',', policies)}");

List<OpenApiSecurityRequirement> securityRequirements = [];
foreach (var authenticationScheme in scheme?.Split(',').Select(s => s.Trim()) ?? [])
Expand Down
2 changes: 1 addition & 1 deletion Common/Swagger/SwaggerGenExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static IServiceCollection AddSwaggerExt<TProgram>(this IServiceCollection
.Select(v => v.ToString())
.ToHashSet()
.OrderBy(v => v)
.ToList();
.ToArray();

if (versions.Any(v => !int.TryParse(v, out _)))
{
Expand Down
Loading