// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A folder in a mailbox. //! //! This is the part of Outlook that has no Gmail equivalent, and the difference //! runs deeper than the name. A Gmail message carries a *set* of labels and //! lives nowhere in particular; an Outlook message is **in exactly one folder**, //! named by `parentFolderId`, and moving it is a move. Anything mirroring one //! model onto the other has to decide what to do about that, and the decision //! belongs to the application rather than here -- so this reports the tree and //! does not flatten it. //! //! Two consequences worth knowing before writing a sync: //! //! **A delta query is per folder.** There is no mailbox-wide change feed. To //! track a whole mailbox, every folder is tracked separately and each keeps its //! own delta token, which is why `Client.messageDelta` takes a folder. //! //! **A move looks like a delete and an add.** A message moved between folders //! gets a *new id*, so the same message arrives in the destination folder's //! delta as something new and in the source folder's as something removed. //! `internetMessageId` is the thing that is stable across the move. //! //! The strings are borrowed from the arena of whatever parsed them. const MailFolder = @This(); const std = @import("std"); const json = @import("json.zig"); /// Opaque, and long: a folder id is a base64url-ish blob of a hundred /// characters or more. Nothing here assumes anything about its contents, which /// is why `Client` percent-encodes it into a path. id: []const u8, /// What the user sees, in the language of their mailbox. `Inbox` in one /// mailbox is `Posteingang` in another, which is exactly why the well-known /// names below exist. display_name: ?[]const u8 = null, /// The folder this one is inside. `null` only for the root. parent_folder_id: ?[]const u8 = null, child_folder_count: ?u32 = null, /// Every item in the folder, of every kind -- a meeting request in the inbox /// counts here as much as a message does, so this need not equal the number of /// messages a listing returns. total_item_count: ?u32 = null, unread_item_count: ?u32 = null, /// Hidden folders are left out of a listing unless `includeHiddenFolders=true` /// was asked for. `null` when the property was not selected. is_hidden: ?bool = null, /// Child folders, when the listing expanded them. Empty otherwise -- which is /// not the same as the folder having none; `child_folder_count` says that. child_folders: []const MailFolder = &.{}, /// The folders Outlook creates itself, whose names may be used in a URL in /// place of an id. /// /// `GET /me/mailFolders/drafts` finds the drafts folder whatever the mailbox's /// language is, which is the whole point: matching `display_name` against /// `"Drafts"` works until somebody in Berlin runs the program. pub const WellKnown = enum { archive, clutter, conflicts, conversationhistory, deleteditems, drafts, inbox, junkemail, localfailures, /// "Top of Information Store": the parent of everything a normal mail /// client shows, and the place to start walking the tree. msgfolderroot, outbox, /// Soft-deleted items -- emptied from Deleted Items, or shift-deleted. /// Invisible in every Outlook client, and worth excluding from a mirror /// unless the mirror is meant to be a backup. recoverableitemsdeletions, scheduled, searchfolders, sentitems, serverfailures, syncissues, /// The spelling that goes in a URL, which is the lowercase name. pub fn toString(w: WellKnown) []const u8 { return @tagName(w); } /// The well-known name matching `name`, compared case-insensitively /// because a configuration file will say `Inbox` and Graph wants `inbox`. pub fn fromString(name: []const u8) ?WellKnown { inline for (comptime std.enums.values(WellKnown)) |w| { if (std.ascii.eqlIgnoreCase(@tagName(w), name)) return w; } return null; } /// A name outside the mailbox that a person would recognise, in the shape /// every other mail store writes: `sentitems` becomes `sent`, and /// `junkemail` becomes `spam`. /// /// Which of these are worth keeping is the application's decision and not /// this library's, so every one of them has a name and none are filtered /// out. pub fn conventionalName(w: WellKnown) []const u8 { return switch (w) { .archive => "archive", .clutter => "clutter", .conflicts => "conflicts", .conversationhistory => "conversations", .deleteditems => "trash", .drafts => "draft", .inbox => "inbox", .junkemail => "spam", .localfailures => "local-failures", .msgfolderroot => "", .outbox => "outbox", .recoverableitemsdeletions => "recoverable", .scheduled => "scheduled", .searchfolders => "search", .sentitems => "sent", .serverfailures => "server-failures", .syncissues => "sync-issues", }; } }; pub const ParseError = error{Malformed} || std.mem.Allocator.Error; /// How deep a folder tree this will follow when `$expand=childFolders` has /// nested them. /// /// Outlook permits a deep hierarchy and the recursion below runs on input from /// the network, so it needs a bound. Folders past it are dropped rather than /// the listing being rejected. pub const max_depth = 32; /// Reads one folder. `alloc` should be an arena: the child list is allocated /// from it and is not freed individually. pub fn fromJson(alloc: std.mem.Allocator, value: std.json.Value) ParseError!MailFolder { return fromJsonAt(alloc, value, 0); } fn fromJsonAt( alloc: std.mem.Allocator, value: std.json.Value, depth: usize, ) ParseError!MailFolder { if (value != .object) return error.Malformed; var folder: MailFolder = .{ .id = json.string(value, "id") orelse return error.Malformed, .display_name = json.string(value, "displayName"), .parent_folder_id = json.nonEmptyString(value, "parentFolderId"), .child_folder_count = json.unsigned(value, "childFolderCount"), .total_item_count = json.unsigned(value, "totalItemCount"), .unread_item_count = json.unsigned(value, "unreadItemCount"), .is_hidden = json.boolean(value, "isHidden"), }; if (depth + 1 >= max_depth) return folder; const children = json.array(value, "childFolders") orelse return folder; var list: std.ArrayList(MailFolder) = .empty; try list.ensureTotalCapacityPrecise(alloc, children.len); for (children) |child| { const c = fromJsonAt(alloc, child, depth + 1) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(c); } folder.child_folders = try list.toOwnedSlice(alloc); return folder; } /// How many messages in this folder have not been read. Zero when the counts /// were not selected, which is not the same as "none unread" -- check /// `unread_item_count` directly where the difference matters. pub fn unread(f: *const MailFolder) u32 { return f.unread_item_count orelse 0; } /// Whether this folder holds items that are deleted, failed, or otherwise not /// mail a person sent or received. /// /// A mirror usually wants to skip these: `recoverableitemsdeletions` holds /// everything that has ever been shift-deleted, and `syncissues` holds /// Outlook's own logs, which are messages only in the technical sense. /// /// It answers from the *name*, so it only knows about a folder that was /// addressed by its well-known name or whose display name happens to match. /// A folder fetched by id is not recognisable this way, which is what /// `Client.wellKnownFolderId` is for. pub fn isSystemDetritus(name: WellKnown) bool { return switch (name) { .conflicts, .localfailures, .recoverableitemsdeletions, .searchfolders, .serverfailures, .syncissues, => true, else => false, }; } const testing = std.testing; const TestFolder = struct { parsed: std.json.Parsed(std.json.Value), arena: std.heap.ArenaAllocator, folder: MailFolder, fn init(text: []const u8) !TestFolder { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{}); errdefer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); errdefer arena.deinit(); const folder: MailFolder = try .fromJson(arena.allocator(), parsed.value); return .{ .parsed = parsed, .arena = arena, .folder = folder }; } fn deinit(t: *TestFolder) void { t.arena.deinit(); t.parsed.deinit(); } }; test "the shape the resource type documents" { var t = try TestFolder.init( \\{"id":"AAMkADcbAAAAAAEJAAA=","displayName":"Inbox", \\ "parentFolderId":"AAMkADcbAAAAAAEIAAA=","childFolderCount":2, \\ "totalItemCount":1024,"unreadItemCount":17,"isHidden":false} ); defer t.deinit(); const f = t.folder; try testing.expectEqualStrings("AAMkADcbAAAAAAEJAAA=", f.id); try testing.expectEqualStrings("Inbox", f.display_name.?); try testing.expectEqual(@as(?u32, 2), f.child_folder_count); try testing.expectEqual(@as(?u32, 1024), f.total_item_count); try testing.expectEqual(@as(u32, 17), f.unread()); try testing.expectEqual(@as(?bool, false), f.is_hidden); // Not expanded, so no children are present -- which is not the same as // there being none, and `child_folder_count` is what says so. try testing.expectEqual(@as(usize, 0), f.child_folders.len); } test "an expanded tree" { var t = try TestFolder.init( \\{"id":"root","displayName":"Top of Information Store","childFolderCount":2, \\ "childFolders":[ \\ {"id":"a","displayName":"Inbox","parentFolderId":"root", \\ "childFolders":[{"id":"a1","displayName":"zig","parentFolderId":"a"}]}, \\ {"id":"b","displayName":"Archive","parentFolderId":"root"}]} ); defer t.deinit(); try testing.expectEqual(@as(usize, 2), t.folder.child_folders.len); try testing.expectEqualStrings("Inbox", t.folder.child_folders[0].display_name.?); try testing.expectEqualStrings("zig", t.folder.child_folders[0].child_folders[0].display_name.?); try testing.expectEqualStrings("a", t.folder.child_folders[0].child_folders[0].parent_folder_id.?); } test "a tree deeper than the cap is truncated, not rejected" { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(testing.allocator); const depth = max_depth + 20; for (0..depth) |_| { try buf.appendSlice(testing.allocator, "{\"id\":\"x\",\"childFolders\":["); } try buf.appendSlice(testing.allocator, "{\"id\":\"leaf\"}"); for (0..depth) |_| try buf.appendSlice(testing.allocator, "]}"); var t = try TestFolder.init(buf.items); defer t.deinit(); var d: usize = 0; var f: *const MailFolder = &t.folder; while (f.child_folders.len > 0) : (d += 1) f = &f.child_folders[0]; try testing.expectEqual(max_depth - 1, d); } test "junk among the children is skipped, not fatal" { var t = try TestFolder.init( \\{"id":"root","childFolders":[{"id":"a"},42,null,{"no":"id"},{"id":"b"}]} ); defer t.deinit(); try testing.expectEqual(@as(usize, 2), t.folder.child_folders.len); try testing.expectEqualStrings("b", t.folder.child_folders[1].id); } test "no id is malformed" { var p = try std.json.parseFromSlice( std.json.Value, testing.allocator, "{\"displayName\":\"nameless\"}", .{}, ); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try testing.expectError(error.Malformed, MailFolder.fromJson(arena.allocator(), p.value)); } test "the well-known names are what goes in a URL" { try testing.expectEqualStrings("sentitems", WellKnown.sentitems.toString()); try testing.expectEqual(WellKnown.inbox, WellKnown.fromString("inbox").?); // A configuration file will say `Inbox` and Graph wants `inbox`. try testing.expectEqual(WellKnown.inbox, WellKnown.fromString("Inbox").?); try testing.expectEqual(WellKnown.deleteditems, WellKnown.fromString("DELETEDITEMS").?); try testing.expectEqual(@as(?WellKnown, null), WellKnown.fromString("Projects")); } test "every well-known folder has a conventional name, and they are distinct" { const values = comptime std.enums.values(WellKnown); for (values, 0..) |a, i| { // The root is deliberately the empty string: it is the container the // tree hangs from and not a folder anything is filed in. if (a == .msgfolderroot) { try testing.expectEqualStrings("", a.conventionalName()); continue; } try testing.expect(a.conventionalName().len > 0); for (values[i + 1 ..]) |b| { if (b == .msgfolderroot) continue; try testing.expect(!std.mem.eql(u8, a.conventionalName(), b.conventionalName())); } } // The two that are renamed rather than lowercased, because every other // mail store spells them this way. try testing.expectEqualStrings("sent", WellKnown.sentitems.conventionalName()); try testing.expectEqualStrings("trash", WellKnown.deleteditems.conventionalName()); try testing.expectEqualStrings("spam", WellKnown.junkemail.conventionalName()); } test "the folders a mirror should skip" { try testing.expect(isSystemDetritus(.recoverableitemsdeletions)); try testing.expect(isSystemDetritus(.syncissues)); try testing.expect(isSystemDetritus(.searchfolders)); try testing.expect(!isSystemDetritus(.inbox)); try testing.expect(!isSystemDetritus(.deleteditems)); try testing.expect(!isSystemDetritus(.junkemail)); }