2020-04-05 16:41:27 +00:00
|
|
|
class ContactBuilder
|
2021-06-15 14:39:17 +00:00
|
|
|
pattr_initialize [:source_id!, :inbox!, :contact_attributes!, :hmac_verified]
|
2020-04-05 16:41:27 +00:00
|
|
|
|
|
|
|
def perform
|
|
|
|
contact_inbox = inbox.contact_inboxes.find_by(source_id: source_id)
|
|
|
|
return contact_inbox if contact_inbox
|
|
|
|
|
2021-01-18 06:13:31 +00:00
|
|
|
build_contact_inbox
|
2020-04-05 16:41:27 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def account
|
|
|
|
@account ||= inbox.account
|
|
|
|
end
|
|
|
|
|
2020-05-14 17:21:07 +00:00
|
|
|
def create_contact_inbox(contact)
|
|
|
|
::ContactInbox.create!(
|
|
|
|
contact_id: contact.id,
|
|
|
|
inbox_id: inbox.id,
|
2021-06-15 14:39:17 +00:00
|
|
|
source_id: source_id,
|
|
|
|
hmac_verified: hmac_verified || false
|
2020-05-14 17:21:07 +00:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_contact_avatar(contact)
|
|
|
|
::ContactAvatarJob.perform_later(contact, contact_attributes[:avatar_url]) if contact_attributes[:avatar_url]
|
|
|
|
end
|
|
|
|
|
2021-01-18 06:13:31 +00:00
|
|
|
def create_contact
|
|
|
|
account.contacts.create!(
|
2021-06-15 14:39:17 +00:00
|
|
|
name: contact_attributes[:name] || ::Haikunator.haikunate(1000),
|
2021-01-18 06:13:31 +00:00
|
|
|
phone_number: contact_attributes[:phone_number],
|
|
|
|
email: contact_attributes[:email],
|
|
|
|
identifier: contact_attributes[:identifier],
|
|
|
|
additional_attributes: contact_attributes[:additional_attributes]
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def find_contact
|
|
|
|
contact = nil
|
|
|
|
|
|
|
|
contact = account.contacts.find_by(identifier: contact_attributes[:identifier]) if contact_attributes[:identifier].present?
|
2020-04-29 20:11:13 +00:00
|
|
|
|
2021-01-18 06:13:31 +00:00
|
|
|
contact ||= account.contacts.find_by(email: contact_attributes[:email]) if contact_attributes[:email].present?
|
|
|
|
|
2021-04-20 17:12:14 +00:00
|
|
|
contact ||= account.contacts.find_by(phone_number: contact_attributes[:phone_number]) if contact_attributes[:phone_number].present?
|
|
|
|
|
2021-01-18 06:13:31 +00:00
|
|
|
contact
|
|
|
|
end
|
|
|
|
|
|
|
|
def build_contact_inbox
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
contact = find_contact || create_contact
|
2020-05-14 17:21:07 +00:00
|
|
|
contact_inbox = create_contact_inbox(contact)
|
|
|
|
update_contact_avatar(contact)
|
2020-04-05 16:41:27 +00:00
|
|
|
contact_inbox
|
|
|
|
rescue StandardError => e
|
2020-05-14 17:21:07 +00:00
|
|
|
Rails.logger.info e
|
2020-04-05 16:41:27 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|