Websites/app/models/e621_thumbnail.rb
Donovan Daniels f84eef5e5f
Add git storage manager
Yes, I'm aware this is dumb
No, I don't care
2024-06-29 02:13:04 -05:00

131 lines
2.8 KiB
Ruby

# frozen_string_literal: true
class E621Thumbnail < ApplicationRecord
class DeletedPostError < StandardError; end
belongs_to_creator
belongs_to :api_key, optional: true
# def post
# p = Requests::E621.get_post(id: post_id)
# current_md5 = p.try(:[], "file").try(:[], "md5")
# if current_md5.present? && current_md5 != stripped_md5
# update(md5: p["file"]["md5"])
# regenerate!
# end
# end
module FileMethods
def regenerate!
delete_files!
generate!
end
def generate!
update(status: "generating")
E621ThumbnailJob.perform_later(self)
end
def delete_files!
Websites.config.e621_thumbnails_storage.delete("/#{stripped_md5}.#{filetype}") if StorageManager::E621Thumbnails.exists?("#{stripped_md5}.#{filetype}")
Websites.config.e621_thumbnails_backup_storage.delete("/#{stripped_md5}.#{filetype}") if StorageManager::E621Thumbnails.exists?("#{stripped_md5}.#{filetype}")
end
def url
Websites.config.e621_thumbnails_storage.url_for(self)
end
def path
"/#{stripped_md5}.#{filetype}"
end
end
module StatusMethods
def pending?
status == "pending"
end
def generating?
status == "generating"
end
def complete?
status == "complete"
end
def error?
status == "error"
end
def timeout?
status == "timeout"
end
end
module CheckMethods
def check_url
"https://thumbs.yiff.rest/check/#{stripped_md5}/#{filetype}"
end
def check_time
time = Time.now - created_at
case filetype
when "gif"
return 5_000 if time > 45_000
return 10_000 if time > 30_000
15_000
when "png"
return 2_500 if time > 30_000
return 5_000 if time > 20_000
10_000
else
0
end
end
end
include FileMethods
include StatusMethods
include CheckMethods
def stripped_md5
md5.gsub("-", "")
end
def refresh!
end
def self.refresh_all!
unique = E621Thumbnail.select(:md5).distinct
unique.each_slice(100) do |slice|
tags = "md5:#{slice.map(&:stripped_md5).join(',')}"
Rails.logger.debug(tags)
end
end
def self.from_post(post, type, api_key_id:)
raise(DeletedPostError) if post["flags"]["deleted"]
E621Thumbnail.create!(
api_key_id: api_key_id,
md5: post["file"]["md5"],
filetype: type,
post_id: post["id"],
)
end
def self.urls_from_post(post)
find_by_post(post).transform_values { |thumb| thumb&.url }
end
def self.find_by_post(post, type = nil)
raise(DeletedPostError) if post["flags"]["deleted"]
md5 = post["file"]["md5"]
q = where(md5: md5)
return q.find_by(filetype: type) if type.present?
{
gif: q.find_by(md5: md5, filetype: "gif"),
png: q.find_by(md5: md5, filetype: "png"),
}
end
end