omnisocials 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 27468385685af2b1f49e6665393bb687f2dd9fc18cf7d06b98190c78c9b3c3fe
4
- data.tar.gz: 24dafc551dc62fd9922aa9ce330ae138288a3ecd86dc768abcf35e2f5f466cae
3
+ metadata.gz: 7ea0275865830c8eb34ba9ae4f21fdf9ee1eef376185a7fcdaf379170d185668
4
+ data.tar.gz: 4b136937c0214a7f703ad46e00cb719a61ee89a071ec58d6df640cb6aa7f88c8
5
5
  SHA512:
6
- metadata.gz: 43d61512382a55a5ef87c2e906f28f55153a15d3deed758262e6f919eeb934e5de86be8e700570ffc2bb9862a33e111e285085248ed0bbd7f3645046a3dcf6ce
7
- data.tar.gz: 93c23762f52f0550bf38fcae55d850aafa24365966adad31d71b603c8c9fbee3c297be8cb31219d947fc2dd38d1d7b7b2252642460ae98d65a024060cb3d16ba
6
+ metadata.gz: 5f2d22fe54e670da7eb3c4451beae5472ac00e7c030ba9f280b2eb379f2b05c48f5e9e0d33420a9645f669d4811953796b66acc46bb8b4a2e8c2aa55d84878ab
7
+ data.tar.gz: fed3adc29d81f96febcd4e2e70974ef1a6a6a76e361f22cf3230daa36c4710fdbbe95236edfcc3fcb5610285d499c7a4308f6e4febc0d876a3c3b01502729396
data/README.md CHANGED
@@ -111,7 +111,23 @@ events["data"].each do |event|
111
111
  end
112
112
  ```
113
113
 
114
- The events response is `{ "data", "counts", "pagination" }`, not the plain list: `counts` is the number of events per outcome (`sent`, `skipped`, `failed`, `pending`, `queued`, `opted_out`). An automation can also listen on a post published outside OmniSocials (`client.automations.create(instagram_media_id: ..., actions: ...)`), on the next post the workspace publishes (`trigger: { "scope" => "next_post" }`) or on every post (`"scope" => "any"`), and on DMs and story replies (`trigger: { "kinds" => ["dm", "story_reply"], ... }`).
114
+ The events response is `{ "data", "counts", "pagination" }`, not the plain list: `counts` is the number of events per outcome (`sent`, `skipped`, `failed`, `pending`, `queued`, `opted_out`, `waiting`). An automation can also listen on a post published outside OmniSocials (`client.automations.create(instagram_media_id: ..., actions: ...)`), on the next post the workspace publishes (`trigger: { "scope" => "next_post" }`) or on every post (`"scope" => "any"`), and on DMs and story replies (`trigger: { "kinds" => ["dm", "story_reply"], ... }`).
115
+
116
+ Follow first (`"follow_gate"` in the actions, Instagram only) sends the link only to people who follow the account. On a comment the private reply is a first message with one button; a tap makes OmniSocials ask Instagram whether the person follows. A follower gets the DM text, anyone else gets the `not_following` message with its button, and every later tap checks again. A DM or a story reply is checked at once. When Instagram gives no answer the link goes out anyway. Texts hold 640 characters and buttons 20; leave them out for the defaults. A person who has not followed yet is an event with outcome `waiting` and `event["follow_gate"]` (`state`, `taps`, `followed`, `checked`, `after_ask`); `stats["followed"]` counts the people who followed after the ask. `"enabled" => true` on a Facebook or X automation is a `400 follow_gate_instagram_only`.
117
+
118
+ ```ruby
119
+ client.automations.update(
120
+ automation_id,
121
+ actions: {
122
+ "dm" => { "text" => "Here is the guide: https://example.com/guide" },
123
+ "follow_gate" => {
124
+ "enabled" => true,
125
+ "first_message" => { "text" => "Tap the button and I'll send you the link 👇", "button" => "Send me the link" },
126
+ "not_following" => { "text" => "Almost there! Follow @yourbrand first, then tap the button again.", "button" => "I follow now" }
127
+ }
128
+ }
129
+ )
130
+ ```
115
131
 
116
132
  A Facebook Page works the same way, and the DM lands in Messenger: pass `platform: "facebook"` to `client.automations.create`, or `facebook_post_id: ...` for a Page post published outside OmniSocials. On a post, `comment_dm_automation: { "platforms" => ["instagram", "facebook"], ... }` makes one automation per channel with the same keywords and DM. Facebook has no story replies.
117
133
 
@@ -303,14 +319,35 @@ recent = client.posts.recent_platform(limit: 10, platforms: ["instagram", "tikto
303
319
 
304
320
  `retry` re-publishes only the platforms that failed, on the same post; platforms that already succeeded are never posted again. It is asynchronous: a 200 means the retry is queued, so poll `get` for the outcome. Max 3 retries per platform.
305
321
 
322
+ These calls answer `409` and change nothing when the post is not in a state for them:
323
+
324
+ - `post_publishing`: `update` or `delete` while the post is publishing (status `posting`) or a retry publishes one of its channels. Poll `get` until the status is `published`, `warning` or `failed`. An `update` with only `tags` still works.
325
+ - `review_required`: changes were requested on the post (`approval_status` `rejected`), so `publish`, or an `update` that would schedule it, is refused. It needs a new review: create it again with `approval_workflow_id`. Saving it as a draft works.
326
+ - `retry_in_progress`: `retry` while another retry of the post runs.
327
+ - `media_processing`: a media id in `create`, `create_and_publish` or `update` is still processing. Wait until `client.media.get(id)` says `ready`, then send the same request again. A file whose processing failed answers `400 invalid_media`: upload it again.
328
+
306
329
  ### Approve or reject a post
307
330
 
308
331
  ```ruby
