Class: Twterm::Client

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

Constant Summary collapse

CREATE_STATUS_PROC =
-> (s) { Status.new(s) }
CONSUMER_KEY =
'vLNSVFgXclBJQJRZ7VLMxL9lA'.freeze
CONSUMER_SECRET =
'OFLKzrepRG2p1hq0nUB9j2S9ndFQoNTPheTpmOY0GYw55jGgS5'.freeze
@@instances =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user_id, screen_name, access_token, access_token_secret) ⇒ Client

Returns a new instance of Client.



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/twterm/client.rb', line 116

def initialize(user_id, screen_name, access_token, access_token_secret)
  @user_id, @screen_name = user_id, screen_name
  @access_token, @access_token_secret = access_token, access_token_secret

  @callbacks = {}

  @mute_filter = -> _ { true }
  fetch_muted_users do |muted_user_ids|
    @mute_filter = lambda do |status|
      !muted_user_ids.include?(status.user.id) &&
        !(status.retweeted_status.is_a?(Twitter::NullObject) &&
        muted_user_ids.include?(status.retweeted_status.user.id))
    end
  end

  initialize_user_stream

  @@instances << self
end

Instance Attribute Details

#screen_nameObject (readonly)

Returns the value of attribute screen_name.



3
4
5
# File 'lib/twterm/client.rb', line 3

def screen_name
  @screen_name
end

#user_idObject (readonly)

Returns the value of attribute user_id.



3
4
5
# File 'lib/twterm/client.rb', line 3

def user_id
  @user_id
end

Class Method Details

.currentObject



445
446
447
# File 'lib/twterm/client.rb', line 445

def self.current
  @@instances[0]
end

.new(user_id, screen_name, token, secret) ⇒ Object



439
440
441
442
443
# File 'lib/twterm/client.rb', line 439

def self.new(user_id, screen_name, token, secret)
  detector = -> (instance) { instance.user_id == user_id }
  instance = @@instances.find(&detector)
  instance.nil? ? super : instance
end

Instance Method Details

#block(*user_ids) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/twterm/client.rb', line 11

def block(*user_ids)
  send_request do
    rest_client.block(*user_ids)
  end.then do |users|
    users.each do |user|
      Friendship.block(self.user_id, user.id)
    end
  end
end

#destroy_status(status) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/twterm/client.rb', line 21

def destroy_status(status)
  send_request_without_catch do
    rest_client.destroy_status(status.id)
  end.catch do |reason|
    case reason
    when Twitter::Error::NotFound, Twitter::Error::Forbidden
      Notifier.instance.show_error 'You cannot destroy that status'
    else
      raise reason
    end
  end.catch(&show_error)
end

#favorite(status) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/twterm/client.rb', line 34

def favorite(status)
  return false unless status.is_a? Status

  send_request do
    rest_client.favorite(status.id)
  end.then do
    status.favorite!
  end
end

#favorites(user_id = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/twterm/client.rb', line 44

def favorites(user_id = nil)
  user_id ||= self.user_id

  send_request do
    rest_client.favorites(user_id, count: 200)
  end.then do |tweets|
    tweets.map(&CREATE_STATUS_PROC)
  end
end

#fetch_muted_usersObject



54
55
56
57
58
# File 'lib/twterm/client.rb', line 54

def fetch_muted_users
  send_request do
    @muted_user_ids = rest_client.muted_ids.to_a
  end
end

#follow(*user_ids) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/twterm/client.rb', line 60

def follow(*user_ids)
  send_request do
    rest_client.follow(*user_ids)
  end.then do |users|
    users.each do |user|
      if user.protected?
        Friendship.following_requested(self.user_id, user.id)
      else
        Friendship.follow(self.user_id, user.id)
      end
    end
  end
end

#followers(user_id = nil) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/twterm/client.rb', line 74

def followers(user_id = nil)
  user_id ||= self.user_id

  m = Mutex.new

  send_request do
    rest_client.follower_ids(user_id).each_slice(100) do |user_ids|
      m.synchronize do
        users = rest_client.users(*user_ids).map(& -> u { User.new(u) })
        users.each do |user|
          Friendship.follow(user.id, self.user_id)
        end if user_id == self.user_id
        yield users
      end
    end
  end
end

#friends(user_id = nil) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/twterm/client.rb', line 92

def friends(user_id = nil)
  user_id ||= self.user_id

  m = Mutex.new

  send_request do
    rest_client.friend_ids(user_id).each_slice(100) do |user_ids|
      m.synchronize do
        yield rest_client.users(*user_ids).map(& -> u { User.new(u) })
      end
    end
  end
end

#home_timelineObject



106
107
108
109
110
111
112
113
114
# File 'lib/twterm/client.rb', line 106

def home_timeline
  send_request do
    rest_client.home_timeline(count: 200)
  end.then do |statuses|
    statuses
      .select(&@mute_filter)
      .map(&CREATE_STATUS_PROC)
  end
end

#initialize_user_streamObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/twterm/client.rb', line 136

