Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Created June 28, 2013 16:33
Show Gist options
  • Save matthutchinson/5886053 to your computer and use it in GitHub Desktop.
Save matthutchinson/5886053 to your computer and use it in GitHub Desktop.
# script to import cms assets from those hosted on cms.housetrip.com and
# upload them as cms asset objects to cloudfront, also updating all
# references to the images in cms_page_contents markdown for all locales
# only the about us and press corner pages contain assets
# create a tmp dir for this script to keep downloaded assets in
`rm -rf tmp/cms_asset_import`
`mkdir -p tmp/cms_asset_import`
# helper methods
def original_local_file_path(url)
uri = URI.parse(url)
filename = uri.path.split('/')[-1]
digest = Digest::MD5.hexdigest(uri.path)[0..5]
"tmp/cms_asset_import/#{digest}-#{filename}"
end
def download_image(url)
local_path = original_local_file_path(url)
uri = URI.parse(url)
response = Net::HTTP.start(uri.host, uri.port) {|http|
http.get(uri.path)
}
case response
when Net::HTTPSuccess
image_data = response.body
return nil if image_data.nil? || image_data.size == 0
filename = uri.path.split('/')[-1]
open(local_path, "wb") { |file| file.write(image_data) }
return true
end
false
end
cms_pages = CmsPage.find(:all, :conditions => ['identity IN (?)', ['about-us', 'press-corner']])
# scan pages for asset urls
asset_urls = []
cms_pages.each do |cms_page|
puts "looking for assets on; '#{cms_page.name}'"
cms_page.cms_page_contents.each do |cms_page_content|
# find all linked assets from cms.housetrip.com in content
urls = cms_page_content.body.scan(/(http:\/\/cms\.housetrip\.com.*(png|jpg|pdf|gif|jpeg|PDF))/)
urls.collect! {|url| url[0] if url[0] =~ /http/ }
break unless urls.present?
puts " - #{cms_page_content.locale} (#{urls.length} assets)"
asset_urls += urls
end
end
asset_urls.uniq!
# download assets and build replacements array
replacements = []
puts "downloading #{asset_urls.length} assets"
asset_urls.each do |asset_url|
# download the assets
if download_image(asset_url)
# upload the asset
if new_cms_asset = CmsAsset.create(:asset => File.open(original_local_file_path(asset_url)))
# set replacement url to gsub
replacements << { :original_url => asset_url, :new_url => new_cms_asset.asset.url }
else
puts "couldn't create asset for #{asset_url}"
end
end
end
# update all references within cms_page_content contents
cms_pages.each do |cms_page|
puts "replacing asset urls on; '#{cms_page.name}'"
cms_page.cms_page_contents.each do |cms_page_content|
new_body = cms_page_content.body
replacements.each do |replacement|
new_body.gsub!(replacement[:original_url], replacement[:new_url])
end
cms_page_content.reload
cms_page_content.body = new_body
if cms_page_content.save!
puts " - #{cms_page_content.locale} done!"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment