Avatars missing after import

Somehow my database after backup restore and migration from 1.6 to 2.5 Discourse was missing width, height and extension values for Upload table (file pointers were correct and files on its place).

I have ended up creating a script that goes through all custom uploaded avatars and corrects extension, dimensions and re-generates all OptimizedImages with version 2 thumbnails which I was missing.

For anyone interested, here it is:

fix-avatars.rb

require File.expand_path("../../config/environment", __FILE__)

generated_count = 0

scope = UserAvatar.where("custom_upload_id > 0")

scope.find_each do |ua|

  upload_id = ua.custom_upload_id

  upload = Upload.find_by(id: upload_id)
  
  unless upload
    puts "\nno upload found for this user avatar"
    next
  end
  
  # fix unknown
  if upload.extension === 'unknown'
    upload.extension = nil 
    upload.save!
    puts "\rupload_id #{upload.id} extension unknown -> nil"
  end

  if upload.extension.nil?
    puts "\rupload_id #{upload.id} fixing extension"

    upload.fix_image_extension

    if upload.height == 0 || upload.width == 0
      puts "\rupload_id #{upload.id} fixing dimensions"
      upload.fix_dimensions!
    end

    # check optimized version
    correct_optimized = OptimizedImage.where(upload_id: upload_id)
      .where(version: 2)

    if correct_optimized.count < 1
      puts "\rupload_id #{upload.id} doesn't have version 2 thumbnails"

      # destroy old optimized
      puts "\rupload_id #{upload.id} deleting avatars"
      optimized = OptimizedImage.where(upload_id: upload_id)

      if optimized
        optimized.destroy_all
      end

      #generate optimized
      puts "\rupload_id #{upload.id} creating avatars"
      Discourse.avatar_sizes.each {|size| OptimizedImage.create_for(upload, size, size, allow_animation: SiteSetting.allow_animated_avatars)}

      generated_count += 1

      puts "\rGenerated #{generated_count} total avatars"

    end
  end

end