♻️ Centralized data models (wip)

This commit is contained in:
2025-09-27 14:09:28 +08:00
parent 51b6f7309e
commit e70d8371f8
206 changed files with 1352 additions and 2128 deletions

View File

@@ -1,169 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
using DysonNetwork.Shared.Data;
using DysonNetwork.Sphere.Post;
using Microsoft.EntityFrameworkCore;
using NodaTime;
using NodaTime.Serialization.Protobuf;
using VerificationMark = DysonNetwork.Shared.Data.VerificationMark;
using Account = DysonNetwork.Shared.Data.AccountReference;
namespace DysonNetwork.Sphere.Publisher;
public enum PublisherType
{
Individual,
Organizational
}
[Index(nameof(Name), IsUnique = true)]
public class Publisher : ModelBase, IIdentifiedResource
{
public Guid Id { get; set; } = Guid.NewGuid();
public PublisherType Type { get; set; }
[MaxLength(256)] public string Name { get; set; } = string.Empty;
[MaxLength(256)] public string Nick { get; set; } = string.Empty;
[MaxLength(4096)] public string? Bio { get; set; }
// Outdated fields, for backward compability
[MaxLength(32)] public string? PictureId { get; set; }
[MaxLength(32)] public string? BackgroundId { get; set; }
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Picture { get; set; }
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Background { get; set; }
[Column(TypeName = "jsonb")] public VerificationMark? Verification { get; set; }
[JsonIgnore] public ICollection<Post.Post> Posts { get; set; } = new List<Post.Post>();
[JsonIgnore] public ICollection<Poll.Poll> Polls { get; set; } = new List<Poll.Poll>();
[JsonIgnore] public ICollection<PostCollection> Collections { get; set; } = new List<PostCollection>();
[JsonIgnore] public ICollection<PublisherMember> Members { get; set; } = new List<PublisherMember>();
[JsonIgnore] public ICollection<PublisherFeature> Features { get; set; } = new List<PublisherFeature>();
[JsonIgnore]
public ICollection<PublisherSubscription> Subscriptions { get; set; } = new List<PublisherSubscription>();
public Guid? AccountId { get; set; }
public Guid? RealmId { get; set; }
[JsonIgnore] public Realm.Realm? Realm { get; set; }
[NotMapped] public Account? Account { get; set; }
public string ResourceIdentifier => $"publisher:{Id}";
public Shared.Proto.Publisher ToProto(AppDatabase db)
{
var p = new Shared.Proto.Publisher()
{
Id = Id.ToString(),
Type = Type == PublisherType.Individual
? Shared.Proto.PublisherType.PubIndividual
: Shared.Proto.PublisherType.PubOrganizational,
Name = Name,
Nick = Nick,
Bio = Bio,
AccountId = AccountId?.ToString() ?? string.Empty,
RealmId = RealmId?.ToString() ?? string.Empty,
CreatedAt = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(CreatedAt.ToDateTimeOffset()),
UpdatedAt = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(UpdatedAt.ToDateTimeOffset())
};
if (Picture is not null)
{
p.Picture = new Shared.Proto.CloudFile
{
Id = Picture.Id,
Name = Picture.Name,
MimeType = Picture.MimeType,
Hash = Picture.Hash,
Size = Picture.Size,
};
}
if (Background is not null)
{
p.Background = new Shared.Proto.CloudFile
{
Id = Background.Id,
Name = Background.Name,
MimeType = Background.MimeType,
Hash = Background.Hash,
Size = Background.Size,
};
}
return p;
}
}
public enum PublisherMemberRole
{
Owner = 100,
Manager = 75,
Editor = 50,
Viewer = 25
}
public class PublisherMember : ModelBase
{
public Guid PublisherId { get; set; }
[JsonIgnore] public Publisher Publisher { get; set; } = null!;
public Guid AccountId { get; set; }
[NotMapped] public Account? Account { get; set; }
public PublisherMemberRole Role { get; set; } = PublisherMemberRole.Viewer;
public Instant? JoinedAt { get; set; }
public Shared.Proto.PublisherMember ToProto()
{
return new Shared.Proto.PublisherMember()
{
PublisherId = PublisherId.ToString(),
AccountId = AccountId.ToString(),
Role = Role switch
{
PublisherMemberRole.Owner => Shared.Proto.PublisherMemberRole.Owner,
PublisherMemberRole.Manager => Shared.Proto.PublisherMemberRole.Manager,
PublisherMemberRole.Editor => Shared.Proto.PublisherMemberRole.Editor,
PublisherMemberRole.Viewer => Shared.Proto.PublisherMemberRole.Viewer,
_ => throw new ArgumentOutOfRangeException(nameof(Role), Role, null)
},
JoinedAt = JoinedAt?.ToTimestamp()
};
}
}
public enum PublisherSubscriptionStatus
{
Active,
Expired,
Cancelled
}
public class PublisherSubscription : ModelBase
{
public Guid Id { get; set; }
public Guid PublisherId { get; set; }
[JsonIgnore] public Publisher Publisher { get; set; } = null!;
public Guid AccountId { get; set; }
public PublisherSubscriptionStatus Status { get; set; } = PublisherSubscriptionStatus.Active;
public int Tier { get; set; } = 0;
}
public class PublisherFeature : ModelBase
{
public Guid Id { get; set; }
[MaxLength(1024)] public string Flag { get; set; } = null!;
public Instant? ExpiredAt { get; set; }
public Guid PublisherId { get; set; }
public Publisher Publisher { get; set; } = null!;
}
public abstract class PublisherFeatureFlag
{
public static List<string> AllFlags => [Develop];
public static string Develop = "develop";
}

