Module: Jekyll::WebmentionIO

Defined in:
lib/jekyll/tags/count.rb,
lib/jekyll/tags/likes.rb,
lib/jekyll/tags/links.rb,
lib/jekyll/tags/posts.rb,
lib/jekyll/tags/rsvps.rb,
lib/jekyll/tags/replies.rb,
lib/jekyll/tags/reposts.rb,
lib/jekyll/webmention_io.rb,
lib/jekyll/tags/bookmarks.rb,
lib/jekyll/tags/webmention.rb,
lib/jekyll/tags/webmentions.rb,
lib/jekyll/commands/webmention.rb,
lib/jekyll/tags/webmentions_js.rb,
lib/jekyll/tags/webmention_type.rb,
lib/jekyll/generators/compile_js.rb,
lib/jekyll/tags/webmentions_head.rb,
lib/jekyll/webmention_io/version.rb,
lib/jekyll/webmention_io/js_handler.rb,
lib/jekyll/generators/queue_webmentions.rb,
lib/jekyll/generators/gather_webmentions.rb,
lib/jekyll/webmention_io/webmention_item.rb

Defined Under Namespace

Modules: Commands, UriPolicy, UriState Classes: CompileJS, GatherWebmentions, JSHandler, JavaScriptFile, QueueWebmentions, WebmentionBookmarksTag, WebmentionCountTag, WebmentionHeadTag, WebmentionItem, WebmentionJSTag, WebmentionLikesTag, WebmentionLinksTag, WebmentionPostsTag, WebmentionRepliesTag, WebmentionRepostsTag, WebmentionRsvpsTag, WebmentionTag, WebmentionTypeTag, WebmentionsTag

Constant Summary collapse

EXCEPTIONS =
[
  SocketError, Timeout::Error,
  Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError,
  Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError,
  OpenSSL::SSL::SSLError,
].freeze
TIMEFRAMES =
{
  "last_week"  => "weekly",
  "last_month" => "monthly",
  "last_year"  => "yearly",
}.freeze
VERSION =
"4.0.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.api_suffix=(value) ⇒ Object (writeonly)

Sets the attribute api_suffix

Parameters:

  • value

    the value to set the attribute api_suffix to.



42
43
44
# File 'lib/jekyll/webmention_io.rb', line 42

def api_suffix=(value)
  @api_suffix = value
end

.cache_filesObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def cache_files
  @cache_files
end

.cache_folderObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def cache_folder
  @cache_folder
end

.configObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def config
  @config
end

.file_prefixObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def file_prefix
  @file_prefix
end

.jekyll_configObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def jekyll_config
  @jekyll_config
end

.js_handlerObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def js_handler
  @js_handler
end

.supported_templatesObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def supported_templates
  @supported_templates
end

.typesObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def types
  @types
end

.uri_blacklistObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def uri_blacklist
  @uri_blacklist
end

.uri_whitelistObject (readonly)

define simple getters and setters



39
40
41
# File 'lib/jekyll/webmention_io.rb', line 39

def uri_whitelist
  @uri_whitelist
end

Class Method Details

.api_path=(path) ⇒ Object

Setter



101
102
103
# File 'lib/jekyll/webmention_io.rb', line 101

def self.api_path=(path)
  @api_endpoint = "#{@api_url}/#{path}"
end

.bootstrap(site) ⇒ Object



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
# File 'lib/jekyll/webmention_io.rb', line 65

def self.bootstrap(site)
  @site = site
  @jekyll_config = site.config
  @config = @jekyll_config["webmentions"] || {}

  # Set up the cache folder & files
  @cache_folder = site.in_source_dir(@config["cache_folder"] || ".jekyll-cache")
  Dir.mkdir(@cache_folder) unless File.exist?(@cache_folder)
  @file_prefix = ""
  @file_prefix = "webmention_io_" unless @cache_folder.include? "webmention"
  @cache_files = {
    "incoming" => cache_file("received.yml"),
    "outgoing" => cache_file("outgoing.yml"),
    "bad_uris" => cache_file("bad_uris.yml"),
    "lookups"  => cache_file("lookups.yml")
  }
  @cache_files.each_value do |file|
    dump_yaml(file) unless File.exist?(file)
  end

  @js_handler = WebmentionIO::JSHandler.new(site)

  @uri_whitelist = @config
    .fetch("bad_uri_policy", {})
    .fetch("whitelist", [])
    .clone
    .insert(-1, "^https?://webmention.io/")
    .map { |expr| Regexp.new(expr) }

  @uri_blacklist = @config
    .fetch("bad_uri_policy", {})
    .fetch("blacklist", [])
    .map { |expr| Regexp.new(expr) }
