mirror of
https://0xacab.org/sutty/sutty
synced 2024-11-24 12:56:21 +00:00
93 lines
2.2 KiB
Ruby
93 lines
2.2 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
# Se encarga del contenido del artículo y quizás otros campos que
|
|
# requieran texto largo.
|
|
class MetadataContent < MetadataTemplate
|
|
include Metadata::ContentConcern
|
|
include Metatada::IndexableConcern
|
|
|
|
# @return [String]
|
|
def default_value
|
|
super || ''
|
|
end
|
|
|
|
# @return [String]
|
|
def value
|
|
self[:value] || legacy_content || default_value
|
|
end
|
|
|
|
# Trae el contenido desde el Post
|
|
#
|
|
# @return [String]
|
|
def document_value
|
|
document.content
|
|
end
|
|
|
|
# Eliminar HTML
|
|
#
|
|
# @return [String]
|
|
def to_s
|
|
sanitizer.sanitize value, tags: [], attributes: []
|
|
end
|
|
|
|
private
|
|
|
|
# Detectar si el contenido estaba en Markdown y pasarlo a HTML
|
|
#
|
|
# @return [String,nil]
|
|
def legacy_content
|
|
return unless document_value
|
|
return document_value if /^\s*</ =~ document_value
|
|
|
|
CommonMarker.render_doc(document_value, %i[FOOTNOTES UNSAFE], %i[table strikethrough autolink]).to_html
|
|
end
|
|
|
|
# Limpiar el HTML que recibimos
|
|
#
|
|
# TODO: En lugar de comprobar el Content Type acá, restringir los
|
|
# tipos de archivo a aceptar en ActiveStorage.
|
|
def sanitize(html_string)
|
|
html = Nokogiri::HTML.fragment(super html_string)
|
|
elements = 'img,audio,video,iframe'
|
|
|
|
# Eliminar elementos sin src y comprobar su origen
|
|
html.css(elements).each do |element|
|
|
unless element['src']
|
|
element.remove
|
|
next
|
|
end
|
|
|
|
begin
|
|
uri = URI element['src']
|
|
|
|
# No permitimos recursos externos
|
|
element.remove unless uri.scheme == 'https' && uri.hostname.end_with?(Site.domain)
|
|
rescue URI::Error
|
|
element.remove
|
|
end
|
|
end
|
|
|
|
# Eliminar figure sin contenido
|
|
html.css('figure').each do |figure|
|
|
figure.remove if figure.css(elements).empty?
|
|
end
|
|
|
|
# Los videos y audios necesitan controles
|
|
html.css('audio,video').each do |resource|
|
|
resource['controls'] = true
|
|
end
|
|
|
|
# Elimina los estilos salvo los que asigne el editor
|
|
html.css('*').each do |element|
|
|
next if elements_with_style.include? element.name.downcase
|
|
|
|
element.remove_attribute('style')
|
|
end
|
|
|
|
html.to_s.html_safe
|
|
end
|
|
|
|
def elements_with_style
|
|
@elements_with_style ||= %w[div mark].freeze
|
|
end
|
|
end
|