instagram_connect 0.2.0 → 0.3.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 +4 -4
- data/.github/workflows/ci.yml +36 -0
- data/CHANGELOG.md +89 -0
- data/Gemfile +4 -0
- data/README.md +328 -73
- data/app/controllers/instagram_connect/comments_controller.rb +1 -1
- data/app/controllers/instagram_connect/posts_controller.rb +1 -1
- data/app/jobs/instagram_connect/account_readiness_job.rb +148 -0
- data/app/jobs/instagram_connect/fetch_media_job.rb +110 -0
- data/app/jobs/instagram_connect/profile_sync_job.rb +78 -0
- data/app/jobs/instagram_connect/replay_events_job.rb +57 -0
- data/app/jobs/instagram_connect/send_message_job.rb +44 -16
- data/app/models/instagram_connect/account.rb +27 -1
- data/app/models/instagram_connect/api_budget.rb +22 -0
- data/app/models/instagram_connect/conversation.rb +99 -11
- data/app/models/instagram_connect/inbound_message.rb +11 -3
- data/app/models/instagram_connect/insight_snapshot.rb +43 -0
- data/app/models/instagram_connect/media_item.rb +38 -0
- data/app/models/instagram_connect/mention.rb +37 -0
- data/app/models/instagram_connect/message.rb +34 -2
- data/app/models/instagram_connect/message_attachment.rb +53 -0
- data/app/models/instagram_connect/message_reaction.rb +33 -0
- data/app/models/instagram_connect/webhook_event.rb +67 -0
- data/db/migrate/20260715072548_create_instagram_connect_accounts.rb +2 -2
- data/db/migrate/20260715072549_create_instagram_connect_conversations.rb +2 -2
- data/db/migrate/20260715072550_create_instagram_connect_messages.rb +3 -3
- data/db/migrate/20260715072551_create_instagram_connect_inbound_messages.rb +2 -2
- data/db/migrate/20260715072552_create_instagram_connect_comments.rb +3 -3
- data/db/migrate/20260725194732_create_instagram_connect_webhook_events.rb +52 -0
- data/db/migrate/20260725200216_add_messaging_event_fields.rb +89 -0
- data/db/migrate/20260725200250_create_instagram_connect_message_reactions.rb +30 -0
- data/db/migrate/20260725201320_create_instagram_connect_message_attachments.rb +33 -0
- data/db/migrate/20260725202616_add_outbound_send_fields.rb +27 -0
- data/db/migrate/20260725203213_create_instagram_connect_media.rb +30 -0
- data/db/migrate/20260725203214_create_instagram_connect_mentions.rb +30 -0
- data/db/migrate/20260725203215_create_instagram_connect_insight_snapshots.rb +45 -0
- data/db/migrate/20260725203306_add_comment_moderation_fields.rb +29 -0
- data/db/migrate/20260725204022_add_per_account_token_fields.rb +76 -0
- data/db/migrate/20260725204815_create_instagram_connect_api_budgets.rb +29 -0
- data/db/migrate/20260725205417_add_conversation_profile_fields.rb +21 -0
- data/docs/CONFIGURATION.md +107 -0
- data/lib/instagram_connect/client.rb +109 -3
- data/lib/instagram_connect/configuration.rb +10 -0
- data/lib/instagram_connect/engine.rb +1 -0
- data/lib/instagram_connect/ingest/dispatcher.rb +151 -0
- data/lib/instagram_connect/ingest/envelope.rb +31 -0
- data/lib/instagram_connect/ingest/handlers/base.rb +55 -0
- data/lib/instagram_connect/ingest/handlers/comments.rb +59 -0
- data/lib/instagram_connect/ingest/handlers/mentions.rb +48 -0
- data/lib/instagram_connect/ingest/handlers/message_reactions.rb +91 -0
- data/lib/instagram_connect/ingest/handlers/messages.rb +135 -0
- data/lib/instagram_connect/ingest/handlers/messaging_handover.rb +53 -0
- data/lib/instagram_connect/ingest/handlers/messaging_optins.rb +37 -0
- data/lib/instagram_connect/ingest/handlers/messaging_postbacks.rb +24 -0
- data/lib/instagram_connect/ingest/handlers/messaging_referral.rb +42 -0
- data/lib/instagram_connect/ingest/handlers/messaging_seen.rb +37 -0
- data/lib/instagram_connect/ingest/handlers/story_insights.rb +62 -0
- data/lib/instagram_connect/ingest/handlers/unknown.rb +19 -0
- data/lib/instagram_connect/ingest/registry.rb +93 -0
- data/lib/instagram_connect/ingest/summary.rb +75 -0
- data/lib/instagram_connect/ingest.rb +27 -105
- data/lib/instagram_connect/media/attaching.rb +57 -0
- data/lib/instagram_connect/media/limits.rb +46 -0
- data/lib/instagram_connect/rate_limiter.rb +88 -0
- data/lib/instagram_connect/result.rb +26 -6
- data/lib/instagram_connect/text_splitter.rb +51 -0
- data/lib/instagram_connect/usage.rb +68 -0
- data/lib/instagram_connect/version.rb +1 -1
- data/lib/instagram_connect.rb +23 -0
- metadata +60 -2
- data/MIT-LICENSE +0 -20
|
@@ -1,112 +1,34 @@
|
|
|
1
1
|
module InstagramConnect
|
|
2
|
-
#
|
|
3
|
-
#
|
|
4
|
-
#
|
|
5
|
-
# can layer extras (notifications, AI replies) on top.
|
|
2
|
+
# Turns a verified Meta webhook payload into persisted rows, and fires the
|
|
3
|
+
# configured host callbacks (on_message / on_comment / on_postback) so the
|
|
4
|
+
# host can layer notifications, AI drafting or CRM linking on top.
|
|
6
5
|
#
|
|
7
|
-
#
|
|
6
|
+
# Every event is banked on InstagramConnect::WebhookEvent before anything
|
|
7
|
+
# parses it. That is what makes an unparsed or mis-parsed event recoverable:
|
|
8
|
+
# Meta neither stores nor re-delivers webhooks, so anything dropped here is
|
|
9
|
+
# gone permanently. See Ingest::Dispatcher for the walk.
|
|
10
|
+
#
|
|
11
|
+
# Returns a Summary, which reads like the plain hash 0.2.x returned.
|
|
8
12
|
class Ingest
|
|
9
13
|
def self.call(payload:, config: InstagramConnect.configuration)
|
|
10
|
-
new(config).call(payload)
|
|
11
|
-
end
|
|
12
|
-
|
|
13
|
-
def initialize(config)
|
|
14
|
-
@config = config
|
|
15
|
-
end
|
|
16
|
-
|
|
17
|
-
def call(payload)
|
|
18
|
-
summary = { messages: 0, comments: 0, postbacks: 0, skipped: 0 }
|
|
19
|
-
Array(payload && payload["entry"]).each do |entry|
|
|
20
|
-
account = account_for(entry)
|
|
21
|
-
if account.nil?
|
|
22
|
-
summary[:skipped] += 1
|
|
23
|
-
next
|
|
24
|
-
end
|
|
25
|
-
Array(entry["messaging"]).each { |event| ingest_messaging(account, event, summary) }
|
|
26
|
-
Array(entry["changes"]).each { |change| ingest_change(account, change, summary) }
|
|
27
|
-
end
|
|
28
|
-
summary
|
|
29
|
-
end
|
|
30
|
-
|
|
31
|
-
private
|
|
32
|
-
|
|
33
|
-
attr_reader :config
|
|
34
|
-
|
|
35
|
-
def account_for(entry)
|
|
36
|
-
id = entry["id"].to_s
|
|
37
|
-
Account.find_by(ig_user_id: id) || Account.find_by(page_id: id)
|
|
38
|
-
end
|
|
39
|
-
|
|
40
|
-
def ingest_messaging(account, event, summary)
|
|
41
|
-
if event["message"]
|
|
42
|
-
ingest_message(account, event, summary)
|
|
43
|
-
elsif event["postback"]
|
|
44
|
-
invoke(config.on_postback, build_postback(account, event))
|
|
45
|
-
summary[:postbacks] += 1
|
|
46
|
-
else
|
|
47
|
-
summary[:skipped] += 1
|
|
48
|
-
end
|
|
49
|
-
end
|
|
50
|
-
|
|
51
|
-
def ingest_message(account, event, summary)
|
|
52
|
-
msg = event["message"]
|
|
53
|
-
mid = msg["mid"].to_s
|
|
54
|
-
if mid.empty? || !InboundMessage.claim(ig_message_id: mid, account_id: account.id)
|
|
55
|
-
summary[:skipped] += 1
|
|
56
|
-
return
|
|
57
|
-
end
|
|
58
|
-
|
|
59
|
-
echo = msg["is_echo"] ? true : false
|
|
60
|
-
igsid = (echo ? event.dig("recipient", "id") : event.dig("sender", "id")).to_s
|
|
61
|
-
conversation = Conversation.locate(account: account, igsid: igsid)
|
|
62
|
-
message = Message.create!(
|
|
63
|
-
conversation: conversation,
|
|
64
|
-
direction: echo ? "outbound" : "inbound",
|
|
65
|
-
status: echo ? "sent" : "received",
|
|
66
|
-
source: echo ? "operator_app" : "inbound",
|
|
67
|
-
kind: "dm",
|
|
68
|
-
body: msg["text"],
|
|
69
|
-
ig_message_id: mid,
|
|
70
|
-
media_status: media?(msg) ? "pending" : "none"
|
|
71
|
-
)
|
|
72
|
-
conversation.register_message(message)
|
|
73
|
-
invoke(config.on_message, message) unless echo
|
|
74
|
-
summary[:messages] += 1
|
|
75
|
-
end
|
|
76
|
-
|
|
77
|
-
def ingest_change(account, change, summary)
|
|
78
|
-
unless change["field"] == "comments"
|
|
79
|
-
summary[:skipped] += 1
|
|
80
|
-
return
|
|
81
|
-
end
|
|
82
|
-
value = change["value"] || {}
|
|
83
|
-
comment = Comment.record(
|
|
84
|
-
account: account,
|
|
85
|
-
comment_id: value["id"].to_s,
|
|
86
|
-
media_id: value.dig("media", "id"),
|
|
87
|
-
text: value["text"],
|
|
88
|
-
from_username: value.dig("from", "username"),
|
|
89
|
-
parent_id: value["parent_id"]
|
|
90
|
-
)
|
|
91
|
-
invoke(config.on_comment, comment)
|
|
92
|
-
summary[:comments] += 1
|
|
93
|
-
end
|
|
94
|
-
|
|
95
|
-
def media?(msg)
|
|
96
|
-
Array(msg["attachments"]).any?
|
|
97
|
-
end
|
|
98
|
-
|
|
99
|
-
def build_postback(account, event)
|
|
100
|
-
{
|
|
101
|
-
account_id: account.id,
|
|
102
|
-
sender_id: event.dig("sender", "id"),
|
|
103
|
-
payload: event.dig("postback", "payload"),
|
|
104
|
-
title: event.dig("postback", "title")
|
|
105
|
-
}
|
|
106
|
-
end
|
|
107
|
-
|
|
108
|
-
def invoke(handler, arg)
|
|
109
|
-
handler.call(arg) if handler.respond_to?(:call)
|
|
14
|
+
Dispatcher.new(config).call(payload)
|
|
110
15
|
end
|
|
111
16
|
end
|
|
112
17
|
end
|
|
18
|
+
|
|
19
|
+
require_relative "ingest/envelope"
|
|
20
|
+
require_relative "ingest/summary"
|
|
21
|
+
require_relative "ingest/handlers/base"
|
|
22
|
+
require_relative "ingest/handlers/messages"
|
|
23
|
+
require_relative "ingest/handlers/messaging_postbacks"
|
|
24
|
+
require_relative "ingest/handlers/message_reactions"
|
|
25
|
+
require_relative "ingest/handlers/messaging_seen"
|
|
26
|
+
require_relative "ingest/handlers/messaging_referral"
|
|
27
|
+
require_relative "ingest/handlers/messaging_optins"
|
|
28
|
+
require_relative "ingest/handlers/messaging_handover"
|
|
29
|
+
require_relative "ingest/handlers/comments"
|
|
30
|
+
require_relative "ingest/handlers/mentions"
|
|
31
|
+
require_relative "ingest/handlers/story_insights"
|
|
32
|
+
require_relative "ingest/handlers/unknown"
|
|
33
|
+
require_relative "ingest/registry"
|
|
34
|
+
require_relative "ingest/dispatcher"
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
require "marcel"
|
|
2
|
+
require "stringio"
|
|
3
|
+
|
|
4
|
+
module InstagramConnect
|
|
5
|
+
module Media
|
|
6
|
+
# Turns fetched bytes into a stored file, or into an honest reason why not.
|
|
7
|
+
#
|
|
8
|
+
# The rule that matters here: when the declared Content-Type and the actual
|
|
9
|
+
# magic bytes disagree, the magic bytes win. A Content-Type header is
|
|
10
|
+
# metadata anyone can set; the first few bytes of the file are what the file
|
|
11
|
+
# actually is. Trusting the header is how a host ends up serving an HTML
|
|
12
|
+
# document from an <img> tag.
|
|
13
|
+
module Attaching
|
|
14
|
+
Result = Struct.new(:ok, :mime, :size, :error, keyword_init: true) do
|
|
15
|
+
def ok? = ok
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
module_function
|
|
19
|
+
|
|
20
|
+
def evaluate(body:, declared_mime:, filename: nil, config: InstagramConnect.configuration)
|
|
21
|
+
bytes = body.to_s
|
|
22
|
+
return failure("empty") if bytes.empty?
|
|
23
|
+
|
|
24
|
+
mime = sniff(bytes, filename: filename, declared: declared_mime)
|
|
25
|
+
return failure("type_not_allowed:#{mime}") unless allowed?(mime, config)
|
|
26
|
+
return failure("too_large:#{bytes.bytesize}") unless within_size?(mime, bytes.bytesize, config)
|
|
27
|
+
|
|
28
|
+
Result.new(ok: true, mime: mime, size: bytes.bytesize)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def sniff(bytes, filename: nil, declared: nil)
|
|
32
|
+
sniffed = ::Marcel::MimeType.for(StringIO.new(bytes), name: filename)
|
|
33
|
+
# Marcel falls back to this when it recognises nothing, in which case the
|
|
34
|
+
# declared type is the only information available and is better than
|
|
35
|
+
# nothing.
|
|
36
|
+
return declared.to_s.split(";").first.to_s.strip if sniffed == "application/octet-stream" && declared.present?
|
|
37
|
+
|
|
38
|
+
sniffed
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def allowed?(mime, config)
|
|
42
|
+
allowed = config.allowed_media_types
|
|
43
|
+
allowed.blank? || allowed.include?(mime)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Both Meta's per-type ceiling and the host's own cap have to hold. The
|
|
47
|
+
# host's exists so an adopter can be stricter than Meta, never looser.
|
|
48
|
+
def within_size?(mime, bytes, config)
|
|
49
|
+
Limits.within_size?(mime, bytes) && bytes <= config.media_max_bytes.to_i
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def failure(reason)
|
|
53
|
+
Result.new(ok: false, error: reason)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
module InstagramConnect
|
|
2
|
+
module Media
|
|
3
|
+
# Meta's ceilings, in one place, read by the composer, the send path and the
|
|
4
|
+
# client so the numbers cannot drift apart.
|
|
5
|
+
module Limits
|
|
6
|
+
IMAGE_MAX_BYTES = 8 * 1024 * 1024
|
|
7
|
+
AUDIO_VIDEO_MAX_BYTES = 25 * 1024 * 1024
|
|
8
|
+
ATTACHMENTS_MAX = 10
|
|
9
|
+
|
|
10
|
+
# BYTES, not characters. An emoji-heavy 400-character reply is over the
|
|
11
|
+
# limit and Meta rejects the whole send, so anything measuring this with
|
|
12
|
+
# String#length is measuring the wrong thing.
|
|
13
|
+
TEXT_MAX_BYTES = 1000
|
|
14
|
+
|
|
15
|
+
IMAGE_TYPES = %w[image/jpeg image/png image/gif].freeze
|
|
16
|
+
AUDIO_TYPES = %w[audio/aac audio/mp4 audio/mpeg audio/ogg audio/wav].freeze
|
|
17
|
+
VIDEO_TYPES = %w[video/mp4 video/ogg video/avi video/quicktime video/webm].freeze
|
|
18
|
+
|
|
19
|
+
module_function
|
|
20
|
+
|
|
21
|
+
# The ceiling that applies to a given MIME type. Images get a tighter one
|
|
22
|
+
# than audio and video, and an unknown type is held to the tighter of the
|
|
23
|
+
# two rather than waved through.
|
|
24
|
+
def max_bytes_for(mime)
|
|
25
|
+
image?(mime) ? IMAGE_MAX_BYTES : AUDIO_VIDEO_MAX_BYTES
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def image?(mime)
|
|
29
|
+
IMAGE_TYPES.include?(mime.to_s)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def within_size?(mime, bytes)
|
|
33
|
+
bytes.to_i.positive? && bytes.to_i <= max_bytes_for(mime)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Only images can be batched; Meta accepts one audio or video per message.
|
|
37
|
+
def attachments_within_limit?(count)
|
|
38
|
+
count.to_i <= ATTACHMENTS_MAX
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def text_within_limit?(text)
|
|
42
|
+
text.to_s.bytesize <= TEXT_MAX_BYTES
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
module InstagramConnect
|
|
2
|
+
# Keeps calls inside Meta's per-account ceilings.
|
|
3
|
+
#
|
|
4
|
+
# Meta publishes several limits at once and exhausting any of them throttles
|
|
5
|
+
# the whole app for hours, so the cost of being slightly conservative is far
|
|
6
|
+
# lower than the cost of being slightly wrong.
|
|
7
|
+
module RateLimiter
|
|
8
|
+
# Meta's documented per-account limits. The graph default is the floor of
|
|
9
|
+
# the 4800 × impressions formula: impressions are not knowable from the
|
|
10
|
+
# messaging API, so the floor is what is safe to assume until the usage
|
|
11
|
+
# headers say otherwise.
|
|
12
|
+
BUCKETS = {
|
|
13
|
+
graph: { limit: 4800, window: 86_400 },
|
|
14
|
+
conversations: { limit: 2, window: 1 },
|
|
15
|
+
send_text: { limit: 100, window: 1 },
|
|
16
|
+
send_media: { limit: 10, window: 1 },
|
|
17
|
+
private_reply: { limit: 750, window: 3600 },
|
|
18
|
+
publish: { limit: 50, window: 86_400 }
|
|
19
|
+
}.freeze
|
|
20
|
+
|
|
21
|
+
Outcome = Struct.new(:allowed, :retry_after, keyword_init: true) do
|
|
22
|
+
def allowed? = allowed
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
module_function
|
|
26
|
+
|
|
27
|
+
# Claims one call from a bucket. Returns an Outcome saying whether to
|
|
28
|
+
# proceed and, if not, how long to wait — callers re-enqueue rather than
|
|
29
|
+
# sleep, since a worker asleep on a rate limit is a worker not delivering
|
|
30
|
+
# anything else.
|
|
31
|
+
def acquire(account:, bucket:, now: Time.current)
|
|
32
|
+
spec = BUCKETS.fetch(bucket.to_sym)
|
|
33
|
+
row = budget_for(account, bucket, spec, now)
|
|
34
|
+
|
|
35
|
+
return Outcome.new(allowed: false, retry_after: (row.blocked_until - now).ceil) if row.blocked?
|
|
36
|
+
|
|
37
|
+
claimed = ApiBudget.where(id: row.id).where("used < limit_value")
|
|
38
|
+
.update_all("used = used + 1, updated_at = #{ApiBudget.connection.quote(now)}")
|
|
39
|
+
|
|
40
|
+
if claimed == 1
|
|
41
|
+
Outcome.new(allowed: true, retry_after: nil)
|
|
42
|
+
else
|
|
43
|
+
Outcome.new(allowed: false, retry_after: (row.window_end - now).ceil.clamp(1, spec[:window]))
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Records what Meta reported after a call. Its own numbers beat any local
|
|
48
|
+
# arithmetic, so a warning halves the remaining allowance and a critical
|
|
49
|
+
# reading blocks the account outright until the stated recovery time.
|
|
50
|
+
def observe(account:, bucket:, usage:, now: Time.current)
|
|
51
|
+
return if usage.nil?
|
|
52
|
+
|
|
53
|
+
spec = BUCKETS.fetch(bucket.to_sym)
|
|
54
|
+
row = budget_for(account, bucket, spec, now)
|
|
55
|
+
|
|
56
|
+
if usage.critical?
|
|
57
|
+
row.update!(blocked_until: now + (usage.retry_after || spec[:window]))
|
|
58
|
+
elsif usage.warning?
|
|
59
|
+
row.update!(limit_value: [ row.limit_value / 2, row.used + 1 ].max)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Called when Meta returns an explicit retry_after: one 429 pauses every
|
|
64
|
+
# job for that account, rather than each one having to discover it.
|
|
65
|
+
def block!(account:, bucket:, seconds:, now: Time.current)
|
|
66
|
+
spec = BUCKETS.fetch(bucket.to_sym)
|
|
67
|
+
budget_for(account, bucket, spec, now).update!(blocked_until: now + seconds.to_i)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def budget_for(account, bucket, spec, now)
|
|
71
|
+
start = window_start(now, spec[:window])
|
|
72
|
+
ApiBudget.find_or_create_by!(
|
|
73
|
+
account_id: account.id, bucket: bucket.to_s, window_start: start
|
|
74
|
+
) do |row|
|
|
75
|
+
row.window_seconds = spec[:window]
|
|
76
|
+
row.limit_value = spec[:limit]
|
|
77
|
+
end
|
|
78
|
+
rescue ActiveRecord::RecordNotUnique
|
|
79
|
+
ApiBudget.find_by!(account_id: account.id, bucket: bucket.to_s, window_start: start)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Fixed windows aligned to the epoch, so every process agrees on where a
|
|
83
|
+
# window starts without having to coordinate.
|
|
84
|
+
def window_start(now, seconds)
|
|
85
|
+
Time.at((now.to_i / seconds) * seconds).utc
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -3,15 +3,17 @@ module InstagramConnect
|
|
|
3
3
|
# API-level failures — callers branch on +success?+ and read +error_code+ /
|
|
4
4
|
# +error_message+. Transport/programming errors still raise.
|
|
5
5
|
class Result
|
|
6
|
-
attr_reader :success, :id, :error_code, :error_message, :retry_after, :data
|
|
6
|
+
attr_reader :success, :id, :error_code, :error_message, :retry_after, :data, :usage
|
|
7
7
|
|
|
8
|
-
def initialize(success:, id: nil, error_code: nil, error_message: nil, retry_after: nil,
|
|
8
|
+
def initialize(success:, id: nil, error_code: nil, error_message: nil, retry_after: nil,
|
|
9
|
+
data: {}, usage: nil)
|
|
9
10
|
@success = success
|
|
10
11
|
@id = id
|
|
11
12
|
@error_code = error_code
|
|
12
13
|
@error_message = error_message
|
|
13
14
|
@retry_after = retry_after
|
|
14
15
|
@data = data || {}
|
|
16
|
+
@usage = usage
|
|
15
17
|
end
|
|
16
18
|
|
|
17
19
|
def success?
|
|
@@ -22,13 +24,31 @@ module InstagramConnect
|
|
|
22
24
|
!success?
|
|
23
25
|
end
|
|
24
26
|
|
|
27
|
+
# Meta's cursor for the next page, or nil when this is the last one. Reading
|
|
28
|
+
# `paging.next` rather than incrementing an offset is the only correct way
|
|
29
|
+
# through a Graph collection — results shift under you between calls.
|
|
30
|
+
def next_cursor
|
|
31
|
+
data.dig("paging", "cursors", "after").presence if more?
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def more?
|
|
35
|
+
data.is_a?(Hash) && data.dig("paging", "next").present?
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# The rows of a collection response, or [] for a single-object one.
|
|
39
|
+
def records
|
|
40
|
+
list = data["data"]
|
|
41
|
+
list.is_a?(Array) ? list : []
|
|
42
|
+
end
|
|
43
|
+
|
|
25
44
|
# Convenience builders so call sites read cleanly.
|
|
26
|
-
def self.ok(id: nil, data: {})
|
|
27
|
-
new(success: true, id: id, data: data)
|
|
45
|
+
def self.ok(id: nil, data: {}, usage: nil)
|
|
46
|
+
new(success: true, id: id, data: data, usage: usage)
|
|
28
47
|
end
|
|
29
48
|
|
|
30
|
-
def self.error(message, error_code: nil, retry_after: nil, data: {})
|
|
31
|
-
new(success: false, error_message: message, error_code: error_code,
|
|
49
|
+
def self.error(message, error_code: nil, retry_after: nil, data: {}, usage: nil)
|
|
50
|
+
new(success: false, error_message: message, error_code: error_code,
|
|
51
|
+
retry_after: retry_after, data: data, usage: usage)
|
|
32
52
|
end
|
|
33
53
|
end
|
|
34
54
|
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
module InstagramConnect
|
|
2
|
+
# Splits a reply that exceeds Meta's 1000-byte message ceiling into parts that
|
|
3
|
+
# fit.
|
|
4
|
+
#
|
|
5
|
+
# Splitting rather than truncating is deliberate: a customer reading half an
|
|
6
|
+
# answer is worse than reading two bubbles, and the operator who wrote it has
|
|
7
|
+
# no way to know it was cut.
|
|
8
|
+
module TextSplitter
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# Returns the parts to send, in order. A message already within the limit
|
|
12
|
+
# comes back as a single-element array, so callers have one code path.
|
|
13
|
+
def split(text, limit: Media::Limits::TEXT_MAX_BYTES)
|
|
14
|
+
text = text.to_s
|
|
15
|
+
return [ text ] if text.bytesize <= limit
|
|
16
|
+
|
|
17
|
+
parts = []
|
|
18
|
+
remaining = text
|
|
19
|
+
|
|
20
|
+
while remaining.bytesize > limit
|
|
21
|
+
chunk = take(remaining, limit)
|
|
22
|
+
parts << chunk.rstrip
|
|
23
|
+
remaining = remaining[chunk.length..].to_s.lstrip
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Text that divides exactly on a break leaves nothing over; appending an
|
|
27
|
+
# empty part would send an empty bubble.
|
|
28
|
+
parts << remaining unless remaining.empty?
|
|
29
|
+
parts
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The longest prefix that fits, broken at whitespace where possible so words
|
|
33
|
+
# survive. Falls back to a hard character break for input with no
|
|
34
|
+
# whitespace at all — a long URL, or a script that does not use spaces.
|
|
35
|
+
def take(text, limit)
|
|
36
|
+
candidate = +""
|
|
37
|
+
last_break = nil
|
|
38
|
+
|
|
39
|
+
text.each_char do |char|
|
|
40
|
+
break if candidate.bytesize + char.bytesize > limit
|
|
41
|
+
|
|
42
|
+
candidate << char
|
|
43
|
+
last_break = candidate.length if char.match?(/\s/)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
return candidate if last_break.nil?
|
|
47
|
+
|
|
48
|
+
candidate[0, last_break]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
|
|
3
|
+
module InstagramConnect
|
|
4
|
+
# Meta's own account of how much of the rate budget a call just consumed,
|
|
5
|
+
# parsed from the response headers.
|
|
6
|
+
#
|
|
7
|
+
# This is worth having because the documented formula — 4800 calls per 24
|
|
8
|
+
# hours multiplied by the account's impressions — depends on a number the
|
|
9
|
+
# messaging API never returns. Any budget computed locally is a guess. These
|
|
10
|
+
# headers are Meta telling you the answer directly, so they are treated as
|
|
11
|
+
# ground truth and the arithmetic only as a fallback.
|
|
12
|
+
class Usage
|
|
13
|
+
HEADERS = %w[x-business-use-case-usage x-app-usage].freeze
|
|
14
|
+
|
|
15
|
+
# Back off well before the wall: at 100% Meta stops answering, and the
|
|
16
|
+
# penalty is measured in hours.
|
|
17
|
+
WARN_AT = 80
|
|
18
|
+
CRITICAL_AT = 95
|
|
19
|
+
|
|
20
|
+
attr_reader :call_count, :total_cputime, :total_time, :estimated_time_to_regain_access
|
|
21
|
+
|
|
22
|
+
def initialize(call_count: 0, total_cputime: 0, total_time: 0, estimated_time_to_regain_access: nil)
|
|
23
|
+
@call_count = call_count.to_i
|
|
24
|
+
@total_cputime = total_cputime.to_i
|
|
25
|
+
@total_time = total_time.to_i
|
|
26
|
+
@estimated_time_to_regain_access = estimated_time_to_regain_access
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Returns nil when Meta sent no usage headers, which is normal for some
|
|
30
|
+
# endpoints — absence is not zero usage and must not be read as headroom.
|
|
31
|
+
def self.from_headers(headers)
|
|
32
|
+
raw = HEADERS.filter_map { |name| headers&.[](name) }.first
|
|
33
|
+
return nil if raw.blank?
|
|
34
|
+
|
|
35
|
+
payload = JSON.parse(raw)
|
|
36
|
+
# The business header is keyed by object id and holds an array; the app
|
|
37
|
+
# header is a flat hash.
|
|
38
|
+
metrics = payload.is_a?(Hash) && payload.values.first.is_a?(Array) ? payload.values.first.first : payload
|
|
39
|
+
return nil unless metrics.is_a?(Hash)
|
|
40
|
+
|
|
41
|
+
new(
|
|
42
|
+
call_count: metrics["call_count"],
|
|
43
|
+
total_cputime: metrics["total_cputime"],
|
|
44
|
+
total_time: metrics["total_time"],
|
|
45
|
+
estimated_time_to_regain_access: metrics["estimated_time_to_regain_access"]
|
|
46
|
+
)
|
|
47
|
+
rescue JSON::ParserError
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# The worst of the three, since exhausting any one of them throttles the app.
|
|
52
|
+
def percentage
|
|
53
|
+
[ call_count, total_cputime, total_time ].max
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def warning?
|
|
57
|
+
percentage >= WARN_AT
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def critical?
|
|
61
|
+
percentage >= CRITICAL_AT
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def retry_after
|
|
65
|
+
estimated_time_to_regain_access.to_i * 60 if estimated_time_to_regain_access.to_i.positive?
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
data/lib/instagram_connect.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
require "logger"
|
|
2
2
|
require_relative "instagram_connect/version"
|
|
3
3
|
require_relative "instagram_connect/errors"
|
|
4
|
+
require_relative "instagram_connect/usage"
|
|
4
5
|
require_relative "instagram_connect/result"
|
|
5
6
|
require_relative "instagram_connect/configuration"
|
|
6
7
|
require_relative "instagram_connect/auth/strategy"
|
|
@@ -10,8 +11,12 @@ require_relative "instagram_connect/auth"
|
|
|
10
11
|
require_relative "instagram_connect/client"
|
|
11
12
|
require_relative "instagram_connect/connect"
|
|
12
13
|
require_relative "instagram_connect/signature_verifier"
|
|
14
|
+
require_relative "instagram_connect/media/limits"
|
|
15
|
+
require_relative "instagram_connect/media/attaching"
|
|
16
|
+
require_relative "instagram_connect/text_splitter"
|
|
13
17
|
require_relative "instagram_connect/messaging_window"
|
|
14
18
|
require_relative "instagram_connect/ingest"
|
|
19
|
+
require_relative "instagram_connect/rate_limiter"
|
|
15
20
|
require_relative "instagram_connect/doctor"
|
|
16
21
|
|
|
17
22
|
# InstagramConnect connects a Rails app to Instagram over the official Meta
|
|
@@ -25,6 +30,24 @@ require_relative "instagram_connect/doctor"
|
|
|
25
30
|
# c.verify_token = Rails.application.credentials.dig(:instagram_connect, :verify_token)
|
|
26
31
|
# end
|
|
27
32
|
module InstagramConnect
|
|
33
|
+
# Every table the gem's migrations own, in dependency order (parents first).
|
|
34
|
+
# Hosts use it to audit what the engine added to their schema; the suite uses
|
|
35
|
+
# it to assert the migrations actually built what the models expect.
|
|
36
|
+
TABLES = %w[
|
|
37
|
+
instagram_connect_accounts
|
|
38
|
+
instagram_connect_conversations
|
|
39
|
+
instagram_connect_messages
|
|
40
|
+
instagram_connect_inbound_messages
|
|
41
|
+
instagram_connect_comments
|
|
42
|
+
instagram_connect_webhook_events
|
|
43
|
+
instagram_connect_message_reactions
|
|
44
|
+
instagram_connect_message_attachments
|
|
45
|
+
instagram_connect_media
|
|
46
|
+
instagram_connect_mentions
|
|
47
|
+
instagram_connect_insight_snapshots
|
|
48
|
+
instagram_connect_api_budgets
|
|
49
|
+
].freeze
|
|
50
|
+
|
|
28
51
|
class << self
|
|
29
52
|
def configuration
|
|
30
53
|
@configuration ||= Configuration.new
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: instagram_connect
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Kshitiz Sinha
|
|
@@ -51,6 +51,20 @@ dependencies:
|
|
|
51
51
|
- - ">="
|
|
52
52
|
- !ruby/object:Gem::Version
|
|
53
53
|
version: '1.0'
|
|
54
|
+
- !ruby/object:Gem::Dependency
|
|
55
|
+
name: marcel
|
|
56
|
+
requirement: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - ">="
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '1.0'
|
|
61
|
+
type: :runtime
|
|
62
|
+
prerelease: false
|
|
63
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - ">="
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: '1.0'
|
|
54
68
|
description: 'A mountable Rails engine that connects your app to Instagram: receive
|
|
55
69
|
and reply to DMs and comments in real time over HMAC-verified webhooks, publish
|
|
56
70
|
posts, and manage OAuth tokens — using the official Instagram Graph API (Instagram-Login
|
|
@@ -67,7 +81,6 @@ files:
|
|
|
67
81
|
- CHANGELOG.md
|
|
68
82
|
- Gemfile
|
|
69
83
|
- LICENSE.txt
|
|
70
|
-
- MIT-LICENSE
|
|
71
84
|
- README.md
|
|
72
85
|
- Rakefile
|
|
73
86
|
- app/assets/stylesheets/instagram_connect/application.css
|
|
@@ -79,16 +92,27 @@ files:
|
|
|
79
92
|
- app/controllers/instagram_connect/posts_controller.rb
|
|
80
93
|
- app/controllers/instagram_connect/webhooks_controller.rb
|
|
81
94
|
- app/helpers/instagram_connect/application_helper.rb
|
|
95
|
+
- app/jobs/instagram_connect/account_readiness_job.rb
|
|
82
96
|
- app/jobs/instagram_connect/application_job.rb
|
|
97
|
+
- app/jobs/instagram_connect/fetch_media_job.rb
|
|
83
98
|
- app/jobs/instagram_connect/ingest_job.rb
|
|
99
|
+
- app/jobs/instagram_connect/profile_sync_job.rb
|
|
84
100
|
- app/jobs/instagram_connect/refresh_tokens_job.rb
|
|
101
|
+
- app/jobs/instagram_connect/replay_events_job.rb
|
|
85
102
|
- app/jobs/instagram_connect/send_message_job.rb
|
|
86
103
|
- app/models/instagram_connect/account.rb
|
|
104
|
+
- app/models/instagram_connect/api_budget.rb
|
|
87
105
|
- app/models/instagram_connect/application_record.rb
|
|
88
106
|
- app/models/instagram_connect/comment.rb
|
|
89
107
|
- app/models/instagram_connect/conversation.rb
|
|
90
108
|
- app/models/instagram_connect/inbound_message.rb
|
|
109
|
+
- app/models/instagram_connect/insight_snapshot.rb
|
|
110
|
+
- app/models/instagram_connect/media_item.rb
|
|
111
|
+
- app/models/instagram_connect/mention.rb
|
|
91
112
|
- app/models/instagram_connect/message.rb
|
|
113
|
+
- app/models/instagram_connect/message_attachment.rb
|
|
114
|
+
- app/models/instagram_connect/message_reaction.rb
|
|
115
|
+
- app/models/instagram_connect/webhook_event.rb
|
|
92
116
|
- app/views/instagram_connect/comments/_comment.html.erb
|
|
93
117
|
- app/views/instagram_connect/comments/index.html.erb
|
|
94
118
|
- app/views/instagram_connect/conversations/_composer.html.erb
|
|
@@ -106,6 +130,19 @@ files:
|
|
|
106
130
|
- db/migrate/20260715072550_create_instagram_connect_messages.rb
|
|
107
131
|
- db/migrate/20260715072551_create_instagram_connect_inbound_messages.rb
|
|
108
132
|
- db/migrate/20260715072552_create_instagram_connect_comments.rb
|
|
133
|
+
- db/migrate/20260725194732_create_instagram_connect_webhook_events.rb
|
|
134
|
+
- db/migrate/20260725200216_add_messaging_event_fields.rb
|
|
135
|
+
- db/migrate/20260725200250_create_instagram_connect_message_reactions.rb
|
|
136
|
+
- db/migrate/20260725201320_create_instagram_connect_message_attachments.rb
|
|
137
|
+
- db/migrate/20260725202616_add_outbound_send_fields.rb
|
|
138
|
+
- db/migrate/20260725203213_create_instagram_connect_media.rb
|
|
139
|
+
- db/migrate/20260725203214_create_instagram_connect_mentions.rb
|
|
140
|
+
- db/migrate/20260725203215_create_instagram_connect_insight_snapshots.rb
|
|
141
|
+
- db/migrate/20260725203306_add_comment_moderation_fields.rb
|
|
142
|
+
- db/migrate/20260725204022_add_per_account_token_fields.rb
|
|
143
|
+
- db/migrate/20260725204815_create_instagram_connect_api_budgets.rb
|
|
144
|
+
- db/migrate/20260725205417_add_conversation_profile_fields.rb
|
|
145
|
+
- docs/CONFIGURATION.md
|
|
109
146
|
- docs/app_review_guide.md
|
|
110
147
|
- docs/auth_paths.md
|
|
111
148
|
- docs/roadmap.md
|
|
@@ -126,10 +163,31 @@ files:
|
|
|
126
163
|
- lib/instagram_connect/engine.rb
|
|
127
164
|
- lib/instagram_connect/errors.rb
|
|
128
165
|
- lib/instagram_connect/ingest.rb
|
|
166
|
+
- lib/instagram_connect/ingest/dispatcher.rb
|
|
167
|
+
- lib/instagram_connect/ingest/envelope.rb
|
|
168
|
+
- lib/instagram_connect/ingest/handlers/base.rb
|
|
169
|
+
- lib/instagram_connect/ingest/handlers/comments.rb
|
|
170
|
+
- lib/instagram_connect/ingest/handlers/mentions.rb
|
|
171
|
+
- lib/instagram_connect/ingest/handlers/message_reactions.rb
|
|
172
|
+
- lib/instagram_connect/ingest/handlers/messages.rb
|
|
173
|
+
- lib/instagram_connect/ingest/handlers/messaging_handover.rb
|
|
174
|
+
- lib/instagram_connect/ingest/handlers/messaging_optins.rb
|
|
175
|
+
- lib/instagram_connect/ingest/handlers/messaging_postbacks.rb
|
|
176
|
+
- lib/instagram_connect/ingest/handlers/messaging_referral.rb
|
|
177
|
+
- lib/instagram_connect/ingest/handlers/messaging_seen.rb
|
|
178
|
+
- lib/instagram_connect/ingest/handlers/story_insights.rb
|
|
179
|
+
- lib/instagram_connect/ingest/handlers/unknown.rb
|
|
180
|
+
- lib/instagram_connect/ingest/registry.rb
|
|
181
|
+
- lib/instagram_connect/ingest/summary.rb
|
|
182
|
+
- lib/instagram_connect/media/attaching.rb
|
|
183
|
+
- lib/instagram_connect/media/limits.rb
|
|
129
184
|
- lib/instagram_connect/messaging_window.rb
|
|
130
185
|
- lib/instagram_connect/railtie.rb
|
|
186
|
+
- lib/instagram_connect/rate_limiter.rb
|
|
131
187
|
- lib/instagram_connect/result.rb
|
|
132
188
|
- lib/instagram_connect/signature_verifier.rb
|
|
189
|
+
- lib/instagram_connect/text_splitter.rb
|
|
190
|
+
- lib/instagram_connect/usage.rb
|
|
133
191
|
- lib/instagram_connect/version.rb
|
|
134
192
|
homepage: https://github.com/kshtzkr/instagram_connect
|
|
135
193
|
licenses:
|