-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
normalize_urls.rb
79 lines (65 loc) · 1.84 KB
/
normalize_urls.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# frozen_string_literal: true
module Docs
class NormalizeUrlsFilter < Filter
ATTRIBUTES = { a: 'href', img: 'src', iframe: 'src' }
def call
ATTRIBUTES.each_pair do |tag, attribute|
update_attribute(tag, attribute)
end
doc
end
def update_attribute(tag, attribute)
css(tag.to_s).each do |node|
next unless value = node[attribute]
next if fragment_url_string?(value) || data_url_string?(value)
node[attribute] = normalize_url(value) || (tag == :iframe ? value : '#')
end
end
def normalize_url(str)
str.strip!
str.gsub!(' ', '%20')
str = context[:fix_urls_before_parse].call(str) if context[:fix_urls_before_parse]
url = to_absolute_url(str)
while new_url = fix_url(url)
url = new_url
end
url.to_s
rescue URI::InvalidURIError
nil
end
def to_absolute_url(str)
url = URL.parse(str)
url.relative? ? current_url.join(url) : url
end
def fix_url(url)
if context[:redirections]
url = URL.parse(url)
path = url.path.downcase
if context[:redirections].key?(path)
url.path = context[:redirections][path]
return url
end
end
if context[:replace_paths]
url = URL.parse(url)
path = subpath_to(url)
if context[:replace_paths].key?(path)
url.path = url.path.sub %r[#{path}\z], context[:replace_paths][path]
return url
end
end
if context[:replace_urls]
url = url.to_s
if context[:replace_urls].key?(url)
return context[:replace_urls][url]
end
end
if context[:fix_urls]
url = url.to_s
orig_url = url.dup
new_url = context[:fix_urls].call(url)
return new_url if new_url != orig_url
end
end
end
end