end

.cache_file(filename) ⇒ Object

Helpers



106
107
108
# File 'lib/jekyll/webmention_io.rb', line 106

def self.cache_file(filename)
  Jekyll.sanitized_path(@cache_folder, "#{@file_prefix}#{filename}")
end

.cache_lookup_dates(lookups) ⇒ Object



175
176
177
178
179
180
# File 'lib/jekyll/webmention_io.rb', line 175

def self.cache_lookup_dates(lookups)
  cache_file = get_cache_file_path "lookups"
  dump_yaml(cache_file, lookups)

  log "msg", "Lookups have been cached."
end

.cache_webmentions(which, webmentions) ⇒ Object



125
126
127
128
129
130
131
132
# File 'lib/jekyll/webmention_io.rb', line 125

def self.cache_webmentions(which, webmentions)
  if %w(incoming outgoing).include? which
    cache_file = get_cache_file_path which
    dump_yaml(cache_file, webmentions)

    log "msg", "#{which.capitalize} webmentions have been cached."
  end
end

.dump_yaml(file, data = {}) ⇒ Object

Utility Method Caches given data to memory and then proceeds to write data as YAML string into file path.

Returns nothing.



361
362
363
364
# File 'lib/jekyll/webmention_io.rb', line 361

def self.dump_yaml(file, data = {})
  @webmention_data_cache[file] = data
  File.open(file, "wb") { |f| f.puts YAML.dump(data) }
end

.gather_documents(site) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/jekyll/webmention_io.rb', line 134

def self.gather_documents(site)
  documents = site.posts.docs.clone

  if @config.dig("pages") == true
    log "info", "Including site pages."
    documents.concat site.pages.clone
  end

  collections = @config.dig("collections")
  if collections
    log "info", "Adding collections."
    site.collections.each do |name, collection|
      # skip _posts
      next if name == "posts"

      unless collections.is_a?(Array) && !collections.include?(name)
        documents.concat collection.docs.clone
      end
    end
  end

  return documents
end

.get_cache_file_path(key) ⇒ Object



114
115
116
# File 'lib/jekyll/webmention_io.rb', line 114

def self.get_cache_file_path(key)
  @cache_files[key] || false
end

.get_date_from_string(text) ⇒ Object

supported: daily, weekly, monthly, yearly, every X days|weeks|months|years



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/jekyll/webmention_io.rb', line 217

def self.get_date_from_string(text)
  today = Date.today
  pattern = /every\s(?:(\d+)\s)?(day|week|month|year)s?/
  matches = text.match(pattern)
  unless matches
    text = if text == "daily"
             "every 1 day"
           else
             "every 1 #{text.sub("ly", "")}"
           end
    matches = text.match(pattern)
  end
  n = matches[1] ? matches[1].to_i : 1
  unit = matches[2]
  # weeks aren't natively supported in Ruby
  if unit == "week"
    n *= 7
    unit = "day"
  end
  # dynamic method call
  return today.send "prev_#{unit}", n
end

.get_response(api_params) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
# File 'lib/jekyll/webmention_io.rb', line 158

def self.get_response(api_params)
  api_params << @api_suffix
  url = URI::Parser.new.escape("#{@api_endpoint}?#{api_params}")
  log "info", "Sending request to #{url}."
  source = get_uri_source(url)
  if source
    JSON.parse(source)
  else
    {}
  end
end

.get_template_contents(template) ⇒ Object



298
299
300
301
302
303
304
# File 'lib/jekyll/webmention_io.rb', line 298

def self.get_template_contents(template)
  template_file = template_file(template)
  @template_content_cache[template_file] ||= begin
    log "info", "Template file: #{template_file}"
    File.read(template_file)
  end
