MailSharp / MailSharp.MailClient / Controllers / Api / MailApiController.cs
Code · 431 lines · 16276 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431using MailSharp.MailClient.Models;
using MailSharp.MailClient.Services;
using MailSharp.MailClient.Services.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;
using MimeKit;
using System.Text.Json;

namespace MailSharp.MailClient.Controllers.Api;

[ApiController]
[Route("api/mail")]
public class MailApiController(
	IAccountStore accountStore,
	SessionAccountManager sessionManager,
	IImapService imapService,
	ISmtpService smtpService,
	IMailCacheStore mailCacheStore,
	IContactStore contactStore,
	IOptions<MailSettings> mailSettings,
	LocalizationService localizer,
	IBackgroundIndexingStatus indexingStatus,
	ILogger<MailApiController> logger) : ControllerBase
{
	private readonly MailSettings _settings = mailSettings.Value;
	private static readonly FileExtensionContentTypeProvider ContentTypeProvider = new();

	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);
	}

	// Lightweight, non-admin view of the same background-indexing state the Maintenance page shows
	// (see BackgroundIndexingStatus) - polled by the topbar toast on every page so users notice
	// their inbox is still being indexed without needing admin rights to open Maintenance.
	[HttpGet("indexing-status")]
	public IActionResult IndexingStatus()
	{
		return Ok(new
		{
			maxConcurrentIndexing = indexingStatus.MaxConcurrentIndexing,
			currentlyAvailableSlots = indexingStatus.CurrentlyAvailableSlots,
			inProgress = indexingStatus.InProgressKeys.Select(key =>
			{
				indexingStatus.TryGetProgress(key, out var processed, out var total);
				return new { key, processed, total };
			})
		});
	}

	private object BuildIndexingStatusPayload() => new
	{
		maxConcurrentIndexing = indexingStatus.MaxConcurrentIndexing,
		currentlyAvailableSlots = indexingStatus.CurrentlyAvailableSlots,
		inProgress = indexingStatus.InProgressKeys.Select(key =>
		{
			indexingStatus.TryGetProgress(key, out var processed, out var total);
			return new { key, processed, total };
		})
	};

	private static object BuildFlagsRefreshPayload(RecentFlagsRefreshResult r) => new
	{
		folder = r.Folder,
		checkedCount = r.CheckedCount,
		changedCount = r.ChangedCount,
		elapsedMs = r.ElapsedMs,
		timestamp = r.TimestampUtc
	};

	private async Task WriteSseEventAsync(string eventName, string data, CancellationToken ct)
	{
		await Response.WriteAsync($"event: {eventName}\ndata: {data}\n\n", ct);
		await Response.Body.FlushAsync(ct);
	}

	// Server-Sent Events push channel for the topbar - started once per page load and kept open,
	// replacing what used to be a client-side setInterval poll (see common.js). An EventSource just
	// sits and receives pushes, so it no longer shares apiFetch's activeControllers/loading-overlay
	// plumbing - a background status refresh could previously call hideLoading() and dismiss the
	// Cancel button/overlay for a real, unrelated, still-in-flight request.
	//
	// Multiplexes more than one kind of push over this one connection rather than opening a stream
	// per feature: "indexing" (background-indexing toast, global - not account-scoped, matching the
	// old polled endpoint's behaviour) and "flags" (ImapService.RecentFlagsRefreshResults - results
	// of the lightweight recent-messages flag recheck, scoped to the caller's own account so one
	// user's folder names/activity never reach another). The push side is still a poll internally
	// (in-memory static state has no change notification), but it only writes to the client when a
	// given snapshot actually changes, and the client opens exactly one long-lived connection instead
	// of a new HTTP request every few seconds.
	[HttpGet("indexing-status/stream")]
	public async Task IndexingStatusStream(CancellationToken ct)
	{
		var active = GetActive();
		if (active == null) { Response.StatusCode = StatusCodes.Status401Unauthorized; return; }
		var accountId = active.Value.account.Id;

		Response.Headers.ContentType = "text/event-stream";
		Response.Headers.CacheControl = "no-cache";
		Response.Headers["X-Accel-Buffering"] = "no";

		string? lastIndexingPayload = null;
		var lastFlagsPayloads = new Dictionary<string, string>();
		try
		{
			while (!ct.IsCancellationRequested)
			{
				var indexingPayload = JsonSerializer.Serialize(BuildIndexingStatusPayload());
				if (indexingPayload != lastIndexingPayload)
				{
					await WriteSseEventAsync("indexing", indexingPayload, ct);
					lastIndexingPayload = indexingPayload;
				}

				foreach (var kvp in ImapService.RecentFlagsRefreshResults)
				{
					if (kvp.Value.AccountId != accountId) continue;
					var flagsPayload = JsonSerializer.Serialize(BuildFlagsRefreshPayload(kvp.Value));
					if (!lastFlagsPayloads.TryGetValue(kvp.Key, out var prev) || prev != flagsPayload)
					{
						await WriteSseEventAsync("flags", flagsPayload, ct);
						lastFlagsPayloads[kvp.Key] = flagsPayload;
					}
				}

				await Task.Delay(1000, ct);
			}
		}
		catch (OperationCanceledException)
		{
			// Client navigated away or closed the EventSource - not an error.
		}
	}

	[HttpGet("folders")]
	public async Task<IActionResult> Folders(CancellationToken ct)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		return Ok(await imapService.GetFoldersAsync(account, password, ct: ct));
	}

	[HttpGet("messages")]
	public async Task<IActionResult> Messages(string folder = "INBOX", string sort = "date", bool desc = true, int page = 1, bool refresh = false, bool unreadOnly = false, CancellationToken ct = default)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;

		var pageSize = account.MessagesPerPage > 0 ? account.MessagesPerPage : _settings.MessageListPageSize;
		var messages = await imapService.GetMessagesAsync(account, password, folder, refresh, ct);

		if (unreadOnly) messages = [.. messages.Where(m => !m.IsRead)];

		messages = sort switch
		{
			"subject" => desc ? [.. messages.OrderByDescending(m => m.Subject)] : [.. messages.OrderBy(m => m.Subject)],
			"from" => desc ? [.. messages.OrderByDescending(m => m.From)] : [.. messages.OrderBy(m => m.From)],
			"size" => desc ? [.. messages.OrderByDescending(m => m.SizeBytes)] : [.. messages.OrderBy(m => m.SizeBytes)],
			_ => desc ? [.. messages.OrderByDescending(m => m.Date)] : [.. messages.OrderBy(m => m.Date)],
		};

		var totalCount = messages.Count;
		var totalPages = Math.Max(1, (int)Math.Ceiling(totalCount / (double)pageSize));
		page = Math.Min(Math.Max(1, page), totalPages);

		return Ok(new MessagesResponse
		{
			Messages = [.. messages.Skip((page - 1) * pageSize).Take(pageSize)],
			Page = page,
			PageSize = pageSize,
			TotalCount = totalCount,
			TotalPages = totalPages
		});
	}

	[HttpGet("messages/{uid}")]
	public async Task<IActionResult> Message(uint uid, [FromQuery] string folder = "INBOX", CancellationToken ct = default)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		return Ok(await imapService.GetMessageAsync(account, password, folder, uid, ct));
	}

	[HttpPost("allow-images")]
	public IActionResult AllowImages(AllowImagesRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();

		// Defense in depth: the client already hides this action inside Spam (see ImapService.
		// GetMessageAsync/IsSpamFolder), but a direct API call should be refused too, not just
		// silently accepted and then ignored on the next render.
		if (ImapService.IsSpamFolder(request.Folder)) return BadRequest(new { error = "Externe afbeeldingen kunnen niet worden toegestaan voor berichten in de Spam-map." });

		if (!string.IsNullOrWhiteSpace(request.Sender))
			mailCacheStore.SetAllowExternalImages(active.Value.account.Id, request.Sender, true);

		return Ok();
	}

	// Fetched via a plain authenticated fetch() call, never navigated to directly - the client
	// turns the response into a blob and opens/downloads it via a local blob: URL, so this
	// address is never shown in an address bar, new tab, or browser history.
	[HttpGet("attachments/{uid}/{part}")]
	public async Task<IActionResult> Attachment(uint uid, int part, [FromQuery] string folder = "INBOX", CancellationToken ct = default)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;

		var detail = await imapService.GetMessageAsync(account, password, folder, uid, ct);
		var info = detail.Attachments.FirstOrDefault(a => a.PartIndex == part);
		var fileName = info?.FileName ?? "attachment";
		var contentType = ResolveContentType(info?.ContentType, fileName);
		var stream = await imapService.GetAttachmentAsync(account, password, folder, uid, part, ct);

		return File(stream, contentType);
	}

	// Prefers the type implied by the file's own extension over the Content-Type the sender's
	// mail client declared for the MIME part: senders frequently stamp every attachment with a
	// generic/wrong type (e.g. application/octet-stream, or a stale type left over from a
	// forward), while the extension in the actual filename is what the user - and the browser's
	// viewer - can see and trust.
	private static string ResolveContentType(string? storedContentType, string fileName)
	{
		if (ContentTypeProvider.TryGetContentType(fileName, out var guessedFromExtension))
		{
			return guessedFromExtension;
		}

		return !string.IsNullOrWhiteSpace(storedContentType) ? storedContentType : "application/octet-stream";
	}

	[HttpPost("mark-read")]
	public async Task<IActionResult> MarkRead(UidsRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.SetSeenAsync(account, password, request.Folder, request.Uids, true);
		return Ok();
	}

	[HttpPost("mark-unread")]
	public async Task<IActionResult> MarkUnread(UidsRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.SetSeenAsync(account, password, request.Folder, request.Uids, false);
		return Ok();
	}

	[HttpPost("flag")]
	public async Task<IActionResult> Flag(UidsRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.SetFlaggedAsync(account, password, request.Folder, request.Uids, true);
		return Ok();
	}

	[HttpPost("unflag")]
	public async Task<IActionResult> Unflag(UidsRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.SetFlaggedAsync(account, password, request.Folder, request.Uids, false);
		return Ok();
	}

	[HttpPost("mark-all-read")]
	public async Task<IActionResult> MarkAllRead(FolderRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.MarkAllAsync(account, password, request.Folder, true);
		return Ok();
	}

	[HttpPost("mark-all-unread")]
	public async Task<IActionResult> MarkAllUnread(FolderRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.MarkAllAsync(account, password, request.Folder, false);
		return Ok();
	}

	[HttpPost("move")]
	public async Task<IActionResult> Move(MoveRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.MoveAsync(account, password, request.Folder, request.Uids, request.TargetFolder);
		return Ok();
	}

	[HttpPost("delete")]
	public async Task<IActionResult> Delete(UidsRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.DeleteAsync(account, password, request.Folder, request.Uids);
		return Ok();
	}

	[HttpPost("empty-folder")]
	public async Task<IActionResult> EmptyFolder(FolderRequest request)
	{
		var active = GetActive();
		if (active == null) return Unauthorized();
		var (account, password) = active.Value;
		await imapService.EmptyFolderAsync(account, password, request.Folder);
		return Ok();
	}

	[HttpPost("send")]
	public async Task<IActionResult> Send([FromForm] ComposeModel model, [FromForm] List<IFormFile>? files)
	{
		var account = accountStore.Get(model.AccountId);
		var password = sessionManager.GetPassword(model.AccountId);
		if (account == null || password == null) return Unauthorized();

		var attachments = await ReadAttachments(files);
		var inlineImages = await ReadInlineImages();
		MimeMessage message;
		try
		{
			message = MimeMessageFactory.Build(account, model, attachments, inlineImages);
			await smtpService.SendAsync(account, password, message, HttpContext.RequestAborted);
		}
		finally
		{
			foreach (var (_, content) in attachments) content.Dispose();
			foreach (var (_, _, content) in inlineImages) content.Dispose();
		}

		// Best-effort: the message has already been sent, so a failure to save it to Sent (e.g. no
		// such folder, transient IMAP error) shouldn't fail the request - but it's surfaced in the
		// response so the UI can warn instead of silently losing the copy.
		string? sentError = null;
		try
		{
			await imapService.AppendSentAsync(account, password, message, HttpContext.RequestAborted);
		}
		catch (Exception ex)
		{
			sentError = ex.Message;
			logger.LogWarning(ex, "Message sent for account {AccountId} but saving a copy to Sent failed", account.Id);
		}

		var recipients = message.To.Concat(message.Cc).OfType<MailboxAddress>()
			.Select(mb => new ContactAddress { Email = mb.Address, Name = mb.Name ?? "" });
		contactStore.AddContacts(account.Id, recipients);

		return Ok(new { message = localizer["compose_sent"], sentError });
	}

	[HttpPost("save-draft")]
	public async Task<IActionResult> SaveDraft([FromForm] ComposeModel model, [FromForm] List<IFormFile>? files)
	{
		var account = accountStore.Get(model.AccountId);
		var password = sessionManager.GetPassword(model.AccountId);
		if (account == null || password == null) return Unauthorized();

		var attachments = await ReadAttachments(files);
		var inlineImages = await ReadInlineImages();
		try
		{
			await imapService.SaveDraftAsync(account, password, model, attachments, inlineImages);
		}
		finally
		{
			foreach (var (_, content) in attachments) content.Dispose();
			foreach (var (_, _, content) in inlineImages) content.Dispose();
		}

		return Ok(new { message = localizer["compose_draft_saved"] });
	}

	private static async Task<List<(string FileName, Stream Content)>> ReadAttachments(List<IFormFile>? files)
	{
		var result = new List<(string, Stream)>();
		if (files == null) return result;
		foreach (var file in files)
		{
			if (file.Length == 0) continue;
			var ms = new MemoryStream();
			await file.CopyToAsync(ms);
			ms.Position = 0;
			result.Add((file.FileName, ms));
		}
		return result;
	}

	// Inline images (pictures inserted into the compose editor via file upload, see compose.js)
	// arrive as regular form files, but under a "inline:<cid>" field name rather than "files" - the
	// [FromForm] List<IFormFile> binder above only picks up fields literally named "files", so these
	// are read directly off Request.Form.Files instead to recover the cid <-> content mapping.
	private async Task<List<(string Cid, string FileName, Stream Content)>> ReadInlineImages()
	{
		var result = new List<(string, string, Stream)>();
		foreach (var file in Request.Form.Files)
		{
			if (!file.Name.StartsWith("inline:", StringComparison.Ordinal) || file.Length == 0) continue;
			var cid = file.Name["inline:".Length..];
			var ms = new MemoryStream();
			await file.CopyToAsync(ms);
			ms.Position = 0;
			result.Add((cid, file.FileName, ms));
		}
		return result;
	}
}