diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d4b3e3..a89e18c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,13 @@ All notable changes to `fopost` are documented here. `event_count`, `replayed`) instead of a dict; read `result.accepted` rather than `result["accepted"]`. +### Removed + +- **Breaking:** `client.blog` (`/v1/blog`: settings, website secret and test, keywords and + articles), the `Blog*` models and `BLOG_*` constants, `ArticlePublishedPayload`, and + `article.published` from the webhook event names. The API no longer serves them; articles + are ordinary posts. `client.blogs` is unchanged. + ## 0.4.0 - 2026-10-18 ### Added diff --git a/README.md b/README.md index 6f33a6d..49cfe7f 100644 --- a/README.md +++ b/README.md @@ -122,47 +122,24 @@ repurposed = client.ai.repurpose_url( > `401` to an API key. They are here so the surface is complete once the server > opens them up. -## Blog +## Verifying webhooks -`client.blog` plans keywords, writes articles and publishes them to a website. A post goes -to a social network; an article goes to a website. `suggest_seeds` proposes search terms from -the blog `goal` and topics, `plan_keywords` researches them into `suggested` keywords, and -setting a keyword's status to `planned` puts it on the calendar. A draft is submitted for -approval before it can be published. +`verify_webhook` checks a delivery's signature over the raw body and returns the envelope: ```python -article = client.blog.request_article( - workspace.id, - keyword="best trail running shoes", - instructions="Mention the return policy.", -) -print(article.status) # "queued"; it becomes a draft once written - -for draft in client.blog.list_articles(workspace.id, status="draft"): - client.blog.submit_article(workspace.id, draft.id) - client.blog.publish_article(workspace.id, draft.id) -``` - -With the Website target, every published article is POSTed to your `website_url` as a signed -webhook. `verify_webhook` checks the signature over the raw body and returns the envelope: - -```python -from fopost import ArticlePublishedPayload, verify_webhook +from fopost import verify_webhook @app.post("/webhooks/fopost") async def inbound(request: Request) -> Response: secret = os.environ["FOPOST_WEBHOOK_SECRET"] event = verify_webhook(await request.body(), request.headers, secret) - if event.event == "article.published": - article = ArticlePublishedPayload.model_validate(event.data) - save_article(article.slug, article.body_html) + if event.event == "post.published": + print(event.data["id"]) return Response(status_code=204) ``` -The secret is returned once, when `update_settings(..., website_url=...)` first saves the URL; -`rotate_website_secret` issues a new one. A forged, stale or unsigned delivery raises -`WebhookVerificationError` with a `code`. +A forged, stale or unsigned delivery raises `WebhookVerificationError` with a `code`. ## Analytics @@ -328,7 +305,6 @@ except FopostError as err: | `knowledge` | `list`, `create`, `update`, `delete`, `sync`, `search` | | `ads` | `list`, `external`, `boostable`, `connections`, `sources`, `providers`, `authorize`, `delete_connection`, `boost`, `create`, `refresh`, `set_status`, `delete`, `audiences`, `create_audience`, `search_targeting`, `lead_forms`, `create_lead_form`, `leads`, `account_tree`, `create_campaign`, `get_campaign`, `update_campaign`, `delete_campaign`, `duplicate_campaign`, `create_ad_set`, `get_ad_set`, `update_ad_set`, `delete_ad_set`, `duplicate_ad_set`, `create_network_ad`, `get_network_ad`, `update_network_ad`, `delete_network_ad`, `duplicate_network_ad`, `bulk_set_status`, `creatives`, `create_creative`, `get_creative`, `delete_creative`, `get_audience`, `update_audience`, `delete_audience`, `add_audience_users`, `add_audience_companies`, `estimate_reach`, `insights`, `ad_insights`, `get_lead_form`, `archive_lead_form`, `leads_feed`, `lead_pages`, `subscribe_lead_page`, `unsubscribe_lead_page`, `bid_pricing`, `supply_forecast`, `conversion_rules`, `create_conversion_rule`, `get_conversion_rule`, `update_conversion_rule`, `delete_conversion_rule`, `attach_conversion_rule`, `detach_conversion_rule`, `conversion_metrics`, `send_conversion_events`, `upload_conversions`, `send_conversions`, `conversion_batches`, `pixels`, `create_pixel`, `get_pixel`, `update_pixel`, `share_pixel`, `pixel_stats`, `event_match_quality`, `custom_conversions`, `create_custom_conversion`, `get_custom_conversion`, `update_custom_conversion`, `delete_custom_conversion` | | `google_business` | `get_location`, `update_location`, `get_attributes`, `update_attributes`, `get_menus`, `replace_menus`, `get_services`, `replace_services`, `list_media`, `add_media`, `delete_media`, `list_place_actions`, `create_place_action`, `update_place_action`, `delete_place_action`, `get_verification_options`, `start_verification`, `complete_verification`, `get_performance`, `get_search_keywords`, `assign` | -| `blog` | `get_settings`, `update_settings`, `rotate_website_secret`, `test_website`, `list_keywords`, `suggest_seeds`, `plan_keywords`, `add_keyword`, `update_keyword`, `delete_keyword`, `list_articles`, `request_article`, `get_article`, `update_article`, `regenerate_article`, `submit_article`, `publish_article`, `reject_article`, `delete_article` | | `blogs` | `list_blogs`, `list_articles`, `get_article`, `create_article`, `update_article`, `delete_article`, `list_products`, `update_product` | | `validate` | `post`, `length`, `media`, `subreddit` | | `whatsapp` | `get_profile`, `update_profile`, `request_display_name`, `set_username`, `list_templates`, `list_template_library`, `get_template`, `create_template`, `import_template`, `update_template`, `delete_template`, `list_groups`, `create_group`, `get_group`, `update_group`, `delete_group`, `get_group_invite_link`, `reset_group_invite_link`, `remove_group_participants`, `list_blocked`, `block_users`, `unblock_users`, `get_commerce_settings`, `update_commerce_settings`, `link_catalog`, `list_flows`, `get_flow`, `create_flow`, `update_flow`, `delete_flow`, `upload_flow_json`, `publish_flow`, `deprecate_flow`, `list_flow_responses`, `get_encryption_key_status`, `set_encryption_key`, `get_account_events`, `list_sandbox_sessions`, `create_sandbox_session` | diff --git a/src/fopost/__init__.py b/src/fopost/__init__.py index f857ae0..f961152 100644 --- a/src/fopost/__init__.py +++ b/src/fopost/__init__.py @@ -32,10 +32,6 @@ ) from .models import ( AUTOMATION_TRIGGER_TYPES, - BLOG_ARTICLE_STATUSES, - BLOG_GOALS, - BLOG_KEYWORD_STATUSES, - BLOG_TARGET_KINDS, CONNECT_SESSION_STATUSES, CONVERSION_ACTION_SOURCES, CUSTOM_CONVERSION_EVENT_TYPES, @@ -82,7 +78,6 @@ AnalyticsPlatformTotals, AnalyticsTimeSeries, AnalyticsTodayStats, - ArticlePublishedPayload, Audience, AudienceDemographics, AudienceFilter, @@ -105,18 +100,6 @@ AutomationVersionAuthor, AutomationVersionNode, BidPricing, - BlogArticle, - BlogArticleFull, - BlogArticleImage, - BlogArticleStatus, - BlogGoal, - BlogKeyword, - BlogKeywordStatus, - BlogPlanRun, - BlogSettings, - BlogSettingsUpdate, - BlogTargetKind, - BlogWebsiteTest, BlueskyLanguages, BoostablePost, Broadcast, @@ -608,23 +591,6 @@ "PIXEL_DATA_USE_SETTINGS", "ReachEstimate", "SupplyForecast", - "BLOG_ARTICLE_STATUSES", - "BLOG_GOALS", - "BLOG_KEYWORD_STATUSES", - "BLOG_TARGET_KINDS", - "ArticlePublishedPayload", - "BlogArticle", - "BlogArticleFull", - "BlogArticleImage", - "BlogArticleStatus", - "BlogGoal", - "BlogKeyword", - "BlogKeywordStatus", - "BlogPlanRun", - "BlogSettings", - "BlogSettingsUpdate", - "BlogTargetKind", - "BlogWebsiteTest", "WebhookEvent", "WebhookVerificationError", "verify_webhook", diff --git a/src/fopost/client.py b/src/fopost/client.py index 6ed046f..308274a 100644 --- a/src/fopost/client.py +++ b/src/fopost/client.py @@ -17,7 +17,6 @@ AiResource, AnalyticsResource, AutomationsResource, - BlogResource, BlogsResource, BroadcastsResource, ConnectSessionsResource, @@ -96,7 +95,6 @@ def __init__( self.knowledge = KnowledgeResource(self._http) self.activity = ActivityResource(self._http) self.google_business = GoogleBusinessResource(self._http) - self.blog = BlogResource(self._http) self.whatsapp = WhatsappResource(self._http) self.queue = QueueResource(self._http) self.connect_sessions = ConnectSessionsResource(self._http) diff --git a/src/fopost/models.py b/src/fopost/models.py index 5dd703c..7e985f7 100644 --- a/src/fopost/models.py +++ b/src/fopost/models.py @@ -8,7 +8,7 @@ from __future__ import annotations -from datetime import date, datetime +from datetime import datetime from typing import Any, Generic, Literal, TypeVar from pydantic import AliasChoices, AliasGenerator, BaseModel, ConfigDict @@ -177,20 +177,6 @@ "ReachFrequencyPrediction", "ReachFrequencyResult", "ValueRuleSet", - "BLOG_ARTICLE_STATUSES", - "BLOG_KEYWORD_STATUSES", - "BLOG_TARGET_KINDS", - "ArticlePublishedPayload", - "BlogArticle", - "BlogArticleFull", - "BlogArticleImage", - "BlogArticleStatus", - "BlogKeyword", - "BlogKeywordStatus", - "BlogSettings", - "BlogSettingsUpdate", - "BlogTargetKind", - "BlogWebsiteTest", "WhatsappTemplate", "WhatsappProfile", "WhatsappGroup", @@ -2667,188 +2653,6 @@ class GoogleConversionAction(FopostModel): value_minor: int | None = None -# ── Blog ────────────────────────────────────────────────────────── - -BlogArticleStatus = Literal[ - "queued", - "writing", - "draft", - "in_review", - "scheduled", - "publishing", - "published", - "failed", - "rejected", -] - -BLOG_ARTICLE_STATUSES: tuple[str, ...] = ( - "queued", - "writing", - "draft", - "in_review", - "scheduled", - "publishing", - "published", - "failed", - "rejected", -) - -BlogKeywordStatus = Literal["suggested", "planned", "written", "dismissed"] - -BLOG_KEYWORD_STATUSES: tuple[str, ...] = ("suggested", "planned", "written", "dismissed") - -BlogTargetKind = Literal["product_blog", "account", "website"] - -BLOG_TARGET_KINDS: tuple[str, ...] = ("product_blog", "account", "website") - -BlogGoal = Literal["traffic", "leads", "sales", "signups", "authority"] - -BLOG_GOALS: tuple[str, ...] = ("traffic", "leads", "sales", "signups", "authority") - - -class BlogPlanRun(FopostModel): - """The last keyword research run.""" - - #: ``queued``, ``running``, ``done`` or ``failed``. - status: str - error: str | None = None - #: New keywords the run found. - added: int | None = None - finished_at: datetime | None = None - - -class BlogSettings(FopostModel): - """How a workspace plans, writes and publishes articles.""" - - site_url: str | None = None - topic: str | None = None - audience: str | None = None - #: One of ``BLOG_GOALS``; steers suggested terms and keyword ranking. - goal: str | None = None - #: What the blog wants to write about. - focus_topics: str | None = None - #: What the blog never writes about. - avoid_topics: str | None = None - language: str = "en" - location_code: int | None = None - #: Articles planned per week; 0 turns planning off. - cadence_per_week: int = 0 - #: Days before its planned date that a picked keyword starts being written. - review_hold_days: int = 0 - image_tier: str | None = None - in_body_images: int | None = None - min_words: int | None = None - max_words: int | None = None - brand_voice_id: str | None = None - #: ``product_blog``, ``account`` or ``website``. - target_kind: str | None = None - target_account_id: str | None = None - target_platform: str | None = None - website_url: str | None = None - has_website_secret: bool = False - #: ``None`` before the first run. - plan_run: BlogPlanRun | None = None - keyword_data_available: bool = False - updated_at: datetime | None = None - - -class BlogSettingsUpdate(FopostModel): - """The saved settings, plus the website secret the one time it is issued.""" - - settings: BlogSettings - website_secret: str | None = None - - -class BlogWebsiteTest(FopostModel): - """What the website answered a test delivery it accepted.""" - - http_status: int - - -class BlogKeyword(FopostModel): - id: str - keyword: str - search_volume: int | None = None - #: 0 to 100. - difficulty: int | None = None - cpc: float | None = None - intent: str | None = None - #: ``provider``, ``user`` or ``agent``. - source: str = "user" - #: ``suggested``, ``planned``, ``written`` or ``dismissed``. - status: str = "suggested" - planned_for: date | None = None - #: Why the keyword serves the blog goal. - fit_reason: str | None = None - created_at: datetime | None = None - - -class BlogArticleImage(FopostModel): - media_id: str - url: str - alt: str = "" - #: Index of the outline heading the image sits under; absent on the featured image. - position: int | None = None - - -class BlogArticle(FopostModel): - """An article as a listing returns it, without the body.""" - - id: str - title: str - slug: str - keyword: str | None = None - excerpt: str | None = None - meta_title: str | None = None - meta_description: str | None = None - featured_image: BlogArticleImage | None = None - tags: list[str] = [] - word_count: int = 0 - #: One of ``BLOG_ARTICLE_STATUSES``. - status: str = "queued" - #: ``plan``, ``user`` or ``agent``. - origin: str = "user" - review_until: datetime | None = None - publish_at: datetime | None = None - published_at: datetime | None = None - published_url: str | None = None - error: str | None = None - created_at: datetime | None = None - updated_at: datetime | None = None - - -class BlogArticleFull(BlogArticle): - """One article with its body, outline, brief and images.""" - - instructions: str | None = None - outline: list[str] = [] - #: The research the writer worked from. - brief: dict[str, Any] | None = None - body_markdown: str = "" - body_html: str = "" - images: list[BlogArticleImage] = [] - - -class ArticlePublishedPayload(FopostModel): - """``data`` of the ``article.published`` webhook. Image URLs expire after six hours.""" - - id: str - title: str - slug: str - excerpt: str | None = None - meta_title: str | None = None - meta_description: str | None = None - body_markdown: str = "" - body_html: str = "" - featured_image: BlogArticleImage | None = None - images: list[BlogArticleImage] = [] - tags: list[str] = [] - keyword: str | None = None - word_count: int = 0 - published_at: datetime | None = None - published_url: str | None = None - - # ─── WhatsApp Business ──────────────────────────────────────────── # # The platform owns these resources, so nothing here is a cached copy: a @@ -3037,7 +2841,6 @@ class ConnectSession(FopostModel): "account.connected", "account.disconnected", "account.health_changed", - "article.published", "inbox.comment_received", "inbox.mention_received", "inbox.message_received", diff --git a/src/fopost/resources/__init__.py b/src/fopost/resources/__init__.py index c9ee59a..d335bf6 100644 --- a/src/fopost/resources/__init__.py +++ b/src/fopost/resources/__init__.py @@ -5,7 +5,6 @@ from .ai import AiResource from .analytics import AnalyticsResource from .automations import AutomationsResource -from .blog import BlogResource from .blogs import BlogsResource from .broadcasts import BroadcastsResource, SequencesResource from .connect_sessions import ConnectSessionsResource @@ -36,7 +35,6 @@ "AdsResource", "BlogsResource", "AiResource", - "BlogResource", "BroadcastsResource", "ContactsResource", "SequencesResource", diff --git a/src/fopost/resources/blog.py b/src/fopost/resources/blog.py deleted file mode 100644 index 0981c5f..0000000 --- a/src/fopost/resources/blog.py +++ /dev/null @@ -1,310 +0,0 @@ -"""``client.blog`` — plan keywords, request articles and publish them to a website. - -A post goes to a social network; an article goes to a website. Everything here -is an article. Suggesting seeds, planning, requesting and regenerating spend AI -credits and need the ``ai`` scope; publishing needs ``publish``; the rest needs -``posts``. A draft is submitted for approval before it can be published. - -The workspace travels as ``workspace_id`` on the query string of reads and per-id -routes and as ``workspaceId`` in the body of the collection ``POST``/``PATCH`` -routes. Request bodies are camelCase on the wire and responses snake_case; pass -arguments snake_case here. -""" - -from __future__ import annotations - -import builtins -from collections.abc import Sequence -from typing import Any - -from .._http import unwrap -from ..models import ( - BlogArticle, - BlogArticleFull, - BlogKeyword, - BlogSettings, - BlogSettingsUpdate, - BlogWebsiteTest, - _to_camel, -) -from ._base import UNSET, Resource, drop_unset, parse_list - -__all__ = ["BlogResource"] - - -def _camel_body(fields: dict[str, Any]) -> dict[str, Any]: - return {_to_camel(key): value for key, value in drop_unset(fields).items()} - - -def _statuses(status: str | Sequence[str] | None) -> str | None: - if status is None or isinstance(status, str): - return status - return ",".join(status) - - -class BlogResource(Resource): - # ── Settings ────────────────────────────────────────────────── - - def get_settings(self, workspace_id: str) -> BlogSettings: - body = self._http.get("/blog/settings", {"workspace_id": workspace_id}) - return BlogSettings.model_validate(unwrap(body)) - - def update_settings( - self, - workspace_id: str, - *, - site_url: str | None | Any = UNSET, - topic: str | None | Any = UNSET, - audience: str | None | Any = UNSET, - goal: str | None | Any = UNSET, - focus_topics: str | None | Any = UNSET, - avoid_topics: str | None | Any = UNSET, - language: str | Any = UNSET, - location_code: int | Any = UNSET, - cadence_per_week: int | Any = UNSET, - review_hold_days: int | Any = UNSET, - image_tier: str | Any = UNSET, - in_body_images: int | Any = UNSET, - min_words: int | Any = UNSET, - max_words: int | Any = UNSET, - brand_voice_id: str | None | Any = UNSET, - target_kind: str | None | Any = UNSET, - target_account_id: str | None | Any = UNSET, - website_url: str | None | Any = UNSET, - ) -> BlogSettingsUpdate: - """Patch the settings; an argument left out keeps its value. - - ``website_secret`` on the result is set only the first time - ``website_url`` is saved. Store it then; it is never shown again. - ``review_hold_days`` is how many days before its planned date a picked - keyword starts being written. - """ - body = _camel_body( - { - "site_url": site_url, - "topic": topic, - "audience": audience, - "goal": goal, - "focus_topics": focus_topics, - "avoid_topics": avoid_topics, - "language": language, - "location_code": location_code, - "cadence_per_week": cadence_per_week, - "review_hold_days": review_hold_days, - "image_tier": image_tier, - "in_body_images": in_body_images, - "min_words": min_words, - "max_words": max_words, - "brand_voice_id": brand_voice_id, - "target_kind": target_kind, - "target_account_id": target_account_id, - "website_url": website_url, - } - ) - body["workspaceId"] = workspace_id - raw = self._http.patch("/blog/settings", body) - secret = raw.get("website_secret") if isinstance(raw, dict) else None - return BlogSettingsUpdate( - settings=BlogSettings.model_validate(unwrap(raw)), website_secret=secret - ) - - def rotate_website_secret(self, workspace_id: str) -> str: - """Issue a new website secret; the previous one stops verifying at once.""" - body = self._http.post("/blog/settings/website-secret", {"workspaceId": workspace_id}) - data = unwrap(body) - return str(data["website_secret"]) if isinstance(data, dict) else "" - - def test_website(self, workspace_id: str) -> BlogWebsiteTest: - """Send a signed ``article.test`` delivery to the website target. - - A refusal raises a 502 ``website_test_failed`` carrying the site's answer. - """ - body = self._http.post("/blog/settings/website-test", {"workspaceId": workspace_id}) - return BlogWebsiteTest.model_validate(unwrap(body)) - - # ── Keywords ────────────────────────────────────────────────── - - def list_keywords( - self, - workspace_id: str, - *, - status: str | Sequence[str] | None = None, - limit: int | None = None, - ) -> builtins.list[BlogKeyword]: - body = self._http.get( - "/blog/keywords", - {"workspace_id": workspace_id, "status": _statuses(status), "limit": limit}, - ) - return parse_list(BlogKeyword, unwrap(body)) - - def suggest_seeds( - self, - workspace_id: str, - *, - seeds: Sequence[str] | None = None, - prompt: str | None = None, - ) -> builtins.list[str]: - """About 10 search terms from the blog goal and topics. - - Pass the current ``seeds`` (up to 20) to refine them and ``prompt`` (up to - 500 characters) to steer. An empty balance raises ``PaymentRequiredError``. - """ - payload: dict[str, Any] = {"workspaceId": workspace_id} - if seeds is not None: - payload["seeds"] = builtins.list(seeds) - if prompt is not None: - payload["prompt"] = prompt - data = unwrap(self._http.post("/blog/keywords/suggest", payload)) - found = data.get("seeds") if isinstance(data, dict) else None - return [str(seed) for seed in found] if isinstance(found, builtins.list) else [] - - def plan_keywords( - self, workspace_id: str, *, seeds: Sequence[str] | None = None - ) -> dict[str, Any]: - """Queue a research run; results land as ``suggested`` keywords. - - The calendar is untouched: setting a keyword's status to ``planned`` picks - it. Follow the run in ``plan_run`` on the settings. - """ - payload: dict[str, Any] = {"workspaceId": workspace_id} - if seeds is not None: - payload["seeds"] = builtins.list(seeds) - data = unwrap(self._http.post("/blog/keywords/plan", payload)) - return data if isinstance(data, dict) else {"status": data} - - def add_keyword( - self, workspace_id: str, *, keyword: str, planned_for: str | None = None - ) -> BlogKeyword: - payload: dict[str, Any] = {"workspaceId": workspace_id, "keyword": keyword} - if planned_for is not None: - payload["plannedFor"] = planned_for - return BlogKeyword.model_validate(unwrap(self._http.post("/blog/keywords", payload))) - - def update_keyword( - self, - workspace_id: str, - keyword_id: str, - *, - status: str | Any = UNSET, - planned_for: str | None | Any = UNSET, - ) -> BlogKeyword: - """Setting ``status`` to ``planned`` picks the keyword; it takes the next free date.""" - body = self._http.request( - "PATCH", - f"/blog/keywords/{keyword_id}", - json=_camel_body({"status": status, "planned_for": planned_for}), - params={"workspace_id": workspace_id}, - ) - return BlogKeyword.model_validate(unwrap(body)) - - def delete_keyword(self, workspace_id: str, keyword_id: str) -> None: - self._http.request( - "DELETE", f"/blog/keywords/{keyword_id}", params={"workspace_id": workspace_id} - ) - - # ── Articles ────────────────────────────────────────────────── - - def list_articles( - self, - workspace_id: str, - *, - status: str | Sequence[str] | None = None, - limit: int | None = None, - ) -> builtins.list[BlogArticle]: - body = self._http.get( - "/blog/articles", - {"workspace_id": workspace_id, "status": _statuses(status), "limit": limit}, - ) - return parse_list(BlogArticle, unwrap(body)) - - def request_article( - self, - workspace_id: str, - *, - title: str | None = None, - keyword: str | None = None, - keyword_id: str | None = None, - instructions: str | None = None, - ) -> BlogArticle: - """Queue an article. One of ``title``, ``keyword`` or ``keyword_id`` is required.""" - payload: dict[str, Any] = {"workspaceId": workspace_id} - for key, value in ( - ("title", title), - ("keyword", keyword), - ("keywordId", keyword_id), - ("instructions", instructions), - ): - if value is not None: - payload[key] = value - return BlogArticle.model_validate(unwrap(self._http.post("/blog/articles", payload))) - - def get_article(self, workspace_id: str, article_id: str) -> BlogArticleFull: - body = self._http.get(f"/blog/articles/{article_id}", {"workspace_id": workspace_id}) - return BlogArticleFull.model_validate(unwrap(body)) - - def update_article( - self, - workspace_id: str, - article_id: str, - *, - title: str | Any = UNSET, - slug: str | Any = UNSET, - excerpt: str | None | Any = UNSET, - meta_title: str | None | Any = UNSET, - meta_description: str | None | Any = UNSET, - body_markdown: str | Any = UNSET, - tags: Sequence[str] | Any = UNSET, - publish_at: str | None | Any = UNSET, - ) -> BlogArticleFull: - """Edit an article. - - ``publish_at`` approves an article in review and puts it on the calendar; - ``None`` returns it to review. A draft answers 409 until it is submitted. - """ - body = self._http.request( - "PATCH", - f"/blog/articles/{article_id}", - json=_camel_body( - { - "title": title, - "slug": slug, - "excerpt": excerpt, - "meta_title": meta_title, - "meta_description": meta_description, - "body_markdown": body_markdown, - "tags": builtins.list(tags) if tags is not UNSET else UNSET, - "publish_at": publish_at, - } - ), - params={"workspace_id": workspace_id}, - ) - return BlogArticleFull.model_validate(unwrap(body)) - - def regenerate_article(self, workspace_id: str, article_id: str) -> BlogArticle: - return self._article_action(workspace_id, article_id, "regenerate") - - def submit_article(self, workspace_id: str, article_id: str) -> BlogArticle: - """Move a draft, failed or rejected article to ``in_review``; any other state is a 409.""" - return self._article_action(workspace_id, article_id, "submit") - - def publish_article(self, workspace_id: str, article_id: str) -> BlogArticle: - """Publish an article in review now. - - A draft is a 409 until it is submitted; a 409 ``no_target`` means the - workspace has no target set. - """ - return self._article_action(workspace_id, article_id, "publish") - - def reject_article(self, workspace_id: str, article_id: str) -> BlogArticle: - return self._article_action(workspace_id, article_id, "reject") - - def delete_article(self, workspace_id: str, article_id: str) -> None: - self._http.request( - "DELETE", f"/blog/articles/{article_id}", params={"workspace_id": workspace_id} - ) - - def _article_action(self, workspace_id: str, article_id: str, action: str) -> BlogArticle: - body = self._http.request( - "POST", f"/blog/articles/{article_id}/{action}", params={"workspace_id": workspace_id} - ) - return BlogArticle.model_validate(unwrap(body)) diff --git a/src/fopost/webhooks.py b/src/fopost/webhooks.py index 3dd83ed..adff4b3 100644 --- a/src/fopost/webhooks.py +++ b/src/fopost/webhooks.py @@ -132,8 +132,8 @@ def verify( from fopost import verify_webhook event = verify_webhook(request.body, request.headers, secret) - if event.event == "article.published": - article = ArticlePublishedPayload.model_validate(event.data) + if event.event == "post.published": + post_id = event.data["id"] """ verify_signature(body, headers, secret, tolerance=tolerance) diff --git a/tests/test_blog.py b/tests/test_blog.py deleted file mode 100644 index 2b38fc0..0000000 --- a/tests/test_blog.py +++ /dev/null @@ -1,381 +0,0 @@ -from __future__ import annotations - -import json -from typing import Any - -import httpx -import pytest -import respx - -from fopost import Fopost, FopostError, PaymentRequiredError -from tests.conftest import BASE_URL - -SETTINGS_FIXTURE: dict[str, Any] = { - "site_url": "https://yourbrand.com", - "topic": "Running shoes", - "audience": "Weekend runners", - "goal": "sales", - "focus_topics": "Trail and road shoes", - "avoid_topics": "Injury advice", - "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": 1600, - "brand_voice_id": None, - "target_kind": "website", - "target_account_id": None, - "target_platform": None, - "website_url": "https://yourbrand.com/api/fopost", - "has_website_secret": True, - "plan_run": { - "status": "done", - "error": None, - "added": 12, - "finished_at": "2026-10-10T09:30:00.000Z", - }, - "keyword_data_available": True, - "updated_at": "2026-10-10T09:00:00.000Z", -} - -KEYWORD_FIXTURE: dict[str, Any] = { - "id": "kw_1", - "keyword": "best trail running shoes", - "search_volume": 12000, - "difficulty": 41, - "cpc": 1.2, - "intent": "commercial", - "source": "provider", - "status": "planned", - "planned_for": "2026-10-14", - "fit_reason": "Buyers compare shoes before they pick one.", - "created_at": "2026-10-10T09:00:00.000Z", -} - -ARTICLE_FIXTURE: dict[str, Any] = { - "id": "art_1", - "title": "The Best Trail Running Shoes of the Year", - "slug": "best-trail-running-shoes", - "keyword": "best trail running shoes", - "excerpt": "What to look for on rock, mud and root.", - "meta_title": None, - "meta_description": None, - "featured_image": {"media_id": "med_1", "url": "https://cdn.test/f.jpg", "alt": "Trail"}, - "tags": ["shoes", "trail"], - "word_count": 1240, - "status": "draft", - "origin": "plan", - "review_until": "2026-10-13T09:00:00.000Z", - "publish_at": None, - "published_at": None, - "published_url": None, - "error": None, - "created_at": "2026-10-10T09:00:00.000Z", - "updated_at": "2026-10-10T10:00:00.000Z", -} - -ARTICLE_FULL_FIXTURE: dict[str, Any] = { - **ARTICLE_FIXTURE, - "instructions": "Mention the return policy.", - "outline": ["Why fit matters", "Our picks"], - "brief": {"questions": ["Are trail shoes waterproof?"], "competitors": []}, - "body_markdown": "# The Best Trail Running Shoes\n\nFit first.", - "body_html": "

