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.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/twterm/client.rb', line 120

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



463
464
465
# File 'lib/twterm/client.rb', line 463

def self.current
  @@instances[0]
end

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



457
458
459
460
461
# File 'lib/twterm/client.rb', line 457

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
33
# File 'lib/twterm/client.rb', line 21

def destroy_status(status)
  send_request_without_catch do
    rest_client.destroy_status(status.id)
    Notifier.instance.show_message('Your tweet has been deleted')
  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



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/twterm/client.rb', line 35

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

  send_request do
    rest_client.favorite(status.id)
  end.then do
    status.favorite!
    Notifier.instance.show_message('Successfully liked: @%s "%s"' % [
      status.user.screen_name, status.text
    ])
  end
end

#favorites(user_id = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/twterm/client.rb', line 48

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



58
59
60
61
62
# File 'lib/twterm/client.rb', line 58

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

#follow(*user_ids) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/twterm/client.rb', line 64

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



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/twterm/client.rb', line 78

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



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/twterm/client.rb', line 96

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



110
111
112
113
114
115
116
117
118
# File 'lib/twterm/client.rb', line 110

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



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
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/twterm/client.rb', line 140

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_event(:follow) do |event|
    screen_name = event[:source][:screen_name]
    break if screen_name == @screen_name

    Notifier.instance.show_message('@%s has followed you' % screen_name)
  end

  streaming_client.on_no_data_received do
    user_stream_disconnected!
    user_stream
  end

  user_stream_initialized!
end

#list(list_id) ⇒ Object



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

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



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

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



201
202
203
204
205
206
207
# File 'lib/twterm/client.rb', line 201

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

#lookup_friendshipsObject



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/twterm/client.rb', line 209

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



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

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



246
247
248
249
250
251
252
253
254
# File 'lib/twterm/client.rb', line 246

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



256
257
258
259
# File 'lib/twterm/client.rb', line 256

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

#on_timeline_status(&block) ⇒ Object



261
262
263
264
# File 'lib/twterm/client.rb', line 261

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



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

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
    Notifier.instance.show_message('Your tweet has been posted')
  end
end

#rest_clientObject



278
279
280
281
282
283
284
285
# File 'lib/twterm/client.rb', line 278

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



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/twterm/client.rb', line 287

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!
    Notifier.instance.show_message('Successfully retweeted: @%s "%s"' % [
      status.user.screen_name, status.text
    ])
  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



318
319
320
321
322
# File 'lib/twterm/client.rb', line 318

def saved_search
  send_request do
    rest_client.saved_searches
  end
end

#search(query) ⇒ Object



324
325
326
327
328
329
330
331
332
# File 'lib/twterm/client.rb', line 324

def search(query)
  send_request do
    rest_client.search(query, count: 100).attrs[:statuses]
  end.then do |statuses|
    statuses
      .map(&Twitter::Tweet.method(:new))
      .map(&CREATE_STATUS_PROC)
  end
end

#show_status(status_id) ⇒ Object



334
335
336
337
338
339
340
# File 'lib/twterm/client.rb', line 334

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



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

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



357
358
359
360
361
362
363
364
365
# File 'lib/twterm/client.rb', line 357

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



367
368
369
370
371
372
373
374
375
# File 'lib/twterm/client.rb', line 367

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



377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/twterm/client.rb', line 377

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!
    Notifier.instance.show_message('Successfully unliked: @%s "%s"' % [
      status.user.screen_name, status.text
    ])
  end
end

#unfollow(*user_ids) ⇒ Object



391
392
393
394
395
396
397
398
399
# File 'lib/twterm/client.rb', line 391

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



401
402
403
404
405
406
407
408
409
# File 'lib/twterm/client.rb', line 401

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



411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/twterm/client.rb', line 411

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



430
431
432
433
# File 'lib/twterm/client.rb', line 430

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)


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

def user_stream_connected?
  @user_stream_connected || false
end

#user_stream_disconnected!Object



435
436
437
# File 'lib/twterm/client.rb', line 435

def user_stream_disconnected!
  @user_stream_connected = false
end

#user_stream_initialized!Object



443
444
445
# File 'lib/twterm/client.rb', line 443

def user_stream_initialized!
  @user_stream_initialized = true
end

#user_stream_initialized?Boolean

Returns:

  • (Boolean)


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

def user_stream_initialized?
  @user_stream_initialized || false
end

#user_timeline(user_id) ⇒ Object



447
448
449
450
451
452
453
454
455
# File 'lib/twterm/client.rb', line 447

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