Class: SilkLayout::HTML::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/silk_layout/html/parser.rb

Class Method Summary collapse

Class Method Details

.base_uri_for(document, url) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/silk_layout/html/parser.rb', line 48

def self.base_uri_for(document, url)
  doc_uri = normalize_document_url(url)

  base_href = document.at_css("base[href]")&.[]("href")
  return doc_uri unless base_href

  normalize_href(base_href.to_s, doc_uri)
end

.default_workdir_uriObject



70
71
72
# File 'lib/silk_layout/html/parser.rb', line 70

def self.default_workdir_uri
  file_uri_for(Pathname.pwd)
end

.extract_stylesheets!(document, base_uri) ⇒ Object



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
# File 'lib/silk_layout/html/parser.rb', line 22

def self.extract_stylesheets!(document, base_uri)
  stylesheets = []
  cache = {}

  document.css("style, link").each do |node|
    if node.name == "style"
      stylesheets << node.content.to_s
      node.remove
      next
    end

    next unless node.name == "link"

    rel = node["rel"].to_s.downcase.split
    next unless rel.include?("stylesheet")

    href = node["href"].to_s.strip
    next if href.empty?

    stylesheets << fetch_stylesheet(href, base_uri, cache)
    node.remove
  end

  stylesheets
end

.fetch_http(uri) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/silk_layout/html/parser.rb', line 127

def self.fetch_http(uri)
  current = uri
  redirects = 0

  loop do
    http = Net::HTTP.new(current.host, current.port)
    http.use_ssl = (current.scheme == "https")
    http.open_timeout = 10
    http.read_timeout = 10

    request = Net::HTTP::Get.new(current)
    request["User-Agent"] = "SilkLayout/#{SilkLayout::VERSION}"

    response = http.request(request)

    case response
    when Net::HTTPSuccess
      return response.body.to_s
    when Net::HTTPRedirection
      location = response["location"].to_s
      raise "Missing redirect location for #{current}" if location.empty?

      redirects += 1
      raise "Too many redirects fetching #{uri}" if redirects > 5

      current = URI.join(current.to_s, location)
    else
      raise "Failed to fetch #{current} (HTTP #{response.code})"
    end
  end
end

.fetch_stylesheet(href, base_uri, cache) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/silk_layout/html/parser.rb', line 84

def self.fetch_stylesheet(href, base_uri, cache)
  resolved = normalize_href(href, base_uri)
  key = resolved.to_s
  return cache[key] if cache.key?(key)

  css =
    case resolved.scheme
    when "file", nil
      path = uri_unescape(resolved.path)
      raise "Stylesheet not found: #{path}" unless File.exist?(path)

      File.read(path)
    when "http", "https"
      fetch_http(resolved)
    else
      raise "Unsupported stylesheet scheme: #{resolved.scheme} (#{resolved})"
    end

  css = inline_css_imports(css, resolved, cache)
  cache[key] = css
end

.file_uri_for(path) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/silk_layout/html/parser.rb', line 74

def self.file_uri_for(path)
  p = path
  p = p.dirname if p.file?

  dir = p.to_s
  dir = "#{dir}/" unless dir.end_with?("/")

  URI::Generic.build(scheme: "file", path: URI::RFC2396_PARSER.escape(dir, /[^A-Za-z0-9\-._~\/]/))
end

.inline_css_imports(css, stylesheet_uri, cache) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/silk_layout/html/parser.rb', line 159

def self.inline_css_imports(css, stylesheet_uri, cache)
  return css unless css.include?("@import")

  base = stylesheet_base_uri(stylesheet_uri)
  remaining = css.dup
  inlined = +""
  seen = {}

  20.times do
    m = remaining.match(/@import\s+(?:url\()?
      \s*['"]?([^'")\s;]+)['"]?
      \s*\)?\s*;/ix)
    break unless m

    href = m[1]
    break if seen[href]

    seen[href] = true
    import_uri = normalize_href(href, base)
    imported = fetch_stylesheet(import_uri.to_s, base, cache)

    inlined << imported.to_s << "\n"
    remaining.sub!(m[0], "")
  end

  (inlined + remaining)
end

.normalize_document_url(url) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/silk_layout/html/parser.rb', line 57

def self.normalize_document_url(url)
  return default_workdir_uri unless url

  uri = URI.parse(url.to_s)
  return uri if uri.scheme

  path = Pathname.new(url.to_s).expand_path
  file_uri_for(path)
rescue URI::InvalidURIError
  path = Pathname.new(url.to_s).expand_path
  file_uri_for(path)
end

.normalize_href(href, base_uri) ⇒ Object



106
107
108
109
110
111
112
113
114
# File 'lib/silk_layout/html/parser.rb', line 106

def self.normalize_href(href, base_uri)
  href = href.to_s
  uri = URI.parse(href)
  return uri if uri.scheme

  URI.join(base_uri.to_s, href)
rescue URI::InvalidURIError
  URI.join(base_uri.to_s, URI::RFC2396_PARSER.escape(href))
end

.parse_document(html, url: nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/silk_layout/html/parser.rb', line 10

def self.parse_document(html, url: nil)
  document = Nokogiri::HTML(html)

  base_uri = base_uri_for(document, url)
  stylesheets = extract_stylesheets!(document, base_uri)

  root = Node.from_nokogiri(document.root)
  resolve_resource_urls!(root, base_uri)

  [root, stylesheets]
end

.resolve_resource_urls!(node, base_uri) ⇒ Object



116
117
118
119
120
121
122
123
124
125
# File 'lib/silk_layout/html/parser.rb', line 116

def self.resolve_resource_urls!(node, base_uri)
  return unless node

  if node.element? && node.tag == "img"
    src = node.attributes["src"].to_s.strip
    node.resolved_source_url = normalize_href(src, base_uri) unless src.empty?
  end

  node.children.each { |child| resolve_resource_urls!(child, base_uri) }
end

.stylesheet_base_uri(stylesheet_uri) ⇒ Object



187
188
189
190
191
192
193
194
195
# File 'lib/silk_layout/html/parser.rb', line 187

def self.stylesheet_base_uri(stylesheet_uri)
  if stylesheet_uri.scheme == "file"
    file_uri_for(Pathname.new(uri_unescape(stylesheet_uri.path)))
  else
    uri = stylesheet_uri.dup
    uri.path = uri.path.to_s.sub(/[^\/]+\z/, "")
    uri
  end
end

.uri_unescape(value) ⇒ Object



197
198
199
# File 'lib/silk_layout/html/parser.rb', line 197

def self.uri_unescape(value)
  URI::RFC2396_PARSER.unescape(value.to_s)
end