Class: TopicEmbed

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Trashable
Defined in:
app/models/topic_embed.rb

Defined Under Namespace

Classes: FetchResponse

Class Method Summary collapse

Methods included from Trashable

#recover!, #trash!, #trashed?

Class Method Details

.absolutize_urls(url, contents) ⇒ Object

Convert any relative URLs to absolute. RSS is annoying for this.



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'app/models/topic_embed.rb', line 233

def self.absolutize_urls(url, contents)
  url = normalize_url(url)
  begin
    uri = URI(UrlHelper.normalized_encode(url))
  rescue URI::Error
    return contents
  end
  prefix = "#{uri.scheme}://#{uri.host}"
  prefix += ":#{uri.port}" if uri.port != 80 && uri.port != 443

  fragment = Nokogiri::HTML5.fragment("<div>#{contents}</div>")
  fragment
    .css("a")
    .each do |a|
      if a["href"].present?
        begin
          a["href"] = URI.join(prefix, a["href"]).to_s
        rescue URI::InvalidURIError
          # NOOP, URL is malformed
        end
      end
    end

  fragment
    .css("img")
    .each do |a|
      if a["src"].present?
        begin
          a["src"] = URI.join(prefix, a["src"]).to_s
        rescue URI::InvalidURIError
          # NOOP, URL is malformed
        end
      end
    end

  fragment.at("div").inner_html
end

.expanded_for(post) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
# File 'app/models/topic_embed.rb', line 299

def self.expanded_for(post)
  Discourse
    .cache
    .fetch("embed-topic:#{post.topic_id}", expires_in: 10.minutes) do
      url = TopicEmbed.where(topic_id: post.topic_id).pick(:embed_url)
      response = TopicEmbed.find_remote(url)

      body = response.body
      body << TopicEmbed.imported_from_html(url)
      body
    end
end

.find_remote(url) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'app/models/topic_embed.rb', line 120

def self.find_remote(url)
  url = UrlHelper.normalized_encode(url)
  URI.parse(url) # ensure url parses, will raise if not
  fd = FinalDestination.new(url, validate_uri: true, max_redirects: 5, follow_canonical: true)

  uri = fd.resolve
  return if uri.blank?

  begin
    html = uri.read
  rescue OpenURI::HTTPError, Net::OpenTimeout
    return
  end

  parse_html(html, uri.to_s)
end

.first_paragraph_from(html) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'app/models/topic_embed.rb', line 281

def self.first_paragraph_from(html)
  doc = Nokogiri.HTML5(html)

  result = +""
  doc
    .css("p")
    .each do |p|
      if p.text.present?
        result << p.to_s
        return result if result.size >= 100
      end
    end
  return result unless result.blank?

  # If there is no first paragraph, return the first div (onebox)
  doc.css("div").first.to_s
end

.import(user, url, title, contents, category_id: nil, cook_method: nil, tags: nil) ⇒ Object

Import an article from a source (RSS/Atom/Other)



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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'app/models/topic_embed.rb', line 43

