discourse/app/models/permalink.rb

112 lines
2.4 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
class Permalink < ActiveRecord::Base
belongs_to :topic
belongs_to :post
belongs_to :category
2020-05-25 04:48:54 -05:00
belongs_to :tag
2024-02-05 10:31:31 -06:00
belongs_to :user
before_validation :normalize_url
validates :url, uniqueness: true
class Normalizer
attr_reader :source
def initialize(source)
@source = source
@rules = source.split("|").map { |rule| parse_rule(rule) }.compact if source.present?
end
def parse_rule(rule)
return unless rule =~ %r{/.*/}
escaping = false
regex = +""
sub = +""
c = 0
rule.chars.each do |l|
c += 1 if !escaping && l == "/"
escaping = l == "\\"
if c > 1
sub << l
else
regex << l
end
end
[Regexp.new(regex[1..-1]), sub[1..-1] || ""] if regex.length > 1
end
def normalize(url)
return url unless @rules
@rules.each { |(regex, sub)| url = url.sub(regex, sub) }
url
end
end
def self.normalize_url(url)
if url
url = url.strip
url = url[1..-1] if url[0, 1] == "/"
end
2017-07-27 20:20:09 -05:00
normalizations = SiteSetting.permalink_normalizations
@normalizer = Normalizer.new(normalizations) unless @normalizer &&
@normalizer.source == normalizations
@normalizer.normalize(url)
end
def self.find_by_url(url)
find_by(url: normalize_url(url))
end
def normalize_url
self.url = Permalink.normalize_url(url) if url
end
def target_url
return external_url if external_url
return "#{Discourse.base_path}#{post.url}" if post
return topic.relative_url if topic
return category.url if category
2020-05-25 04:48:54 -05:00
return tag.full_url if tag
2024-02-05 10:31:31 -06:00
return user.full_url if user
nil
end
2017-07-27 20:20:09 -05:00
def self.filter_by(url = nil)
permalinks =
2024-02-05 10:31:31 -06:00
Permalink.includes(:topic, :post, :category, :tag, :user).order("permalinks.created_at desc")
permalinks.where!("url ILIKE :url OR external_url ILIKE :url", url: "%#{url}%") if url.present?
permalinks.limit!(100)
permalinks.to_a
end
end
# == Schema Information
#
# Table name: permalinks
#
# id :integer not null, primary key
# url :string(1000) not null
# topic_id :integer
# post_id :integer
# category_id :integer
2019-01-11 13:29:56 -06:00
# created_at :datetime not null
# updated_at :datetime not null
# external_url :string(1000)
2020-05-25 04:48:54 -05:00
# tag_id :integer
2024-02-05 10:31:31 -06:00
# user_id :integer
#
# Indexes
#
# index_permalinks_on_url (url) UNIQUE
#