aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/tweet.rb
blob: 7e927ec7796281d0899c76fea0f1e57c60a95001 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class Tweet < ActiveRecord::Base
  belongs_to :user

  belongs_to :in_reply_to, class_name: "Tweet"
  has_many :replies, class_name: "Tweet", foreign_key: "in_reply_to_id"

  has_many :favorites, -> { order("favorites.id") }, dependent: :delete_all
  has_many :retweets, -> { order("retweets.id") }, dependent: :delete_all

  has_many :favoriters, ->  { order("favorites.id") }, through: :favorites, source: :user
  has_many :retweeters, -> { order("retweets.id") }, through: :retweets, source: :user

  scope :recent, ->(period = 3.days) { where("tweets.id > ?", snowflake_min(Time.zone.now - period)) }
  scope :reacted, ->(count = nil) { where("reactions_count >= ?", (count || 1).to_i) }
  scope :not_protected, -> { joins(:user).references(:user).where(users: { protected: false }) }
  scope :registered, -> { joins(user: :account).references(:account).where(accounts: { status: Account::ACTIVE }) }

  scope :max_id, -> id { where("tweets.id <= ?", id.to_i) if id }
  scope :since_id, -> id { where("tweets.id > ?", id.to_i) if id }
  scope :page, ->(page) { offset((page - 1) * all.limit_value) }

  scope :order_by_id, -> { order(id: :desc) }
  scope :order_by_reactions, -> { order(reactions_count: :desc) }

  scope :favorited_by, ->(user) { joins(:favorites).where(favorites: { user: user }) }
  scope :retweeted_by, ->(user) { joins(:retweets).where(retweets: { user: user }) }
  scope :discovered_by, ->(user) {
    load_count = all.limit_value.to_i + all.offset_value.to_i
    load_count = nil if load_count == 0

    un = [:favorites, :retweets].map {|m|
      user.__send__(m).select(:tweet_id).order(tweet_id: :desc).limit(load_count)
    }.map {|m| "(#{m.to_sql})" }.join(" UNION ")

    joins("INNER JOIN ((#{un})) reactions ON reactions.tweet_id = tweets.id")
  }

  def twitter_url
    "https://twitter.com/#{self.user.screen_name}/status/#{self.id}"
  end

  def reply_ancestors(max_level = Float::INFINITY)
    nodes = []
    node = self
    level = 0

    while node.in_reply_to && level < max_level
      nodes.unshift(node = node.in_reply_to)
      level += 1
    end
    nodes
  end

  def reply_descendants(max_level = Float::INFINITY)
    nodes = []
    c_nodes = [self]
    level = 0

    while c_nodes.size > 0 && level < max_level
      nodes.concat(c_nodes.map! {|node| node.replies }.flatten!)
      level += 1
    end
    nodes.sort_by {|t| t.id }
  end

  def update_reactions_count(favorites_count: 0, retweets_count: 0, json: {})
    fav_op = favorites_count >= 0 ? "+" : "-"
    rts_op = retweets_count >= 0 ? "+" : "-"
    Tweet.where(id: self.id)
      .update_all("favorites_count = GREATEST(favorites_count #{fav_op} #{favorites_count.abs}, #{(json[:favorite_count] || 0).to_i}), " +
                  "retweets_count = GREATEST(retweets_count #{rts_op} #{retweets_count.abs}, #{(json[:retweet_count] || 0).to_i}), " +
                  "reactions_count = favorites_count + retweets_count")
  end

  def self.create_from_json(json)
    tweet = transaction do
      self.find_by(id: json[:id]) ||
        self.create!(id: json[:id],
                     text: extract_entities(json),
                     source: json[:source],
                     tweeted_at: json[:created_at],
                     in_reply_to_id: json[:in_reply_to_status_id],
                     user: User.create_from_json(json[:user]))
    end
  rescue ActiveRecord::RecordNotUnique => e
    logger.debug("Duplicate tweet: #{tweet}: #{e.class}")
  rescue => e
    logger.error("Failed to create a tweet: #{tweet}: #{e.class}: #{e.message}/#{e.backtrace.join("\n")}")
  ensure
    return tweet
  end

  def self.create_from_twitter_object(obj)
    t = self.create_from_json(obj.attrs)
    t.update_reactions_count(json: obj.attrs)
    t
  end

  def self.destroy_from_json(json)
    deleted_count = self.delete(json[:delete][:status][:id])

    if deleted_count > 0
      Favorite.where(tweet_id: json[:delete][:status][:id]).delete_all
      Retweet.where(tweet_id: json[:delete][:status][:id]).delete_all
      true
    else
      false
    end
  end

  def self.import(id, client = nil)
    client ||= Account.random.client

    st = client.status(id)
    tweet = self.create_from_twitter_object(st)
    tweet.update(text: extract_entities(st.attrs),
                 source: st.attrs[:source],
                 in_reply_to_id: st.attrs[:in_reply_to_status_id])

    begin
      nt = tweet
      nt = self.create_from_twitter_object(client.status(nt.in_reply_to_id)) while !nt.in_reply_to && nt.in_reply_to_id
    rescue Twitter::Error
      logger.warn($!)
    end

    tweet.reload
  end

  def self.eager_load_for_html
    self.eager_load(:user)
  end

  def self.filter_by_query(query)
    strings = []
    query.gsub!(/"((?:\\"|[^"])*?)"/) {|m| strings << $1; "##{strings.size - 1}" }

    escape_text = -> str do
      str.gsub(/#(\d+)/) { strings[$1.to_i] }
         .gsub("%", "\\%")
         .gsub("*", "%")
         .gsub("_", "\\_")
         .gsub("?", "_")
    end

    parse_condition = ->(scoped, token) do
      positive = !token.slice!(/^[-!]/)

      where_args = case token
      when /^(?:user|from):([A-Za-z0-9_]{1,20})$/
        u = User.find_by(screen_name: $1)
        uid = u && u.id || -1
        { user_id: uid }
      when /^fav(?:orite)?s?:(\d+)$/
        ["favorites_count >= ?", $1.to_i]
      when /^(?:retweet|rt)s?:(\d+)$/
        ["retweets_count >= ?", $1.to_i]
      when /^(?:sum|(?:re)?act(?:ion)?s?):(\d+)$/
        ["reactions_count >= ?", $1.to_i]
      when /^(?:source|via):(.+)$/
        ["source LIKE ?", escape_text.call($1)]
      when /^text:(.+)$/
        ["text LIKE ?", "%" + escape_text.call($1) + "%"]
      else
        nil
      end

      positive ? scoped.where(where_args) : scoped.where.not(where_args)
    end

    query.scan(/\S+/).inject(self.all) {|s, token| parse_condition.call(s, token) }
  end

  private
  # replace t.co with expanded_url
  def self.extract_entities(json)
    entity_values = json[:entities].values.flatten.sort_by {|v| v[:indices].first }
    entity_values.select! {|e| e[:url] }

    result = ""
    last_index = entity_values.inject(0) do |last_index, entity|
      result << json[:text][last_index...entity[:indices].first]
      result << entity[:expanded_url]
      entity[:indices].last
    end
    result << json[:text][last_index..-1]

    result
  end

  def self.snowflake_min(time)
    (time.to_datetime.to_i * 1000 - 1288834974657) << 22
  end
end