diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c5a721..234fed8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.2.0] - 2026-09-14 + +### Added + +- `campaigns()`: `createDraft`, `createAndSend`, `list`, `listForStream`, + `get`, `getForStream`, `update`, `send`, `cancel`. The two create methods + hit different routes: `createDraft` writes the campaign and waits, while + `createAndSend` expands it to the stream's subscribers before the call + returns. +- `subscribers()`: `list`, `add`, `importAddresses`, `complaint`, `remove`. +- `layouts()`: `list`, `create`, `get`, `update`, `delete`, `uploadLogo`. +- `inbound()`: `list`, `get`, `retry`, `bypass`. +- `logs()`: `list`, `tags`. +- `emails().sendToStream()` for broadcasting to a stream's subscribers. +- An idempotency-key overload on all four send methods. The key travels as + the `Idempotency-Key` header, because the body is what the server hashes + to recognise a replay. +- `StreamRequest` takes a `permalink` and an `archived` flag. Without the + permalink the API derives one from the name, which a caller that has to + know the permalink up front cannot rely on. + ## [0.1.0] - 2026-07-12 ### Added @@ -22,5 +43,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `dmarc()`: `summary`, `reports`, `report`. - Typed, unchecked `CamelMailerException` with stable API error `code` and HTTP `statusCode`. -[Unreleased]: https://github.com/camelmailer/camelmailer-java/compare/v0.1.0...HEAD +[Unreleased]: https://github.com/camelmailer/camelmailer-java/compare/v0.2.0...HEAD +[0.2.0]: https://github.com/camelmailer/camelmailer-java/releases/tag/v0.2.0 [0.1.0]: https://github.com/camelmailer/camelmailer-java/releases/tag/v0.1.0 diff --git a/README.md b/README.md index 279925d..eb44528 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,22 @@ client.emails().sendWithTemplate( .build()); client.emails().sendWithTemplateBatch(List.of(...)); +// Retry-safe sends: the same key with the same body returns the first +// result instead of queuing a second copy, and a different body under the +// same key is refused with InvalidIdempotentRequest. All four send methods +// take one. +client.emails().send(request, "order-" + orderId); + +// Broadcast to everyone subscribed to a stream. Recipients past the +// per-request cap of 1000 come back as skipped, so a larger audience wants +// a campaign. +StreamSendResult broadcast = client.emails().sendToStream("newsletter", + SendEmailRequest.builder() + .from("news@acme.com") + .subject("September") + .textBody("What shipped this month.") + .build()); + // Read back EmailDetails details = client.emails().get(messageId); // message + deliveries EmailList page = client.emails().list( @@ -104,12 +120,109 @@ RenderedTemplate preview = client.templates().render("welcome", Map.of("name", " ```java client.streams().list(); -client.streams().create(StreamRequest.builder().name("Receipts").streamType("transactional").build()); +client.streams().create(StreamRequest.builder() + .name("Receipts").permalink("receipts").streamType("transactional").build()); client.streams().get("receipts"); client.streams().update("receipts", StreamRequest.builder().name("Billing").build()); client.streams().archive("receipts"); ``` +### Campaigns + +A campaign is content plus an audience. The two ways to create one behave +differently, so pick deliberately: `createDraft` writes it and waits, +`createAndSend` expands it to the stream's subscribers before the call +returns. + +```java +// Write it and leave it alone. Without a schedule it stays a draft; with +// one it becomes "scheduled" and the server sends it when due. +Campaign draft = client.campaigns().createDraft( + DraftCampaignRequest.builder() + .stream("newsletter") + .from("news@acme.com") + .name("September") + .subject("What shipped") + .textBody("Hello.") + // .scheduledAt("2026-10-01T08:00:00Z") + .build()); + +// Goes out on the spot, no draft and no schedule. +client.campaigns().createAndSend("newsletter", + SendCampaignRequest.builder() + .name("Status update") + .from("news@acme.com") + .textBody("All clear.") + .build()); + +client.campaigns().list(); +client.campaigns().listForStream("newsletter"); +CampaignDetail detail = client.campaigns().get(draft.id()); // campaign + stats + +// scheduledAt schedules; clearSchedule drops it back to a draft. Touching +// neither leaves the schedule standing, so the two are separate. +client.campaigns().update(draft.id(), + UpdateCampaignRequest.builder().scheduledAt("2026-10-01T08:00:00Z").build()); +client.campaigns().update(draft.id(), + UpdateCampaignRequest.builder().clearSchedule().build()); + +client.campaigns().send(draft.id()); // now, whatever the schedule said +client.campaigns().cancel(draft.id()); +``` + +### Subscribers + +A broadcast send to an address that is not subscribed is refused, so this +list is the audience. + +```java +client.subscribers().list("newsletter"); +client.subscribers().add("newsletter", + SubscriberRequest.builder().address("ada@example.com").name("Ada").build()); +client.subscribers().importAddresses("newsletter", + List.of("ada@example.com", "grace@example.com")); +client.subscribers().complaint("newsletter", "ada@example.com"); // suppress + unsubscribe +client.subscribers().remove("newsletter", "ada@example.com"); +``` + +### Layouts + +A layout wraps every template that uses it. `htmlWrapper` has to embed the +body with `{{{ content }}}`. + +```java +client.layouts().list(); +client.layouts().create(LayoutRequest.builder() + .name("Default") + .permalink("default") + .htmlWrapper("{{{ content }}}") + .build()); +client.layouts().get("default"); +client.layouts().update("default", LayoutRequest.builder().name("Main").build()); +String logoUrl = client.layouts().uploadLogo("default", "data:image/png;base64,..."); +client.layouts().delete("default"); +``` + +### Inbound and held messages + +```java +InboundList held = client.inbound().list( + ListInboundOptions.builder().status("held").build()); +client.inbound().get(55); +client.inbound().retry(55); // back on the delivery queue +client.inbound().bypass(55); // release past the hold +``` + +### Logs + +Useful when a send did not arrive and the question is whether the request +ever reached the API. + +```java +LogList requests = client.logs().list(null, 25); +List tags = client.logs().tags(); +``` + ### Stats and bounces ```java diff --git a/pom.xml b/pom.xml index 0c9a90e..ecca6a7 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.camelmailer camelmailer-java - 0.1.0 + 0.2.0 jar camelmailer-java diff --git a/src/main/java/com/camelmailer/CamelMailer.java b/src/main/java/com/camelmailer/CamelMailer.java index d2321aa..062ae36 100644 --- a/src/main/java/com/camelmailer/CamelMailer.java +++ b/src/main/java/com/camelmailer/CamelMailer.java @@ -1,11 +1,16 @@ package com.camelmailer; import com.camelmailer.bounces.Bounces; +import com.camelmailer.campaigns.Campaigns; import com.camelmailer.dmarc.Dmarc; import com.camelmailer.emails.Emails; import com.camelmailer.http.ApiClient; +import com.camelmailer.inbound.Inbound; +import com.camelmailer.layouts.Layouts; +import com.camelmailer.logs.Logs; import com.camelmailer.stats.Stats; import com.camelmailer.streams.Streams; +import com.camelmailer.subscribers.Subscribers; import com.camelmailer.templates.Templates; import java.net.http.HttpClient; @@ -47,6 +52,11 @@ public final class CamelMailer { private final Stats stats; private final Bounces bounces; private final Dmarc dmarc; + private final Campaigns campaigns; + private final Subscribers subscribers; + private final Layouts layouts; + private final Inbound inbound; + private final Logs logs; /** * Creates a client for the CamelMailer cloud ({@value #DEFAULT_BASE_URL}). @@ -70,6 +80,11 @@ private CamelMailer(Builder builder) { this.stats = new Stats(api); this.bounces = new Bounces(api); this.dmarc = new Dmarc(api); + this.campaigns = new Campaigns(api); + this.subscribers = new Subscribers(api); + this.layouts = new Layouts(api); + this.inbound = new Inbound(api); + this.logs = new Logs(api); } /** @@ -127,7 +142,52 @@ public Bounces bounces() { } /** - * DMARC compliance reporting. + * Broadcast campaigns. + * + * @return the campaigns service + */ + public Campaigns campaigns() { + return campaigns; + } + + /** + * Opt-in subscribers of a broadcast stream. + * + * @return the subscribers service + */ + public Subscribers subscribers() { + return subscribers; + } + + /** + * Template layouts. + * + * @return the layouts service + */ + public Layouts layouts() { + return layouts; + } + + /** + * Inbound and held messages. + * + * @return the inbound service + */ + public Inbound inbound() { + return inbound; + } + + /** + * The server's request log and tag index. + * + * @return the logs service + */ + public Logs logs() { + return logs; + } + + /** + * DMARC monitoring. * * @return the DMARC service */ diff --git a/src/main/java/com/camelmailer/campaigns/Campaign.java b/src/main/java/com/camelmailer/campaigns/Campaign.java new file mode 100644 index 0000000..30a1c24 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/Campaign.java @@ -0,0 +1,36 @@ +package com.camelmailer.campaigns; + +/** + * A broadcast campaign: content plus an audience. + * + * @param id numeric campaign id + * @param name display name + * @param subject message subject + * @param from sender address + * @param htmlBody HTML part + * @param textBody plain-text part + * @param status lifecycle state: {@code draft}, {@code scheduled}, {@code sending}, {@code sent}, + * {@code failed} or {@code canceled}. Only draft and scheduled are editable. + * @param total recipient count snapshotted when the send begins + * @param sent recipients expanded into messages so far + * @param streamId id of the audience stream + * @param stream permalink and name of the audience stream + * @param scheduledAt send time of a scheduled campaign, or {@code null} + * @param createdAt when the campaign row was created + * @param completedAt when expansion finished ({@code sent} or {@code failed}) + */ +public record Campaign( + long id, + String name, + String subject, + String from, + String htmlBody, + String textBody, + String status, + long total, + long sent, + long streamId, + CampaignStream stream, + String scheduledAt, + String createdAt, + String completedAt) {} diff --git a/src/main/java/com/camelmailer/campaigns/CampaignDetail.java b/src/main/java/com/camelmailer/campaigns/CampaignDetail.java new file mode 100644 index 0000000..adfe7a4 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/CampaignDetail.java @@ -0,0 +1,9 @@ +package com.camelmailer.campaigns; + +/** + * A campaign together with its statistics. + * + * @param campaign the campaign itself + * @param stats its counters + */ +public record CampaignDetail(Campaign campaign, CampaignStats stats) {} diff --git a/src/main/java/com/camelmailer/campaigns/CampaignStats.java b/src/main/java/com/camelmailer/campaigns/CampaignStats.java new file mode 100644 index 0000000..a18d3ca --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/CampaignStats.java @@ -0,0 +1,21 @@ +package com.camelmailer.campaigns; + +/** + * Per-campaign counters, attributed through the messages the campaign produced. + * + * @param total recipient count of the campaign + * @param sent messages created + * @param delivered messages delivered + * @param failed messages that failed + * @param opened messages opened at least once + * @param clicked messages with at least one click + * @param unsubscribed resulting unsubscribes + */ +public record CampaignStats( + long total, + long sent, + long delivered, + long failed, + long opened, + long clicked, + long unsubscribed) {} diff --git a/src/main/java/com/camelmailer/campaigns/CampaignStream.java b/src/main/java/com/camelmailer/campaigns/CampaignStream.java new file mode 100644 index 0000000..ca0ad53 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/CampaignStream.java @@ -0,0 +1,9 @@ +package com.camelmailer.campaigns; + +/** + * The audience stream carried on every campaign, so a list needs no second lookup. + * + * @param permalink URL-safe identifier of the stream + * @param name display name of the stream + */ +public record CampaignStream(String permalink, String name) {} diff --git a/src/main/java/com/camelmailer/campaigns/Campaigns.java b/src/main/java/com/camelmailer/campaigns/Campaigns.java new file mode 100644 index 0000000..4079b37 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/Campaigns.java @@ -0,0 +1,157 @@ +package com.camelmailer.campaigns; + +import com.camelmailer.http.ApiClient; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; + +/** + * Broadcast campaigns: {@code /api/v2/server/campaigns}. + * + *

