[sln] Apply code style

This commit is contained in:
Laura Hausmann 2024-11-19 21:02:37 +01:00
parent b8452ccb75
commit 7dec2514da
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
141 changed files with 800 additions and 794 deletions

View file

@ -35,14 +35,14 @@ public class AsyncComponentBase : ComponentBase
{
OnParametersSet();
await OnParametersSetAsync();
await RunMethodHandler();
await RunMethodHandlerAsync();
StateHasChanged();
}
protected virtual Task OnPost() => Task.CompletedTask;
protected virtual Task OnGet() => Task.CompletedTask;
private async Task RunMethodHandler()
private async Task RunMethodHandlerAsync()
{
if (string.Equals(Context.Request.Method, "GET", StringComparison.InvariantCultureIgnoreCase))
await OnGet();

View file

@ -12,7 +12,7 @@ public class MfmRenderer(IOptions<Config.InstanceSection> config) : ISingletonSe
{
private readonly MfmConverter _converter = new(config);
public async Task<MarkupString?> Render(
public async Task<MarkupString?> RenderAsync(
string? text, string? host, List<Note.MentionedUser> mentions, List<Emoji> emoji, string rootElement
)
{

View file

@ -22,15 +22,15 @@ public class NoteRenderer(
var allNotes = ((Note?[]) [note, note.Reply, note.Renote]).NotNull().ToList();
var mentions = await GetMentions(allNotes);
var emoji = await GetEmoji(allNotes);
var users = await GetUsers(allNotes);
var attachments = await GetAttachments(allNotes);
var mentions = await GetMentionsAsync(allNotes);
var emoji = await GetEmojiAsync(allNotes);
var users = await GetUsersAsync(allNotes);
var attachments = await GetAttachmentsAsync(allNotes);
return await Render(note, users, mentions, emoji, attachments);
return await RenderAsync(note, users, mentions, emoji, attachments);
}
private async Task<PreviewNote> Render(
private async Task<PreviewNote> RenderAsync(
Note note, List<PreviewUser> users, Dictionary<string, List<Note.MentionedUser>> mentions,
Dictionary<string, List<Emoji>> emoji, Dictionary<string, List<PreviewAttachment>?> attachments
)
@ -38,7 +38,7 @@ public class NoteRenderer(
var res = new PreviewNote
{
User = users.First(p => p.Id == note.User.Id),
Text = await mfm.Render(note.Text, note.User.Host, mentions[note.Id], emoji[note.Id], "span"),
Text = await mfm.RenderAsync(note.Text, note.User.Host, mentions[note.Id], emoji[note.Id], "span"),
Cw = note.Cw,
RawText = note.Text,
QuoteUrl = note.Renote?.Url ?? note.Renote?.Uri ?? note.Renote?.GetPublicUriOrNull(instance.Value),
@ -51,7 +51,7 @@ public class NoteRenderer(
return res;
}
private async Task<Dictionary<string, List<Note.MentionedUser>>> GetMentions(List<Note> notes)
private async Task<Dictionary<string, List<Note.MentionedUser>>> GetMentionsAsync(List<Note> notes)
{
var mentions = notes.SelectMany(n => n.Mentions).Distinct().ToList();
if (mentions.Count == 0) return notes.ToDictionary<Note, string, List<Note.MentionedUser>>(p => p.Id, _ => []);
@ -69,7 +69,7 @@ public class NoteRenderer(
p => users.Where(u => p.Mentions.Contains(u.Key)).Select(u => u.Value).ToList());
}
private async Task<Dictionary<string, List<Emoji>>> GetEmoji(List<Note> notes)
private async Task<Dictionary<string, List<Emoji>>> GetEmojiAsync(List<Note> notes)
{
var ids = notes.SelectMany(n => n.Emojis).Distinct().ToList();
if (ids.Count == 0) return notes.ToDictionary<Note, string, List<Emoji>>(p => p.Id, _ => []);
@ -78,13 +78,13 @@ public class NoteRenderer(
return notes.ToDictionary(p => p.Id, p => emoji.Where(e => p.Emojis.Contains(e.Id)).ToList());
}
private async Task<List<PreviewUser>> GetUsers(List<Note> notes)
private async Task<List<PreviewUser>> GetUsersAsync(List<Note> notes)
{
if (notes is []) return [];
return await userRenderer.RenderMany(notes.Select(p => p.User).Distinct().ToList());
return await userRenderer.RenderManyAsync(notes.Select(p => p.User).Distinct().ToList());
}
private async Task<Dictionary<string, List<PreviewAttachment>?>> GetAttachments(List<Note> notes)
private async Task<Dictionary<string, List<PreviewAttachment>?>> GetAttachmentsAsync(List<Note> notes)
{
if (security.Value.PublicPreview is Enums.PublicPreview.RestrictedNoMedia)
return notes.ToDictionary<Note, string, List<PreviewAttachment>?>(p => p.Id,
@ -106,14 +106,14 @@ public class NoteRenderer(
.ToList());
}
public async Task<List<PreviewNote>> RenderMany(List<Note> notes)
public async Task<List<PreviewNote>> RenderManyAsync(List<Note> notes)
{
if (notes is []) return [];
var allNotes = notes.SelectMany<Note, Note?>(p => [p, p.Renote, p.Reply]).NotNull().Distinct().ToList();
var users = await GetUsers(allNotes);
var mentions = await GetMentions(allNotes);
var emoji = await GetEmoji(allNotes);
var attachments = await GetAttachments(allNotes);
return await notes.Select(p => Render(p, users, mentions, emoji, attachments)).AwaitAllAsync().ToListAsync();
var users = await GetUsersAsync(allNotes);
var mentions = await GetMentionsAsync(allNotes);
var emoji = await GetEmojiAsync(allNotes);
var attachments = await GetAttachmentsAsync(allNotes);
return await notes.Select(p => RenderAsync(p, users, mentions, emoji, attachments)).AwaitAllAsync().ToListAsync();
}
}

View file

@ -18,11 +18,11 @@ public class UserRenderer(
public async Task<PreviewUser?> RenderOne(User? user)
{
if (user == null) return null;
var emoji = await GetEmoji([user]);
return await Render(user, emoji);
var emoji = await GetEmojiAsync([user]);
return await RenderAsync(user, emoji);
}
private async Task<PreviewUser> Render(User user, Dictionary<string, List<Emoji>> emoji)
private async Task<PreviewUser> RenderAsync(User user, Dictionary<string, List<Emoji>> emoji)
{
var mentions = user.UserProfile?.Mentions ?? [];
@ -36,8 +36,8 @@ public class UserRenderer(
AvatarUrl = user.AvatarUrl ?? user.IdenticonUrlPath,
BannerUrl = user.BannerUrl,
RawDisplayName = user.DisplayName,
DisplayName = await mfm.Render(user.DisplayName, user.Host, mentions, emoji[user.Id], "span"),
Bio = await mfm.Render(user.UserProfile?.Description, user.Host, mentions, emoji[user.Id], "span"),
DisplayName = await mfm.RenderAsync(user.DisplayName, user.Host, mentions, emoji[user.Id], "span"),
Bio = await mfm.RenderAsync(user.UserProfile?.Description, user.Host, mentions, emoji[user.Id], "span"),
MovedToUri = user.MovedToUri
};
// @formatter:on
@ -51,7 +51,7 @@ public class UserRenderer(
return res;
}
private async Task<Dictionary<string, List<Emoji>>> GetEmoji(List<User> users)
private async Task<Dictionary<string, List<Emoji>>> GetEmojiAsync(List<User> users)
{
var ids = users.SelectMany(n => n.Emojis).Distinct().ToList();
if (ids.Count == 0) return users.ToDictionary<User, string, List<Emoji>>(p => p.Id, _ => []);
@ -60,9 +60,9 @@ public class UserRenderer(
return users.ToDictionary(p => p.Id, p => emoji.Where(e => p.Emojis.Contains(e.Id)).ToList());
}
public async Task<List<PreviewUser>> RenderMany(List<User> users)
public async Task<List<PreviewUser>> RenderManyAsync(List<User> users)
{
var emoji = await GetEmoji(users);
return await users.Select(p => Render(p, emoji)).AwaitAllAsync().ToListAsync();
var emoji = await GetEmojiAsync(users);
return await users.Select(p => RenderAsync(p, emoji)).AwaitAllAsync().ToListAsync();
}
}

View file

@ -104,7 +104,7 @@ public class AccountController(
IsSensitive = false,
MimeType = request.Avatar.ContentType
};
var avatar = await driveSvc.StoreFile(request.Avatar.OpenReadStream(), user, rq);
var avatar = await driveSvc.StoreFileAsync(request.Avatar.OpenReadStream(), user, rq);
user.Avatar = avatar;
user.AvatarBlurhash = avatar.Blurhash;
user.AvatarUrl = avatar.AccessUrl;
@ -118,7 +118,7 @@ public class AccountController(
IsSensitive = false,
MimeType = request.Banner.ContentType
};
var banner = await driveSvc.StoreFile(request.Banner.OpenReadStream(), user, rq);
var banner = await driveSvc.StoreFileAsync(request.Banner.OpenReadStream(), user, rq);
user.Banner = banner;
user.BannerBlurhash = banner.Blurhash;
user.BannerUrl = banner.AccessUrl;
@ -144,7 +144,7 @@ public class AccountController(
db.Update(user);
await db.SaveChangesAsync();
await driveSvc.RemoveFile(id);
await driveSvc.RemoveFileAsync(id);
}
return await VerifyUserCredentials();
@ -166,7 +166,7 @@ public class AccountController(
db.Update(user);
await db.SaveChangesAsync();
await driveSvc.RemoveFile(id);
await driveSvc.RemoveFileAsync(id);
}
return await VerifyUserCredentials();
@ -187,7 +187,7 @@ public class AccountController(
if (config.Value.PublicPreview <= Enums.PublicPreview.Restricted && user.IsRemoteUser && localUser == null)
throw GracefulException.Forbidden("Public preview is disabled on this instance");
return await userRenderer.RenderAsync(await userResolver.GetUpdatedUser(user), localUser);
return await userRenderer.RenderAsync(await userResolver.GetUpdatedUserAsync(user), localUser);
}
[HttpPost("{id}/follow")]
@ -631,7 +631,7 @@ public class AccountController(
var localUser = HttpContext.GetUser();
var user = await userResolver.ResolveOrNullAsync(acct, flags) ?? throw GracefulException.RecordNotFound();
user = await userResolver.GetUpdatedUser(user);
user = await userResolver.GetUpdatedUserAsync(user);
return await userRenderer.RenderAsync(user, localUser);
}

View file

@ -32,7 +32,7 @@ public class AuthController(DatabaseContext db, MetaService meta) : ControllerBa
return new VerifyAppCredentialsResponse
{
App = token.App, VapidKey = await meta.Get(MetaEntity.VapidPublicKey)
App = token.App, VapidKey = await meta.GetAsync(MetaEntity.VapidPublicKey)
};
}
@ -77,7 +77,7 @@ public class AuthController(DatabaseContext db, MetaService meta) : ControllerBa
await db.AddAsync(app);
await db.SaveChangesAsync();
return new RegisterAppResponse { App = app, VapidKey = await meta.Get(MetaEntity.VapidPublicKey) };
return new RegisterAppResponse { App = app, VapidKey = await meta.GetAsync(MetaEntity.VapidPublicKey) };
}
[HttpPost("/oauth/token")]

View file

@ -33,10 +33,10 @@ public class InstanceController(DatabaseContext db, MetaService meta) : Controll
var instanceCount = await db.Instances.LongCountAsync();
var (instanceName, instanceDescription, adminContact) =
await meta.GetMany(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
await meta.GetManyAsync(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
// can't merge with above call since they're all nullable and this is not.
var vapidKey = await meta.Get(MetaEntity.VapidPublicKey);
var vapidKey = await meta.GetAsync(MetaEntity.VapidPublicKey);
return new InstanceInfoV1Response(config.Value, instanceName, instanceDescription, adminContact)
{
@ -55,7 +55,7 @@ public class InstanceController(DatabaseContext db, MetaService meta) : Controll
p.LastActiveDate > cutoff);
var (instanceName, instanceDescription, adminContact) =
await meta.GetMany(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
await meta.GetManyAsync(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
return new InstanceInfoV2Response(config.Value, instanceName, instanceDescription, adminContact)
{
@ -88,7 +88,7 @@ public class InstanceController(DatabaseContext db, MetaService meta) : Controll
[ProducesResults(HttpStatusCode.OK)]
public async Task<InstanceExtendedDescription> GetExtendedDescription()
{
var description = await meta.Get(MetaEntity.InstanceDescription);
var description = await meta.GetAsync(MetaEntity.InstanceDescription);
return new InstanceExtendedDescription(description);
}
}

View file

@ -39,7 +39,7 @@ public class MediaController(DriveService driveSvc, DatabaseContext db) : Contro
Comment = request.Description,
MimeType = request.File.ContentType
};
var file = await driveSvc.StoreFile(request.File.OpenReadStream(), user, rq);
var file = await driveSvc.StoreFileAsync(request.File.OpenReadStream(), user, rq);
return RenderAttachment(file);
}

View file

@ -115,7 +115,7 @@ public class PollController(
await db.SaveChangesAsync();
foreach (var vote in votes)
await pollSvc.RegisterPollVote(vote, poll, note, votes.IndexOf(vote) == 0);
await pollSvc.RegisterPollVoteAsync(vote, poll, note, votes.IndexOf(vote) == 0);
await db.ReloadEntityAsync(poll);
return await pollRenderer.RenderAsync(poll, user);

View file

@ -150,7 +150,7 @@ public class PushController(DatabaseContext db, MetaService meta) : ControllerBa
{
Id = sub.Id,
Endpoint = sub.Endpoint,
ServerKey = await meta.Get(MetaEntity.VapidPublicKey),
ServerKey = await meta.GetAsync(MetaEntity.VapidPublicKey),
Policy = GetPolicyString(sub.Policy),
Alerts = new Alerts
{

View file

@ -71,18 +71,18 @@ public class NoteRenderer(
var renoted = data?.Renotes?.Contains(note.Id) ??
await db.Notes.AnyAsync(p => p.Renote == note && p.User == user && p.IsPureRenote);
var noteEmoji = data?.Emoji?.Where(p => note.Emojis.Contains(p.Id)).ToList() ?? await GetEmoji([note]);
var noteEmoji = data?.Emoji?.Where(p => note.Emojis.Contains(p.Id)).ToList() ?? await GetEmojiAsync([note]);
var mentions = data?.Mentions == null
? await GetMentions([note])
? await GetMentionsAsync([note])
: [..data.Mentions.Where(p => note.Mentions.Contains(p.Id))];
var attachments = data?.Attachments == null
? await GetAttachments([note])
? await GetAttachmentsAsync([note])
: [..data.Attachments.Where(p => note.FileIds.Contains(p.Id))];
var reactions = data?.Reactions == null
? await GetReactions([note], user)
? await GetReactionsAsync([note], user)
: [..data.Reactions.Where(p => p.NoteId == note.Id)];
var mentionedUsers = mentions.Select(p => new Note.MentionedUser
@ -110,10 +110,10 @@ public class NoteRenderer(
await userRenderer.RenderAsync(note.User, user);
var poll = note.HasPoll
? (data?.Polls ?? await GetPolls([note], user)).FirstOrDefault(p => p.Id == note.Id)
? (data?.Polls ?? await GetPollsAsync([note], user)).FirstOrDefault(p => p.Id == note.Id)
: null;
var filters = data?.Filters ?? await GetFilters(user, filterContext);
var filters = data?.Filters ?? await GetFiltersAsync(user, filterContext);
List<FilterResultEntity> filterResult;
if (filters.Count > 0 && filterContext == null)
@ -178,8 +178,8 @@ public class NoteRenderer(
var edits = await db.NoteEdits.Where(p => p.Note == note).OrderBy(p => p.Id).ToListAsync();
edits.Add(RenderEdit(note));
var attachments = await GetAttachments(note.FileIds.Concat(edits.SelectMany(p => p.FileIds)));
var mentions = await GetMentions([note]);
var attachments = await GetAttachmentsAsync(note.FileIds.Concat(edits.SelectMany(p => p.FileIds)));
var mentions = await GetMentionsAsync([note]);
var mentionedUsers = mentions.Select(p => new Note.MentionedUser
{
Host = p.Host ?? config.Value.AccountDomain,
@ -240,7 +240,7 @@ public class NoteRenderer(
return res;
}
private async Task<List<MentionEntity>> GetMentions(List<Note> notes)
private async Task<List<MentionEntity>> GetMentionsAsync(List<Note> notes)
{
if (notes.Count == 0) return [];
var ids = notes.SelectMany(n => n.Mentions).Distinct();
@ -250,7 +250,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<AttachmentEntity>> GetAttachments(List<Note> notes)
private async Task<List<AttachmentEntity>> GetAttachmentsAsync(List<Note> notes)
{
if (notes.Count == 0) return [];
var ids = notes.SelectMany(n => n.FileIds).Distinct();
@ -270,7 +270,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<AttachmentEntity>> GetAttachments(IEnumerable<string> fileIds)
private async Task<List<AttachmentEntity>> GetAttachmentsAsync(IEnumerable<string> fileIds)
{
var ids = fileIds.Distinct().ToList();
if (ids.Count == 0) return [];
@ -290,13 +290,13 @@ public class NoteRenderer(
.ToListAsync();
}
internal async Task<List<AccountEntity>> GetAccounts(List<User> users, User? localUser)
internal async Task<List<AccountEntity>> GetAccountsAsync(List<User> users, User? localUser)
{
if (users.Count == 0) return [];
return (await userRenderer.RenderManyAsync(users.DistinctBy(p => p.Id), localUser)).ToList();
}
private async Task<List<string>> GetLikedNotes(List<Note> notes, User? user)
private async Task<List<string>> GetLikedNotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -305,7 +305,7 @@ public class NoteRenderer(
.ToListAsync();
}
public async Task<List<ReactionEntity>> GetReactions(List<Note> notes, User? user)
public async Task<List<ReactionEntity>> GetReactionsAsync(List<Note> notes, User? user)
{
if (notes.Count == 0) return [];
var counts = notes.ToDictionary(p => p.Id, p => p.Reactions);
@ -333,7 +333,7 @@ public class NoteRenderer(
foreach (var item in res.Where(item => item.Name.StartsWith(':')))
{
var hit = await emojiSvc.ResolveEmoji(item.Name);
var hit = await emojiSvc.ResolveEmojiAsync(item.Name);
if (hit == null) continue;
item.Url = hit.PublicUrl;
item.StaticUrl = hit.PublicUrl;
@ -343,7 +343,7 @@ public class NoteRenderer(
return res;
}
private async Task<List<string>> GetBookmarkedNotes(List<Note> notes, User? user)
private async Task<List<string>> GetBookmarkedNotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -352,7 +352,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<string>> GetMutedNotes(List<Note> notes, User? user)
private async Task<List<string>> GetMutedNotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -362,7 +362,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<string>> GetPinnedNotes(List<Note> notes, User? user)
private async Task<List<string>> GetPinnedNotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -371,7 +371,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<string>> GetRenotes(List<Note> notes, User? user)
private async Task<List<string>> GetRenotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -383,7 +383,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<PollEntity>> GetPolls(List<Note> notes, User? user)
private async Task<List<PollEntity>> GetPollsAsync(List<Note> notes, User? user)
{
if (notes.Count == 0) return [];
var polls = await db.Polls.Where(p => notes.Contains(p.Note))
@ -392,7 +392,7 @@ public class NoteRenderer(
return await pollRenderer.RenderManyAsync(polls, user).ToListAsync();
}
private async Task<List<EmojiEntity>> GetEmoji(IEnumerable<Note> notes)
private async Task<List<EmojiEntity>> GetEmojiAsync(IEnumerable<Note> notes)
{
var ids = notes.SelectMany(p => p.Emojis).ToList();
if (ids.Count == 0) return [];
@ -411,7 +411,7 @@ public class NoteRenderer(
.ToListAsync();
}
private async Task<List<Filter>> GetFilters(User? user, Filter.FilterContext? filterContext)
private async Task<List<Filter>> GetFiltersAsync(User? user, Filter.FilterContext? filterContext)
{
return filterContext == null
? await db.Filters.Where(p => p.User == user).ToListAsync()
@ -433,18 +433,18 @@ public class NoteRenderer(
var data = new NoteRendererDto
{
Accounts = accounts ?? await GetAccounts(allNotes.Select(p => p.User).ToList(), user),
Mentions = await GetMentions(allNotes),
Attachments = await GetAttachments(allNotes),
Polls = await GetPolls(allNotes, user),
LikedNotes = await GetLikedNotes(allNotes, user),
BookmarkedNotes = await GetBookmarkedNotes(allNotes, user),
MutedNotes = await GetMutedNotes(allNotes, user),
PinnedNotes = await GetPinnedNotes(allNotes, user),
Renotes = await GetRenotes(allNotes, user),
Emoji = await GetEmoji(allNotes),
Reactions = await GetReactions(allNotes, user),
Filters = await GetFilters(user, filterContext)
Accounts = accounts ?? await GetAccountsAsync(allNotes.Select(p => p.User).ToList(), user),
Mentions = await GetMentionsAsync(allNotes),
Attachments = await GetAttachmentsAsync(allNotes),
Polls = await GetPollsAsync(allNotes, user),
LikedNotes = await GetLikedNotesAsync(allNotes, user),
BookmarkedNotes = await GetBookmarkedNotesAsync(allNotes, user),
MutedNotes = await GetMutedNotesAsync(allNotes, user),
PinnedNotes = await GetPinnedNotesAsync(allNotes, user),
Renotes = await GetRenotesAsync(allNotes, user),
Emoji = await GetEmojiAsync(allNotes),
Reactions = await GetReactionsAsync(allNotes, user),
Filters = await GetFiltersAsync(user, filterContext)
};
return await noteList.Select(p => RenderAsync(p, user, filterContext, data)).AwaitAllAsync();

View file

@ -68,7 +68,7 @@ public class NotificationRenderer(DatabaseContext db, NoteRenderer noteRenderer,
var notificationList = notifications.ToList();
if (notificationList.Count == 0) return [];
var accounts = await noteRenderer.GetAccounts(notificationList.Where(p => p.Notifier != null)
var accounts = await noteRenderer.GetAccountsAsync(notificationList.Where(p => p.Notifier != null)
.Select(p => p.Notifier)
.Concat(notificationList.Select(p => p.Notifiee))
.Concat(notificationList
@ -107,7 +107,7 @@ public class NotificationRenderer(DatabaseContext db, NoteRenderer noteRenderer,
Url = e.PublicUrl
})
.ToArrayAsync()
.ContinueWithResult(res => res.DistinctBy(e => e.Name)
.ContinueWithResultAsync(res => res.DistinctBy(e => e.Name)
.ToDictionary(e => e.Name, e => e.Url));
return await notificationList

View file

@ -10,9 +10,9 @@ public class PollRenderer(DatabaseContext db) : IScopedService
{
public async Task<PollEntity> RenderAsync(Poll poll, User? user, PollRendererDto? data = null)
{
var voted = (data?.Voted ?? await GetVoted([poll], user)).Contains(poll.NoteId);
var voted = (data?.Voted ?? await GetVotedAsync([poll], user)).Contains(poll.NoteId);
var ownVotes = (data?.OwnVotes ?? await GetOwnVotes([poll], user)).Where(p => p.Key == poll.NoteId)
var ownVotes = (data?.OwnVotes ?? await GetOwnVotesAsync([poll], user)).Where(p => p.Key == poll.NoteId)
.Select(p => p.Value)
.DefaultIfEmpty([])
.First();
@ -38,7 +38,7 @@ public class PollRenderer(DatabaseContext db) : IScopedService
return res;
}
private async Task<List<string>> GetVoted(IEnumerable<Poll> polls, User? user)
private async Task<List<string>> GetVotedAsync(IEnumerable<Poll> polls, User? user)
{
if (user == null) return [];
return await db.PollVotes.Where(p => polls.Select(i => i.NoteId).Any(i => i == p.NoteId) && p.User == user)
@ -47,7 +47,7 @@ public class PollRenderer(DatabaseContext db) : IScopedService
.ToListAsync();
}
private async Task<Dictionary<string, int[]>> GetOwnVotes(IEnumerable<Poll> polls, User? user)
private async Task<Dictionary<string, int[]>> GetOwnVotesAsync(IEnumerable<Poll> polls, User? user)
{
if (user == null) return [];
return await db.PollVotes
@ -62,7 +62,7 @@ public class PollRenderer(DatabaseContext db) : IScopedService
var data = new PollRendererDto
{
OwnVotes = await GetOwnVotes(pollList, user), Voted = await GetVoted(pollList, user)
OwnVotes = await GetOwnVotesAsync(pollList, user), Voted = await GetVotedAsync(pollList, user)
};
return await pollList.Select(p => RenderAsync(p, user, data)).AwaitAllAsync();

View file

@ -26,7 +26,7 @@ public class UserRenderer(
if (user.IsRemoteUser)
acct += $"@{user.Host}";
var profileEmoji = emoji?.Where(p => user.Emojis.Contains(p.Id)).ToList() ?? await GetEmoji([user]);
var profileEmoji = emoji?.Where(p => user.Emojis.Contains(p.Id)).ToList() ?? await GetEmojiAsync([user]);
var mentions = profile?.Mentions ?? [];
var fields = profile != null
? await profile.Fields
@ -97,7 +97,7 @@ public class UserRenderer(
return res;
}
private async Task<List<EmojiEntity>> GetEmoji(IEnumerable<User> users)
private async Task<List<EmojiEntity>> GetEmojiAsync(IEnumerable<User> users)
{
var ids = users.SelectMany(p => p.Emojis).ToList();
if (ids.Count == 0) return [];
@ -125,7 +125,7 @@ public class UserRenderer(
{
var userList = users.ToList();
if (userList.Count == 0) return [];
var emoji = await GetEmoji(userList);
var emoji = await GetEmojiAsync(userList);
return await userList.Select(p => RenderAsync(p, localUser, emoji)).AwaitAllAsync();
}
}

View file

@ -91,7 +91,7 @@ public class SearchController(
return result switch
{
not null => [await userRenderer.RenderAsync(await userResolver.GetUpdatedUser(result), user)],
not null => [await userRenderer.RenderAsync(await userResolver.GetUpdatedUserAsync(result), user)],
_ => []
};
}
@ -120,7 +120,7 @@ public class SearchController(
var result = await userResolver.ResolveOrNullAsync(GetQuery(username, host), ResolveFlags.Acct);
return result switch
{
not null => [await userRenderer.RenderAsync(await userResolver.GetUpdatedUser(result), user)],
not null => [await userRenderer.RenderAsync(await userResolver.GetUpdatedUserAsync(result), user)],
_ => []
};
}

View file

@ -18,7 +18,7 @@ public class DirectChannel(WebSocketConnection connection) : IChannel
public bool IsSubscribed { get; private set; }
public bool IsAggregate => false;
public async Task Subscribe(StreamingRequestMessage _)
public async Task SubscribeAsync(StreamingRequestMessage _)
{
if (IsSubscribed) return;
IsSubscribed = true;
@ -30,7 +30,7 @@ public class DirectChannel(WebSocketConnection connection) : IChannel
connection.EventService.NoteUpdated += OnNoteUpdated;
}
public Task Unsubscribe(StreamingRequestMessage _)
public Task UnsubscribeAsync(StreamingRequestMessage _)
{
if (!IsSubscribed) return Task.CompletedTask;
IsSubscribed = false;
@ -73,7 +73,7 @@ public class DirectChannel(WebSocketConnection connection) : IChannel
return rendered;
}
private async Task<ConversationEntity> RenderConversation(
private async Task<ConversationEntity> RenderConversationAsync(
Note note, NoteWithVisibilities wrapped, AsyncServiceScope scope
)
{
@ -107,13 +107,13 @@ public class DirectChannel(WebSocketConnection connection) : IChannel
if (note.CreatedAt < DateTime.UtcNow - TimeSpan.FromMinutes(5)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (await connection.IsMutedThread(note, scope)) return;
if (await connection.IsMutedThreadAsync(note, scope)) return;
var message = new StreamingUpdateMessage
{
Stream = [Name],
Event = "conversation",
Payload = JsonSerializer.Serialize(await RenderConversation(note, wrapped, scope))
Payload = JsonSerializer.Serialize(await RenderConversationAsync(note, wrapped, scope))
};
await connection.SendMessageAsync(JsonSerializer.Serialize(message));
@ -137,7 +137,7 @@ public class DirectChannel(WebSocketConnection connection) : IChannel
{
Stream = [Name],
Event = "conversation",
Payload = JsonSerializer.Serialize(await RenderConversation(note, wrapped, scope))
Payload = JsonSerializer.Serialize(await RenderConversationAsync(note, wrapped, scope))
};
await connection.SendMessageAsync(JsonSerializer.Serialize(message));

View file

@ -20,7 +20,7 @@ public class HashtagChannel(WebSocketConnection connection, bool local) : IChann
public bool IsSubscribed => _tags.Count != 0;
public bool IsAggregate => true;
public async Task Subscribe(StreamingRequestMessage msg)
public async Task SubscribeAsync(StreamingRequestMessage msg)
{
if (msg.Tag == null)
{
@ -38,7 +38,7 @@ public class HashtagChannel(WebSocketConnection connection, bool local) : IChann
_tags.AddIfMissing(msg.Tag);
}
public async Task Unsubscribe(StreamingRequestMessage msg)
public async Task UnsubscribeAsync(StreamingRequestMessage msg)
{
if (msg.Tag == null)
{
@ -106,7 +106,7 @@ public class HashtagChannel(WebSocketConnection connection, bool local) : IChann
if (wrapped == null) return;
if (connection.IsFiltered(note)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (await connection.IsMutedThread(note, scope)) return;
if (await connection.IsMutedThreadAsync(note, scope)) return;
var renderer = scope.ServiceProvider.GetRequiredService<NoteRenderer>();
var data = new NoteRenderer.NoteRendererDto { Filters = connection.Filters.ToList() };

View file

@ -25,7 +25,7 @@ public class ListChannel(WebSocketConnection connection) : IChannel
public bool IsSubscribed => _lists.Count != 0;
public bool IsAggregate => true;
public async Task Subscribe(StreamingRequestMessage msg)
public async Task SubscribeAsync(StreamingRequestMessage msg)
{
if (msg.List == null)
{
@ -60,7 +60,7 @@ public class ListChannel(WebSocketConnection connection) : IChannel
}
}
public async Task Unsubscribe(StreamingRequestMessage msg)
public async Task UnsubscribeAsync(StreamingRequestMessage msg)
{
if (msg.List == null)
{
@ -129,7 +129,7 @@ public class ListChannel(WebSocketConnection connection) : IChannel
if (wrapped == null) return;
if (connection.IsFiltered(note)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (await connection.IsMutedThread(note, scope)) return;
if (await connection.IsMutedThreadAsync(note, scope)) return;
var renderer = scope.ServiceProvider.GetRequiredService<NoteRenderer>();
var data = new NoteRenderer.NoteRendererDto { Filters = connection.Filters.ToList() };

View file

@ -21,7 +21,7 @@ public class PublicChannel(
public bool IsSubscribed { get; private set; }
public bool IsAggregate => false;
public Task Subscribe(StreamingRequestMessage _)
public Task SubscribeAsync(StreamingRequestMessage _)
{
if (IsSubscribed) return Task.CompletedTask;
IsSubscribed = true;
@ -32,7 +32,7 @@ public class PublicChannel(
return Task.CompletedTask;
}
public Task Unsubscribe(StreamingRequestMessage _)
public Task UnsubscribeAsync(StreamingRequestMessage _)
{
if (!IsSubscribed) return Task.CompletedTask;
IsSubscribed = false;
@ -89,7 +89,7 @@ public class PublicChannel(
if (wrapped == null) return;
if (connection.IsFiltered(note)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (await connection.IsMutedThread(note, scope)) return;
if (await connection.IsMutedThreadAsync(note, scope)) return;
var renderer = scope.ServiceProvider.GetRequiredService<NoteRenderer>();
var data = new NoteRenderer.NoteRendererDto { Filters = connection.Filters.ToList() };

View file

@ -17,7 +17,7 @@ public class UserChannel(WebSocketConnection connection, bool notificationsOnly)
public bool IsSubscribed { get; private set; }
public bool IsAggregate => false;
public async Task Subscribe(StreamingRequestMessage _)
public async Task SubscribeAsync(StreamingRequestMessage _)
{
if (IsSubscribed) return;
IsSubscribed = true;
@ -35,7 +35,7 @@ public class UserChannel(WebSocketConnection connection, bool notificationsOnly)
connection.EventService.Notification += OnNotification;
}
public Task Unsubscribe(StreamingRequestMessage _)
public Task UnsubscribeAsync(StreamingRequestMessage _)
{
if (!IsSubscribed) return Task.CompletedTask;
IsSubscribed = false;
@ -102,7 +102,7 @@ public class UserChannel(WebSocketConnection connection, bool notificationsOnly)
if (connection.IsFiltered(note)) return;
if (note.CreatedAt < DateTime.UtcNow - TimeSpan.FromMinutes(5)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (await connection.IsMutedThread(note, scope)) return;
if (await connection.IsMutedThreadAsync(note, scope)) return;
var renderer = scope.ServiceProvider.GetRequiredService<NoteRenderer>();
var intermediate = await renderer.RenderAsync(note, connection.Token.User);
@ -175,7 +175,7 @@ public class UserChannel(WebSocketConnection connection, bool notificationsOnly)
if (IsFiltered(notification)) return;
await using var scope = connection.ScopeFactory.CreateAsyncScope();
if (notification.Note != null && await connection.IsMutedThread(notification.Note, scope, true))
if (notification.Note != null && await connection.IsMutedThreadAsync(notification.Note, scope, true))
return;
var renderer = scope.ServiceProvider.GetRequiredService<NotificationRenderer>();

View file

@ -83,10 +83,10 @@ public sealed class WebSocketConnection(
EventService.FilterUpdated += OnFilterUpdated;
EventService.ListMembersUpdated += OnListMembersUpdated;
_ = InitializeRelationships();
_ = InitializeRelationshipsAsync();
}
private async Task InitializeRelationships()
private async Task InitializeRelationshipsAsync()
{
await using var db = Scope.ServiceProvider.GetRequiredService<DatabaseContext>();
Following.AddRange(await db.Followings.Where(p => p.Follower == Token.User)
@ -120,7 +120,7 @@ public sealed class WebSocketConnection(
.Select(p => p.UserId)
.Distinct()
.ToArrayAsync()
.ContinueWithResult(p => p.ToHashSet());
.ContinueWithResultAsync(p => p.ToHashSet());
}
public async Task HandleSocketMessageAsync(string payload)
@ -163,14 +163,14 @@ public sealed class WebSocketConnection(
if (channel.Scopes.Except(MastodonOauthHelpers.ExpandScopes(Token.Scopes)).Any())
await CloseAsync(WebSocketCloseStatus.PolicyViolation);
else
await channel.Subscribe(message);
await channel.SubscribeAsync(message);
break;
}
case "unsubscribe":
{
var channel =
_channels.FirstOrDefault(p => p.Name == message.Stream && (p.IsSubscribed || p.IsAggregate));
if (channel != null) await channel.Unsubscribe(message);
if (channel != null) await channel.UnsubscribeAsync(message);
break;
}
default:
@ -350,7 +350,7 @@ public sealed class WebSocketConnection(
.Where(p => p.UserList.UserId == Token.User.Id && p.UserList.HideFromHomeTl)
.Select(p => p.UserId)
.ToArrayAsync()
.ContinueWithResult(p => p.ToHashSet());
.ContinueWithResultAsync(p => p.ToHashSet());
}
catch (Exception e)
{
@ -375,7 +375,7 @@ public sealed class WebSocketConnection(
(IsFiltered(note.Renote.Renote.User) ||
IsFilteredMentions(note.Renote.Renote.Mentions)));
public async Task<bool> IsMutedThread(Note note, AsyncServiceScope scope, bool isNotification = false)
public async Task<bool> IsMutedThreadAsync(Note note, AsyncServiceScope scope, bool isNotification = false)
{
if (!isNotification && note.Reply == null) return false;
if (!isNotification && note.User.Id == Token.UserId) return false;
@ -396,7 +396,7 @@ public interface IChannel
public List<string> Scopes { get; }
public bool IsSubscribed { get; }
public bool IsAggregate { get; }
public Task Subscribe(StreamingRequestMessage message);
public Task Unsubscribe(StreamingRequestMessage message);
public Task SubscribeAsync(StreamingRequestMessage message);
public Task UnsubscribeAsync(StreamingRequestMessage message);
public void Dispose();
}

View file

@ -32,7 +32,7 @@ public class TimelineController(DatabaseContext db, NoteRenderer noteRenderer, C
public async Task<IEnumerable<StatusEntity>> GetHomeTimeline(MastodonPaginationQuery query)
{
var user = HttpContext.GetUserOrFail();
var heuristic = await QueryableTimelineExtensions.GetHeuristic(user, db, cache);
var heuristic = await QueryableTimelineExtensions.GetHeuristicAsync(user, db, cache);
return await db.Notes
.IncludeCommonProperties()
.FilterByFollowingAndOwn(user, db, heuristic)

View file

@ -66,7 +66,7 @@ public class StatusController(
if (security.Value.PublicPreview <= Enums.PublicPreview.Restricted && note.UserHost != null && user == null)
throw GracefulException.Forbidden("Public preview is disabled on this instance");
var res = await noteRenderer.GetReactions([note], user);
var res = await noteRenderer.GetReactionsAsync([note], user);
foreach (var item in res)
{
@ -98,7 +98,7 @@ public class StatusController(
if (security.Value.PublicPreview <= Enums.PublicPreview.Restricted && note.UserHost != null && user == null)
throw GracefulException.Forbidden("Public preview is disabled on this instance");
var res = (await noteRenderer.GetReactions([note], user)).Where(r => r.Name.Split("@").First() ==
var res = (await noteRenderer.GetReactionsAsync([note], user)).Where(r => r.Name.Split("@").First() ==
Regex.Unescape(reaction))
.ToArray();

View file

@ -227,7 +227,7 @@ public class AdminController(
{
var jobs = db.Jobs
.Where(p => p.Queue == queue && p.Status == Job.JobStatus.Failed)
.AsChunkedAsyncEnumerable(10, p => p.Id);
.AsChunkedAsyncEnumerableAsync(10, p => p.Id);
await foreach (var job in jobs)
await queueSvc.RetryJobAsync(job);
@ -240,7 +240,7 @@ public class AdminController(
var jobs = db.Jobs
.Where(p => p.Queue == queue && p.Status == Job.JobStatus.Failed)
.Where(p => p.Id >= from && p.Id <= to)
.AsChunkedAsyncEnumerable(10, p => p.Id);
.AsChunkedAsyncEnumerableAsync(10, p => p.Id);
await foreach (var job in jobs)
await queueSvc.RetryJobAsync(job);
@ -263,7 +263,7 @@ public class AdminController(
{
return await db.Relays
.ToArrayAsync()
.ContinueWithResult(res => res.Select(p => new RelaySchemas.RelayResponse
.ContinueWithResultAsync(res => res.Select(p => new RelaySchemas.RelayResponse
{
Id = p.Id,
Inbox = p.Inbox,
@ -276,7 +276,7 @@ public class AdminController(
[ProducesResults(HttpStatusCode.OK)]
public async Task SubscribeToRelay(RelaySchemas.RelayRequest rq)
{
await relaySvc.SubscribeToRelay(rq.Inbox);
await relaySvc.SubscribeToRelayAsync(rq.Inbox);
}
[HttpDelete("relays/{id}")]
@ -286,7 +286,7 @@ public class AdminController(
{
var relay = await db.Relays.FirstOrDefaultAsync(p => p.Id == id) ??
throw GracefulException.NotFound("Relay not found");
await relaySvc.UnsubscribeFromRelay(relay);
await relaySvc.UnsubscribeFromRelayAsync(relay);
}
[HttpPost("drive/prune-expired-media")]
@ -294,12 +294,12 @@ public class AdminController(
public async Task PruneExpiredMedia([FromServices] IServiceScopeFactory factory)
{
await using var scope = factory.CreateAsyncScope();
await new MediaCleanupTask().Invoke(scope.ServiceProvider);
await new MediaCleanupTask().InvokeAsync(scope.ServiceProvider);
}
[HttpGet("policy")]
[ProducesResults(HttpStatusCode.OK)]
public async Task<List<string>> GetAvailablePolicies() => await policySvc.GetAvailablePolicies();
public async Task<List<string>> GetAvailablePolicies() => await policySvc.GetAvailablePoliciesAsync();
[HttpGet("policy/{name}")]
[ProducesResults(HttpStatusCode.OK)]
@ -307,7 +307,7 @@ public class AdminController(
public async Task<IPolicyConfiguration> GetPolicyConfiguration(string name)
{
var raw = await db.PolicyConfiguration.Where(p => p.Name == name).Select(p => p.Data).FirstOrDefaultAsync();
return await policySvc.GetConfiguration(name, raw) ?? throw GracefulException.NotFound("Policy not found");
return await policySvc.GetConfigurationAsync(name, raw) ?? throw GracefulException.NotFound("Policy not found");
}
[HttpPut("policy/{name}")]
@ -317,7 +317,7 @@ public class AdminController(
string name, [SwaggerBodyExample("{\n \"enabled\": true\n}")] JsonDocument body
)
{
var type = await policySvc.GetConfigurationType(name) ?? throw GracefulException.NotFound("Policy not found");
var type = await policySvc.GetConfigurationTypeAsync(name) ?? throw GracefulException.NotFound("Policy not found");
var data = body.Deserialize(type, JsonSerialization.Options) as IPolicyConfiguration;
if (data?.GetType() != type) throw GracefulException.BadRequest("Invalid policy config");
var serialized = JsonSerializer.Serialize(data, type, JsonSerialization.Options);
@ -327,7 +327,7 @@ public class AdminController(
.On(p => new { p.Name })
.RunAsync();
await policySvc.Update();
await policySvc.UpdateAsync();
}
[UseNewtonsoftJson]

View file

@ -97,7 +97,7 @@ public class DriveController(
MimeType = file.ContentType,
IsSensitive = false
};
var res = await driveSvc.StoreFile(file.OpenReadStream(), user, request);
var res = await driveSvc.StoreFileAsync(file.OpenReadStream(), user, request);
return await GetFileById(res.Id);
}

View file

@ -70,7 +70,7 @@ public class EmojiController(
[ProducesErrors(HttpStatusCode.Conflict)]
public async Task<EmojiResponse> UploadEmoji(IFormFile file)
{
var emoji = await emojiSvc.CreateEmojiFromStream(file.OpenReadStream(), file.FileName, file.ContentType);
var emoji = await emojiSvc.CreateEmojiFromStreamAsync(file.OpenReadStream(), file.FileName, file.ContentType);
return new EmojiResponse
{
@ -97,7 +97,7 @@ public class EmojiController(
var emojo = await db.Emojis.FirstOrDefaultAsync(e => e.Name == name && e.Host == host);
if (emojo == null) throw GracefulException.NotFound("Emoji not found");
var cloned = await emojiSvc.CloneEmoji(emojo);
var cloned = await emojiSvc.CloneEmojiAsync(emojo);
return new EmojiResponse
{
Id = cloned.Id,
@ -116,8 +116,8 @@ public class EmojiController(
[ProducesResults(HttpStatusCode.Accepted)]
public async Task<AcceptedResult> ImportEmoji(IFormFile file)
{
var zip = await emojiImportSvc.Parse(file.OpenReadStream());
await emojiImportSvc.Import(zip); // TODO: run in background. this will take a while
var zip = await emojiImportSvc.ParseAsync(file.OpenReadStream());
await emojiImportSvc.ImportAsync(zip); // TODO: run in background. this will take a while
return Accepted();
}
@ -128,7 +128,7 @@ public class EmojiController(
[ProducesErrors(HttpStatusCode.NotFound)]
public async Task<EmojiResponse> UpdateEmoji(string id, UpdateEmojiRequest request)
{
var emoji = await emojiSvc.UpdateLocalEmoji(id, request.Name, request.Aliases, request.Category,
var emoji = await emojiSvc.UpdateLocalEmojiAsync(id, request.Name, request.Aliases, request.Category,
request.License, request.Sensitive) ??
throw GracefulException.NotFound("Emoji not found");
@ -151,6 +151,6 @@ public class EmojiController(
[ProducesErrors(HttpStatusCode.NotFound)]
public async Task DeleteEmoji(string id)
{
await emojiSvc.DeleteEmoji(id);
await emojiSvc.DeleteEmojiAsync(id);
}
}

View file

@ -39,7 +39,7 @@ public class FollowRequestController(
.Select(p => new { p.Id, p.Follower })
.ToListAsync();
var users = await userRenderer.RenderMany(requests.Select(p => p.Follower));
var users = await userRenderer.RenderManyAsync(requests.Select(p => p.Follower));
return requests.Select(p => new FollowRequestResponse
{
Id = p.Id, User = users.First(u => u.Id == p.Follower.Id)

View file

@ -26,13 +26,13 @@ public class InstanceController(DatabaseContext db, UserRenderer userRenderer) :
var admins = db.Users
.Where(p => p.IsAdmin == true)
.OrderBy(p => p.UsernameLower);
var adminList = await userRenderer.RenderMany(admins)
var adminList = await userRenderer.RenderManyAsync(admins)
.ToListAsync();
var moderators = db.Users
.Where(p => p.IsAdmin == false && p.IsModerator == true)
.OrderBy(p => p.UsernameLower);
var moderatorList = await userRenderer.RenderMany(moderators)
var moderatorList = await userRenderer.RenderManyAsync(moderators)
.ToListAsync();
return new StaffResponse { Admins = adminList, Moderators = moderatorList };

View file

@ -71,7 +71,7 @@ public class MigrationController(
aliasUri ??= await db.Users.IncludeCommonProperties()
.Where(p => p.Id == rq.UserId)
.FirstOrDefaultAsync()
.ContinueWithResult(p => p is null ? null : p.Uri ?? p.GetPublicUri(config.Value));
.ContinueWithResultAsync(p => p is null ? null : p.Uri ?? p.GetPublicUri(config.Value));
}
if (aliasUri is null) throw GracefulException.NotFound("Alias user not found");

View file

@ -61,6 +61,6 @@ public class MiscController(DatabaseContext db, NoteRenderer noteRenderer, BiteS
.PrecomputeVisibilities(user)
.ToListAsync();
return await noteRenderer.RenderMany(notes.EnforceRenoteReplyVisibility(), user);
return await noteRenderer.RenderManyAsync(notes.EnforceRenoteReplyVisibility(), user);
}
}

View file

@ -96,7 +96,7 @@ public class NoteController(
.ToListAsync();
var notes = hits.EnforceRenoteReplyVisibility();
var res = await noteRenderer.RenderMany(notes, user, Filter.FilterContext.Threads).ToListAsync();
var res = await noteRenderer.RenderManyAsync(notes, user, Filter.FilterContext.Threads).ToListAsync();
// Strip redundant reply data
foreach (var item in res.Where(p => p.Reply != null && res.Any(i => i.Id == p.Reply.Id)))
@ -131,7 +131,7 @@ public class NoteController(
.ToListAsync();
var notes = hits.EnforceRenoteReplyVisibility();
var res = await noteRenderer.RenderMany(notes, user, Filter.FilterContext.Threads).ToListAsync();
var res = await noteRenderer.RenderManyAsync(notes, user, Filter.FilterContext.Threads).ToListAsync();
// Strip redundant reply data
foreach (var item in res.Where(p => p.Reply != null && res.Any(i => i.Id == p.Reply.Id)))
@ -163,7 +163,7 @@ public class NoteController(
.Select(p => p.User)
.ToListAsync();
return await userRenderer.RenderMany(users);
return await userRenderer.RenderManyAsync(users);
}
[HttpPost("{id}/bite")]
@ -249,7 +249,7 @@ public class NoteController(
.Wrap(p => p.User)
.ToListAsync();
var res = await userRenderer.RenderMany(users.Select(p => p.Entity));
var res = await userRenderer.RenderManyAsync(users.Select(p => p.Entity));
return HttpContext.CreatePaginationWrapper(pq, users, res);
}
@ -315,7 +315,7 @@ public class NoteController(
.Wrap(p => p.User)
.ToListAsync();
var res = await userRenderer.RenderMany(users.Select(p => p.Entity));
var res = await userRenderer.RenderManyAsync(users.Select(p => p.Entity));
return HttpContext.CreatePaginationWrapper(pq, users, res);
}
@ -343,7 +343,7 @@ public class NoteController(
.Paginate(pq, ControllerContext)
.ToListAsync();
var res = await noteRenderer.RenderMany(renotes.EnforceRenoteReplyVisibility(), user,
var res = await noteRenderer.RenderManyAsync(renotes.EnforceRenoteReplyVisibility(), user,
Filter.FilterContext.Threads);
return HttpContext.CreatePaginationWrapper(pq, renotes, res);
}

View file

@ -36,7 +36,7 @@ public class NotificationController(DatabaseContext db, NotificationRenderer not
.PrecomputeNoteVisibilities(user)
.ToListAsync();
return await notificationRenderer.RenderMany(notifications.EnforceRenoteReplyVisibility(p => p.Note), user);
return await notificationRenderer.RenderManyAsync(notifications.EnforceRenoteReplyVisibility(p => p.Note), user);
}
[HttpPost("{id}/read")]

View file

@ -21,15 +21,15 @@ public class NoteRenderer(
Note note, User? user, Filter.FilterContext? filterContext = null, NoteRendererDto? data = null
)
{
var res = await RenderBaseInternal(note, user, data);
var res = await RenderBaseInternalAsync(note, user, data);
var renote = note is { Renote: not null, IsPureRenote: true }
? await RenderRenote(note.Renote, user, data)
? await RenderRenoteAsync(note.Renote, user, data)
: null;
var quote = note is { Renote: not null, IsQuote: true } ? await RenderBase(note.Renote, user, data) : null;
var reply = note.Reply != null ? await RenderBase(note.Reply, user, data) : null;
var quote = note is { Renote: not null, IsQuote: true } ? await RenderBaseAsync(note.Renote, user, data) : null;
var reply = note.Reply != null ? await RenderBaseAsync(note.Reply, user, data) : null;
var filters = data?.Filters ?? await GetFilters(user, filterContext);
var filters = data?.Filters ?? await GetFiltersAsync(user, filterContext);
var filtered = FilterHelper.IsFiltered([note, note.Reply, note.Renote, note.Renote?.Renote], filters);
if (filtered.HasValue)
@ -54,10 +54,10 @@ public class NoteRenderer(
return res;
}
private async Task<NoteWithQuote> RenderRenote(Note note, User? user, NoteRendererDto? data = null)
private async Task<NoteWithQuote> RenderRenoteAsync(Note note, User? user, NoteRendererDto? data = null)
{
var res = await RenderBaseInternal(note, user, data);
var quote = note.Renote is { IsPureRenote: false } ? await RenderBase(note.Renote, user, data) : null;
var res = await RenderBaseInternalAsync(note, user, data);
var quote = note.Renote is { IsPureRenote: false } ? await RenderBaseAsync(note.Renote, user, data) : null;
res.Quote = quote;
res.QuoteId = note.RenoteId;
@ -66,17 +66,17 @@ public class NoteRenderer(
return res;
}
private async Task<NoteBase> RenderBase(Note note, User? localUser, NoteRendererDto? data = null)
=> await RenderBaseInternal(note, localUser, data);
private async Task<NoteBase> RenderBaseAsync(Note note, User? localUser, NoteRendererDto? data = null)
=> await RenderBaseInternalAsync(note, localUser, data);
private async Task<NoteResponse> RenderBaseInternal(Note note, User? user, NoteRendererDto? data = null)
private async Task<NoteResponse> RenderBaseInternalAsync(Note note, User? user, NoteRendererDto? data = null)
{
var noteUser = (data?.Users ?? await GetUsers([note])).First(p => p.Id == note.User.Id);
var attachments = (data?.Attachments ?? await GetAttachments([note])).Where(p => note.FileIds.Contains(p.Id));
var reactions = (data?.Reactions ?? await GetReactions([note], user)).Where(p => p.NoteId == note.Id);
var noteUser = (data?.Users ?? await GetUsersAsync([note])).First(p => p.Id == note.User.Id);
var attachments = (data?.Attachments ?? await GetAttachmentsAsync([note])).Where(p => note.FileIds.Contains(p.Id));
var reactions = (data?.Reactions ?? await GetReactionsAsync([note], user)).Where(p => p.NoteId == note.Id);
var liked = data?.LikedNotes?.Contains(note.Id) ??
await db.NoteLikes.AnyAsync(p => p.Note == note && p.User == user);
var emoji = data?.Emoji?.Where(p => note.Emojis.Contains(p.Id)).ToList() ?? await GetEmoji([note]);
var emoji = data?.Emoji?.Where(p => note.Emojis.Contains(p.Id)).ToList() ?? await GetEmojiAsync([note]);
return new NoteResponse
{
@ -98,14 +98,14 @@ public class NoteRenderer(
};
}
private async Task<List<UserResponse>> GetUsers(List<Note> notesList)
private async Task<List<UserResponse>> GetUsersAsync(List<Note> notesList)
{
if (notesList.Count == 0) return [];
var users = notesList.Select(p => p.User).DistinctBy(p => p.Id);
return await userRenderer.RenderMany(users).ToListAsync();
return await userRenderer.RenderManyAsync(users).ToListAsync();
}
private async Task<List<NoteAttachment>> GetAttachments(List<Note> notesList)
private async Task<List<NoteAttachment>> GetAttachmentsAsync(List<Note> notesList)
{
if (notesList.Count == 0) return [];
var ids = notesList.SelectMany(p => p.FileIds).Distinct();
@ -123,7 +123,7 @@ public class NoteRenderer(
.ToList();
}
private async Task<List<NoteReactionSchema>> GetReactions(List<Note> notes, User? user)
private async Task<List<NoteReactionSchema>> GetReactionsAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -146,7 +146,7 @@ public class NoteRenderer(
foreach (var item in res.Where(item => item.Name.StartsWith(':')))
{
var hit = await emojiSvc.ResolveEmoji(item.Name);
var hit = await emojiSvc.ResolveEmojiAsync(item.Name);
if (hit == null) continue;
item.Url = hit.PublicUrl;
item.Sensitive = hit.Sensitive;
@ -155,7 +155,7 @@ public class NoteRenderer(
return res;
}
private async Task<List<string>> GetLikedNotes(List<Note> notes, User? user)
private async Task<List<string>> GetLikedNotesAsync(List<Note> notes, User? user)
{
if (user == null) return [];
if (notes.Count == 0) return [];
@ -172,13 +172,13 @@ public class NoteRenderer(
.ToList();
}
private async Task<List<Filter>> GetFilters(User? user, Filter.FilterContext? filterContext)
private async Task<List<Filter>> GetFiltersAsync(User? user, Filter.FilterContext? filterContext)
{
if (filterContext == null) return [];
return await db.Filters.Where(p => p.User == user && p.Contexts.Contains(filterContext.Value)).ToListAsync();
}
private async Task<List<EmojiResponse>> GetEmoji(IEnumerable<Note> notes)
private async Task<List<EmojiResponse>> GetEmojiAsync(IEnumerable<Note> notes)
{
var ids = notes.SelectMany(p => p.Emojis).ToList();
if (ids.Count == 0) return [];
@ -199,7 +199,7 @@ public class NoteRenderer(
.ToListAsync();
}
public async Task<IEnumerable<NoteResponse>> RenderMany(
public async Task<IEnumerable<NoteResponse>> RenderManyAsync(
IEnumerable<Note> notes, User? user, Filter.FilterContext? filterContext = null
)
{
@ -208,12 +208,12 @@ public class NoteRenderer(
var allNotes = GetAllNotes(notesList);
var data = new NoteRendererDto
{
Users = await GetUsers(allNotes),
Attachments = await GetAttachments(allNotes),
Reactions = await GetReactions(allNotes, user),
Filters = await GetFilters(user, filterContext),
LikedNotes = await GetLikedNotes(allNotes, user),
Emoji = await GetEmoji(allNotes)
Users = await GetUsersAsync(allNotes),
Attachments = await GetAttachmentsAsync(allNotes),
Reactions = await GetReactionsAsync(allNotes, user),
Filters = await GetFiltersAsync(user, filterContext),
LikedNotes = await GetLikedNotesAsync(allNotes, user),
Emoji = await GetEmojiAsync(allNotes)
};
return await notesList.Select(p => RenderOne(p, user, filterContext, data)).AwaitAllAsync();

View file

@ -42,8 +42,8 @@ public class NotificationRenderer(UserRenderer userRenderer, NoteRenderer noteRe
{
var data = new NotificationRendererDto
{
Users = await GetUsers([notification]),
Notes = await GetNotes([notification], localUser),
Users = await GetUsersAsync([notification]),
Notes = await GetNotesAsync([notification], localUser),
Bites = GetBites([notification])
};
@ -71,16 +71,16 @@ public class NotificationRenderer(UserRenderer userRenderer, NoteRenderer noteRe
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
private async Task<List<UserResponse>> GetUsers(IEnumerable<Notification> notifications)
private async Task<List<UserResponse>> GetUsersAsync(IEnumerable<Notification> notifications)
{
var users = notifications.Select(p => p.Notifier).OfType<User>().DistinctBy(p => p.Id);
return await userRenderer.RenderMany(users).ToListAsync();
return await userRenderer.RenderManyAsync(users).ToListAsync();
}
private async Task<List<NoteResponse>> GetNotes(IEnumerable<Notification> notifications, User user)
private async Task<List<NoteResponse>> GetNotesAsync(IEnumerable<Notification> notifications, User user)
{
var notes = notifications.Select(p => p.Note).OfType<Note>().DistinctBy(p => p.Id);
return await noteRenderer.RenderMany(notes, user, Filter.FilterContext.Notifications).ToListAsync();
return await noteRenderer.RenderManyAsync(notes, user, Filter.FilterContext.Notifications).ToListAsync();
}
private static List<BiteResponse> GetBites(IEnumerable<Notification> notifications)
@ -89,13 +89,13 @@ public class NotificationRenderer(UserRenderer userRenderer, NoteRenderer noteRe
return bites.Select(p => new BiteResponse { Id = p.Id, BiteBack = p.TargetBiteId != null }).ToList();
}
public async Task<IEnumerable<NotificationResponse>> RenderMany(IEnumerable<Notification> notifications, User user)
public async Task<IEnumerable<NotificationResponse>> RenderManyAsync(IEnumerable<Notification> notifications, User user)
{
var notificationsList = notifications.ToList();
var data = new NotificationRendererDto
{
Users = await GetUsers(notificationsList),
Notes = await GetNotes(notificationsList, user),
Users = await GetUsersAsync(notificationsList),
Notes = await GetNotesAsync(notificationsList, user),
Bites = GetBites(notificationsList)
};

View file

@ -10,7 +10,7 @@ public class UserProfileRenderer(DatabaseContext db) : IScopedService
{
public async Task<UserProfileResponse> RenderOne(User user, User? localUser, UserRendererDto? data = null)
{
(data?.Relations ?? await GetRelations([user], localUser)).TryGetValue(user.Id, out var relations);
(data?.Relations ?? await GetRelationsAsync([user], localUser)).TryGetValue(user.Id, out var relations);
relations ??= new RelationData
{
UserId = user.Id,
@ -68,7 +68,7 @@ public class UserProfileRenderer(DatabaseContext db) : IScopedService
};
}
private async Task<Dictionary<string, RelationData>> GetRelations(IEnumerable<User> users, User? localUser)
private async Task<Dictionary<string, RelationData>> GetRelationsAsync(IEnumerable<User> users, User? localUser)
{
var ids = users.Select(p => p.Id).ToList();
if (ids.Count == 0) return [];
@ -90,10 +90,10 @@ public class UserProfileRenderer(DatabaseContext db) : IScopedService
.ToDictionaryAsync(p => p.UserId, p => p);
}
public async Task<IEnumerable<UserProfileResponse>> RenderMany(IEnumerable<User> users, User? localUser)
public async Task<IEnumerable<UserProfileResponse>> RenderManyAsync(IEnumerable<User> users, User? localUser)
{
var userList = users.ToList();
var data = new UserRendererDto { Relations = await GetRelations(userList, localUser) };
var data = new UserRendererDto { Relations = await GetRelationsAsync(userList, localUser) };
return await userList.Select(p => RenderOne(p, localUser, data)).AwaitAllAsync();
}

View file

@ -40,31 +40,31 @@ public class UserRenderer(IOptions<Config.InstanceSection> config, DatabaseConte
public async Task<UserResponse> RenderOne(User user)
{
var instanceData = await GetInstanceData([user]);
var emojis = await GetEmojis([user]);
var instanceData = await GetInstanceDataAsync([user]);
var emojis = await GetEmojisAsync([user]);
var data = new UserRendererDto { Emojis = emojis, InstanceData = instanceData };
return Render(user, data);
}
private async Task<List<Instance>> GetInstanceData(IEnumerable<User> users)
private async Task<List<Instance>> GetInstanceDataAsync(IEnumerable<User> users)
{
var hosts = users.Select(p => p.Host).Where(p => p != null).Distinct().Cast<string>();
return await db.Instances.Where(p => hosts.Contains(p.Host)).ToListAsync();
}
public async Task<IEnumerable<UserResponse>> RenderMany(IEnumerable<User> users)
public async Task<IEnumerable<UserResponse>> RenderManyAsync(IEnumerable<User> users)
{
var userList = users.ToList();
var data = new UserRendererDto
{
InstanceData = await GetInstanceData(userList), Emojis = await GetEmojis(userList)
InstanceData = await GetInstanceDataAsync(userList), Emojis = await GetEmojisAsync(userList)
};
return userList.Select(p => Render(p, data));
}
private async Task<Dictionary<string, List<EmojiResponse>>> GetEmojis(ICollection<User> users)
private async Task<Dictionary<string, List<EmojiResponse>>> GetEmojisAsync(ICollection<User> users)
{
var ids = users.SelectMany(p => p.Emojis).ToList();
if (ids.Count == 0) return users.ToDictionary<User, string, List<EmojiResponse>>(p => p.Id, _ => []);

View file

@ -51,7 +51,7 @@ public class SearchController(
.PrecomputeVisibilities(user)
.ToListAsync();
return await noteRenderer.RenderMany(notes.EnforceRenoteReplyVisibility(), user);
return await noteRenderer.RenderManyAsync(notes.EnforceRenoteReplyVisibility(), user);
}
[HttpGet("users")]
@ -71,7 +71,7 @@ public class SearchController(
.OrderByDescending(p => p.NotesCount)
.ToListAsync();
return await userRenderer.RenderMany(users);
return await userRenderer.RenderManyAsync(users);
}
[HttpGet("lookup")]

View file

@ -29,7 +29,7 @@ public class TimelineController(DatabaseContext db, NoteRenderer noteRenderer, C
public async Task<IEnumerable<NoteResponse>> GetHomeTimeline(PaginationQuery pq)
{
var user = HttpContext.GetUserOrFail();
var heuristic = await QueryableTimelineExtensions.GetHeuristic(user, db, cache);
var heuristic = await QueryableTimelineExtensions.GetHeuristicAsync(user, db, cache);
var notes = await db.Notes.IncludeCommonProperties()
.FilterByFollowingAndOwn(user, db, heuristic)
.EnsureVisibleFor(user)
@ -39,6 +39,6 @@ public class TimelineController(DatabaseContext db, NoteRenderer noteRenderer, C
.PrecomputeVisibilities(user)
.ToListAsync();
return await noteRenderer.RenderMany(notes.EnforceRenoteReplyVisibility(), user, Filter.FilterContext.Home);
return await noteRenderer.RenderManyAsync(notes.EnforceRenoteReplyVisibility(), user, Filter.FilterContext.Home);
}
}

View file

@ -43,7 +43,7 @@ public class UserController(
.FirstOrDefaultAsync(p => p.Id == id) ??
throw GracefulException.NotFound("User not found");
return await userRenderer.RenderOne(await userResolver.GetUpdatedUser(user));
return await userRenderer.RenderOne(await userResolver.GetUpdatedUserAsync(user));
}
[HttpGet("lookup")]
@ -61,7 +61,7 @@ public class UserController(
.FirstOrDefaultAsync(p => p.UsernameLower == username && p.Host == host) ??
throw GracefulException.NotFound("User not found");
return await userRenderer.RenderOne(await userResolver.GetUpdatedUser(user));
return await userRenderer.RenderOne(await userResolver.GetUpdatedUserAsync(user));
}
[HttpGet("{id}/profile")]
@ -74,7 +74,7 @@ public class UserController(
.FirstOrDefaultAsync(p => p.Id == id) ??
throw GracefulException.NotFound("User not found");
return await userProfileRenderer.RenderOne(await userResolver.GetUpdatedUser(user), localUser);
return await userProfileRenderer.RenderOne(await userResolver.GetUpdatedUserAsync(user), localUser);
}
[HttpGet("{id}/notes")]
@ -95,9 +95,9 @@ public class UserController(
.Paginate(pq, ControllerContext)
.PrecomputeVisibilities(localUser)
.ToListAsync()
.ContinueWithResult(res => res.EnforceRenoteReplyVisibility());
.ContinueWithResultAsync(res => res.EnforceRenoteReplyVisibility());
return await noteRenderer.RenderMany(notes, localUser, Filter.FilterContext.Accounts);
return await noteRenderer.RenderManyAsync(notes, localUser, Filter.FilterContext.Accounts);
}
[HttpPost("{id}/bite")]

View file

@ -255,13 +255,13 @@ public class DatabaseContext(DbContextOptions<DatabaseContext> options)
RETURNING "jobs".*;
""");
public Task<int> GetJobRunningCount(string queue, CancellationToken token) =>
public Task<int> GetJobRunningCountAsync(string queue, CancellationToken token) =>
Jobs.CountAsync(p => p.Queue == queue && p.Status == Job.JobStatus.Running, token);
public Task<int> GetJobQueuedCount(string queue, CancellationToken token) =>
public Task<int> GetJobQueuedCountAsync(string queue, CancellationToken token) =>
Jobs.CountAsync(p => p.Queue == queue && p.Status == Job.JobStatus.Queued, token);
public async Task<bool> IsDatabaseEmpty()
public async Task<bool> IsDatabaseEmptyAsync()
=> !await Database.SqlQuery<object>($"""
select s.nspname from pg_class c
join pg_namespace s on s.oid = c.relnamespace

View file

@ -28,7 +28,7 @@ public static class QueryableExtensions
/// The result set as an IAsyncEnumerable. Makes one DB roundtrip at the start of each chunk.
/// Successive items in the chunk are yielded instantaneously.
/// </returns>
public static async IAsyncEnumerable<T> AsChunkedAsyncEnumerable<T>(this IQueryable<T> query, int chunkSize)
public static async IAsyncEnumerable<T> AsChunkedAsyncEnumerableAsync<T>(this IQueryable<T> query, int chunkSize)
{
var offset = 0;
while (true)
@ -41,13 +41,13 @@ public static class QueryableExtensions
}
}
/// <inheritdoc cref="AsChunkedAsyncEnumerable{T}(System.Linq.IQueryable{T},int)" select="summary|returns"/>
/// <inheritdoc cref="AsChunkedAsyncEnumerableAsync{T}(System.Linq.IQueryable{T},int)" select="summary|returns"/>
/// <remarks>
/// This overload requires you to pass a predicate to the identifier.
/// .OrderBy(<paramref name="idPredicate"/>) is appended to the query.
/// Set the <paramref name="hook"/> parameter to append things to the query after pagination, for cases where query translation would fail otherwise.
/// </remarks>
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerable<TResult>(
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerableAsync<TResult>(
this IQueryable<TResult> query, int chunkSize, Expression<Func<TResult, string>> idPredicate,
Func<IQueryable<TResult>, IQueryable<TResult>>? hook = null
)
@ -70,8 +70,8 @@ public static class QueryableExtensions
}
}
/// <inheritdoc cref="AsChunkedAsyncEnumerable{T}(System.Linq.IQueryable{T},int,Expression{Func{T,string}},Func{IQueryable{T},IQueryable{T}})"/>
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerable<TResult>(
/// <inheritdoc cref="AsChunkedAsyncEnumerableAsync{TResult}(System.Linq.IQueryable{TResult},int,System.Linq.Expressions.Expression{System.Func{TResult,string}},System.Func{System.Linq.IQueryable{TResult},System.Linq.IQueryable{TResult}}?)"/>
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerableAsync<TResult>(
this IQueryable<TResult> query, int chunkSize, Expression<Func<TResult, Guid>> idPredicate,
Func<IQueryable<TResult>, IQueryable<TResult>>? hook = null
)
@ -94,8 +94,8 @@ public static class QueryableExtensions
}
}
/// <inheritdoc cref="AsChunkedAsyncEnumerable{T}(System.Linq.IQueryable{T},int,Expression{Func{T,string}},Func{IQueryable{T},IQueryable{T}})"/>
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerable<TResult>(
/// <inheritdoc cref="AsChunkedAsyncEnumerableAsync{TResult}(System.Linq.IQueryable{TResult},int,System.Linq.Expressions.Expression{System.Func{TResult,string}},System.Func{System.Linq.IQueryable{TResult},System.Linq.IQueryable{TResult}}?)"/>
public static async IAsyncEnumerable<TResult> AsChunkedAsyncEnumerableAsync<TResult>(
this IQueryable<TResult> query, int chunkSize, Expression<Func<TResult, int>> idPredicate,
Func<IQueryable<TResult>, IQueryable<TResult>>? hook = null
)

View file

@ -29,17 +29,17 @@ public static class QueryableTimelineExtensions
.Concat(new[] { user.Id })
.Contains(note.UserId));
public static async Task ResetHeuristic(User user, CacheService cache)
public static async Task ResetHeuristicAsync(User user, CacheService cache)
{
await cache.ClearAsync($"{Prefix}:{user.Id}");
}
public static async Task<int> GetHeuristic(User user, DatabaseContext db, CacheService cache)
public static async Task<int> GetHeuristicAsync(User user, DatabaseContext db, CacheService cache)
{
return await cache.FetchValueAsync($"{Prefix}:{user.Id}", TimeSpan.FromHours(24), FetchHeuristic);
return await cache.FetchValueAsync($"{Prefix}:{user.Id}", TimeSpan.FromHours(24), FetchHeuristicAsync);
[SuppressMessage("ReSharper", "EntityFramework.UnsupportedServerSideFunctionCall")]
async Task<int> FetchHeuristic()
async Task<int> FetchHeuristicAsync()
{
var latestNote = await db.Notes.OrderByDescending(p => p.Id)
.Select(p => new { p.CreatedAt })

View file

@ -432,9 +432,9 @@ file sealed class EntityFrameworkCoreXmlRepositoryAsync<TContext> : IXmlReposito
public IReadOnlyCollection<XElement> GetAllElements()
{
return GetAllElementsCore().ToBlockingEnumerable().ToList().AsReadOnly();
return GetAllElementsCoreAsync().ToBlockingEnumerable().ToList().AsReadOnly();
async IAsyncEnumerable<XElement> GetAllElementsCore()
async IAsyncEnumerable<XElement> GetAllElementsCoreAsync()
{
using var scope = _services.CreateScope();
var @enum = scope.ServiceProvider.GetRequiredService<TContext>()

View file

@ -13,7 +13,7 @@ public static class StreamExtensions
{
int bytesRead;
var totalBytesRead = 0L;
while ((maxLength == null || totalBytesRead <= maxLength) && (bytesRead = await DoRead()) != 0)
while ((maxLength == null || totalBytesRead <= maxLength) && (bytesRead = await DoReadAsync()) != 0)
{
totalBytesRead += bytesRead;
await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken);
@ -26,6 +26,6 @@ public static class StreamExtensions
return;
ValueTask<int> DoRead() => source.ReadAsync(new Memory<byte>(buffer), cancellationToken);
ValueTask<int> DoReadAsync() => source.ReadAsync(new Memory<byte>(buffer), cancellationToken);
}
}

View file

@ -58,37 +58,37 @@ public static class TaskExtensions
return (await task).ToList();
}
public static async Task ContinueWithResult(this Task task, Action continuation)
public static async Task ContinueWithResultAsync(this Task task, Action continuation)
{
await task;
continuation();
}
public static async Task<TNewResult> ContinueWithResult<TNewResult>(this Task task, Func<TNewResult> continuation)
public static async Task<TNewResult> ContinueWithResultAsync<TNewResult>(this Task task, Func<TNewResult> continuation)
{
await task;
return continuation();
}
public static async Task ContinueWithResult<TResult>(this Task<TResult> task, Action<TResult> continuation)
public static async Task ContinueWithResultAsync<TResult>(this Task<TResult> task, Action<TResult> continuation)
{
continuation(await task);
}
public static async Task<TNewResult> ContinueWithResult<TResult, TNewResult>(
public static async Task<TNewResult> ContinueWithResultAsync<TResult, TNewResult>(
this Task<TResult> task, Func<TResult, TNewResult> continuation
)
{
return continuation(await task);
}
public static async Task ContinueWithResult(this Task task, Func<Task> continuation)
public static async Task ContinueWithResultAsync(this Task task, Func<Task> continuation)
{
await task;
await continuation();
}
public static async Task<TNewResult> ContinueWithResult<TNewResult>(
public static async Task<TNewResult> ContinueWithResultAsync<TNewResult>(
this Task task, Func<Task<TNewResult>> continuation
)
{
@ -96,12 +96,12 @@ public static class TaskExtensions
return await continuation();
}
public static async Task ContinueWithResult<TResult>(this Task<TResult> task, Func<TResult, Task> continuation)
public static async Task ContinueWithResultAsync<TResult>(this Task<TResult> task, Func<TResult, Task> continuation)
{
await continuation(await task);
}
public static async Task<TNewResult> ContinueWithResult<TResult, TNewResult>(
public static async Task<TNewResult> ContinueWithResultAsync<TResult, TNewResult>(
this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation
)
{

View file

@ -82,7 +82,7 @@ public static class WebApplicationExtensions
app.MapFallbackToPage("/@{user}@{host}", page);
}
public static async Task<Config.InstanceSection> Initialize(this WebApplication app, string[] args)
public static async Task<Config.InstanceSection> InitializeAsync(this WebApplication app, string[] args)
{
var instanceConfig = app.Configuration.GetSection("Instance").Get<Config.InstanceSection>() ??
throw new Exception("Failed to read Instance config section");
@ -135,7 +135,7 @@ public static class WebApplicationExtensions
{
app.Logger.LogInformation("Initializing migration assistant...");
var initialMigration = typeof(Initial).GetCustomAttribute<MigrationAttribute>()?.Id;
if (pendingMigration != initialMigration || await db.IsDatabaseEmpty())
if (pendingMigration != initialMigration || await db.IsDatabaseEmptyAsync())
{
app.Logger.LogCritical("Database does not appear to be an iceshrimp-js database.");
Environment.Exit(1);
@ -171,7 +171,7 @@ public static class WebApplicationExtensions
if (pendingMigration != null)
{
var initialMigration = typeof(Initial).GetCustomAttribute<MigrationAttribute>()?.Id;
if (pendingMigration == initialMigration && !await db.IsDatabaseEmpty())
if (pendingMigration == initialMigration && !await db.IsDatabaseEmptyAsync())
{
app.Logger.LogCritical("Initial migration is pending but database is not empty.");
app.Logger.LogCritical("If you are trying to migrate from iceshrimp-js, please follow the instructions on https://iceshrimp.net/help/migrate.");
@ -212,19 +212,19 @@ public static class WebApplicationExtensions
{
app.Logger.LogInformation("Migrating files to object storage, this will take a while...");
db.Database.SetCommandTimeout(0);
await provider.GetRequiredService<StorageMaintenanceService>().MigrateLocalFiles(args.Contains("--purge"));
await provider.GetRequiredService<StorageMaintenanceService>().MigrateLocalFilesAsync(args.Contains("--purge"));
Environment.Exit(0);
}
if (args.Contains("--fixup-media"))
{
await provider.GetRequiredService<StorageMaintenanceService>().FixupMedia(args.Contains("--dry-run"));
await provider.GetRequiredService<StorageMaintenanceService>().FixupMediaAsync(args.Contains("--dry-run"));
Environment.Exit(0);
}
if (args.Contains("--cleanup-storage"))
{
await provider.GetRequiredService<StorageMaintenanceService>().CleanupStorage(args.Contains("--dry-run"));
await provider.GetRequiredService<StorageMaintenanceService>().CleanupStorageAsync(args.Contains("--dry-run"));
Environment.Exit(0);
}
@ -271,14 +271,14 @@ public static class WebApplicationExtensions
app.Logger.LogInformation("Initializing VAPID keys...");
var meta = provider.GetRequiredService<MetaService>();
await meta.EnsureSet([MetaEntity.VapidPublicKey, MetaEntity.VapidPrivateKey], () =>
await meta.EnsureSetAsync([MetaEntity.VapidPublicKey, MetaEntity.VapidPrivateKey], () =>
{
var keypair = VapidHelper.GenerateVapidKeys();
return [keypair.PublicKey, keypair.PrivateKey];
});
app.Logger.LogInformation("Warming up meta cache...");
await meta.WarmupCache();
await meta.WarmupCacheAsync();
// Initialize image processing
provider.GetRequiredService<ImageProcessor>();

View file

@ -49,7 +49,7 @@ public class ActivityFetcherService(
private async Task<IEnumerable<ASObject>> FetchActivityAsync(string url, User actor, UserKeypair keypair)
{
logger.LogDebug("Fetching activity {url} as user {id}", url, actor.Id);
var (activity, finalUri) = await FetchActivityInternalWrapper(url, actor, keypair);
var (activity, finalUri) = await FetchActivityInternalWrapperAsync(url, actor, keypair);
if (activity?.Id == null) return [];
var activityUri = new Uri(activity.Id);
@ -63,7 +63,7 @@ public class ActivityFetcherService(
throw GracefulException.UnprocessableEntity("Activity identifier doesn't match final host");
logger.LogDebug("Fetching activity {url} as user {id} (attempt 2)", activityIdUri.AbsoluteUri, actor.Id);
(activity, finalUri) = await FetchActivityInternalWrapper(activityIdUri.AbsoluteUri, actor, keypair);
(activity, finalUri) = await FetchActivityInternalWrapperAsync(activityIdUri.AbsoluteUri, actor, keypair);
if (activity?.Id == null) return [];
activityUri = new Uri(activity.Id);
@ -79,13 +79,13 @@ public class ActivityFetcherService(
/// This abstracts FetchActivityInternal to keep stack traces short in case of HTTP timeouts.
/// </summary>
/// <exception cref="TimeoutException"></exception>
private async Task<(ASObject? obj, Uri finalUri)> FetchActivityInternalWrapper(
private async Task<(ASObject? obj, Uri finalUri)> FetchActivityInternalWrapperAsync(
string url, User actor, UserKeypair keypair, int recurse = 3
)
{
try
{
return await FetchActivityInternal(url, actor, keypair, recurse);
return await FetchActivityInternalAsync(url, actor, keypair, recurse);
}
catch (TaskCanceledException e) when (e.Message.Contains("HttpClient.Timeout"))
{
@ -93,7 +93,7 @@ public class ActivityFetcherService(
}
}
private async Task<(ASObject? obj, Uri finalUri)> FetchActivityInternal(
private async Task<(ASObject? obj, Uri finalUri)> FetchActivityInternalAsync(
string url, User actor, UserKeypair keypair, int recurse = 3
)
{
@ -115,7 +115,7 @@ public class ActivityFetcherService(
var location = response.Headers.Location;
if (location == null) throw new Exception("Redirection requested but no location header found");
if (recurse <= 0) throw new Exception("Redirection requested but recurse counter is at zero");
return await FetchActivityInternal(location.ToString(), actor, keypair, --recurse);
return await FetchActivityInternalAsync(location.ToString(), actor, keypair, --recurse);
}
var finalUri = response.RequestMessage?.RequestUri ??

View file

@ -72,20 +72,20 @@ public class ActivityHandlerService(
var task = activity switch
{
ASAccept accept => HandleAccept(accept, resolvedActor),
ASAnnounce announce => HandleAnnounce(announce, resolvedActor),
ASBite bite => HandleBite(bite, resolvedActor, inboxUser),
ASBlock block => HandleBlock(block, resolvedActor),
ASCreate create => HandleCreate(create, resolvedActor, inboxUser),
ASDelete delete => HandleDelete(delete, resolvedActor),
ASEmojiReact react => HandleReact(react, resolvedActor),
ASFollow follow => HandleFollow(follow, resolvedActor),
ASLike like => HandleLike(like, resolvedActor),
ASMove move => HandleMove(move, resolvedActor),
ASReject reject => HandleReject(reject, resolvedActor),
ASUndo undo => HandleUndo(undo, resolvedActor),
ASUnfollow unfollow => HandleUnfollow(unfollow, resolvedActor),
ASUpdate update => HandleUpdate(update, resolvedActor),
ASAccept accept => HandleAcceptAsync(accept, resolvedActor),
ASAnnounce announce => HandleAnnounceAsync(announce, resolvedActor),
ASBite bite => HandleBiteAsync(bite, resolvedActor, inboxUser),
ASBlock block => HandleBlockAsync(block, resolvedActor),
ASCreate create => HandleCreateAsync(create, resolvedActor, inboxUser),
ASDelete delete => HandleDeleteAsync(delete, resolvedActor),
ASEmojiReact react => HandleReactAsync(react, resolvedActor),
ASFollow follow => HandleFollowAsync(follow, resolvedActor),
ASLike like => HandleLikeAsync(like, resolvedActor),
ASMove move => HandleMoveAsync(move, resolvedActor),
ASReject reject => HandleRejectAsync(reject, resolvedActor),
ASUndo undo => HandleUndoAsync(undo, resolvedActor),
ASUnfollow unfollow => HandleUnfollowAsync(unfollow, resolvedActor),
ASUpdate update => HandleUpdateAsync(update, resolvedActor),
// Separated for readability
_ => throw GracefulException.UnprocessableEntity($"Activity type {activity.Type} is unknown")
@ -96,31 +96,31 @@ public class ActivityHandlerService(
private void UpdateInstanceMetadataInBackground(string host, string webDomain)
{
_ = followupTaskSvc.ExecuteTask("UpdateInstanceMetadata", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateInstanceMetadata", async provider =>
{
var instanceSvc = provider.GetRequiredService<InstanceService>();
await instanceSvc.UpdateInstanceStatusAsync(host, webDomain);
});
}
private async Task HandleCreate(ASCreate activity, User actor, User? inboxUser)
private async Task HandleCreateAsync(ASCreate activity, User actor, User? inboxUser)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Create activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, actor.Uri) as ASNote ??
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, actor.Uri) as ASNote ??
throw GracefulException.UnprocessableEntity("Failed to resolve create object");
using (await NoteService.GetNoteProcessLockAsync(activity.Object.Id))
await noteSvc.ProcessNoteAsync(activity.Object, actor, inboxUser);
}
private async Task HandleDelete(ASDelete activity, User resolvedActor)
private async Task HandleDeleteAsync(ASDelete activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Delete activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
switch (activity.Object)
{
@ -155,12 +155,12 @@ public class ActivityHandlerService(
}
}
private async Task HandleFollow(ASFollow activity, User resolvedActor)
private async Task HandleFollowAsync(ASFollow activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Follow activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASActor obj)
throw GracefulException.UnprocessableEntity("Follow activity object is invalid");
@ -171,31 +171,31 @@ public class ActivityHandlerService(
await userSvc.FollowUserAsync(resolvedActor, followee, activity.Id);
}
private async Task HandleUnfollow(ASUnfollow activity, User resolvedActor)
private async Task HandleUnfollowAsync(ASUnfollow activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Unfollow activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASActor obj)
throw GracefulException.UnprocessableEntity("Unfollow activity object is invalid");
await UnfollowAsync(obj, resolvedActor);
}
private async Task HandleAccept(ASAccept activity, User actor)
private async Task HandleAcceptAsync(ASAccept activity, User actor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Accept activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, actor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, actor.Uri);
if (activity.Object is not ASFollow obj)
throw GracefulException.UnprocessableEntity("Accept activity object is invalid");
var relayPrefix = $"https://{config.Value.WebDomain}/activities/follow-relay/";
if (obj.Id.StartsWith(relayPrefix))
{
await relaySvc.HandleAccept(actor, obj.Id[relayPrefix.Length..]);
await relaySvc.HandleAcceptAsync(actor, obj.Id[relayPrefix.Length..]);
return;
}
@ -228,21 +228,21 @@ public class ActivityHandlerService(
await userSvc.AcceptFollowRequestAsync(request);
}
private async Task HandleReject(ASReject activity, User resolvedActor)
private async Task HandleRejectAsync(ASReject activity, User resolvedActor)
{
if (activity.Actor == null)
throw GracefulException.UnprocessableEntity("Reject activity actor was null");
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Reject activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASFollow follow)
throw GracefulException.UnprocessableEntity("Reject activity object is invalid");
var relayPrefix = $"https://{config.Value.WebDomain}/activities/follow-relay/";
if (follow.Id.StartsWith(relayPrefix))
{
await relaySvc.HandleReject(resolvedActor, follow.Id[relayPrefix.Length..]);
await relaySvc.HandleRejectAsync(resolvedActor, follow.Id[relayPrefix.Length..]);
return;
}
@ -281,12 +281,12 @@ public class ActivityHandlerService(
.ExecuteDeleteAsync();
}
private async Task HandleUndo(ASUndo activity, User resolvedActor)
private async Task HandleUndoAsync(ASUndo activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Undo activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
switch (activity.Object)
{
@ -318,14 +318,14 @@ public class ActivityHandlerService(
}
}
private async Task HandleLike(ASLike activity, User resolvedActor)
private async Task HandleLikeAsync(ASLike activity, User resolvedActor)
{
if (resolvedActor.Host == null)
throw GracefulException.UnprocessableEntity("Cannot process like for local actor");
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Like activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASNote note)
{
@ -344,14 +344,14 @@ public class ActivityHandlerService(
}
}
private async Task HandleUpdate(ASUpdate activity, User resolvedActor)
private async Task HandleUpdateAsync(ASUpdate activity, User resolvedActor)
{
if (activity.Actor == null)
throw GracefulException.UnprocessableEntity("Cannot process update for null actor");
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Update activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
switch (activity.Object)
{
@ -370,9 +370,9 @@ public class ActivityHandlerService(
}
}
private async Task HandleBite(ASBite activity, User resolvedActor, User? inboxUser)
private async Task HandleBiteAsync(ASBite activity, User resolvedActor, User? inboxUser)
{
var target = await objectResolver.ResolveObject(activity.Target, resolvedActor.Uri);
var target = await objectResolver.ResolveObjectAsync(activity.Target, resolvedActor.Uri);
var dbBite = target switch
{
ASActor targetActor => new Bite
@ -431,15 +431,15 @@ public class ActivityHandlerService(
await db.AddAsync(dbBite);
await db.SaveChangesAsync();
await notificationSvc.GenerateBiteNotification(dbBite);
await notificationSvc.GenerateBiteNotificationAsync(dbBite);
}
private async Task HandleAnnounce(ASAnnounce activity, User resolvedActor)
private async Task HandleAnnounceAsync(ASAnnounce activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("Announce activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASNote note)
{
logger.LogDebug("Announce activity object is unknown, skipping");
@ -471,14 +471,14 @@ public class ActivityHandlerService(
});
}
private async Task HandleReact(ASEmojiReact activity, User resolvedActor)
private async Task HandleReactAsync(ASEmojiReact activity, User resolvedActor)
{
if (resolvedActor.Host == null)
throw GracefulException.UnprocessableEntity("Cannot process EmojiReact for local actor");
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("EmojiReact activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASNote note)
{
logger.LogDebug("EmojiReact activity object is unknown, skipping");
@ -489,12 +489,12 @@ public class ActivityHandlerService(
await noteSvc.ReactToNoteAsync(note, resolvedActor, activity.Content);
}
private async Task HandleBlock(ASBlock activity, User resolvedActor)
private async Task HandleBlockAsync(ASBlock activity, User resolvedActor)
{
if (activity.Object == null)
throw GracefulException.UnprocessableEntity("EmojiReact activity object was null");
activity.Object = await objectResolver.ResolveObject(activity.Object, resolvedActor.Uri);
activity.Object = await objectResolver.ResolveObjectAsync(activity.Object, resolvedActor.Uri);
if (activity.Object is not ASActor blockee)
{
logger.LogDebug("Block activity object is unknown, skipping");
@ -509,7 +509,7 @@ public class ActivityHandlerService(
await userSvc.BlockUserAsync(resolvedActor, resolvedBlockee);
}
private async Task HandleMove(ASMove activity, User resolvedActor)
private async Task HandleMoveAsync(ASMove activity, User resolvedActor)
{
if (activity.Target.Id is null) throw GracefulException.UnprocessableEntity("Move target must have an ID");
var target = await userResolver.ResolveAsync(activity.Target.Id, EnforceUriFlags);
@ -548,7 +548,7 @@ public class ActivityHandlerService(
db.RemoveRange(followings);
await db.SaveChangesAsync();
_ = followupTaskSvc.ExecuteTask("DecrementInstanceIncomingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("DecrementInstanceIncomingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();

View file

@ -17,7 +17,7 @@ public class ObjectResolver(
IOptions<Config.InstanceSection> config
) : IScopedService
{
public async Task<ASObject?> ResolveObject(
public async Task<ASObject?> ResolveObjectAsync(
ASObjectBase baseObj, string? actorUri = null, int recurse = 5, bool force = false, User? user = null
)
{
@ -25,8 +25,8 @@ public class ObjectResolver(
if (baseObj is ASActivity { Object.IsUnresolved: true } activity && recurse > 0)
{
activity.Object = await ResolveObject(activity.Object, actorUri, --recurse, force);
return await ResolveObject(activity, actorUri, recurse);
activity.Object = await ResolveObjectAsync(activity.Object, actorUri, --recurse, force);
return await ResolveObjectAsync(activity, actorUri, recurse);
}
if (baseObj is ASObject { IsUnresolved: false } obj && !force)
@ -90,12 +90,12 @@ public class ObjectResolver(
}
}
public async IAsyncEnumerable<ASObject> IterateCollection(ASCollection? collection, User? user = null, int pageLimit = 10)
public async IAsyncEnumerable<ASObject> IterateCollectionAsync(ASCollection? collection, User? user = null, int pageLimit = 10)
{
if (collection == null) yield break;
if (collection.IsUnresolved)
collection = await ResolveObject(collection, force: true, user: user) as ASCollection;
collection = await ResolveObjectAsync(collection, force: true, user: user) as ASCollection;
if (collection == null) yield break;
@ -110,7 +110,7 @@ public class ObjectResolver(
while (page != null)
{
if (page.IsUnresolved)
page = await ResolveObject(page, force: true, user: user) as ASCollectionPage;
page = await ResolveObjectAsync(page, force: true, user: user) as ASCollectionPage;
if (page == null) break;

View file

@ -345,7 +345,7 @@ public class UserResolver(
return null;
}
public async Task<User> GetUpdatedUser(User user)
public async Task<User> GetUpdatedUserAsync(User user)
{
if (!user.NeedsUpdate) return user;
@ -358,7 +358,7 @@ public class UserResolver(
try
{
var task = followupTaskSvc.ExecuteTask("UpdateUserAsync", async provider =>
var task = followupTaskSvc.ExecuteTaskAsync("UpdateUserAsync", async provider =>
{
// Get a fresh UserService instance in a new scope
var bgUserSvc = provider.GetRequiredService<UserService>();

View file

@ -22,7 +22,7 @@ public abstract class PluginLoader
private static IEnumerable<IPlugin> Plugins => Loaded.Select(p => p.instance);
public static IEnumerable<Assembly> Assemblies => Loaded.Select(p => p.assembly);
public static async Task LoadPlugins()
public static async Task LoadPluginsAsync()
{
if (!Directory.Exists(DllPath)) return;
var dlls = Directory.EnumerateFiles(DllPath, "*.dll").ToList();
@ -33,7 +33,7 @@ public abstract class PluginLoader
.Cast<LoadedPlugin>()
.ToImmutableList();
await Plugins.Select(i => i.Initialize()).AwaitAllNoConcurrencyAsync();
await Plugins.Select(i => i.InitializeAsync()).AwaitAllNoConcurrencyAsync();
}
public static void RunBuilderHooks(WebApplicationBuilder builder)
@ -74,7 +74,7 @@ public interface IPlugin
public string Name { get; }
public string Version { get; }
public Task Initialize() => Task.CompletedTask;
public Task InitializeAsync() => Task.CompletedTask;
public WebApplicationBuilder BuilderHook(WebApplicationBuilder builder) => builder;
public WebApplication AppHook(WebApplication app) => app;
}

View file

@ -26,7 +26,7 @@ public class AuthenticationMiddleware(
var isBlazorSsr = endpoint?.Metadata.GetMetadata<RootComponentMetadata>() != null;
if (isBlazorSsr)
{
await AuthenticateBlazorSsr(ctx, attribute);
await AuthenticateBlazorSsrAsync(ctx, attribute);
await next(ctx);
return;
}
@ -113,7 +113,7 @@ public class AuthenticationMiddleware(
await next(ctx);
}
private async Task AuthenticateBlazorSsr(HttpContext ctx, AuthenticateAttribute attribute)
private async Task AuthenticateBlazorSsrAsync(HttpContext ctx, AuthenticateAttribute attribute)
{
if (!ctx.Request.Cookies.TryGetValue("admin_session", out var token)) return;

View file

@ -105,7 +105,7 @@ public class ErrorHandlerMiddleware(
RequestId = ctx.TraceIdentifier
};
await WriteResponse(error);
await WriteResponseAsync(error);
}
var level = ce.SuppressLog ? LogLevel.Trace : LogLevel.Debug;
@ -131,11 +131,11 @@ public class ErrorHandlerMiddleware(
RequestId = ctx.TraceIdentifier
};
await WriteResponse(error);
await WriteResponseAsync(error);
logger.LogError("Request encountered an unexpected error: {exception}", e);
}
async Task WriteResponse(ErrorResponse payload)
async Task WriteResponseAsync(ErrorResponse payload)
{
var accept = ctx.Request.Headers.Accept.NotNull().SelectMany(p => p.Split(',')).ToImmutableArray();
var resType = ResponseType.Json;

View file

@ -83,7 +83,7 @@ public class BackfillQueue(int parallelism)
.Where(n => n.Id == current.Id)
.ExecuteUpdateAsync(p => p.SetProperty(n => n.RepliesFetchedAt, DateTime.UtcNow), token);
await foreach (var asNote in objectResolver.IterateCollection(new ASCollection(current.RepliesCollection), user: user)
await foreach (var asNote in objectResolver.IterateCollectionAsync(new ASCollection(current.RepliesCollection), user: user)
.Take(MaxRepliesPerNote)
.Where(p => p.Id != null)
.WithCancellation(token))

View file

@ -26,30 +26,30 @@ public class BackgroundTaskQueue(int parallelism)
switch (jobData)
{
case DriveFileDeleteJobData { Expire: true } driveFileDeleteJob:
await ProcessDriveFileExpire(driveFileDeleteJob, scope, token);
await ProcessDriveFileExpireAsync(driveFileDeleteJob, scope, token);
break;
case DriveFileDeleteJobData driveFileDeleteJob:
await ProcessDriveFileDelete(driveFileDeleteJob, scope, token);
await ProcessDriveFileDeleteAsync(driveFileDeleteJob, scope, token);
break;
case PollExpiryJobData pollExpiryJob:
await ProcessPollExpiry(pollExpiryJob, scope, token);
await ProcessPollExpiryAsync(pollExpiryJob, scope, token);
break;
case MuteExpiryJobData muteExpiryJob:
await ProcessMuteExpiry(muteExpiryJob, scope, token);
await ProcessMuteExpiryAsync(muteExpiryJob, scope, token);
break;
case FilterExpiryJobData filterExpiryJob:
await ProcessFilterExpiry(filterExpiryJob, scope, token);
await ProcessFilterExpiryAsync(filterExpiryJob, scope, token);
break;
case UserDeleteJobData userDeleteJob:
await ProcessUserDelete(userDeleteJob, scope, token);
await ProcessUserDeleteAsync(userDeleteJob, scope, token);
break;
case UserPurgeJobData userPurgeJob:
await ProcessUserPurge(userPurgeJob, scope, token);
await ProcessUserPurgeAsync(userPurgeJob, scope, token);
break;
}
}
private static async Task ProcessDriveFileDelete(
private static async Task ProcessDriveFileDeleteAsync(
DriveFileDeleteJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -101,7 +101,7 @@ public class BackgroundTaskQueue(int parallelism)
}
}
private static async Task ProcessDriveFileExpire(
private static async Task ProcessDriveFileExpireAsync(
DriveFileDeleteJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -114,13 +114,13 @@ public class BackgroundTaskQueue(int parallelism)
var file = await db.DriveFiles.FirstOrDefaultAsync(p => p.Id == jobData.DriveFileId, token);
if (file == null) return;
await drive.ExpireFile(file, token);
await drive.ExpireFileAsync(file, token);
}
[SuppressMessage("ReSharper", "EntityFramework.NPlusOne.IncompleteDataQuery",
Justification = "IncludeCommonProperties()")]
[SuppressMessage("ReSharper", "EntityFramework.NPlusOne.IncompleteDataUsage", Justification = "Same as above")]
private static async Task ProcessPollExpiry(
private static async Task ProcessPollExpiryAsync(
PollExpiryJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -135,7 +135,7 @@ public class BackgroundTaskQueue(int parallelism)
if (note == null) return;
var notificationSvc = scope.GetRequiredService<NotificationService>();
await notificationSvc.GeneratePollEndedNotifications(note);
await notificationSvc.GeneratePollEndedNotificationsAsync(note);
if (note.User.IsLocalUser)
{
var voters = await db.PollVotes.Where(p => p.Note == note && p.User.IsRemoteUser)
@ -156,7 +156,7 @@ public class BackgroundTaskQueue(int parallelism)
}
}
private static async Task ProcessMuteExpiry(
private static async Task ProcessMuteExpiryAsync(
MuteExpiryJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -176,7 +176,7 @@ public class BackgroundTaskQueue(int parallelism)
eventSvc.RaiseUserUnmuted(null, muting.Muter, muting.Mutee);
}
private static async Task ProcessFilterExpiry(
private static async Task ProcessFilterExpiryAsync(
FilterExpiryJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -192,7 +192,7 @@ public class BackgroundTaskQueue(int parallelism)
await db.SaveChangesAsync(token);
}
private static async Task ProcessUserDelete(
private static async Task ProcessUserDeleteAsync(
UserDeleteJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -236,7 +236,7 @@ public class BackgroundTaskQueue(int parallelism)
if (user.IsRemoteUser)
{
await followupTaskSvc.ExecuteTask("UpdateInstanceUserCounter", async provider =>
await followupTaskSvc.ExecuteTaskAsync("UpdateInstanceUserCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -250,7 +250,7 @@ public class BackgroundTaskQueue(int parallelism)
logger.LogDebug("User {id} deleted successfully", jobData.UserId);
}
private static async Task ProcessUserPurge(
private static async Task ProcessUserPurgeAsync(
UserPurgeJobData jobData,
IServiceProvider scope,
CancellationToken token
@ -272,7 +272,7 @@ public class BackgroundTaskQueue(int parallelism)
var fileIdQ = db.DriveFiles.Where(p => p.User == user).Select(p => p.Id);
var fileIdCnt = await fileIdQ.CountAsync(token);
var fileIds = fileIdQ.AsChunkedAsyncEnumerable(50, p => p);
var fileIds = fileIdQ.AsChunkedAsyncEnumerableAsync(50, p => p);
logger.LogDebug("Removing {count} files for user {id}", fileIdCnt, user.Id);
await foreach (var id in fileIds)
{
@ -284,7 +284,7 @@ public class BackgroundTaskQueue(int parallelism)
var noteQ = db.Notes.Where(p => p.User == user).Select(p => p.Id);
var noteCnt = await noteQ.CountAsync(token);
var noteIds = noteQ.AsChunkedAsyncEnumerable(50, p => p);
var noteIds = noteQ.AsChunkedAsyncEnumerableAsync(50, p => p);
logger.LogDebug("Removing {count} notes for user {id}", noteCnt, user.Id);
await foreach (var id in noteIds)
{

View file

@ -50,16 +50,16 @@ public class DeliverQueue(int parallelism)
}
catch
{
_ = followup.ExecuteTask("UpdateInstanceMetadata", async provider =>
_ = followup.ExecuteTaskAsync("UpdateInstanceMetadata", async provider =>
{
var instanceSvc = provider.GetRequiredService<InstanceService>();
await instanceSvc.MarkInstanceAsUnresponsive(jobData.RecipientHost, new Uri(jobData.InboxUrl).Host);
await instanceSvc.MarkInstanceAsUnresponsiveAsync(jobData.RecipientHost, new Uri(jobData.InboxUrl).Host);
});
throw;
}
_ = followup.ExecuteTask("UpdateInstanceMetadata", async provider =>
_ = followup.ExecuteTaskAsync("UpdateInstanceMetadata", async provider =>
{
var instanceSvc = provider.GetRequiredService<InstanceService>();
await instanceSvc.UpdateInstanceStatusAsync(jobData.RecipientHost, new Uri(jobData.InboxUrl).Host,

View file

@ -36,7 +36,7 @@ public class BiteService(
await deliverSvc.DeliverToAsync(activity, user, target.User);
}
await notificationSvc.GenerateBiteNotification(bite);
await notificationSvc.GenerateBiteNotificationAsync(bite);
}
public async Task BiteAsync(User user, Note target)
@ -60,7 +60,7 @@ public class BiteService(
await deliverSvc.DeliverToAsync(activity, user, target.User);
}
await notificationSvc.GenerateBiteNotification(bite);
await notificationSvc.GenerateBiteNotificationAsync(bite);
}
public async Task BiteAsync(User user, User target)
@ -83,6 +83,6 @@ public class BiteService(
await deliverSvc.DeliverToAsync(activity, user, target);
}
await notificationSvc.GenerateBiteNotification(bite);
await notificationSvc.GenerateBiteNotificationAsync(bite);
}
}

View file

@ -29,7 +29,7 @@ public class CronService(IServiceScopeFactory serviceScopeFactory) : BackgroundS
try
{
await using var scope = serviceScopeFactory.CreateAsyncScope();
await task.Invoke(scope.ServiceProvider);
await task.InvokeAsync(scope.ServiceProvider);
}
catch
{
@ -46,7 +46,7 @@ public interface ICronTask
{
public TimeSpan Trigger { get; }
public CronTaskType Type { get; }
public Task Invoke(IServiceProvider provider);
public Task InvokeAsync(IServiceProvider provider);
}
public enum CronTaskType

View file

@ -14,7 +14,7 @@ public class CustomHttpClient : HttpClient, IService<HttpClient>, ISingletonServ
private static readonly HttpMessageHandler InnerHandler = new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.All,
ConnectCallback = FastFallbackHandler.ConnectCallback,
ConnectCallback = FastFallbackHandler.ConnectCallbackAsync,
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5),
PooledConnectionLifetime = TimeSpan.FromMinutes(60)
};
@ -53,9 +53,9 @@ public class CustomHttpClient : HttpClient, IService<HttpClient>, ISingletonServ
private bool AllowLocalIPv4 => Security?.CurrentValue.AllowLocalIPv4 ?? false;
private bool AllowLocalIPv6 => Security?.CurrentValue.AllowLocalIPv6 ?? false;
public async ValueTask<Stream> ConnectCallback(SocketsHttpConnectionContext context, CancellationToken token)
public async ValueTask<Stream> ConnectCallbackAsync(SocketsHttpConnectionContext context, CancellationToken token)
{
var sortedRecords = await GetSortedAddresses(context.DnsEndPoint.Host, token);
var sortedRecords = await GetSortedAddressesAsync(context.DnsEndPoint.Host, token);
var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(token);
var tasks = new List<Task<(NetworkStream? stream, Exception? exception)>>();
@ -91,7 +91,7 @@ public class CustomHttpClient : HttpClient, IService<HttpClient>, ISingletonServ
delayCts.CancelAfter(connectionBackoff * i);
var task = AttemptConnection(record, context.DnsEndPoint.Port, linkedToken.Token, delayCts.Token);
var task = AttemptConnectionAsync(record, context.DnsEndPoint.Port, linkedToken.Token, delayCts.Token);
tasks.Add(task);
var nextDelayCts = CancellationTokenSource.CreateLinkedTokenSource(linkedToken.Token);
@ -126,7 +126,7 @@ public class CustomHttpClient : HttpClient, IService<HttpClient>, ISingletonServ
return stream;
}
private static async Task<(NetworkStream? stream, Exception? exception)> AttemptConnection(
private static async Task<(NetworkStream? stream, Exception? exception)> AttemptConnectionAsync(
IPAddress address, int port, CancellationToken token, CancellationToken delayToken
)
{
@ -152,7 +152,7 @@ public class CustomHttpClient : HttpClient, IService<HttpClient>, ISingletonServ
}
}
private static async Task<List<IPAddress>> GetSortedAddresses(string hostname, CancellationToken token)
private static async Task<List<IPAddress>> GetSortedAddressesAsync(string hostname, CancellationToken token)
{
// This method abuses DNS ordering and LINQ a bit. We can normally assume that addresses will be provided in
// the order the system wants to use. GroupBy will return its groups *in the order they're discovered*. Meaning,

View file

@ -29,7 +29,7 @@ public class DriveService(
ImageProcessor imageProcessor
) : IScopedService
{
public async Task<DriveFile?> StoreFile(
public async Task<DriveFile?> StoreFileAsync(
string? uri, User user, bool sensitive, string? description = null, string? mimeType = null,
bool logExisting = true, bool forceStore = false, bool skipImageProcessing = false
)
@ -120,7 +120,7 @@ public class DriveService(
var stream = await GetSafeStreamOrNullAsync(input, maxLength, res.Content.Headers.ContentLength);
try
{
return await StoreFile(stream, user, request, skipImageProcessing);
return await StoreFileAsync(stream, user, request, skipImageProcessing);
}
catch (Exception e)
{
@ -160,7 +160,7 @@ public class DriveService(
}
}
public async Task<DriveFile> StoreFile(
public async Task<DriveFile> StoreFileAsync(
Stream input, User user, DriveFileCreationRequest request, bool skipImageProcessing = false
)
{
@ -283,9 +283,9 @@ public class DriveService(
blurhash = res.Blurhash;
var processed = await res.RequestedFormats
.Select(p => ProcessAndStoreFileVersion(p.Key, p.Value, request.Filename))
.Select(p => ProcessAndStoreFileVersionAsync(p.Key, p.Value, request.Filename))
.AwaitAllNoConcurrencyAsync()
.ContinueWithResult(p => p.ToImmutableArray());
.ContinueWithResultAsync(p => p.ToImmutableArray());
original = processed.FirstOrDefault(p => p?.format.Key == KeyEnum.Original) ??
throw new Exception("Image processing didn't result in an original version");
@ -359,11 +359,11 @@ public class DriveService(
)
{
var accessKey = GenerateAccessKey(extension: Path.GetExtension(request.Filename).TrimStart('.')).TrimStart('-');
var url = await StoreFileVersion(input, accessKey, request.Filename, request.MimeType);
var url = await StoreFileVersionAsync(input, accessKey, request.Filename, request.MimeType);
return (Stub, accessKey, url);
}
private async Task<ImageVerTriple?> ProcessAndStoreFileVersion(
private async Task<ImageVerTriple?> ProcessAndStoreFileVersionAsync(
ImageVersion version, Func<Task<Stream>>? encode, string fileName
)
{
@ -387,7 +387,7 @@ public class DriveService(
}
fileName = GenerateDerivedFileName(fileName, version.Format.Extension);
var url = await StoreFileVersion(stream, accessKey, fileName, version.Format.MimeType);
var url = await StoreFileVersionAsync(stream, accessKey, fileName, version.Format.MimeType);
return (version, accessKey, url);
}
finally
@ -397,17 +397,17 @@ public class DriveService(
}
}
private Task<string> StoreFileVersion(Stream stream, string accessKey, string fileName, string mimeType)
private Task<string> StoreFileVersionAsync(Stream stream, string accessKey, string fileName, string mimeType)
{
return storageConfig.Value.Provider switch
{
Enums.FileStorage.Local => StoreFileVersionLocalStorage(stream, accessKey),
Enums.FileStorage.ObjectStorage => StoreFileVersionObjectStorage(stream, accessKey, fileName, mimeType),
Enums.FileStorage.Local => StoreFileVersionLocalStorageAsync(stream, accessKey),
Enums.FileStorage.ObjectStorage => StoreFileVersionObjectStorageAsync(stream, accessKey, fileName, mimeType),
_ => throw new ArgumentOutOfRangeException()
};
}
private async Task<string> StoreFileVersionLocalStorage(Stream stream, string filename)
private async Task<string> StoreFileVersionLocalStorageAsync(Stream stream, string filename)
{
var pathBase = storageConfig.Value.Local?.Path ??
throw new Exception("Local storage path cannot be null");
@ -419,7 +419,7 @@ public class DriveService(
return $"https://{instanceConfig.Value.WebDomain}/files/{filename}";
}
private async Task<string> StoreFileVersionObjectStorage(
private async Task<string> StoreFileVersionObjectStorageAsync(
Stream stream, string accessKey, string filename, string mimeType
)
{
@ -428,18 +428,18 @@ public class DriveService(
return storageSvc.GetFilePublicUrl(accessKey).AbsoluteUri;
}
public async Task RemoveFile(DriveFile file)
public async Task RemoveFileAsync(DriveFile file)
{
await RemoveFile(file.Id);
await RemoveFileAsync(file.Id);
}
public async Task RemoveFile(string fileId)
public async Task RemoveFileAsync(string fileId)
{
var job = new DriveFileDeleteJobData { DriveFileId = fileId, Expire = false };
await queueSvc.BackgroundTaskQueue.EnqueueAsync(job);
}
public async Task ExpireFile(DriveFile file, CancellationToken token = default)
public async Task ExpireFileAsync(DriveFile file, CancellationToken token = default)
{
if (file is not { UserHost: not null, Uri: not null, IsLink: false }) return;
@ -489,10 +489,10 @@ public class DriveService(
}
}
public async Task<HashSet<string>> GetAllFileNamesFromObjectStorage()
public async Task<HashSet<string>> GetAllFileNamesFromObjectStorageAsync()
{
return storageConfig.Value.ObjectStorage?.Bucket != null
? await storageSvc.EnumerateFilesAsync().ToArrayAsync().AsTask().ContinueWithResult(p => p.ToHashSet())
? await storageSvc.EnumerateFilesAsync().ToArrayAsync().AsTask().ContinueWithResultAsync(p => p.ToHashSet())
: [];
}

View file

@ -35,7 +35,7 @@ public class EmojiImportService(
{
public static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
public async Task<EmojiZip> Parse(Stream zipStream)
public async Task<EmojiZip> ParseAsync(Stream zipStream)
{
var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
@ -62,7 +62,7 @@ public class EmojiImportService(
}
}
public async Task Import(EmojiZip zip)
public async Task ImportAsync(EmojiZip zip)
{
using var archive = zip.Archive;
var contentTypeProvider = new FileExtensionContentTypeProvider();
@ -91,7 +91,7 @@ public class EmojiImportService(
try
{
await emojiSvc.CreateEmojiFromStream(
await emojiSvc.CreateEmojiFromStreamAsync(
buffer,
name,
mimeType,

View file

@ -26,7 +26,7 @@ public partial class EmojiService(
o.PoolInitialFill = 5;
});
public async Task<Emoji> CreateEmojiFromStream(
public async Task<Emoji> CreateEmojiFromStreamAsync(
Stream input, string fileName, string mimeType, List<string>? aliases = null,
string? category = null
)
@ -43,7 +43,7 @@ public partial class EmojiService(
MimeType = mimeType,
IsSensitive = false
};
var driveFile = await driveSvc.StoreFile(input, user, request, true);
var driveFile = await driveSvc.StoreFileAsync(input, user, request, true);
var id = IdHelpers.GenerateSnowflakeId();
var emoji = new Emoji
@ -67,10 +67,10 @@ public partial class EmojiService(
return emoji;
}
public async Task<Emoji> CloneEmoji(Emoji existing)
public async Task<Emoji> CloneEmojiAsync(Emoji existing)
{
var user = await sysUserSvc.GetInstanceActorAsync();
var driveFile = await driveSvc.StoreFile(existing.OriginalUrl, user, false, forceStore: true,
var driveFile = await driveSvc.StoreFileAsync(existing.OriginalUrl, user, false, forceStore: true,
skipImageProcessing: false) ??
throw new Exception("Error storing emoji file");
@ -93,13 +93,13 @@ public partial class EmojiService(
return emoji;
}
public async Task DeleteEmoji(string id)
public async Task DeleteEmojiAsync(string id)
{
var emoji = await db.Emojis.FirstOrDefaultAsync(p => p.Host == null && p.Id == id);
if (emoji == null) throw GracefulException.NotFound("Emoji not found");
var driveFile = await db.DriveFiles.FirstOrDefaultAsync(p => p.Url == emoji.OriginalUrl);
if (driveFile != null) await driveSvc.RemoveFile(driveFile.Id);
if (driveFile != null) await driveSvc.RemoveFileAsync(driveFile.Id);
db.Remove(emoji);
await db.SaveChangesAsync();
@ -150,7 +150,7 @@ public partial class EmojiService(
private const string MisskeyHeart = "\u2764";
private const string EmojiVersionSelector = "\ufe0f";
public async Task<string> ResolveEmojiName(string name, string? host)
public async Task<string> ResolveEmojiNameAsync(string name, string? host)
{
if (name == MisskeyHeart)
return name + EmojiVersionSelector;
@ -177,7 +177,7 @@ public partial class EmojiService(
return hit.Host == null ? $":{hit.Name}:" : $":{hit.Name}@{hit.Host}:";
}
public async Task<Emoji?> ResolveEmoji(string fqn)
public async Task<Emoji?> ResolveEmojiAsync(string fqn)
{
if (!fqn.StartsWith(':')) return null;
var split = fqn.Trim(':').Split('@');
@ -187,7 +187,7 @@ public partial class EmojiService(
return await db.Emojis.FirstOrDefaultAsync(p => p.Host == host && p.Name == name);
}
public async Task<List<Emoji>> ResolveEmoji(IEnumerable<MfmNodeTypes.MfmNode> nodes)
public async Task<List<Emoji>> ResolveEmojiAsync(IEnumerable<MfmNodeTypes.MfmNode> nodes)
{
var list = new List<MfmNodeTypes.MfmEmojiCodeNode>();
ResolveChildren(nodes, ref list);
@ -206,7 +206,7 @@ public partial class EmojiService(
}
}
public async Task<Emoji?> UpdateLocalEmoji(
public async Task<Emoji?> UpdateLocalEmojiAsync(
string id, string? name, List<string>? aliases, string? category, string? license, bool? sensitive
)
{

View file

@ -9,7 +9,7 @@ public class FollowupTaskService(
{
public AsyncLocal<bool> IsBackgroundWorker { get; } = new();
public Task ExecuteTask(string taskName, Func<IServiceProvider, Task> work)
public Task ExecuteTaskAsync(string taskName, Func<IServiceProvider, Task> work)
{
return Task.Run(async () =>
{

View file

@ -48,6 +48,6 @@ public class ImportExportService(
}
}
await QueryableTimelineExtensions.ResetHeuristic(user, cacheSvc);
await QueryableTimelineExtensions.ResetHeuristicAsync(user, cacheSvc);
}
}

View file

@ -142,7 +142,7 @@ public class InstanceService(
await db.SaveChangesAsync();
}
public async Task MarkInstanceAsUnresponsive(string host, string webDomain)
public async Task MarkInstanceAsUnresponsiveAsync(string host, string webDomain)
{
var instance = await GetUpdatedInstanceMetadataAsync(host, webDomain);
instance.LatestRequestSentAt = DateTime.UtcNow;

View file

@ -7,29 +7,29 @@ namespace Iceshrimp.Backend.Core.Services;
public class MetaService([FromKeyedServices("cache")] DatabaseContext db) : IScopedService
{
public async Task<T> Get<T>(Meta<T> meta) => meta.ConvertGet(await Fetch(meta.Key));
public async Task<T> GetAsync<T>(Meta<T> meta) => meta.ConvertGet(await FetchAsync(meta.Key));
public async Task<T[]> GetMany<T>(params Meta<T>[] entities)
public async Task<T[]> GetManyAsync<T>(params Meta<T>[] entities)
{
var res = await FetchMany(entities.Select(p => p.Key));
var res = await FetchManyAsync(entities.Select(p => p.Key));
return entities.Select(p => p.ConvertGet(res.GetValueOrDefault(p.Key, null))).ToArray();
}
public async Task EnsureSet<T>(Meta<T> meta, T value) => await EnsureSet(meta, () => value);
public async Task EnsureSetAsync<T>(Meta<T> meta, T value) => await EnsureSetAsync(meta, () => value);
public async Task EnsureSet<T>(Meta<T> meta, Func<T> value)
public async Task EnsureSetAsync<T>(Meta<T> meta, Func<T> value)
{
if (await Fetch(meta.Key) != null) return;
await Set(meta, value());
if (await FetchAsync(meta.Key) != null) return;
await SetAsync(meta, value());
}
public async Task EnsureSet<T>(Meta<T> meta, Func<Task<T>> value)
public async Task EnsureSetAsync<T>(Meta<T> meta, Func<Task<T>> value)
{
if (await Fetch(meta.Key) != null) return;
await Set(meta, await value());
if (await FetchAsync(meta.Key) != null) return;
await SetAsync(meta, await value());
}
public async Task EnsureSet<T>(IReadOnlyList<Meta<T>> metas, Func<List<T>> values)
public async Task EnsureSetAsync<T>(IReadOnlyList<Meta<T>> metas, Func<List<T>> values)
{
if (await db.MetaStore.CountAsync(p => metas.Select(m => m.Key).Contains(p.Key)) == metas.Count)
return;
@ -39,22 +39,22 @@ public class MetaService([FromKeyedServices("cache")] DatabaseContext db) : ISco
throw new Exception("Metas count doesn't match values count");
for (var i = 0; i < metas.Count; i++)
await Set(metas[i], resolvedValues[i]);
await SetAsync(metas[i], resolvedValues[i]);
}
public async Task Set<T>(Meta<T> meta, T value) => await Set(meta.Key, meta.ConvertSet(value));
public async Task SetAsync<T>(Meta<T> meta, T value) => await SetAsync(meta.Key, meta.ConvertSet(value));
// Ensures the table is in memory (we could use pg_prewarm for this but that extension requires superuser privileges to install)
public async Task WarmupCache() => await db.MetaStore.ToListAsync();
public async Task WarmupCacheAsync() => await db.MetaStore.ToListAsync();
private async Task<string?> Fetch(string key) =>
private async Task<string?> FetchAsync(string key) =>
await db.MetaStore.Where(p => p.Key == key).Select(p => p.Value).FirstOrDefaultAsync();
private async Task<Dictionary<string, string?>> FetchMany(IEnumerable<string> keys) =>
private async Task<Dictionary<string, string?>> FetchManyAsync(IEnumerable<string> keys) =>
await db.MetaStore.Where(p => keys.Contains(p.Key))
.ToDictionaryAsync(p => p.Key, p => p.Value);
private async Task Set(string key, string? value)
private async Task SetAsync(string key, string? value)
{
var entity = await db.MetaStore.FirstOrDefaultAsync(p => p.Key == key);
if (entity != null)

View file

@ -101,7 +101,7 @@ public class NoteService(
{
logger.LogDebug("Creating note for user {id}", data.User.Id);
await policySvc.Initialize();
await policySvc.InitializeAsync();
// @formatter:off
if (data.User.IsRemoteUser && policySvc.ShouldReject(data, out var policy))
@ -215,7 +215,7 @@ public class NoteService(
if (data.Emoji == null && data.User.IsLocalUser && nodes != null)
{
data.Emoji = (await emojiSvc.ResolveEmoji(nodes)).Select(p => p.Id).ToList();
data.Emoji = (await emojiSvc.ResolveEmojiAsync(nodes)).Select(p => p.Id).ToList();
}
List<string> visibleUserIds = [];
@ -295,7 +295,7 @@ public class NoteService(
await db.AddAsync(data.Poll);
note.HasPoll = true;
await EnqueuePollExpiryTask(data.Poll);
await EnqueuePollExpiryTaskAsync(data.Poll);
}
logger.LogDebug("Inserting created note {noteId} for user {userId} into the database", note.Id, data.User.Id);
@ -304,15 +304,15 @@ public class NoteService(
await db.AddAsync(note);
await db.SaveChangesAsync();
eventSvc.RaiseNotePublished(this, note);
await notificationSvc.GenerateMentionNotifications(note, mentionedLocalUserIds);
await notificationSvc.GenerateReplyNotifications(note, mentionedLocalUserIds);
await notificationSvc.GenerateRenoteNotification(note);
await notificationSvc.GenerateMentionNotificationsAsync(note, mentionedLocalUserIds);
await notificationSvc.GenerateReplyNotificationsAsync(note, mentionedLocalUserIds);
await notificationSvc.GenerateRenoteNotificationAsync(note);
logger.LogDebug("Note {id} created successfully", note.Id);
if (data.Uri != null || data.Url != null)
{
_ = followupTaskSvc.ExecuteTask("ResolvePendingReplyRenoteTargets", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("ResolvePendingReplyRenoteTargets", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var count = 0;
@ -372,7 +372,7 @@ public class NoteService(
if (data.User.IsRemoteUser)
{
_ = followupTaskSvc.ExecuteTask("UpdateInstanceNoteCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateInstanceNoteCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -510,7 +510,7 @@ public class NoteService(
if (note.User.IsLocalUser && nodes != null)
{
data.Emoji = (await emojiSvc.ResolveEmoji(nodes)).Select(p => p.Id).ToList();
data.Emoji = (await emojiSvc.ResolveEmojiAsync(nodes)).Select(p => p.Id).ToList();
}
if (data.Emoji != null && !note.Emojis.IsEquivalent(data.Emoji))
@ -576,7 +576,7 @@ public class NoteService(
if (note.Poll.ExpiresAt != poll.ExpiresAt)
{
note.Poll.ExpiresAt = poll.ExpiresAt;
await EnqueuePollExpiryTask(note.Poll);
await EnqueuePollExpiryTaskAsync(note.Poll);
}
if (!note.Poll.Choices.SequenceEqual(poll.Choices) || note.Poll.Multiple != poll.Multiple)
@ -617,7 +617,7 @@ public class NoteService(
poll.Votes = poll.Choices.Select(_ => 0).ToList();
await db.AddAsync(poll);
await EnqueuePollExpiryTask(poll);
await EnqueuePollExpiryTaskAsync(poll);
}
note.HasPoll = true;
@ -654,8 +654,8 @@ public class NoteService(
if (!isEdit) return note;
await notificationSvc.GenerateMentionNotifications(note, mentionedLocalUserIds);
await notificationSvc.GenerateEditNotifications(note);
await notificationSvc.GenerateMentionNotificationsAsync(note, mentionedLocalUserIds);
await notificationSvc.GenerateEditNotificationsAsync(note);
if (note.LocalOnly || note.User.IsRemoteUser) return note;
@ -680,7 +680,7 @@ public class NoteService(
{
if (note.User.Uri != null)
{
_ = followupTaskSvc.ExecuteTask("UpdateInstanceNoteCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateInstanceNoteCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -842,7 +842,7 @@ public class NoteService(
};
await db.AddAsync(vote);
await db.SaveChangesAsync();
await pollSvc.RegisterPollVote(vote, poll, reply);
await pollSvc.RegisterPollVoteAsync(vote, poll, reply);
return null;
}
@ -1062,7 +1062,7 @@ public class NoteService(
tags = tags.Distinct().ToList();
_ = followupTaskSvc.ExecuteTask("UpdateHashtagsTable", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateHashtagsTable", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var existing = await bgDb.Hashtags.Where(p => tags.Contains(p.Name)).Select(p => p.Name).ToListAsync();
@ -1119,7 +1119,7 @@ public class NoteService(
var result = await attachments
.OfType<ASDocument>()
.Take(10)
.Select(p => driveSvc.StoreFile(p.Url?.Id, user, p.Sensitive ?? sensitive, p.Description,
.Select(p => driveSvc.StoreFileAsync(p.Url?.Id, user, p.Sensitive ?? sensitive, p.Description,
p.MediaType, logExisting))
.AwaitAllNoConcurrencyAsync();
@ -1289,7 +1289,7 @@ public class NoteService(
}
eventSvc.RaiseNoteLiked(this, note, user);
await notificationSvc.GenerateLikeNotification(note, user);
await notificationSvc.GenerateLikeNotificationAsync(note, user);
return true;
}
@ -1445,12 +1445,12 @@ public class NoteService(
var collection = actor.Featured;
if (collection == null) return;
if (collection.IsUnresolved)
collection = await objectResolver.ResolveObject(collection, force: true) as ASOrderedCollection;
collection = await objectResolver.ResolveObjectAsync(collection, force: true) as ASOrderedCollection;
if (collection is not { Items: not null }) return;
// ReSharper disable once EntityFramework.UnsupportedServerSideFunctionCall
var followingUser = await db.Users.FirstOrDefaultAsync(p => p.IsFollowing(user));
var notes = await objectResolver.IterateCollection(collection)
var notes = await objectResolver.IterateCollectionAsync(collection)
.Take(10)
.Where(p => p.Id != null)
.Select(p => ResolveNoteAsync(p.Id!, null, followingUser, true))
@ -1480,7 +1480,7 @@ public class NoteService(
await db.SaveChangesAsync();
}
private async Task EnqueuePollExpiryTask(Poll poll)
private async Task EnqueuePollExpiryTaskAsync(Poll poll)
{
// Skip polls without expiry date
if (!poll.ExpiresAt.HasValue) return;
@ -1496,7 +1496,7 @@ public class NoteService(
if (note.IsPureRenote)
throw GracefulException.BadRequest("Cannot react to a pure renote");
name = await emojiSvc.ResolveEmojiName(name, user.Host);
name = await emojiSvc.ResolveEmojiNameAsync(name, user.Host);
if (await db.NoteReactions.AnyAsync(p => p.Note == note && p.User == user && p.Reaction == name))
return (name, false);
@ -1515,7 +1515,7 @@ public class NoteService(
await db.AddAsync(reaction);
await db.SaveChangesAsync();
eventSvc.RaiseNoteReacted(this, reaction);
await notificationSvc.GenerateReactionNotification(reaction);
await notificationSvc.GenerateReactionNotificationAsync(reaction);
// @formatter:off
await db.Database.ExecuteSqlAsync($"""UPDATE "note" SET "reactions" = jsonb_set("reactions", ARRAY[{name}], (COALESCE("reactions"->>{name}, '0')::int + 1)::text::jsonb) WHERE "id" = {note.Id}""");
@ -1523,7 +1523,7 @@ public class NoteService(
if (user.IsLocalUser)
{
var emoji = await emojiSvc.ResolveEmoji(reaction.Reaction);
var emoji = await emojiSvc.ResolveEmojiAsync(reaction.Reaction);
var activity = activityRenderer.RenderReact(reaction, emoji);
await deliverSvc.DeliverToConditionalAsync(activity, user, note);
}
@ -1542,7 +1542,7 @@ public class NoteService(
public async Task<(string name, bool success)> RemoveReactionFromNoteAsync(Note note, User user, string name)
{
name = await emojiSvc.ResolveEmojiName(name, user.Host);
name = await emojiSvc.ResolveEmojiNameAsync(name, user.Host);
var reaction =
await db.NoteReactions.FirstOrDefaultAsync(p => p.Note == note && p.User == user && p.Reaction == name);
@ -1558,7 +1558,7 @@ public class NoteService(
if (user.IsLocalUser)
{
var actor = userRenderer.RenderLite(user);
var emoji = await emojiSvc.ResolveEmoji(reaction.Reaction);
var emoji = await emojiSvc.ResolveEmojiAsync(reaction.Reaction);
var activity = activityRenderer.RenderUndo(actor, activityRenderer.RenderReact(reaction, emoji));
await deliverSvc.DeliverToConditionalAsync(activity, user, note);
}

View file

@ -12,7 +12,7 @@ public class NotificationService(
EventService eventSvc
) : IScopedService
{
public async Task GenerateMentionNotifications(Note note, IReadOnlyCollection<string> mentionedLocalUserIds)
public async Task GenerateMentionNotificationsAsync(Note note, IReadOnlyCollection<string> mentionedLocalUserIds)
{
if (mentionedLocalUserIds.Count == 0) return;
@ -40,7 +40,7 @@ public class NotificationService(
eventSvc.RaiseNotifications(this, notifications);
}
public async Task GenerateReplyNotifications(Note note, IReadOnlyCollection<string> mentionedLocalUserIds)
public async Task GenerateReplyNotificationsAsync(Note note, IReadOnlyCollection<string> mentionedLocalUserIds)
{
var users = mentionedLocalUserIds
.Concat(note.VisibleUserIds)
@ -84,7 +84,7 @@ public class NotificationService(
[SuppressMessage("ReSharper", "EntityFramework.UnsupportedServerSideFunctionCall",
Justification = "Projectable functions are very much translatable")]
public async Task GenerateEditNotifications(Note note)
public async Task GenerateEditNotificationsAsync(Note note)
{
var notifications = await db.Users
.Where(p => p.IsLocalUser && p != note.User && p.HasInteractedWith(note))
@ -107,7 +107,7 @@ public class NotificationService(
eventSvc.RaiseNotifications(this, notifications);
}
public async Task GenerateLikeNotification(Note note, User user)
public async Task GenerateLikeNotificationAsync(Note note, User user)
{
if (note.UserHost != null) return;
if (note.User == user) return;
@ -127,7 +127,7 @@ public class NotificationService(
eventSvc.RaiseNotification(this, notification);
}
public async Task GenerateReactionNotification(NoteReaction reaction)
public async Task GenerateReactionNotificationAsync(NoteReaction reaction)
{
if (reaction.Note.User.IsRemoteUser) return;
if (reaction.Note.User == reaction.User) return;
@ -148,7 +148,7 @@ public class NotificationService(
eventSvc.RaiseNotification(this, notification);
}
public async Task GenerateFollowNotification(User follower, User followee)
public async Task GenerateFollowNotificationAsync(User follower, User followee)
{
if (followee.IsRemoteUser) return;
@ -167,7 +167,7 @@ public class NotificationService(
eventSvc.RaiseUserFollowed(this, follower, followee);
}
public async Task GenerateFollowRequestReceivedNotification(FollowRequest followRequest)
public async Task GenerateFollowRequestReceivedNotificationAsync(FollowRequest followRequest)
{
if (followRequest.FolloweeHost != null) return;
@ -186,7 +186,7 @@ public class NotificationService(
eventSvc.RaiseNotification(this, notification);
}
public async Task GenerateFollowRequestAcceptedNotification(FollowRequest followRequest)
public async Task GenerateFollowRequestAcceptedNotificationAsync(FollowRequest followRequest)
{
if (followRequest.FollowerHost != null) return;
if (!followRequest.Followee.IsLocked) return;
@ -206,7 +206,7 @@ public class NotificationService(
eventSvc.RaiseUserFollowed(this, followRequest.Follower, followRequest.Followee);
}
public async Task GenerateBiteNotification(Bite bite)
public async Task GenerateBiteNotificationAsync(Bite bite)
{
var notification = new Notification
{
@ -225,7 +225,7 @@ public class NotificationService(
eventSvc.RaiseNotification(this, notification);
}
public async Task GeneratePollEndedNotifications(Note note)
public async Task GeneratePollEndedNotificationsAsync(Note note)
{
var notifications = await db.PollVotes
.Where(p => p.Note == note)
@ -264,7 +264,7 @@ public class NotificationService(
}
[SuppressMessage("ReSharper", "EntityFramework.UnsupportedServerSideFunctionCall", Justification = "Projectables")]
public async Task GenerateRenoteNotification(Note note)
public async Task GenerateRenoteNotificationAsync(Note note)
{
if (note.Renote is not { UserHost: null }) return;
if (note.RenoteUserId == note.UserId) return;

View file

@ -28,24 +28,24 @@ public class PluginStore<TPlugin, TData>(DatabaseContext db) where TPlugin : IPl
private readonly IPlugin _plugin = new TPlugin();
/// <exception cref="SerializationException"></exception>
public async Task<TData> GetData()
public async Task<TData> GetDataAsync()
{
return (await GetOrCreateData()).data;
return (await GetOrCreateDataAsync()).data;
}
/// <exception cref="SerializationException"></exception>
public async Task<TResult> GetData<TResult>(Expression<Func<TData, TResult>> predicate)
public async Task<TResult> GetDataAsync<TResult>(Expression<Func<TData, TResult>> predicate)
{
var (_, data) = await GetOrCreateData();
var (_, data) = await GetOrCreateDataAsync();
return predicate.Compile().Invoke(data);
}
/// <exception cref="SerializationException"></exception>
public async Task UpdateData(Action<TData> updateAction)
public async Task UpdateDataAsync(Action<TData> updateAction)
{
using (await PluginStoreHelpers.KeyedLocker.LockAsync(_plugin.Id))
{
var (entry, data) = await GetOrCreateData();
var (entry, data) = await GetOrCreateDataAsync();
updateAction(data);
UpdateEntryIfModified(entry, data);
await db.SaveChangesAsync();
@ -60,7 +60,7 @@ public class PluginStore<TPlugin, TData>(DatabaseContext db) where TPlugin : IPl
}
/// <exception cref="SerializationException"></exception>
private async Task<(PluginStoreEntry entry, TData data)> GetOrCreateData()
private async Task<(PluginStoreEntry entry, TData data)> GetOrCreateDataAsync()
{
TData data;
var entry = await db.PluginStore.FirstOrDefaultAsync(p => p.Id == _plugin.Id);

View file

@ -21,7 +21,7 @@ public class PolicyService(IServiceScopeFactory scopeFactory) : ISingletonServic
private Type[] _policyTypes = [];
private Type[] _policyConfigurationTypes = [];
public async Task Initialize()
public async Task InitializeAsync()
{
if (_initialized) return;
_initialized = true;
@ -35,12 +35,12 @@ public class PolicyService(IServiceScopeFactory scopeFactory) : ISingletonServic
_policyTypes.Contains(t)))
.ToArray();
await Update();
await UpdateAsync();
}
public async Task Update()
public async Task UpdateAsync()
{
if (!_initialized) await Initialize();
if (!_initialized) await InitializeAsync();
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
@ -95,9 +95,9 @@ public class PolicyService(IServiceScopeFactory scopeFactory) : ISingletonServic
foreach (var hook in hooks) hook.Apply(note, actor);
}
public async Task<Type?> GetConfigurationType(string name)
public async Task<Type?> GetConfigurationTypeAsync(string name)
{
await Initialize();
await InitializeAsync();
var type = _policyTypes.FirstOrDefault(p => p.Name == name);
return _policyConfigurationTypes
.FirstOrDefault(p => p.GetInterfaces()
@ -106,17 +106,17 @@ public class PolicyService(IServiceScopeFactory scopeFactory) : ISingletonServic
type);
}
public async Task<IPolicyConfiguration?> GetConfiguration(string name, string? data)
public async Task<IPolicyConfiguration?> GetConfigurationAsync(string name, string? data)
{
var type = await GetConfigurationType(name);
var type = await GetConfigurationTypeAsync(name);
if (type == null) return null;
if (data == null) return (IPolicyConfiguration?)Activator.CreateInstance(type);
return (IPolicyConfiguration?)JsonSerializer.Deserialize(data, type, JsonSerialization.Options);
}
public async Task<List<string>> GetAvailablePolicies()
public async Task<List<string>> GetAvailablePoliciesAsync()
{
await Initialize();
await InitializeAsync();
return _policyTypes.Select(p => p.Name).ToList();
}
}

View file

@ -12,7 +12,7 @@ public class PollService(
ActivityPub.ActivityDeliverService deliverSvc
) : IScopedService
{
public async Task RegisterPollVote(PollVote pollVote, Poll poll, Note note, bool updateVotersCount = true)
public async Task RegisterPollVoteAsync(PollVote pollVote, Poll poll, Note note, bool updateVotersCount = true)
{
await db.Database
.ExecuteSqlAsync($"""UPDATE "poll" SET "votes"[{pollVote.Choice + 1}] = "votes"[{pollVote.Choice + 1}] + 1 WHERE "noteId" = {note.Id}""");

View file

@ -26,12 +26,12 @@ public class PushService(
{
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
eventSvc.Notification += MastodonPushHandler;
eventSvc.Notification += MastodonPushHandlerAsync;
//TODO: eventSvc.Notification += WebPushHandler;
return Task.CompletedTask;
}
private async void MastodonPushHandler(object? _, Notification notification)
private async void MastodonPushHandlerAsync(object? _, Notification notification)
{
try
{
@ -103,7 +103,7 @@ public class PushService(
body = body.Truncate(137).TrimEnd() + "...";
var meta = scope.ServiceProvider.GetRequiredService<MetaService>();
var (priv, pub) = await meta.GetMany(MetaEntity.VapidPrivateKey, MetaEntity.VapidPublicKey);
var (priv, pub) = await meta.GetManyAsync(MetaEntity.VapidPrivateKey, MetaEntity.VapidPublicKey);
var client = new WebPushClient(httpClient);
client.SetVapidDetails(new VapidDetails($"https://{config.Value.WebDomain}", pub, priv));

View file

@ -53,19 +53,19 @@ public class QueueService(
logger.LogInformation("Queue shutdown complete.");
});
_ = Task.Run(ExecuteHealthchecksWorker, token);
await Task.Run(ExecuteBackgroundWorkers, tokenSource.Token);
_ = Task.Run(ExecuteHealthchecksWorkerAsync, token);
await Task.Run(ExecuteBackgroundWorkersAsync, tokenSource.Token);
return;
async Task? ExecuteBackgroundWorkers()
async Task? ExecuteBackgroundWorkersAsync()
{
var tasks = _queues.Select(queue => queue.ExecuteAsync(scopeFactory, tokenSource.Token, queueToken));
await Task.WhenAll(tasks);
await tokenSource.CancelAsync();
}
async Task ExecuteHealthchecksWorker()
async Task ExecuteHealthchecksWorkerAsync()
{
var first = true;
while (!token.IsCancellationRequested)
@ -261,7 +261,7 @@ public abstract class PostgresJobQueue<T>(
await using var scope = GetScope();
await using var db = GetDbContext(scope);
var queuedCount = await db.GetJobQueuedCount(name, token);
var queuedCount = await db.GetJobQueuedCountAsync(name, token);
var actualParallelism = Math.Min(_semaphore.CurrentCount, queuedCount);
if (actualParallelism == 0)
@ -351,7 +351,7 @@ public abstract class PostgresJobQueue<T>(
}
var tokenSource = new CancellationTokenSource();
await ScheduleDelayedEvent(tokenSource.Token);
await ScheduleDelayedEventAsync(tokenSource.Token);
await _delayedChannel.WaitAsync(token);
await tokenSource.CancelAsync();
}
@ -367,7 +367,7 @@ public abstract class PostgresJobQueue<T>(
}
}
private async Task ScheduleDelayedEvent(CancellationToken token)
private async Task ScheduleDelayedEventAsync(CancellationToken token)
{
await using var scope = GetScope();
await using var db = GetDbContext(scope);

View file

@ -15,7 +15,7 @@ public class RelayService(
ActivityPub.UserRenderer userRenderer
) : IScopedService
{
public async Task SubscribeToRelay(string uri)
public async Task SubscribeToRelayAsync(string uri)
{
uri = new Uri(uri).AbsoluteUri;
if (await db.Relays.AnyAsync(p => p.Inbox == uri)) return;
@ -35,7 +35,7 @@ public class RelayService(
await deliverSvc.DeliverToAsync(activity, actor, uri);
}
public async Task UnsubscribeFromRelay(Relay relay)
public async Task UnsubscribeFromRelayAsync(Relay relay)
{
var actor = await systemUserSvc.GetRelayActorAsync();
var follow = activityRenderer.RenderFollow(actor, relay);
@ -46,7 +46,7 @@ public class RelayService(
await db.SaveChangesAsync();
}
public async Task HandleAccept(User actor, string id)
public async Task HandleAcceptAsync(User actor, string id)
{
// @formatter:off
if (await db.Relays.FirstOrDefaultAsync(p => p.Id == id) is not { } relay)
@ -60,7 +60,7 @@ public class RelayService(
await db.SaveChangesAsync();
}
public async Task HandleReject(User actor, string id)
public async Task HandleRejectAsync(User actor, string id)
{
// @formatter:off
if (db.Relays.FirstOrDefault(p => p.Id == id) is not { } relay)

View file

@ -18,7 +18,7 @@ public class StorageMaintenanceService(
ILogger<StorageMaintenanceService> logger
) : IScopedService
{
public async Task MigrateLocalFiles(bool purge)
public async Task MigrateLocalFilesAsync(bool purge)
{
var pathBase = options.Value.Local?.Path;
var pathsToDelete = new ConcurrentBag<string>();
@ -46,7 +46,7 @@ public class StorageMaintenanceService(
if (hits.Count == 0) break;
await Parallel.ForEachAsync(hits, new ParallelOptions { MaxDegreeOfParallelism = 8 }, TryMigrateFile);
await Parallel.ForEachAsync(hits, new ParallelOptions { MaxDegreeOfParallelism = 8 }, TryMigrateFileAsync);
await db.SaveChangesAsync();
foreach (var path in pathsToDelete)
File.Delete(path);
@ -62,16 +62,16 @@ public class StorageMaintenanceService(
else if (!purge)
logger.LogInformation("Done. Some files could not be migrated successfully. You may retry this process or clean them up by adding --purge to the CLI arguments.");
else
await PurgeFiles();
await PurgeFilesAsync();
return;
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
async ValueTask TryMigrateFile(IEnumerable<DriveFile> files, CancellationToken token)
async ValueTask TryMigrateFileAsync(IEnumerable<DriveFile> files, CancellationToken token)
{
try
{
await MigrateFile(files).WaitAsync(token);
await MigrateFileAsync(files).WaitAsync(token);
}
catch (Exception e)
{
@ -84,7 +84,7 @@ public class StorageMaintenanceService(
}
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
async Task MigrateFile(IEnumerable<DriveFile> files)
async Task MigrateFileAsync(IEnumerable<DriveFile> files)
{
var file = files.FirstOrDefault();
if (file == null) return;
@ -135,7 +135,7 @@ public class StorageMaintenanceService(
foreach (var item in deletionQueue) pathsToDelete.Add(item);
}
async Task PurgeFiles()
async Task PurgeFilesAsync()
{
logger.LogInformation("Done. Purging {count} failed files...", failed.Count);
foreach (var chunk in failed.Chunk(100))
@ -144,7 +144,7 @@ public class StorageMaintenanceService(
}
}
public async Task FixupMedia(bool dryRun)
public async Task FixupMediaAsync(bool dryRun)
{
var query = db.DriveFiles.Where(p => !p.IsLink && p.Uri != null && p.CreatedAt < DateTime.UtcNow);
var total = await query.CountAsync();
@ -153,9 +153,9 @@ public class StorageMaintenanceService(
logger.LogInformation("Validating all files, this may take a long time...");
var localFiles = driveSvc.GetAllFileNamesFromLocalStorage();
var objStorageFiles = await driveSvc.GetAllFileNamesFromObjectStorage();
var objStorageFiles = await driveSvc.GetAllFileNamesFromObjectStorageAsync();
await foreach (var file in query.AsChunkedAsyncEnumerable(50, p => p.Id))
await foreach (var file in query.AsChunkedAsyncEnumerableAsync(50, p => p.Id))
{
if (++progress % 500 == 0)
logger.LogInformation("Validating files... ({idx}/{total})", progress, total);
@ -178,7 +178,7 @@ public class StorageMaintenanceService(
continue;
}
await driveSvc.ExpireFile(file);
await driveSvc.ExpireFileAsync(file);
await db.Users.Where(p => p.AvatarId == file.Id)
.ExecuteUpdateAsync(p => p.SetProperty(u => u.AvatarUrl, file.Uri));
await db.Users.Where(p => p.BannerId == file.Id)
@ -236,7 +236,7 @@ public class StorageMaintenanceService(
}
}
public async Task CleanupStorage(bool dryRun)
public async Task CleanupStorageAsync(bool dryRun)
{
var filenames = await db.DriveFiles
.Where(p => !p.IsLink)
@ -247,7 +247,7 @@ public class StorageMaintenanceService(
p.PublicAccessKey
})
.ToArrayAsync()
.ContinueWithResult(res => res.SelectMany(p => new List<string?>
.ContinueWithResultAsync(res => res.SelectMany(p => new List<string?>
{
p.AccessKey,
p.ThumbnailAccessKey,

View file

@ -60,14 +60,14 @@ public sealed class StreamingService : ISingletonService
conn?.Dispose();
}
public Task Subscribe(string userId, string connectionId, StreamingTimeline timeline)
public Task SubscribeAsync(string userId, string connectionId, StreamingTimeline timeline)
{
_connections.TryGetValue(userId, out var conn);
conn?.Subscribe(connectionId, timeline);
return Task.CompletedTask;
}
public Task Unsubscribe(string userId, string connectionId, StreamingTimeline timeline)
public Task UnsubscribeAsync(string userId, string connectionId, StreamingTimeline timeline)
{
_connections.TryGetValue(userId, out var conn);
conn?.Unsubscribe(connectionId, timeline);

View file

@ -19,7 +19,7 @@ public class UserProfileMentionsResolver(
IOptions<Config.InstanceSection> config
) : IScopedService
{
public async Task<MentionTuple> ResolveMentions(ASActor actor, string? host)
public async Task<MentionTuple> ResolveMentionsAsync(ASActor actor, string? host)
{
var fields = actor.Attachments?.OfType<ASField>()
.Where(p => p is { Name: not null, Value: not null })
@ -72,7 +72,7 @@ public class UserProfileMentionsResolver(
return (mentions, splitDomainMapping);
}
public async Task<List<Note.MentionedUser>> ResolveMentions(UserProfile.Field[]? fields, string? bio, string? host)
public async Task<List<Note.MentionedUser>> ResolveMentionsAsync(UserProfile.Field[]? fields, string? bio, string? host)
{
if (fields is not { Length: > 0 } && bio == null) return [];
var input = (fields ?? [])

View file

@ -211,11 +211,11 @@ public class UserService(
{
await db.AddRangeAsync(user, profile, publicKey);
await db.SaveChangesAsync();
var processPendingDeletes = await ResolveAvatarAndBanner(user, actor);
var processPendingDeletes = await ResolveAvatarAndBannerAsync(user, actor);
await processPendingDeletes();
user = await UpdateProfileMentions(user, actor);
user = await UpdateProfileMentionsAsync(user, actor);
UpdateUserPinnedNotesInBackground(actor, user);
_ = followupTaskSvc.ExecuteTask("UpdateInstanceUserCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateInstanceUserCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -317,7 +317,7 @@ public class UserService(
//TODO: update acct host via webfinger here
var processPendingDeletes = await ResolveAvatarAndBanner(user, actor);
var processPendingDeletes = await ResolveAvatarAndBannerAsync(user, actor);
user.UserProfile.Description = actor.MkSummary ?? await MfmConverter.FromHtmlAsync(actor.Summary);
//user.UserProfile.Birthday = TODO;
@ -334,7 +334,7 @@ public class UserService(
db.Update(user);
await db.SaveChangesAsync();
await processPendingDeletes();
user = await UpdateProfileMentions(user, actor, true);
user = await UpdateProfileMentionsAsync(user, actor, true);
UpdateUserPinnedNotesInBackground(actor, user, true);
return user;
}
@ -351,38 +351,38 @@ public class UserService(
if (user.UserProfile.Description != null)
{
var nodes = MfmParser.Parse(user.UserProfile.Description);
user.Emojis.AddRange((await emojiSvc.ResolveEmoji(nodes)).Select(p => p.Id).ToList());
user.Emojis.AddRange((await emojiSvc.ResolveEmojiAsync(nodes)).Select(p => p.Id).ToList());
}
if (user.DisplayName != null)
{
var nodes = MfmParser.Parse(user.DisplayName);
user.Emojis.AddRange((await emojiSvc.ResolveEmoji(nodes)).Select(p => p.Id).ToList());
user.Emojis.AddRange((await emojiSvc.ResolveEmojiAsync(nodes)).Select(p => p.Id).ToList());
}
if (user.UserProfile.Fields.Length != 0)
{
var input = user.UserProfile.Fields.Select(p => $"{p.Name} {p.Value}");
var nodes = MfmParser.Parse(string.Join('\n', input));
user.Emojis.AddRange((await emojiSvc.ResolveEmoji(nodes)).Select(p => p.Id).ToList());
user.Emojis.AddRange((await emojiSvc.ResolveEmojiAsync(nodes)).Select(p => p.Id).ToList());
}
db.Update(user);
db.Update(user.UserProfile);
await db.SaveChangesAsync();
user = await UpdateProfileMentions(user, null, wait: true);
user = await UpdateProfileMentionsAsync(user, null, wait: true);
var activity = activityRenderer.RenderUpdate(await userRenderer.RenderAsync(user));
await deliverSvc.DeliverToFollowersAsync(activity, user, []);
_ = followupTaskSvc.ExecuteTask("UpdateLocalUserAsync", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateLocalUserAsync", async provider =>
{
var bgDriveSvc = provider.GetRequiredService<DriveService>();
if (prevAvatarId != null && user.Avatar?.Id != prevAvatarId)
await bgDriveSvc.RemoveFile(prevAvatarId);
await bgDriveSvc.RemoveFileAsync(prevAvatarId);
if (prevBannerId != null && user.Banner?.Id != prevBannerId)
await bgDriveSvc.RemoveFile(prevBannerId);
await bgDriveSvc.RemoveFileAsync(prevBannerId);
});
return user;
@ -445,11 +445,11 @@ public class UserService(
return user;
}
private async Task<Func<Task>> ResolveAvatarAndBanner(User user, ASActor actor)
private async Task<Func<Task>> ResolveAvatarAndBannerAsync(User user, ASActor actor)
{
var avatar = await driveSvc.StoreFile(actor.Avatar?.Url?.Link, user, actor.Avatar?.Sensitive ?? false,
var avatar = await driveSvc.StoreFileAsync(actor.Avatar?.Url?.Link, user, actor.Avatar?.Sensitive ?? false,
logExisting: false);
var banner = await driveSvc.StoreFile(actor.Banner?.Url?.Link, user, actor.Banner?.Sensitive ?? false,
var banner = await driveSvc.StoreFileAsync(actor.Banner?.Url?.Link, user, actor.Banner?.Sensitive ?? false,
logExisting: false);
var prevAvatarId = user.AvatarId;
@ -469,10 +469,10 @@ public class UserService(
return async () =>
{
if (prevAvatarId != null && avatar?.Id != prevAvatarId)
await driveSvc.RemoveFile(prevAvatarId);
await driveSvc.RemoveFileAsync(prevAvatarId);
if (prevBannerId != null && banner?.Id != prevBannerId)
await driveSvc.RemoveFile(prevBannerId);
await driveSvc.RemoveFileAsync(prevBannerId);
};
}
@ -542,7 +542,7 @@ public class UserService(
if (token.LastActiveDate != null && token.LastActiveDate > DateTime.UtcNow - TimeSpan.FromHours(1)) return;
_ = followupTaskSvc.ExecuteTask("UpdateOauthTokenMetadata", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateOauthTokenMetadata", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
await bgDb.OauthTokens.Where(p => p.Id == token.Id)
@ -557,7 +557,7 @@ public class UserService(
if (session.LastActiveDate != null && session.LastActiveDate > DateTime.UtcNow - TimeSpan.FromMinutes(5))
return;
_ = followupTaskSvc.ExecuteTask("UpdateSessionMetadata", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateSessionMetadata", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
await bgDb.Sessions.Where(p => p.Id == session.Id)
@ -570,7 +570,7 @@ public class UserService(
if (user.LastActiveDate != null && user.LastActiveDate > DateTime.UtcNow - TimeSpan.FromMinutes(5))
return;
_ = followupTaskSvc.ExecuteTask("UpdateUserLastActive", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateUserLastActive", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
await bgDb.Users.Where(p => p.Id == user.Id)
@ -609,7 +609,7 @@ public class UserService(
if (request.Follower is { IsRemoteUser: true })
{
_ = followupTaskSvc.ExecuteTask("IncrementInstanceIncomingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("IncrementInstanceIncomingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -623,7 +623,7 @@ public class UserService(
}
else if (request.Followee is { IsRemoteUser: true })
{
_ = followupTaskSvc.ExecuteTask("IncrementInstanceOutgoingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("IncrementInstanceOutgoingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -636,8 +636,8 @@ public class UserService(
if (request.Followee.IsRemoteUser && request.Follower.IsLocalUser && request.Followee.FollowersCount == 0)
UpdateUserPinnedNotesInBackground(request.Followee);
await notificationSvc.GenerateFollowNotification(request.Follower, request.Followee);
await notificationSvc.GenerateFollowRequestAcceptedNotification(request);
await notificationSvc.GenerateFollowNotificationAsync(request.Follower, request.Followee);
await notificationSvc.GenerateFollowRequestAcceptedNotificationAsync(request);
// Clean up notifications
await db.Notifications
@ -771,7 +771,7 @@ public class UserService(
await db.AddAsync(following);
await db.SaveChangesAsync();
await notificationSvc.GenerateFollowNotification(follower, followee);
await notificationSvc.GenerateFollowNotificationAsync(follower, followee);
await db.Users.Where(p => p.Id == follower.Id)
.ExecuteUpdateAsync(p => p.SetProperty(i => i.FollowingCount,
@ -782,7 +782,7 @@ public class UserService(
if (follower.IsRemoteUser)
{
_ = followupTaskSvc.ExecuteTask("IncrementInstanceIncomingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("IncrementInstanceIncomingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -814,7 +814,7 @@ public class UserService(
await db.AddAsync(request);
await db.SaveChangesAsync();
await notificationSvc.GenerateFollowRequestReceivedNotification(request);
await notificationSvc.GenerateFollowRequestReceivedNotificationAsync(request);
}
}
}
@ -840,7 +840,7 @@ public class UserService(
await db.AddAsync(following);
await db.SaveChangesAsync();
await notificationSvc.GenerateFollowNotification(follower, followee);
await notificationSvc.GenerateFollowNotificationAsync(follower, followee);
await db.Users.Where(p => p.Id == follower.Id)
.ExecuteUpdateAsync(p => p.SetProperty(i => i.FollowingCount, i => i.FollowingCount + 1));
@ -849,7 +849,7 @@ public class UserService(
if (follower.IsRemoteUser)
{
_ = followupTaskSvc.ExecuteTask("IncrementInstanceIncomingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("IncrementInstanceIncomingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -906,7 +906,7 @@ public class UserService(
if (follower.IsRemoteUser)
{
_ = followupTaskSvc.ExecuteTask("DecrementInstanceIncomingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("DecrementInstanceIncomingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -958,7 +958,7 @@ public class UserService(
if (followee.IsRemoteUser)
{
_ = followupTaskSvc.ExecuteTask("DecrementInstanceOutgoingFollowsCounter", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("DecrementInstanceOutgoingFollowsCounter", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var bgInstanceSvc = provider.GetRequiredService<InstanceService>();
@ -999,7 +999,7 @@ public class UserService(
{
if (followupTaskSvc.IsBackgroundWorker.Value && !force) return;
if (KeyedLocker.IsInUse($"pinnedNotes:{user.Id}")) return;
_ = followupTaskSvc.ExecuteTask("UpdateUserPinnedNotes", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateUserPinnedNotes", async provider =>
{
using (await KeyedLocker.LockAsync($"pinnedNotes:{user.Id}"))
{
@ -1019,7 +1019,7 @@ public class UserService(
if (!user.IsRemoteUser) return;
if (followupTaskSvc.IsBackgroundWorker.Value && !force) return;
if (KeyedLocker.IsInUse($"pinnedNotes:{user.Id}")) return;
_ = followupTaskSvc.ExecuteTask("UpdateUserPinnedNotes", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateUserPinnedNotes", async provider =>
{
using (await KeyedLocker.LockAsync($"pinnedNotes:{user.Id}"))
{
@ -1037,14 +1037,14 @@ public class UserService(
[SuppressMessage("ReSharper", "EntityFramework.NPlusOne.IncompleteDataQuery", Justification = "Projectables")]
[SuppressMessage("ReSharper", "EntityFramework.NPlusOne.IncompleteDataUsage", Justification = "Same as above")]
[SuppressMessage("ReSharper", "SuggestBaseTypeForParameter", Justification = "Method only makes sense for users")]
private async Task<User> UpdateProfileMentions(User user, ASActor? actor, bool force = false, bool wait = false)
private async Task<User> UpdateProfileMentionsAsync(User user, ASActor? actor, bool force = false, bool wait = false)
{
if (followupTaskSvc.IsBackgroundWorker.Value && !force) return user;
if (KeyedLocker.IsInUse($"profileMentions:{user.Id}")) return user;
var success = false;
var task = followupTaskSvc.ExecuteTask("UpdateProfileMentionsInBackground", async provider =>
var task = followupTaskSvc.ExecuteTaskAsync("UpdateProfileMentionsInBackground", async provider =>
{
using (await KeyedLocker.LockAsync($"profileMentions:{user.Id}"))
{
@ -1056,7 +1056,7 @@ public class UserService(
if (actor != null)
{
var (mentions, splitDomainMapping) = await bgMentionsResolver.ResolveMentions(actor, bgUser.Host);
var (mentions, splitDomainMapping) = await bgMentionsResolver.ResolveMentionsAsync(actor, bgUser.Host);
var fields = actor.Attachments != null
? await actor.Attachments
.OfType<ASField>()
@ -1079,7 +1079,7 @@ public class UserService(
}
else
{
bgUser.UserProfile.Mentions = await bgMentionsResolver.ResolveMentions(bgUser.UserProfile.Fields,
bgUser.UserProfile.Mentions = await bgMentionsResolver.ResolveMentionsAsync(bgUser.UserProfile.Fields,
bgUser.UserProfile.Description, bgUser.Host);
}
@ -1131,7 +1131,7 @@ public class UserService(
tags = tags.Distinct().ToList();
_ = followupTaskSvc.ExecuteTask("UpdateHashtagsTable", async provider =>
_ = followupTaskSvc.ExecuteTaskAsync("UpdateHashtagsTable", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
var existing = await bgDb.Hashtags.Where(p => tags.Contains(p.Name)).Select(p => p.Name).ToListAsync();
@ -1379,7 +1379,7 @@ public class UserService(
var followers = db.Followings
.Where(p => p.Followee == source && p.Follower.IsLocalUser)
.Select(p => p.Follower)
.AsChunkedAsyncEnumerable(50, p => p.Id, hook: p => p.PrecomputeRelationshipData(source));
.AsChunkedAsyncEnumerableAsync(50, p => p.Id, hook: p => p.PrecomputeRelationshipData(source));
await foreach (var follower in followers)
{
@ -1407,7 +1407,7 @@ public class UserService(
var following = db.Followings
.Where(p => p.Follower == source)
.Select(p => p.Follower)
.AsChunkedAsyncEnumerable(50, p => p.Id, hook: p => p.PrecomputeRelationshipData(source));
.AsChunkedAsyncEnumerableAsync(50, p => p.Id, hook: p => p.PrecomputeRelationshipData(source));
await foreach (var followee in following)
{

View file

@ -8,7 +8,7 @@ namespace Iceshrimp.Backend.Core.Tasks;
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Instantiated at runtime by CronService")]
public class CacheCleanupTask : ICronTask
{
public async Task Invoke(IServiceProvider provider)
public async Task InvokeAsync(IServiceProvider provider)
{
var db = provider.GetRequiredService<DatabaseContext>();
await db.CacheStore.Where(p => p.Expiry != null && p.Expiry < DateTime.UtcNow).ExecuteDeleteAsync();

View file

@ -8,7 +8,7 @@ namespace Iceshrimp.Backend.Core.Tasks;
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Instantiated at runtime by CronService")]
public class FilterExpiryTask : ICronTask
{
public async Task Invoke(IServiceProvider provider)
public async Task InvokeAsync(IServiceProvider provider)
{
var db = provider.GetRequiredService<DatabaseContext>();
await db.Filters.Where(p => p.Expiry != null && p.Expiry < DateTime.UtcNow - TimeSpan.FromMinutes(5))

View file

@ -11,7 +11,7 @@ namespace Iceshrimp.Backend.Core.Tasks;
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Instantiated at runtime by CronService")]
public class JobCleanupTask : ICronTask
{
public async Task Invoke(IServiceProvider provider)
public async Task InvokeAsync(IServiceProvider provider)
{
var db = provider.GetRequiredService<DatabaseContext>();
var queue = provider.GetRequiredService<QueueService>();

View file

@ -12,7 +12,7 @@ namespace Iceshrimp.Backend.Core.Tasks;
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Instantiated at runtime by CronService")]
public class MediaCleanupTask : ICronTask
{
public async Task Invoke(IServiceProvider provider)
public async Task InvokeAsync(IServiceProvider provider)
{
var config = provider.GetRequiredService<IOptionsSnapshot<Config.StorageSection>>().Value;
if (config.MediaRetentionTimeSpan == TimeSpan.MaxValue) return;
@ -34,7 +34,7 @@ public class MediaCleanupTask : ICronTask
var cnt = await fileIds.CountAsync();
logger.LogInformation("Expiring {count} files...", cnt);
await foreach (var fileId in fileIds.AsChunkedAsyncEnumerable(50, p => p))
await foreach (var fileId in fileIds.AsChunkedAsyncEnumerableAsync(50, p => p))
{
await queueService.BackgroundTaskQueue.EnqueueAsync(new DriveFileDeleteJobData
{

View file

@ -8,7 +8,7 @@ namespace Iceshrimp.Backend.Core.Tasks;
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Instantiated at runtime by CronService")]
public class MuteExpiryTask : ICronTask
{
public async Task Invoke(IServiceProvider provider)
public async Task InvokeAsync(IServiceProvider provider)
{
var db = provider.GetRequiredService<DatabaseContext>();
await db.Mutings.Where(p => p.ExpiresAt != null && p.ExpiresAt < DateTime.UtcNow - TimeSpan.FromMinutes(5))

View file

@ -54,15 +54,15 @@
protected override async Task OnGet()
{
(Model.Name, Model.Description, Model.AdminContact) =
await Meta.GetMany(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
await Meta.GetManyAsync(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
}
async Task OnSubmit()
{
Model.Canonicalize();
await Meta.Set(MetaEntity.InstanceName, Model.Name);
await Meta.Set(MetaEntity.InstanceDescription, Model.Description);
await Meta.Set(MetaEntity.AdminContactEmail, Model.AdminContact);
await Meta.SetAsync(MetaEntity.InstanceName, Model.Name);
await Meta.SetAsync(MetaEntity.InstanceDescription, Model.Description);
await Meta.SetAsync(MetaEntity.AdminContactEmail, Model.AdminContact);
ReloadPage();
}

View file

@ -80,7 +80,7 @@
if (Model.InboxUri == null)
throw GracefulException.BadRequest("Missing host field");
await RelayService.SubscribeToRelay(Model.InboxUri);
await RelayService.SubscribeToRelayAsync(Model.InboxUri);
ReloadPage();
}
}

View file

@ -22,7 +22,7 @@ public class IndexModel(MetaService meta, IOptionsSnapshot<Config.InstanceSectio
return Redirect(dest);
var (instanceName, instanceDescription, contactEmail) =
await meta.GetMany(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
await meta.GetManyAsync(MetaEntity.InstanceName, MetaEntity.InstanceDescription, MetaEntity.AdminContactEmail);
InstanceName = instanceName ?? "Iceshrimp.NET";
InstanceDescription =

View file

@ -31,7 +31,7 @@ public partial class NotePreview(
if (security.Value.PublicPreview == Enums.PublicPreview.Lockdown)
throw new PublicPreviewDisabledException();
_instanceName = await meta.Get(MetaEntity.InstanceName) ?? _instanceName;
_instanceName = await meta.GetAsync(MetaEntity.InstanceName) ?? _instanceName;
//TODO: show publish & edit timestamps
//TODO: show quotes inline (enforce visibility by checking VisibilityIsPublicOrHome)

View file

@ -106,7 +106,7 @@
<tbody>
@foreach (var job in Model.Jobs)
{
await RenderJob(job, true);
await RenderJobAsync(job, true);
}
</tbody>
</table>
@ -148,7 +148,7 @@ else
<tbody>
@foreach (var job in Model.Jobs)
{
await RenderJob(job);
await RenderJobAsync(job);
}
</tbody>
</table>
@ -219,7 +219,7 @@ else
}
@{
async Task RenderJob(Job job, bool withQueue = false)
async Task RenderJobAsync(Job job, bool withQueue = false)
{
var id = job.Id.ToStringLower();
var additional = job.Status switch

View file

@ -36,7 +36,7 @@ public class QueueModel(DatabaseContext db, QueueService queueSvc, MetaService m
return Redirect("/login");
Request.HttpContext.HideFooter();
InstanceName = await meta.Get(MetaEntity.InstanceName) ?? InstanceName;
InstanceName = await meta.GetAsync(MetaEntity.InstanceName) ?? InstanceName;
if (queue == null)
{

View file

@ -29,7 +29,7 @@ public class QueueJobModel(DatabaseContext db, MetaService meta) : PageModel
return Redirect("/login");
Request.HttpContext.HideFooter();
InstanceName = await meta.Get(MetaEntity.InstanceName) ?? InstanceName;
InstanceName = await meta.GetAsync(MetaEntity.InstanceName) ?? InstanceName;
Job = await db.Jobs.FirstOrDefaultAsync(p => p.Id == id) ??
throw GracefulException.NotFound($"Job {id} not found");

View file

@ -62,7 +62,7 @@
protected override async Task OnParametersSetAsync()
{
_instanceName = await Meta.Get(MetaEntity.InstanceName);
_instanceName = await Meta.GetAsync(MetaEntity.InstanceName);
_user = Context.GetUser();
if (Context.GetEndpoint()?.Metadata.GetMetadata<RequireAuthorizationAttribute>() == null)

View file

@ -31,7 +31,7 @@ public partial class UserPreview(
if (security.Value.PublicPreview == Enums.PublicPreview.Lockdown)
throw new PublicPreviewDisabledException();
_instanceName = await meta.Get(MetaEntity.InstanceName) ?? _instanceName;
_instanceName = await meta.GetAsync(MetaEntity.InstanceName) ?? _instanceName;
//TODO: user banner
//TODO: user note view (respect public preview settings - don't show renotes of remote notes if set to restricted or lower)

View file

@ -71,12 +71,12 @@ public sealed class StreamingConnectionAggregate : IDisposable
if (notification.Notifier != null && IsFiltered(notification.Notifier)) return;
await using var scope = GetTempScope();
if (notification.Note != null && await IsMutedThread(notification.Note, scope, true))
if (notification.Note != null && await IsMutedThreadAsync(notification.Note, scope, true))
return;
var renderer = scope.ServiceProvider.GetRequiredService<NotificationRenderer>();
var rendered = await renderer.RenderOne(notification, _user);
await _hub.Clients.User(_userId).Notification(rendered);
await _hub.Clients.User(_userId).NotificationAsync(rendered);
}
catch (Exception e)
{
@ -96,12 +96,12 @@ public sealed class StreamingConnectionAggregate : IDisposable
if (data.note.Reply != null)
{
await using var scope = _scopeFactory.CreateAsyncScope();
if (await IsMutedThread(data.note, scope))
if (await IsMutedThreadAsync(data.note, scope))
return;
}
var rendered = EnforceRenoteReplyVisibility(await data.rendered.Value, wrapped);
await _hub.Clients.Clients(recipients.connectionIds).NotePublished(recipients.timelines, rendered);
await _hub.Clients.Clients(recipients.connectionIds).NotePublishedAsync(recipients.timelines, rendered);
}
catch (Exception e)
{
@ -119,7 +119,7 @@ public sealed class StreamingConnectionAggregate : IDisposable
if (connectionIds.Count == 0) return;
var rendered = EnforceRenoteReplyVisibility(await data.rendered.Value, wrapped);
await _hub.Clients.Clients(connectionIds).NoteUpdated(rendered);
await _hub.Clients.Clients(connectionIds).NoteUpdatedAsync(rendered);
}
catch (Exception e)
{
@ -136,7 +136,7 @@ public sealed class StreamingConnectionAggregate : IDisposable
var (connectionIds, _) = FindRecipients(note);
if (connectionIds.Count == 0) return;
await _hub.Clients.Clients(connectionIds).NoteDeleted(note.Id);
await _hub.Clients.Clients(connectionIds).NoteDeletedAsync(note.Id);
}
catch (Exception e)
{
@ -170,7 +170,7 @@ public sealed class StreamingConnectionAggregate : IDisposable
return res is not { Note.IsPureRenote: true, Renote: null } ? res : null;
}
private async Task<bool> IsMutedThread(Note note, AsyncServiceScope scope, bool isNotification = false)
private async Task<bool> IsMutedThreadAsync(Note note, AsyncServiceScope scope, bool isNotification = false)
{
if (!isNotification && note.Reply == null) return false;
if (!isNotification && note.User.Id == _userId) return false;
@ -266,7 +266,7 @@ public sealed class StreamingConnectionAggregate : IDisposable
_eventService.UserFollowed += OnUserFollow;
_eventService.UserUnfollowed += OnUserUnfollow;
await InitializeRelationships();
await InitializeRelationshipsAsync();
_eventService.Notification += OnNotification;
_streamingService.NotePublished += OnNotePublished;
@ -278,7 +278,7 @@ public sealed class StreamingConnectionAggregate : IDisposable
_eventService.FilterRemoved += OnFilterRemoved;
}
private async Task InitializeRelationships()
private async Task InitializeRelationshipsAsync()
{
await using var scope = GetTempScope();
await using var db = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
@ -419,19 +419,19 @@ public sealed class StreamingConnectionAggregate : IDisposable
private async void OnFilterAdded(object? _, Filter filter)
{
if (filter.User.Id != _userId) return;
await _hub.Clients.User(_userId).FilterAdded(FilterRenderer.RenderOne(filter));
await _hub.Clients.User(_userId).FilterAddedAsync(FilterRenderer.RenderOne(filter));
}
private async void OnFilterUpdated(object? _, Filter filter)
{
if (filter.User.Id != _userId) return;
await _hub.Clients.User(_userId).FilterUpdated(FilterRenderer.RenderOne(filter));
await _hub.Clients.User(_userId).FilterUpdatedAsync(FilterRenderer.RenderOne(filter));
}
private async void OnFilterRemoved(object? _, Filter filter)
{
if (filter.User.Id != _userId) return;
await _hub.Clients.User(_userId).FilterRemoved(filter.Id);
await _hub.Clients.User(_userId).FilterRemovedAsync(filter.Id);
}
#endregion

View file

@ -8,16 +8,16 @@ namespace Iceshrimp.Backend.SignalR;
[Microsoft.AspNetCore.Authorization.Authorize(Policy = "HubAuthorization")]
public class StreamingHub(StreamingService streamingService) : Hub<IStreamingHubClient>, IStreamingHubServer
{
public Task Subscribe(StreamingTimeline timeline)
public Task SubscribeAsync(StreamingTimeline timeline)
{
var userId = Context.UserIdentifier ?? throw new Exception("UserIdentifier must not be null at this stage");
return streamingService.Subscribe(userId, Context.ConnectionId, timeline);
return streamingService.SubscribeAsync(userId, Context.ConnectionId, timeline);
}
public Task Unsubscribe(StreamingTimeline timeline)
public Task UnsubscribeAsync(StreamingTimeline timeline)
{
var userId = Context.UserIdentifier ?? throw new Exception("UserIdentifier must not be null at this stage");
return streamingService.Unsubscribe(userId, Context.ConnectionId, timeline);
return streamingService.UnsubscribeAsync(userId, Context.ConnectionId, timeline);
}
public override async Task OnConnectedAsync()

View file

@ -12,7 +12,7 @@ var builder = WebApplication.CreateBuilder(options);
builder.Configuration.Sources.Clear();
builder.Configuration.AddCustomConfiguration();
await PluginLoader.LoadPlugins();
await PluginLoader.LoadPluginsAsync();
builder.Services
.AddControllersWithOptions()
@ -47,7 +47,7 @@ builder.WebHost.UseStaticWebAssets();
PluginLoader.RunBuilderHooks(builder);
var app = builder.Build();
var config = await app.Initialize(args);
var config = await app.InitializeAsync(args);
// This determines the order of middleware execution in the request pipeline
#if DEBUG

View file

@ -1,8 +1,12 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Build.Framework;
// ReSharper disable UnusedMember.Local
// ReSharper disable CheckNamespace
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable ConvertToAutoProperty
// ReSharper disable PropertyCanBeMadeInitOnly.Local
// ReSharper disable once CheckNamespace
namespace Iceshrimp.Build.Tasks;
public class RewriteStaticAssetManifest : Microsoft.Build.Utilities.Task

View file

@ -246,7 +246,7 @@
try
{
await ApiService.Notes.CreateNote(NoteDraft);
await ApiService.Notes.CreateNoteAsync(NoteDraft);
}
catch (ApiException)
{
@ -256,8 +256,8 @@
if (ReplyOrQuote != null)
{
var res = await ApiService.Notes.GetNote(ReplyOrQuote.Id);
if (res != null) _ = MessageService.UpdateNote(res);
var res = await ApiService.Notes.GetNoteAsync(ReplyOrQuote.Id);
if (res != null) _ = MessageService.UpdateNoteAsync(res);
}
SendButton.State = StateButton.StateEnum.Success;
@ -274,7 +274,7 @@
private async Task Upload(InputFileChangeEventArgs e)
{
var res = await ApiService.Drive.UploadFile(e.File);
var res = await ApiService.Drive.UploadFileAsync(e.File);
Attachments.Add(res);
}

View file

@ -41,7 +41,7 @@
protected override async Task OnInitializedAsync()
{
GlobalComponentSvc.EmojiPicker = this;
EmojiList = await EmojiService.GetEmoji();
EmojiList = await EmojiService.GetEmojiAsync();
_module = (IJSInProcessObjectReference)await Js.InvokeAsync<IJSObjectReference>("import",
"./Components/EmojiPicker.razor.js");
FilterEmojis();

View file

@ -75,7 +75,7 @@
private async void Unfollow()
{
await Api.Users.UnfollowUser(User.Id);
await Api.Users.UnfollowUserAsync(User.Id);
UserProfile.Relations -= (int)Relations.Following;
ChooseButton();
StateHasChanged();
@ -83,11 +83,11 @@
private async void Follow()
{
await Api.Users.FollowUser(User.Id);
await Api.Users.FollowUserAsync(User.Id);
UserProfile.Relations += (int)Relations.Requested;
ChooseButton();
StateHasChanged();
UserProfile = await Api.Users.GetUserProfile(UserProfile.Id) ?? throw new Exception("How did it stop existing");
UserProfile = await Api.Users.GetUserProfileAsync(UserProfile.Id) ?? throw new Exception("How did it stop existing");
ChooseButton();
StateHasChanged();
}

View file

@ -33,26 +33,26 @@
protected override async Task OnInitializedAsync()
{
var profile = await Api.Users.GetUserProfile(FollowRequest.User.Id);
var profile = await Api.Users.GetUserProfileAsync(FollowRequest.User.Id);
if (profile != null) _followBack = profile.Relations.HasFlag(Relations.None);
}
private async void Accept()
{
await Api.FollowRequests.AcceptFollowRequest(FollowRequest.Id);
await Api.FollowRequests.AcceptFollowRequestAsync(FollowRequest.Id);
await OnDelete.InvokeAsync(FollowRequest.Id);
}
private async void AcceptAndFollowBack()
{
await Api.FollowRequests.AcceptFollowRequest(FollowRequest.Id);
await Api.Users.FollowUser(FollowRequest.User.Id);
await Api.FollowRequests.AcceptFollowRequestAsync(FollowRequest.Id);
await Api.Users.FollowUserAsync(FollowRequest.User.Id);
await OnDelete.InvokeAsync(FollowRequest.Id);
}
private async void Reject()
{
await Api.FollowRequests.RejectFollowRequest(FollowRequest.Id);
await Api.FollowRequests.RejectFollowRequestAsync(FollowRequest.Id);
await OnDelete.InvokeAsync(FollowRequest.Id);
}
}

Some files were not shown because too many files have changed in this diff Show more