Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

10.5 KB
Raw Blame
@page "/emails"
@using AliasVault.Admin.Main.Components.Tables
@inherits MainBase

<LayoutPageTitle>Emails</LayoutPageTitle>

<PageHeader
    BreadcrumbItems="@BreadcrumbItems"
    Title="@(TotalRecords > 0 ? $"Emails ({TotalRecords:N0})" : "Emails")"
    Description="This page shows all received mails by this AliasVault server. All email fields except 'To' are encrypted with the public key of the receiving vault and are unreadable by the server.">
    <CustomActions>
        <RefreshButton OnClick="() => RefreshData(CancellationToken.None)" ButtonText="Refresh" />
    </CustomActions>
</PageHeader>

@if (IsInitialized)
{
    <div class="px-4">
        <ResponsivePaginator CurrentPage="CurrentPage" PageSize="PageSize" TotalRecords="TotalRecords" OnPageChanged="HandlePageChanged" />
        <div class="mb-3">
            <div class="relative">
                <SearchIcon />
                <input type="text" @bind-value="SearchTerm" @bind-value:event="oninput" id="search" placeholder="Search emails..." class="w-full px-4 ps-10 py-2 border rounded text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white">
            </div>
        </div>
    </div>
}

@if (IsLoading)
{
    <LoadingIndicator />
}
else
{
    <div class="overflow-x-auto px-4">
        <SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
            @foreach (var viewModel in EmailViewModelList)
            {
                <SortableTableRow>
                    <SortableTableColumn IsPrimary="true">@viewModel.Email.Id</SortableTableColumn>
                    <SortableTableColumn>@viewModel.Email.DateSystem.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>
                    <SortableTableColumn>@(viewModel.Email.FromLocal.Length > 10 ? viewModel.Email.FromLocal.Substring(0, 10) : viewModel.Email.FromLocal)@@@(viewModel.Email.FromDomain.Length > 10 ? viewModel.Email.FromDomain.Substring(0, 10) : viewModel.Email.FromDomain)</SortableTableColumn>
                    <SortableTableColumn>@viewModel.Email.ToLocal@@@viewModel.Email.ToDomain</SortableTableColumn>
                    <SortableTableColumn>
                        @if (viewModel.Recipients.Count == 0)
                        {
                            <UserNameDisplay User="null" />
                        }
                        else
                        {
                            <div class="flex flex-col gap-1">
                                @foreach (var recipient in viewModel.Recipients)
                                {
                                    <UserNameDisplay User="@recipient" />
                                }
                            </div>
                        }
                    </SortableTableColumn>
                    <SortableTableColumn>@viewModel.Email.AttachmentCount</SortableTableColumn>
                </SortableTableRow>
            }
        </SortableTable>
    </div>
}

