diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e58dc8..5fac58a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ All notable changes to `fopost` are documented here. ### Added +- `client.designs`: `list`, `create`, `get`, `update` (returns a `DesignSaveResult` with the + `design` and the saved `version`), `delete`, `versions` (`include_document=True` adds + each version's document), `restore_version`, `duplicate`, `export` (`png`, `jpg`, `pdf`, + `mp4` or `gif` into the media library), `bulk_create` (one design per row), `posts`, + `text_to_slides` and `from_post`. The design `document` is a plain dict. +- `client.fonts`: `list` (the built-in library plus a workspace's uploads), `upload` (a + path, an open binary file, or `(filename, bytes, mime_type)`) and `delete`. +- `client.video_edits`: `ops`, `list`, `create` with `operations` as + `{"op": ..., "params": {...}}` dicts or `VideoEditOperation`s, and `get`. +- `media.generate_alt_text(media_id)` returns an `AltTextResult`. Uses AI credits. +- Models `Design`, `DesignVersion`, `DesignSaveResult`, `DesignDeleteResult`, + `DesignExport`, `DesignExportFile`, `DesignPost`, `TextToSlidesResult`, `SlideCover`, + `SlidePoint`, `SlidesBrand`, `FontList`, `LibraryFont`, `LibraryFontFile`, + `UploadedFont`, `VideoEdit`, `VideoEditOperation`, `VideoEditOpInfo`, + `VideoEditResultMedia`, `VideoEditOutput`, `AltTextResult`, and the tuples + `DESIGN_KINDS`, `VIDEO_EDIT_OPS`, `VIDEO_EDIT_STATUSES`. - `posts.validate_bulk_import` and `posts.commit_bulk_import` take an optional `accounts` list (account ids or platform names), sent comma-separated and applied to every CSV row whose own `accounts` cell is empty. diff --git a/CLAUDE.md b/CLAUDE.md index 71d5e41..bf40bf2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,6 +50,7 @@ src/fopost/ posts.py accounts.py account_groups.py workspaces.py labels.py ai.py inbox.py contacts.py broadcasts.py ads.py media.py analytics.py queue.py connect_sessions.py webhook_endpoints.py automations.py logs.py + designs.py fonts.py video_edits.py ``` Request flow: a resource method builds a snake_case body/params dict, calls @@ -116,12 +117,14 @@ preflight/unpublish/deliveries, bulk import validate/commit/rollback, `schedule= create and update), accounts (list/get/health/update/move, X communities, Telegram connect code and bot commands, Slack channels, members and posting identity, …), account_groups (list/create/get/update/delete/set_members), workspaces (list/get/create/update/delete), labels -(list/create/get/update/delete), media (list/upload/delete/limits/presign/complete/upload_direct), +(list/create/get/update/delete), media (list/upload/delete/limits/presign/complete/upload_direct/generate_alt_text), ai (credits/generate_caption/rewrite/repurpose_url), inbox (the `/v1/inbox` family except the X Chat routes), ads (the `/v1/ads` family), validate (post/length/media), analytics (dashboard reads plus decay/frequency/timeline/changes), queue (slots CRUD, next, preview), connect_sessions (create/get), webhook_endpoints (CRUD, test, deliveries, redeliver), automations (CRUD, toggle, -stats, versions, runs), logs (list). **`client.webhook_endpoints` manages outbound endpoints; +stats, versions, runs), logs (list), designs (CRUD, versions, restore, duplicate, export, bulk, +posts, text-to-slides, from-post; `document` is a plain dict), fonts (list/upload/delete), +video_edits (ops/list/create/get; no wait helper). **`client.webhook_endpoints` manages outbound endpoints; `fopost.webhooks` (the module) verifies the deliveries they receive** — the names differ on purpose so `from fopost import webhooks` keeps meaning the verifier. The checker in `fopost-api-collections` (`scripts/sdk-gaps.mjs`) must report no gap before a release. Adding a diff --git a/README.md b/README.md index 2a8abdc..8c9467c 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,41 @@ The SDK picks the route: when every file fits in a multipart request it sends on otherwise it uploads each file directly and attaches the results before sending the post. On `update` with no `content`, the files are appended to the post's first block. +## Designs and video edits + +A design's `document` is the editor document, sent and returned as a plain dict. +`update` and `restore_version` return a `DesignSaveResult` with the `design` and the +`version` that call saved, if any. `export` renders pages into the media library: + +```python +design = client.designs.create(workspace_id=workspace.id, kind="post", name="Launch") +client.designs.update(design.id, document=document, create_version=True) +export = client.designs.export(design.id, format="png") +print([f.media_id for f in export.files]) +``` + +`fonts.upload` takes a path, an open binary file, or `(filename, bytes, mime_type)`: + +```python +font = client.fonts.upload(workspace_id=workspace.id, file="BrandSans-Bold.woff2", weight=700) +``` + +A video edit runs a library video through `operations` in order and finishes in the +background. `video_edits.ops()` lists every operation and whether it uses AI credits; +poll `get` until `status` is `succeeded` or `failed`: + +```python +edit = client.video_edits.create( + media_id=video.id, + operations=[{"op": "trim", "params": {"start": 0, "end": 30}}, {"op": "denoise"}], +) +edit = client.video_edits.get(edit.id) +print(edit.status, edit.result_media_id) +``` + +`media.generate_alt_text(media_id)` describes a library image with AI and saves it as +the item's alt text. + ## Configuration ```python @@ -294,7 +329,7 @@ except FopostError as err: | `account_groups` | `list`, `create`, `get`, `update`, `delete`, `set_members` | | `workspaces` | `list`, `get`, `create`, `update`, `delete` | | `labels` | `list`, `create`, `get`, `update`, `delete` | -| `media` | `list`, `upload`, `delete`, `limits`, `presign`, `complete`, `upload_direct` | +| `media` | `list`, `upload`, `delete`, `limits`, `presign`, `complete`, `upload_direct`, `generate_alt_text` | | `ai` | `credits`, `generate_caption`, `rewrite`, `repurpose_url` | | `inbox` | `list`, `threads`, `conversations`, `unread_count`, `accounts`, `platforms`, `mark_thread_read`, `refresh`, `resolve`, `update`, `edit_comment`, `reply`, `hide`, `unhide`, `delete`, `like`, `unlike`, `repost`, `unrepost`, `bookmark`, `unbookmark`, `vote`, `pin`, `unpin`, `react`, `start_conversation`, `set_typing`, `handover`, `list_approvals`, `approve_reply`, `reject_reply` | | `inbox` | `list`, `threads`, `conversations`, `unread_count`, `accounts`, `platforms`, `mark_thread_read`, `refresh`, `resolve`, `update`, `edit_comment`, `reply`, `hide`, `unhide`, `delete`, `like`, `unlike`, `repost`, `unrepost`, `bookmark`, `unbookmark`, `vote`, `pin`, `unpin`, `react`, `start_conversation`, `set_typing`, `list_approvals`, `approve_reply`, `reject_reply` | @@ -315,6 +350,9 @@ except FopostError as err: | `webhook_endpoints` | `list`, `create`, `update`, `delete`, `test`, `deliveries`, `get_delivery`, `redeliver` | | `automations` | `list`, `create`, `get`, `update`, `delete`, `toggle`, `stats`, `versions`, `get_version`, `restore_version`, `runs`, `get_run` | | `logs` | `list` | +| `designs` | `list`, `create`, `get`, `update`, `delete`, `versions`, `restore_version`, `duplicate`, `export`, `bulk_create`, `posts`, `text_to_slides`, `from_post` | +| `fonts` | `list`, `upload`, `delete` | +| `video_edits` | `ops`, `list`, `create`, `get` | For an endpoint the SDK does not wrap yet, `client.request` sends an authenticated call and hands back the decoded body: diff --git a/src/fopost/__init__.py b/src/fopost/__init__.py index f961152..c72b68c 100644 --- a/src/fopost/__init__.py +++ b/src/fopost/__init__.py @@ -35,9 +35,12 @@ CONNECT_SESSION_STATUSES, CONVERSION_ACTION_SOURCES, CUSTOM_CONVERSION_EVENT_TYPES, + DESIGN_KINDS, PIXEL_DATA_USE_SETTINGS, PLATFORMS, POST_STATUSES, + VIDEO_EDIT_OPS, + VIDEO_EDIT_STATUSES, WEBHOOK_EVENTS, AccountGroup, AccountMove, @@ -70,6 +73,7 @@ AdSource, AiCreditBalance, AiCredits, + AltTextResult, AnalyticsAccountSummary, AnalyticsCollectError, AnalyticsCollectResult, @@ -141,6 +145,13 @@ DemographicAccountRef, DemographicBucket, DemographicDimensions, + Design, + DesignDeleteResult, + DesignExport, + DesignExportFile, + DesignPost, + DesignSaveResult, + DesignVersion, DiscordChannel, DiscordIdentity, DiscordMember, @@ -153,6 +164,7 @@ ExternalAd, FeedLead, FollowerHistoryPoint, + FontList, FrequencyBand, FrequencyBest, FrequencyWeek, @@ -214,6 +226,8 @@ LeadPageSubscription, LeadsFeedPage, LeadsPage, + LibraryFont, + LibraryFontFile, LinkedInMention, MatchKeyCoverage, MediaItem, @@ -278,6 +292,9 @@ SlackChannel, SlackIdentity, SlackMember, + SlideCover, + SlidePoint, + SlidesBrand, SocialAccount, SparkPost, SubredditCheck, @@ -287,6 +304,7 @@ TelegramBotCommands, TelegramConnectCode, TelegramConnectStatus, + TextToSlidesResult, TikTokCreatorInfo, TikTokMusic, TikTokPlace, @@ -301,6 +319,7 @@ TopPostPlatform, UnpublishDelivery, UnpublishResult, + UploadedFont, UploadLimits, UploadLimitTier, ValidateLengthCheck, @@ -308,6 +327,11 @@ ValidateMediaResult, ValidatePlatformCheck, ValidatePostResult, + VideoEdit, + VideoEditOperation, + VideoEditOpInfo, + VideoEditOutput, + VideoEditResultMedia, WebhookDelivery, WebhookEndpoint, WebhookSubscription, @@ -342,6 +366,30 @@ FoPost = Fopost __all__ = [ + "AltTextResult", + "DESIGN_KINDS", + "Design", + "DesignDeleteResult", + "DesignExport", + "DesignExportFile", + "DesignPost", + "DesignSaveResult", + "DesignVersion", + "FontList", + "LibraryFont", + "LibraryFontFile", + "SlideCover", + "SlidePoint", + "SlidesBrand", + "TextToSlidesResult", + "UploadedFont", + "VIDEO_EDIT_OPS", + "VIDEO_EDIT_STATUSES", + "VideoEdit", + "VideoEditOpInfo", + "VideoEditOperation", + "VideoEditOutput", + "VideoEditResultMedia", "AccountGroup", "AccountMove", "AccountPrimary", diff --git a/src/fopost/client.py b/src/fopost/client.py index 308274a..ecf7010 100644 --- a/src/fopost/client.py +++ b/src/fopost/client.py @@ -21,6 +21,8 @@ BroadcastsResource, ConnectSessionsResource, ContactsResource, + DesignsResource, + FontsResource, GoogleBusinessResource, InboxResource, KnowledgeResource, @@ -31,6 +33,7 @@ QueueResource, SequencesResource, ValidateResource, + VideoEditsResource, WebhookEndpointsResource, WhatsappResource, WorkspacesResource, @@ -102,6 +105,9 @@ def __init__( self.webhook_endpoints = WebhookEndpointsResource(self._http) self.automations = AutomationsResource(self._http) self.logs = LogsResource(self._http) + self.designs = DesignsResource(self._http) + self.fonts = FontsResource(self._http) + self.video_edits = VideoEditsResource(self._http) @property def base_url(self) -> str: diff --git a/src/fopost/models.py b/src/fopost/models.py index 7e985f7..25e8543 100644 --- a/src/fopost/models.py +++ b/src/fopost/models.py @@ -14,6 +14,31 @@ from pydantic import AliasChoices, AliasGenerator, BaseModel, ConfigDict __all__ = [ + "AltTextResult", + "DESIGN_KINDS", + "Design", + "DesignDeleteResult", + "DesignExport", + "DesignExportFile", + "DesignKind", + "DesignPost", + "DesignSaveResult", + "DesignVersion", + "FontList", + "LibraryFont", + "LibraryFontFile", + "SlideCover", + "SlidePoint", + "SlidesBrand", + "TextToSlidesResult", + "UploadedFont", + "VIDEO_EDIT_OPS", + "VIDEO_EDIT_STATUSES", + "VideoEdit", + "VideoEditOpInfo", + "VideoEditOperation", + "VideoEditOutput", + "VideoEditResultMedia", "AccountGroup", "RemoteArticle", "RemoteBlog", @@ -3468,3 +3493,209 @@ class AnalyticsCollectResult(FopostModel): demographics: int = 0 errors: int = 0 error_details: list[AnalyticsCollectError] = [] + + +# --- Designs --------------------------------------------------------------- + +DESIGN_KINDS: tuple[str, ...] = ("story", "post", "carousel", "thumbnail", "card", "collage") + +DesignKind = Literal["story", "post", "carousel", "thumbnail", "card", "collage"] + + +class Design(FopostModel): + """A design. ``document`` is the editor document, passed through as a plain dict.""" + + id: str + name: str | None = None + kind: DesignKind | str | None = None + width: int | None = None + height: int | None = None + document: dict[str, Any] | None = None + thumbnail_media_id: str | None = None + thumbnail_url: str | None = None + created_at: datetime | None = None + updated_at: datetime | None = None + + +class DesignVersion(FopostModel): + id: str + version: int | None = None + document: dict[str, Any] | None = None + created_at: datetime | None = None + + +class DesignSaveResult(FopostModel): + """A design after an update or restore, plus the version that call saved (if any).""" + + design: Design + version: DesignVersion | None = None + + +class DesignDeleteResult(FopostModel): + id: str + deleted: bool = True + + +class DesignExportFile(FopostModel): + media_id: str + page_index: int | None = None + mime_type: str | None = None + preview_url: str | None = None + + +class DesignExport(FopostModel): + format: str + files: list[DesignExportFile] = [] + + +class DesignPost(FopostModel): + """A post that uses a design's exports.""" + + id: str + status: str | None = None + title: str | None = None + text: str | None = None + schedule_at: datetime | None = None + published_at: datetime | None = None + platforms: list[str] = [] + engagement: int | None = None + views: int | None = None + + +class SlidePoint(FopostModel): + heading: str = "" + body: str = "" + + +class SlideCover(FopostModel): + title: str = "" + subtitle: str = "" + + +class SlidesBrand(FopostModel): + colors: list[str] = [] + fonts: dict[str, str] = {} + logo_media_id: str | None = None + + +class TextToSlidesResult(FopostModel): + """Slide copy drafted from text or a post, ready to lay out as a carousel.""" + + cover: SlideCover | None = None + slides: list[SlidePoint] = [] + cta: SlidePoint | None = None + brand: SlidesBrand | None = None + + +# --- Fonts ----------------------------------------------------------------- + + +class LibraryFontFile(FopostModel): + path: str | None = None + subset: str | None = None + weight: int | str | None = None + style: str | None = None + unicode_range: str | None = None + + +class LibraryFont(FopostModel): + """A font that ships with FoPost.""" + + slug: str + family: str + category: str | None = None + scripts: list[str] = [] + weights: list[int] = [] + files: list[LibraryFontFile] = [] + + +class UploadedFont(FopostModel): + """A font file uploaded into a workspace.""" + + id: str + family: str + style: Literal["normal", "italic"] | str = "normal" + weight: int = 400 + format: str | None = None + file_url: str | None = None + created_at: datetime | None = None + + +class FontList(FopostModel): + library: list[LibraryFont] = [] + uploaded: list[UploadedFont] = [] + + +# --- Video edits ----------------------------------------------------------- + +VIDEO_EDIT_OPS: tuple[str, ...] = ( + "trim", + "cut", + "speed", + "merge", + "volume", + "remove_silence", + "denoise", + "subtitles", + "translate_subtitles", + "clips", + "music", + "voiceover", + "watermark", + "cover", + "reframe", + "audiogram", +) + +VIDEO_EDIT_STATUSES: tuple[str, ...] = ("queued", "running", "succeeded", "failed") + + +class VideoEditOpInfo(FopostModel): + name: str + available: bool = False + uses_ai: bool = False + + +class VideoEditOperation(FopostModel): + op: str + params: dict[str, Any] = {} + + +class VideoEditResultMedia(FopostModel): + id: str + preview_url: str | None = None + mime_type: str | None = None + + +class VideoEditOutput(FopostModel): + media_id: str + label: str | None = None + mime: str | None = None + preview_url: str | None = None + + +class VideoEdit(FopostModel): + """A video edit job: one source video run through ``operations`` in order.""" + + id: str + status: Literal["queued", "running", "succeeded", "failed"] | str + progress: float | None = None + source_media_id: str | None = None + operations: list[VideoEditOperation] = [] + result_media_id: str | None = None + result_media: VideoEditResultMedia | None = None + extra_outputs: list[VideoEditOutput] = [] + result: dict[str, Any] | None = None + error: str | None = None + created_at: datetime | None = None + updated_at: datetime | None = None + completed_at: datetime | None = None + + +# --- Alt text -------------------------------------------------------------- + + +class AltTextResult(FopostModel): + alt_text: str + alt_text_source: str | None = None + tags: list[str] = [] diff --git a/src/fopost/resources/__init__.py b/src/fopost/resources/__init__.py index d335bf6..8f0fdb0 100644 --- a/src/fopost/resources/__init__.py +++ b/src/fopost/resources/__init__.py @@ -9,6 +9,8 @@ from .broadcasts import BroadcastsResource, SequencesResource from .connect_sessions import ConnectSessionsResource from .contacts import ContactsResource +from .designs import DesignsResource +from .fonts import FontsResource from .google_business import GoogleBusinessResource from .inbox import InboxResource from .knowledge import KnowledgeResource @@ -18,6 +20,7 @@ from .posts import PostsResource from .queue import QueueResource from .validate import ValidateResource +from .video_edits import VideoEditsResource from .webhook_endpoints import WebhookEndpointsResource from .whatsapp import WhatsappResource from .workspaces import WorkspacesResource @@ -37,6 +40,9 @@ "AiResource", "BroadcastsResource", "ContactsResource", + "DesignsResource", + "FontsResource", + "VideoEditsResource", "SequencesResource", "GoogleBusinessResource", "InboxResource", diff --git a/src/fopost/resources/designs.py b/src/fopost/resources/designs.py new file mode 100644 index 0000000..2641622 --- /dev/null +++ b/src/fopost/resources/designs.py @@ -0,0 +1,193 @@ +"""``client.designs`` — designs, their versions, exports and bulk variants.""" + +from __future__ import annotations + +import builtins +from collections.abc import Mapping, Sequence +from typing import Any + +from .._http import unwrap +from ..models import ( + Design, + DesignDeleteResult, + DesignExport, + DesignPost, + DesignSaveResult, + DesignVersion, + TextToSlidesResult, +) +from ._base import UNSET, Resource, drop_unset, parse_list + +__all__ = ["DesignsResource"] + + +def _save_result(body: Any) -> DesignSaveResult: + raw = body if isinstance(body, dict) else {} + return DesignSaveResult.model_validate( + {"design": raw.get("data"), "version": raw.get("version")} + ) + + +class DesignsResource(Resource): + def list( + self, + *, + workspace_id: str, + kind: str | None = None, + limit: int | None = None, + offset: int | None = None, + ) -> builtins.list[Design]: + """Designs in a workspace, without their documents.""" + body = self._http.get( + "/designs", + {"workspace_id": workspace_id, "kind": kind, "limit": limit, "offset": offset}, + ) + return parse_list(Design, unwrap(body)) + + def create( + self, + *, + workspace_id: str, + kind: str, + name: str | None = None, + document: Mapping[str, Any] | None = None, + brand_voice_id: str | None = None, + ) -> Design: + body: dict[str, Any] = {"workspace_id": workspace_id, "kind": kind} + optional = { + "name": name, + "document": dict(document) if document is not None else None, + "brand_voice_id": brand_voice_id, + } + body.update({k: v for k, v in optional.items() if v is not None}) + return Design.model_validate(unwrap(self._http.post("/designs", body))) + + def get(self, design_id: str) -> Design: + return Design.model_validate(unwrap(self._http.get(f"/designs/{design_id}"))) + + def update( + self, + design_id: str, + *, + name: str | Any = UNSET, + kind: str | Any = UNSET, + document: Mapping[str, Any] | Any = UNSET, + create_version: bool | Any = UNSET, + ) -> DesignSaveResult: + """Partial update. ``create_version=True`` also saves a version of the document.""" + body = drop_unset( + { + "name": name, + "kind": kind, + "document": dict(document) if document is not UNSET else UNSET, + "create_version": create_version, + } + ) + return _save_result(self._http.patch(f"/designs/{design_id}", body)) + + def delete(self, design_id: str) -> DesignDeleteResult: + return DesignDeleteResult.model_validate(unwrap(self._http.delete(f"/designs/{design_id}"))) + + def versions( + self, design_id: str, *, include_document: bool = False + ) -> builtins.list[DesignVersion]: + """Saved versions, newest first. Documents are left out unless asked for.""" + body = self._http.get( + f"/designs/{design_id}/versions", + {"include": "document" if include_document else None}, + ) + return parse_list(DesignVersion, unwrap(body)) + + def restore_version(self, design_id: str, version_id: str) -> DesignSaveResult: + return _save_result(self._http.post(f"/designs/{design_id}/versions/{version_id}/restore")) + + def duplicate(self, design_id: str, *, name: str | None = None) -> Design: + body = {"name": name} if name is not None else {} + return Design.model_validate( + unwrap(self._http.post(f"/designs/{design_id}/duplicate", body)) + ) + + def export( + self, + design_id: str, + *, + format: str, + page_indexes: Sequence[int] | None = None, + duration_sec: int | None = None, + ) -> DesignExport: + """Render to ``png``, ``jpg``, ``pdf``, ``mp4`` or ``gif``; files land in the library.""" + body: dict[str, Any] = {"format": format} + if page_indexes is not None: + body["page_indexes"] = builtins.list(page_indexes) + if duration_sec is not None: + body["duration_sec"] = duration_sec + return DesignExport.model_validate( + unwrap(self._http.post(f"/designs/{design_id}/export", body)) + ) + + def bulk_create( + self, + design_id: str, + *, + rows: Sequence[Mapping[str, Any]], + name_column: str | None = None, + ) -> builtins.list[Design]: + """One new design per row, filling the template's fields from the row's columns.""" + body: dict[str, Any] = {"rows": [dict(row) for row in rows]} + if name_column is not None: + body["name_column"] = name_column + return parse_list(Design, unwrap(self._http.post(f"/designs/{design_id}/bulk", body))) + + def posts(self, design_id: str) -> builtins.list[DesignPost]: + """Posts that use this design's exports.""" + return parse_list(DesignPost, unwrap(self._http.get(f"/designs/{design_id}/posts"))) + + def text_to_slides( + self, + *, + workspace_id: str, + text: str | None = None, + post_id: str | None = None, + max_slides: int | None = None, + brand_voice_id: str | None = None, + ) -> TextToSlidesResult: + """Draft carousel slide copy from ``text`` or a post. Uses AI credits.""" + body: dict[str, Any] = {"workspace_id": workspace_id} + optional = { + "text": text, + "post_id": post_id, + "max_slides": max_slides, + "brand_voice_id": brand_voice_id, + } + body.update({k: v for k, v in optional.items() if v is not None}) + return TextToSlidesResult.model_validate( + unwrap(self._http.post("/designs/text-to-slides", body)) + ) + + def from_post( + self, + *, + workspace_id: str, + text: str | None = None, + post_id: str | None = None, + style: str | None = None, + preset: str | None = None, + account_id: str | None = None, + carousel: bool | None = None, + name: str | None = None, + brand_voice_id: str | None = None, + ) -> Design: + """Create a design from ``text`` or a post's text.""" + body: dict[str, Any] = {"workspace_id": workspace_id} + optional = { + "text": text, + "post_id": post_id, + "style": style, + "preset": preset, + "account_id": account_id, + "carousel": carousel, + "name": name, + "brand_voice_id": brand_voice_id, + } + body.update({k: v for k, v in optional.items() if v is not None}) + return Design.model_validate(unwrap(self._http.post("/designs/from-post", body))) diff --git a/src/fopost/resources/fonts.py b/src/fopost/resources/fonts.py new file mode 100644 index 0000000..2eaf1f5 --- /dev/null +++ b/src/fopost/resources/fonts.py @@ -0,0 +1,45 @@ +"""``client.fonts`` — the built-in font library and a workspace's uploaded fonts.""" + +from __future__ import annotations + +from typing import Any + +from .._http import unwrap +from ..models import FontList, UploadedFont +from ._base import Resource +from .posts import FileInput, _read_file + +__all__ = ["FontsResource"] + + +class FontsResource(Resource): + def list(self, *, workspace_id: str | None = None) -> FontList: + """The built-in library, plus the workspace's uploads when ``workspace_id`` is set.""" + return FontList.model_validate( + unwrap(self._http.get("/fonts", {"workspace_id": workspace_id})) + ) + + def upload( + self, + *, + workspace_id: str, + file: FileInput, + family: str | None = None, + weight: int | None = None, + style: str | None = None, + ) -> UploadedFont: + """Upload a font file: a path, an open binary file, or ``(filename, bytes, mime)``.""" + fields: dict[str, Any] = {"workspace_id": workspace_id} + if family is not None: + fields["family"] = family + if weight is not None: + fields["weight"] = str(weight) + if style is not None: + fields["style"] = style + body = self._http.send_multipart( + "POST", "/fonts", fields=fields, files=[("file", _read_file(file))] + ) + return UploadedFont.model_validate(unwrap(body)) + + def delete(self, font_id: str) -> None: + self._http.delete(f"/fonts/{font_id}") diff --git a/src/fopost/resources/media.py b/src/fopost/resources/media.py index 070e4cc..aa522aa 100644 --- a/src/fopost/resources/media.py +++ b/src/fopost/resources/media.py @@ -8,7 +8,7 @@ from .._http import unwrap from ..errors import error_from_response -from ..models import MediaItem, Page, PageMeta, PresignedUpload, UploadLimits +from ..models import AltTextResult, MediaItem, Page, PageMeta, PresignedUpload, UploadLimits from ._base import Resource, parse_list __all__ = ["MediaResource"] @@ -86,6 +86,10 @@ def delete(self, media_id: str) -> None: """Remove the stored file and the library record.""" self._http.delete(f"/media/{media_id}") + def generate_alt_text(self, media_id: str) -> AltTextResult: + """Describe a library image with AI and save it as the item's alt text. Uses AI credits.""" + return AltTextResult.model_validate(unwrap(self._http.post(f"/media/{media_id}/alt-text"))) + def limits(self, *, workspace_id: str | None = None) -> UploadLimits: """The upload ceilings for the caller's account.""" return UploadLimits.model_validate( diff --git a/src/fopost/resources/video_edits.py b/src/fopost/resources/video_edits.py new file mode 100644 index 0000000..3b2e00a --- /dev/null +++ b/src/fopost/resources/video_edits.py @@ -0,0 +1,64 @@ +"""``client.video_edits`` — run a library video through a chain of edit operations.""" + +from __future__ import annotations + +import builtins +from collections.abc import Mapping, Sequence +from typing import Any + +from .._http import unwrap +from ..models import VideoEdit, VideoEditOperation, VideoEditOpInfo +from ._base import Resource, parse_list + +__all__ = ["VideoEditsResource"] + +OperationInput = Mapping[str, Any] | VideoEditOperation + + +def _operation(op: OperationInput) -> dict[str, Any]: + if isinstance(op, VideoEditOperation): + return {"op": op.op, "params": dict(op.params)} + out: dict[str, Any] = {"op": op["op"]} + if op.get("params") is not None: + out["params"] = dict(op["params"]) + return out + + +class VideoEditsResource(Resource): + def ops(self) -> builtins.list[VideoEditOpInfo]: + """Every operation, whether it is available here, and whether it uses AI credits.""" + return parse_list(VideoEditOpInfo, unwrap(self._http.get("/video-edits/ops"))) + + def list( + self, + *, + workspace_id: str | None = None, + media_id: str | None = None, + limit: int | None = None, + ) -> builtins.list[VideoEdit]: + body = self._http.get( + "/video-edits", + {"workspace_id": workspace_id, "media_id": media_id, "limit": limit}, + ) + return parse_list(VideoEdit, unwrap(body)) + + def create( + self, + *, + media_id: str, + operations: Sequence[OperationInput], + workspace_id: str | None = None, + ) -> VideoEdit: + """Queue an edit. ``operations`` are ``{"op": ..., "params": {...}}`` applied in order.""" + body: dict[str, Any] = { + "media_id": media_id, + "operations": [_operation(op) for op in operations], + } + if workspace_id is not None: + body["workspace_id"] = workspace_id + return VideoEdit.model_validate(unwrap(self._http.post("/video-edits", body))) + + def get(self, edit_id: str, *, workspace_id: str | None = None) -> VideoEdit: + return VideoEdit.model_validate( + unwrap(self._http.get(f"/video-edits/{edit_id}", {"workspace_id": workspace_id})) + ) diff --git a/tests/test_designs.py b/tests/test_designs.py new file mode 100644 index 0000000..728f12f --- /dev/null +++ b/tests/test_designs.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import json + +import httpx +import respx + +from fopost import Fopost +from tests.conftest import BASE_URL + +DOCUMENT = {"version": 1, "width": 1080, "height": 1080, "pages": [{"elements": []}]} + +DESIGN = { + "id": "des_1", + "name": "Launch", + "kind": "post", + "width": 1080, + "height": 1080, + "document": DOCUMENT, + "thumbnail_media_id": "med_9", + "thumbnail_url": "https://api.test.fopost.com/v1/media/med_9/file", + "created_at": "2026-11-20T10:00:00.000Z", + "updated_at": "2026-11-20T10:05:00.000Z", +} + +VERSION = {"id": "ver_1", "version": 3, "created_at": "2026-11-20T10:05:00.000Z"} + + +@respx.mock +def test_list_sends_filters_and_maps_designs(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/designs").mock( + return_value=httpx.Response(200, json={"data": [{**DESIGN, "document": None}]}) + ) + + designs = client.designs.list(workspace_id="ws_1", kind="post", limit=10, offset=20) + + assert dict(route.calls.last.request.url.params) == { + "workspace_id": "ws_1", + "kind": "post", + "limit": "10", + "offset": "20", + } + assert designs[0].id == "des_1" + assert designs[0].thumbnail_media_id == "med_9" + assert designs[0].document is None + + +@respx.mock +def test_create_sends_the_document_through(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs").mock( + return_value=httpx.Response(201, json={"data": DESIGN}) + ) + + design = client.designs.create( + workspace_id="ws_1", kind="post", name="Launch", document=DOCUMENT, brand_voice_id="bv_1" + ) + + assert json.loads(route.calls.last.request.content) == { + "workspace_id": "ws_1", + "kind": "post", + "name": "Launch", + "document": DOCUMENT, + "brand_voice_id": "bv_1", + } + assert design.document == DOCUMENT + assert design.kind == "post" + + +@respx.mock +def test_get(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/designs/des_1").mock( + return_value=httpx.Response(200, json={"data": DESIGN}) + ) + + design = client.designs.get("des_1") + + assert route.called + assert design.width == 1080 and design.updated_at is not None + + +@respx.mock +def test_update_patches_only_what_was_passed_and_returns_the_version(client: Fopost) -> None: + route = respx.patch(f"{BASE_URL}/designs/des_1").mock( + return_value=httpx.Response(200, json={"data": DESIGN, "version": VERSION}) + ) + + result = client.designs.update("des_1", document=DOCUMENT, create_version=True) + + assert json.loads(route.calls.last.request.content) == { + "document": DOCUMENT, + "create_version": True, + } + assert result.design.id == "des_1" + assert result.version is not None and result.version.version == 3 + + +@respx.mock +def test_update_without_a_version(client: Fopost) -> None: + route = respx.patch(f"{BASE_URL}/designs/des_1").mock( + return_value=httpx.Response(200, json={"data": DESIGN, "version": None}) + ) + + result = client.designs.update("des_1", name="Renamed") + + assert json.loads(route.calls.last.request.content) == {"name": "Renamed"} + assert result.version is None + + +@respx.mock +def test_delete(client: Fopost) -> None: + route = respx.delete(f"{BASE_URL}/designs/des_1").mock( + return_value=httpx.Response(200, json={"data": {"id": "des_1", "deleted": True}}) + ) + + result = client.designs.delete("des_1") + + assert route.called + assert result.id == "des_1" and result.deleted is True + + +@respx.mock +def test_versions_and_restore(client: Fopost) -> None: + listed = respx.get(f"{BASE_URL}/designs/des_1/versions").mock( + return_value=httpx.Response(200, json={"data": [{**VERSION, "document": DOCUMENT}]}) + ) + restored = respx.post(f"{BASE_URL}/designs/des_1/versions/ver_1/restore").mock( + return_value=httpx.Response(200, json={"data": DESIGN, "version": VERSION}) + ) + + versions = client.designs.versions("des_1", include_document=True) + assert dict(listed.calls.last.request.url.params) == {"include": "document"} + assert versions[0].document == DOCUMENT + + client.designs.versions("des_1") + assert dict(listed.calls.last.request.url.params) == {} + + result = client.designs.restore_version("des_1", "ver_1") + assert restored.called + assert result.design.id == "des_1" and result.version is not None + + +@respx.mock +def test_duplicate(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs/des_1/duplicate").mock( + return_value=httpx.Response(201, json={"data": {**DESIGN, "id": "des_2"}}) + ) + + copy = client.designs.duplicate("des_1", name="Copy") + + assert json.loads(route.calls.last.request.content) == {"name": "Copy"} + assert copy.id == "des_2" + + +@respx.mock +def test_export(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs/des_1/export").mock( + return_value=httpx.Response( + 200, + json={ + "data": { + "format": "png", + "files": [ + { + "media_id": "med_1", + "page_index": 0, + "mime_type": "image/png", + "preview_url": "https://api.test.fopost.com/v1/media/med_1/file", + } + ], + } + }, + ) + ) + + export = client.designs.export("des_1", format="png", page_indexes=[0], duration_sec=5) + + assert json.loads(route.calls.last.request.content) == { + "format": "png", + "page_indexes": [0], + "duration_sec": 5, + } + assert export.format == "png" + assert export.files[0].media_id == "med_1" + assert export.files[0].page_index == 0 + + +@respx.mock +def test_bulk_create(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs/des_1/bulk").mock( + return_value=httpx.Response(201, json={"data": [DESIGN, {**DESIGN, "id": "des_3"}]}) + ) + + designs = client.designs.bulk_create( + "des_1", rows=[{"name": "A", "headline": "Hi"}, {"name": "B"}], name_column="name" + ) + + assert json.loads(route.calls.last.request.content) == { + "rows": [{"name": "A", "headline": "Hi"}, {"name": "B"}], + "name_column": "name", + } + assert [d.id for d in designs] == ["des_1", "des_3"] + + +@respx.mock +def test_posts(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/designs/des_1/posts").mock( + return_value=httpx.Response( + 200, + json={ + "data": [ + { + "id": "post_1", + "status": "published", + "title": None, + "text": "Launch", + "schedule_at": None, + "published_at": "2026-11-20T12:00:00.000Z", + "platforms": ["twitter"], + "engagement": 12, + "views": 300, + } + ] + }, + ) + ) + + posts = client.designs.posts("des_1") + + assert route.called + assert posts[0].status == "published" + assert posts[0].platforms == ["twitter"] and posts[0].views == 300 + + +@respx.mock +def test_text_to_slides(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs/text-to-slides").mock( + return_value=httpx.Response( + 200, + json={ + "data": { + "cover": {"title": "Five tips", "subtitle": "For launch day"}, + "slides": [{"heading": "One", "body": "Plan early"}], + "cta": {"heading": "Follow", "body": "for more"}, + "brand": {"colors": ["#111111"], "fonts": {}, "logo_media_id": None}, + } + }, + ) + ) + + result = client.designs.text_to_slides(workspace_id="ws_1", text="Some notes", max_slides=5) + + assert json.loads(route.calls.last.request.content) == { + "workspace_id": "ws_1", + "text": "Some notes", + "max_slides": 5, + } + assert result.cover is not None and result.cover.title == "Five tips" + assert result.slides[0].body == "Plan early" + assert result.brand is not None and result.brand.colors == ["#111111"] + + +@respx.mock +def test_from_post(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/designs/from-post").mock( + return_value=httpx.Response(201, json={"data": {**DESIGN, "kind": "carousel"}}) + ) + + design = client.designs.from_post( + workspace_id="ws_1", post_id="post_1", style="quote", carousel=True + ) + + assert json.loads(route.calls.last.request.content) == { + "workspace_id": "ws_1", + "post_id": "post_1", + "style": "quote", + "carousel": True, + } + assert design.kind == "carousel" diff --git a/tests/test_fonts.py b/tests/test_fonts.py new file mode 100644 index 0000000..945e1b7 --- /dev/null +++ b/tests/test_fonts.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +from pathlib import Path + +import httpx +import respx + +from fopost import Fopost +from tests.conftest import BASE_URL + +UPLOADED = { + "id": "fnt_1", + "family": "Brand Sans", + "style": "normal", + "weight": 700, + "format": "woff2", + "file_url": "https://api.test.fopost.com/v1/fonts/fnt_1/file", + "created_at": "2026-11-20T10:00:00.000Z", +} + + +@respx.mock +def test_list_returns_library_and_uploads(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/fonts").mock( + return_value=httpx.Response( + 200, + json={ + "library": [ + { + "slug": "geist", + "family": "Geist", + "category": "sans-serif", + "scripts": ["latin"], + "weights": [400, 700], + "files": [{"path": "geist.woff2", "subset": "latin", "weight": 400}], + } + ], + "uploaded": [UPLOADED], + }, + ) + ) + + fonts = client.fonts.list(workspace_id="ws_1") + + assert dict(route.calls.last.request.url.params) == {"workspace_id": "ws_1"} + assert fonts.library[0].slug == "geist" + assert fonts.library[0].files[0].subset == "latin" + assert fonts.uploaded[0].id == "fnt_1" + assert fonts.uploaded[0].weight == 700 + + +@respx.mock +def test_upload_from_bytes_sends_multipart(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/fonts").mock(return_value=httpx.Response(201, json=UPLOADED)) + + font = client.fonts.upload( + workspace_id="ws_1", + file=("brand.woff2", b"wOF2", "font/woff2"), + family="Brand Sans", + weight=700, + style="normal", + ) + + request = route.calls.last.request + assert request.headers["content-type"].startswith("multipart/form-data") + assert b'name="workspace_id"\r\n\r\nws_1' in request.content + assert b'name="family"\r\n\r\nBrand Sans' in request.content + assert b'name="weight"\r\n\r\n700' in request.content + assert b'name="style"\r\n\r\nnormal' in request.content + assert b'name="file"; filename="brand.woff2"' in request.content + assert b"wOF2" in request.content + assert font.id == "fnt_1" and font.family == "Brand Sans" + + +@respx.mock +def test_upload_from_a_path(client: Fopost, tmp_path: Path) -> None: + path = tmp_path / "brand.ttf" + path.write_bytes(b"\x00\x01\x00\x00") + route = respx.post(f"{BASE_URL}/fonts").mock(return_value=httpx.Response(201, json=UPLOADED)) + + client.fonts.upload(workspace_id="ws_1", file=path) + + content = route.calls.last.request.content + assert b'name="file"; filename="brand.ttf"' in content + assert b'name="family"' not in content + + +@respx.mock +def test_delete(client: Fopost) -> None: + route = respx.delete(f"{BASE_URL}/fonts/fnt_1").mock(return_value=httpx.Response(204)) + + assert client.fonts.delete("fnt_1") is None + assert route.called diff --git a/tests/test_media.py b/tests/test_media.py index 8f44361..fa26820 100644 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -261,3 +261,24 @@ def test_list_upload_and_delete(client: Fopost) -> None: client.media.delete("med_1") assert deleted.called + + +@respx.mock +def test_generate_alt_text_posts_and_maps_the_result(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/media/med_1/alt-text").mock( + return_value=httpx.Response( + 200, + json={ + "alt_text": "A bar chart of weekly signups", + "alt_text_source": "ai", + "tags": ["chart"], + }, + ) + ) + + result = client.media.generate_alt_text("med_1") + + assert route.called + assert result.alt_text == "A bar chart of weekly signups" + assert result.alt_text_source == "ai" + assert result.tags == ["chart"] diff --git a/tests/test_video_edits.py b/tests/test_video_edits.py new file mode 100644 index 0000000..ef5838d --- /dev/null +++ b/tests/test_video_edits.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import json + +import httpx +import pytest +import respx + +from fopost import Fopost, PaymentRequiredError, VideoEditOperation +from tests.conftest import BASE_URL + +EDIT = { + "id": "ve_1", + "status": "succeeded", + "progress": 1, + "source_media_id": "med_1", + "operations": [{"op": "trim", "params": {"start": 0, "end": 10}}], + "result_media_id": "med_2", + "result_media": { + "id": "med_2", + "preview_url": "https://api.test.fopost.com/v1/media/med_2/file", + "mime_type": "video/mp4", + }, + "extra_outputs": [{"media_id": "med_3", "label": "Captions", "mime": "text/vtt"}], + "result": {}, + "error": None, + "created_at": "2026-11-20T10:00:00.000Z", + "updated_at": "2026-11-20T10:01:00.000Z", + "completed_at": "2026-11-20T10:01:00.000Z", +} + + +@respx.mock +def test_ops(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/video-edits/ops").mock( + return_value=httpx.Response( + 200, + json={ + "data": [ + {"name": "trim", "available": True, "uses_ai": False}, + {"name": "subtitles", "available": False, "uses_ai": True}, + ] + }, + ) + ) + + ops = client.video_edits.ops() + + assert route.called + assert [o.name for o in ops] == ["trim", "subtitles"] + assert ops[1].uses_ai is True and ops[1].available is False + + +@respx.mock +def test_list_sends_filters(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/video-edits").mock( + return_value=httpx.Response(200, json={"data": [EDIT]}) + ) + + edits = client.video_edits.list(workspace_id="ws_1", media_id="med_1", limit=5) + + assert dict(route.calls.last.request.url.params) == { + "workspace_id": "ws_1", + "media_id": "med_1", + "limit": "5", + } + assert edits[0].id == "ve_1" + assert edits[0].result_media is not None and edits[0].result_media.mime_type == "video/mp4" + + +@respx.mock +def test_create_sends_operations_in_order(client: Fopost) -> None: + route = respx.post(f"{BASE_URL}/video-edits").mock( + return_value=httpx.Response(201, json={**EDIT, "status": "queued", "progress": 0}) + ) + + edit = client.video_edits.create( + workspace_id="ws_1", + media_id="med_1", + operations=[ + {"op": "trim", "params": {"start": 0, "end": 10}}, + VideoEditOperation(op="denoise"), + {"op": "remove_silence"}, + ], + ) + + assert json.loads(route.calls.last.request.content) == { + "media_id": "med_1", + "operations": [ + {"op": "trim", "params": {"start": 0, "end": 10}}, + {"op": "denoise", "params": {}}, + {"op": "remove_silence"}, + ], + "workspace_id": "ws_1", + } + assert edit.status == "queued" + assert edit.operations[0].params == {"start": 0, "end": 10} + + +@respx.mock +def test_get(client: Fopost) -> None: + route = respx.get(f"{BASE_URL}/video-edits/ve_1").mock( + return_value=httpx.Response(200, json=EDIT) + ) + + edit = client.video_edits.get("ve_1", workspace_id="ws_1") + + assert dict(route.calls.last.request.url.params) == {"workspace_id": "ws_1"} + assert edit.result_media_id == "med_2" + assert edit.extra_outputs[0].label == "Captions" + assert edit.completed_at is not None + + +@respx.mock +def test_an_empty_balance_raises_payment_required(client: Fopost) -> None: + respx.post(f"{BASE_URL}/video-edits").mock( + return_value=httpx.Response( + 402, + json={ + "error": "insufficient_credits", + "message": "Your AI balance is empty.", + "upgrade_url": "/settings/billing", + }, + ) + ) + + with pytest.raises(PaymentRequiredError) as excinfo: + client.video_edits.create(media_id="med_1", operations=[{"op": "subtitles"}]) + + assert excinfo.value.upgrade_url == "/settings/billing"