309
- client.posts.approve("123") # approve the current approval-workflow step
310
- client.posts.reject("123", comment: "Wrong CTA link, please fix.") # reject and stop the workflow (comment optional)
332
+ # Read the step you review first, then name it on the decision.
333
+ review = client.posts.get_approval("123")["data"]
334
+ step = review["current_step"]
335
+
336
+ begin
337
+ client.posts.approve("123", step_order: step) # approve the step you reviewed
338
+ # or: reject and stop the workflow (comment optional)
339
+ # client.posts.reject("123", comment: "Wrong CTA link, please fix.", step_order: step)
340
+ rescue OmniSocials::APIError => e
341
+ raise unless e.code == "step_changed"
342
+
343
+ # Somebody decided since you read it: nothing was decided. Read the approval again.
344
+ puts "The review is on step #{e.body["error"]["current_step_order"]}"
345
+ end
311
346
  ```
312
347
 
313
- Only works on a post with `approval_status: "pending"` (`status: "in_approval"`). Both act on behalf of the user who owns the API key, who must be a listed approver for the workflow's CURRENT step — steps approve in order, so being an approver on a later step is not enough yet (raises a 403 `OmniSocials::PermissionDeniedError`). Approving the last step finalizes the post (`scheduled` or `posting`); rejecting stops the whole workflow immediately, not just the current step.
348
+ Only works on a post with `approval_status: "pending"` (`status: "in_approval"`). Both act on behalf of the user who owns the API key, who must be a listed approver for the workflow's CURRENT step. Steps approve in order, so being an approver on a later step is not enough yet (raises a 403 `OmniSocials::PermissionDeniedError`). Approving the last step finalizes the post (`scheduled` or `posting`); rejecting stops the whole workflow immediately, not just the current step.
349
+
350
+ `step_order:` is optional: the `current_step` of `get_approval`. When the review is on another step now (somebody decided since you read it, or a retried call already went through), nothing is decided and the call raises a 409 `OmniSocials::APIError` with code `step_changed` and `error.current_step_order`, the step the review is on now. Without `step_order:` the call acts on whatever step is current, so a retry after a timeout could approve the next step too.
314
351
 
315
352
  ### Read the approval review
316
353
 
@@ -339,7 +376,7 @@ media = client.media.upload_from_url(
339
376
  media_id = media["data"]["id"]
340
377
  ```
341
378
 
342
- Files over 100MB are processed in the background: the response has `media["data"]["status"] == "processing"`; poll `client.media.get(media_id)` until it is `"ready"` before attaching it to a post.
379
+ Files over 100MB are processed in the background: the response has `media["data"]["status"] == "processing"`; poll `client.media.get(media_id)` until it is `"ready"` before attaching it to a post. When such a file cannot be queued, the call answers `503 processing_unavailable`: send the same request again in a minute.
343
380
 
344
381
  ### Upload a local file (multipart, max 100MB)
345
382
 
