FEATURE: Only count topic views for explicit/deferred tracked views (#27533)

Followup 2f2da7274732cba30d03b6c5c3a4194652cb6783

This commit moves topic view tracking from happening
every time a Topic is requested, which is susceptible
to inflating numbers of views from web crawlers, to
our request tracker middleware.

In this new location, topic views are only tracked when
the following headers are sent:

* HTTP_DISCOURSE_TRACK_VIEW - This is sent on every page navigation when
  clicking around the ember app. We count these as browser page views
  because we know it comes from the AJAX call in our app. The topic ID
  is extracted from HTTP_DISCOURSE_TRACK_VIEW_TOPIC_ID
* HTTP_DISCOURSE_DEFERRED_TRACK_VIEW - Sent when MessageBus initializes
  after first loading the page to count the initial page load view. The
  topic ID is extracted from HTTP_DISCOURSE_DEFERRED_TRACK_VIEW.

This will bring topic views more in line with the change we
made to page views in the referenced commit and result in
more realistic topic view counts.
This commit is contained in:
Martin Brennan
2024-07-03 10:38:49 +10:00
committed by GitHub
parent 57af5d6f0d
commit 527f02e99f
12 changed files with 641 additions and 183 deletions

View File

@ -1266,7 +1266,6 @@ class TopicsController < ApplicationController
topic_id = @topic_view.topic.id
ip = request.remote_ip
user_id = (current_user.id if current_user)
track_visit = should_track_visit_to_topic?
if !request.format.json?
hash = {
@ -1283,13 +1282,32 @@ class TopicsController < ApplicationController
TopicsController.defer_add_incoming_link(hash)
end
TopicsController.defer_track_visit(topic_id, ip, user_id, track_visit)
TopicsController.defer_track_visit_v2(topic_id, user_id) if should_track_visit_to_topic?
end
# TODO (martin) Remove this once discourse-docs is updated.
def self.defer_track_visit(topic_id, ip, user_id, track_visit)
self.defer_track_visit_v2(topic_id, user_id) if track_visit
self.defer_topic_view(topic_id, ip, user_id)
end
def self.defer_track_visit_v2(topic_id, user_id)
Scheduler::Defer.later "Track Visit" do
TopicUser.track_visit!(topic_id, user_id)
end
end
def self.defer_topic_view(topic_id, ip, user_id = nil)
Scheduler::Defer.later "Topic View" do
topic = Topic.find_by(id: topic_id)
return if topic.blank?
# We need to make sure that we aren't allowing recording
# random topic views against topics the user cannot see.
user = User.find_by(id: user_id) if user_id.present?
return if user_id.present? && user.blank?
return if !Guardian.new(user).can_see_topic?(topic)
TopicViewItem.add(topic_id, ip, user_id)
TopicUser.track_visit!(topic_id, user_id) if track_visit
end
end