Bulk action help: replace hotlinked images with local image files

AI-generated summary

A user, shyguy, is seeking help with a bulk action to replace hotlinked images with local image files on a Discourse forum. The images were previously hosted on a defunct image hoster (foo-host.com), but have been manually backed up and a mapping exists between the image URL and local file path. The user has provided a Ruby script to find posts with hotlinked images, but needs assistance with uploading the local images as attachments and replacing the hotlinks with the attachments. pfaffman suggests looking at the import scripts for examples of how to upload files and insert the HTML for those uploads.

scenario:

  • a free image hoster (foo-host in this example) has gone defunct, and a discourse forum currently has a bunch of hotlinked images in its posts
  • images were backed up manually before they rotted and exist on the local filesystem
  • a mapping exists between image url and local file path: get_paths_from_hotlinked_urls()

how can i:

  1. create an attachment in rails for each of these images and
  2. add them to the post correctly?
image_host_domain = 'foo-host.com'

hotlink_posts = Post.where('cooked ~ ?', image_host_domain)
puts "found #{hotlink_posts.length} posts with hotlinked images..."

hotlink_posts.each do |p|
  # get all URLs in post containing image_host_domain
  urls = URI.extract(p.cooked).select { |url| url[/#{Regexp.quote(image_host_domain)}/] }

  local_paths = get_paths_from_hotlinked_urls(urls)

  new_raw = p.raw
  urls.each.with_index do |url, i|
    next if local_paths[i].blank?

    # ***** TODO: 1) 'upload' local_paths[i] as attachment
    #                and correctly associate it with the post

    # ***** TODO: 2) replace hotlink with attachment
    # new_raw = new_raw...
  end

  p.update(raw: new_raw)
end

sorry for the low effort post. just feeling a bit stressed today, lol

can someone please point me in the right direction? complete solution not required if it’s too much hassle. thanks

You can look at the import scripts for examples of how to upload files and insert the html for those uploads.