about summary refs log tree commit diff
path: root/app/controllers/api/subscriptions_controller.rb
blob: dd2f42aab7bdff474fc01eba594e34ca8f1de8c0 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

class Api::SubscriptionsController < ApiController
  before_action :set_account
  respond_to :txt

  def show
    if subscription.valid?(params['hub.topic'])
      @account.update(subscription_expires_at: future_expires)
      render plain: encoded_challenge, status: 200
    else
      head 404
    end
  end

  def update
    if subscription.verify(body, request.headers['HTTP_X_HUB_SIGNATURE'])
      ProcessingWorker.perform_async(@account.id, body.force_encoding('UTF-8'))
    end

    head 200
  end

  private

  def subscription
    @_subscription ||= @account.subscription(
      api_subscription_url(@account.id)
    )
  end

  def body
    @_body ||= request.body.read
  end

  def encoded_challenge
    HTMLEntities.new.encode(params['hub.challenge'])
  end

  def future_expires
    Time.now.utc + lease_seconds_or_default
  end

  def lease_seconds_or_default
    (params['hub.lease_seconds'] || 86_400).to_i.seconds
  end

  def set_account
    @account = Account.find(params[:id])
  end
end