Class: Webhookdb::Replicator::SignalwireMessageV1

Inherits:
Base
  • Object
show all
Includes:
Appydays::Loggable
Defined in:
lib/webhookdb/replicator/signalwire_message_v1.rb

Constant Summary

Constants inherited from Base

Base::MAX_INDEX_NAME_LENGTH

Constants included from DBAdapter::ColumnTypes

DBAdapter::ColumnTypes::BIGINT, DBAdapter::ColumnTypes::BIGINT_ARRAY, DBAdapter::ColumnTypes::BOOLEAN, DBAdapter::ColumnTypes::COLUMN_TYPES, DBAdapter::ColumnTypes::DATE, DBAdapter::ColumnTypes::DECIMAL, DBAdapter::ColumnTypes::DOUBLE, DBAdapter::ColumnTypes::FLOAT, DBAdapter::ColumnTypes::INTEGER, DBAdapter::ColumnTypes::INTEGER_ARRAY, DBAdapter::ColumnTypes::OBJECT, DBAdapter::ColumnTypes::TEXT, DBAdapter::ColumnTypes::TEXT_ARRAY, DBAdapter::ColumnTypes::TIMESTAMP, DBAdapter::ColumnTypes::UUID

Instance Attribute Summary

Attributes inherited from Base

#service_integration

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#_any_subscriptions_to_notify?, #_backfill_state_change_fields, #_backfillers, #_clear_backfill_information, #_clear_webook_information, #_coalesce_excluded_on_update, #_enqueue_backfill_jobs, #_extra_index_specs, #_fetch_enrichment, #_find_dependency_candidate, #_notify_dependents, #_parallel_backfill, #_prepare_for_insert, #_publish_rowupsert, #_resource_to_data, #_store_enrichment_body?, #_to_json, #_upsert_update_expr, #_upsert_webhook, #_webhook_state_change_fields, #admin_dataset, #backfill, #backfill_not_supported_message, #calculate_and_backfill_state_machine, #calculate_dependency_state_machine_step, #calculate_preferred_create_state_machine, #calculate_webhook_state_machine, chunked_row_update_bounds, #clear_backfill_information, #clear_webhook_information, #create_table, #create_table_modification, #data_column, #dbadapter_table, #denormalized_columns, #descriptor, #dispatch_request_to, #documentation_url, #enqueue_sync_targets, #enrichment_column, #ensure_all_columns, #ensure_all_columns_modification, #find_dependent, #find_dependent!, #indices, #initialize, #on_dependency_webhook_upsert, #preferred_create_state_machine_method, #preprocess_headers_for_logging, #primary_key_column, #process_webhooks_synchronously?, #qualified_table_sequel_identifier, #readonly_dataset, #remote_key_column, #requires_sequence?, #resource_name_plural, #resource_name_singular, #schema_and_table_symbols, #storable_columns, #synchronous_processing_response_body, #timestamp_column, #upsert_has_deps?, #upsert_webhook, #upsert_webhook_body, #verify_backfill_credentials, #webhook_endpoint, #webhook_response

Constructor Details

This class inherits a constructor from Webhookdb::Replicator::Base

Class Method Details

.descriptorWebhookdb::Replicator::Descriptor



11
12
13
14
15
16
17
18
19
20
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 11

def self.descriptor
  return Webhookdb::Replicator::Descriptor.new(
    name: "signalwire_message_v1",
    ctor: ->(sint) { Webhookdb::Replicator::SignalwireMessageV1.new(sint) },
    feature_roles: [],
    resource_name_singular: "SignalWire Message",
    supports_backfill: true,
    api_docs_url: "https://developer.signalwire.com/compatibility-api/rest/list-all-messages",
  )
end

Instance Method Details

#_denormalized_columnsObject



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 118

def _denormalized_columns
  return [
    Webhookdb::Replicator::Column.new(
      :date_created,
      TIMESTAMP,
      index: true,
      converter: Webhookdb::Replicator::Column::CONV_PARSE_TIME,
    ),
    Webhookdb::Replicator::Column.new(
      :date_sent,
      TIMESTAMP,
      index: true,
      converter: Webhookdb::Replicator::Column::CONV_PARSE_TIME,
    ),
    Webhookdb::Replicator::Column.new(
      :date_updated,
      TIMESTAMP,
      index: true,
      converter: Webhookdb::Replicator::Column::CONV_PARSE_TIME,
    ),
    Webhookdb::Replicator::Column.new(:direction, TEXT),
    Webhookdb::Replicator::Column.new(:from, TEXT, index: true),
    Webhookdb::Replicator::Column.new(:status, TEXT),
    Webhookdb::Replicator::Column.new(:to, TEXT, index: true),
  ]
end

#_fetch_backfill_page(pagination_token, last_backfilled:) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 157

def _fetch_backfill_page(pagination_token, last_backfilled:)
  urltail = pagination_token
  if pagination_token.blank?
    # We need to handle positive and negative UTC offset running locally (non-UTC).
    # Using UTC + 1 day would give 'today' in some cases, we always want 'tomorrow the day after'.
    date_send_max = (Time.now.utc + 2.days).to_date
    urltail = "/2010-04-01/Accounts/#{self.service_integration.backfill_key}/Messages.json" \
              "?PageSize=100&DateSend%3C=#{date_send_max}"
  end
  data = Webhookdb::Signalwire.http_request(
    :get,
    urltail,
    space_url: self.service_integration.api_url,
    project_id: self.service_integration.backfill_key,
    api_key: self.service_integration.backfill_secret,
    logger: self.logger,
  )
  messages = data["messages"]

  if last_backfilled.present?
    earliest_data_created = messages.empty? ? Time.at(0) : messages[-1].fetch("date_created")
    paged_to_already_seen_records = earliest_data_created < last_backfilled

    return messages, nil if paged_to_already_seen_records
  end

  return messages, data["next_page_uri"]