def self.import(user, url, title, contents, category_id: nil, cook_method: nil, tags: nil)
  return unless url =~ %r{\Ahttps?\://}

  contents = first_paragraph_from(contents) if SiteSetting.embed_truncate && cook_method.nil?
  contents ||= ""
  contents = contents.dup << imported_from_html(url)

  url = normalize_url(url)

  embed = topic_embed_by_url(url)
  content_sha1 = Digest::SHA1.hexdigest(contents)
  post = nil

  # If there is no embed, create a topic, post and the embed.
  if embed.blank?
    Topic.transaction do
      eh = EmbeddableHost.record_for_url(url)

      cook_method ||=
        if SiteSetting.embed_support_markdown
          Post.cook_methods[:regular]
        else
          Post.cook_methods[:raw_html]
        end

      create_args = {
        title: title,
        raw: absolutize_urls(url, contents),
        skip_validations: true,
        cook_method: cook_method,
        category: category_id || eh.try(:category_id),
        tags: SiteSetting.tagging_enabled ? tags : nil,
      }
      create_args[:visible] = false if SiteSetting.embed_unlisted?

      creator = PostCreator.new(user, create_args)
      post = creator.create
      if post.present?
        TopicEmbed.create!(
          topic_id: post.topic_id,
          embed_url: url,
          content_sha1: content_sha1,
          post_id: post.id,
        )
      end
    end
  else
    absolutize_urls(url, contents)
    post = embed.post

    # Update the topic if it changed
    if post&.topic
      if post.user != user
        PostOwnerChanger.new(
          post_ids: [post.id],
          topic_id: post.topic_id,
          new_owner: user,
          acting_user: Discourse.system_user,
        ).change_owner!

        # make sure the post returned has the right author
        post.reload
      end

      if (content_sha1 != embed.content_sha1) || (title && title != post&.topic&.title)
        changes = { raw: absolutize_urls(url, contents) }
        changes[:title] = title if title.present?

        post.revise(user, changes, skip_validations: true, bypass_rate_limiter: true)
        embed.update!(content_sha1: content_sha1)
      end
    end
  end

  post
end

.import_remote(url, opts = nil) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
# File 'app/models/topic_embed.rb', line 219

def self.import_remote(url, opts = nil)
  opts = opts || {}
  response = find_remote(url)
  return if response.nil?

  response.title = opts[:title] if opts[:title].present?
  import_user = opts[:user] if opts[:user].present?
  import_user = response.author if response.author.present?
  url = normalize_url(response.url) if response.url.present?

  TopicEmbed.import(import_user, url, response.title, response.body)
end

.imported_from_html(url) ⇒ Object



35
36
37
38
39
40
# File 'app/models/topic_embed.rb', line 35

def self.imported_from_html(url)
  url = UrlHelper.normalized_encode(url)
  I18n.with_locale(SiteSetting.default_locale) do
    "\n<hr>\n<small>#{I18n.t("embed.imported_from", link: "<a href='#{url}'>#{url}</a>")}</small>\n"
  end
end

.normalize_url(url) ⇒ Object



27
28
29
30
31
32
33
# File 'app/models/topic_embed.rb', line 27

def self.normalize_url(url)
  # downcase
  # remove trailing forward slash/
  # remove consecutive hyphens
  # remove leading and trailing whitespace
  url.downcase.sub(%r{/\z}, "").sub(/\-+/, "-").strip
end

.parse_html(html, url) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/models/topic_embed.rb', line 137

def self.parse_html(html, url)
  require "ruby-readability"

  opts = {
    tags: %w[div p code pre h1 h2 h3 b em i strong a img ul li ol blockquote figure figcaption],
    attributes: %w[href src class],
    remove_empty_nodes: false,
  }

  opts[
    :whitelist
  ] = SiteSetting.allowed_embed_selectors if SiteSetting.allowed_embed_selectors.present?
  opts[
    :blacklist
  ] = SiteSetting.blocked_embed_selectors if SiteSetting.blocked_embed_selectors.present?
  allowed_embed_classnames =
    SiteSetting.allowed_embed_classnames if SiteSetting.allowed_embed_classnames.present?

  response = FetchResponse.new

  raw_doc = Nokogiri.HTML5(html)

  response.url = url

  auth_element =
    raw_doc.at('meta[@name="discourse-username"]') || raw_doc.at('meta[@name="author"]')
  if auth_element.present?
    response.author = User.where(username_lower: auth_element[:content].strip).first
  end

  read_doc = Readability::Document.new(html, opts)

  title = +(raw_doc.title || "")
  title.strip!

  if SiteSetting.embed_title_scrubber.present?
    title.sub!(Regexp.new(SiteSetting.embed_title_scrubber), "")
    title.strip!
  end
  response.title = title
  doc = Nokogiri.HTML5(read_doc.content)

  tags = { "img" => "src", "script" => "src", "a" => "href" }
  doc
    .search(tags.keys.join(","))
    .each do |node|
      url_param = tags[node.name]
      src = node[url_param]
      unless (src.nil? || src.empty?)
        begin
          # convert URL to absolute form
          node[url_param] = URI.join(url, UrlHelper.normalized_encode(src)).to_s
        rescue URI::Error, Addressable::URI::InvalidURIError
          # If there is a mistyped URL, just do nothing
        end
      end
      # only allow classes in the allowlist
      allowed_classes =
        if allowed_embed_classnames.blank?
          []
        else
          allowed_embed_classnames.split(/[ ,]+/i)
        end
      doc
        .search('[class]:not([class=""])')
        .each do |classnode|
          classes =
            classnode[:class]
              .split(" ")
              .select { |classname| allowed_classes.include?(classname) }
          if classes.length === 0
            classnode.delete("class")
          else
            classnode[:class] = classes.join(" ")
          end
        end
    end

  response.body = doc.at("body").children.to_html
  response
end

.topic_embed_by_url(embed_url) ⇒ Object



271
272
273
274
# File 'app/models/topic_embed.rb', line 271

def self.topic_embed_by_url(embed_url)
  embed_url = normalize_url(embed_url).sub(%r{\Ahttps?\://}, "")
  TopicEmbed.where("embed_url ~* ?", "^https?://#{Regexp.escape(embed_url)}$").first
end

.topic_id_for_embed(embed_url) ⇒ Object



276
277
278
279
# File 'app/models/topic_embed.rb', line 276

def self.topic_id_for_embed(embed_url)
  topic_embed = topic_embed_by_url(embed_url)
  topic_embed&.topic_id
end