Chatwoot/app/models/message.rb

290 lines
10 KiB
Ruby
Raw Normal View History

# == Schema Information
#
# Table name: messages
#
# id :integer not null, primary key
# additional_attributes :jsonb
# content :text
# content_attributes :json
# content_type :integer default("text"), not null
# external_source_ids :jsonb
# message_type :integer not null
# private :boolean default(FALSE)
# sender_type :string
# status :integer default("sent")
# created_at :datetime not null
# updated_at :datetime not null
# account_id :integer not null
# conversation_id :integer not null
# inbox_id :integer not null
# sender_id :bigint
# source_id :string
#
# Indexes
#
# index_messages_on_account_id (account_id)
# index_messages_on_additional_attributes_campaign_id (((additional_attributes -> 'campaign_id'::text))) USING gin
# index_messages_on_conversation_id (conversation_id)
# index_messages_on_inbox_id (inbox_id)
# index_messages_on_sender_type_and_sender_id (sender_type,sender_id)
# index_messages_on_source_id (source_id)
#
class Message < ApplicationRecord
2021-08-23 16:30:47 +00:00
include MessageFilterHelpers
NUMBER_OF_PERMITTED_ATTACHMENTS = 15
2022-12-05 16:08:12 +00:00
include PgSearch::Model
include MultiSearchableHelpers
multisearchable(
against: [:content],
if: :allowed_message_types?,
additional_attributes: ->(message) { { conversation_id: message.conversation_id, account_id: message.account_id } }
)
before_validation :ensure_content_type
validates :account_id, presence: true
validates :inbox_id, presence: true
validates :conversation_id, presence: true
validates_with ContentAttributeValidator
validates :content_type, presence: true
validates :content, length: { maximum: 150_000 }
# when you have a temperory id in your frontend and want it echoed back via action cable
attr_accessor :echo_id
enum message_type: { incoming: 0, outgoing: 1, activity: 2, template: 3 }
enum content_type: {
text: 0,
input_text: 1,
input_textarea: 2,
input_email: 3,
input_select: 4,
cards: 5,
form: 6,
Feature: Conversation Continuity with Email (#770) * Added POC for mail inbox reply email * created mailbox and migratuion for the same * cleaned up sidekiq queues and added the queues for action mailbox and active storage * created conversation mailbox and functionlaity to create a message on the conversation when it's replied * Added UUID to conversation to be used in email replies * added migration to add uuid for conversation * changed parsing and resource fetching to reflect matching uuid and loading conversation alone * cleaned up conversation mailbox.rb * Added content type & attribute for message * Added the new reply email to outgoing emails * Added migration to accounts for adding domain and settings * Modified seeds to reflect this changes * Added the flag based column on account for boolean settings * Added the new reply to email in outgoing conversation emails based on conditions * Added dynamic email routing in application mailbox * Added dynamic email routing in application mailbox * Added a catch all deafult empty mailbox * Added annotation for account * Added the complete email details & attachments to the message * Added the complete email details to the message in content_attributes, like subject, to, cc, bcc etc * Modified the mail extractor to give a serilaized version of email * Handled storing attachments of email on the message * Added incoming email settings, env variables * [#138] Added documentation regarding different email settings and variables * Fixed the mail attachments blob issue (#138) * Decoided attachments were strings and had to construct blobs out fo them to work with active storage * Fixed the content encoding issue with mail body * Fixed issue with Proc used in apllication mailbox routing * Fixed couple of typos and silly mistakes * Set appropriate from email for conversation reply mails (#138) * From email was taken from a env variable, changed it to take from account settings if enabled * Set the reply to email correctly based on conversation UUID * Added commented config ind development.rb for mailbox ingress * Added account settings for domain and support email (#138) * Added the new attributes in accounts controller params whitelisting, api responses * Added options for the the new fields in account settings * Fixed typos in email continuity docs and warnings * Added specs for conversation reply mailer changes (#138) * Added specs for * conversation reply mailer * Accounts controller * Account and Conversation models * Added tests for email presenter (#138) * Specs for inbound email routing and mailboxes (#138)
2020-04-30 14:50:26 +00:00
article: 7,
incoming_email: 8,
input_csat: 9
}
enum status: { sent: 0, delivered: 1, read: 2, failed: 3 }
# [:submitted_email, :items, :submitted_values] : Used for bot message types
# [:email] : Used by conversation_continuity incoming email messages
# [:in_reply_to] : Used to reply to a particular tweet in threads
# [:deleted] : Used to denote whether the message was deleted by the agent
# [:external_created_at] : Can specify if the message was created at a different timestamp externally
# [:external_error : Can specify if the message creation failed due to an error at external API
store :content_attributes, accessors: [:submitted_email, :items, :submitted_values, :email, :in_reply_to, :deleted,
:external_created_at, :story_sender, :story_id, :external_error], coder: JSON
store :external_source_ids, accessors: [:slack], coder: JSON, prefix: :external_source_id
# .succ is a hack to avoid https://makandracards.com/makandra/1057-why-two-ruby-time-objects-are-not-equal-although-they-appear-to-be
scope :unread_since, ->(datetime) { where('EXTRACT(EPOCH FROM created_at) > (?)', datetime.to_i.succ) }
scope :chat, -> { where.not(message_type: :activity).where(private: false) }
scope :non_activity_messages, -> { where.not(message_type: :activity).reorder('id desc') }
scope :today, -> { where("date_trunc('day', created_at) = ?", Date.current) }
default_scope { order(created_at: :asc) }
belongs_to :account
belongs_to :inbox
belongs_to :conversation, touch: true
# FIXME: phase out user and contact after 1.4 since the info is there in sender
belongs_to :user, required: false
belongs_to :contact, required: false
belongs_to :sender, polymorphic: true, required: false
has_many :attachments, dependent: :destroy, autosave: true, before_add: :validate_attachments_limit
has_one :csat_survey_response, dependent: :destroy_async
has_many :notifications, as: :primary_actor, dependent: :destroy_async
after_create_commit :execute_after_create_commit_callbacks
2021-07-14 04:50:06 +00:00
after_update_commit :dispatch_update_event
def channel_token
@token ||= inbox.channel.try(:page_access_token)
end
def push_event_data
data = attributes.merge(
created_at: created_at.to_i,
message_type: message_type_before_type_cast,
conversation_id: conversation.display_id,
conversation: { assignee_id: conversation.assignee_id }
)
data.merge!(echo_id: echo_id) if echo_id.present?
validate_instagram_story if instagram_story_mention?
data.merge!(attachments: attachments.map(&:push_event_data)) if attachments.present?
merge_sender_attributes(data)
end
# TODO: We will be removing this code after instagram_manage_insights is implemented
# Better logic is to listen to webhook and remove stories proactively rather than trying
# a fetch every time a message is returned
def validate_instagram_story
inbox.channel.fetch_instagram_story_link(self)
# we want to reload the message in case the story has expired and data got removed
reload
end
def merge_sender_attributes(data)
data.merge!(sender: sender.push_event_data) if sender && !sender.is_a?(AgentBot)
data.merge!(sender: sender.push_event_data(inbox)) if sender.is_a?(AgentBot)
data
end
def webhook_data
data = {
account: account.webhook_data,
additional_attributes: additional_attributes,
content_attributes: content_attributes,
content_type: content_type,
content: content,
conversation: conversation.webhook_data,
created_at: created_at,
id: id,
inbox: inbox.webhook_data,
message_type: message_type,
private: private,
sender: sender.try(:webhook_data),
source_id: source_id
}
data.merge!(attachments: attachments.map(&:push_event_data)) if attachments.present?
data
end
2021-08-23 16:30:47 +00:00
def content
# move this to a presenter
return self[:content] if !input_csat? || inbox.web_widget?
I18n.t('conversations.survey.response', link: "#{ENV.fetch('FRONTEND_URL', nil)}/survey/responses/#{conversation.uuid}")
2021-08-23 16:30:47 +00:00
end
def email_notifiable_message?
return false if private?
return false if %w[outgoing template].exclude?(message_type)
return false if template? && %w[input_csat text].exclude?(content_type)
true
end
private
def ensure_content_type
self.content_type ||= Message.content_types[:text]
end
def execute_after_create_commit_callbacks
# rails issue with order of active record callbacks being executed https://github.com/rails/rails/issues/20911
2021-08-23 16:30:47 +00:00
reopen_conversation
notify_via_mail
set_conversation_activity
dispatch_create_events
send_reply
execute_message_template_hooks
update_contact_activity
end
def update_contact_activity
sender.update(last_activity_at: DateTime.now) if sender.is_a?(Contact)
end
def dispatch_create_events
2022-04-12 14:53:34 +00:00
Rails.configuration.dispatcher.dispatch(MESSAGE_CREATED, Time.zone.now, message: self, performed_by: Current.executed_by)
if outgoing? && conversation.messages.outgoing.where("(additional_attributes->'campaign_id') is null").count == 1
2022-04-12 14:53:34 +00:00
Rails.configuration.dispatcher.dispatch(FIRST_REPLY_CREATED, Time.zone.now, message: self, performed_by: Current.executed_by)
end
end
def dispatch_update_event
2022-04-12 14:53:34 +00:00
Rails.configuration.dispatcher.dispatch(MESSAGE_UPDATED, Time.zone.now, message: self, performed_by: Current.executed_by)
end
def send_reply
2021-04-13 08:39:51 +00:00
# FIXME: Giving it few seconds for the attachment to be uploaded to the service
# active storage attaches the file only after commit
attachments.blank? ? ::SendReplyJob.perform_later(id) : ::SendReplyJob.set(wait: 2.seconds).perform_later(id)
end
def reopen_conversation
return if conversation.muted?
return unless incoming?
conversation.open! if conversation.snoozed?
reopen_resolved_conversation if conversation.resolved?
end
def reopen_resolved_conversation
# mark resolved bot conversation as pending to be reopened by bot processor service
if conversation.inbox.active_bot?
conversation.pending!
else
conversation.open!
end
end
def execute_message_template_hooks
::MessageTemplates::HookExecutionService.new(message: self).perform
end
def email_notifiable_webwidget?
inbox.web_widget? && inbox.channel.continuity_via_email
end
def email_notifiable_api_channel?
inbox.api? && inbox.account.feature_enabled?('email_continuity_on_api_channel')
end
def email_notifiable_channel?
email_notifiable_webwidget? || %w[Email].include?(inbox.inbox_type) || email_notifiable_api_channel?
end
def can_notify_via_mail?
return unless email_notifiable_message?
return unless email_notifiable_channel?
return if conversation.contact.email.blank?
true
end
def notify_via_mail
return unless can_notify_via_mail?
trigger_notify_via_mail
end
def trigger_notify_via_mail
return EmailReplyWorker.perform_in(1.second, id) if inbox.inbox_type == 'Email'
# will set a redis key for the conversation so that we don't need to send email for every new message
# last few messages coupled together is sent every 2 minutes rather than one email for each message
# if redis key exists there is an unprocessed job that will take care of delivering the email
return if Redis::Alfred.get(conversation_mail_key).present?
Redis::Alfred.setex(conversation_mail_key, id)
ConversationReplyEmailWorker.perform_in(2.minutes, conversation.id, id)
end
def conversation_mail_key
format(::Redis::Alfred::CONVERSATION_MAILER_KEY, conversation_id: conversation.id)
end
def validate_attachments_limit(_attachment)
errors.add(:attachments, message: 'exceeded maximum allowed') if attachments.size >= NUMBER_OF_PERMITTED_ATTACHMENTS
end
def set_conversation_activity
# rubocop:disable Rails/SkipsModelValidations
conversation.update_columns(last_activity_at: created_at)
# rubocop:enable Rails/SkipsModelValidations
end
2022-12-05 16:08:12 +00:00
def allowed_message_types?
incoming? || outgoing?
end
end