Class: InstagramConnect::UploadAttachmentJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
app/jobs/instagram_connect/upload_attachment_job.rb

Overview

Uploads a message's file to Meta and records the reusable attachment id, then hands the message to the sender.

Two steps rather than one because Meta's upload is a separate call with its own failure mode: a file it rejects (too large, wrong type) must fail the message with THAT reason, not with whatever the send would have said afterwards. The id is reusable, so the same file sent to a second thread costs no upload at all.

The host attaches the file however it likes (Active Storage, a Tempfile); this job only needs something that responds to #open or #path.

Constant Summary collapse

SIZE_LIMITS =

Meta's own ceilings, stated here so a file that cannot possibly work is refused before it costs an upload.

{ "image" => 8.megabytes, "video" => 25.megabytes,
"audio" => 25.megabytes, "file" => 25.megabytes }.freeze

Instance Method Summary collapse

Instance Method Details

#perform(message_id, file_path, type: "image") ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/jobs/instagram_connect/upload_attachment_job.rb', line 21

def perform(message_id, file_path, type: "image")
  message = Message.find_by(id: message_id)
  return if message.nil? || message.attachment_upload_id.present?

  unless File.exist?(file_path)
    return fail_message(message, "attachment_missing",
                        "The file to send could not be read.")
  end

  limit = SIZE_LIMITS.fetch(type, SIZE_LIMITS["file"])
  if File.size(file_path) > limit
    return fail_message(message, "attachment_too_large",
                        "Instagram refuses #{type}s over #{limit / 1.megabyte}MB.")
  end

  upload(message, file_path, type)
end