|
| 1 | +# lib/tasks/migrate_resource_pdfs.rake |
| 2 | +require "open-uri" |
| 3 | + |
| 4 | +namespace :resources do |
| 5 | + desc "Migrate legacy PDF URLs to main or gallery images" |
| 6 | + task migrate_pdfs: :environment do |
| 7 | + dry_run = ENV["DRY_RUN"] == "true" |
| 8 | + |
| 9 | + scope = Resource.where.not(url: [nil, ""]) |
| 10 | + .where.not(kind: ["Story", "LeaderSpotlight", |
| 11 | + "SectorImpact", "Scholarship", "Theme"]) |
| 12 | + |
| 13 | + puts "Found #{scope.count} resources with legacy PDF URLs" |
| 14 | + puts "DRY RUN: #{dry_run ? 'ON' : 'OFF'}" |
| 15 | + puts "-" * 70 |
| 16 | + |
| 17 | + scope.find_each(batch_size: 25) do |resource| |
| 18 | + puts "→ Resource ##{resource.id} — #{resource.title}" |
| 19 | + |
| 20 | + begin |
| 21 | + uri = URI.parse(resource.url) |
| 22 | + filename = File.basename(uri.path.presence || "resource-#{resource.id}.pdf") |
| 23 | + |
| 24 | + image_class = resource.main_image.blank? ? Images::MainImage : Images::GalleryImage |
| 25 | + |
| 26 | + puts " Resource type: #{resource.kind}" |
| 27 | + puts " Target image type: #{image_class.name}" |
| 28 | + puts " Source URL: #{resource.url}" |
| 29 | + puts " Filename: #{filename}" |
| 30 | + puts " ++++++++++" |
| 31 | + |
| 32 | + if dry_run |
| 33 | + puts " DRY RUN — no changes made" |
| 34 | + puts "-" * 70 |
| 35 | + next |
| 36 | + end |
| 37 | + |
| 38 | + file = uri.open( |
| 39 | + read_timeout: 30, |
| 40 | + ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER |
| 41 | + ) |
| 42 | + |
| 43 | + unless file.content_type == "application/pdf" |
| 44 | + raise "Expected PDF, got #{file.content_type}" |
| 45 | + end |
| 46 | + |
| 47 | + uploaded_file = ActionDispatch::Http::UploadedFile.new( |
| 48 | + tempfile: file, |
| 49 | + filename: filename, |
| 50 | + type: "application/pdf" |
| 51 | + ) |
| 52 | + |
| 53 | + image = image_class.create!( |
| 54 | + owner: resource, |
| 55 | + file: uploaded_file |
| 56 | + ) |
| 57 | + |
| 58 | + puts " ✔ Attached as #{image.class.name}" |
| 59 | + |
| 60 | + rescue => e |
| 61 | + puts " ✖ ERROR: #{e.class}" |
| 62 | + puts " #{e.message}" |
| 63 | + puts " Resource left unchanged" |
| 64 | + end |
| 65 | + |
| 66 | + puts "-" * 70 |
| 67 | + end |
| 68 | + |
| 69 | + puts "Migration complete." |
| 70 | + end |
| 71 | +end |
0 commit comments