post view count service: switch to Danbooru::Http.

This commit is contained in:
evazion
2020-06-13 21:50:06 -05:00
parent 9e29326b96
commit 1846133cd6
2 changed files with 25 additions and 102 deletions

View File

@@ -1,38 +1,25 @@
class PostViewCountService
def self.enabled?
Danbooru.config.reportbooru_server.present?
attr_reader :http, :reportbooru_server
def initialize(http: Danbooru::Http.new, reportbooru_server: Danbooru.config.reportbooru_server)
@reportbooru_server = reportbooru_server
@http = http
end
def initialize
if !PostViewCountService.enabled?
raise NotImplementedError.new("the Reportbooru service isn't configured. Post views are not available.")
end
end
def fetch_count(post_id)
url = URI.parse("#{Danbooru.config.reportbooru_server}/post_views/#{post_id}")
response = HTTParty.get(url, Danbooru.config.httparty_options.reverse_merge(timeout: 6))
if response.success?
return JSON.parse(response.body)
else
return nil
end
def enabled?
reportbooru_server.present?
end
def fetch_rank(date = Date.today)
url = URI.parse("#{Danbooru.config.reportbooru_server}/post_views/rank?date=#{date}")
response = HTTParty.get(url, Danbooru.config.httparty_options.reverse_merge(timeout: 6))
if response.success?
return JSON.parse(response.body)
else
return nil
end
rescue JSON::ParserError
nil
raise NotImplementedError, "Reportbooru not configured, post views not available." unless enabled?
response = http.get("#{reportbooru_server}/post_views/rank?date=#{date}")
return [] if response.status != 200
JSON.parse(response.to_s)
end
def popular_posts(date = Date.today)
ranking = fetch_rank(date) || []
ranking = fetch_rank(date)
ranking.slice(0, 50).map {|x| Post.find(x[0])}
end
end