House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- Services, controllers and jobs take their dependencies through primary constructors and use them directly; where a method already named a local after a dependency, the dependency takes its type's name. - Every async method takes a CancellationToken last and passes it down to MongoDB, HTTP and the job queue. The setup claim is still given back when a request is cancelled. - The federation and media options are read through IOptionsMonitor. - The Mastodon entities keep sending "" for empty strings, and every model field where null means something says so. - The inbox's 503 with Retry-After, which other servers retry, is the one server error left, and says why. - Arasaka.HouseRules.Analyzers checks all of this in every build, here and in PrivaPub.ClientModels as decePubClient builds it. Checked against GoToSocial in the pasture: 64 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -31,31 +31,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/admin"),
|
||||
Authorize(Policy = Policies.IsAdmin)]
|
||||
public class AdminController : ControllerBase
|
||||
public class AdminController(
|
||||
ILogger<RootUserController> logger,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
IRootUsersService rootUsersService,
|
||||
IModerationLog moderationLog,
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors) : ControllerBase
|
||||
{
|
||||
const int MaxRootsPage = 100;
|
||||
|
||||
readonly IRootUsersService RootUsersService;
|
||||
readonly ILogger<RootUserController> Logger;
|
||||
readonly IStringLocalizer Localizer;
|
||||
readonly IModerationLog _log;
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
|
||||
public AdminController(ILogger<RootUserController> logger,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
IRootUsersService rootUsersService,
|
||||
IModerationLog log,
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors)
|
||||
{
|
||||
Logger = logger;
|
||||
Localizer = localizer;
|
||||
RootUsersService = rootUsersService;
|
||||
_log = log;
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
}
|
||||
|
||||
// an administrator never removes, bans or unbans itself; the request's own list is left as it came
|
||||
UsersIds Others(UsersIds usersIds)
|
||||
@@ -81,17 +66,17 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var others = Others(usersIds);
|
||||
var named = await Named(others, token);
|
||||
result = await RootUsersService.RemoveUserAsync(others);
|
||||
result = await rootUsersService.RemoveUserAsync(others, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
foreach (var (id, name) in named)
|
||||
await _log.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +93,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var others = Others(usersIds);
|
||||
var named = await Named(others, token);
|
||||
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
|
||||
result = await RootUsersService.BanUserAsync(others);
|
||||
result = await rootUsersService.BanUserAsync(others, token);
|
||||
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
@@ -116,16 +101,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
foreach (var (id, name) in named.Where(n => !banned.Contains(n.Key)))
|
||||
{
|
||||
await sessions.Revoke(id, CancellationToken.None);
|
||||
foreach (var link in await _dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token))
|
||||
foreach (var link in await dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token))
|
||||
Streams.CloseFor(link.AvatarId);
|
||||
await _log.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
}
|
||||
return Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,18 +125,18 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var others = Others(usersIds);
|
||||
var named = await Named(others, token);
|
||||
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
|
||||
result = await RootUsersService.UnbanUserAsync(others);
|
||||
result = await rootUsersService.UnbanUserAsync(others, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
await Restrictions.Reload(CancellationToken.None);
|
||||
foreach (var (id, name) in named.Where(n => banned.Contains(n.Key)))
|
||||
await _log.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,9 +183,9 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> Role(string id, RootRoleForm form, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid || !RootUser.TryParseRole(form.Role, out var role))
|
||||
return UnprocessableEntity(new WebResult().Invalidate(Localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity));
|
||||
return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity));
|
||||
if (id == User.GetUserId())
|
||||
return Conflict(new WebResult().Invalidate(Localizer["You can't change your own role."], StatusCodes.Status409Conflict));
|
||||
return Conflict(new WebResult().Invalidate(localizer["You can't change your own role."], StatusCodes.Status409Conflict));
|
||||
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (root == default)
|
||||
return NotFound();
|
||||
@@ -208,7 +193,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (was == role)
|
||||
return Ok((await Views(new List<RootUser> { root }, token))[0]);
|
||||
if (was == RootRole.Admin && !await OtherAdministrators(root.ID, token))
|
||||
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
|
||||
return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
|
||||
root.SetRole(role);
|
||||
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).Modify(u => u.UpdatedAt, root.UpdatedAt)
|
||||
.ExecuteAsync(CancellationToken.None);
|
||||
@@ -217,11 +202,11 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
root.SetRole(was);
|
||||
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).ExecuteAsync(CancellationToken.None);
|
||||
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
|
||||
return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
|
||||
}
|
||||
if (role == RootRole.Admin)
|
||||
await ServerSetup.Seal(root.ID, default);//an administrator exists: the client's setup is closed
|
||||
await _log.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName,
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName,
|
||||
note: $"{RoleName(was)} → {RoleName(role)}", token: CancellationToken.None);
|
||||
return Ok((await Views(new List<RootUser> { root }, token))[0]);
|
||||
}
|
||||
@@ -236,12 +221,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> ResetTotp(string id, CancellationToken token)
|
||||
{
|
||||
if (id == User.GetUserId())
|
||||
return Conflict(new WebResult().Invalidate(Localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict));
|
||||
return Conflict(new WebResult().Invalidate(localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict));
|
||||
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (root == default)
|
||||
return NotFound();
|
||||
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync(CancellationToken.None);
|
||||
await _log.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@@ -251,16 +236,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> DeletePersona(string id, AdminPasswordForm form, [FromServices] IPersonaRemoval personas, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
var avatar = await _dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
var avatar = await dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (avatar == default)
|
||||
return NotFound();
|
||||
var label = "@" + _localActors.FromAvatar(avatar).Handle;
|
||||
var label = "@" + localActors.FromAvatar(avatar).Handle;
|
||||
if (!await personas.Remove(avatar.ID, CancellationToken.None))
|
||||
return NotFound();
|
||||
await _log.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@@ -268,30 +253,30 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> DeleteGroup(string id, AdminPasswordForm form, [FromServices] IGroupRemoval groups, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
var group = await _dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
var group = await dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (group == default)
|
||||
return NotFound();
|
||||
var label = "@" + _localActors.FromGroup(group).Handle;
|
||||
var label = "@" + localActors.FromGroup(group).Handle;
|
||||
if (!await groups.Remove(group.ID, CancellationToken.None))
|
||||
return NotFound();
|
||||
await _log.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None);
|
||||
await moderationLog.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
async Task<List<ViewAdminRoot>> Views(List<RootUser> roots, CancellationToken token)
|
||||
{
|
||||
var ids = roots.Select(r => r.ID).ToList();
|
||||
var links = ids.Count == 0 ? new List<RootToAvatar>() : await _dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token);
|
||||
var links = ids.Count == 0 ? new List<RootToAvatar>() : await dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token);
|
||||
var avatarIds = links.Select(l => l.AvatarId).Distinct().ToList();
|
||||
var avatars = avatarIds.Count == 0
|
||||
? new Dictionary<string, Avatar>()
|
||||
: (await _dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID);
|
||||
: (await dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID);
|
||||
var owned = avatarIds.Count == 0
|
||||
? new List<GroupEntity>()
|
||||
: await _dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token);
|
||||
: await dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token);
|
||||
var me = User.GetUserId();
|
||||
return roots.Select(root => new ViewAdminRoot
|
||||
{
|
||||
@@ -308,7 +293,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.OrderBy(a => a.UserName, StringComparer.Ordinal)
|
||||
.Select(a =>
|
||||
{
|
||||
var persona = _localActors.FromAvatar(a);
|
||||
var persona = localActors.FromAvatar(a);
|
||||
return new ViewAdminPersona
|
||||
{
|
||||
Id = a.ID,
|
||||
|
||||
@@ -9,24 +9,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
[ApiController,
|
||||
Route("clientapi/data")]
|
||||
public class DataController : ControllerBase
|
||||
public class DataController(
|
||||
IDataService dataService,
|
||||
ILogger<DataController> logger) : ControllerBase
|
||||
{
|
||||
readonly IDataService DataService;
|
||||
readonly ILogger<DataController> Logger;
|
||||
|
||||
public DataController(IDataService dataService,
|
||||
ILogger<DataController> logger)
|
||||
{
|
||||
DataService = dataService;
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/data/ping"), AllowAnonymous]
|
||||
public async ValueTask<IActionResult> Ping() => NoContent();
|
||||
public async ValueTask<IActionResult> Ping(CancellationToken token = default) => NoContent();
|
||||
|
||||
[HttpGet, Route("/clientapi/data/current-version"), AllowAnonymous]
|
||||
public IActionResult CurrentVersion() =>
|
||||
Ok(DataService.GetCurrentVersion());
|
||||
Ok(dataService.GetCurrentVersion());
|
||||
|
||||
[HttpGet, Route("/clientapi/data/languages"), AllowAnonymous]
|
||||
public async Task<IActionResult> Languages(CancellationToken cancellationToken)
|
||||
@@ -34,7 +26,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var languages = await DataService.GetLanguages(cancellationToken);
|
||||
var languages = await dataService.GetLanguages(cancellationToken);
|
||||
var viewLanguages = new List<ViewLanguage>();
|
||||
|
||||
viewLanguages.AddRange(languages.Select(l => new ViewLanguage
|
||||
@@ -47,7 +39,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(DataController)}.{nameof(Languages)}()");
|
||||
logger.LogError(ex, $"{nameof(DataController)}.{nameof(Languages)}()");
|
||||
return BadRequest(result.Invalidate("Something went wrong.", exception: ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,24 +18,13 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/admin/domainblocks"),
|
||||
Authorize(Policy = Policies.IsAdmin)]
|
||||
public class DomainBlockController : ControllerBase
|
||||
public class DomainBlockController(
|
||||
IDomainBlocks domainBlocks,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
Domain.Media.IMediaProxy mediaProxy,
|
||||
IModerationLog log,
|
||||
IAccountModeration moderation) : ControllerBase
|
||||
{
|
||||
readonly IDomainBlocks _domainBlocks;
|
||||
readonly IStringLocalizer _localizer;
|
||||
readonly Domain.Media.IMediaProxy _proxy;
|
||||
readonly IModerationLog _log;
|
||||
readonly IAccountModeration _moderation;
|
||||
|
||||
public DomainBlockController(IDomainBlocks domainBlocks, IStringLocalizer<GenericRes> localizer, Domain.Media.IMediaProxy proxy, IModerationLog log,
|
||||
IAccountModeration moderation)
|
||||
{
|
||||
_moderation = moderation;
|
||||
_domainBlocks = domainBlocks;
|
||||
_localizer = localizer;
|
||||
_proxy = proxy;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/domainblocks/list")]
|
||||
public async Task<IActionResult> List(CancellationToken token) =>
|
||||
Ok((await DB.Default.Find<DomainBlock>().Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token)).Select(ToView).ToList());
|
||||
@@ -45,7 +34,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var domain = DomainBlocks.Normalise(form.Domain);
|
||||
if (!ModelState.IsValid || Uri.CheckHostName(domain) != UriHostNameType.Dns)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
|
||||
var block = await DB.Default.UpdateAndGet<DomainBlock>()
|
||||
.Match(b => b.Domain == domain)
|
||||
@@ -59,13 +48,13 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.Modify(b => b.SetOnInsert(x => x.CreatedAt, DateTime.UtcNow))
|
||||
.Option(o => o.IsUpsert = true)
|
||||
.ExecuteAsync(token);
|
||||
await _domainBlocks.Reload(token);
|
||||
await domainBlocks.Reload(token);
|
||||
// a silenced server's posts are limited from now on, and no longer once it is not (R6)
|
||||
await _moderation.DomainChanged(domain, token);
|
||||
await moderation.DomainChanged(domain, token);
|
||||
// what the media proxy holds of it goes with the block
|
||||
if (block.Severity == DomainBlockSeverity.Suspend || block.RejectMedia)
|
||||
_proxy.Purge(domain);
|
||||
await _log.Write(User.GetUserId(), AdminActions.DomainBlockInsert, AdminTargets.Domain, domain, domain,
|
||||
mediaProxy.Purge(domain);
|
||||
await log.Write(User.GetUserId(), AdminActions.DomainBlockInsert, AdminTargets.Domain, domain, domain,
|
||||
note: string.Join(", ", new[] { block.Severity.ToString().ToLowerInvariant(), block.RejectMedia ? "media rejected" : default,
|
||||
block.Published ? (block.Obfuscate ? "published, obfuscated" : "published") : default }.Where(n => n != default)), token: token);
|
||||
return Ok(ToView(block));
|
||||
@@ -76,11 +65,11 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
domain = DomainBlocks.Normalise(domain);
|
||||
var deleted = await DB.Default.DeleteAsync<DomainBlock>(b => b.Domain == domain);
|
||||
await _domainBlocks.Reload(token);
|
||||
await domainBlocks.Reload(token);
|
||||
if (deleted.DeletedCount > 0)
|
||||
await _moderation.DomainChanged(domain, token);
|
||||
await moderation.DomainChanged(domain, token);
|
||||
if (deleted.DeletedCount > 0)
|
||||
await _log.Write(User.GetUserId(), AdminActions.DomainBlockDelete, AdminTargets.Domain, domain, domain, token: token);
|
||||
await log.Write(User.GetUserId(), AdminActions.DomainBlockDelete, AdminTargets.Domain, domain, domain, token: token);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
|
||||
@@ -26,23 +26,15 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/admin/emoji"),
|
||||
Authorize(Policy = Policies.IsAdmin)]
|
||||
public class EmojiAdminController : ControllerBase
|
||||
public class EmojiAdminController(
|
||||
IModerationLog log,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
IMediaService media,
|
||||
ILocalActorService localActors) : ControllerBase
|
||||
{
|
||||
// a picture up to a megabyte reaches EmojiImage, which refuses one over 256 KB with its reason
|
||||
const long MaxRequestBytes = 1024 * 1024;
|
||||
|
||||
readonly IModerationLog _log;
|
||||
readonly IStringLocalizer _localizer;
|
||||
readonly IMediaService _media;
|
||||
readonly ILocalActorService _localActors;
|
||||
|
||||
public EmojiAdminController(IModerationLog log, IStringLocalizer<GenericRes> localizer, IMediaService media, ILocalActorService localActors)
|
||||
{
|
||||
_log = log;
|
||||
_localizer = localizer;
|
||||
_media = media;
|
||||
_localActors = localActors;
|
||||
}
|
||||
|
||||
// the token says administrator; the database has the last word
|
||||
async Task<RootUser> Administrator(CancellationToken token)
|
||||
@@ -51,7 +43,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default;
|
||||
}
|
||||
|
||||
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(_localizer[message], status));
|
||||
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status));
|
||||
|
||||
[HttpGet, Route("list")]
|
||||
public async Task<IActionResult> List(CancellationToken token)
|
||||
@@ -73,7 +65,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var existing = await DB.Default.Find<LocalEmoji>().Match(e => e.Key == key).ExecuteFirstAsync(token);
|
||||
if (existing != default && (existing.DeletedAt == default || existing.Shortcode != form.Shortcode))
|
||||
return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.");
|
||||
var outcome = await _media.EmojiImage(form.Shortcode, await Picture(token), token);
|
||||
var outcome = await media.EmojiImage(form.Shortcode, await Picture(token), token);
|
||||
if (!outcome.Ok)
|
||||
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
|
||||
|
||||
@@ -100,12 +92,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.ModifiedCount > 0;
|
||||
if (!saved)
|
||||
{
|
||||
await _media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
|
||||
await media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
|
||||
return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.");
|
||||
}
|
||||
await LocalEmojis.Reload(CancellationToken.None);
|
||||
var notes = new[] { existing != default ? "added again" : default, emoji.Disabled ? "disabled" : default, Animated(emoji) }.Where(n => n != default).ToList();
|
||||
await _log.Write(admin.ID, AdminActions.EmojiInsert, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:",
|
||||
await log.Write(admin.ID, AdminActions.EmojiInsert, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:",
|
||||
note: notes.Count > 0 ? string.Join(", ", notes) : default, token: token);
|
||||
return Ok(View(emoji));
|
||||
}
|
||||
@@ -139,7 +131,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
MediaOutcome outcome = default;
|
||||
if (image != default)
|
||||
{
|
||||
outcome = await _media.EmojiImage(emoji.Shortcode, image, token);
|
||||
outcome = await media.EmojiImage(emoji.Shortcode, image, token);
|
||||
if (!outcome.Ok)
|
||||
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
|
||||
Picture(emoji, outcome.Attachment, now);
|
||||
@@ -151,14 +143,14 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if ((await DB.Default.Update<LocalEmoji>().Match(e => e.ID == emoji.ID && e.DeletedAt == null).ModifyWith(emoji).ExecuteAsync(token)).ModifiedCount == 0)
|
||||
{
|
||||
if (outcome != default)
|
||||
await _media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
|
||||
await media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
|
||||
return NotFound();//deleted meanwhile
|
||||
}
|
||||
if (outcome != default)
|
||||
{
|
||||
var use = LocalEmojis.ServerUse(emoji.Shortcode);
|
||||
if (previous.MediaId != default)
|
||||
await _media.Trash(m => m.ID == previous.MediaId && m.ServerUse == use, "emoji image replaced", token);
|
||||
await media.Trash(m => m.ID == previous.MediaId && m.ServerUse == use, "emoji image replaced", token);
|
||||
// the reactions made with it show the picture it has now
|
||||
if (previous.Url != default)
|
||||
{
|
||||
@@ -169,7 +161,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
}
|
||||
await LocalEmojis.Reload(CancellationToken.None);
|
||||
await _log.Write(admin.ID, AdminActions.EmojiUpdate, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", note: string.Join(", ", changed), token: token);
|
||||
await log.Write(admin.ID, AdminActions.EmojiUpdate, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", note: string.Join(", ", changed), token: token);
|
||||
return Ok(View(emoji));
|
||||
}
|
||||
|
||||
@@ -189,9 +181,9 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.Modify(e => e.DeletedAt, now).Modify(e => e.UpdatedAt, now).ExecuteAsync(token)).ModifiedCount == 0)
|
||||
return NotFound();
|
||||
var use = LocalEmojis.ServerUse(emoji.Shortcode);
|
||||
await _media.Trash(m => m.ID == emoji.MediaId && m.ServerUse == use, "emoji deleted", token);
|
||||
await media.Trash(m => m.ID == emoji.MediaId && m.ServerUse == use, "emoji deleted", token);
|
||||
await LocalEmojis.Reload(CancellationToken.None);
|
||||
await _log.Write(admin.ID, AdminActions.EmojiDelete, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", token: token);
|
||||
await log.Write(admin.ID, AdminActions.EmojiDelete, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", token: token);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@@ -211,8 +203,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
void Picture(LocalEmoji emoji, Models.Media.MediaAttachment attachment, DateTime now)
|
||||
{
|
||||
emoji.MediaId = attachment.ID;
|
||||
emoji.Url = _media.Url(attachment.FilePath);
|
||||
emoji.StaticUrl = attachment.PreviewPath == default ? emoji.Url : _media.Url(attachment.PreviewPath);
|
||||
emoji.Url = media.Url(attachment.FilePath);
|
||||
emoji.StaticUrl = attachment.PreviewPath == default ? emoji.Url : media.Url(attachment.PreviewPath);
|
||||
emoji.ContentType = attachment.ContentType;
|
||||
emoji.Width = attachment.Width;
|
||||
emoji.Height = attachment.Height;
|
||||
@@ -237,7 +229,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
Width = emoji.Width,
|
||||
Height = emoji.Height,
|
||||
Size = emoji.Size,
|
||||
Uri = LocalEmojis.Uri(_localActors.BaseAddress, emoji.Shortcode),
|
||||
Uri = LocalEmojis.Uri(localActors.BaseAddress, emoji.Shortcode),
|
||||
CreatedAt = emoji.CreatedAt,
|
||||
UpdatedAt = emoji.UpdatedAt,
|
||||
ImageUpdatedAt = emoji.ImageUpdatedAt
|
||||
|
||||
@@ -13,52 +13,45 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/group"),
|
||||
Authorize(Policy = Policies.IsUser)]
|
||||
public class GroupController : ControllerBase
|
||||
public class GroupController(
|
||||
IGroupUsersService groupUsersService,
|
||||
IStringLocalizer<GenericRes> localizer) : ControllerBase
|
||||
{
|
||||
readonly IGroupUsersService _groupUsersService;
|
||||
readonly IStringLocalizer _localizer;
|
||||
|
||||
public GroupController(IGroupUsersService groupUsersService, IStringLocalizer<GenericRes> localizer)
|
||||
{
|
||||
_groupUsersService = groupUsersService;
|
||||
_localizer = localizer;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/group/list")]
|
||||
public async Task<IActionResult> List([FromQuery] string avatarId, CancellationToken token) =>
|
||||
Answer(await _groupUsersService.GetGroups(User.GetUserId(), avatarId, token));
|
||||
Answer(await groupUsersService.GetGroups(User.GetUserId(), avatarId, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/insert")]
|
||||
public async Task<IActionResult> Insert(InsertGroupForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.InsertGroup(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.InsertGroup(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/update")]
|
||||
public async Task<IActionResult> Update(UpdateGroupForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.UpdateGroup(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.UpdateGroup(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/join")]
|
||||
public async Task<IActionResult> Join(JoinGroupForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.JoinGroup(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.JoinGroup(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/leave")]
|
||||
public async Task<IActionResult> Leave(GroupMembershipForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.LeaveGroup(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.LeaveGroup(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/approve")]
|
||||
public async Task<IActionResult> Approve(GroupMembershipForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.ApproveMember(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.ApproveMember(User.GetUserId(), form, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/group/members")]
|
||||
public async Task<IActionResult> Members([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) =>
|
||||
Answer(await _groupUsersService.GetMembers(User.GetUserId(), avatarId, groupId, token));
|
||||
Answer(await groupUsersService.GetMembers(User.GetUserId(), avatarId, groupId, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/reject")]
|
||||
public async Task<IActionResult> Reject(GroupMembershipForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.RejectMember(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.RejectMember(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/group/remove")]
|
||||
public async Task<IActionResult> Remove(GroupMembershipForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.RemoveMember(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await groupUsersService.RemoveMember(User.GetUserId(), form, token));
|
||||
|
||||
// the group's owner deletes it, with the login's password (R6): its members and followers are told, its name stays
|
||||
// taken (GroupRemoval)
|
||||
@@ -69,19 +62,19 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (!ModelState.IsValid)
|
||||
return Invalid();
|
||||
var rootId = User.GetUserId();
|
||||
if (!await users.PasswordMatches(rootId, form.Password))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer[RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
if (!await users.PasswordMatches(rootId, form.Password, token))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
var owns = await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token);
|
||||
var group = owns ? await dbEntities.Groups.MatchID(form.GroupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token) : default;
|
||||
if (group == default)
|
||||
return NotFound(new WebResult().Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound));
|
||||
return NotFound(new WebResult().Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound));
|
||||
if (group.OwnerAvatarId != form.AvatarId)
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer["Only the group's owner can delete it."], StatusCodes.Status403Forbidden));
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer["Only the group's owner can delete it."], StatusCodes.Status403Forbidden));
|
||||
await groups.Remove(group.ID, CancellationToken.None);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
|
||||
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
@@ -30,26 +30,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/admin"),
|
||||
Authorize(Policy = Policies.IsAdmin)]
|
||||
public class InstanceAdminController : ControllerBase
|
||||
public class InstanceAdminController(
|
||||
IInstanceSettings instanceSettings,
|
||||
IModerationLog moderationLog,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILocalActorService localActors,
|
||||
ILogger<InstanceAdminController> logger) : ControllerBase
|
||||
{
|
||||
const int MaxSettingsRelays = 20;
|
||||
const string Thumbnail = "thumbnail";
|
||||
|
||||
readonly IInstanceSettings _settings;
|
||||
readonly IModerationLog _log;
|
||||
readonly IStringLocalizer _localizer;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly ILogger<InstanceAdminController> _logger;
|
||||
|
||||
public InstanceAdminController(IInstanceSettings settings, IModerationLog log, IStringLocalizer<GenericRes> localizer, ILocalActorService localActors,
|
||||
ILogger<InstanceAdminController> logger)
|
||||
{
|
||||
_settings = settings;
|
||||
_log = log;
|
||||
_localizer = localizer;
|
||||
_localActors = localActors;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// the token says administrator; the database has the last word
|
||||
async Task<RootUser> Administrator(CancellationToken token)
|
||||
@@ -58,7 +48,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default;
|
||||
}
|
||||
|
||||
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(_localizer[message], status));
|
||||
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status));
|
||||
|
||||
#region settings
|
||||
|
||||
@@ -67,7 +57,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
if (await Administrator(token) == default)
|
||||
return Forbid();
|
||||
return Ok(await View(_settings.Current, token));
|
||||
return Ok(await View(instanceSettings.Current, token));
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/admin/settings")]
|
||||
@@ -86,7 +76,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var changed = new List<string>();
|
||||
var ruleActs = new List<(string Action, ServerRule Rule)>();
|
||||
var now = DateTime.UtcNow;
|
||||
var saved = await _settings.Update(settings =>
|
||||
var saved = await instanceSettings.Update(settings =>
|
||||
{
|
||||
void Set(string name, string value, Func<string> get, Action<string> set)
|
||||
{
|
||||
@@ -175,9 +165,9 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}, admin.ID, token);
|
||||
|
||||
if (changed.Count > 0)
|
||||
await _log.Write(admin.ID, AdminActions.SettingsUpdate, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: string.Join(", ", changed), token: token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.SettingsUpdate, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: string.Join(", ", changed), token: token);
|
||||
foreach (var (action, rule) in ruleActs)
|
||||
await _log.Write(admin.ID, action, AdminTargets.Rule, rule.Id, rule.Text, token: token);
|
||||
await moderationLog.Write(admin.ID, action, AdminTargets.Rule, rule.Id, rule.Text, token: token);
|
||||
return Ok(await View(saved, token));
|
||||
}
|
||||
|
||||
@@ -194,7 +184,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (!outcome.Ok)
|
||||
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
|
||||
var previous = default(string);
|
||||
var saved = await _settings.Update(settings =>
|
||||
var saved = await instanceSettings.Update(settings =>
|
||||
{
|
||||
previous = settings.ThumbnailMediaId;
|
||||
settings.ThumbnailMediaId = outcome.Attachment.ID;
|
||||
@@ -202,7 +192,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}, admin.ID, token);
|
||||
if (previous != default)
|
||||
await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail replaced", token);
|
||||
await _log.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "replaced", token: token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "replaced", token: token);
|
||||
return Ok(await View(saved, token));
|
||||
}
|
||||
|
||||
@@ -213,7 +203,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (admin == default)
|
||||
return Forbid();
|
||||
var previous = default(string);
|
||||
var saved = await _settings.Update(settings =>
|
||||
var saved = await instanceSettings.Update(settings =>
|
||||
{
|
||||
previous = settings.ThumbnailMediaId;
|
||||
settings.ThumbnailMediaId = default;
|
||||
@@ -222,7 +212,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (previous != default)
|
||||
{
|
||||
await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail removed", token);
|
||||
await _log.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "removed", token: token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "removed", token: token);
|
||||
}
|
||||
return Ok(await View(saved, token));
|
||||
}
|
||||
@@ -257,9 +247,9 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
Id = contact.ID,
|
||||
UserName = contact.UserName,
|
||||
Name = contact.Name,
|
||||
Handle = _localActors.FromAvatar(contact).Handle
|
||||
Handle = localActors.FromAvatar(contact).Handle
|
||||
},
|
||||
ThumbnailUrl = settings.ThumbnailUrl ?? $"{_localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}",
|
||||
ThumbnailUrl = settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}",
|
||||
ThumbnailIsDefault = settings.ThumbnailUrl == default,
|
||||
PrivacyPolicy = settings.PrivacyPolicy,
|
||||
PrivacyPolicyUpdatedAt = settings.PrivacyPolicyUpdatedAt,
|
||||
@@ -322,7 +312,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (Invalid(form) is { } refused)
|
||||
return refused;
|
||||
var made = await announcements.Insert(Draft(form), token);
|
||||
await _log.Write(admin.ID, AdminActions.AnnouncementInsert, AdminTargets.Announcement, made.ID, made.Text,
|
||||
await moderationLog.Write(admin.ID, AdminActions.AnnouncementInsert, AdminTargets.Announcement, made.ID, made.Text,
|
||||
note: made.IsPublished ? "published" : "draft", token: token);
|
||||
return Ok(await View(made, token));
|
||||
}
|
||||
@@ -338,7 +328,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var updated = await announcements.Update(form.Id, Draft(form), token);
|
||||
if (updated == default)
|
||||
return NotFound();
|
||||
await _log.Write(admin.ID, AdminActions.AnnouncementUpdate, AdminTargets.Announcement, updated.ID, updated.Text,
|
||||
await moderationLog.Write(admin.ID, AdminActions.AnnouncementUpdate, AdminTargets.Announcement, updated.ID, updated.Text,
|
||||
note: updated.IsPublished ? "published" : "draft", token: token);
|
||||
return Ok(await View(updated, token));
|
||||
}
|
||||
@@ -352,7 +342,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var deleted = await announcements.Delete(id, token);
|
||||
if (deleted == default)
|
||||
return NotFound();
|
||||
await _log.Write(admin.ID, AdminActions.AnnouncementDelete, AdminTargets.Announcement, deleted.ID, deleted.Text, token: token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.AnnouncementDelete, AdminTargets.Announcement, deleted.ID, deleted.Text, token: token);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@@ -398,7 +388,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
if (await Administrator(token) == default)
|
||||
return Forbid();
|
||||
return Ok(await StaffPickViews(_settings.Current, token));
|
||||
return Ok(await StaffPickViews(instanceSettings.Current, token));
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/admin/staff-picks/insert")]
|
||||
@@ -411,16 +401,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var picked = await Pickable(id, token);
|
||||
if (picked == default)
|
||||
return Refused(StatusCodes.Status404NotFound, "No such account to suggest.");
|
||||
if (_settings.Current.StaffPicks.Contains(id))
|
||||
if (instanceSettings.Current.StaffPicks.Contains(id))
|
||||
return Refused(StatusCodes.Status409Conflict, "This account is suggested already.");
|
||||
if (_settings.Current.StaffPicks.Count >= MaxStaffPicks)
|
||||
if (instanceSettings.Current.StaffPicks.Count >= MaxStaffPicks)
|
||||
return Refused(StatusCodes.Status422UnprocessableEntity, "40 accounts at most are suggested.");
|
||||
var saved = await _settings.Update(settings =>
|
||||
var saved = await instanceSettings.Update(settings =>
|
||||
{
|
||||
if (!settings.StaffPicks.Contains(id))
|
||||
settings.StaffPicks.Add(id);
|
||||
}, admin.ID, token);
|
||||
await _log.Write(admin.ID, AdminActions.StaffPickInsert, picked.Value.IsLocal ? AdminTargets.Persona : AdminTargets.Account, id, picked.Value.Handle,
|
||||
await moderationLog.Write(admin.ID, AdminActions.StaffPickInsert, picked.Value.IsLocal ? AdminTargets.Persona : AdminTargets.Account, id, picked.Value.Handle,
|
||||
token: token);
|
||||
return Ok(await StaffPickViews(saved, token));
|
||||
}
|
||||
@@ -432,11 +422,11 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (admin == default)
|
||||
return Forbid();
|
||||
accountId = accountId?.Trim();
|
||||
if (string.IsNullOrEmpty(accountId) || !_settings.Current.StaffPicks.Contains(accountId))
|
||||
if (string.IsNullOrEmpty(accountId) || !instanceSettings.Current.StaffPicks.Contains(accountId))
|
||||
return NotFound();
|
||||
var view = (await StaffPickViews(_settings.Current, token)).FirstOrDefault(p => p.AccountId == accountId);
|
||||
var saved = await _settings.Update(settings => settings.StaffPicks.Remove(accountId), admin.ID, token);
|
||||
await _log.Write(admin.ID, AdminActions.StaffPickDelete, view?.IsLocal == true ? AdminTargets.Persona : AdminTargets.Account, accountId,
|
||||
var view = (await StaffPickViews(instanceSettings.Current, token)).FirstOrDefault(p => p.AccountId == accountId);
|
||||
var saved = await instanceSettings.Update(settings => settings.StaffPicks.Remove(accountId), admin.ID, token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.StaffPickDelete, view?.IsLocal == true ? AdminTargets.Persona : AdminTargets.Account, accountId,
|
||||
view?.Handle ?? accountId, token: token);
|
||||
return Ok(await StaffPickViews(saved, token));
|
||||
}
|
||||
@@ -451,7 +441,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return default;
|
||||
var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue && !a.SuspendedAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (avatar != default)
|
||||
return (await Counted.HeldBackPersonas(token)).Contains(avatar.ID) ? ((bool, string)?)null : (true, _localActors.FromAvatar(avatar).Handle);
|
||||
return (await Counted.HeldBackPersonas(token)).Contains(avatar.ID) ? ((bool, string)?)null : (true, localActors.FromAvatar(avatar).Handle);
|
||||
var foreign = await DB.Default.Find<ForeignAvatar>().Match(f => f.ID == id && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue
|
||||
&& (f.AvatarType == AvatarType.Person || f.AvatarType == AvatarType.Service || f.AvatarType == AvatarType.Organization)).ExecuteFirstAsync(token);
|
||||
return foreign == default ? ((bool, string)?)null : (false, $"{foreign.UserName}@{foreign.Domain}");
|
||||
@@ -468,7 +458,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
AccountId = id,
|
||||
IsLocal = true,
|
||||
Handle = _localActors.FromAvatar(avatar).Handle,
|
||||
Handle = localActors.FromAvatar(avatar).Handle,
|
||||
Name = avatar.Name,
|
||||
IsShown = avatar.DeletionAt == default && avatar.SuspendedAt == default && avatar.SilencedAt == default && !held.Contains(id)
|
||||
}
|
||||
@@ -492,7 +482,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
if (await Administrator(token) == default)
|
||||
return Forbid();
|
||||
return Ok(await RelayViews(_settings.Current, token));
|
||||
return Ok(await RelayViews(instanceSettings.Current, token));
|
||||
}
|
||||
|
||||
// a relay named by the settings: subscribed to at once (in the background: resolving it is a fetch), the page polls
|
||||
@@ -508,16 +498,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return Refused(StatusCodes.Status422UnprocessableEntity, "A relay is named by the https address of its actor or its inbox.");
|
||||
if (relays.Configured.Contains(address))
|
||||
return Refused(StatusCodes.Status409Conflict, "The configuration names this relay already.");
|
||||
if (_settings.Current.Relays.Contains(address))
|
||||
return Ok(await RelayViews(_settings.Current, token));
|
||||
if (_settings.Current.Relays.Count >= MaxSettingsRelays)
|
||||
if (instanceSettings.Current.Relays.Contains(address))
|
||||
return Ok(await RelayViews(instanceSettings.Current, token));
|
||||
if (instanceSettings.Current.Relays.Count >= MaxSettingsRelays)
|
||||
return Refused(StatusCodes.Status422UnprocessableEntity, "The settings name 20 relays at most.");
|
||||
var saved = await _settings.Update(settings =>
|
||||
var saved = await instanceSettings.Update(settings =>
|
||||
{
|
||||
if (!settings.Relays.Contains(address))
|
||||
settings.Relays.Add(address);
|
||||
}, admin.ID, token);
|
||||
await _log.Write(admin.ID, AdminActions.RelayInsert, AdminTargets.Relay, address, address, token: token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.RelayInsert, AdminTargets.Relay, address, address, token: token);
|
||||
Reconcile(relays);
|
||||
return Accepted(await RelayViews(saved, token));
|
||||
}
|
||||
@@ -532,10 +522,10 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
address = address?.Trim();
|
||||
if (relays.Configured.Contains(address))
|
||||
return Refused(StatusCodes.Status409Conflict, "This relay is named by the configuration (Federation:Relays): remove it there.");
|
||||
if (string.IsNullOrEmpty(address) || !_settings.Current.Relays.Contains(address))
|
||||
if (string.IsNullOrEmpty(address) || !instanceSettings.Current.Relays.Contains(address))
|
||||
return NotFound();
|
||||
var saved = await _settings.Update(settings => settings.Relays.Remove(address), admin.ID, token);
|
||||
await _log.Write(admin.ID, AdminActions.RelayDelete, AdminTargets.Relay, address, address, token: token);
|
||||
var saved = await instanceSettings.Update(settings => settings.Relays.Remove(address), admin.ID, token);
|
||||
await moderationLog.Write(admin.ID, AdminActions.RelayDelete, AdminTargets.Relay, address, address, token: token);
|
||||
Reconcile(relays);
|
||||
return Accepted(await RelayViews(saved, token));
|
||||
}
|
||||
@@ -548,7 +538,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Relay subscriptions could not be brought up to date");
|
||||
logger.LogWarning(ex, "Relay subscriptions could not be brought up to date");
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
|
||||
|
||||
@@ -17,32 +17,22 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/moderator"),
|
||||
Authorize(Policy = Policies.IsModerator)]
|
||||
public class ModeratorController : ControllerBase
|
||||
public class ModeratorController(
|
||||
IInstanceSettings settings,
|
||||
IModerationLog moderationLog,
|
||||
IAccountModeration accountModeration,
|
||||
Federation.Actors.ILocalActorService localActors,
|
||||
Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> localizer) : ControllerBase
|
||||
{
|
||||
const int MaxLogPage = 100;
|
||||
|
||||
const int MaxAccountsPage = 100;
|
||||
|
||||
readonly IInstanceSettings _settings;
|
||||
readonly IModerationLog _log;
|
||||
readonly IAccountModeration _moderation;
|
||||
readonly Federation.Actors.ILocalActorService _localActors;
|
||||
readonly Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> _localizer;
|
||||
|
||||
public ModeratorController(IInstanceSettings settings, IModerationLog log, IAccountModeration moderation,
|
||||
Federation.Actors.ILocalActorService localActors, Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> localizer)
|
||||
{
|
||||
_settings = settings;
|
||||
_log = log;
|
||||
_moderation = moderation;
|
||||
_localActors = localActors;
|
||||
_localizer = localizer;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/moderator/reports")]
|
||||
public async Task<IActionResult> Reports([FromQuery] bool resolved, CancellationToken token)
|
||||
{
|
||||
var rules = _settings.Current.Rules.ToDictionary(r => r.Id, r => r.Text ?? string.Empty);
|
||||
var rules = settings.Current.Rules.ToDictionary(r => r.Id, r => r.Text ?? string.Empty);
|
||||
return Ok((await DB.Default.Find<Report>().Match(r => r.IsResolved == resolved).Sort(r => r.ID, Order.Descending).Limit(100).ExecuteAsync(token))
|
||||
.Select(r => new ViewReport
|
||||
{
|
||||
@@ -77,7 +67,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
form ??= new ResolveReportForm();
|
||||
var action = string.IsNullOrWhiteSpace(form.Action) ? ModerationActions.None : form.Action.Trim().ToLowerInvariant();
|
||||
if (!ModerationActions.IsResolution(action))
|
||||
return UnprocessableEntity(new WebResult().Invalidate(_localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity));
|
||||
return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity));
|
||||
var by = User.GetUserId();
|
||||
var report = await DB.Default.Find<Report>().MatchID(id).ExecuteFirstAsync(token);
|
||||
if (report == default)
|
||||
@@ -85,16 +75,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
switch (action)
|
||||
{
|
||||
case ModerationActions.Silence or ModerationActions.Suspend:
|
||||
var moderated = await _moderation.Moderate(by, report.TargetAccountId, action, form.Note, form.Warning, report.ID, token);
|
||||
var moderated = await accountModeration.Moderate(by, report.TargetAccountId, action, form.Note, form.Warning, report.ID, token);
|
||||
if (!moderated.IsValid)
|
||||
return StatusCode(moderated.StatusCode, moderated);
|
||||
break;
|
||||
case ModerationActions.RemovePosts:
|
||||
if (report.PostIds.Count == 0)
|
||||
return UnprocessableEntity(new WebResult().Invalidate(_localizer["The report names no posts."], StatusCodes.Status422UnprocessableEntity));
|
||||
return UnprocessableEntity(new WebResult().Invalidate(localizer["The report names no posts."], StatusCodes.Status422UnprocessableEntity));
|
||||
foreach (var postId in report.PostIds)
|
||||
{
|
||||
var removed = await _moderation.RemovePost(by, postId, form.Note, form.Warning, report.ID, token);
|
||||
var removed = await accountModeration.RemovePost(by, postId, form.Note, form.Warning, report.ID, token);
|
||||
if (!removed.IsValid && removed.StatusCode != StatusCodes.Status404NotFound)//one already gone is removed
|
||||
return StatusCode(removed.StatusCode, removed);
|
||||
}
|
||||
@@ -107,7 +97,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.Modify(r => r.Resolution, action)
|
||||
.Modify(r => r.ResolutionNote, string.IsNullOrWhiteSpace(form.Note) ? null : form.Note.Trim())
|
||||
.ExecuteAsync(CancellationToken.None);
|
||||
await _log.Write(by, AdminActions.ReportResolve, AdminTargets.Report, id, report.Category, reportId: id,
|
||||
await moderationLog.Write(by, AdminActions.ReportResolve, AdminTargets.Report, id, report.Category, reportId: id,
|
||||
note: action == ModerationActions.None ? form.Note : string.IsNullOrWhiteSpace(form.Note) ? action : $"{action}: {form.Note.Trim()}",
|
||||
token: CancellationToken.None);
|
||||
return Ok();
|
||||
@@ -125,21 +115,21 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return Ok(new ViewModeratedAccountsPage { Items = items });
|
||||
if (Uri.TryCreate(q, UriKind.Absolute, out var address) && address.Scheme is "https" or "http")
|
||||
{
|
||||
if (await _localActors.FindByUri(q, token) is { Kind: Models.Federation.LocalActorKind.Person } local
|
||||
if (await localActors.FindByUri(q, token) is { Kind: Models.Federation.LocalActorKind.Person } local
|
||||
&& await DB.Default.Find<Avatar>().MatchID(local.Id).ExecuteFirstAsync(token) is { } persona)
|
||||
items.Add(_moderation.View(persona));
|
||||
items.AddRange((await DB.Default.Find<ForeignAvatar>().Match(f => f.ActorURI == q || f.Url == q).Limit(limit).ExecuteAsync(token)).Select(_moderation.View));
|
||||
items.Add(accountModeration.View(persona));
|
||||
items.AddRange((await DB.Default.Find<ForeignAvatar>().Match(f => f.ActorURI == q || f.Url == q).Limit(limit).ExecuteAsync(token)).Select(accountModeration.View));
|
||||
return Ok(new ViewModeratedAccountsPage { Items = items.Take(limit).ToList() });
|
||||
}
|
||||
var parts = q.Split('@', 2);
|
||||
var name = parts[0];
|
||||
var domain = parts.Length > 1 ? parts[1].ToLowerInvariant() : default;
|
||||
var here = new Uri(_localActors.BaseAddress).Authority;
|
||||
var here = new Uri(localActors.BaseAddress).Authority;
|
||||
if (domain == default || domain == here)
|
||||
{
|
||||
var lowered = name.ToLowerInvariant();
|
||||
items.AddRange((await DB.Default.Find<Avatar>().Match(a => a.UserName.StartsWith(lowered) && !a.DeletionAt.HasValue)
|
||||
.Sort(a => a.UserName, Order.Ascending).Limit(limit).ExecuteAsync(token)).Select(_moderation.View));
|
||||
.Sort(a => a.UserName, Order.Ascending).Limit(limit).ExecuteAsync(token)).Select(accountModeration.View));
|
||||
}
|
||||
if (domain != here && items.Count < limit && name.Length > 0)
|
||||
{
|
||||
@@ -148,7 +138,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (domain != default)
|
||||
remote.Match(f => f.Regex(a => a.Domain, new MongoDB.Bson.BsonRegularExpression("^" + System.Text.RegularExpressions.Regex.Escape(domain), "i")));
|
||||
items.AddRange((await remote.Match(f => !f.DeletionAt.HasValue).Sort(f => f.UserName, Order.Ascending).Limit(limit - items.Count).ExecuteAsync(token))
|
||||
.Select(_moderation.View));
|
||||
.Select(accountModeration.View));
|
||||
}
|
||||
return Ok(new ViewModeratedAccountsPage { Items = items });
|
||||
}
|
||||
@@ -162,7 +152,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
limit = Math.Clamp(limit, 1, MaxAccountsPage);
|
||||
var locals = await DB.Default.Find<Avatar>().Match(a => (a.SilencedAt != null || a.SuspendedAt != null) && a.DeletionAt == null).ExecuteAsync(token);
|
||||
var remotes = await DB.Default.Find<ForeignAvatar>().Match(f => f.SilencedAt != null || f.SuspendedAt != null).ExecuteAsync(token);
|
||||
var all = locals.Select(_moderation.View).Concat(remotes.Select(_moderation.View))
|
||||
var all = locals.Select(accountModeration.View).Concat(remotes.Select(accountModeration.View))
|
||||
.OrderByDescending(a => Latest(a.SilencedAt, a.SuspendedAt)).ThenBy(a => a.Id, StringComparer.Ordinal).ToList();
|
||||
return Ok(new ViewModeratedAccountsPage
|
||||
{
|
||||
@@ -175,15 +165,15 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
|
||||
[HttpGet, Route("/clientapi/moderator/accounts/{id}")]
|
||||
public async Task<IActionResult> Account(string id, CancellationToken token) =>
|
||||
await _moderation.View(id, token) is { } account ? Ok(account) : NotFound();
|
||||
await accountModeration.View(id, token) is { } account ? Ok(account) : NotFound();
|
||||
|
||||
// silence, unsilence, suspend or unsuspend a persona here or an account elsewhere
|
||||
[HttpPost, Route("/clientapi/moderator/accounts/moderate")]
|
||||
public async Task<IActionResult> Moderate(ModerateAccountForm form, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
var result = await _moderation.Moderate(User.GetUserId(), form.AccountId, form.Action.Trim().ToLowerInvariant(), form.Note, form.Warning, default, token);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await accountModeration.Moderate(User.GetUserId(), form.AccountId, form.Action.Trim().ToLowerInvariant(), form.Note, form.Warning, default, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
@@ -192,8 +182,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> RemovePost(RemovePostForm form, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
var result = await _moderation.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await accountModeration.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token);
|
||||
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,46 +13,39 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/post"),
|
||||
Authorize(Policy = Policies.IsUser)]
|
||||
public class PostController : ControllerBase
|
||||
public class PostController(
|
||||
IPostsService postsService,
|
||||
IStringLocalizer<GenericRes> localizer) : ControllerBase
|
||||
{
|
||||
readonly IPostsService _postsService;
|
||||
readonly IStringLocalizer _localizer;
|
||||
|
||||
public PostController(IPostsService postsService, IStringLocalizer<GenericRes> localizer)
|
||||
{
|
||||
_postsService = postsService;
|
||||
_localizer = localizer;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/post/list")]
|
||||
public async Task<IActionResult> List([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) =>
|
||||
Answer(await _postsService.GetPosts(User.GetUserId(), avatarId, groupId, token));
|
||||
Answer(await postsService.GetPosts(User.GetUserId(), avatarId, groupId, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/post/insert")]
|
||||
public async Task<IActionResult> Insert(InsertPostForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _postsService.InsertPost(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await postsService.InsertPost(User.GetUserId(), form, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/post/nearby")]
|
||||
public async Task<IActionResult> Nearby([FromQuery] string avatarId, [FromQuery] double latitude, [FromQuery] double longitude, CancellationToken token) =>
|
||||
Answer(await _postsService.Nearby(User.GetUserId(), avatarId, latitude, longitude, token));
|
||||
Answer(await postsService.Nearby(User.GetUserId(), avatarId, latitude, longitude, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/post/update")]
|
||||
public async Task<IActionResult> Update(UpdatePostForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _postsService.UpdatePost(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await postsService.UpdatePost(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/post/delete")]
|
||||
public async Task<IActionResult> Delete(DeletePostForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _postsService.DeletePost(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await postsService.DeletePost(User.GetUserId(), form, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/dm/list")]
|
||||
public async Task<IActionResult> Dms([FromQuery] string avatarId, [FromQuery] string dmGroupId, CancellationToken token) =>
|
||||
Answer(await _postsService.GetDms(User.GetUserId(), avatarId, dmGroupId, token));
|
||||
Answer(await postsService.GetDms(User.GetUserId(), avatarId, dmGroupId, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/dm/insert")]
|
||||
public async Task<IActionResult> InsertDm(InsertDmForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _postsService.InsertDm(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await postsService.InsertDm(User.GetUserId(), form, token));
|
||||
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
|
||||
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
@@ -13,38 +13,28 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/avatar/private"),
|
||||
Authorize(Policy = Policies.IsUser)]
|
||||
public class PrivateAvatarController : ControllerBase
|
||||
public class PrivateAvatarController(
|
||||
IPrivateAvatarUsersService privateAvatarUsersService,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PrivateAvatarController> logger) : ControllerBase
|
||||
{
|
||||
readonly ILogger<PrivateAvatarController> _logger;
|
||||
readonly IPrivateAvatarUsersService _privateAvatarUsersService;
|
||||
readonly IStringLocalizer _localizer;
|
||||
|
||||
public PrivateAvatarController(IPrivateAvatarUsersService privateAvatarUsersService,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<PrivateAvatarController> logger)
|
||||
{
|
||||
_privateAvatarUsersService = privateAvatarUsersService;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/avatar/private/list")]
|
||||
public async Task<IActionResult> GetAvatars(CancellationToken token)
|
||||
{
|
||||
var result = await _privateAvatarUsersService.GetRootAvatars(User.GetUserId(), token);
|
||||
var result = await privateAvatarUsersService.GetRootAvatars(User.GetUserId(), token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/avatar/private/insert")]
|
||||
public async Task<IActionResult> InsertAvatar(InsertAvatarForm model)
|
||||
public async Task<IActionResult> InsertAvatar(InsertAvatarForm model, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(_localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
model.RootId = User.GetUserId();
|
||||
result = await _privateAvatarUsersService.InsertAvatar(model);
|
||||
result = await privateAvatarUsersService.InsertAvatar(model, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -52,8 +42,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()");
|
||||
return BadRequest(result.Invalidate(_localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,13 +54,13 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[FromServices] Services.IPersonaRemoval personas, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var rootId = User.GetUserId();
|
||||
if (!await users.PasswordMatches(rootId, form.Password))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
if (!await users.PasswordMatches(rootId, form.Password, token))
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
|
||||
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token)
|
||||
|| !await personas.Remove(form.AvatarId, CancellationToken.None))
|
||||
return NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound));
|
||||
return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound));
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@@ -80,7 +70,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var avatar = await OwnPersona(avatarId, dbEntities, token);
|
||||
return avatar == default
|
||||
? NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound))
|
||||
? NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound))
|
||||
: Ok(PreferencesOf(avatar));
|
||||
}
|
||||
|
||||
@@ -88,12 +78,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> SavePreferences(PersonaPreferencesForm form, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
if (!Models.User.ExpandMediaModes.IsKnown(form.ExpandMedia))
|
||||
return UnprocessableEntity(new WebResult().Invalidate(_localizer["Media are shown as default, show_all or hide_all."], StatusCodes.Status422UnprocessableEntity));
|
||||
return UnprocessableEntity(new WebResult().Invalidate(localizer["Media are shown as default, show_all or hide_all."], StatusCodes.Status422UnprocessableEntity));
|
||||
var avatar = await OwnPersona(form.AvatarId, dbEntities, token);
|
||||
if (avatar == default)
|
||||
return NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound));
|
||||
return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound));
|
||||
await MongoDB.Entities.DB.Default.Update<Models.User.Avatar>().MatchID(avatar.ID)
|
||||
.Modify(a => a.Settings.ExpandMedia, form.ExpandMedia)
|
||||
.Modify(a => a.Settings.ExpandSpoilers, form.ExpandSpoilers)
|
||||
@@ -120,15 +110,15 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
};
|
||||
|
||||
[HttpPost, Route("/clientapi/avatar/private/update")]
|
||||
public async Task<IActionResult> UpdateAvatar(UpdateAvatarForm model)
|
||||
public async Task<IActionResult> UpdateAvatar(UpdateAvatarForm model, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(_localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
model.RootId = User.GetUserId();
|
||||
result = await _privateAvatarUsersService.UpdateAvatar(model);
|
||||
result = await privateAvatarUsersService.UpdateAvatar(model, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -136,8 +126,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()");
|
||||
return BadRequest(result.Invalidate(_localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,90 +28,68 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
[ApiController,
|
||||
Route("clientapi/user")]
|
||||
public class RootUserController : ControllerBase
|
||||
public class RootUserController(
|
||||
IRootUsersService usersService,
|
||||
IGroupUsersService groupUsersService,
|
||||
IPrivateAvatarUsersService avatarUsersService,
|
||||
ILocalActorService localActors,
|
||||
AuthTokenManager authTokenManager,
|
||||
IOptionsMonitor<AppConfiguration> appConfiguration,
|
||||
IOptionsMonitor<RegistrationOptions> registrations,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<RootUserController> logger) : ControllerBase
|
||||
{
|
||||
readonly IRootUsersService UsersService;
|
||||
readonly IGroupUsersService GroupUsersService;
|
||||
readonly IPrivateAvatarUsersService AvatarUsersService;
|
||||
readonly ILocalActorService LocalActors;
|
||||
readonly AuthTokenManager AuthTokenManager;
|
||||
readonly IOptionsMonitor<AppConfiguration> AppConfiguration;
|
||||
readonly IOptionsMonitor<RegistrationOptions> Registrations;
|
||||
readonly ILogger<RootUserController> Logger;
|
||||
readonly IStringLocalizer Localizer;
|
||||
|
||||
public RootUserController(IRootUsersService usersService,
|
||||
IGroupUsersService groupUsersService,
|
||||
IPrivateAvatarUsersService avatarUsersService,
|
||||
ILocalActorService localActors,
|
||||
AuthTokenManager authTokenManager,
|
||||
IOptionsMonitor<AppConfiguration> appConfiguration,
|
||||
IOptionsMonitor<RegistrationOptions> registrations,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<RootUserController> logger)
|
||||
{
|
||||
Registrations = registrations;
|
||||
UsersService = usersService;
|
||||
GroupUsersService = groupUsersService;
|
||||
AvatarUsersService = avatarUsersService;
|
||||
LocalActors = localActors;
|
||||
AuthTokenManager = authTokenManager;
|
||||
AppConfiguration = appConfiguration;
|
||||
Localizer = localizer;
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
#region User endpoints
|
||||
|
||||
[HttpPost, Route("/clientapi/user/signup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
|
||||
public async Task<IActionResult> SignUp(LoginForm signUpForm)
|
||||
public async Task<IActionResult> SignUp(LoginForm signUpForm, CancellationToken token = default)
|
||||
{
|
||||
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
||||
var result = new WebResult();
|
||||
if (!Registrations.CurrentValue.IsOpen)
|
||||
return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(Localizer[RegistrationOptions.ClosedMessage], StatusCodes.Status403Forbidden));
|
||||
if (!registrations.CurrentValue.IsOpen)
|
||||
return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(localizer[RegistrationOptions.ClosedMessage], StatusCodes.Status403Forbidden));
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.SignUpAsync(signUpForm);
|
||||
result = await usersService.SignUpAsync(signUpForm, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
(var user, var userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
||||
var jwtUser = AuthTokenManager.GenerateToken(user, userSettings);
|
||||
var jwtUser = authTokenManager.GenerateToken(user, userSettings);
|
||||
return Ok(jwtUser);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/login"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
|
||||
public async Task<IActionResult> Login(LoginForm loginForm)
|
||||
public async Task<IActionResult> Login(LoginForm loginForm, CancellationToken token = default)
|
||||
{
|
||||
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.LoginAsync(loginForm);
|
||||
result = await usersService.LoginAsync(loginForm, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
var (user, userSettings) =
|
||||
((RootUser, ViewUserSettings))result.Data;
|
||||
var jwtUser = AuthTokenManager.GenerateToken(user, userSettings);
|
||||
var jwtUser = authTokenManager.GenerateToken(user, userSettings);
|
||||
|
||||
return Ok(jwtUser);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,10 +98,10 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
var invitation = await GroupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token);
|
||||
var invitation = await groupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token);
|
||||
if (!invitation.IsValid)
|
||||
return StatusCode(invitation.StatusCode, invitation);
|
||||
|
||||
@@ -132,16 +110,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (personaProblem != default)
|
||||
return BadRequest(result.Invalidate(personaProblem));
|
||||
|
||||
result = await UsersService.SignUpAsync(signUpForm);
|
||||
result = await usersService.SignUpAsync(signUpForm, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
||||
|
||||
var avatar = await InsertPersona(user.ID, avatarUserName, signUpForm.AvatarName);
|
||||
var avatar = await InsertPersona(user.ID, avatarUserName, signUpForm.AvatarName, token);
|
||||
if (!avatar.IsValid)
|
||||
return StatusCode(avatar.StatusCode, avatar);
|
||||
|
||||
var joined = await GroupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
||||
var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
||||
{
|
||||
AvatarId = ((ViewAvatar)avatar.Data).Id,
|
||||
InvitationCode = signUpForm.InvitationCode,
|
||||
@@ -150,12 +128,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (!joined.IsValid)
|
||||
return StatusCode(joined.StatusCode, joined);
|
||||
|
||||
return Ok(AuthTokenManager.GenerateToken(user, userSettings));
|
||||
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,19 +142,19 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
var invitation = await GroupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token);
|
||||
var invitation = await groupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token);
|
||||
if (!invitation.IsValid)
|
||||
return StatusCode(invitation.StatusCode, invitation);
|
||||
|
||||
result = await UsersService.LoginAsync(loginForm);
|
||||
result = await usersService.LoginAsync(loginForm, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
||||
|
||||
var avatars = await AvatarUsersService.GetRootAvatars(user.ID, token);
|
||||
var avatars = await avatarUsersService.GetRootAvatars(user.ID, token);
|
||||
var avatarUserName = loginForm.AvatarUserName?.Trim().ToLowerInvariant();
|
||||
var avatar = string.IsNullOrEmpty(avatarUserName)
|
||||
? (avatars.Data as List<ViewAvatar>)?.FirstOrDefault()
|
||||
@@ -186,13 +164,13 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
var personaProblem = await PersonaProblem(avatarUserName, user.UserName, token);
|
||||
if (personaProblem != default)
|
||||
return BadRequest(new WebResult().Invalidate(personaProblem));
|
||||
var inserted = await InsertPersona(user.ID, avatarUserName, loginForm.AvatarName);
|
||||
var inserted = await InsertPersona(user.ID, avatarUserName, loginForm.AvatarName, token);
|
||||
if (!inserted.IsValid)
|
||||
return StatusCode(inserted.StatusCode, inserted);
|
||||
avatar = (ViewAvatar)inserted.Data;
|
||||
}
|
||||
|
||||
var joined = await GroupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
||||
var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
|
||||
{
|
||||
AvatarId = avatar.Id,
|
||||
InvitationCode = loginForm.InvitationCode,
|
||||
@@ -201,12 +179,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (!joined.IsValid)
|
||||
return StatusCode(joined.StatusCode, joined);
|
||||
|
||||
return Ok(AuthTokenManager.GenerateToken(user, userSettings));
|
||||
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,14 +194,14 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
|
||||
// The server's first login, made while it has no administrator (owner decision 2026-10-16: first come, first served):
|
||||
// it is made the administrator, with its first persona, and setup closes for good. Sign-up stays closed to everyone
|
||||
// else (Registrations), so NodeInfo and the instance API don't change.
|
||||
// else (registrations), so NodeInfo and the instance API don't change.
|
||||
[HttpPost, Route("/clientapi/user/setup"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
||||
public async Task<IActionResult> SetUp(SetupForm setupForm, CancellationToken token)
|
||||
{
|
||||
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
var claimed = false;
|
||||
var adminId = default(string);
|
||||
try
|
||||
@@ -240,10 +218,10 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (!claimed)
|
||||
return SetUpAlready();
|
||||
|
||||
result = await UsersService.SignUpAsync(setupForm);
|
||||
result = await usersService.SignUpAsync(setupForm, token);
|
||||
if (!result.IsValid)
|
||||
{
|
||||
await ServerSetup.Release();
|
||||
await ServerSetup.Release(CancellationToken.None);
|
||||
return StatusCode(result.StatusCode, result);
|
||||
}
|
||||
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
||||
@@ -253,42 +231,42 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
await ServerSetup.Claimed(adminId, CancellationToken.None);
|
||||
|
||||
// set up from here, whatever happens to the persona: it can be made in the client's settings
|
||||
var avatar = await InsertPersona(user.ID, avatarUserName, setupForm.AvatarName);
|
||||
var avatar = await InsertPersona(user.ID, avatarUserName, setupForm.AvatarName, token);
|
||||
if (!avatar.IsValid)
|
||||
return StatusCode(avatar.StatusCode, avatar);
|
||||
|
||||
return Ok(AuthTokenManager.GenerateToken(user, userSettings));
|
||||
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()");
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()");
|
||||
if (claimed && adminId == default)
|
||||
await ServerSetup.Release();
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
await ServerSetup.Release(CancellationToken.None);
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
IActionResult SetUpAlready() =>
|
||||
StatusCode(StatusCodes.Status403Forbidden,
|
||||
new WebResult().Invalidate(Localizer["This server is already set up: joining it takes a group invitation."], StatusCodes.Status403Forbidden));
|
||||
new WebResult().Invalidate(localizer["This server is already set up: joining it takes a group invitation."], StatusCodes.Status403Forbidden));
|
||||
|
||||
Task<WebResult> InsertPersona(string rootId, string avatarUserName, string avatarName) =>
|
||||
AvatarUsersService.InsertAvatar(new InsertAvatarForm
|
||||
Task<WebResult> InsertPersona(string rootId, string avatarUserName, string avatarName, CancellationToken token = default) =>
|
||||
avatarUsersService.InsertAvatar(new InsertAvatarForm
|
||||
{
|
||||
RootId = rootId,
|
||||
Name = string.IsNullOrWhiteSpace(avatarName) ? avatarUserName : avatarName.Trim(),
|
||||
UserName = avatarUserName,
|
||||
Biography = string.Empty
|
||||
});
|
||||
}, token);
|
||||
|
||||
async Task<string> PersonaProblem(string avatarUserName, string rootUserName, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(avatarUserName))
|
||||
return Localizer["Choose a username for your persona."];
|
||||
return localizer["Choose a username for your persona."];
|
||||
if (string.Equals(avatarUserName, rootUserName?.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Localizer["Your persona's username must differ from your login."];
|
||||
if (await LocalActors.IsUserNameTaken(avatarUserName, token))
|
||||
return Localizer["The username '{0}' is already taken.", avatarUserName];
|
||||
return localizer["Your persona's username must differ from your login."];
|
||||
if (await localActors.IsUserNameTaken(avatarUserName, token))
|
||||
return localizer["The username '{0}' is already taken.", avatarUserName];
|
||||
return default;
|
||||
}
|
||||
|
||||
@@ -309,8 +287,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,8 +303,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,82 +313,82 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[HttpPost, Route("/clientapi/user/update"), Authorize(Policy = Policies.IsUser)]
|
||||
public IActionResult UpdateUser(UserForm userEmailForm) =>
|
||||
StatusCode(StatusCodes.Status422UnprocessableEntity,
|
||||
new WebResult().Invalidate(Localizer["Changing the address takes your password and a code sent to it."], StatusCodes.Status422UnprocessableEntity));
|
||||
new WebResult().Invalidate(localizer["Changing the address takes your password and a code sent to it."], StatusCodes.Status422UnprocessableEntity));
|
||||
|
||||
[HttpGet, Route("/clientapi/user/account"), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> Account()
|
||||
public async Task<IActionResult> Account(CancellationToken token = default)
|
||||
{
|
||||
var result = await UsersService.AccountAsync(User.GetUserId());
|
||||
var result = await usersService.AccountAsync(User.GetUserId(), token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/email"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> RequestEmailChange(EmailChangeForm form)
|
||||
public async Task<IActionResult> RequestEmailChange(EmailChangeForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.RequestEmailChangeAsync(User.GetUserId(), form);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.RequestEmailChangeAsync(User.GetUserId(), form, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/email/verify"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> VerifyEmail(EmailCodeForm form)
|
||||
public async Task<IActionResult> VerifyEmail(EmailCodeForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.VerifyEmailAsync(User.GetUserId(), form.Code);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.VerifyEmailAsync(User.GetUserId(), form.Code, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/totp/setup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> TotpSetup(PasswordForm form)
|
||||
public async Task<IActionResult> TotpSetup(PasswordForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.TotpSetupAsync(User.GetUserId(), form.Password);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.TotpSetupAsync(User.GetUserId(), form.Password, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
// on with the app's first code; every other session ends, and this device goes on with a new one
|
||||
[HttpPost, Route("/clientapi/user/totp/enable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> TotpEnable(TotpCodeForm form)
|
||||
public async Task<IActionResult> TotpEnable(TotpCodeForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.TotpEnableAsync(User.GetUserId(), form.Code);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.TotpEnableAsync(User.GetUserId(), form.Code, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
var (user, userSettings, codes) = ((RootUser, ViewUserSettings, List<string>))result.Data;
|
||||
return Ok(new ViewTotpEnabled { RecoveryCodes = codes, Session = AuthTokenManager.GenerateToken(user, userSettings) });
|
||||
return Ok(new ViewTotpEnabled { RecoveryCodes = codes, Session = authTokenManager.GenerateToken(user, userSettings) });
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/totp/disable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> TotpDisable(TotpDisableForm form)
|
||||
public async Task<IActionResult> TotpDisable(TotpDisableForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.TotpDisableAsync(User.GetUserId(), form.Password, form.Code);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.TotpDisableAsync(User.GetUserId(), form.Password, form.Code, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/email/remove"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> RemoveEmail(PasswordForm form)
|
||||
public async Task<IActionResult> RemoveEmail(PasswordForm form, CancellationToken token = default)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
|
||||
var result = await UsersService.RemoveEmailAsync(User.GetUserId(), form.Password);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await usersService.RemoveEmailAsync(User.GetUserId(), form.Password, token);
|
||||
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/update/settings"), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> UpdateUserSettings(ViewUserSettings userSettings)
|
||||
public async Task<IActionResult> UpdateUserSettings(ViewUserSettings userSettings, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.UpdateUserSettingsAsync(userSettings, User.GetUserId());
|
||||
result = await usersService.UpdateUserSettingsAsync(userSettings, User.GetUserId(), token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -418,31 +396,31 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/update/password"), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> UpdatePassword(UserPasswordForm userPasswordForm)
|
||||
public async Task<IActionResult> UpdatePassword(UserPasswordForm userPasswordForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId());
|
||||
result = await usersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId(), token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
// every session ended with the change; this device goes on with a new one
|
||||
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
|
||||
return Ok(AuthTokenManager.GenerateToken(user, userSettings));
|
||||
return Ok(authTokenManager.GenerateToken(user, userSettings));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,35 +434,35 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/user/settings"), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> GetUserSettings()
|
||||
public async Task<IActionResult> GetUserSettings(CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
result = await UsersService.GetUserSettingsAsync(User.GetUserId());
|
||||
result = await usersService.GetUserSettingsAsync(User.GetUserId(), token: token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/recover/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
||||
public async Task<IActionResult> RecoverPassword(PasswordRecoveryForm passwordRecoveryForm)
|
||||
public async Task<IActionResult> RecoverPassword(PasswordRecoveryForm passwordRecoveryForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
var host = string.IsNullOrEmpty(AppConfiguration.CurrentValue.FrontendBaseAddress)
|
||||
var host = string.IsNullOrEmpty(appConfiguration.CurrentValue.FrontendBaseAddress)
|
||||
? $"{Request.Scheme}://{Request.Host.Host}"
|
||||
: AppConfiguration.CurrentValue.FrontendBaseAddress.TrimEnd('/');
|
||||
result = await UsersService.SetupAndSendRecoveryEmail(passwordRecoveryForm, host);
|
||||
: appConfiguration.CurrentValue.FrontendBaseAddress.TrimEnd('/');
|
||||
result = await usersService.SetupAndSendRecoveryEmail(passwordRecoveryForm, host, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -492,8 +470,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,12 +480,12 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[FromBody,
|
||||
Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)),
|
||||
Display(Name = "RecoveryCode", ResourceType = typeof(FieldsNameResource))]
|
||||
string recoveryCode)
|
||||
string recoveryCode, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
result = await UsersService.IsValidRecoveryCode(recoveryCode);
|
||||
result = await usersService.IsValidRecoveryCode(recoveryCode, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -515,20 +493,20 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/recover/update/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
|
||||
public async Task<IActionResult> ChangePassword(NewPasswordForm newPasswordForm)
|
||||
public async Task<IActionResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.ChangePassword(newPasswordForm);
|
||||
result = await usersService.ChangePassword(newPasswordForm, token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
@@ -536,26 +514,26 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/user/delete"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
|
||||
public async Task<IActionResult> RemoveSelf(RemoveSelfForm form)
|
||||
public async Task<IActionResult> RemoveSelf(RemoveSelfForm form, CancellationToken token = default)
|
||||
{
|
||||
var result = new WebResult();
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(result.Invalidate(Localizer["Invalid model."]));
|
||||
return BadRequest(result.Invalidate(localizer["Invalid model."]));
|
||||
try
|
||||
{
|
||||
result = await UsersService.RemoveSelfAsync(User.GetUserId(), form.Password);
|
||||
result = await usersService.RemoveSelfAsync(User.GetUserId(), form.Password, token);
|
||||
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,17 +549,17 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
{
|
||||
var user = await dbEntities.RootUsers.MatchID(User.GetUserId()).ExecuteFirstAsync(token);
|
||||
if (user is not { IsBanned: false, DeletedAt: null })
|
||||
return Unauthorized(result.Invalidate(Localizer["Unauthorized."], StatusCodes.Status401Unauthorized));
|
||||
result = await UsersService.GetUserSettingsAsync(user.ID);
|
||||
return Unauthorized(result.Invalidate(localizer["Unauthorized."], StatusCodes.Status401Unauthorized));
|
||||
result = await usersService.GetUserSettingsAsync(user.ID, token: token);
|
||||
if (!result.IsValid)
|
||||
return StatusCode(result.StatusCode, result);
|
||||
|
||||
return Ok(AuthTokenManager.GenerateToken(user, (ViewUserSettings)result.Data, User.FindFirst(AuthTokenManager.SessionId)?.Value));
|
||||
return Ok(authTokenManager.GenerateToken(user, (ViewUserSettings)result.Data, User.FindFirst(AuthTokenManager.SessionId)?.Value));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()");
|
||||
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
|
||||
logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()");
|
||||
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,30 +13,23 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/social"),
|
||||
Authorize(Policy = Policies.IsUser)]
|
||||
public class SocialController : ControllerBase
|
||||
public class SocialController(
|
||||
IFollowService follows,
|
||||
IStringLocalizer<GenericRes> localizer) : ControllerBase
|
||||
{
|
||||
readonly IFollowService _follows;
|
||||
readonly IStringLocalizer _localizer;
|
||||
|
||||
public SocialController(IFollowService follows, IStringLocalizer<GenericRes> localizer)
|
||||
{
|
||||
_follows = follows;
|
||||
_localizer = localizer;
|
||||
}
|
||||
|
||||
[HttpPost, Route("/clientapi/follow")]
|
||||
public async Task<IActionResult> Follow(FollowForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _follows.Follow(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await follows.Follow(User.GetUserId(), form, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/unfollow")]
|
||||
public async Task<IActionResult> Unfollow(FollowForm form, CancellationToken token) =>
|
||||
!ModelState.IsValid ? Invalid() : Answer(await _follows.Unfollow(User.GetUserId(), form, token));
|
||||
!ModelState.IsValid ? Invalid() : Answer(await follows.Unfollow(User.GetUserId(), form, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/following")]
|
||||
public async Task<IActionResult> Following([FromQuery] string avatarId, CancellationToken token) =>
|
||||
Answer(await _follows.Followings(User.GetUserId(), avatarId, token));
|
||||
Answer(await follows.Followings(User.GetUserId(), avatarId, token));
|
||||
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
|
||||
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
@@ -14,27 +14,19 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/admin/statistics"),
|
||||
Authorize(Policy = Policies.IsAdmin)]
|
||||
public class StatisticsController : ControllerBase
|
||||
public class StatisticsController(
|
||||
StatisticsQueries queries,
|
||||
IJobQueue queue,
|
||||
Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> options) : ControllerBase
|
||||
{
|
||||
readonly StatisticsQueries _queries;
|
||||
readonly IJobQueue _queue;
|
||||
readonly Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> _options;
|
||||
|
||||
public StatisticsController(StatisticsQueries queries, IJobQueue queue, Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> options)
|
||||
{
|
||||
_queries = queries;
|
||||
_queue = queue;
|
||||
_options = options;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/statistics/crawler")]
|
||||
public async Task<IActionResult> Crawler(CancellationToken token) =>
|
||||
Ok(await _queries.Crawler(_options.CurrentValue.Crawler.Enabled, _options.CurrentValue.Crawler.RevisitDays, token));
|
||||
Ok(await queries.Crawler(options.CurrentValue.Crawler.Enabled, options.CurrentValue.Crawler.RevisitDays, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/statistics/overview")]
|
||||
public async Task<IActionResult> Overview([FromServices] Domain.Media.IMediaService media, [FromQuery] int days = 30, CancellationToken token = default)
|
||||
{
|
||||
var overview = await _queries.Overview(days, token);
|
||||
var overview = await queries.Overview(days, token);
|
||||
overview.Media.ProxyCacheBytes = Bytes(media.ProxyRoot);
|
||||
overview.Media.TrashBytes = Bytes(media.TrashRoot);
|
||||
return Ok(overview);
|
||||
@@ -46,20 +38,20 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[HttpGet, Route("/clientapi/admin/statistics/hosts")]
|
||||
public async Task<IActionResult> Hosts([FromQuery] int days = 30, [FromQuery] string sort = default, [FromQuery] string software = default,
|
||||
[FromQuery] int page = 1, [FromQuery] int limit = 50, CancellationToken token = default) =>
|
||||
Ok(await _queries.Hosts(days, sort, software, page, limit, token));
|
||||
Ok(await queries.Hosts(days, sort, software, page, limit, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/statistics/hosts/{host}")]
|
||||
public async Task<IActionResult> Host(string host, [FromQuery] int days = 90, CancellationToken token = default) =>
|
||||
await _queries.Host(host, days, token) is { } found ? Ok(found) : NotFound();
|
||||
await queries.Host(host, days, token) is { } found ? Ok(found) : NotFound();
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/statistics/events")]
|
||||
public async Task<IActionResult> Events([FromQuery] string host = default, [FromQuery] string channel = default, [FromQuery] string outcome = default,
|
||||
[FromQuery] string reason = default, [FromQuery] DateTime? before = default, [FromQuery] int limit = 100, CancellationToken token = default) =>
|
||||
Ok(await _queries.Events(host, channel, outcome, reason, before, limit, token));
|
||||
Ok(await queries.Events(host, channel, outcome, reason, before, limit, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/admin/statistics/server")]
|
||||
public async Task<IActionResult> Server([FromQuery] int days = 30, CancellationToken token = default) =>
|
||||
Ok(await _queries.Server(days, token));
|
||||
Ok(await queries.Server(days, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/admin/statistics/rollups/{day}")]
|
||||
public async Task<IActionResult> Rollup(string day, CancellationToken token)
|
||||
@@ -69,7 +61,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return BadRequest();
|
||||
var job = RollupJob.For(parsed.Date, $"rollup|{day}|rerun|{DateTime.UtcNow.Ticks}");
|
||||
job.RunAt = DateTime.UtcNow;
|
||||
await _queue.EnqueueMany(new[] { job }, token);
|
||||
await queue.EnqueueMany(new[] { job }, token);
|
||||
return Accepted();
|
||||
}
|
||||
|
||||
@@ -79,7 +71,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
host = Interactions.Host(host);
|
||||
if (host == Interactions.Unknown)
|
||||
return BadRequest();
|
||||
await _queue.Enqueue(JobKind.DescribeInstance, host, host, $"describe|{host}|admin|{DateTime.UtcNow.Ticks}", token);
|
||||
await queue.Enqueue(JobKind.DescribeInstance, host, host, $"describe|{host}|admin|{DateTime.UtcNow.Ticks}", token);
|
||||
return Accepted();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,28 +10,22 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/timeline"),
|
||||
Authorize(Policy = Policies.IsUser)]
|
||||
public class TimelineController : ControllerBase
|
||||
public class TimelineController(
|
||||
ITimelineService timelines) : ControllerBase
|
||||
{
|
||||
readonly ITimelineService _timelines;
|
||||
|
||||
public TimelineController(ITimelineService timelines)
|
||||
{
|
||||
_timelines = timelines;
|
||||
}
|
||||
|
||||
[HttpGet, Route("/clientapi/timeline/home")]
|
||||
public async Task<IActionResult> Home([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20,
|
||||
CancellationToken token = default) =>
|
||||
Answer(await _timelines.Home(User.GetUserId(), avatarId, maxId, limit, token));
|
||||
Answer(await timelines.Home(User.GetUserId(), avatarId, maxId, limit, token));
|
||||
|
||||
[HttpGet, Route("/clientapi/notifications")]
|
||||
public async Task<IActionResult> Notifications([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20,
|
||||
CancellationToken token = default) =>
|
||||
Answer(await _timelines.Notifications(User.GetUserId(), avatarId, maxId, limit, token));
|
||||
Answer(await timelines.Notifications(User.GetUserId(), avatarId, maxId, limit, token));
|
||||
|
||||
[HttpPost, Route("/clientapi/notifications/read")]
|
||||
public async Task<IActionResult> Read([FromQuery] string avatarId, CancellationToken token) =>
|
||||
Answer(await _timelines.MarkNotificationsRead(User.GetUserId(), avatarId, token));
|
||||
Answer(await timelines.MarkNotificationsRead(User.GetUserId(), avatarId, token));
|
||||
|
||||
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user