freetubesync/FreeTubeSync/EndPoints/ProfileEndpoint.cs
Mario Steele 8187a03419 Some updates to Endpoint Logic
Ensure that we are adding videos to the playlist database object when we insert them.
Updated logic to follow profiles for playlist.
Do not search for existing subs when inserting a new sub, the sub's belongs to id will be different.
Formatted linq statement to be multi-line, instead of single line, to make it easier to read.
Removed check for subscription if we are adding a new one, the profile id is going to be different.
Ensure we are deleting subs from the database when they are no longer associated with a profile.
2025-08-04 19:13:17 -05:00

90 lines
No EOL
3.2 KiB
C#

using FreeTubeSync.Database;
using FreeTubeSync.Model.Database;
using FreeTubeSync.Model.Json;
namespace FreeTubeSync.EndPoints;
public static class ProfileEndpoint
{
public static void MapProfileEndpoints(this WebApplication app)
{
var group = app.MapGroup("profile");
group.MapGet("/", async (IRepository<Profile> repository, CancellationToken ct) =>
{
var results = (await repository.GetAllAsync(ct)).ToList();
var jsonResults = new List<ProfileJson>();
results.MapTo(jsonResults);
for (var i = 0; i < jsonResults.Count; i++)
results[i].subscriptions.MapTo(jsonResults[i].subscriptions);
return Results.Ok(results);
});
group.MapPost("/", async (IRepository<Profile> repository, IRepository<Subscription> subRepo, CancellationToken ct, ProfileJson profileJson) =>
{
var res = await repository.GetByIdAsync(profileJson._id, ct);
if (res == null)
{
res = new Profile();
res.MapFrom(profileJson);
foreach (var subscription in profileJson.subscriptions)
{
var sub = new Subscription();
sub.MapFrom(subscription);
await subRepo.AddAsync(sub, ct, false);
res.subscriptions.Add(sub);
}
await repository.AddAsync(res, ct);
}
else
{
res.MapFrom(profileJson);
var notFound = new List<Subscription>();
foreach (var subscription in res.subscriptions)
{
var f = profileJson.subscriptions.FirstOrDefault(s => s.id == subscription.id);
if (f == null)
notFound.Add(subscription);
else
{
subscription.MapFrom(f);
await subRepo.UpdateAsync(subscription, ct, false);
}
}
var newSubs = (from subscription in profileJson.subscriptions
let f = res.subscriptions.FirstOrDefault(s => s.id == subscription.id)
where f == null
select subscription).ToList();
foreach (var newSub in newSubs)
{
var sres = new Subscription();
sres.MapFrom(newSub);
await subRepo.AddAsync(sres, ct, false);
res.subscriptions.Add(sres);
}
foreach (var nfSub in notFound)
{
await subRepo.DeleteAsync(nfSub, ct, false);
res.subscriptions.Remove(nfSub);
}
await repository.UpdateAsync(res, ct);
}
return Results.Ok();
});
group.MapDelete("/{id}", async (IRepository<Profile> repository, CancellationToken ct, string id) =>
{
var result = await repository.GetByIdAsync(id, ct);
if (result == null) return Results.NotFound();
await repository.DeleteAsync(result, ct);
return Results.Ok();
});
}
}