# frozen_string_literal: true require "open-uri" class APIUser < ApplicationRecord has_many :api_keys, foreign_key: :owner_id has_many :api_images, foreign_key: :creator_id has_many :short_urls, foreign_key: :creator_id has_many :e621_thumbnails, foreign_key: :creator_id has_one_attached :avatar attr_accessor :discord_data before_create do self.level = Levels::DEFAULT if level.blank? self.name = "User#{id}" if name.blank? end module Levels DEFAULT = 0 MANAGER = 10 ADMIN = 20 def self.level_name(level) name = constants.find { |c| const_get(c) == level }.to_s.titleize return "Unknown: #{level}" if name.blank? name end end module LevelMethods Levels.constants.each do |constant| define_method("is_#{constant.downcase}?") do level >= Levels.const_get(constant) end define_method("is_exactly_#{constant.downcase}?") do level == Levels.const_get(constant) end end def level_name Levels.level_name(level) end def is_anonymous? self == APIUser.anonymous end end include LevelMethods def self.anonymous user = new(id: "0", name: "Anonymous", level: Levels::DEFAULT, created_at: Time.now) user.freeze.readonly! user end def self.system sys = find_or_create_by(id: "875334238856163368") sys.update_columns(name: "System") if sys.name != "System" sys end def method_missing(method, *) return discord_data[method.to_s] if discord_data.present? && discord_data.key?(method.to_s) super end def update_avatar(hash) return false if hash == last_avatar_hash && avatar.attached? return false if Cache.fetch("avatar_update:#{id}") Cache.write("avatar_update:#{id}", "1", expires_in: 1.day) avatar.purge url = "https://yiff.rest/Blep.png" url = "https://cdn.discordapp.com/avatars/#{id}/#{hash}.webp?size=128" unless hash.nil? image = URI.open(url) # rubocop:disable Security/Open avatar.attach(io: image, filename: "#{hash}.webp") update!(last_avatar_hash: hash) true rescue OpenURI::HTTPError => e Rails.logger.warn(e) end def can_create_apikey? api_keys.length < 3 end end