Class: Lolcommits::Twitter::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/lolcommits/twitter/client.rb

Constant Summary collapse

API_ENDPOINT =
'https://api.twitter.com'.freeze
UPLOAD_ENDPOINT =
'https://upload.twitter.com'.freeze
CONSUMER_KEY =
'CwMCjbxREk5dSloZeR5Uhb1Fe'.freeze
CONSUMER_SECRET =
'UfgIvD32rRgSwIWZq9hjADMYd0e3ax9FluSEePSNOqgmSCerU5'.freeze
CHUNK_SIZE_BYTES =
5_000_000
MAX_TWEET_CHARS =

(140 - space - reserved media chars)

(140 - 1 - 24).freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token, token_secret) ⇒ Client

Returns a new instance of Client.



30
31
32
33
34
35
36
37
# File 'lib/lolcommits/twitter/client.rb', line 30

def initialize(token, token_secret)
  @oauth_credentials = {
    consumer_key: CONSUMER_KEY,
    consumer_secret: CONSUMER_SECRET,
    token: token,
    token_secret: token_secret
  }
end

Class Method Details

.oauth_consumerObject



20
21
22
23
24
25
26
27
28
# File 'lib/lolcommits/twitter/client.rb', line 20

def self.oauth_consumer
  OAuth::Consumer.new(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    site: API_ENDPOINT,
    request_endpoint: API_ENDPOINT,
    sign_in: true
  )
end

Instance Method Details

#update_status(status, media_ids: []) ⇒ Object



40
41
42
43
# File 'lib/lolcommits/twitter/client.rb', line 40

def update_status(status, media_ids: [])
  url = API_ENDPOINT + "/1.1/statuses/update.json"
  post(url, params: { status: status, media_ids: media_ids })
end

#upload_media(media) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/lolcommits/twitter/client.rb', line 46

def upload_media(media)
  response = begin
    # upload animated gifs in 5MB chunks
    if File.basename(media) =~ /\.gif$/
      upload_media_chunked(media)
    else
      post(upload_url, payload: { media: media })
    end
  end
  response['media_id_string']
end

#upload_media_chunked(media) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/lolcommits/twitter/client.rb', line 59

def upload_media_chunked(media)
  media_id = upload('INIT', {
    media_type: 'image/gif',
    media_category: 'tweet_gif',
    total_bytes: media.size
  })['media_id_string']

  until media.eof?
    seg ||= -1
    base64_chunk = Base64.encode64(media.read(CHUNK_SIZE_BYTES))
    base64_chunk.delete("\n")
    upload('APPEND', {
      media_id: media_id,
      segment_index: seg += 1,
      media_data: base64_chunk
    })
  end
  media.close

  finalize = upload('FINALIZE', media_id: media_id)

  # check STATUS if this is an async media upload
  # @see https://dev.twitter.com/rest/reference/get/media/upload-status
  processing = finalize['processing_info']
  if processing
    until processing['state'] == 'succeeded'
      sleep processing['check_after_secs'] || 0.5
      processing = upload_status(media_id)['processing_info']
    end
  end

  finalize
end