Change logging to just log a message, instead of the exception. Moved logic to Syncer involvement. When posting the data, if a 500 is returned, then it is up to the Syncer to re-submit it.
86 lines
No EOL
3.1 KiB
C#
86 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
|
|
{
|
|
logger.LogInformation("Playlist {id} does not exist, adding it to the database", playlist._id);
|
|
await repository.AddAsync(playlist, ct);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
logger.LogError("Failed to create Playlist {playlist}", playlist._id);
|
|
return Results.StatusCode(500);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
logger.LogInformation("Playlist {id} exists, updating the databsae.", playlist._id);
|
|
results.UpdateFrom(playlist);
|
|
var toRemove = results.videos.Where(vid => !playlist.videos.Any(x => x.playlistItemId == vid.playlistItemId)).ToList();
|
|
|
|
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();
|
|
}
|
|
} |