// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The Microsoft Graph mail API, over an OAuth 2.0 token that this keeps alive. //! //! ## Where the credentials come from //! //! This library does not do OAuth; `zig-oidc` does, and this holds one of its //! `Client`s and one of its `TokenSet`s. Signing in is that library's job and //! happens once, before any of this: //! //! ```zig //! var tenant = try o365.tenant.init(gpa, "common", .{}); //! defer tenant.deinit(); //! //! var listener = try oidc.loopback.Listener.listen(io, .{}); //! defer listener.deinit(io); //! const redirect_uri = try listener.redirectUri(gpa); //! defer gpa.free(redirect_uri); //! //! const oauth: oidc.Client = .{ //! .provider = tenant.provider, //! .client_id = client_id, //! .redirect_uri = redirect_uri, //! // `offline_access` is in here, and without it there is no refresh //! // token and the grant dies in an hour. //! .scopes = o365.scopes.mirror, //! }; //! //! const rng: std.Random.IoSource = .{ .io = io }; //! var authorization = try oauth.authorize(gpa, rng.interface(), .{}); //! defer authorization.deinit(); //! // ... send the user to authorization.url, then: //! var redirect = try listener.wait(io, gpa, .{}); //! defer redirect.deinit(); //! var tokens = try oauth.exchange(io, gpa, &authorization, redirect.query, &d); //! defer tokens.deinit(); //! //! var client: o365.Client = .{ .gpa = gpa, .oauth = oauth, .tokens = &tokens }; //! ``` //! //! `gpa` on the client is the long-lived one -- see the field -- and is a //! different thing from the `gpa` each call takes. //! //! A public client -- a desktop program, which cannot keep a secret -- leaves //! `client_secret` null and relies on PKCE, which is what the app registration //! should be set to. A confidential client sets it. //! //! ## Keeping them alive //! //! An access token lasts about an hour and a mailbox walk lasts longer, so //! every call here refreshes on its own when the token is within //! `refresh_leeway` of expiring, and again if a call comes back 401 anyway -- //! which happens when consent is withdrawn, when a conditional access policy //! changes, or when this machine's clock is not Microsoft's. //! //! Set `on_refresh` to write the token set back to wherever it is kept: //! Microsoft rotates the refresh token on most refreshes, so dropping the new //! one breaks the next run. `TokenStore` is that, for a file. //! //! ## Walking a mailbox //! //! Two shapes, and the second is the one to build a sync on. //! //! `messageIterator` walks a folder or the whole mailbox, page by page. That is //! the first run. //! //! `messageDelta` walks the *changes* to one folder since a token from last //! time, and ends by handing back a new token to store. That is every run //! after. It is per folder -- Graph has no mailbox-wide change feed -- so //! tracking a whole mailbox means one delta walk and one stored token for each //! folder, which `folderTree` enumerates. const Client = @This(); const std = @import("std"); const oidc = @import("oidc"); const ApiError = @import("ApiError.zig"); const Attachment = @import("Attachment.zig"); const Batch = @import("Batch.zig"); const MailFolder = @import("MailFolder.zig"); const Message = @import("Message.zig"); const User = @import("User.zig"); const http = @import("http.zig"); const iso8601 = @import("iso8601.zig"); const json = @import("json.zig"); const odata = @import("odata.zig"); const log = std.log.scoped(.o365); /// The allocator for what this client does that outlives a single call. /// /// Today that is one thing: the token set a refresh produces, which replaces /// the one behind `tokens`. It is also the allocator a `Diagnostics` should be /// built on -- `diagnostics()` does that -- so that the client and the record /// of what it last said are freed by the same hand. /// /// The `gpa` every method takes is a *different* allocator with a different /// job: it is for what that call returns and for the scratch it needs on the /// way, and an arena is a perfectly good choice for it. gpa: std.mem.Allocator, /// The OAuth client the tokens were minted by, and which will refresh them. /// Its `provider` should be one of `tenant`'s. oauth: oidc.Client, /// The tokens. Borrowed and mutated: a refresh replaces what is behind this /// pointer, so it must outlive the client and must not be shared with anything /// that is reading it at the same time. tokens: *oidc.TokenSet, /// Whose mailbox. `me` is the authenticated user and is almost always right; a /// user id, a principal name, or a shared mailbox's address goes here for the /// cases that are not. user_id: []const u8 = "me", user_agent: []const u8 = "zig-o365", /// Where Graph is. A national cloud moves it -- `https://graph.microsoft.us` /// for US Government, `https://microsoftgraph.chinacloudapi.cn` for China /// operated by 21Vianet -- and a test points it at a loopback socket. /// /// It is also the origin every `@odata.nextLink` is checked against before it /// is followed. See `odata.sameOrigin`. base_url: []const u8 = "https://graph.microsoft.com", /// `v1.0`, or `beta` for the things that are only there. Nothing in this /// library depends on a beta member, but the delta query's shape is the same /// on both and pointing this at `beta` is how a caller reaches the rest. api_version: []const u8 = "v1.0", /// How early to treat the access token as expired. Enough slack that a call is /// not started with a token that dies while it is in flight. refresh_leeway: std.Io.Duration = .fromSeconds(300), max_response_bytes: usize = http.default_max_response_bytes, /// The separate, much larger ceiling for `getMime`, which returns a whole /// message. See `http.default_max_message_bytes`. max_message_bytes: usize = http.default_max_message_bytes, retry: http.Retry = .{}, /// Where the retry jitter comes from. Not a secret, but it must differ between /// processes or backing off does not spread anything out. rng: ?std.Random = null, /// Called after every successful refresh, with the merged token set. on_refresh: ?RefreshHook = null, /// What to do with a token set that has just been refreshed. /// /// An error here fails the API call that triggered the refresh, deliberately: a /// rotated refresh token that was not written down is one the next run does not /// have, and finding that out now is better than finding it out tomorrow. pub const RefreshHook = struct { context: ?*anyopaque = null, func: *const fn (context: ?*anyopaque, tokens: *const oidc.TokenSet) anyerror!void, }; pub const Diagnostics = struct { /// The allocator everything in here was made with. See the note on /// `http.Diagnostics.gpa` for why it is owned rather than passed in: what /// a `Diagnostics` holds outlives the call that filled it in, so borrowing /// that call's allocator is a use-after-free waiting for an arena. gpa: std.mem.Allocator, /// What the last API call said. http: http.Diagnostics, /// What the last *refresh* said, which is a different server with a /// different error vocabulary. `invalid_grant` here means the grant is gone /// -- consent withdrawn, the refresh token expired from disuse, or a /// password changed -- and the user has to sign in again. oauth: oidc.Client.Diagnostics = .{}, /// `gpa` should be the client's own -- `Diagnostics.init(client.gpa)` -- /// so that the client and the record of what it last said are freed by the /// same hand. Nothing checks it, but nothing else makes sense either: a /// `Diagnostics` is reset by the next request, so it has to outlive /// whatever allocator that request was given. pub fn init(gpa: std.mem.Allocator) Diagnostics { return .{ .gpa = gpa, .http = .{ .gpa = gpa } }; } pub fn reset(d: *Diagnostics) void { d.http.reset(); d.oauth.reset(d.gpa); } pub fn deinit(d: *Diagnostics) void { d.reset(); } /// The API error, when the failure was one. pub fn apiError(d: *const Diagnostics) ?*const ApiError { if (d.http.api_error) |*e| return e; return null; } /// The Graph `request-id` of the last call, which is what a support /// request has to quote. pub fn requestId(d: *const Diagnostics) ?[]const u8 { if (d.http.api_error) |*e| if (e.request_id) |r| return r; return d.http.request_id; } pub fn format(d: *const Diagnostics, w: *std.Io.Writer) std.Io.Writer.Error!void { if (d.oauth.message()) |m| return m.format(w); return d.http.format(w); } }; pub const Error = http.Error || error{ /// `base_url` or a path built from it is not a URL. InvalidEndpoint, /// The response was 2xx but was not the JSON this expected. Malformed, /// The access token has expired and there is no refresh token to spend. /// The user has to sign in again. NoRefreshToken, /// The refresh was refused. `Diagnostics.oauth` says why; `invalid_grant` /// means the grant itself is gone. RefreshFailed, /// `on_refresh` returned an error. The tokens in memory are the new ones; /// whatever was supposed to persist them did not. RefreshHookFailed, /// A continuation URL -- an `@odata.nextLink`, an `@odata.deltaLink`, or a /// stored delta token -- pointed somewhere other than `base_url`. /// /// Following it would have sent the access token to whoever wrote it. See /// the note at the top of `odata.zig`. UntrustedLink, /// A delta walk only: the stored `delta_link` has aged out. /// /// Not a failure to retry. It means the incremental path is gone and the /// folder has to be walked in full -- `messageDelta` with a `delta_link` /// of `null` -- which produces a fresh token to resume from. ResyncRequired, }; // -- authentication --------------------------------------------------------- /// Refreshes the access token if it is expired or about to be, and returns /// whether it did. /// /// Every call here does this on its own, so a caller only needs it to force the /// issue -- at the start of a long run, say, so that a refresh failure surfaces /// before an hour of work rather than after it. pub fn refreshIfNeeded( c: *Client, io: std.Io, diagnostics: *Diagnostics, ) Error!bool { if (!c.tokens.isExpired(io, c.refresh_leeway)) return false; try c.forceRefresh(io, diagnostics); return true; } /// Spends the refresh token whether or not the access token looks expired. /// /// No per-call allocator, unlike every other method here, because there is /// nothing to hand back: what this produces goes into `tokens` and into /// `diagnostics`, both of which outlive the call. It works on `c.gpa`. pub fn forceRefresh( c: *Client, io: std.Io, diagnostics: *Diagnostics, ) Error!void { const refresh_token = c.tokens.refresh_token orelse return error.NoRefreshToken; var refreshed = c.oauth.refresh(io, c.gpa, refresh_token, &diagnostics.oauth) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { log.debug("refresh failed: {t}", .{err}); return error.RefreshFailed; }, }; { // `replaceWithRefreshed` consumes `refreshed` and frees it, so this // errdefer is scoped to the one call that can fail before it does. errdefer refreshed.deinit(); // Microsoft rotates the refresh token on most refreshes and omits the // scope on some, and both are handled here rather than by assignment // -- which is the bug this call exists to prevent. try c.tokens.replaceWithRefreshed(&refreshed); } if (c.on_refresh) |hook| { hook.func(hook.context, c.tokens) catch |err| { // Logged as well as returned: `RefreshHookFailed` erases which // error the hook actually hit, and that is the useful part. log.warn("could not persist refreshed tokens: {t}", .{err}); return error.RefreshHookFailed; }; } } // -- the user --------------------------------------------------------------- /// `GET /me`. The cheapest call there is, which also makes it the way to check /// that a token works before starting anything long. pub fn getUser( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!Response(User) { var body = try c.getJson(io, gpa, "", null, .{}, c.max_response_bytes, diagnostics); errdefer body.deinit(); return .{ .value = User.fromJson(body.root) catch return error.Malformed, .owned = body, }; } // -- folders ---------------------------------------------------------------- pub const ListFoldersOptions = struct { /// List the children of this folder rather than the top level. A /// `MailFolder.WellKnown` name works here as well as an id. /// /// `null` lists the top-level folders, which is *not* the whole mailbox: /// a folder nested inside another is not in it. `folderTree` is what walks /// the lot. parent: ?[]const u8 = null, /// Graph leaves hidden folders out unless asked. A mirror of the mailbox /// wants them; a folder list shown to a person does not. include_hidden: bool = false, /// Fetch each folder's children in the same response, up to Graph's own /// nesting limit. Cheaper than a request per folder, and what `folderTree` /// uses. expand_children: bool = false, /// Per page. Graph's default for folders is 10, which is a request per /// handful of folders. page_size: u32 = 100, }; /// One page of the folder listing. pub fn listMailFolders( c: *Client, io: std.Io, gpa: std.mem.Allocator, options: ListFoldersOptions, diagnostics: *Diagnostics, ) Error!Page(MailFolder) { var path_buf: std.Io.Writer.Allocating = .init(gpa); defer path_buf.deinit(); if (options.parent) |parent| { path_buf.writer.writeAll("mailFolders/") catch return error.OutOfMemory; oidc.QueryBuilder.encode(&path_buf.writer, parent) catch return error.OutOfMemory; path_buf.writer.writeAll("/childFolders") catch return error.OutOfMemory; } else { path_buf.writer.writeAll("mailFolders") catch return error.OutOfMemory; } var q: odata.Query = .init(gpa); defer q.deinit(); if (options.include_hidden) try q.add("includeHiddenFolders", "true"); if (options.expand_children) try q.add("$expand", "childFolders"); var body = try c.getJson( io, gpa, path_buf.written(), q.written(), .{ .page_size = options.page_size }, c.max_response_bytes, diagnostics, ); errdefer body.deinit(); return try pageOf(MailFolder, &body); } /// `GET /me/mailFolders/{id}`, where the id may be a `MailFolder.WellKnown` /// name: `inbox`, `sentitems`, `deleteditems`. pub fn getMailFolder( c: *Client, io: std.Io, gpa: std.mem.Allocator, folder_id: []const u8, diagnostics: *Diagnostics, ) Error!Response(MailFolder) { const path = try resourcePath(gpa, "mailFolders", folder_id, null); defer gpa.free(path); var body = try c.getJson(io, gpa, path, null, .{}, c.max_response_bytes, diagnostics); errdefer body.deinit(); const arena_alloc = body.arena.allocator(); return .{ .value = MailFolder.fromJson(arena_alloc, body.root) catch return error.Malformed, .owned = body, }; } /// The id of a well-known folder, resolved once so that it can be compared /// against the `parent_folder_id` on a message. /// /// A message says which folder it is in by id, and the well-known *names* only /// work in a URL -- nothing on a message ever says `inbox`. Asking Graph what /// the inbox's id is, once, is what connects the two. pub fn wellKnownFolderId( c: *Client, io: std.Io, gpa: std.mem.Allocator, name: MailFolder.WellKnown, diagnostics: *Diagnostics, ) Error![]u8 { var folder = try c.getMailFolder(io, gpa, name.toString(), diagnostics); defer folder.deinit(); return gpa.dupe(u8, folder.value.id); } /// Every folder in the mailbox, with the path of each worked out. /// /// This is what a mirror needs and what a single listing does not give: a /// message carries a `parent_folder_id` and nothing else, so turning that into /// something a person would recognise means having the whole tree in hand. /// /// It walks from `msgfolderroot` rather than from the top-level listing, /// because the top-level listing is not the whole mailbox -- it is the folders /// directly under the root, and a folder inside one of those is not in it. pub fn folderTree( c: *Client, io: std.Io, gpa: std.mem.Allocator, options: FolderTreeOptions, diagnostics: *Diagnostics, ) Error!FolderTree { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const alloc = arena.allocator(); var collected: std.ArrayList(Entry) = .empty; var queue: std.ArrayList(Pending) = .empty; defer queue.deinit(gpa); try queue.append(gpa, .{ .id = null, .prefix = "" }); var visited: usize = 0; while (queue.items.len > 0) { const pending = queue.orderedRemove(0); visited += 1; if (visited > options.max_folders) { log.warn("stopping the folder walk at {d} folders", .{options.max_folders}); break; } var it = try c.mailFolderIterator(gpa, .{ .parent = pending.id, .include_hidden = options.include_hidden, }); defer it.deinit(); while (try it.next(io, diagnostics)) |folder| { const name = folder.display_name orelse ""; const path = if (pending.prefix.len == 0) try alloc.dupe(u8, name) else try std.fmt.allocPrint(alloc, "{s}{c}{s}", .{ pending.prefix, options.separator, name, }); const id = try alloc.dupe(u8, folder.id); try collected.append(alloc, .{ .id = id, .name = try alloc.dupe(u8, name), .path = path, .parent_folder_id = if (folder.parent_folder_id) |p| try alloc.dupe(u8, p) else null, .total_item_count = folder.total_item_count, .unread_item_count = folder.unread_item_count, }); // Only descend where there is something to descend into, so that // a mailbox of flat folders costs one request rather than one per // folder. const children = folder.child_folder_count orelse 0; if (children > 0) { try queue.append(gpa, .{ .id = id, .prefix = path, }); } } } const folders = try collected.toOwnedSlice(alloc); // Built after the slice is final, because the map holds pointers into it // and `toOwnedSlice` can move the allocation. var by_id: std.StringHashMapUnmanaged(*const Entry) = .empty; try by_id.ensureTotalCapacity(alloc, @intCast(folders.len)); for (folders) |*entry| by_id.putAssumeCapacity(entry.id, entry); return .{ .by_id = by_id, .folders = folders, .arena = arena }; } pub const FolderTreeOptions = struct { include_hidden: bool = false, /// What goes between a parent's name and a child's in `Entry.path`. separator: u8 = '/', /// A ceiling on how many folders will be visited, so that a mailbox with a /// pathological hierarchy -- or a service that answers a child listing /// with its own parent -- cannot turn this into an endless walk. max_folders: usize = 10_000, }; const Pending = struct { id: ?[]const u8, prefix: []const u8, }; pub const Entry = struct { id: []const u8, /// The folder's own name, in the mailbox's language. name: []const u8, /// The name with every ancestor in front of it: `Inbox/zig/mailing list`. path: []const u8, parent_folder_id: ?[]const u8, total_item_count: ?u32, unread_item_count: ?u32, }; /// Every folder in a mailbox, indexed by id. pub const FolderTree = struct { by_id: std.StringHashMapUnmanaged(*const Entry), folders: []const Entry, arena: std.heap.ArenaAllocator, /// The entry for a folder id, or `null` for one this walk did not see -- /// a folder created since, or a hidden one that was not asked for. pub fn get(t: *const FolderTree, folder_id: []const u8) ?*const Entry { return t.by_id.get(folder_id); } /// The full path of a folder id, for rendering a message's /// `parent_folder_id`. pub fn path(t: *const FolderTree, folder_id: []const u8) ?[]const u8 { const entry = t.get(folder_id) orelse return null; return entry.path; } pub fn count(t: *const FolderTree) usize { return t.folders.len; } pub fn deinit(t: *FolderTree) void { t.arena.deinit(); t.* = undefined; } }; // -- messages --------------------------------------------------------------- /// The `$select` a mailbox walk should ask for: enough to file a message and /// decide whether it is already held, and none of the body. /// /// Naming the properties wanted is the single largest thing a caller can do /// about how long a walk takes. Left off, Graph sends every property of every /// message, `body` included -- which for a listing is the whole mailbox /// downloaded to find out what is in it. pub const walk_select: []const []const u8 = &.{ "id", "parentFolderId", "internetMessageId", "receivedDateTime", "sentDateTime", "lastModifiedDateTime", "subject", "from", "sender", "isRead", "isDraft", "hasAttachments", "categories", }; pub const ListMessagesOptions = struct { /// Which folder. A `MailFolder.WellKnown` name works as well as an id. /// `null` lists every message in the mailbox, across every folder. folder: ?[]const u8 = null, /// The properties to return. Empty means all of them, which is almost /// never what is wanted -- see `walk_select`. select: []const []const u8 = &.{}, /// An OData `$filter`. `receivedDateTime ge 2024-01-01T00:00:00Z` is the /// useful one; `receivedAfter` builds it. filter: ?[]const u8 = null, /// An OData `$orderby`, such as `receivedDateTime desc`. /// /// Graph refuses `$orderby` and `$filter` on different properties in the /// same request, which is a 400 rather than a slow answer. order_by: ?[]const u8 = null, /// A `$search` term. Graph's own caveat applies: a request with `$search` /// may not also carry `$filter` or `$orderby`. search: ?[]const u8 = null, /// Per page, sent as `Prefer: odata.maxpagesize`. Graph's default is 10, /// which is a request per ten messages. page_size: u32 = 100, /// Ask Graph for the total as well. Costs it a count; worth it once at the /// start of a walk and not on every page. count: bool = false, /// What `body` should come back as, when `body` was selected. Sent as /// `Prefer: outlook.body-content-type`; without it Graph sends HTML. body_type: ?Message.BodyType = null, }; /// One page of the message listing. pub fn listMessages( c: *Client, io: std.Io, gpa: std.mem.Allocator, options: ListMessagesOptions, diagnostics: *Diagnostics, ) Error!Page(Message) { const path = try messagesPath(gpa, options.folder, null); defer gpa.free(path); var q: odata.Query = .init(gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); try q.addOptional("$filter", options.filter); try q.addOptional("$orderby", options.order_by); try q.addOptional("$search", options.search); if (options.count) try q.add("$count", "true"); var body = try c.getJson(io, gpa, path, q.written(), .{ .page_size = options.page_size, .body_type = options.body_type, // `$count` on a message collection is one of the requests Graph // refuses without this header. .eventual_consistency = options.count, }, c.max_response_bytes, diagnostics); errdefer body.deinit(); return try pageOf(Message, &body); } pub const GetMessageOptions = struct { /// The properties to return. Empty means all of them. /// /// `internetMessageHeaders` is the one worth naming: Graph leaves the RFC /// 5322 headers out unless they are selected, and selecting them excludes /// nothing else that was also named. select: []const []const u8 = &.{}, /// What `body` should come back as. Without it Graph sends HTML. body_type: ?Message.BodyType = null, }; /// `GET /me/messages/{id}`. pub fn getMessage( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_id: []const u8, options: GetMessageOptions, diagnostics: *Diagnostics, ) Error!Response(Message) { const path = try resourcePath(gpa, "messages", message_id, null); defer gpa.free(path); var q: odata.Query = .init(gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); var body = try c.getJson( io, gpa, path, q.written(), .{ .body_type = options.body_type }, c.max_response_bytes, diagnostics, ); errdefer body.deinit(); return .{ .value = Message.fromJson(body.arena.allocator(), body.root) catch |err| switch (err) { error.Malformed => return error.Malformed, error.OutOfMemory => return error.OutOfMemory, }, .owned = body, }; } /// `GET /me/messages/{id}/$value`: the message as RFC 5322, exactly as it /// arrived. /// /// This is what belongs in a maildir, and it is the reason `Message` models no /// MIME tree. `Message.body` is Outlook's rendering of the message -- already /// parsed, already flattened, and not what anybody sent. This is the bytes. /// /// The result is owned by the caller. It can be large: `max_message_bytes` is /// the ceiling, and it is allocated per call. /// /// Needs `Mail.Read`. `Mail.ReadBasic` is refused here, which is the one place /// the difference between those two scopes shows up as an error rather than as /// a missing property. pub fn getMime( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_id: []const u8, diagnostics: *Diagnostics, ) Error![]u8 { const path = try resourcePath(gpa, "messages", message_id, "$value"); defer gpa.free(path); const url = try c.buildUrl(gpa, path, null); defer gpa.free(url); return c.getRaw(io, gpa, url, .{ // Not JSON: Graph answers this with `text/plain` and the message in // the body. .accept = "text/plain, message/rfc822, */*", .max_response_bytes = c.max_message_bytes, }, diagnostics); } /// Walks every page of the message listing. /// /// The iterator owns the URL of the page it has not fetched yet, so it has an /// allocator of its own and `next` does not take one. That differs from the /// sibling Gmail library on purpose: Gmail paginates with a token that lives in /// the page it came from, and Graph paginates with a whole URL that has to /// outlive the page it came from. pub fn messageIterator( c: *Client, gpa: std.mem.Allocator, options: ListMessagesOptions, ) Error!Iterator(Message) { const path = try messagesPath(gpa, options.folder, null); defer gpa.free(path); var q: odata.Query = .init(gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); try q.addOptional("$filter", options.filter); try q.addOptional("$orderby", options.order_by); try q.addOptional("$search", options.search); const url = try c.buildUrl(gpa, path, q.written()); return .{ .client = c, .gpa = gpa, .initial_url = url, .next_url = url, .request = .{ .page_size = options.page_size, .body_type = options.body_type, }, .max_response_bytes = c.max_response_bytes, }; } /// Walks every page of the folder listing. pub fn mailFolderIterator( c: *Client, gpa: std.mem.Allocator, options: ListFoldersOptions, ) Error!Iterator(MailFolder) { var path_buf: std.Io.Writer.Allocating = .init(gpa); defer path_buf.deinit(); if (options.parent) |parent| { path_buf.writer.writeAll("mailFolders/") catch return error.OutOfMemory; oidc.QueryBuilder.encode(&path_buf.writer, parent) catch return error.OutOfMemory; path_buf.writer.writeAll("/childFolders") catch return error.OutOfMemory; } else { path_buf.writer.writeAll("mailFolders") catch return error.OutOfMemory; } var q: odata.Query = .init(gpa); defer q.deinit(); if (options.include_hidden) try q.add("includeHiddenFolders", "true"); if (options.expand_children) try q.add("$expand", "childFolders"); const url = try c.buildUrl(gpa, path_buf.written(), q.written()); return .{ .client = c, .gpa = gpa, .initial_url = url, .next_url = url, .request = .{ .page_size = options.page_size }, .max_response_bytes = c.max_response_bytes, }; } // -- delta ------------------------------------------------------------------ pub const DeltaOptions = struct { /// Which folder to track. Required: **Graph has no mailbox-wide delta**, /// so a whole mailbox is one of these per folder. folder: []const u8, /// The `@odata.deltaLink` stored at the end of the last run. /// /// `null` starts a full synchronisation: every message in the folder comes /// back, and then a token to resume from. That is the first run, and it is /// also what to do after `error.ResyncRequired`. delta_link: ?[]const u8 = null, /// The properties to return. `id` always comes back whatever this says. /// /// Ignored when `delta_link` is given: Graph encodes the original query /// into the token, so a resumed walk keeps the `$select` it started with /// and changing it means starting again. select: []const []const u8 = &.{}, /// Only report this kind of change. Ignored when resuming, for the same /// reason as `select`. change_type: ?ChangeType = null, /// Per page, sent as `Prefer: odata.maxpagesize`. page_size: u32 = 100, }; pub const ChangeType = enum { created, updated, deleted }; /// Walks the changes to one folder since `delta_link`, and ends holding the /// token for next time. /// /// ```zig /// var it = try client.messageDelta(gpa, .{ /// .folder = "inbox", /// .delta_link = stored, /// .select = o365.Client.walk_select, /// }); /// defer it.deinit(); /// /// while (try it.next(io, &d)) |message| { /// if (message.isRemoved()) { /// // A tombstone: `id` and nothing else. /// } /// } /// // Store this, and pass it as `delta_link` next time. It is borrowed from /// // the iterator, so copy it before `deinit`. /// const token = it.delta_link.?; /// ``` /// /// The walk must run to the end for `delta_link` to be set: an interrupted one /// has no resume point and has to be started again. That is Graph's design /// rather than this library's -- a `@odata.nextLink` in the middle of a delta /// walk is a `$skiptoken`, which is not a delta token and expires in hours. pub fn messageDelta( c: *Client, gpa: std.mem.Allocator, options: DeltaOptions, ) Error!Iterator(Message) { const url = if (options.delta_link) |link| blk: { // A stored delta link is a URL that has been outside this program -- // in a file, in a database, through whatever wrote it. It is checked // exactly as a link off the wire is, and for the same reason. odata.sameOrigin(c.base_url, link) catch |err| return switch (err) { error.InvalidLink => error.InvalidEndpoint, error.UntrustedLink => error.UntrustedLink, }; break :blk try gpa.dupe(u8, link); } else blk: { const path = try messagesPath(gpa, options.folder, "delta"); defer gpa.free(path); var q: odata.Query = .init(gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); if (options.change_type) |t| try q.add("changeType", @tagName(t)); break :blk try c.buildUrl(gpa, path, q.written()); }; return .{ .client = c, .gpa = gpa, .initial_url = url, .next_url = url, .request = .{ .page_size = options.page_size }, .max_response_bytes = c.max_response_bytes, .is_delta = true, }; } // -- attachments ------------------------------------------------------------ /// The `$select` that lists attachments without their bytes, which is the /// default and wants to be: `contentBytes` is returned inline and base64 /// encoded, so listing the attachments of a message with a 20 MB file on it is /// a 27 MB response. pub const attachment_list_select: []const []const u8 = &.{ "id", "name", "contentType", "size", "isInline", "lastModifiedDateTime", }; pub const ListAttachmentsOptions = struct { /// Empty means every property, **including the bytes**. The default leaves /// them out; see `attachment_list_select`. select: []const []const u8 = attachment_list_select, page_size: u32 = 100, }; /// `GET /me/messages/{id}/attachments`. pub fn listAttachments( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_id: []const u8, options: ListAttachmentsOptions, diagnostics: *Diagnostics, ) Error!Page(Attachment) { const path = try resourcePath(gpa, "messages", message_id, "attachments"); defer gpa.free(path); var q: odata.Query = .init(gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); var body = try c.getJson( io, gpa, path, q.written(), .{ .page_size = options.page_size }, // Bytes come back here when the caller asked for them, so this gets // the larger ceiling rather than the metadata one. if (options.select.len == 0) c.max_message_bytes else c.max_response_bytes, diagnostics, ); errdefer body.deinit(); return try pageOf(Attachment, &body); } /// `GET /me/messages/{id}/attachments/{id}`, with the bytes. pub fn getAttachment( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_id: []const u8, attachment_id: []const u8, diagnostics: *Diagnostics, ) Error!Response(Attachment) { var path_buf: std.Io.Writer.Allocating = .init(gpa); defer path_buf.deinit(); const w = &path_buf.writer; w.writeAll("messages/") catch return error.OutOfMemory; oidc.QueryBuilder.encode(w, message_id) catch return error.OutOfMemory; w.writeAll("/attachments/") catch return error.OutOfMemory; oidc.QueryBuilder.encode(w, attachment_id) catch return error.OutOfMemory; var body = try c.getJson( io, gpa, path_buf.written(), null, .{}, c.max_message_bytes, diagnostics, ); errdefer body.deinit(); return .{ .value = Attachment.fromJson(body.arena.allocator(), body.root) catch |err| switch (err) { error.Malformed => return error.Malformed, error.OutOfMemory => return error.OutOfMemory, }, .owned = body, }; } // -- batching --------------------------------------------------------------- /// A `$batch`: several requests in one round trip. /// /// The reason to reach for it is a mailbox walk, where the listing is one /// request and the fetches are forty thousand. See `Batch` for what it costs in /// exchange -- chiefly that a throttled request inside a batch is invisible to /// every other layer of this library, so `Batch` has retry logic of its own. /// /// ```zig /// var batch = client.batch(gpa); /// defer batch.deinit(); /// for (ids) |id| _ = try batch.getMessage(id, .{ .select = walk_select }); /// var results = try batch.send(io, &d); /// defer results.deinit(); /// ``` pub fn batch(c: *Client, gpa: std.mem.Allocator) Batch { return .init(c, gpa); } /// `//$batch`. Note what is *not* in it: the mailbox. A batch is /// posted to the service root and each entry names its own mailbox in its /// `url`, which is why `buildBatchUrl` exists. pub fn batchUrl(c: *const Client, gpa: std.mem.Allocator) std.mem.Allocator.Error![]u8 { return std.fmt.allocPrint(gpa, "{s}/{s}/$batch", .{ std.mem.trimEnd(u8, c.base_url, "/"), c.api_version, }); } /// Fetches many messages by id in as few round trips as Graph allows. /// /// The convenience the whole batch machinery exists for: this is the second /// half of a mailbox walk, where `messageIterator` gave out ids and each one /// now needs its properties. Twenty at a time rather than one. /// /// The result holds one entry per id **in the order the ids were given**, /// whatever order the service answered in. An id that failed has a `null` /// message and a status saying why -- a message deleted between the listing and /// the fetch is a 404 on that entry and not a failure of the call, which is /// exactly the case a serial walk has to handle anyway. pub fn getMessages( c: *Client, io: std.Io, gpa: std.mem.Allocator, ids: []const []const u8, options: GetMessageOptions, diagnostics: *Diagnostics, ) Error!MessageBatch { var b = c.batch(gpa); defer b.deinit(); for (ids) |id| _ = b.getMessage(id, options) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // An id that cannot go into a JSON string is a programming error in // the caller rather than something Graph will ever hand back, so it // surfaces as the same `Malformed` the rest of this uses. error.InvalidRequest => return error.Malformed, }; var results = b.send(io, diagnostics) catch |err| switch (err) { error.MalformedBatch, error.InvalidRequest => return error.Malformed, error.BatchThrottled => return error.TooManyRetries, else => |e| return e, }; errdefer results.deinit(); const alloc = results.allocator(); const items = try alloc.alloc(MessageBatch.Item, results.responses.len); for (results.responses, 0..) |r, i| { items[i] = .{ .status = r.status, .message = message: { if (!r.ok()) break :message null; const body = r.body orelse break :message null; break :message Message.fromJson(alloc, body) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // One unreadable message does not discard the nineteen // beside it. error.Malformed => null, }; }, }; } return .{ .items = items, .round_trips = results.round_trips, .results = results }; } pub const MessageBatch = struct { /// One per id, in the order the ids were given. items: []const Item, /// How many POSTs it took. One per twenty ids, plus one per retry pass. round_trips: u32, results: Batch.Results, pub const Item = struct { status: std.http.Status, /// `null` when the fetch failed; `status` says why. message: ?Message, }; /// How many were fetched. pub fn okCount(m: *const MessageBatch) usize { var n: usize = 0; for (m.items) |item| { if (item.message != null) n += 1; } return n; } pub fn deinit(m: *MessageBatch) void { m.results.deinit(); m.* = undefined; } }; // -- helpers for building a request ----------------------------------------- /// An OData `$filter` for everything received at or after an instant, which is /// the only filter a delta query accepts and the most useful one anywhere /// else. Owned by the caller. pub fn receivedAfter(gpa: std.mem.Allocator, when: std.Io.Timestamp) ![]u8 { var buf: [32]u8 = undefined; return std.fmt.allocPrint( gpa, "receivedDateTime ge {s}", .{iso8601.bufRender(&buf, when)}, ); } // -- plumbing --------------------------------------------------------------- /// A parsed response body and the arena everything in it points into. pub const Owned = struct { arena: std.heap.ArenaAllocator, root: std.json.Value, pub fn deinit(o: *Owned) void { o.arena.deinit(); o.* = undefined; } }; /// A single resource, and the memory its strings live in. pub fn Response(comptime T: type) type { return struct { value: T, owned: Owned, pub fn deinit(r: *@This()) void { r.owned.deinit(); r.* = undefined; } }; } /// One page of a listing, and the memory its contents live in. pub fn Page(comptime T: type) type { return struct { items: []const T, /// The absolute URL of the next page. `null` at the end of the /// listing. Checked against `base_url` before it is followed. next_link: ?[]const u8 = null, /// A delta query only, and only on its last page: the token to store /// and resume from next time. delta_link: ?[]const u8 = null, /// `@odata.count`, when `$count=true` asked for it. count: ?u32 = null, owned: Owned, pub fn deinit(p: *@This()) void { p.owned.deinit(); p.* = undefined; } }; } /// Takes `body` by pointer rather than by value, which matters: the items are /// allocated from its arena, and a copy taken before that would leave the /// caller's `errdefer` freeing an arena that does not know about them. fn pageOf(comptime T: type, body: *Owned) Error!Page(T) { const alloc = body.arena.allocator(); const items = json.array(body.root, "value") orelse &.{}; var list: std.ArrayList(T) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const parsed = parseItem(T, alloc, item) catch |err| switch (err) { // One unreadable entry does not discard the page it arrived in: a // mailbox walk that dies on message 40,000 has to be understood // before it can be resumed. error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(parsed); } return .{ .items = try list.toOwnedSlice(alloc), .next_link = json.nonEmptyString(body.root, "@odata.nextLink"), .delta_link = json.nonEmptyString(body.root, "@odata.deltaLink"), .count = json.unsigned(body.root, "@odata.count"), .owned = body.*, }; } fn parseItem( comptime T: type, alloc: std.mem.Allocator, value: std.json.Value, ) (error{Malformed} || std.mem.Allocator.Error)!T { // `User` is the only one of these that needs no allocator, because it has // no list members. return switch (T) { User => User.fromJson(value), else => T.fromJson(alloc, value), }; } /// Walks every page of a listing, following `@odata.nextLink`. pub fn Iterator(comptime T: type) type { return struct { const Self = @This(); client: *Client, /// Frees `initial_url`. The pages have arenas of their own. gpa: std.mem.Allocator, /// The URL this walk started at, which is the only one this owns: /// every later one is borrowed from the page that carried it. initial_url: []u8, /// The page not yet fetched. `null` once the last one has been. next_url: ?[]const u8, /// A delta walk only: the token to store, once the walk has reached /// the end. /// /// **Borrowed from the iterator's last page**, so it stops being valid /// at `deinit`. Copy it before then. delta_link: ?[]const u8 = null, /// `@odata.count` from the first page that carried one. count: ?u32 = null, request: RequestOptions = .{}, max_response_bytes: usize = http.default_max_response_bytes, is_delta: bool = false, page: ?Page(T) = null, index: usize = 0, /// The next item, or `null` at the end of the listing. /// /// **The result is borrowed from the iterator** and stays valid only /// until the next call, which frees the page it came out of. Anything /// that outlives the loop body -- an id going into a list -- must be /// copied. pub fn next(it: *Self, io: std.Io, diagnostics: *Diagnostics) Error!?T { while (true) { if (it.page) |p| { if (it.index < p.items.len) { defer it.index += 1; return p.items[it.index]; } } const url = it.next_url orelse return null; var body = try it.client.fetchLink( io, it.gpa, url, it.request, it.max_response_bytes, it.is_delta, diagnostics, ); errdefer body.deinit(); var page = try pageOf(T, &body); errdefer page.deinit(); // Both links are read before the old page is freed, because // they are borrowed from the *new* page's arena -- and the old // page is freed after, because that is where the previous // ones lived. const next_link = page.next_link; const delta_link = page.delta_link; const count = page.count; if (it.page) |*old| old.deinit(); it.page = page; it.next_url = next_link; if (delta_link) |d| it.delta_link = d; if (count) |n| if (it.count == null) { it.count = n; }; it.index = 0; // An empty page with a link is not the end: a delta query // returns one whenever a page of changes filtered down to // nothing, and stopping here would silently truncate the walk. if (page.items.len == 0 and next_link == null) return null; } } pub fn deinit(it: *Self) void { if (it.page) |*p| p.deinit(); it.gpa.free(it.initial_url); it.* = undefined; } }; } /// The bits of a request that are headers rather than query parameters. const RequestOptions = struct { /// `Prefer: odata.maxpagesize=N`. Graph takes the page size as a header, /// not as `$top` -- `$top` is a limit on the whole result, not a page /// size, and using it for pagination stops the walk at `$top` items. page_size: ?u32 = null, /// `Prefer: outlook.body-content-type="text"`. body_type: ?Message.BodyType = null, /// `ConsistencyLevel: eventual`, which `$count` needs. eventual_consistency: bool = false, }; /// Does one GET against a path below the mailbox, refreshing the token first if /// it is due and once more if the call is refused anyway. fn getJson( c: *Client, io: std.Io, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, request: RequestOptions, max_response_bytes: usize, diagnostics: *Diagnostics, ) Error!Owned { const url = try c.buildUrl(gpa, path, query); defer gpa.free(url); return c.fetchLink(io, gpa, url, request, max_response_bytes, false, diagnostics); } /// Fetches an absolute URL and parses it as a JSON object. /// /// Every continuation URL goes through here, and the first thing it does is /// refuse one that does not belong to `base_url`. fn fetchLink( c: *Client, io: std.Io, gpa: std.mem.Allocator, url: []const u8, request: RequestOptions, max_response_bytes: usize, is_delta: bool, diagnostics: *Diagnostics, ) Error!Owned { odata.sameOrigin(c.base_url, url) catch |err| switch (err) { error.InvalidLink => return error.InvalidEndpoint, error.UntrustedLink => { log.warn("refusing to follow a link to another host", .{}); return error.UntrustedLink; }, }; const body = c.getRaw(io, gpa, url, .{ .page_size = request.page_size, .body_type = request.body_type, .eventual_consistency = request.eventual_consistency, .max_response_bytes = max_response_bytes, }, diagnostics) catch |err| switch (err) { error.ApiError => { // A stale delta token is 410 Gone with `resyncRequired`, and it is // not a failure to retry: it means the incremental path is gone // and the folder has to be listed in full. Nothing else in this // library returns 410. if (is_delta) { if (diagnostics.http.api_error) |*e| { if (e.isResyncRequired(diagnostics.http.status orelse .ok)) { return error.ResyncRequired; } } } return error.ApiError; }, else => |e| return e, }; defer gpa.free(body); var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const root = std.json.parseFromSliceLeaky( std.json.Value, arena.allocator(), body, .{}, ) catch return error.Malformed; if (root != .object) return error.Malformed; return .{ .arena = arena, .root = root }; } pub const RawOptions = struct { method: std.http.Method = .GET, accept: []const u8 = "application/json", /// An already-encoded request body. `$batch` is the only thing in this /// library that sends one. payload: ?[]const u8 = null, content_type: ?[]const u8 = null, page_size: ?u32 = null, body_type: ?Message.BodyType = null, eventual_consistency: bool = false, max_response_bytes: usize = http.default_max_response_bytes, }; /// The body of an absolute URL, with the token refreshed as needed. Not /// parsed: this is also how `getMime` gets the RFC 5322 bytes and how `Batch` /// posts to `$batch`. pub fn getRaw( c: *Client, io: std.Io, gpa: std.mem.Allocator, url: []const u8, options: RawOptions, diagnostics: *Diagnostics, ) Error![]u8 { _ = try c.refreshIfNeeded(io, diagnostics); return c.getOnce(io, gpa, url, options, diagnostics) catch |err| switch (err) { // The token was refused despite looking valid -- consent withdrawn, a // conditional access policy, or a clock that disagrees with // Microsoft's. One refresh, one more try, and then the failure is // real. error.Unauthorized => blk: { log.debug("401 with a token that looked good; refreshing", .{}); try c.forceRefresh(io, diagnostics); break :blk try c.getOnce(io, gpa, url, options, diagnostics); }, else => |e| return e, }; } fn getOnce( c: *Client, io: std.Io, gpa: std.mem.Allocator, url: []const u8, options: RawOptions, diagnostics: *Diagnostics, ) Error![]u8 { const uri = std.Uri.parse(url) catch return error.InvalidEndpoint; const authorization = try c.tokens.authorizationHeader(gpa); defer gpa.free(authorization); // Two `Prefer` values would be two headers, which is legal, but one // comma-separated header is what every Graph example shows. var prefer_buf: [96]u8 = undefined; var prefer: std.Io.Writer = .fixed(&prefer_buf); if (options.page_size) |size| { prefer.print("odata.maxpagesize={d}", .{size}) catch return error.OutOfMemory; } if (options.body_type) |body_type| { if (prefer.buffered().len > 0) prefer.writeAll(", ") catch return error.OutOfMemory; // Quoted, which is how the reference writes it and how Graph's own // parser wants it. prefer.print("outlook.body-content-type=\"{t}\"", .{body_type}) catch return error.OutOfMemory; } var headers: [2]std.http.Header = undefined; var header_count: usize = 0; if (prefer.buffered().len > 0) { headers[header_count] = .{ .name = "Prefer", .value = prefer.buffered() }; header_count += 1; } if (options.eventual_consistency) { headers[header_count] = .{ .name = "ConsistencyLevel", .value = "eventual" }; header_count += 1; } return http.fetch(io, gpa, .{ .method = options.method, .uri = uri, .payload = options.payload, .content_type = options.content_type, .authorization = authorization, .accept = options.accept, .extra_headers = headers[0..header_count], .user_agent = c.user_agent, .max_response_bytes = options.max_response_bytes, .retry = c.retry, .rng = c.rng, }, &diagnostics.http); } /// `//me/`, or `//users//`. fn buildUrl( c: *const Client, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); const w = &buf.writer; // Writing to an `Allocating` can only fail by the allocator failing, which // is why every one of these maps its error to `OutOfMemory`. w.writeAll(std.mem.trimEnd(u8, c.base_url, "/")) catch return error.OutOfMemory; w.writeByte('/') catch return error.OutOfMemory; w.writeAll(c.api_version) catch return error.OutOfMemory; c.writeMailboxPath(w, path, query) catch return error.OutOfMemory; return buf.toOwnedSlice(); } /// `/me/?`, which is the form a `$batch` entry's `url` takes: /// relative to the version root, because the version is already in the URL the /// batch itself was posted to. /// /// Public so that a caller assembling its own batch entries spells them the /// same way this does -- and, more to the point, encodes the mailbox id the /// same way. pub fn buildBatchUrl( c: *const Client, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); c.writeMailboxPath(&buf.writer, path, query) catch return error.OutOfMemory; return buf.toOwnedSlice(); } fn writeMailboxPath( c: *const Client, w: *std.Io.Writer, path: []const u8, query: ?[]const u8, ) std.Io.Writer.Error!void { if (std.mem.eql(u8, c.user_id, "me")) { try w.writeAll("/me"); } else { try w.writeAll("/users/"); // A principal name needs encoding: an `@` is legal in a path segment, // but an apostrophe in a surname is not what it looks like and a `/` // would address something else entirely. try oidc.QueryBuilder.encode(w, c.user_id); } if (path.len > 0) { try w.writeByte('/'); try w.writeAll(path); } if (query) |q| { if (q.len > 0) { try w.writeByte('?'); try w.writeAll(q); } } } /// `messages`, `mailFolders//messages`, or either with a suffix such as /// `delta` on the end. fn messagesPath( gpa: std.mem.Allocator, folder: ?[]const u8, suffix: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); const w = &buf.writer; if (folder) |id| { w.writeAll("mailFolders/") catch return error.OutOfMemory; oidc.QueryBuilder.encode(w, id) catch return error.OutOfMemory; w.writeByte('/') catch return error.OutOfMemory; } w.writeAll("messages") catch return error.OutOfMemory; if (suffix) |s| { w.writeByte('/') catch return error.OutOfMemory; w.writeAll(s) catch return error.OutOfMemory; } return buf.toOwnedSlice(); } /// `/[/]` with the id percent-encoded. /// /// Graph's ids are opaque and long, and they routinely contain `/`, `+` and /// `=` -- a message id really is base64-shaped. An id carrying a `/` /// unencoded would not merely fail: it would address a different endpoint. /// The suffix is written through, because every one of them is a literal here. pub fn resourcePath( gpa: std.mem.Allocator, collection: []const u8, id: []const u8, suffix: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); const w = &buf.writer; w.writeAll(collection) catch return error.OutOfMemory; w.writeByte('/') catch return error.OutOfMemory; oidc.QueryBuilder.encode(w, id) catch return error.OutOfMemory; if (suffix) |s| { w.writeByte('/') catch return error.OutOfMemory; w.writeAll(s) catch return error.OutOfMemory; } return buf.toOwnedSlice(); } const testing = std.testing; /// A client that never talks to anything, for the tests below that only look /// at what a URL comes out as. fn testClient(base_url: []const u8, user_id: []const u8) Client { // `tokens` is never dereferenced by the functions under test here. return .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined, .base_url = base_url, .user_id = user_id, }; } test "the URL for the signed-in user" { const c = testClient("https://graph.microsoft.com", "me"); const url = try c.buildUrl(testing.allocator, "messages", "$top=5"); defer testing.allocator.free(url); try testing.expectEqualStrings( "https://graph.microsoft.com/v1.0/me/messages?$top=5", url, ); const bare = try c.buildUrl(testing.allocator, "", null); defer testing.allocator.free(bare); try testing.expectEqualStrings("https://graph.microsoft.com/v1.0/me", bare); } test "a mailbox that is not the signed-in user" { const c = testClient("https://graph.microsoft.com", "someone+else@example.com"); const url = try c.buildUrl(testing.allocator, "mailFolders", null); defer testing.allocator.free(url); // The `+` is encoded, which is the whole reason the id goes through the // encoder: unencoded it would read as a space. try testing.expectEqualStrings( "https://graph.microsoft.com/v1.0/users/someone%2Belse%40example.com/mailFolders", url, ); } test "a trailing slash on the base URL does not double up" { const c = testClient("https://graph.microsoft.com/", "me"); const url = try c.buildUrl(testing.allocator, "messages", null); defer testing.allocator.free(url); try testing.expectEqualStrings("https://graph.microsoft.com/v1.0/me/messages", url); } test "a national cloud and the beta version" { var c = testClient("https://microsoftgraph.chinacloudapi.cn", "me"); c.api_version = "beta"; const url = try c.buildUrl(testing.allocator, "messages", null); defer testing.allocator.free(url); try testing.expectEqualStrings( "https://microsoftgraph.chinacloudapi.cn/beta/me/messages", url, ); } test "an id cannot address another endpoint" { // Graph's message ids are base64-shaped and really do contain `/` and // `=`. Unencoded, the second of these addresses `/me/messages/../../..`. const path = try resourcePath( testing.allocator, "messages", "AAMkAGI1/AAAoZ+CfHAAA=", null, ); defer testing.allocator.free(path); try testing.expectEqualStrings("messages/AAMkAGI1%2FAAAoZ%2BCfHAAA%3D", path); const escaping = try resourcePath(testing.allocator, "messages", "../../users", "$value"); defer testing.allocator.free(escaping); try testing.expectEqualStrings("messages/..%2F..%2Fusers/$value", escaping); } test "the message collection paths" { { const path = try messagesPath(testing.allocator, null, null); defer testing.allocator.free(path); try testing.expectEqualStrings("messages", path); } { const path = try messagesPath(testing.allocator, "inbox", null); defer testing.allocator.free(path); try testing.expectEqualStrings("mailFolders/inbox/messages", path); } { const path = try messagesPath(testing.allocator, "AAMk/ADcb=", "delta"); defer testing.allocator.free(path); try testing.expectEqualStrings("mailFolders/AAMk%2FADcb%3D/messages/delta", path); } } test "the filter a delta query will accept" { const filter = try receivedAfter( testing.allocator, .fromNanoseconds(@as(i96, 1700000000) * std.time.ns_per_s), ); defer testing.allocator.free(filter); try testing.expectEqualStrings("receivedDateTime ge 2023-11-14T22:13:20Z", filter); } test "the walk select names what a walk needs and not the body" { for (walk_select) |field| { try testing.expect(!std.mem.eql(u8, field, "body")); try testing.expect(!std.mem.eql(u8, field, "uniqueBody")); } // And the two that a local store cannot do without. var has_id = false; var has_message_id = false; for (walk_select) |field| { if (std.mem.eql(u8, field, "id")) has_id = true; // The one thing that survives a message being moved between folders. if (std.mem.eql(u8, field, "internetMessageId")) has_message_id = true; } try testing.expect(has_id); try testing.expect(has_message_id); } test "the attachment list select leaves the bytes out" { for (attachment_list_select) |field| { try testing.expect(!std.mem.eql(u8, field, "contentBytes")); } } test { _ = ApiError; _ = Attachment; _ = Batch; _ = MailFolder; _ = Message; _ = User; _ = http; _ = iso8601; _ = json; _ = odata; }