81 lines
1.8 KiB
Ruby
Raw Normal View History

2024-12-07 18:40:23 +01:00
# frozen_string_literal: true
module DiscourseRewind
# Service responsible to fetch a rewind for a username/year.
#
# @example
# ::DiscourseRewind::Rewind::Fetch.call(
2024-12-13 17:00:17 +01:00
# guardian: guardian
2024-12-07 18:40:23 +01:00
# )
#
2025-01-20 16:50:51 +01:00
class FetchReports
2024-12-07 18:40:23 +01:00
include Service::Base
# @!method self.call(guardian:, params:)
# @param [Guardian] guardian
# @param [Hash] params
# @option params [Integer] :year of the rewind
# @option params [Integer] :username of the rewind
# @return [Service::Base::Context]
2025-01-20 16:50:51 +01:00
CACHE_DURATION = Rails.env.development? ? 10.seconds : 5.minutes
# order matters
REPORTS = [
Action::TopWords,
Action::ReadingTime,
Action::Reactions,
Action::Fbff,
Action::FavoriteTags,
2025-01-20 16:50:51 +01:00
Action::FavoriteCategories,
Action::BestTopics,
Action::BestPosts,
Action::ActivityCalendar,
]
2024-12-07 18:40:23 +01:00
2025-01-13 17:00:32 +01:00
model :year
2024-12-11 22:38:58 +01:00
model :user
model :date
2024-12-07 18:40:23 +01:00
model :reports
private
2024-12-13 17:00:17 +01:00
def fetch_user(guardian:)
User.find_by_username(guardian.user.username)
2024-12-11 22:38:58 +01:00
end
2025-01-13 17:00:32 +01:00
def fetch_year
current_date = Time.zone.now
current_month = current_date.month
current_year = current_date.year
case current_month
when 1
current_year - 1
when 12
current_year
else
false
end
end
def fetch_date(params:, year:)
Date.new(year).all_year
2024-12-11 22:38:58 +01:00
end
2025-01-13 17:00:32 +01:00
def fetch_reports(date:, user:, guardian:, year:)
2025-01-20 16:50:51 +01:00
key = "rewind:#{guardian.user.username}:#{year}"
reports = Discourse.redis.get(key)
2024-12-07 18:40:23 +01:00
2025-01-20 16:50:51 +01:00
if !reports
reports = REPORTS.map { |report| report.call(date:, user:, guardian:) }
Discourse.redis.setex(key, CACHE_DURATION, MultiJson.dump(reports))
else
reports = MultiJson.load(reports, symbolize_keys: true)
end
2024-12-07 18:40:23 +01:00
reports
end
end
end