- Implement index action to list sitemaps - Create view for displaying sitemaps with details - Add helper method for generating sitemap URLs - Enhance error handling for S3 service errors This commit introduces a new feature for managing sitemaps in the application. It includes an index view that lists all available sitemaps with their last modified date and size, along with a link to view each sitemap. The error handling for S3 interactions has also been improved to log errors and return appropriate responses.
87 lines
2.2 KiB
Ruby
87 lines
2.2 KiB
Ruby
class SitemapsController < ApplicationController
|
|
include SitemapsHelper
|
|
before_action :set_bucket_name
|
|
|
|
def index
|
|
@sitemaps = list_sitemaps
|
|
respond_to do |format|
|
|
format.html
|
|
format.xml { render_sitemap_index }
|
|
end
|
|
rescue Aws::S3::Errors::ServiceError => e
|
|
Rails.logger.error "S3 Error: #{e.message}"
|
|
render status: :internal_server_error
|
|
end
|
|
def show
|
|
path = params[:path]
|
|
Rails.logger.info "Sitemap: #{path}"
|
|
|
|
begin
|
|
response = s3_client.get_object(
|
|
bucket: @bucket_name,
|
|
key: "sitemaps/#{path}"
|
|
)
|
|
|
|
expires_in 12.hours, public: true
|
|
content_type = response.content_type || "application/xml"
|
|
|
|
send_data(
|
|
response.body.read,
|
|
filename: path,
|
|
type: content_type,
|
|
disposition: "inline"
|
|
)
|
|
rescue Aws::S3::Errors::NoSuchKey
|
|
render status: :not_found
|
|
rescue Aws::S3::Errors::ServiceError => e
|
|
Rails.logger.error "S3 Error: #{e.message}"
|
|
render status: :internal_server_error
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def set_bucket_name
|
|
@bucket_name = Rails.env.production? ?
|
|
ENV.fetch("AWS_BUCKET", Rails.application.credentials.dig(:minio, :bucket)) :
|
|
ENV.fetch("AWS_DEV_BUCKET", Rails.application.credentials.dig(:minio_dev, :bucket))
|
|
end
|
|
|
|
def s3_client
|
|
@s3_client ||= Aws::S3::Client.new
|
|
end
|
|
|
|
def list_sitemaps
|
|
response = s3_client.list_objects_v2(
|
|
bucket: @bucket_name,
|
|
prefix: "sitemaps/"
|
|
)
|
|
|
|
response.contents.map do |object|
|
|
{
|
|
key: object.key.sub("sitemaps/", ""),
|
|
last_modified: object.last_modified,
|
|
size: object.size,
|
|
url: sitemap_url(object.key.sub("sitemaps/", ""))
|
|
}
|
|
end.reject { |obj| obj[:key].empty? }
|
|
end
|
|
|
|
def render_sitemap_index
|
|
base_url = "#{request.protocol}#{request.host_with_port}"
|
|
|
|
builder = Nokogiri::XML::Builder.new(encoding: "UTF-8") do |xml|
|
|
xml.sitemapindex(xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9") do
|
|
@sitemaps.each do |sitemap|
|
|
xml.sitemap do
|
|
xml.loc "#{base_url}/sitemaps/#{sitemap[:key]}"
|
|
xml.lastmod sitemap[:last_modified].iso8601
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
render xml: builder.to_xml
|
|
end
|
|
end
|