freetubesync/FreeTubeSync/EndPoints/PlaylistEndpoint.cs
Mario Steele 73955353cb Possibly fix issues
After doing testing with a test project, re-organized code to new method
of storing, as well as ensure that all Endpoint lambda's are separated
out into functions.

Large commit, will be testing.
2025-08-08 16:59:29 -05:00

89 lines
No EOL
3.1 KiB
C#

using FreeTubeSync.Model;
namespace FreeTubeSync.EndPoints;
public static class PlaylistEndpoint
{
public static void MapPlaylistEndpoints(this WebApplication app)
{
var group = app.MapGroup("playlists");
group.MapGet("/", GetAllPlaylists);
group.MapGet("/{id}", GetPlaylist);
group.MapPost("/", UpdatePlaylist);
group.MapDelete("/{id}", RemovePlaylist);
}
private static async Task<IResult> GetAllPlaylists(IRepository<Playlist> repository, CancellationToken ct)
{
var results = await repository.GetAllAsync(ct);
return Results.Ok(results);
}
private static async Task<IResult> GetPlaylist(IRepository<Playlist> repository, string id, CancellationToken ct)
{
var result = await repository.GetByIdAsync(id, ct);
return result == null ? Results.NotFound() : Results.Ok(result);
}
private static async Task<IResult> UpdatePlaylist(IRepository<Playlist> repository, Playlist playlist, CancellationToken ct,
ILogger<Program> logger)
{
var results = await repository.GetByIdAsync(playlist._id, ct);
if (results == null)
{
try
{
await repository.AddAsync(playlist, ct);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create Playlist {playlist}", playlist._id);
return Results.StatusCode(500);
}
}
else
{
// Add Update Code here
var toRemove = results.videos.Where(vid => !playlist.videos.Any(x => x.playlistItemId == vid.playlistItemId)).ToList();
results.lastUpdatedAt = playlist.lastUpdatedAt;
results.@protected = playlist.@protected;
results.playlistName = playlist.playlistName;
results.createdAt = playlist.createdAt;
foreach (var vid in toRemove)
results.videos.Remove(vid);
foreach (var vid in playlist.videos)
{
var ovid = results.videos.FirstOrDefault(x => x.playlistItemId == vid.playlistItemId);
if (ovid == null)
results.videos.Add(vid);
else
{
ovid.videoId = vid.videoId;
ovid.title = vid.title;
ovid.author = vid.author;
ovid.authorId = vid.authorId;
ovid.lengthSeconds = vid.lengthSeconds;
ovid.published = vid.published;
ovid.timeAdded = vid.timeAdded;
ovid.playlistItemId = vid.playlistItemId;
ovid.type = vid.type;
}
}
await repository.UpdateAsync(results, ct);
}
return Results.Ok();
}
private static async Task<IResult> RemovePlaylist(IRepository<Playlist> repository, string id, CancellationToken ct)
{
var result = await repository.GetByIdAsync(id, ct);
if (result == null) return Results.NotFound();
await repository.DeleteAsync(result, ct);
return Results.Ok();
}
}