diff --git a/CHANGELOG.md b/CHANGELOG.md index c178114..3b38e9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,13 @@ All notable changes to this project are documented here. The format follows - `ads().uploadConversions` returns `ConversionUploadResult` (`id`, `accepted`, `eventCount`, `replayed`) instead of the accepted count, and takes an optional `idempotencyKey`. +### Removed + +- `blog()` (`BlogResource`) and the retired `/v1/blog/*` endpoints it wrapped (settings, + website secret and test, destinations, keywords, articles), with `BlogParams`, every `Blog*` + model and constant class, and `WebhookEvents.ARTICLE_PUBLISHED`. Articles are ordinary posts + now; `blogs()` (remote articles on a connected site) is unchanged. + ## [0.4.0] - 2026-10-18 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 8d33209..ea73517 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,7 +62,7 @@ src/main/java/com/fopost/sdk/ LabelsResource, WebhooksResource, AnalyticsResource, AutomationsResource, MediaResource, AiResource, CommunitiesResource, InboxResource, AdsResource, GoogleAdsResource, ValidateResource, - BroadcastsResource, SequencesResource, BlogResource + BroadcastsResource, SequencesResource WebhookVerifier.java signature check over the raw bytes; WebhookEnvelope is what it returns ``` @@ -82,7 +82,7 @@ calls `ApiClient.unwrap(...)` and `convert(...)`/`convertList(...)` into a recor - `FoPost` instances are immutable and safe to share across threads. **Resources wired today:** `posts`, `accounts` (with `accounts().communities()`), `workspaces`, -`labels`, `webhooks`, `analytics`, `automations`, `media`, `ai`, `inbox`, `contacts`, `broadcasts`, `sequences`, `ads`, `googleAds`, `blog`, `validate`. This is +`labels`, `webhooks`, `analytics`, `automations`, `media`, `ai`, `inbox`, `contacts`, `broadcasts`, `sequences`, `ads`, `googleAds`, `validate`. This is the most complete of the FoPost SDKs — do not narrow it. `FoPost.request(...)` is the escape hatch for anything unwrapped. diff --git a/README.md b/README.md index 52d985c..9ad6eb8 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,6 @@ long failed = client.posts().stream(PostListParams.create().workspaceId(workspac | `accountGroups()` | `list`, `get`, `create`, `update`, `delete`, `setMembers` | | `labels()` | `list`, `get`, `create`, `update`, `delete` | | `webhooks()` | `list`, `create`, `update`, `delete`, `test`, `deliveries`, `delivery`, `redeliver`, `verify` | -| `blog()` | `getSettings`, `updateSettings`, `rotateWebsiteSecret`, `testWebsite`, `listKeywords`, `suggestSeeds`, `planKeywords`, `addKeyword`, `updateKeyword`, `deleteKeyword`, `listArticles`, `requestArticle`, `getArticle`, `updateArticle`, `regenerateArticle`, `submitArticle`, `publishArticle`, `rejectArticle`, `deleteArticle` | | `analytics()` | `overview`, `timeSeries`, `topPosts`, `labels`, `postsTable`, `postingStreak`, `demographics`, `collect`, `decay`, `frequency`, `timeline`, `changes`, `collectPost`, `nativePosts`, `inbox` | | `automations()` | `list`, `get`, `create`, `update`, `delete`, `toggle`, `runs`, `run`, `trigger`, `stats`, `versions`, `version`, `restoreVersion` | | `media()` | `list`, `limits`, `upload`, `presign`, `complete`, `uploadDirect`, `delete` | @@ -263,53 +262,6 @@ System.out.println(hook.secret()); client.webhooks().test(hook.id()); ``` -## Blog - -A post goes to a social network; an article goes to a website. `blog()` holds the keyword plan, -the articles the writer produces, and the settings that say where they are published: -`BlogTargetKind.PRODUCT_BLOG`, a connected `ACCOUNT`, or your own `WEBSITE`, which receives each -published article as a signed webhook. - -Planning starts from the blog's goal. Suggest search terms, research them, then pick the keywords -worth writing; a picked keyword takes the next free date on the calendar. - -```java -client.blog().updateSettings( - workspace.id(), - BlogParams.Settings.create().goal(BlogGoal.LEADS).focusTopics("Scheduling for small teams")); - -List seeds = client.blog().suggestSeeds(workspace.id(), List.of(), "Beginners, not agencies"); -client.blog().planKeywords(workspace.id(), seeds); - -for (BlogKeyword keyword : client.blog().listKeywords( - workspace.id(), BlogParams.Filter.create().status(BlogKeywordStatus.SUGGESTED).limit(3))) { - client.blog().updateKeyword( - workspace.id(), keyword.id(), BlogParams.KeywordUpdate.create().status(BlogKeywordStatus.PLANNED)); -} -``` - -Every article is approved before it publishes: submit a draft for review, then publish it or give -it a `publishAt`. - -```java -BlogArticle article = client.blog().requestArticle( - workspace.id(), - BlogParams.Article.create() - .keyword("how to schedule posts") - .instructions("Lead with the calendar view.")); - -// Poll until the status leaves queued and writing, then read the body. -BlogArticleFull draft = client.blog().getArticle(workspace.id(), article.id()); -client.blog().submitArticle(workspace.id(), article.id()); -client.blog().publishArticle(workspace.id(), article.id()); -``` - -Reads, settings, keyword edits and `submitArticle` need `posts`; `suggestSeeds`, `planKeywords`, -`requestArticle` and `regenerateArticle` spend AI credits and need `ai` (an empty balance is a -`PaymentRequiredException`); `publishArticle` needs `publish`, answers 409 for a draft that was -never submitted, and 409 `no_target` until a target is set. Setting `websiteUrl` issues the site's signing secret once, on -`BlogSettingsUpdate.websiteSecret()`; `rotateWebsiteSecret` issues a new one. - To verify a delivery, hand `WebhookVerifier` the raw request bytes, the headers and the secret. It prefers the timestamped signature, refuses one more than 300 seconds old, and falls back to the body-only signature when no timestamp header is present. The same call is on @@ -319,15 +271,13 @@ the body-only signature when no timestamp header is present. The same call is on byte[] rawBody = request.getInputStream().readAllBytes(); WebhookEnvelope envelope = WebhookVerifier.verify(rawBody, headers, System.getenv("FOPOST_WEBHOOK_SECRET")); -if (WebhookEvents.ARTICLE_PUBLISHED.equals(envelope.event())) { - BlogArticlePublished published = envelope.data(BlogArticlePublished.class); - store(published.slug(), published.bodyHtml()); +if (WebhookEvents.POST_PUBLISHED.equals(envelope.event())) { + String postId = envelope.data().path("id").asText(); } ``` A failed check is a `FoPostException` with code `missing_signature`, `invalid_signature`, -`stale_timestamp` or `invalid_payload`. Image URLs in the payload are fetchable for six hours; -download and store your own copy. +`stale_timestamp` or `invalid_payload`. ## AI features diff --git a/src/main/java/com/fopost/sdk/FoPost.java b/src/main/java/com/fopost/sdk/FoPost.java index 05b3b3a..8e6e57a 100644 --- a/src/main/java/com/fopost/sdk/FoPost.java +++ b/src/main/java/com/fopost/sdk/FoPost.java @@ -13,7 +13,6 @@ import com.fopost.sdk.resource.AiResource; import com.fopost.sdk.resource.AnalyticsResource; import com.fopost.sdk.resource.AutomationsResource; -import com.fopost.sdk.resource.BlogResource; import com.fopost.sdk.resource.BroadcastsResource; import com.fopost.sdk.resource.ConnectSessionsResource; import com.fopost.sdk.resource.ContactsResource; @@ -92,7 +91,6 @@ public final class FoPost { private final InboxResource inbox; private final AdsResource ads; private final GoogleAdsResource googleAds; - private final BlogResource blog; private final BlogsResource blogs; private final ValidateResource validate; @@ -121,7 +119,6 @@ private FoPost(ApiClient http) { this.sequences = new SequencesResource(http); this.ads = new AdsResource(http); this.googleAds = new GoogleAdsResource(http); - this.blog = new BlogResource(http); this.blogs = new BlogsResource(http); this.validate = new ValidateResource(http); } @@ -252,14 +249,6 @@ public GoogleAdsResource googleAds() { return googleAds; } - /** - * Articles for a website: the keyword plan, the drafts the writer produces, and where they - * are published. A post goes to a social network; an article goes to a website. - */ - public BlogResource blog() { - return blog; - } - public ValidateResource validate() { return validate; } diff --git a/src/main/java/com/fopost/sdk/WebhookEnvelope.java b/src/main/java/com/fopost/sdk/WebhookEnvelope.java index e3976ad..dfe3d67 100644 --- a/src/main/java/com/fopost/sdk/WebhookEnvelope.java +++ b/src/main/java/com/fopost/sdk/WebhookEnvelope.java @@ -8,14 +8,14 @@ * *
{@code
  * WebhookEnvelope envelope = WebhookVerifier.verify(rawBody, headers, secret);
- * if (WebhookEvents.ARTICLE_PUBLISHED.equals(envelope.event())) {
- *     BlogArticlePublished article = envelope.data(BlogArticlePublished.class);
+ * if (WebhookEvents.POST_PUBLISHED.equals(envelope.event())) {
+ *     String postId = envelope.data().path("id").asText();
  * }
  * }
*/ public record WebhookEnvelope(String event, JsonNode data, String timestamp) { - /** The body as a typed record, such as {@link com.fopost.sdk.model.BlogArticlePublished}. */ + /** The body as a typed record. */ public T data(Class type) { if (data == null || data.isNull() || data.isMissingNode()) { return null; diff --git a/src/main/java/com/fopost/sdk/model/BlogArticle.java b/src/main/java/com/fopost/sdk/model/BlogArticle.java deleted file mode 100644 index b6ee92c..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogArticle.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.fopost.sdk.model; - -import java.time.Instant; -import java.util.List; - -/** - * An article as a listing shows it. {@code status} is one of {@link BlogArticleStatus}; - * {@code origin} is {@code plan}, {@code user} or {@code agent}. {@code reviewUntil} is when a - * draft may auto-publish, {@code publishAt} where it sits on the calendar, and {@code error} the - * reason the last write or publish failed. {@link com.fopost.sdk.resource.BlogResource#getArticle} - * returns the body as well, as a {@link BlogArticleFull}. - */ -public record BlogArticle( - String id, - String title, - String slug, - String keyword, - String excerpt, - String metaTitle, - String metaDescription, - BlogArticleImage featuredImage, - List tags, - int wordCount, - String status, - String origin, - Instant reviewUntil, - Instant publishAt, - Instant publishedAt, - String publishedUrl, - String error, - Instant createdAt, - Instant updatedAt) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogArticleFull.java b/src/main/java/com/fopost/sdk/model/BlogArticleFull.java deleted file mode 100644 index 61c7462..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogArticleFull.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.fopost.sdk.model; - -import com.fasterxml.jackson.databind.JsonNode; -import java.time.Instant; -import java.util.List; - -/** - * An article with its body: every field of {@link BlogArticle} plus the instructions it was - * written from, the outline, the research brief, both renderings of the body and the in-body - * images. - */ -public record BlogArticleFull( - String id, - String title, - String slug, - String keyword, - String excerpt, - String metaTitle, - String metaDescription, - BlogArticleImage featuredImage, - List tags, - int wordCount, - String status, - String origin, - Instant reviewUntil, - Instant publishAt, - Instant publishedAt, - String publishedUrl, - String error, - Instant createdAt, - Instant updatedAt, - String instructions, - List outline, - JsonNode brief, - String bodyMarkdown, - String bodyHtml, - List images) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogArticleImage.java b/src/main/java/com/fopost/sdk/model/BlogArticleImage.java deleted file mode 100644 index f38c810..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogArticleImage.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.fopost.sdk.model; - -/** - * An image on an article. {@code position} is the index of the outline heading the image sits - * under, and is absent on the featured image. A URL in a webhook payload is fetchable for six - * hours; download and store your own copy. - */ -public record BlogArticleImage(String mediaId, String url, String alt, Integer position) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogArticlePublished.java b/src/main/java/com/fopost/sdk/model/BlogArticlePublished.java deleted file mode 100644 index 01fb267..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogArticlePublished.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.fopost.sdk.model; - -import java.time.Instant; -import java.util.List; - -/** - * The {@code data} of an {@code article.published} webhook, and of the delivery a website target - * receives. Image URLs are fetchable for six hours; download and store your own copy. - */ -public record BlogArticlePublished( - String id, - String title, - String slug, - String excerpt, - String metaTitle, - String metaDescription, - String bodyMarkdown, - String bodyHtml, - BlogArticleImage featuredImage, - List images, - List tags, - String keyword, - int wordCount, - Instant publishedAt, - String publishedUrl) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogArticleStatus.java b/src/main/java/com/fopost/sdk/model/BlogArticleStatus.java deleted file mode 100644 index 02fe820..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogArticleStatus.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.fopost.sdk.model; - -import java.util.List; - -/** The statuses an article moves through, from the request to the live page. */ -public final class BlogArticleStatus { - - private BlogArticleStatus() {} - - public static final String QUEUED = "queued"; - public static final String WRITING = "writing"; - public static final String DRAFT = "draft"; - public static final String IN_REVIEW = "in_review"; - public static final String SCHEDULED = "scheduled"; - public static final String PUBLISHING = "publishing"; - public static final String PUBLISHED = "published"; - public static final String FAILED = "failed"; - public static final String REJECTED = "rejected"; - - public static final List ALL = - List.of(QUEUED, WRITING, DRAFT, IN_REVIEW, SCHEDULED, PUBLISHING, PUBLISHED, FAILED, REJECTED); -} diff --git a/src/main/java/com/fopost/sdk/model/BlogGoal.java b/src/main/java/com/fopost/sdk/model/BlogGoal.java deleted file mode 100644 index db58dd0..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogGoal.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.fopost.sdk.model; - -import java.util.List; - -/** What the blog is for; steers suggested search terms and keyword ranking. */ -public final class BlogGoal { - - private BlogGoal() {} - - public static final String TRAFFIC = "traffic"; - public static final String LEADS = "leads"; - public static final String SALES = "sales"; - public static final String SIGNUPS = "signups"; - public static final String AUTHORITY = "authority"; - - public static final List ALL = List.of(TRAFFIC, LEADS, SALES, SIGNUPS, AUTHORITY); -} diff --git a/src/main/java/com/fopost/sdk/model/BlogKeyword.java b/src/main/java/com/fopost/sdk/model/BlogKeyword.java deleted file mode 100644 index 245a31d..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogKeyword.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.fopost.sdk.model; - -import java.time.Instant; -import java.time.LocalDate; - -/** - * A keyword in the plan. {@code status} is one of {@link BlogKeywordStatus}; {@code source} is - * {@code provider}, {@code user} or {@code agent}. {@code difficulty} runs 0 to 100. - * {@code fitReason} says why the keyword serves the blog goal. - */ -public record BlogKeyword( - String id, - String keyword, - Integer searchVolume, - Integer difficulty, - Double cpc, - String intent, - String source, - String status, - LocalDate plannedFor, - String fitReason, - Instant createdAt) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogKeywordStatus.java b/src/main/java/com/fopost/sdk/model/BlogKeywordStatus.java deleted file mode 100644 index 5a558cc..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogKeywordStatus.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.fopost.sdk.model; - -import java.util.List; - -/** Where a keyword sits in the plan. */ -public final class BlogKeywordStatus { - - private BlogKeywordStatus() {} - - public static final String SUGGESTED = "suggested"; - public static final String PLANNED = "planned"; - public static final String WRITTEN = "written"; - public static final String DISMISSED = "dismissed"; - - public static final List ALL = List.of(SUGGESTED, PLANNED, WRITTEN, DISMISSED); -} diff --git a/src/main/java/com/fopost/sdk/model/BlogPlanRun.java b/src/main/java/com/fopost/sdk/model/BlogPlanRun.java deleted file mode 100644 index 9c42f39..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogPlanRun.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.fopost.sdk.model; - -import java.time.Instant; - -/** - * The last keyword research run. {@code status} is {@code queued}, {@code running}, {@code done} or - * {@code failed}; {@code added} is how many new keywords it found. - */ -public record BlogPlanRun(String status, String error, Integer added, Instant finishedAt) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogSettings.java b/src/main/java/com/fopost/sdk/model/BlogSettings.java deleted file mode 100644 index c2e064b..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogSettings.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.fopost.sdk.model; - -import java.time.Instant; - -/** - * A workspace's blog configuration. - * - *

{@code goal} is one of {@link BlogGoal}, or null. {@code cadencePerWeek} is how many articles - * the planner queues each week; 0 turns planning off. {@code reviewHoldDays} is how many days before - * its planned date a picked keyword starts being written. {@code targetKind} is one of - * {@link BlogTargetKind}. {@code hasWebsiteSecret} says whether a - * website target has a signing secret; the secret itself is only ever returned when issued. - * {@code planRun} is the last keyword research run, null before the first. - * {@code keywordDataAvailable} says whether search volume and difficulty can be fetched on this - * deployment. - */ -public record BlogSettings( - String siteUrl, - String topic, - String audience, - String goal, - String focusTopics, - String avoidTopics, - String language, - Integer locationCode, - int cadencePerWeek, - int reviewHoldDays, - String imageTier, - Integer inBodyImages, - Integer minWords, - Integer maxWords, - String brandVoiceId, - String targetKind, - String targetAccountId, - String targetPlatform, - String websiteUrl, - boolean hasWebsiteSecret, - BlogPlanRun planRun, - Boolean keywordDataAvailable, - Instant updatedAt) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogSettingsUpdate.java b/src/main/java/com/fopost/sdk/model/BlogSettingsUpdate.java deleted file mode 100644 index 9987e8a..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogSettingsUpdate.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.fopost.sdk.model; - -/** - * The answer to a settings update. {@code websiteSecret} is set only when the update set - * {@code websiteUrl} for the first time, and is never shown again: store it then. - */ -public record BlogSettingsUpdate(BlogSettings settings, String websiteSecret) {} diff --git a/src/main/java/com/fopost/sdk/model/BlogTargetKind.java b/src/main/java/com/fopost/sdk/model/BlogTargetKind.java deleted file mode 100644 index 02c1435..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogTargetKind.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.fopost.sdk.model; - -import java.util.List; - -/** Where published articles go: the hosted product blog, a connected account, or your own site. */ -public final class BlogTargetKind { - - private BlogTargetKind() {} - - public static final String PRODUCT_BLOG = "product_blog"; - public static final String ACCOUNT = "account"; - public static final String WEBSITE = "website"; - - public static final List ALL = List.of(PRODUCT_BLOG, ACCOUNT, WEBSITE); -} diff --git a/src/main/java/com/fopost/sdk/model/BlogWebsiteTest.java b/src/main/java/com/fopost/sdk/model/BlogWebsiteTest.java deleted file mode 100644 index 72e7658..0000000 --- a/src/main/java/com/fopost/sdk/model/BlogWebsiteTest.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.fopost.sdk.model; - -/** - * The outcome of a test delivery to the website target. {@code httpStatus} is the site's HTTP - * answer; {@code error} says why a failed test failed. - */ -public record BlogWebsiteTest(boolean ok, Integer httpStatus, String error) {} diff --git a/src/main/java/com/fopost/sdk/model/WebhookEvents.java b/src/main/java/com/fopost/sdk/model/WebhookEvents.java index 959bbbd..86552d4 100644 --- a/src/main/java/com/fopost/sdk/model/WebhookEvents.java +++ b/src/main/java/com/fopost/sdk/model/WebhookEvents.java @@ -14,9 +14,8 @@ private WebhookEvents() {} public static final String DELIVERY_FAILED = "delivery.failed"; public static final String DELIVERY_DELAYED = "delivery.delayed"; public static final String ACCOUNT_HEALTH_CHANGED = "account.health_changed"; - public static final String ARTICLE_PUBLISHED = "article.published"; public static final List ALL = List.of( POST_PUBLISHED, POST_FAILED, POST_PARTIALLY_FAILED, DELIVERY_PUBLISHED, - DELIVERY_FAILED, DELIVERY_DELAYED, ACCOUNT_HEALTH_CHANGED, ARTICLE_PUBLISHED); + DELIVERY_FAILED, DELIVERY_DELAYED, ACCOUNT_HEALTH_CHANGED); } diff --git a/src/main/java/com/fopost/sdk/param/BlogParams.java b/src/main/java/com/fopost/sdk/param/BlogParams.java deleted file mode 100644 index 4d47a62..0000000 --- a/src/main/java/com/fopost/sdk/param/BlogParams.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.fopost.sdk.param; - -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fopost.sdk.internal.Json; -import java.time.Instant; -import java.time.LocalDate; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Request builders for {@link com.fopost.sdk.resource.BlogResource}. Bodies are camelCase on the - * wire, and a field set to null is sent as null so the API clears it. - */ -public final class BlogParams { - - private BlogParams() {} - - // A plain Map would lose its nulls: the mapper is NON_NULL, and a cleared field must reach - // the API as null. - static ObjectNode node(Map values) { - ObjectNode node = Json.MAPPER.createObjectNode(); - values.forEach((key, value) -> { - if (value == null) { - node.putNull(key); - } else { - node.set(key, Json.MAPPER.valueToTree(value)); - } - }); - return node; - } - - /** A partial update of the workspace's blog settings; only what is set is sent. */ - public static final class Settings { - - private final Map body = new LinkedHashMap<>(); - - public static Settings create() { - return new Settings(); - } - - /** The site the articles are written for; null clears it. */ - public Settings siteUrl(String siteUrl) { - body.put("siteUrl", siteUrl); - return this; - } - - public Settings topic(String topic) { - body.put("topic", topic); - return this; - } - - public Settings audience(String audience) { - body.put("audience", audience); - return this; - } - - /** One of {@link com.fopost.sdk.model.BlogGoal}; null clears it. */ - public Settings goal(String goal) { - body.put("goal", goal); - return this; - } - - /** What the blog wants to write about; null clears it. */ - public Settings focusTopics(String focusTopics) { - body.put("focusTopics", focusTopics); - return this; - } - - /** What the blog never writes about; null clears it. */ - public Settings avoidTopics(String avoidTopics) { - body.put("avoidTopics", avoidTopics); - return this; - } - - public Settings language(String language) { - body.put("language", language); - return this; - } - - public Settings locationCode(int locationCode) { - body.put("locationCode", locationCode); - return this; - } - - /** Articles planned per week, 0 to 7; 0 turns planning off. */ - public Settings cadencePerWeek(int cadencePerWeek) { - body.put("cadencePerWeek", cadencePerWeek); - return this; - } - - /** Days before its planned date that a picked keyword starts being written, 0 to 14. */ - public Settings reviewHoldDays(int reviewHoldDays) { - body.put("reviewHoldDays", reviewHoldDays); - return this; - } - - /** {@code draft}, {@code standard} or {@code best}. */ - public Settings imageTier(String imageTier) { - body.put("imageTier", imageTier); - return this; - } - - /** Images placed in the body, 0 to 3. */ - public Settings inBodyImages(int inBodyImages) { - body.put("inBodyImages", inBodyImages); - return this; - } - - public Settings minWords(int minWords) { - body.put("minWords", minWords); - return this; - } - - public Settings maxWords(int maxWords) { - body.put("maxWords", maxWords); - return this; - } - - /** The brand the writer takes its voice from; null returns to the workspace default. */ - public Settings brandVoiceId(String brandVoiceId) { - body.put("brandVoiceId", brandVoiceId); - return this; - } - - /** One of {@link com.fopost.sdk.model.BlogTargetKind}; null leaves the blog with no target. */ - public Settings targetKind(String targetKind) { - body.put("targetKind", targetKind); - return this; - } - - public Settings targetAccountId(String targetAccountId) { - body.put("targetAccountId", targetAccountId); - return this; - } - - /** - * Where published articles are POSTed as a signed webhook. Setting it for the first time - * issues a secret, returned once on {@link com.fopost.sdk.model.BlogSettingsUpdate}. - */ - public Settings websiteUrl(String websiteUrl) { - body.put("websiteUrl", websiteUrl); - return this; - } - - public ObjectNode toNode() { - return node(body); - } - } - - /** Filters for a keyword or article listing. */ - public static final class Filter { - - private final Map query = new LinkedHashMap<>(); - - public static Filter create() { - return new Filter(); - } - - /** One or more statuses; several are joined with a comma. */ - public Filter status(String... statuses) { - query.put("status", String.join(",", statuses)); - return this; - } - - public Filter limit(int limit) { - query.put("limit", limit); - return this; - } - - public Map toQuery() { - return new LinkedHashMap<>(query); - } - } - - /** A keyword added to the plan by hand. */ - public static final class Keyword { - - private final Map body = new LinkedHashMap<>(); - - public static Keyword of(String keyword) { - Keyword params = new Keyword(); - params.body.put("keyword", keyword); - return params; - } - - /** The day the article for it should be written. */ - public Keyword plannedFor(LocalDate plannedFor) { - Params.put(body, "plannedFor", plannedFor == null ? null : plannedFor.toString()); - return this; - } - - public Map toMap() { - return new LinkedHashMap<>(body); - } - } - - /** Moves a keyword in the plan or re-dates it. */ - public static final class KeywordUpdate { - - private final Map body = new LinkedHashMap<>(); - - public static KeywordUpdate create() { - return new KeywordUpdate(); - } - - /** - * One of {@link com.fopost.sdk.model.BlogKeywordStatus}. {@code planned} picks the keyword and - * gives it the next free date. - */ - public KeywordUpdate status(String status) { - body.put("status", status); - return this; - } - - /** The day the article for it should be written; null takes it off the calendar. */ - public KeywordUpdate plannedFor(LocalDate plannedFor) { - body.put("plannedFor", plannedFor == null ? null : plannedFor.toString()); - return this; - } - - public ObjectNode toNode() { - return node(body); - } - } - - /** Asks the writer for an article. One of {@code title}, {@code keyword} or {@code keywordId} is required. */ - public static final class Article { - - private final Map body = new LinkedHashMap<>(); - - public static Article create() { - return new Article(); - } - - public Article title(String title) { - body.put("title", title); - return this; - } - - public Article keyword(String keyword) { - body.put("keyword", keyword); - return this; - } - - /** A keyword from the plan; its term becomes the target. */ - public Article keywordId(String keywordId) { - body.put("keywordId", keywordId); - return this; - } - - /** Up to 4000 characters of direction for the writer. */ - public Article instructions(String instructions) { - body.put("instructions", instructions); - return this; - } - - public Map toMap() { - return new LinkedHashMap<>(body); - } - } - - /** Edits an article. One still being written or already publishing answers 409. */ - public static final class ArticleUpdate { - - private final Map body = new LinkedHashMap<>(); - - public static ArticleUpdate create() { - return new ArticleUpdate(); - } - - public ArticleUpdate title(String title) { - body.put("title", title); - return this; - } - - /** Lowercase letters, digits and hyphens. */ - public ArticleUpdate slug(String slug) { - body.put("slug", slug); - return this; - } - - public ArticleUpdate excerpt(String excerpt) { - body.put("excerpt", excerpt); - return this; - } - - public ArticleUpdate metaTitle(String metaTitle) { - body.put("metaTitle", metaTitle); - return this; - } - - public ArticleUpdate metaDescription(String metaDescription) { - body.put("metaDescription", metaDescription); - return this; - } - - public ArticleUpdate bodyMarkdown(String bodyMarkdown) { - body.put("bodyMarkdown", bodyMarkdown); - return this; - } - - public ArticleUpdate tags(List tags) { - body.put("tags", tags); - return this; - } - - /** - * Puts an article in review on the calendar; a draft answers 409 until it is submitted. Null - * returns it to draft. - */ - public ArticleUpdate publishAt(Instant publishAt) { - body.put("publishAt", Params.iso(publishAt)); - return this; - } - - public ObjectNode toNode() { - return node(body); - } - } -} diff --git a/src/main/java/com/fopost/sdk/resource/BlogResource.java b/src/main/java/com/fopost/sdk/resource/BlogResource.java deleted file mode 100644 index 6af80a0..0000000 --- a/src/main/java/com/fopost/sdk/resource/BlogResource.java +++ /dev/null @@ -1,271 +0,0 @@ -package com.fopost.sdk.resource; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fopost.sdk.FoPostException; -import com.fopost.sdk.internal.ApiClient; -import com.fopost.sdk.internal.Json; -import com.fopost.sdk.model.BlogArticle; -import com.fopost.sdk.model.BlogArticleFull; -import com.fopost.sdk.model.BlogKeyword; -import com.fopost.sdk.model.BlogSettings; -import com.fopost.sdk.model.BlogSettingsUpdate; -import com.fopost.sdk.model.BlogWebsiteTest; -import com.fopost.sdk.param.BlogParams; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Articles for a website: the keyword plan, the drafts the writer produces, and where they are - * published. A post goes to a social network; an article goes to a website. - * - *

Reads, settings, keyword edits and {@code submitArticle} need the {@code posts} scope. - * {@code suggestSeeds}, {@code planKeywords}, {@code requestArticle} and {@code regenerateArticle} - * spend AI credits and need {@code ai}; an empty balance answers 402. {@code publishArticle} needs - * {@code publish}, answers 409 for a draft that was never submitted, and 409 {@code no_target} - * until the settings name a target. Every call names the workspace: as {@code workspace_id} on the - * query string for a read, an update or a delete, as {@code workspaceId} in the body for a create. - * - *

{@code
- * BlogArticle article = fopost.blog().requestArticle(
- *         workspace.id(), BlogParams.Article.create().keyword("how to schedule posts"));
- *
- * BlogArticleFull full = fopost.blog().getArticle(workspace.id(), article.id());
- * fopost.blog().submitArticle(workspace.id(), article.id());
- * fopost.blog().publishArticle(workspace.id(), article.id());
- * }
- */ -public final class BlogResource { - - private final ApiClient http; - - public BlogResource(ApiClient http) { - this.http = http; - } - - // ── Settings ── - - public BlogSettings getSettings(String workspaceId) { - return http.convert( - ApiClient.unwrap(http.get("/v1/blog/settings", query(workspaceId))), BlogSettings.class); - } - - /** - * Change the settings. Setting {@code websiteUrl} for the first time issues the signing secret - * for that site; it comes back once on {@link BlogSettingsUpdate#websiteSecret()} and is never - * shown again. Rotate it with {@link #rotateWebsiteSecret}. - */ - public BlogSettingsUpdate updateSettings(String workspaceId, BlogParams.Settings params) { - JsonNode body = http.patch("/v1/blog/settings", withWorkspace(workspaceId, params.toNode())); - BlogSettings settings = http.convert(ApiClient.unwrap(body), BlogSettings.class); - JsonNode secret = ApiClient.unwrap(body).path("website_secret"); - return new BlogSettingsUpdate(settings, secret.isTextual() ? secret.asText() : null); - } - - /** Issue a new website signing secret. The old one stops verifying at once. */ - public String rotateWebsiteSecret(String workspaceId) { - JsonNode body = ApiClient.unwrap(http.post("/v1/blog/settings/website-secret", body(workspaceId))); - return body.path("website_secret").asText(null); - } - - /** - * Send a signed {@code article.test} delivery to the website target. A site that does not - * answer 2xx comes back with {@code ok} false, its {@code httpStatus} and the reason, rather - * than as an exception. - */ - public BlogWebsiteTest testWebsite(String workspaceId) { - try { - JsonNode body = ApiClient.unwrap(http.post("/v1/blog/settings/website-test", body(workspaceId))); - return new BlogWebsiteTest(true, httpStatus(body), null); - } catch (FoPostException e) { - // The API answers 502 website_test_failed, with the site's http_status, when the site fails. - if (e.status() == 502 && e.body() instanceof JsonNode body && body.has("http_status")) { - return new BlogWebsiteTest(false, httpStatus(body), e.getMessage()); - } - throw e; - } - } - - private static Integer httpStatus(JsonNode body) { - JsonNode status = body.path("http_status"); - return status.isNumber() ? status.asInt() : null; - } - - // ── Keywords ── - - public List listKeywords(String workspaceId) { - return listKeywords(workspaceId, BlogParams.Filter.create()); - } - - public List listKeywords(String workspaceId, BlogParams.Filter filter) { - Map query = query(workspaceId); - query.putAll(filter.toQuery()); - return http.convertList(ApiClient.unwrap(http.get("/v1/blog/keywords", query)), BlogKeyword.class); - } - - /** About 10 search terms from the blog goal and topics. Spends AI credits. */ - public List suggestSeeds(String workspaceId) { - return suggestSeeds(workspaceId, List.of(), null); - } - - /** - * About 10 search terms from the blog goal and topics, to edit before {@link #planKeywords}. - * Pass the current {@code seeds} (at most 20) to refine them and a {@code prompt} (up to 500 - * characters, or null) to steer. Spends AI credits. - */ - public List suggestSeeds(String workspaceId, List seeds, String prompt) { - Map body = body(workspaceId); - if (!seeds.isEmpty()) { - body.put("seeds", seeds); - } - if (prompt != null) { - body.put("prompt", prompt); - } - JsonNode data = ApiClient.unwrap(http.post("/v1/blog/keywords/suggest", body)); - return http.convertList(data.path("seeds"), String.class); - } - - /** - * Queue a research run with terms derived from the blog settings. Results land as - * {@code suggested} keywords; follow the run in {@link BlogSettings#planRun()}. Spends AI - * credits. - */ - public void planKeywords(String workspaceId) { - planKeywords(workspaceId, List.of()); - } - - /** - * Queue a research run around these seed terms. Results land as {@code suggested} keywords and - * never fill the calendar; set one to {@code planned} with {@link #updateKeyword} to pick it. - * Spends AI credits. - */ - public void planKeywords(String workspaceId, List seeds) { - Map body = body(workspaceId); - if (!seeds.isEmpty()) { - body.put("seeds", seeds); - } - http.post("/v1/blog/keywords/plan", body); - } - - public BlogKeyword addKeyword(String workspaceId, BlogParams.Keyword params) { - Map body = body(workspaceId); - body.putAll(params.toMap()); - return http.convert(ApiClient.unwrap(http.post("/v1/blog/keywords", body)), BlogKeyword.class); - } - - public BlogKeyword updateKeyword(String workspaceId, String keywordId, BlogParams.KeywordUpdate params) { - return http.convert( - ApiClient.unwrap(http.request( - "PATCH", "/v1/blog/keywords/" + keywordId, params.toNode(), query(workspaceId))), - BlogKeyword.class); - } - - public void deleteKeyword(String workspaceId, String keywordId) { - http.request("DELETE", "/v1/blog/keywords/" + keywordId, null, query(workspaceId)); - } - - // ── Articles ── - - public List listArticles(String workspaceId) { - return listArticles(workspaceId, BlogParams.Filter.create()); - } - - public List listArticles(String workspaceId, BlogParams.Filter filter) { - Map query = query(workspaceId); - query.putAll(filter.toQuery()); - return http.convertList(ApiClient.unwrap(http.get("/v1/blog/articles", query)), BlogArticle.class); - } - - /** - * Ask the writer for an article. The answer is the queued row; poll {@link #getArticle} until - * its status leaves {@code queued} and {@code writing}. Spends AI credits. - */ - public BlogArticle requestArticle(String workspaceId, BlogParams.Article params) { - Map body = body(workspaceId); - body.putAll(params.toMap()); - return http.convert(ApiClient.unwrap(http.post("/v1/blog/articles", body)), BlogArticle.class); - } - - public BlogArticleFull getArticle(String workspaceId, String articleId) { - return http.convert( - ApiClient.unwrap(http.get("/v1/blog/articles/" + articleId, query(workspaceId))), - BlogArticleFull.class); - } - - /** - * Edit an article. One that is not editable answers 409 {@code invalid_state}, as does a - * {@code publishAt} on a draft that was never submitted with {@link #submitArticle}. - */ - public BlogArticleFull updateArticle(String workspaceId, String articleId, BlogParams.ArticleUpdate params) { - return http.convert( - ApiClient.unwrap(http.request( - "PATCH", "/v1/blog/articles/" + articleId, params.toNode(), query(workspaceId))), - BlogArticleFull.class); - } - - /** - * Write the article again from its instructions. Spends AI credits. - * - *

Wraps the API's {@code regenerateBlogArticle} operation. - */ - public BlogArticle regenerateArticle(String workspaceId, String articleId) { - return action(workspaceId, articleId, "regenerate"); - } - - /** - * Publish an article in review to the configured target. Needs {@code publish}. A draft answers - * 409 until it is submitted with {@link #submitArticle}; 409 {@code no_target} means the - * settings name none. - */ - public BlogArticle publishArticle(String workspaceId, String articleId) { - return action(workspaceId, articleId, "publish"); - } - - /** - * Move a draft, failed or rejected article to {@code in_review}. Any other state answers 409. - * - *

Wraps the API's {@code submitBlogArticle} operation. - */ - public BlogArticle submitArticle(String workspaceId, String articleId) { - return action(workspaceId, articleId, "submit"); - } - - /** - * Take an article out of review without publishing it. - * - *

Wraps the API's {@code rejectBlogArticle} operation. - */ - public BlogArticle rejectArticle(String workspaceId, String articleId) { - return action(workspaceId, articleId, "reject"); - } - - public void deleteArticle(String workspaceId, String articleId) { - http.request("DELETE", "/v1/blog/articles/" + articleId, null, query(workspaceId)); - } - - private BlogArticle action(String workspaceId, String articleId, String action) { - return http.convert( - ApiClient.unwrap(http.post("/v1/blog/articles/" + articleId + "/" + action, null, query(workspaceId))), - BlogArticle.class); - } - - private static Map query(String workspaceId) { - Map map = new LinkedHashMap<>(); - map.put("workspace_id", workspaceId); - return map; - } - - private static Map body(String workspaceId) { - Map map = new LinkedHashMap<>(); - map.put("workspaceId", workspaceId); - return map; - } - - private static ObjectNode withWorkspace(String workspaceId, ObjectNode fields) { - ObjectNode body = Json.MAPPER.createObjectNode(); - body.put("workspaceId", workspaceId); - body.setAll(fields); - return body; - } -} diff --git a/src/test/java/com/fopost/sdk/BlogTest.java b/src/test/java/com/fopost/sdk/BlogTest.java deleted file mode 100644 index fc7274f..0000000 --- a/src/test/java/com/fopost/sdk/BlogTest.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.fopost.sdk; - -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.fopost.sdk.model.BlogArticle; -import com.fopost.sdk.model.BlogArticleFull; -import com.fopost.sdk.model.BlogArticleStatus; -import com.fopost.sdk.model.BlogGoal; -import com.fopost.sdk.model.BlogKeyword; -import com.fopost.sdk.model.BlogKeywordStatus; -import com.fopost.sdk.model.BlogSettings; -import com.fopost.sdk.model.BlogSettingsUpdate; -import com.fopost.sdk.model.BlogTargetKind; -import com.fopost.sdk.model.BlogWebsiteTest; -import com.fopost.sdk.param.BlogParams; -import java.time.Instant; -import java.time.LocalDate; -import java.util.List; -import org.junit.jupiter.api.Test; - -class BlogTest { - - private static final String SETTINGS = - """ - {"site_url":"https://yourbrand.com","topic":"Scheduling","audience":"Marketers", - "goal":"leads","focus_topics":"Scheduling tips","avoid_topics":"Competitor brands", - "language":"en","location_code":2840,"cadence_per_week":2,"review_hold_days":3, - "image_tier":"standard","in_body_images":2,"min_words":900, - "max_words":1500,"brand_voice_id":null,"target_kind":"website","target_account_id":null, - "target_platform":null,"website_url":"https://yourbrand.com/hooks/fopost", - "has_website_secret":true,"keyword_data_available":true, - "plan_run":{"status":"done","error":null,"added":12,"finished_at":"2026-10-11T09:05:00.000Z"}, - "updated_at":"2026-10-11T09:00:00.000Z"}"""; - - private static final String KEYWORD = - """ - {"id":"kw_1","keyword":"how to schedule posts","search_volume":1200,"difficulty":34, - "cpc":1.25,"intent":"informational","source":"provider","status":"planned", - "planned_for":"2026-10-14","fit_reason":"Readers who schedule posts need a tool", - "created_at":"2026-10-11T09:00:00.000Z"}"""; - - private static final String ARTICLE = - """ - {"id":"art_1","title":"How to schedule posts","slug":"how-to-schedule-posts", - "keyword":"how to schedule posts","excerpt":null,"meta_title":null,"meta_description":null, - "featured_image":{"media_id":"m_1","url":"https://cdn.example/f.png","alt":"Calendar"}, - "tags":["scheduling"],"word_count":0,"status":"queued","origin":"user", - "review_until":null,"publish_at":null,"published_at":null,"published_url":null,"error":null, - "created_at":"2026-10-11T09:00:00.000Z","updated_at":"2026-10-11T09:00:00.000Z"}"""; - - @Test - void settingsTravelOnTheQueryForAReadAndInTheBodyForAnUpdate() { - FakeTransport transport = new FakeTransport() - .enqueue(200, SETTINGS) - .enqueue(200, SETTINGS.substring(0, SETTINGS.length() - 1) + ",\"website_secret\":\"whsec_abc\"}") - .enqueue(200, "{\"website_secret\":\"whsec_def\"}") - .enqueue(200, "{\"http_status\":204}") - .enqueue(502, "{\"error\":\"website_test_failed\",\"message\":\"HTTP 500\",\"http_status\":500}"); - FoPost client = TestSupport.client(transport); - - BlogSettings settings = client.blog().getSettings("w1"); - assertEquals("https://api.fopost.test/v1/blog/settings?workspace_id=w1", transport.last().url()); - assertEquals(BlogTargetKind.WEBSITE, settings.targetKind()); - assertEquals(2, settings.cadencePerWeek()); - assertTrue(settings.hasWebsiteSecret()); - assertEquals(Instant.parse("2026-10-11T09:00:00Z"), settings.updatedAt()); - assertEquals(BlogGoal.LEADS, settings.goal()); - assertEquals("Scheduling tips", settings.focusTopics()); - assertEquals("Competitor brands", settings.avoidTopics()); - assertEquals("done", settings.planRun().status()); - assertEquals(12, settings.planRun().added()); - assertEquals(Instant.parse("2026-10-11T09:05:00Z"), settings.planRun().finishedAt()); - - BlogSettingsUpdate updated = client.blog().updateSettings( - "w1", - BlogParams.Settings.create() - .websiteUrl("https://yourbrand.com/hooks/fopost") - .targetKind(BlogTargetKind.WEBSITE) - .brandVoiceId(null) - .cadencePerWeek(2) - .goal(BlogGoal.LEADS) - .focusTopics("Scheduling tips") - .avoidTopics(null)); - assertEquals("PATCH", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/settings", transport.last().url()); - assertEquals( - "{\"workspaceId\":\"w1\",\"websiteUrl\":\"https://yourbrand.com/hooks/fopost\"," - + "\"targetKind\":\"website\",\"brandVoiceId\":null,\"cadencePerWeek\":2," - + "\"goal\":\"leads\",\"focusTopics\":\"Scheduling tips\",\"avoidTopics\":null}", - transport.lastBody()); - assertEquals("whsec_abc", updated.websiteSecret()); - assertEquals("en", updated.settings().language()); - - assertEquals("whsec_def", client.blog().rotateWebsiteSecret("w1")); - assertEquals("https://api.fopost.test/v1/blog/settings/website-secret", transport.last().url()); - assertEquals("{\"workspaceId\":\"w1\"}", transport.lastBody()); - - BlogWebsiteTest passed = client.blog().testWebsite("w1"); - assertEquals("https://api.fopost.test/v1/blog/settings/website-test", transport.last().url()); - assertEquals("{\"workspaceId\":\"w1\"}", transport.lastBody()); - assertTrue(passed.ok()); - assertEquals(204, passed.httpStatus()); - - BlogWebsiteTest failed = client.blog().testWebsite("w1"); - assertFalse(failed.ok()); - assertEquals(500, failed.httpStatus()); - assertEquals("HTTP 500", failed.error()); - } - - @Test - void keywordsFilterOnTheQueryAndClearAPlannedDateWithNull() { - FakeTransport transport = new FakeTransport() - .enqueue(200, "{\"data\":[" + KEYWORD + "]}") - .enqueue(202, "{\"status\":\"queued\"}") - .enqueue(201, KEYWORD) - .enqueue(200, KEYWORD) - .enqueue(204, ""); - FoPost client = TestSupport.client(transport); - - List keywords = client.blog().listKeywords( - "w1", BlogParams.Filter.create().status(BlogKeywordStatus.SUGGESTED, BlogKeywordStatus.PLANNED).limit(20)); - assertEquals( - "https://api.fopost.test/v1/blog/keywords?workspace_id=w1&status=suggested%2Cplanned&limit=20", - transport.last().url()); - assertEquals(1200, keywords.get(0).searchVolume()); - assertEquals(LocalDate.of(2026, 10, 14), keywords.get(0).plannedFor()); - assertEquals(1.25, keywords.get(0).cpc()); - assertEquals("Readers who schedule posts need a tool", keywords.get(0).fitReason()); - - client.blog().planKeywords("w1", List.of("scheduling", "analytics")); - assertEquals("https://api.fopost.test/v1/blog/keywords/plan", transport.last().url()); - assertEquals("{\"workspaceId\":\"w1\",\"seeds\":[\"scheduling\",\"analytics\"]}", transport.lastBody()); - - BlogKeyword added = client.blog().addKeyword( - "w1", BlogParams.Keyword.of("how to schedule posts").plannedFor(LocalDate.of(2026, 10, 14))); - assertEquals("https://api.fopost.test/v1/blog/keywords", transport.last().url()); - assertEquals( - "{\"workspaceId\":\"w1\",\"keyword\":\"how to schedule posts\",\"plannedFor\":\"2026-10-14\"}", - transport.lastBody()); - assertEquals("kw_1", added.id()); - - client.blog().updateKeyword( - "w1", "kw_1", BlogParams.KeywordUpdate.create().status(BlogKeywordStatus.DISMISSED).plannedFor(null)); - assertEquals("PATCH", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/keywords/kw_1?workspace_id=w1", transport.last().url()); - assertEquals("{\"status\":\"dismissed\",\"plannedFor\":null}", transport.lastBody()); - - client.blog().deleteKeyword("w1", "kw_1"); - assertEquals("DELETE", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/keywords/kw_1?workspace_id=w1", transport.last().url()); - assertNull(transport.last().body()); - } - - @Test - void articlesAreRequestedInTheBodyAndActedOnByPath() { - String full = ARTICLE.substring(0, ARTICLE.length() - 1) - + ",\"instructions\":\"Keep it short\",\"outline\":[\"Why\",\"How\"]," - + "\"brief\":{\"questions\":[\"Why\"],\"search_volume\":2},\"body_markdown\":\"# Hi\",\"body_html\":\"

Hi

\"," - + "\"images\":[{\"media_id\":\"m_2\",\"url\":\"https://cdn.example/i.png\",\"alt\":\"Step\",\"position\":1}]}"; - FakeTransport transport = new FakeTransport() - .enqueue(200, "{\"data\":[" + ARTICLE + "]}") - .enqueue(202, ARTICLE) - .enqueue(200, full) - .enqueue(200, full) - .enqueue(202, ARTICLE) - .enqueue(202, ARTICLE) - .enqueue(200, ARTICLE) - .enqueue(204, "") - .enqueue(402, "{\"error\":\"insufficient_credits\",\"message\":\"Balance\",\"upgrade_url\":\"https://fopost.com/billing\"}") - .enqueue(409, "{\"error\":\"no_target\",\"message\":\"Pick a target first\"}"); - FoPost client = TestSupport.client(transport); - - List articles = client.blog().listArticles( - "w1", BlogParams.Filter.create().status(BlogArticleStatus.DRAFT)); - assertEquals("https://api.fopost.test/v1/blog/articles?workspace_id=w1&status=draft", transport.last().url()); - assertEquals("Calendar", articles.get(0).featuredImage().alt()); - assertEquals(List.of("scheduling"), articles.get(0).tags()); - - BlogArticle requested = client.blog().requestArticle( - "w1", BlogParams.Article.create().keyword("how to schedule posts").instructions("Keep it short")); - assertEquals("https://api.fopost.test/v1/blog/articles", transport.last().url()); - assertEquals( - "{\"workspaceId\":\"w1\",\"keyword\":\"how to schedule posts\",\"instructions\":\"Keep it short\"}", - transport.lastBody()); - assertEquals(BlogArticleStatus.QUEUED, requested.status()); - - BlogArticleFull fetched = client.blog().getArticle("w1", "art_1"); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1?workspace_id=w1", transport.last().url()); - assertEquals("# Hi", fetched.bodyMarkdown()); - assertEquals(List.of("Why", "How"), fetched.outline()); - assertEquals(2, fetched.brief().path("search_volume").asInt()); - assertEquals(1, fetched.images().get(0).position()); - - client.blog().updateArticle( - "w1", "art_1", BlogParams.ArticleUpdate.create().title("New title").tags(List.of("a", "b")).publishAt(null)); - assertEquals("PATCH", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1?workspace_id=w1", transport.last().url()); - assertEquals("{\"title\":\"New title\",\"tags\":[\"a\",\"b\"],\"publishAt\":null}", transport.lastBody()); - - client.blog().regenerateArticle("w1", "art_1"); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1/regenerate?workspace_id=w1", transport.last().url()); - client.blog().publishArticle("w1", "art_1"); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1/publish?workspace_id=w1", transport.last().url()); - assertEquals("POST", transport.last().method()); - assertNull(transport.last().body()); - client.blog().rejectArticle("w1", "art_1"); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1/reject?workspace_id=w1", transport.last().url()); - client.blog().deleteArticle("w1", "art_1"); - assertEquals("DELETE", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1?workspace_id=w1", transport.last().url()); - - PaymentRequiredException noCredits = assertThrows( - PaymentRequiredException.class, - () -> client.blog().requestArticle("w1", BlogParams.Article.create().title("Again"))); - assertEquals("insufficient_credits", noCredits.code()); - assertEquals("https://fopost.com/billing", noCredits.upgradeUrl()); - - FoPostException noTarget = assertThrows(FoPostException.class, () -> client.blog().publishArticle("w1", "art_1")); - assertEquals(409, noTarget.status()); - assertEquals("no_target", noTarget.code()); - } - - @Test - void suggestSeedsSendsTheCurrentSeedsAndPromptAndReturnsTheTerms() { - FakeTransport transport = new FakeTransport() - .enqueue(200, "{\"seeds\":[\"schedule posts\",\"best time to post\"]}") - .enqueue(200, "{\"seeds\":[]}") - .enqueue(402, "{\"error\":\"insufficient_credits\",\"message\":\"Balance\"}"); - FoPost client = TestSupport.client(transport); - - List seeds = client.blog().suggestSeeds("w1", List.of("scheduling"), "Small teams"); - assertEquals("POST", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/keywords/suggest", transport.last().url()); - assertEquals( - "{\"workspaceId\":\"w1\",\"seeds\":[\"scheduling\"],\"prompt\":\"Small teams\"}", - transport.lastBody()); - assertEquals(List.of("schedule posts", "best time to post"), seeds); - - assertEquals(List.of(), client.blog().suggestSeeds("w1")); - assertEquals("{\"workspaceId\":\"w1\"}", transport.lastBody()); - - assertThrows(PaymentRequiredException.class, () -> client.blog().suggestSeeds("w1")); - } - - @Test - void submitArticleMovesItToReviewByPath() { - String inReview = ARTICLE.replace("\"status\":\"queued\"", "\"status\":\"in_review\""); - FakeTransport transport = new FakeTransport() - .enqueue(200, inReview) - .enqueue(409, "{\"error\":\"invalid_state\",\"message\":\"Only a draft can be submitted\"}"); - FoPost client = TestSupport.client(transport); - - BlogArticle submitted = client.blog().submitArticle("w1", "art_1"); - assertEquals("POST", transport.last().method()); - assertEquals("https://api.fopost.test/v1/blog/articles/art_1/submit?workspace_id=w1", transport.last().url()); - assertNull(transport.last().body()); - assertEquals(BlogArticleStatus.IN_REVIEW, submitted.status()); - assertTrue(BlogArticleStatus.ALL.contains(submitted.status())); - - FoPostException conflict = assertThrows(FoPostException.class, () -> client.blog().submitArticle("w1", "art_1")); - assertEquals(409, conflict.status()); - assertEquals("invalid_state", conflict.code()); - } -} diff --git a/src/test/java/com/fopost/sdk/WebhookVerifierTest.java b/src/test/java/com/fopost/sdk/WebhookVerifierTest.java index 1e5b41e..8a95d3b 100644 --- a/src/test/java/com/fopost/sdk/WebhookVerifierTest.java +++ b/src/test/java/com/fopost/sdk/WebhookVerifierTest.java @@ -3,7 +3,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import com.fopost.sdk.model.BlogArticlePublished; import com.fopost.sdk.model.WebhookEvents; import java.nio.charset.StandardCharsets; import java.time.Clock; @@ -20,14 +19,8 @@ class WebhookVerifierTest { private static final String BODY = """ - {"event":"article.published","timestamp":"2026-10-11T09:00:00.000Z", - "data":{"id":"art_1","title":"How to schedule posts","slug":"how-to-schedule-posts", - "excerpt":null,"metaTitle":null,"metaDescription":null, - "bodyMarkdown":"# Hi","bodyHtml":"

Hi

", - "featuredImage":{"mediaId":"m_1","url":"https://cdn.example/f.png","alt":"Calendar"}, - "images":[],"tags":["scheduling"],"keyword":"how to schedule posts", - "wordCount":2,"publishedAt":"2026-10-11T09:00:00.000Z", - "publishedUrl":"https://yourbrand.com/blog/how-to-schedule-posts"}}"""; + {"event":"post.published","timestamp":"2026-10-11T09:00:00.000Z", + "data":{"id":"post_1","status":"published","title":"How to schedule posts"}}"""; private static byte[] bytes(String body) { return body.getBytes(StandardCharsets.UTF_8); @@ -41,16 +34,12 @@ private static Map timestamped(String body, long timestamp) { } @Test - void aFreshTimestampedSignaturePassesAndParsesTheArticle() { + void aFreshTimestampedSignaturePassesAndParsesTheEnvelope() { WebhookEnvelope envelope = WebhookVerifier.verify(bytes(BODY), timestamped(BODY, NOW - 10), SECRET, CLOCK); - assertEquals(WebhookEvents.ARTICLE_PUBLISHED, envelope.event()); + assertEquals(WebhookEvents.POST_PUBLISHED, envelope.event()); assertEquals("2026-10-11T09:00:00.000Z", envelope.timestamp()); - BlogArticlePublished article = envelope.data(BlogArticlePublished.class); - assertEquals("how-to-schedule-posts", article.slug()); - assertEquals("Calendar", article.featuredImage().alt()); - assertEquals("https://yourbrand.com/blog/how-to-schedule-posts", article.publishedUrl()); - assertEquals(Instant.parse("2026-10-11T09:00:00Z"), article.publishedAt()); + assertEquals("post_1", envelope.data().path("id").asText()); } @Test @@ -78,7 +67,7 @@ void theBodyOnlySignatureIsAcceptedWhenNoTimestampIsSent() { Map legacy = Map.of("X-FoPost-Signature", WebhookVerifier.sign(bytes(BODY), SECRET)); WebhookEnvelope envelope = WebhookVerifier.verify(BODY, legacy, SECRET); - assertEquals(WebhookEvents.ARTICLE_PUBLISHED, envelope.event()); + assertEquals(WebhookEvents.POST_PUBLISHED, envelope.event()); FoPostException error = assertThrows( FoPostException.class,