end

#_remote_key_columnObject



114
115
116
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 114

def _remote_key_column
  return Webhookdb::Replicator::Column.new(:signalwire_id, TEXT, data_key: "sid")
end

#_resource_and_event(request) ⇒ Object



149
150
151
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 149

def _resource_and_event(request)
  return request.body, nil
end

#_timestamp_column_nameObject



145
146
147
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 145

def _timestamp_column_name
  return :date_updated
end

#_update_where_exprObject



153
154
155
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 153

def _update_where_expr
  return self.qualified_table_sequel_identifier[:date_updated] < Sequel[:excluded][:date_updated]
end

#_verify_backfill_401_err_msgObject



106
107
108
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 106

def _verify_backfill_401_err_msg
  return "It looks like that API Key is invalid. Please reenter the API Key you just created:"
end

#_verify_backfill_err_msgObject



110
111
112
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 110

def _verify_backfill_err_msg
  return "An error occurred. Please reenter the API Key you just created:"
end

#_webhook_response(request) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 22

def _webhook_response(request)
  auth = request.get_header("Authorization")
  if auth.nil? || !auth.match(/^Basic /)
    return Webhookdb::WebhookResponse.new(
      status: 401,
      body: "",
      reason: "challenge",
      headers: {"Content-Type" => "text/plain", "WWW-Authenticate" => 'Basic realm="Webhookdb"'},
    )
  end
  user_and_pass = Base64.decode64(auth.gsub(/^Basic /, ""))
  if user_and_pass != self.service_integration.webhook_secret
    return Webhookdb::WebhookResponse.new(
      status: 401,
      body: "",
      reason: "invalid",
      headers: {"Content-Type" => "text/plain"},
    )
  end
  return Webhookdb::WebhookResponse.new(
    status: 202,
    headers: {"Content-Type" => "text/xml"},
    body: "<Response></Response>",
  )
end

#calculate_backfill_state_machineObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 58

def calculate_backfill_state_machine
  step = Webhookdb::Replicator::StateMachineStep.new
  unless self.service_integration.api_url.present?
    step.output = %(Let's finish setting up your SignalWire Messaging (SMS) integration.

Rather than using your phone number's webhooks (of which each number can have only one),
we poll SignalWire for changes, and will also backfill historical messages.

To do this, we need your Space URL, Project ID, and an API Token.

First enter your Space URL. You can see this on your SignalWire dashboard.
It's the part of your dashboard URL before '.signalwire.com'.)
    return step.prompting("Space URL").api_url(self.service_integration)
  end

  unless self.service_integration.backfill_key.present?
    step.output = %(You can get your Project ID from the 'API' section of your SignalWire dashboard.

Go to https://#{self.service_integration.api_url}.signalwire.com/credentials and copy your Project ID.)
    return step.prompting("Project ID").backfill_key(self.service_integration)
  end

  unless self.service_integration.backfill_secret.present?
    step.needs_input = true
    step.output = %(Let's create or reuse an API token.

Go to https://#{self.service_integration.api_url}.signalwire.com/credentials
and press the 'New' button.
Name the token something like 'WebhookDB'.
Under Scopes, ensure the 'Messaging' checkbox is checked.
Then press 'Save'.

Press 'Show' next to the newly-created API token, and copy it.)
    return step.secret_prompt("API Token").backfill_secret(self.service_integration)
  end

  unless (result = self.verify_backfill_credentials).verified
    self.service_integration.replicator.clear_backfill_information
    step.output = result.message
    return step.secret_prompt("API Key").backfill_key(self.service_integration)
  end

  step.output = %(We are going to start replicating your SignalWire Messages, and will keep it updated.
#{self._query_help_output}
    )
  return step.completed
end

#on_backfill_error(be) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 186

def on_backfill_error(be)
  e = Webhookdb::Errors.find_cause(be) do |ex|
    next true if ex.is_a?(Webhookdb::Http::Error) && ex.status == 401
    next true if ex.is_a?(::SocketError)
  end
  return unless e
  if e.is_a?(::SocketError)
    response_status = 0
    response_body = e.message
    request_url = "<unknown>"
    request_method = "<unknown>"
  else
    response_status = e.status
    response_body = e.body
    request_url = e.uri.to_s
    request_method = e.http_method
  end
  self.logger.warn("signalwire_backfill_error", response_body:, response_status:, request_url:)
  message = Webhookdb::Messages::ErrorGenericBackfill.new(
    self.service_integration,
    response_status:,
    response_body:,
    request_url:,
    request_method:,
  )
  self.service_integration.organization.alerting.dispatch_alert(message)
  return true
end

#process_state_change(field, value, attr: nil) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/webhookdb/replicator/signalwire_message_v1.rb', line 48

def process_state_change(field, value, attr: nil)
  if field == "api_url" && value.include?(".")
    value = "https://" + value unless value.include?("://")
    u = URI(value)
    h = u.host.gsub(/\.signalwire\.com$/, "")
    value = h
  end
  return super(field, value, attr:)
end