end

.get_timeframe_from_date(time) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/jekyll/webmention_io.rb', line 203

def self.get_timeframe_from_date(time)
  date = time.to_date
  timeframe = nil
  TIMEFRAMES.each do |key, value|
    if date.to_date > get_date_from_string(value)
      timeframe = key
      break
    end
  end
  timeframe ||= "older"
  return timeframe
end

.get_uri_source(uri, redirect_limit = 10, original_uri = false) ⇒ Object

Connections



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/jekyll/webmention_io.rb', line 324

def self.get_uri_source(uri, redirect_limit = 10, original_uri = false)
  original_uri ||= uri
  return false unless uri_ok?(uri)

  if redirect_limit.positive?
    response = get_http_response(uri)
    case response
    when Net::HTTPSuccess then
      return response.body.force_encoding("UTF-8")
    when Net::HTTPRedirection then
      redirect_to = URI::Parser.new.parse(response["location"])
      redirect_to = redirect_to.relative? ? "#{original_uri.scheme}://#{original_uri.host}" + redirect_to.to_s : redirect_to.to_s
      return get_uri_source(redirect_to, redirect_limit - 1, original_uri)
    else
      update_uri_cache(uri, UriState::FAILURE)
      return false
    end
  else
    log("warn", "too many redirects for #{original_uri}") if original_uri
    update_uri_cache(uri, UriState::FAILURE)
    return false
  end
end

.get_webmention_endpoint(uri) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/jekyll/webmention_io.rb', line 240

def self.get_webmention_endpoint(uri)
  # log "info", "Looking for webmention endpoint at #{uri}"
  begin
    endpoint = IndieWeb::Endpoints.get(uri)[:webmention]
    unless endpoint
      log("info", "Could not find a webmention endpoint at #{uri}")
      update_uri_cache(uri, UriState::UNSUPPORTED)
    end
  rescue StandardError => e
    log "info", "Endpoint lookup failed for #{uri}: #{e.message}"
    update_uri_cache(uri, UriState::FAILURE)
    endpoint = false
  end
  endpoint
end

.html_templatesObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/jekyll/webmention_io.rb', line 306

def self.html_templates
  proofer = if @config['html_proofer'] == true
              ' data-proofer-ignore'
            else
              ''
            end
  @html_templates ||= begin
    templates = +"" # unfrozen String
    supported_templates.each do |template|
      templates << "<template style=\"display:none\" id=\"webmention-#{template}\"#{proofer}>"
      templates << get_template_contents(template)
      templates << "</template>"
    end
    templates
  end
end

.load_yaml(file) ⇒ Object

Utility Method Attempts to first load data cached in memory and then proceeds to safely parse given YAML file path and return data.

Returns empty hash if parsing fails to return data



371
372
373
# File 'lib/jekyll/webmention_io.rb', line 371

def self.load_yaml(file)
  @webmention_data_cache[file] || SafeYAML.load_file(file) || {}
end

.log(type, message) ⇒ Object



348
349
350
351
352
353
354
# File 'lib/jekyll/webmention_io.rb', line 348

def self.log(type, message)
  debug = !!@config.dig("debug")
  if debug || %w(error msg).include?(type)
    type = "info" if type == "msg"
    Jekyll.logger.method(type).call("#{@logger_prefix} #{message}")
  end
end

.max_attemptsObject



110
111
112
# File 'lib/jekyll/webmention_io.rb', line 110

def self.max_attempts()
  @config.dig("max_attempts")
end

.post_should_be_throttled?(post, item_date, last_lookup) ⇒ Boolean

allowed throttles: last_week, last_month, last_year, older allowed values: daily, weekly, monthly, yearly, every X days|weeks|months|years

Returns:

  • (Boolean)


184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/jekyll/webmention_io.rb', line 184

def self.post_should_be_throttled?(post, item_date, last_lookup)
  throttles = @config.dig("throttle_lookups")
  if throttles && item_date && last_lookup
    age = get_timeframe_from_date(item_date)
    throttle = throttles.dig(age)
    if throttle && last_lookup >= get_date_from_string(throttle)
      log "info", "Throttling #{post.data["title"]} (Only checking it #{throttle})"
      return true
    end
  end
  return false