The Best Trail Running Shoes

Fit first.

", - "images": [ - {"media_id": "med_2", "url": "https://cdn.test/1.jpg", "alt": "Mud", "position": 1}, - ], -} - - -def _json(request: httpx.Request) -> dict[str, Any]: - return dict(json.loads(request.content)) - - -# ── Settings ────────────────────────────────────────────────────── - - -@respx.mock -def test_settings_round_trip(client: Fopost) -> None: - get_route = respx.get(f"{BASE_URL}/blog/settings").mock( - return_value=httpx.Response(200, json=SETTINGS_FIXTURE) - ) - patch_route = respx.patch(f"{BASE_URL}/blog/settings").mock( - return_value=httpx.Response(200, json={**SETTINGS_FIXTURE, "website_secret": "whsec_once"}) - ) - rotate_route = respx.post(f"{BASE_URL}/blog/settings/website-secret").mock( - return_value=httpx.Response(200, json={"website_secret": "whsec_new"}) - ) - test_route = respx.post(f"{BASE_URL}/blog/settings/website-test").mock( - return_value=httpx.Response( - 502, - json={ - "error": "website_test_failed", - "message": "upstream failed", - "http_status": 500, - }, - ) - ) - - settings = client.blog.get_settings("ws_1") - assert settings.cadence_per_week == 2 - assert settings.target_kind == "website" - assert settings.has_website_secret is True - assert settings.goal == "sales" - assert settings.focus_topics == "Trail and road shoes" - assert settings.plan_run is not None and settings.plan_run.added == 12 - assert dict(get_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert get_route.calls.last.request.headers["X-API-Key"] == "osk_test_key" - - updated = client.blog.update_settings( - "ws_1", - website_url="https://yourbrand.com/api/fopost", - cadence_per_week=2, - topic=None, - goal="leads", - focus_topics="Trail shoes", - avoid_topics=None, - ) - assert updated.website_secret == "whsec_once" - assert updated.settings.site_url == "https://yourbrand.com" - assert _json(patch_route.calls.last.request) == { - "workspaceId": "ws_1", - "websiteUrl": "https://yourbrand.com/api/fopost", - "cadencePerWeek": 2, - "topic": None, - "goal": "leads", - "focusTopics": "Trail shoes", - "avoidTopics": None, - } - - assert client.blog.rotate_website_secret("ws_1") == "whsec_new" - assert _json(rotate_route.calls.last.request) == {"workspaceId": "ws_1"} - - with pytest.raises(FopostError) as err: - client.blog.test_website("ws_1") - assert err.value.status == 502 - assert _json(test_route.calls.last.request) == {"workspaceId": "ws_1"} - - -@respx.mock -def test_website_test_reports_the_outcome(client: Fopost) -> None: - respx.post(f"{BASE_URL}/blog/settings/website-test").mock( - return_value=httpx.Response(200, json={"http_status": 200}) - ) - result = client.blog.test_website("ws_1") - assert result.http_status == 200 - - -# ── Keywords ────────────────────────────────────────────────────── - - -@respx.mock -def test_keywords_round_trip(client: Fopost) -> None: - list_route = respx.get(f"{BASE_URL}/blog/keywords").mock( - return_value=httpx.Response(200, json={"data": [KEYWORD_FIXTURE]}) - ) - plan_route = respx.post(f"{BASE_URL}/blog/keywords/plan").mock( - return_value=httpx.Response(202, json={"status": "queued"}) - ) - add_route = respx.post(f"{BASE_URL}/blog/keywords").mock( - return_value=httpx.Response(201, json=KEYWORD_FIXTURE) - ) - patch_route = respx.patch(f"{BASE_URL}/blog/keywords/kw_1").mock( - return_value=httpx.Response(200, json={**KEYWORD_FIXTURE, "status": "dismissed"}) - ) - delete_route = respx.delete(f"{BASE_URL}/blog/keywords/kw_1").mock( - return_value=httpx.Response(204) - ) - - keywords = client.blog.list_keywords("ws_1", status=["suggested", "planned"], limit=50) - assert keywords[0].search_volume == 12000 - assert keywords[0].fit_reason == "Buyers compare shoes before they pick one." - assert str(keywords[0].planned_for) == "2026-10-14" - assert dict(list_route.calls.last.request.url.params) == { - "workspace_id": "ws_1", - "status": "suggested,planned", - "limit": "50", - } - - assert client.blog.plan_keywords("ws_1", seeds=["trail shoes"]) == {"status": "queued"} - assert _json(plan_route.calls.last.request) == {"workspaceId": "ws_1", "seeds": ["trail shoes"]} - - added = client.blog.add_keyword("ws_1", keyword="trail shoes", planned_for="2026-10-14") - assert added.id == "kw_1" - assert _json(add_route.calls.last.request) == { - "workspaceId": "ws_1", - "keyword": "trail shoes", - "plannedFor": "2026-10-14", - } - - dismissed = client.blog.update_keyword("ws_1", "kw_1", status="dismissed", planned_for=None) - assert dismissed.status == "dismissed" - assert dict(patch_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert _json(patch_route.calls.last.request) == {"status": "dismissed", "plannedFor": None} - - assert client.blog.delete_keyword("ws_1", "kw_1") is None - assert dict(delete_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - - -@respx.mock -def test_suggest_seeds(client: Fopost) -> None: - route = respx.post(f"{BASE_URL}/blog/keywords/suggest").mock( - return_value=httpx.Response(200, json={"seeds": ["trail running shoes", "shoe sizing"]}) - ) - - seeds = client.blog.suggest_seeds( - "ws_1", seeds=["trail shoes"], prompt="Lean towards beginners." - ) - assert seeds == ["trail running shoes", "shoe sizing"] - assert _json(route.calls.last.request) == { - "workspaceId": "ws_1", - "seeds": ["trail shoes"], - "prompt": "Lean towards beginners.", - } - - client.blog.suggest_seeds("ws_1") - assert _json(route.calls.last.request) == {"workspaceId": "ws_1"} - - -@respx.mock -def test_suggesting_on_an_empty_balance_is_a_payment_error(client: Fopost) -> None: - respx.post(f"{BASE_URL}/blog/keywords/suggest").mock( - return_value=httpx.Response( - 402, json={"error": "insufficient_credits", "message": "Your balance ran out."} - ) - ) - with pytest.raises(PaymentRequiredError): - client.blog.suggest_seeds("ws_1") - - -@respx.mock -def test_planning_on_an_empty_balance_is_a_payment_error(client: Fopost) -> None: - respx.post(f"{BASE_URL}/blog/keywords/plan").mock( - return_value=httpx.Response( - 402, - json={ - "error": "insufficient_credits", - "message": "Your balance ran out.", - "upgrade_url": "/settings/billing", - }, - ) - ) - with pytest.raises(PaymentRequiredError) as err: - client.blog.plan_keywords("ws_1") - assert err.value.code == "insufficient_credits" - assert err.value.upgrade_url == "/settings/billing" - - -# ── Articles ────────────────────────────────────────────────────── - - -@respx.mock -def test_articles_round_trip(client: Fopost) -> None: - list_route = respx.get(f"{BASE_URL}/blog/articles").mock( - return_value=httpx.Response(200, json={"data": [ARTICLE_FIXTURE]}) - ) - create_route = respx.post(f"{BASE_URL}/blog/articles").mock( - return_value=httpx.Response(202, json={**ARTICLE_FIXTURE, "status": "queued"}) - ) - get_route = respx.get(f"{BASE_URL}/blog/articles/art_1").mock( - return_value=httpx.Response(200, json=ARTICLE_FULL_FIXTURE) - ) - patch_route = respx.patch(f"{BASE_URL}/blog/articles/art_1").mock( - return_value=httpx.Response(200, json=ARTICLE_FULL_FIXTURE) - ) - regenerate_route = respx.post(f"{BASE_URL}/blog/articles/art_1/regenerate").mock( - return_value=httpx.Response(202, json={**ARTICLE_FIXTURE, "status": "writing"}) - ) - publish_route = respx.post(f"{BASE_URL}/blog/articles/art_1/publish").mock( - return_value=httpx.Response(202, json={**ARTICLE_FIXTURE, "status": "publishing"}) - ) - reject_route = respx.post(f"{BASE_URL}/blog/articles/art_1/reject").mock( - return_value=httpx.Response(200, json={**ARTICLE_FIXTURE, "status": "rejected"}) - ) - delete_route = respx.delete(f"{BASE_URL}/blog/articles/art_1").mock( - return_value=httpx.Response(204) - ) - - articles = client.blog.list_articles("ws_1", status="draft", limit=10) - assert articles[0].word_count == 1240 - assert articles[0].featured_image is not None - assert articles[0].featured_image.media_id == "med_1" - assert dict(list_route.calls.last.request.url.params) == { - "workspace_id": "ws_1", - "status": "draft", - "limit": "10", - } - - queued = client.blog.request_article( - "ws_1", keyword_id="kw_1", instructions="Mention the return policy." - ) - assert queued.status == "queued" - assert _json(create_route.calls.last.request) == { - "workspaceId": "ws_1", - "keywordId": "kw_1", - "instructions": "Mention the return policy.", - } - - full = client.blog.get_article("ws_1", "art_1") - assert full.body_markdown.startswith("# The Best") - assert full.images[0].position == 1 - assert full.brief is not None and full.brief["questions"] == ["Are trail shoes waterproof?"] - assert dict(get_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - - client.blog.update_article( - "ws_1", "art_1", title="New title", tags=["shoes"], publish_at="2026-10-15T09:00:00Z" - ) - assert dict(patch_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert _json(patch_route.calls.last.request) == { - "title": "New title", - "tags": ["shoes"], - "publishAt": "2026-10-15T09:00:00Z", - } - - assert client.blog.regenerate_article("ws_1", "art_1").status == "writing" - assert dict(regenerate_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert client.blog.publish_article("ws_1", "art_1").status == "publishing" - assert dict(publish_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert client.blog.reject_article("ws_1", "art_1").status == "rejected" - assert dict(reject_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert client.blog.delete_article("ws_1", "art_1") is None - assert dict(delete_route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - - -@respx.mock -def test_submit_article(client: Fopost) -> None: - route = respx.post(f"{BASE_URL}/blog/articles/art_1/submit").mock( - return_value=httpx.Response(200, json={**ARTICLE_FIXTURE, "status": "in_review"}) - ) - assert client.blog.submit_article("ws_1", "art_1").status == "in_review" - assert dict(route.calls.last.request.url.params) == {"workspace_id": "ws_1"} - assert route.calls.last.request.content == b"" - - -@respx.mock -def test_submitting_a_published_article_is_a_conflict(client: Fopost) -> None: - respx.post(f"{BASE_URL}/blog/articles/art_1/submit").mock( - return_value=httpx.Response( - 409, json={"error": "invalid_state", "message": "Only a draft can be submitted."} - ) - ) - with pytest.raises(FopostError) as err: - client.blog.submit_article("ws_1", "art_1") - assert err.value.status == 409 - assert err.value.code == "invalid_state" - - -@respx.mock -def test_publishing_without_a_target_is_a_conflict(client: Fopost) -> None: - respx.post(f"{BASE_URL}/blog/articles/art_1/publish").mock( - return_value=httpx.Response( - 409, json={"error": "no_target", "message": "Choose where articles go first."} - ) - ) - with pytest.raises(FopostError) as err: - client.blog.publish_article("ws_1", "art_1") - assert type(err.value) is FopostError - assert err.value.status == 409 - assert err.value.code == "no_target" diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py index 6b67fb1..88dd7ee 100644 --- a/tests/test_webhooks.py +++ b/tests/test_webhooks.py @@ -8,27 +8,11 @@ import pytest -from fopost import ArticlePublishedPayload, WebhookVerificationError, verify_webhook, webhooks +from fopost import WebhookVerificationError, verify_webhook, webhooks SECRET = "whsec_test" -PAYLOAD: dict[str, Any] = { - "id": "art_1", - "title": "The Best Trail Running Shoes of the Year", - "slug": "best-trail-running-shoes", - "excerpt": None, - "metaTitle": None, - "metaDescription": None, - "bodyMarkdown": "# Shoes", - "bodyHtml": "