@code {
    /// <summary>
    /// The search term from the query parameter.
    /// </summary>
    [Parameter]
    [SupplyParameterFromQuery(Name = "search")]
    public string? SearchTermFromQuery { get; set; }

    private readonly List<TableColumn> _tableColumns = [
        new TableColumn { Title = "ID", PropertyName = "Id" },
        new TableColumn { Title = "Time (UTC)", PropertyName = "DateSystem" },
        new TableColumn { Title = "From", PropertyName = "From" },
        new TableColumn { Title = "To", PropertyName = "To" },
        new TableColumn { Title = "Vault", Sortable = false },
        new TableColumn { Title = "Attachments", PropertyName = "AttachmentCount" },
    ];

    private List<EmailViewModel> EmailViewModelList { get; set; } = [];
    private bool IsInitialized { get; set; } = false;
    private bool IsLoading { get; set; } = true;
    private int CurrentPage { get; set; } = 1;
    private int PageSize { get; set; } = 50;
    private int TotalRecords { get; set; }
    private string _searchTerm = string.Empty;
    private CancellationTokenSource? _searchCancellationTokenSource;

    /// <summary>
    /// The last search term.
    /// </summary>
    private string _lastSearchTerm = string.Empty;

    private string SearchTerm
    {
        get => _searchTerm;
        set
        {
            if (_searchTerm != value)
            {
                _searchTerm = value;
                _searchCancellationTokenSource?.Cancel();
                _searchCancellationTokenSource = new CancellationTokenSource();
                _ = RefreshData(_searchCancellationTokenSource.Token);
            }
        }
    }

    private string SortColumn { get; set; } = "Id";
    private SortDirection SortDirection { get; set; } = SortDirection.Descending;
    private async Task HandleSortChanged((string column, SortDirection direction) sort)
    {
        SortColumn = sort.column;
        SortDirection = sort.direction;
        await RefreshData(CancellationToken.None);
    }

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Emails" });
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Set the search term from the query parameter if it exists
            if (!string.IsNullOrEmpty(SearchTermFromQuery))
            {
                _searchTerm = SearchTermFromQuery;
            }

            await RefreshData(CancellationToken.None);
        }
    }

    private void HandlePageChanged(int newPage)
    {
        CurrentPage = newPage;
        _ = RefreshData(CancellationToken.None);
    }

    private async Task RefreshData(CancellationToken cancellationToken = default)
    {
        try
        {
            IsLoading = true;
            StateHasChanged();

            await using var dbContext = await DbContextFactory.CreateDbContextAsync(cancellationToken);

            IQueryable<Email> query = dbContext.Emails;

            query = ApplySearchFilter(query);
            query = ApplySort(query);

            TotalRecords = await query.CountAsync(cancellationToken);
            var emailList = await query
                .Skip((CurrentPage - 1) * PageSize)
                .Take(PageSize)
                .ToListAsync(cancellationToken);

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            // An email is stored once and its key is wrapped for every vault that claimed the alias at delivery time.
            // Resolve each of those vaults to its owner: the user behind a personal group, or the group's name for
            // a shared vault.
            var emailIds = emailList.Select(x => x.Id).ToList();
            var recipients = await dbContext.EmailDecryptionKeys
                .Where(d => emailIds.Contains(d.EmailId))
                .Select(d => new
                {
                    d.EmailId,
                    GroupId = d.VaultManifestDeliveryKey.VaultManifest.OwnerGroupId,
                    GroupName = d.VaultManifestDeliveryKey.VaultManifest.OwnerGroup.Name,
                    Owner = dbContext.AliasVaultUsers.Where(u => u.PersonalGroupId == d.VaultManifestDeliveryKey.VaultManifest.OwnerGroupId).Select(u => new { u.Id, u.UserName, u.Blocked }).FirstOrDefault(),
                })
                .ToListAsync(cancellationToken);

            EmailViewModelList = emailList.Select(email => new EmailViewModel
            {
                Email = email,
                Recipients = recipients
                    .Where(r => r.EmailId == email.Id)
                    .DistinctBy(r => r.GroupId)
                    .Select(r => r.Owner != null
                        ? new UserDisplay { UserId = r.Owner.Id, UserName = r.Owner.UserName, Blocked = r.Owner.Blocked }
                        : new UserDisplay { UserName = r.GroupName })
                    .ToList(),
            }).ToList();

            IsLoading = false;
            IsInitialized = true;
            StateHasChanged();
        }
        catch (OperationCanceledException)
        {
            // Expected when cancellation is requested, do nothing
        }
    }

    /// <summary>
    /// Applies a search filter to the query based on the search term.
    /// </summary>
    /// <param name="query">The query to filter.</param>
    /// <returns>The filtered query.</returns>
    private IQueryable<Email> ApplySearchFilter(IQueryable<Email> query)
    {
        if (SearchTerm.Length > 0)
        {
            // Reset page number back to 1 if the search term has changed.
            if (SearchTerm != _lastSearchTerm && CurrentPage != 1)
            {
                CurrentPage = 1;
            }
            _lastSearchTerm = SearchTerm;

            query = query.Where(x => EF.Functions.Like(x.To.ToLower(), "%" + SearchTerm.Trim().ToLower() + "%"));
        }

        return query;
    }

    /// <summary>
    /// Applies sorting to the query based on the sort column and direction.
    /// </summary>
    /// <param name="query">The query to sort.</param>
    /// <returns>The sorted query.</returns>
    private IQueryable<Email> ApplySort(IQueryable<Email> query)
    {
        var ascending = SortDirection == SortDirection.Ascending;
        return SortColumn switch
        {
            "Id" => ascending ? query.OrderBy(x => x.Id) : query.OrderByDescending(x => x.Id),
            "DateSystem" => ascending ? query.OrderBy(x => x.DateSystem) : query.OrderByDescending(x => x.DateSystem),
            "From" => ascending ? query.OrderBy(x => x.FromLocal + "@" + x.FromDomain) : query.OrderByDescending(x => x.FromLocal + "@" + x.FromDomain),
            "To" => ascending ? query.OrderBy(x => x.ToLocal + "@" + x.ToDomain) : query.OrderByDescending(x => x.ToLocal + "@" + x.ToDomain),
            "AttachmentCount" => ascending ? query.OrderBy(x => x.AttachmentCount) : query.OrderByDescending(x => x.AttachmentCount),
            _ => query.OrderByDescending(x => x.DateSystem),
        };
    }

    private sealed class EmailViewModel
    {
        public Email Email { get; set; } = new();
        public List<UserDisplay> Recipients { get; set; } = [];
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _searchCancellationTokenSource?.Cancel();
            _searchCancellationTokenSource?.Dispose();
        }
        base.Dispose(disposing);
    }
}