]> git.openstreetmap.org Git - rails.git/blob - lib/tasks/normalise_avatars.rake
Merge remote-tracking branch 'upstream/pull/7650'
[rails.git] / lib / tasks / normalise_avatars.rake
1 # frozen_string_literal: true
2
3 namespace :db do
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"]
7
8     before = Time.zone.iso8601(ENV.fetch("BEFORE"))
9
10     User.joins(:avatar_blob)
11         .where(:active_storage_blobs => { :content_type => User::AVATAR_CONTENT_TYPES })
12         .where(:active_storage_blobs => { :created_at => ...before })
13         .find_each do |user|
14       user.with_lock do
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
18
19         blob.open do |file|
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}"
24           else
25             puts "Failed to normalise #{blob.content_type} avatar for user #{user.id}: #{user.errors.full_messages.to_sentence}"
26           end
27         end
28       end
29     rescue ActiveStorage::FileNotFoundError
30       puts "Missing avatar file for user #{user.id}"
31     end
32   end
33 end