2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-31 00:06:56 -04:00
|
|
|
class BackfillPostUploadReverseIndex < ActiveRecord::Migration[4.2]
|
2013-10-14 08:27:41 -04:00
|
|
|
def up
|
|
|
|
# clean the reverse index
|
|
|
|
execute "TRUNCATE TABLE post_uploads"
|
|
|
|
|
|
|
|
# fill the reverse index up
|
|
|
|
Post
|
|
|
|
.select(%i[id cooked])
|
|
|
|
.find_each do |post|
|
2020-05-04 23:46:57 -04:00
|
|
|
doc = Nokogiri::HTML5.fragment(post.cooked)
|
2013-10-14 08:27:41 -04:00
|
|
|
# images
|
|
|
|
doc.search("img").each { |img| add_to_reverse_index(img["src"], post.id) }
|
|
|
|
# thumbnails and/or attachments
|
|
|
|
doc.search("a").each { |a| add_to_reverse_index(a["href"], post.id) }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def add_to_reverse_index(url, post_id)
|
|
|
|
# make sure we have a url to insert
|
|
|
|
return unless url.present?
|
|
|
|
# local uploads are relative
|
|
|
|
if index = url.index(local_base_url)
|
|
|
|
url = url[index..-1]
|
|
|
|
end
|
|
|
|
# filter out non-uploads
|
2013-10-15 05:36:27 -04:00
|
|
|
return unless is_local?(url) || is_on_s3?(url)
|
2013-10-14 08:27:41 -04:00
|
|
|
# update the reverse index
|
|
|
|
execute "INSERT INTO post_uploads (upload_id, post_id)
|
|
|
|
SELECT u.id, #{post_id}
|
|
|
|
FROM uploads u
|
|
|
|
WHERE u.url = '#{url}'
|
|
|
|
AND NOT EXISTS (SELECT 1 FROM post_uploads WHERE upload_id = u.id AND post_id = #{post_id})"
|
|
|
|
end
|
|
|
|
|
|
|
|
def local_base_url
|
|
|
|
@local_base_url ||= "/uploads/#{RailsMultisite::ConnectionManagement.current_db}"
|
|
|
|
end
|
|
|
|
|
2013-10-15 05:36:27 -04:00
|
|
|
def local_optimized_base_url
|
2013-10-16 04:55:20 -04:00
|
|
|
@local_optimized_base_url ||= "#{local_base_url}/_optimized"
|
|
|
|
end
|
|
|
|
|
|
|
|
def local_avatar_base_url
|
|
|
|
@local_avatar_base_url ||= "#{local_base_url}/avatars"
|
2013-10-15 05:36:27 -04:00
|
|
|
end
|
|
|
|
|
2013-10-14 08:27:41 -04:00
|
|
|
def s3_base_url
|
|
|
|
@s3_base_url ||= "//#{SiteSetting.s3_upload_bucket.downcase}.s3.amazonaws.com"
|
|
|
|
end
|
|
|
|
|
2013-10-16 04:55:20 -04:00
|
|
|
def s3_avatar_base_url
|
|
|
|
@s3_avatar_base_url ||= "#{s3_base_url}/avatars"
|
|
|
|
end
|
|
|
|
|
2013-10-15 05:36:27 -04:00
|
|
|
def is_local?(url)
|
2013-10-16 04:55:20 -04:00
|
|
|
url.starts_with?(local_base_url) && !is_local_thumbnail?(url) && !is_local_avatar?(url)
|
2013-10-15 05:36:27 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def is_local_thumbnail?(url)
|
|
|
|
url.starts_with?(local_optimized_base_url)
|
|
|
|
end
|
|
|
|
|
2013-10-16 04:55:20 -04:00
|
|
|
def is_local_avatar?(url)
|
|
|
|
url.starts_with?(local_avatar_base_url)
|
|
|
|
end
|
|
|
|
|
2013-10-15 05:36:27 -04:00
|
|
|
def is_on_s3?(url)
|
2013-10-16 04:55:20 -04:00
|
|
|
url.starts_with?(s3_base_url) && !is_s3_avatar?(url)
|
|
|
|
end
|
|
|
|
|
|
|
|
def is_s3_avatar?(url)
|
|
|
|
url.starts_with?(s3_avatar_base_url)
|
2013-10-15 05:36:27 -04:00
|
|
|
end
|
2013-10-14 08:27:41 -04:00
|
|
|
end
|