Links, mainly...
Some checks failed
/ Run system tests (push) Waiting to run
/ Build, push and deploy image (push) Blocked by required conditions
/ Run tests (push) Has been cancelled
/ Checkout (push) Successful in 8m9s

This commit is contained in:
david 2024-07-26 00:59:00 +02:00
parent fd42a3f173
commit 21ab02d647
69 changed files with 2258 additions and 155 deletions

51
app/models/link.rb Normal file
View file

@ -0,0 +1,51 @@
class Link < ApplicationRecord
belongs_to :link_category
has_rich_text :description_html
validates :url, :text, presence: true
validate :check_url
validate :valid_url
before_validation :ensure_absolute_url
def ok?
fail_count == 0
end
private
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"
def check_url(input = url, add_error = true)
response = begin
Net::HTTP.get_response(URI.parse(input), "User-Agent": USER_AGENT)
rescue Socket::ResolutionError
errors.add(:url, :invalid) if add_error
return false
end
case response
when Net::HTTPSuccess
self.last_check_at = Time.zone.now
self.fail_count = 0
true
when Net::HTTPRedirection
check_url(response[:location])
else
self.last_check_at = Time.zone.now
self.fail_count += 1
errors.add(:url, :invalid) if add_error
false
end
end
def ensure_absolute_url
self.url = "https://#{self.url}" unless self.url.match?(%r{https{0,1}://.*})
end
def valid_url
errors.add(:url, :invalid) unless url.match /\A#{URI::regexp(['http', 'https'])}\z/
end
end