A campaign is content plus an audience. There are two ways to create one and they behave + * differently: {@link #createDraft} writes it and waits, while {@link #createAndSend} expands it to + * the stream's subscribers before the call returns. + * + *

Obtain via {@link com.camelmailer.CamelMailer#campaigns()}. + */ +public final class Campaigns { + + private static final String BASE = "/api/v2/server/campaigns"; + private static final String STREAMS = "/api/v2/server/streams"; + + private final ApiClient client; + + /** + * Creates the service. + * + * @param client the internal API client + */ + public Campaigns(ApiClient client) { + this.client = client; + } + + /** + * Lists every campaign of the server, newest first. + * + * @return the campaigns + */ + public List list() { + return client.convertList(client.get(BASE).path("campaigns"), Campaign.class); + } + + /** + * Lists the campaigns of one broadcast stream. + * + * @param permalink the stream permalink + * @return the campaigns of that stream + */ + public List listForStream(String permalink) { + JsonNode data = client.get(STREAMS + "/" + permalink + "/campaigns"); + return client.convertList(data.path("campaigns"), Campaign.class); + } + + /** + * Fetches a campaign together with its statistics. + * + * @param id the campaign id + * @return the campaign and its counters + */ + public CampaignDetail get(long id) { + return client.convert(client.get(BASE + "/" + id), CampaignDetail.class); + } + + /** + * Fetches a campaign through its stream. + * + * @param permalink the stream permalink + * @param id the campaign id + * @return the campaign and its counters + */ + public CampaignDetail getForStream(String permalink, long id) { + return client.convert( + client.get(STREAMS + "/" + permalink + "/campaigns/" + id), CampaignDetail.class); + } + + /** + * Creates a campaign without sending it. + * + *

Name the audience with {@code stream}. Leave the schedule unset for a draft, set it for a + * scheduled send, or set {@code sendNow} to send on creation. + * + * @param request the campaign fields + * @return the created campaign + */ + public Campaign createDraft(DraftCampaignRequest request) { + return client.convert(client.post(BASE, request).path("campaign"), Campaign.class); + } + + /** + * Creates a campaign on a broadcast stream and sends it immediately. + * + *

The send starts before this call returns, so there is no draft to review and no schedule to + * set. Use {@link #createDraft} when the campaign should wait. + * + * @param permalink the broadcast stream permalink + * @param request the campaign fields + * @return the created campaign, already sending + */ + public Campaign createAndSend(String permalink, SendCampaignRequest request) { + JsonNode data = client.post(STREAMS + "/" + permalink + "/campaigns", request); + return client.convert(data.path("campaign"), Campaign.class); + } + + /** + * Updates a draft or scheduled campaign. + * + *

A campaign that is already sending cannot be edited and the API answers {@code + * ValidationError}. + * + * @param id the campaign id + * @param request the fields to change + * @return the updated campaign + */ + public Campaign update(long id, UpdateCampaignRequest request) { + ObjectNode body = client.newObject(); + putIfSet(body, "name", request.getName()); + putIfSet(body, "from", request.getFrom()); + putIfSet(body, "subject", request.getSubject()); + putIfSet(body, "html_body", request.getHtmlBody()); + putIfSet(body, "text_body", request.getTextBody()); + if (request.isClearSchedule()) { + // An omitted field leaves the schedule standing; only an explicit + // null drops the campaign back to a draft. + body.putNull("scheduled_at"); + } else { + putIfSet(body, "scheduled_at", request.getScheduledAt()); + } + return client.convert(client.patch(BASE + "/" + id, body).path("campaign"), Campaign.class); + } + + /** + * Sends a campaign now, whatever its schedule said. + * + * @param id the campaign id + * @return the campaign, now sending + */ + public Campaign send(long id) { + return client.convert( + client.post(BASE + "/" + id + "/send", null).path("campaign"), Campaign.class); + } + + /** + * Cancels a scheduled or in-flight campaign. Messages already queued are not recalled. + * + * @param id the campaign id + * @return the canceled campaign + */ + public Campaign cancel(long id) { + return client.convert( + client.post(BASE + "/" + id + "/cancel", null).path("campaign"), Campaign.class); + } + + private static void putIfSet(ObjectNode body, String field, String value) { + if (value != null) { + body.put(field, value); + } + } +} diff --git a/src/main/java/com/camelmailer/campaigns/DraftCampaignRequest.java b/src/main/java/com/camelmailer/campaigns/DraftCampaignRequest.java new file mode 100644 index 0000000..1ef4f79 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/DraftCampaignRequest.java @@ -0,0 +1,224 @@ +package com.camelmailer.campaigns; + +/** + * Fields for {@link Campaigns#createDraft}. + * + *

The initial status follows what you pass: {@code sendNow} wins, then a {@code scheduledAt} + * (status {@code scheduled}), else a draft. + */ +public final class DraftCampaignRequest { + + private final String stream; + private final String from; + private final String name; + private final String subject; + private final String htmlBody; + private final String textBody; + private final String scheduledAt; + private final Boolean sendNow; + + private DraftCampaignRequest(Builder builder) { + this.stream = builder.stream; + this.from = builder.from; + this.name = builder.name; + this.subject = builder.subject; + this.htmlBody = builder.htmlBody; + this.textBody = builder.textBody; + this.scheduledAt = builder.scheduledAt; + this.sendNow = builder.sendNow; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the permalink of the broadcast stream to send to. + * + * @return the permalink of the broadcast stream to send to, or {@code null} when unset + */ + public String getStream() { + return stream; + } + + /** + * Returns the bare sender address. + * + * @return the bare sender address, or {@code null} when unset + */ + public String getFrom() { + return from; + } + + /** + * Returns the display name. + * + * @return the display name, or {@code null} when unset + */ + public String getName() { + return name; + } + + /** + * Returns the message subject. + * + * @return the message subject, or {@code null} when unset + */ + public String getSubject() { + return subject; + } + + /** + * Returns the HTML part. + * + * @return the HTML part, or {@code null} when unset + */ + public String getHtmlBody() { + return htmlBody; + } + + /** + * Returns the plain-text part. + * + * @return the plain-text part, or {@code null} when unset + */ + public String getTextBody() { + return textBody; + } + + /** + * Returns the RFC 3339 send time, which arms the campaign as scheduled. + * + * @return the RFC 3339 send time, which arms the campaign as scheduled, or {@code null} when + * unset + */ + public String getScheduledAt() { + return scheduledAt; + } + + /** + * Returns whether to send on creation, overriding the schedule. + * + * @return whether to send on creation, overriding the schedule, or {@code null} when unset + */ + public Boolean getSendNow() { + return sendNow; + } + + /** Builder for {@link DraftCampaignRequest}. */ + public static final class Builder { + + private String stream; + private String from; + private String name; + private String subject; + private String htmlBody; + private String textBody; + private String scheduledAt; + private Boolean sendNow; + + private Builder() {} + + /** + * Sets the permalink of the broadcast stream to send to (required). + * + * @param stream the permalink of the broadcast stream to send to + * @return this builder + */ + public Builder stream(String stream) { + this.stream = stream; + return this; + } + + /** + * Sets the bare sender address (required). + * + * @param from the bare sender address + * @return this builder + */ + public Builder from(String from) { + this.from = from; + return this; + } + + /** + * Sets the display name. + * + * @param name the display name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Sets the message subject. + * + * @param subject the message subject + * @return this builder + */ + public Builder subject(String subject) { + this.subject = subject; + return this; + } + + /** + * Sets the HTML part. + * + * @param htmlBody the HTML part + * @return this builder + */ + public Builder htmlBody(String htmlBody) { + this.htmlBody = htmlBody; + return this; + } + + /** + * Sets the plain-text part. + * + * @param textBody the plain-text part + * @return this builder + */ + public Builder textBody(String textBody) { + this.textBody = textBody; + return this; + } + + /** + * Sets the RFC 3339 send time, which arms the campaign as scheduled. + * + * @param scheduledAt the RFC 3339 send time, which arms the campaign as scheduled + * @return this builder + */ + public Builder scheduledAt(String scheduledAt) { + this.scheduledAt = scheduledAt; + return this; + } + + /** + * Sets whether to send on creation, overriding the schedule. + * + * @param sendNow whether to send on creation, overriding the schedule + * @return this builder + */ + public Builder sendNow(Boolean sendNow) { + this.sendNow = sendNow; + return this; + } + + /** + * Builds the request. + * + * @return the immutable request + */ + public DraftCampaignRequest build() { + return new DraftCampaignRequest(this); + } + } +} diff --git a/src/main/java/com/camelmailer/campaigns/SendCampaignRequest.java b/src/main/java/com/camelmailer/campaigns/SendCampaignRequest.java new file mode 100644 index 0000000..bf92966 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/SendCampaignRequest.java @@ -0,0 +1,153 @@ +package com.camelmailer.campaigns; + +/** + * Fields for {@link Campaigns#createAndSend}. + * + *

There is no schedule here: the send starts before the call returns. + */ +public final class SendCampaignRequest { + + private final String name; + private final String from; + private final String subject; + private final String htmlBody; + private final String textBody; + + private SendCampaignRequest(Builder builder) { + this.name = builder.name; + this.from = builder.from; + this.subject = builder.subject; + this.htmlBody = builder.htmlBody; + this.textBody = builder.textBody; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the display name. + * + * @return the display name, or {@code null} when unset + */ + public String getName() { + return name; + } + + /** + * Returns the bare sender address. + * + * @return the bare sender address, or {@code null} when unset + */ + public String getFrom() { + return from; + } + + /** + * Returns the message subject. + * + * @return the message subject, or {@code null} when unset + */ + public String getSubject() { + return subject; + } + + /** + * Returns the HTML part. + * + * @return the HTML part, or {@code null} when unset + */ + public String getHtmlBody() { + return htmlBody; + } + + /** + * Returns the plain-text part. + * + * @return the plain-text part, or {@code null} when unset + */ + public String getTextBody() { + return textBody; + } + + /** Builder for {@link SendCampaignRequest}. */ + public static final class Builder { + + private String name; + private String from; + private String subject; + private String htmlBody; + private String textBody; + + private Builder() {} + + /** + * Sets the display name (required). + * + * @param name the display name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Sets the bare sender address. + * + * @param from the bare sender address + * @return this builder + */ + public Builder from(String from) { + this.from = from; + return this; + } + + /** + * Sets the message subject. + * + * @param subject the message subject + * @return this builder + */ + public Builder subject(String subject) { + this.subject = subject; + return this; + } + + /** + * Sets the HTML part. + * + * @param htmlBody the HTML part + * @return this builder + */ + public Builder htmlBody(String htmlBody) { + this.htmlBody = htmlBody; + return this; + } + + /** + * Sets the plain-text part. + * + * @param textBody the plain-text part + * @return this builder + */ + public Builder textBody(String textBody) { + this.textBody = textBody; + return this; + } + + /** + * Builds the request. + * + * @return the immutable request + */ + public SendCampaignRequest build() { + return new SendCampaignRequest(this); + } + } +} diff --git a/src/main/java/com/camelmailer/campaigns/UpdateCampaignRequest.java b/src/main/java/com/camelmailer/campaigns/UpdateCampaignRequest.java new file mode 100644 index 0000000..37a5173 --- /dev/null +++ b/src/main/java/com/camelmailer/campaigns/UpdateCampaignRequest.java @@ -0,0 +1,208 @@ +package com.camelmailer.campaigns; + +/** + * Fields for {@link Campaigns#update}. Unset fields are left unchanged. + * + *

The schedule is three-valued, which is why it has two builder methods: touching neither keeps + * the current schedule, {@code scheduledAt} moves a draft to {@code scheduled}, and {@code + * clearSchedule} sends an explicit {@code null}, which drops the campaign back to {@code draft}. An + * omitted field and a {@code null} mean different things to the API. + */ +public final class UpdateCampaignRequest { + + private final String name; + private final String from; + private final String subject; + private final String htmlBody; + private final String textBody; + private final String scheduledAt; + private final boolean clearSchedule; + + private UpdateCampaignRequest(Builder builder) { + this.name = builder.name; + this.from = builder.from; + this.subject = builder.subject; + this.htmlBody = builder.htmlBody; + this.textBody = builder.textBody; + this.scheduledAt = builder.scheduledAt; + this.clearSchedule = builder.clearSchedule; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the display name. + * + * @return the name, or {@code null} when unset + */ + public String getName() { + return name; + } + + /** + * Returns the sender address. + * + * @return the address, or {@code null} when unset + */ + public String getFrom() { + return from; + } + + /** + * Returns the subject. + * + * @return the subject, or {@code null} when unset + */ + public String getSubject() { + return subject; + } + + /** + * Returns the HTML part. + * + * @return the HTML body, or {@code null} when unset + */ + public String getHtmlBody() { + return htmlBody; + } + + /** + * Returns the plain-text part. + * + * @return the text body, or {@code null} when unset + */ + public String getTextBody() { + return textBody; + } + + /** + * Returns the schedule. + * + * @return the RFC 3339 send time, or {@code null} when unset or cleared + */ + public String getScheduledAt() { + return scheduledAt; + } + + /** + * Returns whether the update clears the schedule. + * + *

{@link Campaigns#update} turns this into an explicit {@code null} in the body; an omitted + * field would leave the schedule standing. + * + * @return {@code true} when the schedule should be cleared + */ + public boolean isClearSchedule() { + return clearSchedule; + } + + /** Builder for {@link UpdateCampaignRequest}. */ + public static final class Builder { + + private String name; + private String from; + private String subject; + private String htmlBody; + private String textBody; + private String scheduledAt; + private boolean clearSchedule; + + private Builder() {} + + /** + * Sets the display name. + * + * @param name the name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Sets the sender address. + * + * @param from the address + * @return this builder + */ + public Builder from(String from) { + this.from = from; + return this; + } + + /** + * Sets the subject. + * + * @param subject the subject + * @return this builder + */ + public Builder subject(String subject) { + this.subject = subject; + return this; + } + + /** + * Sets the HTML part. + * + * @param htmlBody the HTML body + * @return this builder + */ + public Builder htmlBody(String htmlBody) { + this.htmlBody = htmlBody; + return this; + } + + /** + * Sets the plain-text part. + * + * @param textBody the text body + * @return this builder + */ + public Builder textBody(String textBody) { + this.textBody = textBody; + return this; + } + + /** + * Schedules the campaign, moving a draft to {@code scheduled}. + * + * @param scheduledAt RFC 3339 send time + * @return this builder + */ + public Builder scheduledAt(String scheduledAt) { + this.scheduledAt = scheduledAt; + this.clearSchedule = false; + return this; + } + + /** + * Clears the schedule, dropping the campaign back to {@code draft}. + * + *

This sends an explicit {@code null}; omitting the field would leave the schedule standing. + * + * @return this builder + */ + public Builder clearSchedule() { + this.scheduledAt = null; + this.clearSchedule = true; + return this; + } + + /** + * Builds the request. + * + * @return the immutable request + */ + public UpdateCampaignRequest build() { + return new UpdateCampaignRequest(this); + } + } +} diff --git a/src/main/java/com/camelmailer/emails/Emails.java b/src/main/java/com/camelmailer/emails/Emails.java index ab29f86..44a6efd 100644 --- a/src/main/java/com/camelmailer/emails/Emails.java +++ b/src/main/java/com/camelmailer/emails/Emails.java @@ -32,7 +32,39 @@ public Emails(ApiClient client) { * @return the queue result */ public SendResult send(SendEmailRequest request) { - return client.convert(client.post(BASE, request), SendResult.class); + return send(request, null); + } + + /** + * Sends an email with an idempotency key. + * + *

The same key with the same body returns the original result instead of queuing a second + * copy; the same key with a different body is refused with {@code InvalidIdempotentRequest} (HTTP + * 409) rather than silently ignored. Keys are scoped to the server and a completed result is kept + * for 24 hours. + * + * @param request the send parameters + * @param idempotencyKey the key, or {@code null} to send none + * @return the queue result + */ + public SendResult send(SendEmailRequest request, String idempotencyKey) { + return client.convert(client.post(BASE, request, idempotencyKey), SendResult.class); + } + + /** + * Sends the same content to every subscriber of a broadcast stream. + * + *

The result counts what was queued against what was skipped: recipients past the per-request + * cap of 1000 are skipped rather than queued, so a larger audience wants a campaign. + * + * @param permalink the broadcast stream permalink + * @param request the content; give either a subject with a body, or a template + * @return how the broadcast was split + */ + public StreamSendResult sendToStream(String permalink, SendEmailRequest request) { + return client.convert( + client.post("/api/v2/server/streams/" + permalink + "/send", request), + StreamSendResult.class); } /** @@ -43,7 +75,18 @@ public SendResult send(SendEmailRequest request) { * @return one result per request, in order */ public List sendBatch(List requests) { - JsonNode data = client.post(BASE + "/batch", requests); + return sendBatch(requests, null); + } + + /** + * Sends a batch of emails with an idempotency key. See {@link #send(SendEmailRequest, String)}. + * + * @param requests the send requests + * @param idempotencyKey the key, or {@code null} to send none + * @return one result per request, in order + */ + public List sendBatch(List requests, String idempotencyKey) { + JsonNode data = client.post(BASE + "/batch", requests, idempotencyKey); return client.convertList(data.path("messages"), BatchItem.class); } @@ -56,7 +99,19 @@ public List sendBatch(List requests) { * @return the queue result */ public SendResult sendWithTemplate(SendEmailRequest request) { - return client.convert(client.post(BASE + "/with_template", request), SendResult.class); + return sendWithTemplate(request, null); + } + + /** + * Sends a templated email with an idempotency key. See {@link #send(SendEmailRequest, String)}. + * + * @param request the send parameters including template and template model + * @param idempotencyKey the key, or {@code null} to send none + * @return the queue result + */ + public SendResult sendWithTemplate(SendEmailRequest request, String idempotencyKey) { + return client.convert( + client.post(BASE + "/with_template", request, idempotencyKey), SendResult.class); } /** @@ -66,7 +121,19 @@ public SendResult sendWithTemplate(SendEmailRequest request) { * @return one result per request, in order */ public List sendWithTemplateBatch(List requests) { - JsonNode data = client.post(BASE + "/with_template/batch", requests); + return sendWithTemplateBatch(requests, null); + } + + /** + * Sends a templated batch with an idempotency key. See {@link #send(SendEmailRequest, String)}. + * + * @param requests the send requests, each with a template set + * @param idempotencyKey the key, or {@code null} to send none + * @return one result per request, in order + */ + public List sendWithTemplateBatch( + List requests, String idempotencyKey) { + JsonNode data = client.post(BASE + "/with_template/batch", requests, idempotencyKey); return client.convertList(data.path("messages"), BatchItem.class); } diff --git a/src/main/java/com/camelmailer/emails/StreamSendResult.java b/src/main/java/com/camelmailer/emails/StreamSendResult.java new file mode 100644 index 0000000..c468ca0 --- /dev/null +++ b/src/main/java/com/camelmailer/emails/StreamSendResult.java @@ -0,0 +1,9 @@ +package com.camelmailer.emails; + +/** + * How a broadcast to a stream was split. + * + * @param queued recipients queued + * @param skipped recipients past the per-request cap of 1000 + */ +public record StreamSendResult(long queued, long skipped) {} diff --git a/src/main/java/com/camelmailer/http/ApiClient.java b/src/main/java/com/camelmailer/http/ApiClient.java index c835d9e..b6d59fd 100644 --- a/src/main/java/com/camelmailer/http/ApiClient.java +++ b/src/main/java/com/camelmailer/http/ApiClient.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.net.URI; import java.net.URLEncoder; @@ -26,6 +27,9 @@ */ public final class ApiClient { + /** SDK version, sent in the User-Agent header. Keep in sync with the POM. */ + public static final String VERSION = "0.2.0"; + private static final ObjectMapper MAPPER = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) @@ -78,7 +82,36 @@ public JsonNode get(String path, Map query) { * @return the {@code data} node of the success envelope */ public JsonNode post(String path, Object body) { - return execute(request(path, Map.of()).POST(jsonBody(body)).build()); + return post(path, body, null); + } + + /** + * Performs a POST request with an idempotency key. + * + *

The key travels as the {@code Idempotency-Key} header rather than in the body, because the + * body is what the server hashes to recognise the same request. + * + * @param path absolute API path + * @param body request body, serialized as JSON; {@code null} sends an empty JSON object + * @param idempotencyKey the key, or {@code null} to send none + * @return the {@code data} node of the success envelope + */ + public JsonNode post(String path, Object body, String idempotencyKey) { + HttpRequest.Builder builder = request(path, Map.of()); + if (idempotencyKey != null && !idempotencyKey.isEmpty()) { + builder = builder.header("Idempotency-Key", idempotencyKey); + } + return execute(builder.POST(jsonBody(body)).build()); + } + + /** + * Performs a DELETE request. + * + * @param path absolute API path + * @return the {@code data} node of the success envelope + */ + public JsonNode delete(String path) { + return execute(request(path, Map.of()).DELETE().build()); } /** @@ -130,6 +163,18 @@ public List convertList(JsonNode node, Class type) { return result; } + /** + * Creates a mutable JSON object for a request body. + * + *

Needed where a field has to reach the API as an explicit {@code null}: the mapper drops null + * properties, but a {@code NullNode} placed here survives. + * + * @return an empty object node + */ + public ObjectNode newObject() { + return MAPPER.createObjectNode(); + } + private HttpRequest.Builder request(String path, Map query) { StringBuilder url = new StringBuilder(baseUrl).append(path); boolean first = true; @@ -147,7 +192,7 @@ private HttpRequest.Builder request(String path, Map query) { .header("X-Server-API-Key", apiKey) .header("Content-Type", "application/json") .header("Accept", "application/json") - .header("User-Agent", "camelmailer-java/0.1.0"); + .header("User-Agent", "camelmailer-java/" + VERSION); } private HttpRequest.BodyPublisher jsonBody(Object body) { diff --git a/src/main/java/com/camelmailer/inbound/Inbound.java b/src/main/java/com/camelmailer/inbound/Inbound.java new file mode 100644 index 0000000..ca6635d --- /dev/null +++ b/src/main/java/com/camelmailer/inbound/Inbound.java @@ -0,0 +1,79 @@ +package com.camelmailer.inbound; + +import com.camelmailer.emails.Email; +import com.camelmailer.http.ApiClient; +import java.util.Map; + +/** + * Inbound and held messages: {@code /api/v2/server/inbound}. + * + *

Covers mail arriving through an inbound route as well as outbound mail the spam filter put on + * hold, which is why a message here can be either retried or released past the hold. + * + *

Obtain via {@link com.camelmailer.CamelMailer#inbound()}. + */ +public final class Inbound { + + private static final String BASE = "/api/v2/server/inbound"; + + private final ApiClient client; + + /** + * Creates the service. + * + * @param client the internal API client + */ + public Inbound(ApiClient client) { + this.client = client; + } + + /** + * Lists inbound and held messages, newest first. + * + * @return the first page, unfiltered + */ + public InboundList list() { + return client.convert(client.get(BASE, Map.of()), InboundList.class); + } + + /** + * Lists inbound and held messages with filters. + * + * @param options the filters + * @return the matching page + */ + public InboundList list(ListInboundOptions options) { + return client.convert(client.get(BASE, options.toQuery()), InboundList.class); + } + + /** + * Fetches one inbound message. + * + * @param id the message id + * @return the message + */ + public Email get(long id) { + return client.convert(client.get(BASE + "/" + id).path("message"), Email.class); + } + + /** + * Puts a message back on the delivery queue, for instance after fixing the route it should have + * matched. + * + * @param id the message id + * @return whether it was queued + */ + public RequeueResult retry(long id) { + return client.convert(client.post(BASE + "/" + id + "/retry", null), RequeueResult.class); + } + + /** + * Releases a held message past the hold and delivers it. + * + * @param id the message id + * @return whether it was queued + */ + public RequeueResult bypass(long id) { + return client.convert(client.post(BASE + "/" + id + "/bypass", null), RequeueResult.class); + } +} diff --git a/src/main/java/com/camelmailer/inbound/InboundList.java b/src/main/java/com/camelmailer/inbound/InboundList.java new file mode 100644 index 0000000..cf9da0b --- /dev/null +++ b/src/main/java/com/camelmailer/inbound/InboundList.java @@ -0,0 +1,13 @@ +package com.camelmailer.inbound; + +import com.camelmailer.common.Pagination; +import com.camelmailer.emails.Email; +import java.util.List; + +/** + * One page of inbound and held messages. + * + * @param inbound the page of messages; the API names this key {@code inbound}, not {@code messages} + * @param pagination the page window + */ +public record InboundList(List inbound, Pagination pagination) {} diff --git a/src/main/java/com/camelmailer/inbound/ListInboundOptions.java b/src/main/java/com/camelmailer/inbound/ListInboundOptions.java new file mode 100644 index 0000000..f69899a --- /dev/null +++ b/src/main/java/com/camelmailer/inbound/ListInboundOptions.java @@ -0,0 +1,138 @@ +package com.camelmailer.inbound; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Filters for {@link Inbound#list}. All optional. + * + *

{@code
+ * ListInboundOptions options = ListInboundOptions.builder().status("held").perPage(50).build();
+ * }
+ */ +public final class ListInboundOptions { + + private final String status; + private final String stream; + private final String query; + private final Integer page; + private final Integer perPage; + + private ListInboundOptions(Builder builder) { + this.status = builder.status; + this.stream = builder.stream; + this.query = builder.query; + this.page = builder.page; + this.perPage = builder.perPage; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Renders the filters as query parameters. + * + * @return the parameters; unset filters are omitted + */ + public Map toQuery() { + Map query = new LinkedHashMap<>(); + if (status != null) { + query.put("status", status); + } + if (stream != null) { + query.put("stream", stream); + } + if (this.query != null) { + query.put("query", this.query); + } + if (page != null) { + query.put("page", String.valueOf(page)); + } + if (perPage != null) { + query.put("per_page", String.valueOf(perPage)); + } + return query; + } + + /** Builder for {@link ListInboundOptions}. */ + public static final class Builder { + + private String status; + private String stream; + private String query; + private Integer page; + private Integer perPage; + + private Builder() {} + + /** + * Restricts to one delivery status, e.g. {@code held}. + * + * @param status the status + * @return this builder + */ + public Builder status(String status) { + this.status = status; + return this; + } + + /** + * Restricts to one message stream. + * + * @param stream the stream permalink + * @return this builder + */ + public Builder stream(String stream) { + this.stream = stream; + return this; + } + + /** + * Substring match on subject and addresses. + * + * @param query the search term + * @return this builder + */ + public Builder query(String query) { + this.query = query; + return this; + } + + /** + * Sets the page number. + * + * @param page 1-based page number + * @return this builder + */ + public Builder page(int page) { + this.page = page; + return this; + } + + /** + * Sets the page size. + * + * @param perPage page size, capped at 100 + * @return this builder + */ + public Builder perPage(int perPage) { + this.perPage = perPage; + return this; + } + + /** + * Builds the options. + * + * @return the immutable options + */ + public ListInboundOptions build() { + return new ListInboundOptions(this); + } + } +} diff --git a/src/main/java/com/camelmailer/inbound/RequeueResult.java b/src/main/java/com/camelmailer/inbound/RequeueResult.java new file mode 100644 index 0000000..2f24adb --- /dev/null +++ b/src/main/java/com/camelmailer/inbound/RequeueResult.java @@ -0,0 +1,8 @@ +package com.camelmailer.inbound; + +/** + * What a retry or bypass did. + * + * @param queued whether the message went back on the delivery queue + */ +public record RequeueResult(boolean queued) {} diff --git a/src/main/java/com/camelmailer/layouts/Layout.java b/src/main/java/com/camelmailer/layouts/Layout.java new file mode 100644 index 0000000..eeae277 --- /dev/null +++ b/src/main/java/com/camelmailer/layouts/Layout.java @@ -0,0 +1,15 @@ +package com.camelmailer.layouts; + +/** + * A template layout: the wrapper shared by every template that uses it, so header, footer and + * styling live in one place. + * + * @param id numeric layout id + * @param uuid stable UUID + * @param name display name + * @param permalink URL-safe identifier used in API paths and by templates + * @param htmlWrapper wrapper for the HTML body; embeds it with {{{ content }}} + * @param textWrapper wrapper for the plain-text body, or {@code null} when the layout has none + */ +public record Layout( + long id, String uuid, String name, String permalink, String htmlWrapper, String textWrapper) {} diff --git a/src/main/java/com/camelmailer/layouts/LayoutRequest.java b/src/main/java/com/camelmailer/layouts/LayoutRequest.java new file mode 100644 index 0000000..bb3104e --- /dev/null +++ b/src/main/java/com/camelmailer/layouts/LayoutRequest.java @@ -0,0 +1,131 @@ +package com.camelmailer.layouts; + +/** + * Fields for creating or updating a template layout. + * + *

{@code htmlWrapper} is required when creating, and has to embed the body with + * {{{ content }}}; anything else is refused with {@code ValidationError}. + */ +public final class LayoutRequest { + + private final String name; + private final String permalink; + private final String htmlWrapper; + private final String textWrapper; + + private LayoutRequest(Builder builder) { + this.name = builder.name; + this.permalink = builder.permalink; + this.htmlWrapper = builder.htmlWrapper; + this.textWrapper = builder.textWrapper; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the display name. + * + * @return the display name, or {@code null} when unset + */ + public String getName() { + return name; + } + + /** + * Returns the URL-safe identifier, derived from the name when unset. + * + * @return the URL-safe identifier, derived from the name when unset, or {@code null} when unset + */ + public String getPermalink() { + return permalink; + } + + /** + * Returns the wrapper for the HTML body. + * + * @return the wrapper for the HTML body, or {@code null} when unset + */ + public String getHtmlWrapper() { + return htmlWrapper; + } + + /** + * Returns the wrapper for the plain-text body. + * + * @return the wrapper for the plain-text body, or {@code null} when unset + */ + public String getTextWrapper() { + return textWrapper; + } + + /** Builder for {@link LayoutRequest}. */ + public static final class Builder { + + private String name; + private String permalink; + private String htmlWrapper; + private String textWrapper; + + private Builder() {} + + /** + * Sets the display name. + * + * @param name the display name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Sets the URL-safe identifier, derived from the name when unset. + * + * @param permalink the URL-safe identifier, derived from the name when unset + * @return this builder + */ + public Builder permalink(String permalink) { + this.permalink = permalink; + return this; + } + + /** + * Sets the wrapper for the HTML body. + * + * @param htmlWrapper the wrapper for the HTML body + * @return this builder + */ + public Builder htmlWrapper(String htmlWrapper) { + this.htmlWrapper = htmlWrapper; + return this; + } + + /** + * Sets the wrapper for the plain-text body. + * + * @param textWrapper the wrapper for the plain-text body + * @return this builder + */ + public Builder textWrapper(String textWrapper) { + this.textWrapper = textWrapper; + return this; + } + + /** + * Builds the request. + * + * @return the immutable request + */ + public LayoutRequest build() { + return new LayoutRequest(this); + } + } +} diff --git a/src/main/java/com/camelmailer/layouts/Layouts.java b/src/main/java/com/camelmailer/layouts/Layouts.java new file mode 100644 index 0000000..68cfc90 --- /dev/null +++ b/src/main/java/com/camelmailer/layouts/Layouts.java @@ -0,0 +1,98 @@ +package com.camelmailer.layouts; + +import com.camelmailer.http.ApiClient; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; + +/** + * Template layouts: {@code /api/v2/server/layouts}. + * + *

A layout wraps every template that uses it, so header, footer and styling live in one place + * instead of in each template. + * + *

Obtain via {@link com.camelmailer.CamelMailer#layouts()}. + */ +public final class Layouts { + + private static final String BASE = "/api/v2/server/layouts"; + + private final ApiClient client; + + /** + * Creates the service. + * + * @param client the internal API client + */ + public Layouts(ApiClient client) { + this.client = client; + } + + /** + * Lists all layouts of the server. + * + * @return the layouts + */ + public List list() { + return client.convertList(client.get(BASE).path("layouts"), Layout.class); + } + + /** + * Creates a layout. + * + *

{@code htmlWrapper} has to embed the body with {{{ content }}}; anything else + * is refused with {@code ValidationError}. + * + * @param request the layout fields + * @return the created layout + */ + public Layout create(LayoutRequest request) { + return client.convert(client.post(BASE, request).path("layout"), Layout.class); + } + + /** + * Fetches a layout by permalink. + * + * @param permalink the layout permalink + * @return the layout + */ + public Layout get(String permalink) { + return client.convert(client.get(BASE + "/" + permalink).path("layout"), Layout.class); + } + + /** + * Updates a layout; only the given fields change. + * + * @param permalink the layout permalink + * @param request the fields to change + * @return the updated layout + */ + public Layout update(String permalink, LayoutRequest request) { + return client.convert( + client.patch(BASE + "/" + permalink, request).path("layout"), Layout.class); + } + + /** + * Deletes a layout. Templates that referenced it fall back to no wrapper. + * + * @param permalink the layout permalink + * @return whether the layout was removed + */ + public boolean delete(String permalink) { + return client.delete(BASE + "/" + permalink).path("deleted").asBoolean(); + } + + /** + * Uploads the layout's logo, given as a {@code data:image/png;base64,...} URL. + * + * @param permalink the layout permalink + * @param dataUrl the logo as a data URL + * @return the absolute URL to reference from the wrapper; it is served without authentication, + * because mail clients fetch it without a session + */ + public String uploadLogo(String permalink, String dataUrl) { + ObjectNode body = client.newObject(); + body.put("data_url", dataUrl); + // The endpoint answers with "url", not "logo_url". + return client.post(BASE + "/" + permalink + "/logo", body).path("url").asText(); + } +} diff --git a/src/main/java/com/camelmailer/logs/ApiRequestLog.java b/src/main/java/com/camelmailer/logs/ApiRequestLog.java new file mode 100644 index 0000000..1e958e3 --- /dev/null +++ b/src/main/java/com/camelmailer/logs/ApiRequestLog.java @@ -0,0 +1,21 @@ +package com.camelmailer.logs; + +/** + * One logged API request. + * + * @param id numeric log id + * @param method the HTTP method + * @param path the request path + * @param statusCode the status the API answered with + * @param durationMs how long the request took, in milliseconds + * @param userAgent the client's User-Agent header + * @param createdAt when the request arrived + */ +public record ApiRequestLog( + long id, + String method, + String path, + int statusCode, + long durationMs, + String userAgent, + String createdAt) {} diff --git a/src/main/java/com/camelmailer/logs/LogList.java b/src/main/java/com/camelmailer/logs/LogList.java new file mode 100644 index 0000000..f7a3e2f --- /dev/null +++ b/src/main/java/com/camelmailer/logs/LogList.java @@ -0,0 +1,12 @@ +package com.camelmailer.logs; + +import com.camelmailer.common.Pagination; +import java.util.List; + +/** + * One page of logged requests. + * + * @param requests the page of logged requests + * @param pagination the page window + */ +public record LogList(List requests, Pagination pagination) {} diff --git a/src/main/java/com/camelmailer/logs/Logs.java b/src/main/java/com/camelmailer/logs/Logs.java new file mode 100644 index 0000000..4b37a47 --- /dev/null +++ b/src/main/java/com/camelmailer/logs/Logs.java @@ -0,0 +1,65 @@ +package com.camelmailer.logs; + +import com.camelmailer.http.ApiClient; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The server's own request log and tag index: {@code /api/v2/server/logs} and {@code + * /api/v2/server/tags}. + * + *

Useful when a send did not arrive and the question is whether the request ever reached the + * API, and with what answer. + * + *

Obtain via {@link com.camelmailer.CamelMailer#logs()}. + */ +public final class Logs { + + private final ApiClient client; + + /** + * Creates the service. + * + * @param client the internal API client + */ + public Logs(ApiClient client) { + this.client = client; + } + + /** + * Lists logged API requests, newest first. + * + * @return the first page + */ + public LogList list() { + return list(null, null); + } + + /** + * Lists logged API requests with paging. + * + * @param page 1-based page number, or {@code null} for the first + * @param perPage page size (capped at 100), or {@code null} for the default + * @return the matching page + */ + public LogList list(Integer page, Integer perPage) { + Map query = new LinkedHashMap<>(); + if (page != null) { + query.put("page", String.valueOf(page)); + } + if (perPage != null) { + query.put("per_page", String.valueOf(perPage)); + } + return client.convert(client.get("/api/v2/server/logs", query), LogList.class); + } + + /** + * Lists the tags used by the server's recent messages, most used first. + * + * @return the tags with their counts + */ + public List tags() { + return client.convertList(client.get("/api/v2/server/tags").path("tags"), TagCount.class); + } +} diff --git a/src/main/java/com/camelmailer/logs/TagCount.java b/src/main/java/com/camelmailer/logs/TagCount.java new file mode 100644 index 0000000..010598e --- /dev/null +++ b/src/main/java/com/camelmailer/logs/TagCount.java @@ -0,0 +1,9 @@ +package com.camelmailer.logs; + +/** + * One tag with how often the server's recent messages used it. + * + * @param tag the tag itself + * @param count how many messages carry it + */ +public record TagCount(String tag, long count) {} diff --git a/src/main/java/com/camelmailer/streams/StreamRequest.java b/src/main/java/com/camelmailer/streams/StreamRequest.java index 649a707..ddce487 100644 --- a/src/main/java/com/camelmailer/streams/StreamRequest.java +++ b/src/main/java/com/camelmailer/streams/StreamRequest.java @@ -11,10 +11,14 @@ public final class StreamRequest { private final String name; private final String streamType; + private final String permalink; + private final Boolean archived; private StreamRequest(Builder builder) { this.name = builder.name; this.streamType = builder.streamType; + this.permalink = builder.permalink; + this.archived = builder.archived; } /** @@ -44,11 +48,31 @@ public String getStreamType() { return streamType; } + /** + * Returns the permalink. + * + * @return the permalink, or {@code null} when unset; the API derives one from the name then + */ + public String getPermalink() { + return permalink; + } + + /** + * Returns the archived flag. + * + * @return {@code true}, {@code false}, or {@code null} when unset (update only) + */ + public Boolean getArchived() { + return archived; + } + /** Builder for {@link StreamRequest}. */ public static final class Builder { private String name; private String streamType; + private String permalink; + private Boolean archived; private Builder() {} @@ -74,6 +98,28 @@ public Builder streamType(String streamType) { return this; } + /** + * Sets the permalink used in API paths and send requests. + * + * @param permalink URL-safe identifier; the API derives one from the name when omitted + * @return this builder + */ + public Builder permalink(String permalink) { + this.permalink = permalink; + return this; + } + + /** + * Archives or unarchives the stream (update only). Archived streams reject new messages. + * + * @param archived whether the stream is archived + * @return this builder + */ + public Builder archived(boolean archived) { + this.archived = archived; + return this; + } + /** * Builds the request. * diff --git a/src/main/java/com/camelmailer/subscribers/ImportResult.java b/src/main/java/com/camelmailer/subscribers/ImportResult.java new file mode 100644 index 0000000..98a5d39 --- /dev/null +++ b/src/main/java/com/camelmailer/subscribers/ImportResult.java @@ -0,0 +1,12 @@ +package com.camelmailer.subscribers; + +/** + * What an import wrote. + * + *

Blanks and duplicates within the request are skipped, so {@code added} can be lower than the + * number of addresses passed. + * + * @param added subscriptions written + * @param total the stream's subscriber count after the import + */ +public record ImportResult(long added, long total) {} diff --git a/src/main/java/com/camelmailer/subscribers/Subscriber.java b/src/main/java/com/camelmailer/subscribers/Subscriber.java new file mode 100644 index 0000000..cd7bab0 --- /dev/null +++ b/src/main/java/com/camelmailer/subscribers/Subscriber.java @@ -0,0 +1,12 @@ +package com.camelmailer.subscribers; + +/** + * One address on a broadcast stream. + * + * @param id numeric subscriber id + * @param address the email address + * @param name optional display name + * @param status {@code subscribed} or {@code unsubscribed} + * @param createdAt when the subscription row was created + */ +public record Subscriber(long id, String address, String name, String status, String createdAt) {} diff --git a/src/main/java/com/camelmailer/subscribers/SubscriberRequest.java b/src/main/java/com/camelmailer/subscribers/SubscriberRequest.java new file mode 100644 index 0000000..d1175f6 --- /dev/null +++ b/src/main/java/com/camelmailer/subscribers/SubscriberRequest.java @@ -0,0 +1,107 @@ +package com.camelmailer.subscribers; + +/** + * Fields for {@link Subscribers#add}. + * + *

Upserts by address, so calling it twice is safe. + */ +public final class SubscriberRequest { + + private final String address; + private final String name; + private final String status; + + private SubscriberRequest(Builder builder) { + this.address = builder.address; + this.name = builder.name; + this.status = builder.status; + } + + /** + * Creates a new builder. + * + * @return a fresh builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the email address. + * + * @return the email address, or {@code null} when unset + */ + public String getAddress() { + return address; + } + + /** + * Returns the display name. + * + * @return the display name, or {@code null} when unset + */ + public String getName() { + return name; + } + + /** + * Returns {@code subscribed} (default) or {@code unsubscribed}. + * + * @return {@code subscribed} (default) or {@code unsubscribed}, or {@code null} when unset + */ + public String getStatus() { + return status; + } + + /** Builder for {@link SubscriberRequest}. */ + public static final class Builder { + + private String address; + private String name; + private String status; + + private Builder() {} + + /** + * Sets the email address (required). + * + * @param address the email address + * @return this builder + */ + public Builder address(String address) { + this.address = address; + return this; + } + + /** + * Sets the display name. + * + * @param name the display name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Sets {@code subscribed} (default) or {@code unsubscribed}. + * + * @param status {@code subscribed} (default) or {@code unsubscribed} + * @return this builder + */ + public Builder status(String status) { + this.status = status; + return this; + } + + /** + * Builds the request. + * + * @return the immutable request + */ + public SubscriberRequest build() { + return new SubscriberRequest(this); + } + } +} diff --git a/src/main/java/com/camelmailer/subscribers/Subscribers.java b/src/main/java/com/camelmailer/subscribers/Subscribers.java new file mode 100644 index 0000000..a38773d --- /dev/null +++ b/src/main/java/com/camelmailer/subscribers/Subscribers.java @@ -0,0 +1,107 @@ +package com.camelmailer.subscribers; + +import com.camelmailer.http.ApiClient; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * Opt-in subscribers of a broadcast stream: {@code /api/v2/server/streams/{permalink}/subscribers}. + * + *

A broadcast send to an address that is not subscribed is refused, so this list is the + * audience. + * + *

Obtain via {@link com.camelmailer.CamelMailer#subscribers()}. + */ +public final class Subscribers { + + private final ApiClient client; + + /** + * Creates the service. + * + * @param client the internal API client + */ + public Subscribers(ApiClient client) { + this.client = client; + } + + /** + * Lists the stream's subscribers, subscribed and unsubscribed alike. + * + * @param permalink the stream permalink + * @return the subscribers + */ + public List list(String permalink) { + return client.convertList(client.get(base(permalink)).path("subscribers"), Subscriber.class); + } + + /** + * Adds or updates one subscriber. Upserts by address, so calling it twice is safe. + * + * @param permalink the stream permalink + * @param request the subscriber fields + * @return the stored subscriber + */ + public Subscriber add(String permalink, SubscriberRequest request) { + return client.convert( + client.post(base(permalink), request).path("subscriber"), Subscriber.class); + } + + /** + * Adds many addresses at once, all as subscribed. + * + * @param permalink the stream permalink + * @param addresses the addresses to subscribe + * @return how many were written, and the resulting total + */ + public ImportResult importAddresses(String permalink, List addresses) { + ObjectNode body = client.newObject(); + addresses.forEach(body.putArray("addresses")::add); + return client.convert(client.post(base(permalink) + "/import", body), ImportResult.class); + } + + /** + * Records a spam complaint against an address. + * + *

Writes a stream-scoped suppression and flips the subscription to {@code unsubscribed}. + * Idempotent, so a feedback loop can replay it safely. + * + * @param permalink the stream permalink + * @param address the complaining address + * @return the updated subscriber + */ + public Subscriber complaint(String permalink, String address) { + return client.convert( + client + .post(base(permalink) + "/" + encode(address) + "/complaint", null) + .path("subscriber"), + Subscriber.class); + } + + /** + * Removes a subscriber from the stream entirely. + * + * @param permalink the stream permalink + * @param address the address to remove + * @return whether the row was removed + */ + public boolean remove(String permalink, String address) { + return client.delete(base(permalink) + "/" + encode(address)).path("deleted").asBoolean(); + } + + private static String base(String permalink) { + return "/api/v2/server/streams/" + permalink + "/subscribers"; + } + + /** + * Percent-encodes an address for a path segment. + * + *

{@link URLEncoder} is form encoding, which turns a space into {@code +} and leaves a literal + * {@code +} alone; in a path a bare plus is ambiguous, so it is escaped explicitly. + */ + private static String encode(String address) { + return URLEncoder.encode(address, StandardCharsets.UTF_8).replace("+", "%2B"); + } +} diff --git a/src/test/java/com/camelmailer/CampaignsTest.java b/src/test/java/com/camelmailer/CampaignsTest.java new file mode 100644 index 0000000..21bff71 --- /dev/null +++ b/src/test/java/com/camelmailer/CampaignsTest.java @@ -0,0 +1,221 @@ +package com.camelmailer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.camelmailer.campaigns.Campaign; +import com.camelmailer.campaigns.CampaignDetail; +import com.camelmailer.campaigns.DraftCampaignRequest; +import com.camelmailer.campaigns.SendCampaignRequest; +import com.camelmailer.campaigns.UpdateCampaignRequest; +import java.util.List; +import org.junit.jupiter.api.Test; + +class CampaignsTest { + + private static final String CAMPAIGN = + "{\"id\":7,\"name\":\"September\",\"subject\":\"What shipped\",\"from\":\"news@acme.com\"," + + "\"status\":\"draft\",\"total\":120,\"sent\":0,\"stream_id\":3," + + "\"stream\":{\"permalink\":\"product-news\",\"name\":\"Product news\"}," + + "\"scheduled_at\":null,\"created_at\":\"2026-09-01T10:00:00Z\",\"completed_at\":null}"; + + @Test + void listParsesCampaignsWithTheirStream() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaigns\":[" + CAMPAIGN + "]}"); + List campaigns = server.client().campaigns().list(); + + assertEquals("/api/v2/server/campaigns", server.takeRequest().path()); + assertEquals(1, campaigns.size()); + assertEquals("product-news", campaigns.get(0).stream().permalink()); + assertEquals("draft", campaigns.get(0).status()); + } + } + + @Test + void listForStreamUsesTheStreamPath() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaigns\":[]}"); + server.client().campaigns().listForStream("product-news"); + assertEquals("/api/v2/server/streams/product-news/campaigns", server.takeRequest().path()); + } + } + + @Test + void getCarriesTheStats() { + try (MockServer server = new MockServer()) { + server.enqueueData( + "{\"campaign\":" + + CAMPAIGN + + ",\"stats\":{\"total\":120,\"sent\":118,\"delivered\":110,\"failed\":8," + + "\"opened\":40,\"clicked\":9,\"unsubscribed\":1}}"); + CampaignDetail detail = server.client().campaigns().get(7); + + assertEquals("/api/v2/server/campaigns/7", server.takeRequest().path()); + assertEquals(110L, detail.stats().delivered()); + assertEquals(7L, detail.campaign().id()); + } + } + + @Test + void getForStreamUsesTheStreamPath() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaign\":" + CAMPAIGN + "}"); + server.client().campaigns().getForStream("product-news", 7); + assertEquals("/api/v2/server/streams/product-news/campaigns/7", server.takeRequest().path()); + } + } + + @Test + void createDraftNamesTheStreamInTheBody() { + try (MockServer server = new MockServer()) { + server.enqueue( + 201, "{\"status\":\"success\",\"time\":0.001,\"data\":{\"campaign\":" + CAMPAIGN + "}}"); + Campaign campaign = + server + .client() + .campaigns() + .createDraft( + DraftCampaignRequest.builder().stream("product-news") + .from("news@acme.com") + .name("September") + .build()); + + MockServer.Recorded recorded = server.takeRequest(); + // The planning route: the stream travels in the body, not the path. + assertEquals("/api/v2/server/campaigns", recorded.path()); + assertTrue(recorded.body().contains("\"stream\":\"product-news\"")); + assertFalse(recorded.body().contains("scheduled_at")); + assertEquals("draft", campaign.status()); + } + } + + @Test + void createDraftArmsASchedule() { + try (MockServer server = new MockServer()) { + server.enqueue( + 201, + "{\"status\":\"success\",\"time\":0.001,\"data\":{\"campaign\":" + + "{\"id\":8,\"status\":\"scheduled\"}}}"); + Campaign campaign = + server + .client() + .campaigns() + .createDraft( + DraftCampaignRequest.builder().stream("product-news") + .from("news@acme.com") + .scheduledAt("2026-10-01T08:00:00Z") + .build()); + + assertTrue(server.takeRequest().body().contains("\"scheduled_at\":\"2026-10-01T08:00:00Z\"")); + assertEquals("scheduled", campaign.status()); + } + } + + @Test + void createAndSendGoesOutImmediately() { + try (MockServer server = new MockServer()) { + server.enqueue( + 201, + "{\"status\":\"success\",\"time\":0.001,\"data\":{\"campaign\":" + + "{\"id\":9,\"status\":\"sending\"}}}"); + Campaign campaign = + server + .client() + .campaigns() + .createAndSend( + "product-news", + SendCampaignRequest.builder() + .name("Status update") + .from("news@acme.com") + .build()); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("/api/v2/server/streams/product-news/campaigns", recorded.path()); + // The stream-scoped route expands to the subscribers before it answers. + assertEquals("sending", campaign.status()); + } + } + + @Test + void updateSchedulesWithATime() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaign\":{\"id\":7,\"status\":\"scheduled\"}}"); + server + .client() + .campaigns() + .update(7, UpdateCampaignRequest.builder().scheduledAt("2026-10-01T08:00:00Z").build()); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("PATCH", recorded.method()); + assertTrue(recorded.body().contains("\"scheduled_at\":\"2026-10-01T08:00:00Z\"")); + } + } + + @Test + void clearScheduleSendsAnExplicitNull() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaign\":{\"id\":7,\"status\":\"draft\"}}"); + Campaign campaign = + server + .client() + .campaigns() + .update(7, UpdateCampaignRequest.builder().clearSchedule().build()); + + // An omitted field leaves the schedule standing; only an explicit + // null drops the campaign back to a draft. + assertTrue(server.takeRequest().body().contains("\"scheduled_at\":null")); + assertEquals("draft", campaign.status()); + } + } + + @Test + void anUntouchedScheduleIsOmitted() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaign\":" + CAMPAIGN + "}"); + server + .client() + .campaigns() + .update(7, UpdateCampaignRequest.builder().subject("Corrected").build()); + + String body = server.takeRequest().body(); + assertTrue(body.contains("\"subject\":\"Corrected\"")); + assertFalse(body.contains("scheduled_at")); + } + } + + @Test + void sendAndCancel() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"campaign\":{\"id\":7,\"status\":\"sending\"}}"); + server.enqueueData("{\"campaign\":{\"id\":7,\"status\":\"canceled\"}}"); + + assertEquals("sending", server.client().campaigns().send(7).status()); + assertEquals("/api/v2/server/campaigns/7/send", server.takeRequest().path()); + assertEquals("canceled", server.client().campaigns().cancel(7).status()); + assertEquals("/api/v2/server/campaigns/7/cancel", server.takeRequest().path()); + } + } + + @Test + void editingASendingCampaignIsRefused() { + try (MockServer server = new MockServer()) { + server.enqueue( + 422, + "{\"status\":\"error\",\"time\":0.001,\"error\":{\"code\":\"ValidationError\"," + + "\"message\":\"a sent campaign can no longer be edited\"}}"); + + CamelMailerException error = + assertThrows( + CamelMailerException.class, + () -> + server + .client() + .campaigns() + .update(7, UpdateCampaignRequest.builder().subject("Too late").build())); + assertEquals("ValidationError", error.getCode()); + } + } +} diff --git a/src/test/java/com/camelmailer/IdempotencyTest.java b/src/test/java/com/camelmailer/IdempotencyTest.java new file mode 100644 index 0000000..18ec5a7 --- /dev/null +++ b/src/test/java/com/camelmailer/IdempotencyTest.java @@ -0,0 +1,131 @@ +package com.camelmailer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.camelmailer.emails.SendEmailRequest; +import com.camelmailer.emails.StreamSendResult; +import java.util.List; +import org.junit.jupiter.api.Test; + +class IdempotencyTest { + + private static SendEmailRequest receipt() { + return SendEmailRequest.builder() + .from("billing@acme.com") + .to("ada@example.com") + .subject("Your receipt") + .textBody("Thanks.") + .build(); + } + + @Test + void theKeyTravelsAsAHeaderNotInTheBody() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"message_id\":1,\"recipients\":[]}"); + server.client().emails().send(receipt(), "order-4711"); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("order-4711", recorded.headers().getFirst("Idempotency-Key")); + // The body is what the server hashes for the claim, so the key must + // not end up inside it. + assertFalse(recorded.body().contains("idempotency")); + assertFalse(recorded.body().contains("Idempotency")); + } + } + + @Test + void noHeaderWithoutAKey() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"message_id\":1}"); + server.client().emails().send(receipt()); + assertNull(server.takeRequest().headers().getFirst("Idempotency-Key")); + } + } + + @Test + void everySendEndpointCarriesTheKey() { + // The API claims all four, so all four have to send it. + try (MockServer server = new MockServer()) { + server.enqueueData("{\"message_id\":1}"); + server.client().emails().send(receipt(), "k"); + assertEquals("k", server.takeRequest().headers().getFirst("Idempotency-Key")); + + server.enqueueData("{\"messages\":[]}"); + server.client().emails().sendBatch(List.of(receipt()), "k"); + MockServer.Recorded batch = server.takeRequest(); + assertEquals("/api/v2/server/messages/batch", batch.path()); + assertEquals("k", batch.headers().getFirst("Idempotency-Key")); + + server.enqueueData("{\"message_id\":1}"); + server.client().emails().sendWithTemplate(receipt(), "k"); + MockServer.Recorded template = server.takeRequest(); + assertEquals("/api/v2/server/messages/with_template", template.path()); + assertEquals("k", template.headers().getFirst("Idempotency-Key")); + + server.enqueueData("{\"messages\":[]}"); + server.client().emails().sendWithTemplateBatch(List.of(receipt()), "k"); + MockServer.Recorded templateBatch = server.takeRequest(); + assertEquals("/api/v2/server/messages/with_template/batch", templateBatch.path()); + assertEquals("k", templateBatch.headers().getFirst("Idempotency-Key")); + } + } + + @Test + void aReusedKeyForAnotherBodyIsRefused() { + try (MockServer server = new MockServer()) { + server.enqueue( + 409, + "{\"status\":\"error\",\"time\":0.001,\"error\":{\"code\":\"InvalidIdempotentRequest\"," + + "\"message\":\"The same idempotency key was used with a different request\"}}"); + + CamelMailerException error = + assertThrows( + CamelMailerException.class, () -> server.client().emails().send(receipt(), "reused")); + assertEquals("InvalidIdempotentRequest", error.getCode()); + assertEquals(409, error.getStatusCode()); + } + } + + @Test + void theSendAllowanceSurfacesAsSendLimitExceeded() { + try (MockServer server = new MockServer()) { + server.enqueue( + 429, + "{\"status\":\"error\",\"time\":0.001,\"error\":{\"code\":\"SendLimitExceeded\"," + + "\"message\":\"the send allowance is used up\"}}"); + + CamelMailerException error = + assertThrows(CamelMailerException.class, () -> server.client().emails().send(receipt())); + assertEquals("SendLimitExceeded", error.getCode()); + assertEquals(429, error.getStatusCode()); + } + } + + @Test + void sendToStreamCountsQueuedAgainstSkipped() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"queued\":42,\"skipped\":3}"); + StreamSendResult result = + server + .client() + .emails() + .sendToStream( + "newsletter", + SendEmailRequest.builder() + .from("news@acme.com") + .subject("September") + .textBody("Hello.") + .build()); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("/api/v2/server/streams/newsletter/send", recorded.path()); + assertTrue(recorded.body().contains("\"from\"")); + assertEquals(42L, result.queued()); + assertEquals(3L, result.skipped()); + } + } +} diff --git a/src/test/java/com/camelmailer/InboundLogsTest.java b/src/test/java/com/camelmailer/InboundLogsTest.java new file mode 100644 index 0000000..d4de5e7 --- /dev/null +++ b/src/test/java/com/camelmailer/InboundLogsTest.java @@ -0,0 +1,73 @@ +package com.camelmailer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.camelmailer.inbound.InboundList; +import com.camelmailer.inbound.ListInboundOptions; +import com.camelmailer.logs.LogList; +import com.camelmailer.logs.TagCount; +import java.util.List; +import org.junit.jupiter.api.Test; + +class InboundLogsTest { + + @Test + void inboundListReadsTheInboundKey() { + try (MockServer server = new MockServer()) { + // The page comes back under "inbound", not "messages". + server.enqueueData( + "{\"inbound\":[{\"id\":55,\"status\":\"Held\",\"held\":true}]," + + "\"pagination\":{\"page\":1,\"per_page\":50,\"total\":1,\"total_pages\":1}}"); + InboundList page = + server + .client() + .inbound() + .list(ListInboundOptions.builder().status("held").perPage(50).build()); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("/api/v2/server/inbound", recorded.path()); + assertTrue(recorded.query().contains("status=held"), "query was " + recorded.query()); + assertTrue(recorded.query().contains("per_page=50"), "query was " + recorded.query()); + assertEquals(1, page.inbound().size()); + assertEquals(1L, page.pagination().total()); + } + } + + @Test + void inboundRetryAndBypass() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"queued\":true}"); + assertTrue(server.client().inbound().retry(55).queued()); + assertEquals("/api/v2/server/inbound/55/retry", server.takeRequest().path()); + + server.enqueueData("{\"queued\":true}"); + assertTrue(server.client().inbound().bypass(55).queued()); + assertEquals("/api/v2/server/inbound/55/bypass", server.takeRequest().path()); + } + } + + @Test + void logsListAndTags() { + try (MockServer server = new MockServer()) { + server.enqueueData( + "{\"requests\":[{\"id\":1,\"method\":\"POST\",\"path\":\"/api/v2/server/messages\"," + + "\"status_code\":201,\"duration_ms\":12,\"user_agent\":\"camelmailer-java\"," + + "\"created_at\":\"2026-09-14T08:00:00Z\"}]," + + "\"pagination\":{\"page\":1,\"per_page\":25,\"total\":1,\"total_pages\":1}}"); + LogList page = server.client().logs().list(null, 25); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("/api/v2/server/logs", recorded.path()); + assertTrue(recorded.query().contains("per_page=25")); + assertEquals(201, page.requests().get(0).statusCode()); + assertEquals(12L, page.requests().get(0).durationMs()); + + server.enqueueData("{\"tags\":[{\"tag\":\"receipt\",\"count\":12}]}"); + List tags = server.client().logs().tags(); + assertEquals("/api/v2/server/tags", server.takeRequest().path()); + assertEquals("receipt", tags.get(0).tag()); + assertEquals(12L, tags.get(0).count()); + } + } +} diff --git a/src/test/java/com/camelmailer/IntegrationTest.java b/src/test/java/com/camelmailer/IntegrationTest.java index bb5d0a1..174a454 100644 --- a/src/test/java/com/camelmailer/IntegrationTest.java +++ b/src/test/java/com/camelmailer/IntegrationTest.java @@ -3,11 +3,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import com.camelmailer.campaigns.Campaign; +import com.camelmailer.campaigns.DraftCampaignRequest; +import com.camelmailer.campaigns.SendCampaignRequest; +import com.camelmailer.campaigns.UpdateCampaignRequest; import com.camelmailer.emails.EmailDetails; import com.camelmailer.emails.SendEmailRequest; import com.camelmailer.emails.SendResult; +import com.camelmailer.emails.StreamSendResult; +import com.camelmailer.layouts.Layout; +import com.camelmailer.layouts.LayoutRequest; import com.camelmailer.stats.MessageStats; +import com.camelmailer.streams.StreamRequest; +import com.camelmailer.subscribers.ImportResult; +import com.camelmailer.subscribers.SubscriberRequest; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; @@ -48,6 +62,167 @@ void statsAndListsAreReachable() { assertNotNull(client.templates().list()); assertNotNull(client.bounces().list()); assertNotNull(client.dmarc().summary()); + assertNotNull(client.campaigns().list()); + assertNotNull(client.layouts().list()); + assertNotNull(client.inbound().list()); + assertNotNull(client.logs().list()); + assertNotNull(client.logs().tags()); + } + + @Test + @EnabledIfEnvironmentVariable(named = "CAMELMAILER_FROM", matches = ".+") + void broadcastRoundTrip() { + CamelMailer client = client(); + String stamp = String.valueOf(System.currentTimeMillis()); + String permalink = "java-live-" + stamp; + String from = System.getenv("CAMELMAILER_FROM"); + + String stream = + client + .streams() + .create( + StreamRequest.builder() + .name("Java live " + stamp) + .permalink(permalink) + .streamType("broadcast") + .build()) + .permalink(); + + client + .subscribers() + .add(stream, SubscriberRequest.builder().address("ada@example.test").build()); + ImportResult imported = + client.subscribers().importAddresses(stream, List.of("grace@example.test")); + assertEquals(1L, imported.added()); + + // The two create routes behave differently, which is the whole reason + // they are separate methods. + Campaign draft = + client + .campaigns() + .createDraft( + DraftCampaignRequest.builder().stream(stream) + .from(from) + .name("Java draft " + stamp) + .subject("D") + .textBody("d") + .build()); + assertEquals("draft", draft.status()); + + Campaign scheduled = + client + .campaigns() + .createDraft( + DraftCampaignRequest.builder().stream(stream) + .from(from) + .name("Java scheduled " + stamp) + .scheduledAt("2027-01-01T09:00:00Z") + .build()); + assertEquals("scheduled", scheduled.status()); + + Campaign sending = + client + .campaigns() + .createAndSend( + stream, + SendCampaignRequest.builder() + .name("Java now " + stamp) + .from(from) + .subject("N") + .textBody("n") + .build()); + assertEquals("sending", sending.status()); + + assertEquals( + "scheduled", + client + .campaigns() + .update( + draft.id(), + UpdateCampaignRequest.builder().scheduledAt("2027-01-01T09:00:00Z").build()) + .status()); + assertEquals( + "draft", + client + .campaigns() + .update(draft.id(), UpdateCampaignRequest.builder().clearSchedule().build()) + .status()); + assertEquals("canceled", client.campaigns().cancel(draft.id()).status()); + + StreamSendResult broadcast = + client + .emails() + .sendToStream( + stream, + SendEmailRequest.builder() + .from(from) + .subject("Broadcast " + stamp) + .textBody("hello") + .build()); + assertEquals(0L, broadcast.skipped()); + + client.subscribers().remove(stream, "grace@example.test"); + client.streams().archive(stream); + } + + @Test + @EnabledIfEnvironmentVariable(named = "CAMELMAILER_FROM", matches = ".+") + @EnabledIfEnvironmentVariable(named = "CAMELMAILER_TO", matches = ".+") + void anIdempotentSendReplaysInsteadOfSendingTwice() { + CamelMailer client = client(); + String key = "java-live-" + System.currentTimeMillis(); + SendEmailRequest request = + SendEmailRequest.builder() + .from(System.getenv("CAMELMAILER_FROM")) + .to(System.getenv("CAMELMAILER_TO")) + .subject("camelmailer-java idempotency") + .textBody("once") + .build(); + + long first = client.emails().send(request, key).messageId(); + assertEquals(first, client.emails().send(request, key).messageId()); + + SendEmailRequest other = + SendEmailRequest.builder() + .from(System.getenv("CAMELMAILER_FROM")) + .to(System.getenv("CAMELMAILER_TO")) + .subject("camelmailer-java idempotency (different)") + .textBody("twice") + .build(); + CamelMailerException error = + assertThrows(CamelMailerException.class, () -> client.emails().send(other, key)); + assertEquals("InvalidIdempotentRequest", error.getCode()); + } + + @Test + void layoutRoundTrip() { + CamelMailer client = client(); + String permalink = "java-layout-" + System.currentTimeMillis(); + + Layout created = + client + .layouts() + .create( + LayoutRequest.builder() + .name(permalink) + .permalink(permalink) + .htmlWrapper("{{{ content }}}") + .build()); + assertEquals(permalink, created.permalink()); + // A layout created with only an HTML wrapper has no text one. + assertNull(created.textWrapper()); + + String logo = + client + .layouts() + .uploadLogo( + permalink, + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ" + + "AAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="); + // The endpoint answers with "url"; reading "logo_url" would yield "". + assertFalse(logo.isEmpty()); + + assertTrue(client.layouts().delete(permalink)); } @Test diff --git a/src/test/java/com/camelmailer/MockServer.java b/src/test/java/com/camelmailer/MockServer.java index 9a5f29d..d57160e 100644 --- a/src/test/java/com/camelmailer/MockServer.java +++ b/src/test/java/com/camelmailer/MockServer.java @@ -13,7 +13,8 @@ final class MockServer implements AutoCloseable { /** A recorded incoming request. */ - record Recorded(String method, String path, String query, Headers headers, String body) {} + record Recorded( + String method, String path, String rawPath, String query, Headers headers, String body) {} private record Stubbed(int status, String body) {} @@ -36,6 +37,9 @@ private record Stubbed(int status, String body) {} new Recorded( exchange.getRequestMethod(), exchange.getRequestURI().getPath(), + // The raw path keeps the percent-encoding, which is the + // only place an escaped address can be checked. + exchange.getRequestURI().getRawPath(), exchange.getRequestURI().getRawQuery(), exchange.getRequestHeaders(), body)); diff --git a/src/test/java/com/camelmailer/StreamsTest.java b/src/test/java/com/camelmailer/StreamsTest.java index 2a29bcc..3906711 100644 --- a/src/test/java/com/camelmailer/StreamsTest.java +++ b/src/test/java/com/camelmailer/StreamsTest.java @@ -39,13 +39,21 @@ void createPostsNameAndStreamType() { server .client() .streams() - .create(StreamRequest.builder().name("Receipts").streamType("transactional").build()); + .create( + StreamRequest.builder() + .name("Receipts") + .streamType("transactional") + .permalink("receipts") + .build()); MockServer.Recorded recorded = server.takeRequest(); assertEquals("POST", recorded.method()); assertEquals("/api/v2/server/streams", recorded.path()); assertTrue(recorded.body().contains("\"name\":\"Receipts\"")); assertTrue(recorded.body().contains("\"stream_type\":\"transactional\"")); + // Without this the API derives a permalink from the name, which a + // caller that has to know the permalink up front cannot rely on. + assertTrue(recorded.body().contains("\"permalink\":\"receipts\"")); assertEquals(2L, stream.id()); } } diff --git a/src/test/java/com/camelmailer/SubscribersLayoutsTest.java b/src/test/java/com/camelmailer/SubscribersLayoutsTest.java new file mode 100644 index 0000000..c62129e --- /dev/null +++ b/src/test/java/com/camelmailer/SubscribersLayoutsTest.java @@ -0,0 +1,178 @@ +package com.camelmailer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.camelmailer.layouts.Layout; +import com.camelmailer.layouts.LayoutRequest; +import com.camelmailer.subscribers.ImportResult; +import com.camelmailer.subscribers.Subscriber; +import com.camelmailer.subscribers.SubscriberRequest; +import java.util.List; +import org.junit.jupiter.api.Test; + +class SubscribersLayoutsTest { + + @Test + void subscribersListParses() { + try (MockServer server = new MockServer()) { + server.enqueueData( + "{\"subscribers\":[{\"id\":1,\"address\":\"ada@example.com\"," + + "\"status\":\"subscribed\",\"created_at\":\"2026-09-01T10:00:00Z\"}]}"); + List subscribers = server.client().subscribers().list("product-news"); + + assertEquals("/api/v2/server/streams/product-news/subscribers", server.takeRequest().path()); + assertEquals("subscribed", subscribers.get(0).status()); + } + } + + @Test + void subscribersAddUpsertsByAddress() { + try (MockServer server = new MockServer()) { + server.enqueue( + 201, + "{\"status\":\"success\",\"time\":0.001,\"data\":{\"subscriber\":" + + "{\"id\":1,\"address\":\"ada@example.com\",\"status\":\"subscribed\"}}}"); + Subscriber subscriber = + server + .client() + .subscribers() + .add( + "product-news", + SubscriberRequest.builder().address("ada@example.com").name("Ada").build()); + + assertTrue(server.takeRequest().body().contains("\"address\":\"ada@example.com\"")); + assertEquals("ada@example.com", subscriber.address()); + } + } + + @Test + void subscribersImportSendsAnAddressesArray() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"added\":2,\"total\":2}"); + ImportResult result = + server + .client() + .subscribers() + .importAddresses("product-news", List.of("ada@example.com", "grace@example.com")); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("/api/v2/server/streams/product-news/subscribers/import", recorded.path()); + assertTrue(recorded.body().contains("\"addresses\":[\"ada@example.com\"")); + assertEquals(2L, result.added()); + } + } + + @Test + void subscribersRemoveEscapesTheAddress() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"deleted\":true}"); + boolean removed = + server.client().subscribers().remove("product-news", "ada+news@example.com"); + + MockServer.Recorded recorded = server.takeRequest(); + assertEquals("DELETE", recorded.method()); + // The plus has to survive the path, or a different address is removed. + assertTrue( + recorded.rawPath().endsWith("/subscribers/ada%2Bnews%40example.com"), + "raw path was " + recorded.rawPath()); + assertTrue(removed); + } + } + + @Test + void subscribersComplaintUnsubscribes() { + try (MockServer server = new MockServer()) { + server.enqueueData( + "{\"subscriber\":{\"id\":1,\"address\":\"ada@example.com\",\"status\":\"unsubscribed\"}}"); + Subscriber subscriber = + server.client().subscribers().complaint("product-news", "ada@example.com"); + + assertTrue(server.takeRequest().path().endsWith("/complaint")); + assertEquals("unsubscribed", subscriber.status()); + } + } + + @Test + void layoutsListParses() { + try (MockServer server = new MockServer()) { + server.enqueueData( + "{\"layouts\":[{\"id\":1,\"uuid\":\"l-1\",\"name\":\"Default\",\"permalink\":\"default\"," + + "\"html_wrapper\":\"{{{ content }}}\",\"text_wrapper\":null}]}"); + List layouts = server.client().layouts().list(); + + assertEquals("/api/v2/server/layouts", server.takeRequest().path()); + assertEquals("default", layouts.get(0).permalink()); + // A layout created with only an HTML wrapper comes back with an + // explicit null for the text one. + assertNull(layouts.get(0).textWrapper()); + } + } + + @Test + void layoutsCreateSendsTheWrapper() { + try (MockServer server = new MockServer()) { + server.enqueue( + 201, + "{\"status\":\"success\",\"time\":0.001,\"data\":{\"layout\":" + + "{\"id\":1,\"name\":\"Default\",\"permalink\":\"default\"}}}"); + Layout layout = + server + .client() + .layouts() + .create( + LayoutRequest.builder() + .name("Default") + .permalink("default") + .htmlWrapper("{{{ content }}}") + .build()); + + assertTrue(server.takeRequest().body().contains("html_wrapper")); + assertEquals("Default", layout.name()); + } + } + + @Test + void layoutsCreateWithoutThePlaceholderIsRefused() { + try (MockServer server = new MockServer()) { + server.enqueue( + 422, + "{\"status\":\"error\",\"time\":0.001,\"error\":{\"code\":\"ValidationError\"," + + "\"message\":\"html_wrapper must contain {{{ content }}}\"}}"); + + CamelMailerException error = + assertThrows( + CamelMailerException.class, + () -> + server + .client() + .layouts() + .create( + LayoutRequest.builder() + .name("Broken") + .htmlWrapper("") + .build())); + assertEquals("ValidationError", error.getCode()); + } + } + + @Test + void layoutsDeleteAndUploadLogo() { + try (MockServer server = new MockServer()) { + server.enqueueData("{\"deleted\":true}"); + assertTrue(server.client().layouts().delete("default")); + assertEquals("/api/v2/server/layouts/default", server.takeRequest().path()); + + server.enqueueData("{\"url\":\"https://app.camelmailer.com/assets/layouts/l-1/logo\"}"); + String url = + server.client().layouts().uploadLogo("default", "data:image/png;base64,iVBORw0KGgo="); + + MockServer.Recorded recorded = server.takeRequest(); + assertTrue(recorded.body().contains("\"data_url\"")); + // The endpoint answers with "url", not "logo_url". + assertEquals("https://app.camelmailer.com/assets/layouts/l-1/logo", url); + } + } +}