end

.read_cached_webmentions(which) ⇒ Object



118
119
120
121
122
123
# File 'lib/jekyll/webmention_io.rb', line 118

def self.read_cached_webmentions(which)
  return {} unless %w(incoming outgoing).include?(which)

  cache_file = get_cache_file_path which
  load_yaml(cache_file)
end

.read_lookup_datesObject



170
171
172
173
# File 'lib/jekyll/webmention_io.rb', line 170

def self.read_lookup_dates
  cache_file = get_cache_file_path "lookups"
  load_yaml(cache_file)
end

.template_file(template) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
# File 'lib/jekyll/webmention_io.rb', line 286

def self.template_file(template)
  @template_file_cache[template] ||= begin
    configured_template = @config.dig("templates", template)
    if configured_template
      log "info", "Using custom #{template} template from site source"
      @site.in_source_dir configured_template
    else
      File.expand_path("templates/#{template}.html", __dir__)
    end
  end
end

.uri_ok?(uri) ⇒ Boolean

Check if we should attempt to send a webmention to the given URI based on the error handling policy and the last attempt.

Returns:

  • (Boolean)


498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/jekyll/webmention_io.rb', line 498

def self.uri_ok?(uri)
  uri = URI::Parser.new.parse(uri.to_s)
  now = Time.now.to_s
  uri_str = uri.to_s

  # If the URI is whitelisted, it's always ok!
  return true if @uri_whitelist.any? { |expr| expr.match uri_str }

  # If the URI is blacklisted, it's never ok!
  return false if @uri_blacklist.any? { |expr| expr.match uri_str }

  bad_uris = load_yaml(@cache_files["bad_uris"])
  entry = get_bad_uri_cache_entry(bad_uris, uri)

  # If the entry isn't in our cache yet, then it's ok.
  return true if entry.nil?

  # Okay, the last time we tried to send a webmention to this URI it
  # failed, so depending on what happened and the policy, we need to
  # decide what to do.
  #
  # First pull the retry policy given the type of the last error for the URI
  policy_entry = get_bad_uri_policy_entry(entry["state"])
  policy = policy_entry["policy"]

  if policy == UriPolicy::BAN
    return false
  elsif policy == UriPolicy::IGNORE
    return true
  elsif policy == UriPolicy::RETRY
    now = Time.now

    attempts = entry["attempts"]
    max_attempts = policy_entry["max_attempts"]

    if ! max_attempts.nil? and attempts >= max_attempts
      # If there's a retry limit and we've hit it, URI is not ok.
      log "msg", "Skipping #{uri}, attempted #{attempts} times and max is #{max_attempts}"

      return false
    end

    retry_delay = policy_entry["retry_delay"]

    # Sneaky trick.  By clamping to the array length, the last entry in
    # the retry_delay list is used for all remaining retries.
    delay = retry_delay[(attempts - 1).clamp(0, retry_delay.length - 1)]

    recheck_at = (entry["last_checked"] + delay * 3600)

    if recheck_at.to_r > now.to_r
      log "msg", "Skipping #{uri}, next attempt will happen after #{recheck_at}"

      return false
    end
  else
    log "error", "Invalid bad URI policy type: #{policy}"
  end

  return true
end

.webmention(source, target) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/jekyll/webmention_io.rb', line 256

def self.webmention(source, target)
  log "info", "Sending webmention of #{target} in #{source}"
  # return `curl -s -i -d \"source=#{source}&target=#{target}\" -o /dev/null #{endpoint}`
  response = Webmention.send_webmention(source, target)

  case response.code
  when 200, 201, 202
    log "info", "Webmention successful!"
    update_uri_cache(target, UriState::SUCCESS)
    response.body
  else
    log "info", response.inspect
    log "info", "Webmention failed, but will remain queued for next time"

    if response.body
      begin
        body = JSON.parse(response.body)

        if body.key? "error"
          log "msg", "Endpoint returned error: #{body['error']}"
        end
      rescue
      end
    end

    update_uri_cache(target, UriState::ERROR)
    false
  end
end