view app/models/tweet.rb @ 139:ee5876dd9b45

Link alt to main twitter
author nanaya <me@nanaya.pro>
date Wed, 13 Dec 2017 04:21:48 +0900
parents 7907fe886675
children 88d7a7714d4e
line wrap: on
line source

class Tweet
  TIMELINE_OPTIONS = {
    :count => 100,
    :exclude_replies => false,
    :include_rts => true,
    :tweet_mode => :extended,
  }

  def initialize(twitter_id)
    @clients = {}
    @twitter_id = twitter_id
  end

  def cache_expires_time
    (15 + rand(15)).minutes
  end

  def timeline
    initial_config_id = client_config_id

    @timeline ||=
      Rails.cache.fetch({ :timeline => @twitter_id }, :expires_in => cache_expires_time) do
        begin
          client.user_timeline(@twitter_id, TIMELINE_OPTIONS).select do |tweet|
            tweet.retweeted_status.nil? || tweet.user.id != tweet.retweeted_status.user.id
          end.map do |tweet|
            # Fails when there's Twitter::NullObject initiated somewhere in previous select
            # Reference: https://github.com/sferik/twitter/issues/892
            tweet.to_h
          end
        rescue Twitter::Error::TooManyRequests
          @client_config_id += 1

          if initial_config_id == client_config_id
            raise
          else
            retry
          end
        end
      end.map do |tweet_hash|
        Twitter::Tweet.new(tweet_hash)
      end
  end

  def user
    @user ||=
      if timeline.any?
        timeline.first.user
      else
        Rails.cache.fetch({ :user => @twitter_id }, :expires_in => cache_expires_time) do
          @client.user(@twitter_id)
        end
      end
  end

  def client
    @clients[client_config_id] ||=
      Twitter::REST::Client.new do |config|
        $cfg[:twitter][client_config_id].each do |cfg_key, cfg_value|
          config.public_send(:"#{cfg_key}=", cfg_value)
        end
      end
  end

  def client_config_id
    @client_config_id ||= 0

    @client_config_id %= $cfg[:twitter].size
  end
end