1 # frozen_string_literal: true
4 desc "Normalise avatars uploaded before BEFORE (an ISO 8601 time), replacing the originals"
5 task :normalise_avatars => :environment do
6 abort "Set BEFORE to the ISO 8601 time when upload normalisation was deployed, e.g. BEFORE=2026-11-20T00:00:00Z" unless ENV["BEFORE"]
8 before = Time.zone.iso8601(ENV.fetch("BEFORE"))
10 User.joins(:avatar_blob)
11 .where(:active_storage_blobs => { :content_type => User::AVATAR_CONTENT_TYPES })
12 .where(:active_storage_blobs => { :created_at => ...before })
15 blob = user.avatar.blob
16 # Skip if the user uploaded a new avatar since we selected them
17 next if blob.created_at >= before
20 user.avatar = { :io => file, :filename => blob.filename.to_s, :content_type => blob.content_type }
21 # Skip validation, as old users and avatars may not pass current checks
22 if user.save(:validate => false)
23 puts "Normalised #{blob.content_type} avatar for user #{user.id}"
25 puts "Failed to normalise #{blob.content_type} avatar for user #{user.id}: #{user.errors.full_messages.to_sentence}"
29 rescue ActiveStorage::FileNotFoundError
30 puts "Missing avatar file for user #{user.id}"