Files
raucao ab3c2bffd6 Process and relay Nostr profile images server-side
Add a server-side API for avatar and header images: uploads are cropped with Vips (400x400 and 1500x500, GIFs passed through, EXIF stripped, transparency flattened to white) and stored as one pending attachment per field. Saving the profile flushes them to the configured Blossom server, authorized by a user-signed kind-24242 token whose x tags cover the stored hashes.
2026-11-19 21:58:08 +04:00

57 lines
1.7 KiB
Ruby

module NostrManager
class ProcessProfileImage < NostrManagerService
DIMENSIONS = { "picture" => [400, 400], "banner" => [1500, 500] }.freeze
PASSTHROUGH_TYPES = %w[image/gif].freeze
OUTPUT_EXTENSIONS = { "image/png" => "png" }.freeze
DEFAULT_EXTENSION = "jpg"
MAX_PIXELS = 50_000_000
MAX_SIDE = 20_000
def initialize(field:, io:, content_type:)
@field = field.to_s
@io = io
@content_type = content_type
end
def call
dimensions = DIMENSIONS[@field]
return nil if dimensions.nil? || @io.nil?
Tempfile.create(["nostr-profile-image", ".#{output_extension}"]) do |source|
source.binmode
source.write(@io.read)
source.rewind
image = Vips::Image.new_from_file(source.path)
return nil unless within_bounds?(image)
return File.binread(source.path) if PASSTHROUGH_TYPES.include?(@content_type)
width, height = dimensions
pipeline = ImageProcessing::Vips.source(source.path).resize_to_fill(width, height)
pipeline = pipeline.flatten(background: [255]) if jpeg_output? && image.has_alpha?
pipeline.saver(strip: true).call.read
end
rescue Vips::Error => e
Rails.logger.warn { "Nostr profile image processing failed: #{e.message}" }
nil
end
private
def output_extension
OUTPUT_EXTENSIONS.fetch(@content_type, DEFAULT_EXTENSION)
end
def jpeg_output?
output_extension == DEFAULT_EXTENSION
end
def within_bounds?(image)
return false unless image.width.between?(1, MAX_SIDE)
return false unless image.height.between?(1, MAX_SIDE)
image.width * image.height <= MAX_PIXELS
end
end
end