goo.gl 即将关闭(请参阅 https://developers.googleblog.com/en/google-url-shortener-links-will-no-longer-be-available/)。因此,您论坛上包含 goo.gl 链接的帖子将在 2025 年 8 月 25 日之后失效。
我为一位客户开发了这个脚本。它花费的时间远远超过了我向他收取的费用,也远远超过了我愿意承认的时间。
它会查找所有包含 goo.gl 的帖子,然后(如果它们不是 maps.app.goo.gl 或 maps.goo.gl)尝试将它们替换为 goo.gl 返回的 URL。它使用帖子修订器,因此您可以查看更新内容和原因,并且可以根据需要进行还原。我已经尽力使其万无一失,但请自行承担风险。
如果您不知道如何运行此脚本,则可能不应自行操作。如果您需要帮助使其正常工作并且有预算,请联系我或在 Marketplace 中提问。
如果您使用它并对如何改进它有什么建议,请回复并/或根据需要进行编辑。
URL_CACHE ||= {}
def resolve_url_simple(short_url)
uri = URI.parse(short_url)
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPRedirection)
response['location']
else
short_url # 如果没有重定向,则返回原始 URL
end
rescue
short_url # 如果发生错误,则返回原始 URL
end
def resolve_url(short_url)
short_url.gsub!(/http:/,"https:")
# 检查 URL 是否已在缓存中
return URL_CACHE[short_url] if URL_CACHE.key?(short_url)
begin
uri = URI.parse(short_url + "?si=1")
response = Net::HTTP.get_response(uri)
# 如果是重定向,则解析 URL
resolved_url = if response.is_a?(Net::HTTPRedirection)
response['location']
else
short_url # 如果没有重定向,则返回原始 URL
end
sleep 1
# 将解析后的 URL 存储在缓存中
URL_CACHE[short_url] = resolved_url
resolved_url
rescue
# 发生错误时,将原始 URL 存储在缓存中
URL_CACHE[short_url] = short_url
short_url
end
end
def replace_goo_gl_links(text)
goo_gl_regex = %r{(?<=\A|[\\[\\]\\(\\)\\s])(https?://)?goo\\.gl(/[a-zA-Z0-9]+)+}
text.gsub(goo_gl_regex) do |match|
if match.include?('maps.app.goo.gl')
match
else
full_url = match.start_with?('http') ? match : "https://#{match}"
print "FIXING!!: #{match} -----> "
fixed = resolve_url(full_url)
puts fixed
fixed
end
end
end
def replace_all_goo_gl_links
system_user= User.find(-1)
goo_go = Post.where("raw LIKE '%goo.gl%'")
total_posts = goo_go.count
puts "Found #{total_posts} posts to check"
count = 0
goo_go.find_each do |post|
count += 1
# puts "Processing #{count}. #{Discourse.base_url}/t/#{post.topic_id}/#{post.post_number}"
print "."
# 出于不明原因,尝试更新这些主题中的帖子会导致 rails 崩溃
# next if [145478,64885,84408].include? post.topic_id
# 查找 goo.gl 链接并查看它重定向到哪里
new_raw = replace_goo_gl_links(post.raw)
if new_raw != post.raw
revision_options = {
edit_reason: "Fix goo.gl links",
bypass_bump: true
}
begin
puts "Revising (#{count}/#{total_posts}) #{Discourse.base_url}/t/#{post.topic_id}/#{post.post_number}"
if !post.topic # 已删除主题中的帖子没有主题,会导致 PostRevisor 崩溃
post.topic = Topic.with_deleted.find_by(id: post.topic_id)
next if !post.topic
end
PostRevisor.new(post).revise!(system_user, raw: new_raw, **revision_options)
rescue => e
puts "cannot revise (number: #{count} #{Discourse.base_url}/t/#{post.topic_id}/#{post.post_number}): #{e}"
end
sleep 15
end
end
end