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

Instance Method Summary collapse

Instance Method Details

#await_processing(client:, media:) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/x/media_uploader.rb', line 39

def await_processing(client:, media:)
  upload_client = client.dup.tap { |c| c.base_url = "https://upload.twitter.com/1.1/" }
  loop do
    status = upload_client.get("media/upload.json?command=STATUS&media_id=#{media["media_id"]}")
    return status if !status["processing_info"] || %w[failed succeeded].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: 8) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# 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: 8)
  validate!(file_path: file_path, media_category: media_category)
  upload_client = client.dup.tap { |c| c.base_url = "https://upload.twitter.com/1.1/" }
  media = init(upload_client: upload_client, file_path: file_path, media_type: media_type,
    media_category: media_category)
  chunk_size = chunk_size_mb * BYTES_PER_MB
  append(upload_client: upload_client, file_paths: split(file_path, chunk_size), media: media,
    media_type: media_type, boundary: boundary)
  upload_client.post("media/upload.json?command=FINALIZE&media_id=#{media["media_id"]}")
end

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



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

def upload(client:, file_path:, media_category:, media_type: infer_media_type(file_path, media_category),
  boundary: SecureRandom.hex)
  validate!(file_path: file_path, media_category: media_category)
  upload_client = client.dup.tap { |c| c.base_url = "https://upload.twitter.com/1.1/" }
  upload_body = construct_upload_body(file_path: file_path, media_type: media_type, boundary: boundary)
  headers = {"Content-Type" => "multipart/form-data, boundary=#{boundary}"}
  upload_client.post("media/upload.json?media_category=#{media_category}", upload_body, headers: headers)
end