@@ -461,12 +498,15 @@ end
461
498
  ```ruby
462
499
  accounts = client.accounts.list
463
500
  accounts["data"].each do |account|
464
- puts "#{account["platform"]}: #{account["username"]}"
501
+ puts "#{account["platform"]}: #{account["username"]} (#{account["status"]})"
502
+ puts " needs a reconnect: #{account["reauth_reason"]}" if account["needs_reconnect"]
465
503
  end
466
504
 
467
505
  account = client.accounts.get("instagram")
468
506
  ```
469
507
 
508
+ `status` is `active` or `needs_reconnect` (the token was revoked or expired; Bluesky also when its sign-in could not be renewed). Posts to a `needs_reconnect` account fail until it is reconnected in the OmniSocials app. OmniSocials Connect customer workspaces can also show `pick_pending` (Facebook, Connect customers only: no Page chosen yet).
509
+
470
510
  ## Analytics
471
511
 
472
512
  ```ruby
@@ -575,6 +615,7 @@ client.inbox.reply(conversation_id, text: "Thanks for reaching out!")
575
615
  message_id = messages["data"][0]["id"]
576
616
  client.inbox.hide(message_id) # hide
577
617
  client.inbox.hide(message_id, hide: false) # unhide
618
+ # Delete a comment, or one of your own replies (Facebook, Instagram, TikTok).
578
619
  client.inbox.delete_message(message_id)
579
620
 
580
621
  # Like a comment as the Page or account (Facebook, LinkedIn Page, TikTok).
@@ -631,9 +672,75 @@ end
631
672
 
632
673
  `x_inbox_suspended` fires once a workspace's X inbox has auto-suspended after its credit balance hit zero; topping up and re-enabling it in the dashboard resumes delivery, but DMs that arrived while suspended are not recovered.
633
674
 
675
+ ## Ads
676
+
677
+ Boost a published post or create a new ad on Meta, Pinterest, TikTok, LinkedIn, X and Google. Boosts and new ads are drafts: your code writes the draft, and the person who pays sees the amount and starts the ad in OmniSocials from the draft's `review_url`. A key starts and raises spend itself only with the opt-in **Start ads** switch (scope `ads:spend`). Without it `ads.activate`, `ads.activate_multi`, `ads.resume`, `ads.drafts.launch`, a budget raise or any change of a campaign that reached the network through `ads.update`, and the parity calls that switch something on or raise a budget answer `403 start_in_app`, and the error message names the page where the person does it. Google (`api_draft_only` of `ads.capabilities`) always stops at the draft, also with `ads:spend`. `ads.pause` and `ads.delete` stay open, except on the networks in `api_stop_in_app` (Google), where a campaign that reached the network also answers `403 start_in_app`. Only a paused campaign resumes (`409 not_paused`). The calls that start or raise spend repeat the amount (`confirm_budget_amount`) and are not retried after a 5xx or a timeout, only after a 429, because the first attempt may have started the ad: read the campaign or the draft to see what happened.
678
+
679
+ The `ads:read` and `ads:write` scopes are opt-in: create the API key with **Ads** switched on (Settings, API). `ads:spend` is the **Start ads** switch under it, offered only to a person with `manage_ads`. A key without a scope it needs gets `403 insufficient_scope`. Ad accounts are connected and picked in the OmniSocials dashboard. Budgets are in major units (10 = 10 EUR) in the ad account's currency: a draft whose `budget["currency"]` differs from the attached ad account's currency answers `400 currency_mismatch`. Ads errors may carry `param`, the field at fault: read it from `e.body["error"]["param"]` on the raised `OmniSocials::APIError` (here `"budget.currency"`). Ad account and campaign ids come back as strings (`"51"`); the methods take an id as a string or a number.
680
+
681
+ ### Create an ad (a draft the person starts)
682
+
683
+ ```ruby
684
+ caps = client.ads.capabilities
685
+ p caps["data"]["create_networks"], caps["data"]["network_states"]
686
+
687
+ draft = client.ads.drafts.create(
688
+ name: "Autumn sale",
689
+ objective: "traffic",
690
+ platforms: %w[meta linkedin],
691
+ budget: { "amount" => 10, "currency" => "EUR" },
692
+ schedule: { "duration_days" => 7 },
693
+ targeting: { "countries" => %w[NL BE], "automatic_audience" => true },
694
+ ads: [
695
+ {
696
+ "media" => [{ "url" => "https://example.com/sale.jpg", "type" => "image", "width" => 1080, "height" => 1350 }],
697
+ "primary_text" => "30% off everything this week",
698
+ "headline" => "Autumn sale",
699
+ "cta" => "shop_now",
700
+ "link" => "https://example.com/sale"
701
+ }
702
+ ]
703
+ )["data"]
704
+
705
+ # A draft spends nothing. The person checks it and starts it in OmniSocials:
706
+ puts "Check and start the ad here: #{draft["review_url"]}"
707
+ ```
708
+
709
+ With a key that has `ads:spend`, `client.ads.drafts.launch(draft["group_id"], confirm_budget_amount: 10)` starts the draft after the person agreed to the amount; Google is skipped with code `start_in_app`. Without `ads:spend` the call answers `403 start_in_app`.
710
+
711
+ A draft needs no ad account; `client.ads.drafts.attach_account(group_id, platform: "meta", ad_account_id: "51")` sets one, and `campaigns[].readiness` says what still stops a network. `client.ads.drafts.update(group_id, ...)` replaces the whole draft (HTTP PUT), so send every field again. On Meta an ad can carry a second upright 9:16 file for Stories and Reels: `"placement_media" => { "stories_reels" => { "url" => ..., "type" => ... } }`.
712
+
713
+ ### Boost a post
714
+
715
+ ```ruby
716
+ accounts = client.ads.list_accounts["data"]
717
+ meta = accounts.find { |account| account["platform"] == "meta" && account["is_selected"] }
718
+
719
+ boost = client.ads.boost(
720
+ post_id: 12_345,
721
+ ad_account_id: meta["id"],
722
+ budget: { "type" => "daily", "amount" => 5, "currency" => meta.dig("account_info", "currency") || "EUR" },
723
+ targeting: { "countries" => ["NL"] }
724
+ )["data"]
725
+
726
+ # The boost is a draft: the person starts it in OmniSocials.
727
+ puts boost["status"] # "draft"
728
+ ```
729
+
730
+ `client.ads.boost_multi` makes one draft boost per ad account (up to 10, the same budget each). `client.ads.suggestions` lists posts that do better than your median, `client.ads.overview` the totals (`totals["spend"]` is `nil` when the campaigns use more than one currency: read `totals_by_currency`, one row per currency), and `client.ads.list`, `get`, `pause` and `delete` manage campaigns. Keyword ideas through the connected Google Ads account: `client.ads.research_keywords(keywords: ["running shoes"], country: "NL")` and `client.ads.keyword_metrics(keywords: [...])`.
731
+
732
+ ### More of the Ads API
733
+
734
+ Sub-resources cover the rest of the Ads API: `objects` (the tree of an ad account, also campaigns made outside OmniSocials, and their import), `campaign_ads`, `comments`, `targeting`, `audiences`, `lead_forms`, `leads`, `conversions`, `insights`, `reports`, `rules`, `results`, `media`, `previews`, `partnership`, `accounts` (health, finance, settings, people), `reach_frequency`, `studies`, `budget_schedules` and `google`, plus `ads.bulk_status` and `ads.duplicate`. A network without a feature answers `400 not_supported_on_network`; `ads.capabilities` lists `features` and `targeting_types` per network. Every call that switches something on or raises spend needs a key with `ads:spend` (without it, and on Google always, `403 start_in_app`; a rule that switches on or raises a budget: `403 rule_raises_spend`): `objects.update`, `objects.set_status` (switching on), `objects.duplicate`, `bulk_status` (resuming), `campaign_ads.add`, `campaign_ads.set_status` (switching on), `rules.create`, `rules.update`, `rules.undo`, `accounts.update_settings` (a spend cap), `reach_frequency.reserve`, `studies.create` and `budget_schedules.create`. The ones that raise spend take the person's own amount and are not retried after a 5xx or a timeout. Pausing, deleting and archiving stay open, except on Google; a rule that notifies, pauses or lowers a budget works with `ads:write` and never acts on Google.
735
+
736
+ ```ruby
737
+ interests = client.ads.targeting.search(ad_account_id: meta["id"], type: "interest", q: "running")["data"]["items"]
738
+ # Use the ids in targeting["networks"]["meta"]["include"]["interest"] of a draft.
739
+ ```
740
+
634
741
  ## Webhooks
635
742
 
636
- Subscribe to `post.scheduled`, `post.published`, `post.failed`, `post.approved`, and `post.rejected` events. `post.approved` fires when the last step of a post's approval workflow is approved, `post.rejected` when an approver rejects the post (it will not publish). These two carry `data["approval"]` with `status`, `decided_by` (the approver's user id) and `reason` (`nil` on `post.approved`), and an empty `data["targets"]`.
743
+ Subscribe to `post.scheduled`, `post.published`, `post.failed`, `post.approved`, and `post.rejected` events. `post.approved` fires when the last step of a post's approval workflow is approved, `post.rejected` when an approver rejects the post (it will not publish). These two carry `data["approval"]` with `status`, `decided_by` (the approver's user id) and `reason` (`nil` on `post.approved`), and an empty `data["targets"]`. `ad.status_changed` fires when an ad campaign changes status (for example `pending_review` to `active` or `rejected`); its `data` is the campaign, not a post: `campaign_id`, `workspace_id`, `name`, `platform`, `campaign_type`, `status`, `previous_status`, `external_campaign_id` and `budget`. The other ads events are `ad.created`, `ad.updated`, `ad.review`, `ad.delivery_issue`, `campaign.created`, `campaign.updated`, `campaign.budget`, `lead.received`, `ads.sync_failed`, `ads.sync_recovered`, `ads.initial_sync_completed` and `ad_rule.triggered`. Subscribing to `ad.status_changed` or any other Ads event (`ad.*`, `campaign.*`, `lead.*`, `ads.*`, `ad_rule.*`) needs the `ads:read` scope on the key and `access_ads` for its person (`403 insufficient_scope` / `insufficient_permission`).
637
744
 
638
745
  ```ruby
