about summary refs log tree commit diff stats
path: root/app/controllers/webmentions_controller.rb
blob: d8aefc77cce3f59cbec381fa56ca315efb795399 (plain) (blame)
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
require 'microformats'
require 'webmention'

class WebmentionsController < ApplicationController
  skip_before_action :verify_authenticity_token

  def create
    source = params[:source]
    target = params[:target]

    verification = Webmention.verify_webmention(source, target)
    unless verification.verified?
      render json: { error: "Webmention could not be verified." }
      return
    end

    target_parts = URI.parse(target).path.split("/").drop(1)

    if target_parts[0] == "blog"
      blog = Blog.find_by_slug(target_parts[1])

      raise ActiveRecord::RecordNotFound unless blog
      raise ActiveRecord::RecordNotFound unless blog.published

      response = Webmention::Request.get(source)
      parsed = Microformats.parse(response.body.to_s)

      if parsed.entry.properties.to_hash.include?("like-of") and parsed.entry.like_of(:all).map(&:to_s).include? target
        blog.like!(parsed.entry.author.url, parsed.entry.author.name)
      end
    end

    head :ok
  end
  
end