MailSharp / MailSharp.MailClient / Controllers / Api / ContactsApiController.cs
Code · 66 lines · 2083 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66using MailSharp.MailClient.Models;
using MailSharp.MailClient.Services;
using Microsoft.AspNetCore.Mvc;

namespace MailSharp.MailClient.Controllers.Api;

[ApiController]
[Route("api/contacts")]
public class ContactsApiController(
	IAccountStore accountStore,
	SessionAccountManager sessionManager,
	IImapService imapService,
	IContactStore contactStore) : ControllerBase
{
	private (Account account, string password)? GetActive()
	{
		var id = sessionManager.GetActiveAccountId();
		if (id == null) return null;
		var account = accountStore.Get(id.Value);
		var password = sessionManager.GetPassword(id.Value);
		if (account == null || password == null) return null;
		return (account, password);
	}

	[HttpGet]
	public async Task<IActionResult> List(CancellationToken ct)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;

		var sentContacts = contactStore.GetCachedContacts(account.Id);
		if (sentContacts == null)
		{
			sentContacts = await imapService.GetSentContactsAsync(account, password, ct);
			contactStore.SaveContacts(account.Id, sentContacts);
		}
		var result = sentContacts.Select(c => new ContactDto
		{
			Email = c.Email,
			DisplayName = contactStore.GetDisplayName(account.Id, c.Email) ?? (string.IsNullOrWhiteSpace(c.Name) ? c.Email : c.Name)
		}).OrderBy(c => c.DisplayName).ToList();

		return Ok(result);
	}

	[HttpPost("update")]
	public IActionResult Update(UpdateContactRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		if (string.IsNullOrWhiteSpace(request.Email)) return BadRequest();

		contactStore.SetDisplayName(active.Value.account.Id, request.Email, request.DisplayName);
		return Ok();
	}

	[HttpGet("mails")]
	public async Task<IActionResult> Mails(string email, bool refresh = false, CancellationToken ct = default)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		return Ok(await imapService.SearchByAddressAsync(account, password, email, refresh, ct));
	}
}