Bulk action help: replace hotlinked images with local image files

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

1 Like

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

2 Likes