# frozen_string_literal: true module YiffRest class ThumbsController < ApplicationController include ::ApplicationController::ReadonlyMethods before_action :handle_ratelimit before_action :validate_api_key_required before_action :validate_thumbs_access before_action :validate_post before_action -> { track_usage("thumbs") } def show render(json: E621Thumbnail.urls_from_post(@post)) end def create return render_error(YiffyAPIErrorCodes::THUMBS_GIF_DISABLED, error: "The gif type has been disabled.") if params[:type] == "gif" && Websites.config.e621_thumbnails_disable_gif thumb = E621Thumbnail.find_by_post(@post, params[:type]) if thumb.present? return render_error(YiffyAPIErrorCodes::THUMBS_TIMEOUT, error: "Generation timed out.", expiresAt: thumb.expires_at&.to_i) if thumb.timeout? if thumb.error? message = "Generation encountered an error." message += " (#{thumb.error_code})" if thumb.error_code.present? return render_error(YiffyAPIErrorCodes::THUMBS_GENERIC_ERROR, error: message, expiresAt: thumb.expires_at&.to_i) end if thumb.complete? return render(json: { success: true, status: "done", url: thumb.url, }) end else thumb = E621Thumbnail.from_post(@post, params[:type], api_key_id: @apikey.id) end thumb.generate! if thumb.pending? render(status: 202, json: { success: true, status: "processing", checkURL: thumb.check_url, checkAt: (Time.now + thumb.check_time).to_i, time: thumb.check_time, startedAt: thumb.created_at.to_i, }) end def check return render_error(YiffyAPIErrorCodes::THUMBS_GIF_DISABLED, error: "The gif type has been disabled.") if params[:type] == "gif" && Websites.config.e621_thumbnails_disable_gif thumb = E621Thumbnail.find_by_post(@post, params[:type]) return render_error(YiffyAPIErrorCodes::THUMBS_CHECK_NOT_FOUND, error: "Not Found") if thumb.blank? return render_error(YiffyAPIErrorCodes::THUMBS_TIMEOUT, error: "Generation timed out.", expiresAt: thumb.expires_at&.to_i) if thumb.timeout? if thumb.error? message = "Generation encountered an error." message += " (#{thumb.error_code})" if thumb.error_code.present? return render_error(YiffyAPIErrorCodes::THUMBS_GENERIC_ERROR, error: message, expiresAt: thumb.expires_at&.to_i) end if thumb.complete? return render(status: 201, json: { success: true, status: "done", url: thumb.url, }) end render(status: 200, json: { success: true, status: "processing", checkURL: thumb.check_url, checkAt: (Time.now + thumb.check_time).to_i, time: thumb.check_time, startedAt: thumb.created_at.to_i, }) end private def validate_post @md5 = params[:id].to_s @post = nil if /^\d+$/.match?(@md5) @post = Requests::E621.get_post(id: params[:id]) return render_error(YiffyAPIErrorCodes::THUMBS_INVALID_POST_ID, error: "Invalid Post ID") if @post.nil? @md5 = post["file"]["md5"] end @post = Requests::E621.get_post(md5: params[:id]) if /[a-f\d]{32}/i.match?(@md5) render_error(YiffyAPIErrorCodes::THUMBS_INVALID_MD5, error: "Invalid Post") if @post.nil? end end end