Shoes

", - "featuredImage": {"mediaId": "med_1", "url": "https://cdn.test/f.jpg", "alt": "Trail"}, - "images": [{"mediaId": "med_2", "url": "https://cdn.test/1.jpg", "alt": "Mud", "position": 0}], - "tags": ["shoes"], - "keyword": "trail shoes", - "wordCount": 1240, - "publishedAt": "2026-10-10T09:00:00.000Z", - "publishedUrl": "https://yourbrand.com/blog/best-trail-running-shoes", -} +PAYLOAD: dict[str, Any] = {"id": "post_1", "status": "published"} def _sign(message: bytes) -> str: @@ -37,11 +21,11 @@ def _sign(message: bytes) -> str: def delivery(sent_at: int | None = None) -> tuple[bytes, dict[str, str]]: body = json.dumps( - {"event": "article.published", "data": PAYLOAD, "timestamp": "2026-10-10T09:00:01.000Z"} + {"event": "post.published", "data": PAYLOAD, "timestamp": "2026-10-10T09:00:01.000Z"} ).encode() sent_at = int(time.time()) if sent_at is None else sent_at return body, { - "X-FoPost-Event": "article.published", + "X-FoPost-Event": "post.published", "X-FoPost-Delivery": "dlv_1", "X-FoPost-Timestamp": str(sent_at), "X-FoPost-Signature": _sign(body), @@ -52,13 +36,9 @@ def delivery(sent_at: int | None = None) -> tuple[bytes, dict[str, str]]: def test_a_timestamped_signature_passes_and_the_envelope_is_parsed() -> None: body, headers = delivery() event = verify_webhook(body, headers, SECRET) - assert event.event == "article.published" + assert event.event == "post.published" assert event.timestamp == "2026-10-10T09:00:01.000Z" - article = ArticlePublishedPayload.model_validate(event.data) - assert article.slug == "best-trail-running-shoes" - assert article.featured_image is not None and article.featured_image.media_id == "med_1" - assert article.images[0].position == 0 - assert article.published_url == "https://yourbrand.com/blog/best-trail-running-shoes" + assert event.data == PAYLOAD def test_the_module_path_is_the_same_helper() -> None: @@ -68,7 +48,7 @@ def test_the_module_path_is_the_same_helper() -> None: def test_a_tampered_body_fails() -> None: body, headers = delivery() - tampered = body.replace(b"best-trail", b"worst-trail") + tampered = body.replace(b"post_1", b"post_2") with pytest.raises(WebhookVerificationError) as err: verify_webhook(tampered, headers, SECRET) assert err.value.code == "invalid_signature" @@ -85,7 +65,7 @@ def test_the_body_only_signature_passes_without_a_timestamp() -> None: body, headers = delivery() del headers["X-FoPost-Signature-256"] del headers["X-FoPost-Timestamp"] - assert verify_webhook(body, headers, SECRET).event == "article.published" + assert verify_webhook(body, headers, SECRET).event == "post.published" def test_the_body_only_signature_is_ignored_when_the_timestamped_one_is_present() -> None: @@ -99,7 +79,7 @@ def test_the_body_only_signature_is_ignored_when_the_timestamped_one_is_present( def test_header_lookup_is_case_insensitive() -> None: body, headers = delivery() lowered = {key.lower(): value for key, value in headers.items()} - assert verify_webhook(body.decode(), lowered, SECRET).event == "article.published" + assert verify_webhook(body.decode(), lowered, SECRET).event == "post.published" def test_a_missing_secret_is_refused() -> None: