Class: TopicViewItem

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/topic_view_item.rb

Overview

awkward TopicView is taken

Class Method Summary collapse

Class Method Details

.add(topic_id, ip, user_id = nil, at = nil, skip_redis = false) ⇒ Object



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
# File 'app/models/topic_view_item.rb', line 12

def self.add(topic_id, ip, user_id = nil, at = nil, skip_redis = false)
  # Only store a view once per day per thing per (user || ip)
  at ||= Date.today
  redis_key = +"view:#{topic_id}:#{at}"
  if user_id
    redis_key << ":user-#{user_id}"
  else
    redis_key << ":ip-#{ip}"
  end

  if skip_redis || Discourse.redis.setnx(redis_key, "1")
    skip_redis || Discourse.redis.expire(redis_key, SiteSetting.topic_view_duration_hours.hours)

    TopicViewItem.transaction do
      # this is called real frequently, working hard to avoid exceptions
      sql =
        "INSERT INTO topic_views (topic_id, ip_address, viewed_at, user_id)
             SELECT :topic_id, :ip_address, :viewed_at, :user_id
             WHERE NOT EXISTS (
               SELECT 1 FROM topic_views
               /*where*/
             )"

      builder = DB.build(sql)

      if !user_id
        builder.where("ip_address = :ip_address AND topic_id = :topic_id AND user_id IS NULL")
      else
        builder.where("user_id = :user_id AND topic_id = :topic_id")
        ip = nil # do not store IP of logged in users
      end

      result = builder.exec(topic_id: topic_id, ip_address: ip, viewed_at: at, user_id: user_id)

      Topic.where(id: topic_id).update_all "views = views + 1"

      if result > 0
        if user_id
          UserStat.where(user_id: user_id).update_all "topics_entered = topics_entered + 1"
        end
      end

      # Update the views count in the parent, if it exists.
    end
  end
end