Files
Wino-Mail/Wino.Services/ContactService.cs

66 lines
2.4 KiB
C#
Raw Normal View History

2024-04-18 01:44:37 +02:00
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MimeKit;
using SqlKata;
using Wino.Core.Domain.Entities.Shared;
using Wino.Core.Domain.Interfaces;
using Wino.Services.Extensions;
2024-04-18 01:44:37 +02:00
namespace Wino.Services
2024-04-18 01:44:37 +02:00
{
public class ContactService : BaseDatabaseService, IContactService
{
public ContactService(IDatabaseService databaseService) : base(databaseService) { }
public async Task<AccountContact> CreateNewContactAsync(string address, string displayName)
{
var contact = new AccountContact() { Address = address, Name = displayName };
await Connection.InsertAsync(contact).ConfigureAwait(false);
return contact;
}
public Task<List<AccountContact>> GetAddressInformationAsync(string queryText)
2024-04-18 01:44:37 +02:00
{
if (queryText == null || queryText.Length < 2)
return Task.FromResult<List<AccountContact>>(null);
2024-04-18 01:44:37 +02:00
var query = new Query(nameof(AccountContact));
2024-04-18 01:44:37 +02:00
query.WhereContains("Address", queryText);
query.OrWhereContains("Name", queryText);
var rawLikeQuery = query.GetRawQuery();
return Connection.QueryAsync<AccountContact>(rawLikeQuery);
2024-04-18 01:44:37 +02:00
}
2024-08-23 02:07:50 +02:00
public Task<AccountContact> GetAddressInformationByAddressAsync(string address)
=> Connection.Table<AccountContact>().Where(a => a.Address == address).FirstOrDefaultAsync();
2024-04-18 01:44:37 +02:00
public async Task SaveAddressInformationAsync(MimeMessage message)
{
var recipients = message
.GetRecipients(true)
.Where(a => !string.IsNullOrEmpty(a.Name) && !string.IsNullOrEmpty(a.Address));
var addressInformations = recipients.Select(a => new AccountContact() { Name = a.Name, Address = a.Address });
2024-04-18 01:44:37 +02:00
foreach (var info in addressInformations)
2024-08-23 02:07:50 +02:00
{
var currentContact = await GetAddressInformationByAddressAsync(info.Address).ConfigureAwait(false);
if (currentContact == null)
{
await Connection.InsertAsync(info).ConfigureAwait(false);
}
2024-08-24 00:14:32 +02:00
else if (!currentContact.IsRootContact) // Don't update root contacts. They belong to accounts.
{
await Connection.InsertOrReplaceAsync(info).ConfigureAwait(false);
}
2024-08-23 02:07:50 +02:00
}
2024-04-18 01:44:37 +02:00
}
}
}