2020-01-09 07:36:40 +00:00
|
|
|
class Messages::MessageBuilder
|
2020-07-21 06:45:24 +00:00
|
|
|
include ::FileTypeHelper
|
|
|
|
attr_reader :message
|
2020-01-09 07:36:40 +00:00
|
|
|
|
2020-07-21 06:45:24 +00:00
|
|
|
def initialize(user, conversation, params)
|
|
|
|
@content = params[:content]
|
|
|
|
@private = params[:private] || false
|
|
|
|
@conversation = conversation
|
|
|
|
@user = user
|
|
|
|
@message_type = params[:message_type] || 'outgoing'
|
|
|
|
@content_type = params[:content_type]
|
|
|
|
@items = params.to_unsafe_h&.dig(:content_attributes, :items)
|
|
|
|
@attachments = params[:attachments]
|
2020-08-11 04:27:42 +00:00
|
|
|
@in_reply_to = params.to_unsafe_h&.dig(:content_attributes, :in_reply_to)
|
2020-01-09 07:36:40 +00:00
|
|
|
end
|
2019-08-14 09:48:44 +00:00
|
|
|
|
2020-01-09 07:36:40 +00:00
|
|
|
def perform
|
2020-07-21 06:45:24 +00:00
|
|
|
@message = @conversation.messages.build(message_params)
|
|
|
|
if @attachments.present?
|
|
|
|
@attachments.each do |uploaded_attachment|
|
|
|
|
attachment = @message.attachments.new(
|
|
|
|
account_id: @message.account_id,
|
|
|
|
file_type: file_type(uploaded_attachment&.content_type)
|
|
|
|
)
|
|
|
|
attachment.file.attach(uploaded_attachment)
|
|
|
|
end
|
2019-10-20 19:10:18 +00:00
|
|
|
end
|
2020-07-21 06:45:24 +00:00
|
|
|
@message.save
|
|
|
|
@message
|
2020-01-09 07:36:40 +00:00
|
|
|
end
|
2019-08-14 09:48:44 +00:00
|
|
|
|
2020-01-09 07:36:40 +00:00
|
|
|
private
|
2019-08-31 06:22:09 +00:00
|
|
|
|
2020-07-21 06:45:24 +00:00
|
|
|
def message_type
|
2020-08-10 06:45:29 +00:00
|
|
|
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'
|
2019-10-20 19:10:18 +00:00
|
|
|
end
|
2019-10-05 09:15:32 +00:00
|
|
|
|
2020-07-21 06:45:24 +00:00
|
|
|
@message_type
|
2020-01-09 07:36:40 +00:00
|
|
|
end
|
2019-10-05 09:15:32 +00:00
|
|
|
|
2020-07-21 06:45:24 +00:00
|
|
|
def sender
|
|
|
|
message_type == 'outgoing' ? @user : @conversation.contact
|
2020-01-09 07:36:40 +00:00
|
|
|
end
|
2019-10-20 19:10:18 +00:00
|
|
|
|
2020-01-09 07:36:40 +00:00
|
|
|
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: @content,
|
|
|
|
private: @private,
|
|
|
|
sender: sender,
|
|
|
|
content_type: @content_type,
|
2020-08-11 04:27:42 +00:00
|
|
|
items: @items,
|
|
|
|
in_reply_to: @in_reply_to
|
2020-01-09 07:36:40 +00:00
|
|
|
}
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|