def initialize_user_stream
  return if user_stream_initialized?

  streaming_client.on_friends do
    user_stream_connected!
  end

  streaming_client.on_timeline_status do |tweet|
    status = Status.new(tweet)
    invoke_callbacks(:timeline_status, status)
    invoke_callbacks(:mention, status) if status.text.include? "@#{@screen_name}"
  end

  streaming_client.on_delete do |status_id|
    timeline.delete_status(status_id)
  end

  streaming_client.on_event(:favorite) do |event|
    break if event[:source][:screen_name] == @screen_name

    user = event[:source][:screen_name]
    text = event[:target_object][:text]
    message = "@#{user} has favorited your tweet: #{text}"
    Notifier.instance.show_message(message)
  end

  streaming_client.on_no_data_received do
    user_stream_disconnected!
    user_stream
  end

  user_stream_initialized!
end

#list(list_id) ⇒ Object



170
171
172
173
174
175
176
# File 'lib/twterm/client.rb', line 170

def list(list_id)
  send_request do
    rest_client.list(list_id)
  end.then do |list|
    List.new(list)
  end
end

#list_timeline(list) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
# File 'lib/twterm/client.rb', line 178

def list_timeline(list)
  fail ArgumentError,
    'argument must be an instance of List class' unless list.is_a? List
  send_request do
    rest_client.list_timeline(list.id, count: 200)
  end.then do |statuses|
    statuses
      .select(&@mute_filter)
      .map(&CREATE_STATUS_PROC)
  end
end

#listsObject



190
191
192
193
194
195
196
# File 'lib/twterm/client.rb', line 190

def lists
  send_request do
    rest_client.lists
  end.then do |lists|
    lists.map { |list| List.new(list) }
  end
end

#lookup_friendshipsObject



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/twterm/client.rb', line 198

def lookup_friendships
  user_ids = User.ids.reject { |id| Friendship.already_looked_up?(id) }
  send_request_without_catch do
    user_ids.each_slice(100) do |chunked_user_ids|
      friendships = rest_client.friendships(*chunked_user_ids)
      friendships.each do |friendship|
        id = friendship.id
        client_id = user_id

        conn = friendship.connections
        conn.include?('blocking') ? Friendship.block(client_id, id) : Friendship.unblock(client_id, id)
        conn.include?('following') ? Friendship.follow(client_id, id) : Friendship.unfollow(client_id, id)
        conn.include?('following_requested') ? Friendship.following_requested(client_id, id) : Friendship.following_not_requested(client_id, id)
        conn.include?('followed_by') ? Friendship.follow(id, client_id) : Friendship.unfollow(id, client_id)
        conn.include?('muting') ? Friendship.mute(client_id, id) : Friendship.unmute(client_id, id)
      end
    end
  end.catch do |e|
    case e
    when Twitter::Error::TooManyRequests
      # do nothing
    else
      raise e
    end
  end.catch(&show_error)
end

#mentionsObject



225
226
227
228
229
230
231
232
233
# File 'lib/twterm/client.rb', line 225

def mentions
  send_request do
    rest_client.mentions(count: 200)
  end.then do |statuses|
    statuses
      .select(&@mute_filter)
      .map(&CREATE_STATUS_PROC)
  end
end

#mute(user_ids) ⇒ Object



235
236
237
238
239
240
241
242
243
# File 'lib/twterm/client.rb', line 235

def mute(user_ids)
  send_request do
    rest_client.mute(*user_ids)
  end.then do |users|
    users.each do |user|
      Friendship.mute(self.user_id, user.id)
    end
  end
end

#on_mention(&block) ⇒ Object



245
246
247
248
# File 'lib/twterm/client.rb', line 245

def on_mention(&block)
  fail ArgumentError, 'no block given' unless block_given?
  on(:mention, &block)
end

#on_timeline_status(&block) ⇒ Object



250
251
252
253
# File 'lib/twterm/client.rb', line 250

def on_timeline_status(&block)
  fail ArgumentError, 'no block given' unless block_given?
  on(:timeline_status, &block)
end

#post(text, in_reply_to = nil) ⇒ Object



255
256
257
258
259
260
261
262
263
264
# File 'lib/twterm/client.rb', line 255

def post(text, in_reply_to = nil)
  send_request do
    if in_reply_to.is_a? Status
      text = "@#{in_reply_to.user.screen_name} #{text}"
      rest_client.update(text, in_reply_to_status_id: in_reply_to.id)
    else
      rest_client.update(text)
    end
  end
end

#rest_clientObject



266
267
268
269
270
271
272
273
# File 'lib/twterm/client.rb', line 266

def rest_client
  @rest_client ||= Twitter::REST::Client.new do |config|
    config.consumer_key        = CONSUMER_KEY
    config.consumer_secret     = CONSUMER_SECRET
    config.access_token        = @access_token
    config.access_token_secret = @access_token_secret
  end
end

#retweet(status) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/twterm/client.rb', line 275

