Websites/app/models/api_image.rb

100 lines
2.7 KiB
Ruby
Raw Normal View History

2024-05-03 03:04:43 +00:00
# frozen_string_literal: true
class APIImage < ApplicationRecord
CDN_URL = "https://v2.yiff.media/"
belongs_to_creator
module SearchMethods
def random(category, limit, size_limit = nil)
q = where(category: category)
q = q.where(file_size: ..size_limit) if size_limit
q.ids.sample(limit).map(&method(:find))
end
def bulk(category_map, size_limit = nil)
data = {}
category_map.each do |category, limit|
data[category] = random(category, limit, size_limit)
end
data
end
end
extend SearchMethods
def md5
id.gsub("-", "")
end
def url
"#{CDN_URL}#{category.gsub('.', '/')}/#{md5}.#{file_ext}"
end
def short_url
ShortUrl.override(md5, url).shorturl
end
def serializable_hash(*)
{
artists: artists,
sources: sources,
width: width,
height: height,
url: url,
type: mime_type,
name: "#{md5}.#{file_ext}",
id: md5,
ext: file_ext,
size: file_size,
reportURL: nil,
shortURL: short_url,
}
end
def self.categories
sfw = %w[animals.birb animals.blep animals.dikdik furry.boop furry.cuddle furry.flop furry.fursuit furry.hold furry.howl furry.hug furry.kiss furry.lick furry.propose]
nsfw = %w[furry.butts furry.bulge furry.yiff.andromorph furry.yiff.gay furry.yiff.gynomorph furry.yiff.lesbian furry.yiff.straight]
titles = {
**sfw.index_with { |c| c.split(".").map(&:capitalize).join(" > ") },
"animals.dikdik" => "Animals > Dik Dik",
**nsfw.index_with { |c| c.split(".").map(&:capitalize).join(" > ") },
}
# noinspection RubyMismatchedArgumentType
sfw.map { |c| { name: titles[c], db: c, sfw: true } }
.concat(nsfw.map { |c| { name: titles[c], db: c, sfw: false } })
end
def self.category_title(db)
categories.find { |k| k == db }.try(:db) || db.split(".").map(&:capitalize).join(" > ")
end
def self.cached_count(category)
count = Cache.redis.get("yiffy2:images:#{category}")
if count.nil?
count = APIImage.where(category: category).count
# images aren't changing so we really don't need any expiry, but I still want an expiry just in case
Cache.redis.set("yiffy2:images:#{category}", count.to_s, ex: 60 * 60 * 24 * 7)
end
count.to_i
end
def self.state
data = group(:category).count.map do |k, v|
{
count: v,
name: category_title(k),
category: k,
state: v < 5 ? "red" : v < 20 ? "yellow" : "green",
}
end
[*data, {
count: data.pluck(:count).reduce(:+),
name: "Total",
category: "total",
state: "total",
},]
end
end