-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathrich_text_urls_update.rake
More file actions
210 lines (192 loc) · 6.71 KB
/
rich_text_urls_update.rake
File metadata and controls
210 lines (192 loc) · 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
require "csv"
require "aws-sdk-s3"
include Rails.application.routes.url_helpers
namespace :rich_text_urls_update do
desc "Update picture URLs in all text columns for models with optional start/end IDs"
task :images, [ :start_id, :finish_id ] => :environment do |t, args|
run_update(
dry_run: false,
html_attr: "src",
start_id: args[:start_id]&.to_i,
finish_id: args[:finish_id]&.to_i
)
end
desc "Update link URLs in all text columns for models with optional start/end IDs"
task :links, [ :start_id, :finish_id ] => :environment do |t, args|
run_update(
dry_run: false,
html_attr: "href",
start_id: args[:start_id]&.to_i,
finish_id: args[:finish_id]&.to_i
)
end
desc "Dry run: check picture URLs without updating, generate CSV report"
task dry_run: :environment do
run_update(dry_run: true)
end
def run_update(dry_run:, html_attr:, start_id: nil, finish_id: nil)
models = [
Address,
AnswerOption,
Attachment,
Banner,
Bookmark,
Category,
CategorizableItem,
CommunityNews,
EventRegistration,
Event,
Facilitator,
Faq,
FormBuilder,
FormFieldAnswerOption,
FormField,
Form,
Image,
Location,
MediaFile,
CategoryType,
MonthlyReport,
Notification,
ProjectObligation,
ProjectStatus,
ProjectUser,
Project,
QuotableItemQuote,
Quote,
ReportFormFieldAnswer,
Report,
Resource,
SectorableItem,
Sector,
Story,
StoryIdea,
UserFormFormField,
UserForm,
User,
WindowsType,
WorkshopIdea,
WorkshopLog,
WorkshopResource,
WorkshopSeriesMembership,
WorkshopVariation,
Workshop
]
timestamp = Time.now.strftime("%Y%m%d_%H%M%S")
csv_file = Rails.root.join("tmp", dry_run ? "dry_run_picture_urls_#{timestamp}.csv" : "updated_picture_urls_#{timestamp}.csv")
CSV.open(csv_file, "w") do |csv|
csv << [ "model", "record_id", "column", "old_url", "aws_key", "status", "error", "replacement_url" ]
models.each do |model|
text_columns = model.columns.select { |c| c.type == :text }.map(&:name)
puts "Processing #{model}..........................................................................................."
model.find_each(start: start_id, finish: finish_id) do |record|
puts "Processing #{model} id: #{record.id}"
text_columns.each do |column|
next unless record[column].present?
process_content(model, record, column, dry_run, csv, html_attr)
end
end
end
end
upload_csv("rich_text_update_log_#{Time.now.to_i}.csv", csv_file)
puts "CSV report generated at #{csv_file}"
end
def process_content(model, record, column, dry_run, csv, html_attr)
regex = /#{html_attr}="([^"]*)"/
record.public_send(column).gsub(regex) do |match|
url = match[regex, 1] # extract the actual URL
aws_prefix = "https://s3.amazonaws.com/awbwassets/"
aws_prefix_2 = "http://s3.amazonaws.com/awbwassets/"
aws_prefix_3 = "//s3.amazonaws.com/awbwassets/"
dashboard_url = nil
key = nil
puts url
case url
when %r{^/awbw/u} # matches any URL starting with /awbw/u
dashboard_url = "https://dashboard.awbw.org#{url}"
key = url
when ->(u) { u.start_with?("https://dashboard.awbw.org/awbw") } # https
key = url.sub(%r{^https://dashboard\.awbw\.org}, "")
dashboard_url = url
when ->(u) { u.start_with?("http://dashboard.awbw.org/awbw") }
key = url.sub(%r{^http://dashboard\.awbw\.org}, "")
dashboard_url = "https://dashboard.awbw.org#{key}"
when ->(u) { u.start_with?("https://legacy.awbw.org/awbw") }
key = url.sub(%r{^https://legacy\.awbw\.org}, "")
dashboard_url = "https://dashboard.awbw.org#{key}"
when ->(u) { u.start_with?("http://legacy.awbw.org/awbw") }
key = url.sub(%r{^http://legacy\.awbw\.org}, "")
dashboard_url = "https://dashboard.awbw.org#{key}"
when ->(u) { u.start_with?(aws_prefix) } # matches URLs starting with the AWS prefix
key = url.sub(aws_prefix, "")
when ->(u) { u.start_with?(aws_prefix_2) }
key = url.sub(aws_prefix_2, "")
when ->(u) { u.start_with?(aws_prefix_3) }
key = url.sub(aws_prefix_3, "")
else
csv << [ model.name, record.id, column, url, nil, "skipped", "No Matching Url", nil ]
next
end
# Extract the S3 key
bucket = ENV["AWS_S3_BUCKET"]
if dry_run
begin
s3_client.head_object(bucket: bucket, key: key)
csv << [ model.name, record.id, column, url, key, "success", nil, nil ]
rescue Aws::S3::Errors::NotFound, Aws::S3::Errors::NoSuchKey
csv << [ model.name, record.id, column, url, key, "skipped", "Key not found", nil ]
end
next
end
begin
blob = ActiveStorage::Blob.find_by(aws_key: key)
asset = record.rich_text_assets.build
file_name = File.basename(key)
temp = nil
ActiveRecord::Base.transaction do
unless blob
temp = if dashboard_url
# Download from previous production local storage
URI.open(dashboard_url)
else
Tempfile.new(file_name)
end
temp.binmode
# Download from S3
unless dashboard_url
s3_client.get_object(bucket: bucket, key: key) do |chunk|
temp.write(chunk)
end
end
temp.rewind
content_type = Marcel::MimeType.for temp
blob = ActiveStorage::Blob.create_and_upload!(
io: temp,
filename: file_name,
content_type: content_type
)
blob.update!(aws_key: key)
end
asset.file.attach(blob)
asset.save!
new_url = url_for(asset.file)
# Verify attachment and association
record.rich_text_assets.reload
unless record.rich_text_assets.include?(asset) && asset.file.attached?
raise "Media not associated with record or file missing"
end
content = record.public_send(column)
new_content = content.gsub(url, new_url)
record.update_column(column, new_content)
# Log success
puts "#{model.name} # #{record.id} updated"
csv << [ model.name, record.id, column, url, key, "updated", nil, new_url ]
end
rescue => e
csv << [ model.name, record.id, column, url, key, "error", "#{e.class}: #{e.message}", nil ]
ensure
temp&.close
end
end
end
end