def retweet(status)
  fail ArgumentError,
    'argument must be an instance of Status class' unless status.is_a? Status

  send_request_without_catch do
    rest_client.retweet!(status.id)
  end.then do
    status.retweet!
  end.catch do |reason|
    message =
      case reason
      when Twitter::Error::AlreadyRetweeted
        'The status is already retweeted'
      when Twitter::Error::NotFound
        'The status is not found'
      when Twitter::Error::Forbidden
        if status.user.id == user_id  # when the status is mine
          'You cannot retweet your own status'
        else  # when the status is not mine
          'The status is protected'
        end
      else
        raise e
      end
    Notifier.instance.show_error "Retweet attempt failed: #{message}"
  end.catch(&show_error)
end

#saved_searchObject



303
304
305
306
307
# File 'lib/twterm/client.rb', line 303

def saved_search
  send_request do
    rest_client.saved_searches
  end
end

#search(query) ⇒ Object



309
310
311
312
313
314
315
316
317
# File 'lib/twterm/client.rb', line 309

def search(query)
  send_request do
    rest_client.search(query, count: 200)
  end.then do |statuses|
    statuses
      .select(&@mute_filter)
      .map(&CREATE_STATUS_PROC)
  end
end

#show_status(status_id) ⇒ Object



319
320
321
322
323
324
325
# File 'lib/twterm/client.rb', line 319

def show_status(status_id)
  send_request do
    rest_client.status(status_id)
  end.then do |status|
    Status.new(status)
  end
end

#show_user(query) ⇒ Object



327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/twterm/client.rb', line 327

def show_user(query)
  send_request_without_catch do
    rest_client.user(query)
  end.catch do |reason|
    case reason
    when Twitter::Error::NotFound
      nil
    else
      raise reason
    end
  end.catch(&show_error).then do |user|
    user.nil? ? nil : User.new(user)
  end
end

#streaming_clientObject



342
343
344
345
346
347
348
349
350
# File 'lib/twterm/client.rb', line 342

def streaming_client
  @streaming_client ||= TweetStream::Client.new(
    consumer_key:       CONSUMER_KEY,
    consumer_secret:    CONSUMER_SECRET,
    oauth_token:        @access_token,
    oauth_token_secret: @access_token_secret,
    auth_method:        :oauth
  )
end

#unblock(*user_ids) ⇒ Object



352
353
354
355
356
357
358
359
360
# File 'lib/twterm/client.rb', line 352

def unblock(*user_ids)
  send_request do
    rest_client.unblock(*user_ids)
  end.then do |users|
    users.each do |user|
      Friendship.unblock(self.user_id, user.id)
    end
  end
end

#unfavorite(status) ⇒ Object



362
363
364
365
366
367
368
369
370
371
# File 'lib/twterm/client.rb', line 362

def unfavorite(status)
  fail ArgumentError,
    'argument must be an instance of Status class' unless status.is_a? Status

  send_request do
    rest_client.unfavorite(status.id)
  end.then do
    status.unfavorite!
  end
end

#unfollow(*user_ids) ⇒ Object



373
374
375
376
377
378
379
380
381
# File 'lib/twterm/client.rb', line 373

def unfollow(*user_ids)
  send_request do
    rest_client.unfollow(*user_ids)
  end.then do |users|
    users.each do |user|
      Friendship.unfollow(self.user_id, user.id)
    end
  end
end

#unmute(user_ids) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/twterm/client.rb', line 383

def unmute(user_ids)
  send_request do
    rest_client.unmute(*user_ids)
  end.then do |users|
    users.each do |user|
      Friendship.unmute(self.user_id, user.id)
    end
  end
end

#user_streamObject



393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/twterm/client.rb', line 393

def user_stream
  streaming_client.stop_stream

  @streaming_thread = Thread.new do
    begin
      Notifier.instance.show_message 'Trying to connect to Twitter...'
      streaming_client.userstream
    rescue EventMachine::ConnectionError
      Notifier.instance.show_error 'Connection failed'
      sleep 30
      retry
    end
  end
end

#user_stream_connected!Object



412
413
414
415
# File 'lib/twterm/client.rb', line 412

def user_stream_connected!
  Notifier.instance.show_message 'Connection established' unless user_stream_connected?
  @user_stream_connected = true
end

#user_stream_connected?Boolean

Returns:

  • (Boolean)


408
409
410
# File 'lib/twterm/client.rb', line 408

def user_stream_connected?
  @user_stream_connected || false
end

#user_stream_disconnected!Object



417
418
419
# File 'lib/twterm/client.rb', line 417

def user_stream_disconnected!
  @user_stream_connected = false
end

#user_stream_initialized!Object



425
426
427
# File 'lib/twterm/client.rb', line 425

def user_stream_initialized!
  @user_stream_initialized = true
end

#user_stream_initialized?Boolean

Returns:

  • (Boolean)


421
422
423
# File 'lib/twterm/client.rb', line 421

def user_stream_initialized?
  @user_stream_initialized || false
end

#user_timeline(user_id) ⇒ Object



429
430
431
432
433
434
435
436
437
# File 'lib/twterm/client.rb', line 429

def user_timeline(user_id)
  send_request do
    rest_client.user_timeline(user_id, count: 200)
  end.then do |statuses|
    statuses
      .select(&@mute_filter)
      .map(&CREATE_STATUS_PROC)
  end
end