Module: X::MediaUploader

Extended by:
MediaUploader
Included in:
MediaUploader
Defined in:
lib/x/media_uploader.rb

Constant Summary collapse

MAX_RETRIES =
3
BYTES_PER_MB =
1_048_576
MEDIA_CATEGORIES =
%w[dm_gif dm_image dm_video subtitles tweet_gif tweet_image tweet_video].freeze
DEFAULT_MIME_TYPE =
"application/octet-stream".freeze
MIME_TYPES =
%w[image/gif image/jpeg video/mp4 image/png application/x-subrip image/webp].freeze
MIME_TYPE_MAP =
{"gif" => GIF_MIME_TYPE, "jpg" => JPEG_MIME_TYPE, "jpeg" => JPEG_MIME_TYPE, "mp4" => MP4_MIME_TYPE,
"png" => PNG_MIME_TYPE, "srt" => SUBRIP_MIME_TYPE, "webp" => WEBP_MIME_TYPE}.freeze
PROCESSING_INFO_STATES =
%w[failed succeeded].freeze

Instance Method Summary collapse

Instance Method Details

#await_processing(client:, media:) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/x/media_uploader.rb', line 36

def await_processing(client:, media:)
  loop do
    status = client.get("media/upload?command=STATUS&media_id=#{media["id"]}")&.fetch("data")
    return status if !status["processing_info"] || PROCESSING_INFO_STATES.include?(status["processing_info"]["state"])

    sleep status["processing_info"]["check_after_secs"].to_i
  end
end

#chunked_upload(client:, file_path:, media_category:, media_type: infer_media_type(file_path, media_category), boundary: SecureRandom.hex, chunk_size_mb: 1) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/x/media_uploader.rb', line 27

def chunked_upload(client:, file_path:, media_category:, media_type: infer_media_type(file_path,
  media_category), boundary: SecureRandom.hex, chunk_size_mb: 1)
  validate!(file_path:, media_category:)
  media = init(client:, file_path:, media_type:, media_category:)
  chunk_size = chunk_size_mb * BYTES_PER_MB
  append(client:, file_paths: split(file_path, chunk_size), media:, media_type:, boundary:)
  client.post("media/upload?command=FINALIZE&media_key=#{media["media_key"]}")&.fetch("data")
end

#upload(client:, file_path:, media_category:, media_type: infer_media_type(file_path, media_category), boundary: SecureRandom.hex) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/x/media_uploader.rb', line 19

def upload(client:, file_path:, media_category:, media_type: infer_media_type(file_path, media_category),
  boundary: SecureRandom.hex)
  validate!(file_path:, media_category:)
  upload_body = construct_upload_body(file_path:, media_type:, boundary:)
  headers = {"Content-Type" => "multipart/form-data, boundary=#{boundary}"}
  client.post("media/upload?media_category=#{media_category}", upload_body, headers:)
end