# Bulk action help: replace hotlinked images with local image files

**URL:** <https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912>\
**Category:** Development\
**Created:** [May 13, 2023, 9:07pm UTC](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912 "2023-05-13T21:07:13Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![shyguy](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/shyguy/32/295079_2.png) [@shyguy](https://meta.discourse.org/u/shyguy)\
**Post date:** [May 13, 2023, 9:07pm UTC](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912/1 "2023-05-13T21:07:13Z")

</div>

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?

```ruby
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

---

_[View the full topic](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912)._