639
746
  webhook = client.webhooks.create(
@@ -645,10 +752,12 @@ secret = webhook["data"]["secret"] # only shown once, store it
645
752
  client.webhooks.list
646
753
  client.webhooks.get(webhook["data"]["id"])
647
754
  client.webhooks.update(webhook["data"]["id"], is_active: false)
648
- client.webhooks.rotate_secret(webhook["data"]["id"]) # new secret, shown once
755
+ client.webhooks.rotate_secret(webhook["data"]["id"]) # new secret, shown once; the old one signs for 24 hours more
649
756
  client.webhooks.delete(webhook["data"]["id"])
650
757
  ```
651
758
 
759
+ Every webhook carries `workspace_id`. `list` and `get` also return the organisation-wide webhooks of the key's organisation (`workspace_id` `nil`, made in the OmniSocials dashboard; they receive the events of every workspace), and `update`, `delete` and `rotate_secret` work on them too. Webhooks you create through the API belong to the key's workspace. When the person behind a webhook loses access to the organisation or workspace, OmniSocials switches the webhook off: `is_active` is `false` and `last_failure["error"]` says why. `update(id, is_active: true)` switches it on again.
760
+
652
761
  ### Verifying webhook signatures (Rails example)
653
762
 
654
763
  Every delivery is signed with HMAC-SHA256. The `X-OmniSocials-Signature` header has the form `t=<unix>,v1=<hex>`, signed over `"{timestamp}.{raw_body}"`. Use `OmniSocials::Webhooks.verify` with the raw request body (do not parse it first):
@@ -715,6 +824,64 @@ run app
715
824
 
716
825
  `OmniSocials::Webhooks.verify` uses a constant-time comparison, rejects timestamps older than `tolerance` seconds (default 300) to block replays, and returns the parsed event Hash on success. Respond with any 2xx within 10 seconds to acknowledge; deliveries are retried up to 3 times.
717
826
 
827
+ ### Rotate the secret without missing deliveries
828
+
829
+ For 24 hours after `rotate_secret`, every delivery carries two headers: `X-OmniSocials-Signature`, signed with the new secret, and `X-OmniSocials-Signature-Previous`, signed with the old secret (same format, same timestamp and body). Verify the first with the new secret and, when that fails, the second with the old one:
830
+
831
+ ```ruby
832
+ def verify_delivery(payload, headers)
833
+ OmniSocials::Webhooks.verify(
834
+ payload: payload,
835
+ signature: headers["X-OmniSocials-Signature"],
836
+ secret: ENV.fetch("OMNISOCIALS_WEBHOOK_SECRET") # the new secret
837
+ )
838
+ rescue OmniSocials::WebhookVerificationError
839
+ previous = headers["X-OmniSocials-Signature-Previous"]
840
+ raise if previous.nil?
841
+
842
+ OmniSocials::Webhooks.verify(
843
+ payload: payload,
844
+ signature: previous,
845
+ secret: ENV.fetch("OMNISOCIALS_WEBHOOK_SECRET_OLD") # the old secret
846
+ )
847
+ end
848
+ ```
849
+
850
+ Rotating again within the 24 hours replaces the previous secret with the one you just rotated out.
851
+
852
+ ## Limits and feature requests
853
+
854
+ `client.limits.list` lists what OmniSocials cannot do, why (`says`) and what to do instead (`instead`): platform rules, features not built yet, features that work in the OmniSocials app only. Read it before you tell a person that something is not possible. When the person still wants a `requestable` entry, send a feature request with its `limit_id`. The request is stored for the person who owns the key; they see it in OmniSocials (Settings, Request a feature) and get an email when its status changes. Works with every key, no scope needed.
855
+
856
+ ```ruby
857
+ limits = client.limits.list(platform: "telegram") # area: "posts" | "inbox" | ...
858
+ limits["data"].each do |limit|
859
+ puts [limit["id"], limit["says"], limit["instead"], limit["requestable"]].inspect
860
+ end
861
+
862
+ begin
863
+ result = client.feature_requests.create(
864
+ summary: "Post our daily update to the Announcements topic of our Telegram group, not to the whole group.",
865
+ platform: "telegram",
866
+ limit_id: "telegram.forum_topics"
867
+ )
868
+ # "created" (new), "voted" (added a vote to your organisation's open request)
869
+ # or "already_requested" (you asked before; data is that request)
870
+ puts result["outcome"], result["data"]["id"], result["data"]["status"]
871
+ rescue OmniSocials::APIError => e
872
+ raise unless e.code == "not_requestable"
873
+
874
+ # A platform rule or a choice of OmniSocials: nothing was stored.
875
+ limit = e.body["error"]["limit"]
876
+ puts limit["says"], limit["instead"]
877
+ end
878
+
879
+ mine = client.feature_requests.list # newest first, at most 50
880
+ one = client.feature_requests.get(mine["data"].first["id"]) # status, team_answer, team_replies
881
+ ```
882
+
883
+ A limit is `{ "id", "kind", "kind_label", "area", "platforms", "title", "says", "instead", "requestable" }`; `kind` is `platform`, `by_design`, `not_built`, `beta`, `dashboard_only` or `needs_setup`, and `requestable` is false for `platform` and `by_design`. `limits.list` also returns `kinds` (a label per kind). A request carries `status` (`open`, `in_progress`, `completed`, `declined`), `votes_count`, `team_answer` and `team_replies`. `summary:` is 10 to 1000 characters (what the person wants to do and why), `title:` at most 120 (made from the summary when left out); `area:` is one of posts, media, inbox, analytics, automations, accounts, ads, team, other. Errors: `400 invalid_summary` / `invalid_title` / `invalid_platform` / `invalid_area` / `unknown_limit`, `409 not_requestable` (the entry is in `e.body["error"]["limit"]`), `429 too_many_requests` (10 an hour per person), and `400 invalid_id` / `404 not_found` on `get`.
884
+
718
885
  ## Error handling
719
886
 
720
887
  Non-2xx responses raise typed exceptions with `status`, `code`, `message`, and the parsed `body`:
@@ -745,7 +912,7 @@ The API allows **100 requests per minute** per API key. Every response includes
745
912
 
746
913
  ## Retries and timeouts
747
914
 
748
- The SDK automatically retries on 429, 5xx, and connection errors with exponential backoff (0.5s, 1s, 2s, with jitter), honoring the `Retry-After` header when present. Other 4xx errors are never retried. Defaults: 2 retries, 30 second timeout. Both are configurable:
915
+ The SDK automatically retries on 429, 5xx, and connection errors with exponential backoff (0.5s, 1s, 2s, with jitter), honoring the `Retry-After` header when present. Other 4xx errors are never retried. The ads calls that start or raise spend retry a 429 only (see [Ads](#ads)). Defaults: 2 retries, 30 second timeout. Both are configurable:
749
916
 
750
917
  ```ruby
751
918
  client = OmniSocials::Client.new(
@@ -38,6 +38,7 @@ module OmniSocials
38
38
  "GET" => Net::HTTP::Get,
39
39
  "POST" => Net::HTTP::Post,
40
40
  "PATCH" => Net::HTTP::Patch,
41
+ "PUT" => Net::HTTP::Put,
41
42
  "DELETE" => Net::HTTP::Delete
42
43
  }.freeze
43
44
 
@@ -61,7 +62,8 @@ module OmniSocials
61
62
  attr_reader :api_key, :base_url, :timeout, :max_retries,
62
63
  :posts, :media, :folders, :hashtag_sets, :approval_workflows,
63
64
  :accounts, :analytics, :audio, :locations, :pinterest,
64
- :automations, :inbox, :webhooks, :tags
65
+ :automations, :ads, :inbox, :webhooks, :tags,
66
+ :limits, :feature_requests
65
67
 
66
68
  # api_key - API key (omsk_live_*). Falls back to the
67
69
  # OMNISOCIALS_API_KEY environment variable. Raises
@@ -98,8 +100,11 @@ module OmniSocials
98
100
  @locations = Resources::Locations.new(self)
99
101
  @pinterest = Resources::Pinterest.new(self)
100
102
  @automations = Resources::Automations.new(self)
103
+ @ads = Resources::Ads.new(self)
101
104
  @inbox = Resources::Inbox.new(self)
102
105
  @webhooks = Resources::Webhooks.new(self)
106
+ @limits = Resources::Limits.new(self)
107
+ @feature_requests = Resources::FeatureRequests.new(self)
103
108
  end
104
109
 
105
110
  # GET /health - API health check (no scopes required).
@@ -113,7 +118,11 @@ module OmniSocials
113
118
  # non-JSON responses, or nil for 204. Raises an OmniSocials::APIError
114
119
  # subclass on non-2xx and OmniSocials::APIConnectionError when no
115
120
  # response was ever received.
116
- def request(method, path, query: nil, json: nil, multipart: nil)
121
+ #
122
+ # retry_on: :rate_limit retries only a 429. A call that can start ad
123
+ # spend uses it: after a 5xx, a timeout or a lost connection the first
124
+ # attempt may have gone through, so it is never sent again.
125
+ def request(method, path, query: nil, json: nil, multipart: nil, retry_on: nil)
117
126
  uri = build_uri(path, query)
118
127
  last_error = nil
119
128
 
@@ -122,13 +131,14 @@ module OmniSocials
122
131
  response = perform(method, uri, json: json, multipart: multipart)
123
132
  rescue *CONNECTION_ERRORS => e
124
133
  last_error = e
125
- break if attempt >= max_retries
134
+ # Not sent again when the call may have started ad spend.
135
+ break if retry_on == :rate_limit || attempt >= max_retries
126
136
 
127
137
  sleep(Internal.backoff_delay(attempt, nil))
128
138
  next
129
139
  end
130
140
 
131
- should_retry, retry_after = retry_info(response)
141
+ should_retry, retry_after = retry_info(response, retry_on)
132
142
  if should_retry && attempt < max_retries
133
143
  sleep(Internal.backoff_delay(attempt, retry_after))
134
144
  next
@@ -178,9 +188,10 @@ module OmniSocials
178
188
  http.start { |conn| conn.request(req) }
179
189
  end
180
190
 
181
- def retry_info(response)
191
+ def retry_info(response, retry_on)
182
192
  status = response.code.to_i
183
- if RETRY_STATUSES.include?(status) || status >= 500
193
+ server_error = RETRY_STATUSES.include?(status) || status >= 500
194
+ if status == 429 || (server_error && retry_on != :rate_limit)
184
195
  [true, parse_retry_after(response, Internal.parse_body(response.body))]
185
196
  else
186
197
  [false, nil]
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "cgi"
3
4
  require "json"
4
5
  require "pathname"
5
6
 
@@ -34,6 +35,12 @@ module OmniSocials
34
35
  hash.reject { |_key, value| value.nil? || value.is_a?(NotGiven) }
35
36
  end
36
37
 
38
+ # URL-encode an id for use as one path segment. Spaces become %20 (a
39
+ # path segment treats "+" literally, unlike a query string).
40
+ def path_segment(value)
41
+ CGI.escape(value.to_s).gsub("+", "%20")
42
+ end
43
+
37
44
  # Join an array into a comma-separated string; pass strings through.
38
45
  def join_list(value)
39
46
  return nil if value.nil?