View File

@@ -1,8 +1,7 @@
using System.ComponentModel.DataAnnotations;
using DysonNetwork.Shared.Auth;
using DysonNetwork.Shared.Data;
using DysonNetwork.Shared.Models;
using DysonNetwork.Shared.Proto;
using DysonNetwork.Sphere.Realm;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@@ -23,7 +22,7 @@ public class PublisherController(
: ControllerBase
{
[HttpGet("{name}")]
public async Task<ActionResult<Publisher>> GetPublisher(string name)
public async Task<ActionResult<SnPublisher>> GetPublisher(string name)
{
var publisher = await db.Publishers
.Where(e => e.Name == name)
@@ -34,7 +33,7 @@ public class PublisherController(
var account = await accounts.GetAccountAsync(
new GetAccountRequest { Id = publisher.AccountId.Value.ToString() }
);
publisher.Account = AccountReference.FromProtoValue(account);
publisher.Account = SnAccount.FromProtoValue(account);
return Ok(publisher);
}
@@ -48,7 +47,7 @@ public class PublisherController(
}
[HttpGet("of/{accountId:guid}")]
public async Task<ActionResult<List<Publisher>>> GetAccountManagedPublishers(Guid accountId)
public async Task<ActionResult<List<SnPublisher>>> GetAccountManagedPublishers(Guid accountId)
{
var members = await db.PublisherMembers
.Where(m => m.AccountId == accountId)
@@ -61,7 +60,7 @@ public class PublisherController(
[HttpGet]
[Authorize]
public async Task<ActionResult<List<Publisher>>> ListManagedPublishers()
public async Task<ActionResult<List<SnPublisher>>> ListManagedPublishers()
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);
@@ -77,7 +76,7 @@ public class PublisherController(
[HttpGet("invites")]
[Authorize]
public async Task<ActionResult<List<PublisherMember>>> ListInvites()
public async Task<ActionResult<List<SnPublisherMember>>> ListInvites()
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);
@@ -99,7 +98,7 @@ public class PublisherController(
[HttpPost("invites/{name}")]
[Authorize]
public async Task<ActionResult<PublisherMember>> InviteMember(string name,
public async Task<ActionResult<SnPublisherMember>> InviteMember(string name,
[FromBody] PublisherMemberRequest request)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
@@ -117,7 +116,7 @@ public class PublisherController(
if (!await ps.IsMemberWithRole(publisher.Id, accountId, request.Role))
return StatusCode(403, "You cannot invite member has higher permission than yours.");
var newMember = new PublisherMember
var newMember = new SnPublisherMember
{
AccountId = Guid.Parse(relatedUser.Id),
PublisherId = publisher.Id,
@@ -145,7 +144,7 @@ public class PublisherController(
[HttpPost("invites/{name}/accept")]
[Authorize]
public async Task<ActionResult<Publisher>> AcceptMemberInvite(string name)
public async Task<ActionResult<SnPublisher>> AcceptMemberInvite(string name)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);
@@ -270,7 +269,7 @@ public class PublisherController(
[HttpPost("individual")]
[Authorize]
[RequiredPermission("global", "publishers.create")]
public async Task<ActionResult<Publisher>> CreatePublisherIndividual([FromBody] PublisherRequest request)
public async Task<ActionResult<SnPublisher>> CreatePublisherIndividual([FromBody] PublisherRequest request)
{
if (string.IsNullOrEmpty(request.Name) || string.IsNullOrEmpty(request.Nick))
return BadRequest("Name and Nick are required.");
@@ -288,7 +287,7 @@ public class PublisherController(
"your name firstly to get your name back."
);
CloudFileReferenceObject? picture = null, background = null;
SnCloudFileReferenceObject? picture = null, background = null;
if (request.PictureId is not null)
{
var queryResult = await files.GetFileAsync(
@@ -296,7 +295,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
picture = CloudFileReferenceObject.FromProtoValue(queryResult);
picture = SnCloudFileReferenceObject.FromProtoValue(queryResult);
}
if (request.BackgroundId is not null)
@@ -306,7 +305,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid background id, unable to find the file on cloud.");
background = CloudFileReferenceObject.FromProtoValue(queryResult);
background = SnCloudFileReferenceObject.FromProtoValue(queryResult);
}
var publisher = await ps.CreateIndividualPublisher(
@@ -338,7 +337,7 @@ public class PublisherController(
[HttpPost("organization/{realmSlug}")]
[Authorize]
[RequiredPermission("global", "publishers.create")]
public async Task<ActionResult<Publisher>> CreatePublisherOrganization(string realmSlug,
public async Task<ActionResult<SnPublisher>> CreatePublisherOrganization(string realmSlug,
[FromBody] PublisherRequest request)
{
if (string.IsNullOrEmpty(request.Name) || string.IsNullOrEmpty(request.Nick))
@@ -362,7 +361,7 @@ public class PublisherController(
if (duplicateNameCount > 0)
return BadRequest("The name you requested has already been taken");
CloudFileReferenceObject? picture = null, background = null;
SnCloudFileReferenceObject? picture = null, background = null;
if (request.PictureId is not null)
{
var queryResult = await files.GetFileAsync(
@@ -370,7 +369,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
picture = CloudFileReferenceObject.FromProtoValue(queryResult);
picture = SnCloudFileReferenceObject.FromProtoValue(queryResult);
}
if (request.BackgroundId is not null)
@@ -380,7 +379,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid background id, unable to find the file on cloud.");
background = CloudFileReferenceObject.FromProtoValue(queryResult);
background = SnCloudFileReferenceObject.FromProtoValue(queryResult);
}
var publisher = await ps.CreateOrganizationPublisher(
@@ -414,7 +413,7 @@ public class PublisherController(
[HttpPatch("{name}")]
[Authorize]
public async Task<ActionResult<Publisher>> UpdatePublisher(string name, PublisherRequest request)
public async Task<ActionResult<SnPublisher>> UpdatePublisher(string name, PublisherRequest request)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);
@@ -442,7 +441,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid picture id, unable to find the file on cloud.");
var picture = CloudFileReferenceObject.FromProtoValue(queryResult);
var picture = SnCloudFileReferenceObject.FromProtoValue(queryResult);
// Remove old references for the publisher picture
if (publisher.Picture is not null)
@@ -470,7 +469,7 @@ public class PublisherController(
);
if (queryResult is null)
throw new InvalidOperationException("Invalid background id, unable to find the file on cloud.");
var background = CloudFileReferenceObject.FromProtoValue(queryResult);
var background = SnCloudFileReferenceObject.FromProtoValue(queryResult);
// Remove old references for the publisher background
if (publisher.Background is not null)
@@ -518,7 +517,7 @@ public class PublisherController(
[HttpDelete("{name}")]
[Authorize]
public async Task<ActionResult<Publisher>> DeletePublisher(string name)
public async Task<ActionResult<SnPublisher>> DeletePublisher(string name)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);
@@ -564,7 +563,7 @@ public class PublisherController(
}
[HttpGet("{name}/members")]
public async Task<ActionResult<List<PublisherMember>>> ListMembers(
public async Task<ActionResult<List<SnPublisherMember>>> ListMembers(
string name,
[FromQuery] int offset = 0,
[FromQuery] int take = 20
@@ -594,7 +593,7 @@ public class PublisherController(
[HttpGet("{name}/members/me")]
[Authorize]
public async Task<ActionResult<PublisherMember>> GetCurrentIdentity(string name)
public async Task<ActionResult<SnPublisherMember>> GetCurrentIdentity(string name)
{
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
var accountId = Guid.Parse(currentUser.Id);

View File

@@ -1,8 +1,7 @@
using DysonNetwork.Shared.Cache;
using DysonNetwork.Shared.Data;
using DysonNetwork.Shared.Models;
using DysonNetwork.Shared.Proto;
using DysonNetwork.Shared.Registry;
using DysonNetwork.Sphere.Post;
using Microsoft.EntityFrameworkCore;
using NodaTime;
@@ -15,7 +14,7 @@ public class PublisherService(
AccountClientHelper accountsHelper
)
{
public async Task<Publisher?> GetPublisherByName(string name)
public async Task<SnPublisher?> GetPublisherByName(string name)
{
return await db.Publishers
.Where(e => e.Name == name)
@@ -24,12 +23,12 @@ public class PublisherService(
private const string UserPublishersCacheKey = "accounts:{0}:publishers";
public async Task<List<Publisher>> GetUserPublishers(Guid userId)
public async Task<List<SnPublisher>> GetUserPublishers(Guid userId)
{
var cacheKey = string.Format(UserPublishersCacheKey, userId);
// Try to get publishers from the cache first
var publishers = await cache.GetAsync<List<Publisher>>(cacheKey);
var publishers = await cache.GetAsync<List<SnPublisher>>(cacheKey);
if (publishers is not null)
return publishers;
@@ -48,16 +47,16 @@ public class PublisherService(
return publishers;
}
public async Task<Dictionary<Guid, List<Publisher>>> GetUserPublishersBatch(List<Guid> userIds)
public async Task<Dictionary<Guid, List<SnPublisher>>> GetUserPublishersBatch(List<Guid> userIds)
{
var result = new Dictionary<Guid, List<Publisher>>();
var result = new Dictionary<Guid, List<SnPublisher>>();
var missingIds = new List<Guid>();
// Try to get publishers from cache for each user
foreach (var userId in userIds)
{
var cacheKey = string.Format(UserPublishersCacheKey, userId);
var publishers = await cache.GetAsync<List<Publisher>>(cacheKey);
var publishers = await cache.GetAsync<List<SnPublisher>>(cacheKey);
if (publishers != null)
result[userId] = publishers;
else
@@ -103,12 +102,12 @@ public class PublisherService(
public const string SubscribedPublishersCacheKey = "accounts:{0}:subscribed-publishers";
public async Task<List<Publisher>> GetSubscribedPublishers(Guid userId)
public async Task<List<SnPublisher>> GetSubscribedPublishers(Guid userId)
{
var cacheKey = string.Format(SubscribedPublishersCacheKey, userId);
// Try to get publishers from the cache first
var publishers = await cache.GetAsync<List<Publisher>>(cacheKey);
var publishers = await cache.GetAsync<List<SnPublisher>>(cacheKey);
if (publishers is not null)
return publishers;
@@ -130,12 +129,12 @@ public class PublisherService(
private const string PublisherMembersCacheKey = "publishers:{0}:members";
public async Task<List<PublisherMember>> GetPublisherMembers(Guid publisherId)
public async Task<List<SnPublisherMember>> GetPublisherMembers(Guid publisherId)
{
var cacheKey = string.Format(PublisherMembersCacheKey, publisherId);
// Try to get members from the cache first
var members = await cache.GetAsync<List<PublisherMember>>(cacheKey);
var members = await cache.GetAsync<List<SnPublisherMember>>(cacheKey);
if (members is not null)
return members;
@@ -150,16 +149,16 @@ public class PublisherService(
return members;
}
public async Task<Publisher> CreateIndividualPublisher(
public async Task<SnPublisher> CreateIndividualPublisher(
Account account,
string? name,
string? nick,
string? bio,
CloudFileReferenceObject? picture,
CloudFileReferenceObject? background
SnCloudFileReferenceObject? picture,
SnCloudFileReferenceObject? background
)
{
var publisher = new Publisher
var publisher = new SnPublisher
{
Type = PublisherType.Individual,
Name = name ?? account.Name,
@@ -167,12 +166,12 @@ public class PublisherService(
Bio = bio ?? account.Profile.Bio,
Picture = picture ?? (account.Profile.Picture is null
? null
: CloudFileReferenceObject.FromProtoValue(account.Profile.Picture)),
: SnCloudFileReferenceObject.FromProtoValue(account.Profile.Picture)),
Background = background ?? (account.Profile.Background is null
? null
: CloudFileReferenceObject.FromProtoValue(account.Profile.Background)),
: SnCloudFileReferenceObject.FromProtoValue(account.Profile.Background)),
AccountId = Guid.Parse(account.Id),
Members = new List<PublisherMember>
Members = new List<SnPublisherMember>
{
new()
{
@@ -213,26 +212,26 @@ public class PublisherService(
return publisher;
}
public async Task<Publisher> CreateOrganizationPublisher(
Realm.Realm realm,
public async Task<SnPublisher> CreateOrganizationPublisher(
Shared.Models.SnRealm realm,
Account account,
string? name,
string? nick,
string? bio,
CloudFileReferenceObject? picture,
CloudFileReferenceObject? background
SnCloudFileReferenceObject? picture,
SnCloudFileReferenceObject? background
)
{
var publisher = new Publisher
var publisher = new SnPublisher
{
Type = PublisherType.Organizational,
Name = name ?? realm.Slug,
Nick = nick ?? realm.Name,
Bio = bio ?? realm.Description,
Picture = picture ?? CloudFileReferenceObject.FromProtoValue(account.Profile.Picture),
Background = background ?? CloudFileReferenceObject.FromProtoValue(account.Profile.Background),
Picture = picture ?? SnCloudFileReferenceObject.FromProtoValue(account.Profile.Picture),
Background = background ?? SnCloudFileReferenceObject.FromProtoValue(account.Profile.Background),
RealmId = realm.Id,
Members = new List<PublisherMember>
Members = new List<SnPublisherMember>
{
new()
{
@@ -379,14 +378,14 @@ public class PublisherService(
return member != null && member.Role >= requiredRole;
}
public async Task<PublisherMember> LoadMemberAccount(PublisherMember member)
public async Task<SnPublisherMember> LoadMemberAccount(SnPublisherMember member)
{
var account = await accountsHelper.GetAccount(member.AccountId);
member.Account = AccountReference.FromProtoValue(account);
member.Account = SnAccount.FromProtoValue(account);
return member;
}
public async Task<List<PublisherMember>> LoadMemberAccounts(ICollection<PublisherMember> members)
public async Task<List<SnPublisherMember>> LoadMemberAccounts(ICollection<SnPublisherMember> members)
{
var accountIds = members.Select(m => m.AccountId).ToList();
var accounts = (await accountsHelper.GetAccountBatch(accountIds)).ToDictionary(a => Guid.Parse(a.Id), a => a);
@@ -394,7 +393,7 @@ public class PublisherService(
return members.Select(m =>
{
if (accounts.TryGetValue(m.AccountId, out var account))
m.Account = AccountReference.FromProtoValue(account);
m.Account = SnAccount.FromProtoValue(account);
return m;
}).ToList();
}

View File

@@ -1,3 +1,4 @@
using DysonNetwork.Shared.Models;
using DysonNetwork.Shared.Proto;
using Grpc.Core;
using Microsoft.EntityFrameworkCore;
@@ -12,7 +13,7 @@ public class PublisherServiceGrpc(PublisherService service, AppDatabase db)
ServerCallContext context
)
{
Publisher? p = null;
SnPublisher? p = null;
switch (request.QueryCase)
{
case GetPublisherRequest.QueryOneofCase.Id:

View File

@@ -1,3 +1,4 @@
using DysonNetwork.Shared.Models;
using DysonNetwork.Shared.Proto;
using DysonNetwork.Sphere.Post;
using Microsoft.AspNetCore.Authorization;

View File

@@ -1,5 +1,6 @@
using DysonNetwork.Shared;
using DysonNetwork.Shared.Cache;
using DysonNetwork.Shared.Models;
using DysonNetwork.Shared.Proto;
using DysonNetwork.Sphere.Localization;
using DysonNetwork.Sphere.Post;
@@ -49,7 +50,7 @@ public class PublisherSubscriptionService(
/// </summary>
/// <param name="post">The new post</param>
/// <returns>The number of subscribers notified</returns>
public async Task<int> NotifySubscriberPost(Post.Post post)
public async Task<int> NotifySubscriberPost(SnPost post)
{
if (post.RepliedPostId is not null)
return 0;
@@ -74,7 +75,7 @@ public class PublisherSubscriptionService(
if (subscribers.Count == 0)
return 0;
List<PostCategorySubscription> categorySubscribers = [];
List<SnPostCategorySubscription> categorySubscribers = [];
if (post.Categories.Count > 0)
{
var categoryIds = post.Categories.Select(x => x.Id).ToList();