Chatwoot/app/builders/messages/message_builder.rb

86 lines
2.3 KiB
Ruby
Raw Normal View History

class Messages::MessageBuilder
2020-07-21 06:45:24 +00:00
include ::FileTypeHelper
attr_reader :message
2020-07-21 06:45:24 +00:00
def initialize(user, conversation, params)
@params = params
2020-07-21 06:45:24 +00:00
@private = params[:private] || false
@conversation = conversation
@user = user
@message_type = params[:message_type] || 'outgoing'
@attachments = params[:attachments]
2022-01-10 07:11:59 +00:00
return unless params.instance_of?(ActionController::Parameters)
@in_reply_to = params.to_unsafe_h&.dig(:content_attributes, :in_reply_to)
2022-01-10 07:11:59 +00:00
@items = params.to_unsafe_h&.dig(:content_attributes, :items)
end
def perform
2020-07-21 06:45:24 +00:00
@message = @conversation.messages.build(message_params)
process_attachments
process_emails
@message.save!
2020-07-21 06:45:24 +00:00
@message
end
private
def process_attachments
return if @attachments.blank?
@attachments.each do |uploaded_attachment|
@message.attachments.build(
account_id: @message.account_id,
file: uploaded_attachment
)
end
end
def process_emails
return unless @conversation.inbox&.inbox_type == 'Email'
cc_emails = @params[:cc_emails].split(',') if @params[:cc_emails]
bcc_emails = @params[:bcc_emails].split(',') if @params[:bcc_emails]
@message.content_attributes[:cc_emails] = cc_emails
@message.content_attributes[:bcc_emails] = bcc_emails
end
2020-07-21 06:45:24 +00:00
def message_type
if @conversation.inbox.channel_type != 'Channel::Api' && @message_type == 'incoming'
2020-07-21 06:45:24 +00:00
raise StandardError, 'Incoming messages are only allowed in Api inboxes'
end
2020-07-21 06:45:24 +00:00
@message_type
end
2020-07-21 06:45:24 +00:00
def sender
message_type == 'outgoing' ? (message_sender || @user) : @conversation.contact
end
def external_created_at
@params[:external_created_at].present? ? { external_created_at: @params[:external_created_at] } : {}
end
def message_sender
return if @params[:sender_type] != 'AgentBot'
AgentBot.where(account_id: [nil, @conversation.account.id]).find_by(id: @params[:sender_id])
end
def message_params
{
2020-07-21 06:45:24 +00:00
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: message_type,
content: @params[:content],
2020-07-21 06:45:24 +00:00
private: @private,
sender: sender,
content_type: @params[:content_type],
items: @items,
in_reply_to: @in_reply_to,
echo_id: @params[:echo_id]
}.merge(external_created_at)
end
end