about summary refs log tree commit diff
path: root/app/lib/permalink_redirector.rb
blob: cf1a37625105e3abfe0347b0fb910b4f1533fa21 (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
# frozen_string_literal: true

class PermalinkRedirector
  include RoutingHelper

  def initialize(path)
    @path = path
  end

  def redirect_path
    if path_segments[0].present? && path_segments[0].start_with?('@') && path_segments[1] =~ /\d/
      find_status_url_by_id(path_segments[1])
    elsif path_segments[0].present? && path_segments[0].start_with?('@')
      find_account_url_by_name(path_segments[0])
    elsif path_segments[0] == 'statuses' && path_segments[1] =~ /\d/
      find_status_url_by_id(path_segments[1])
    elsif path_segments[0] == 'accounts' && path_segments[1] =~ /\d/
      find_account_url_by_id(path_segments[1])
    end
  end

  private

  def path_segments
    @path_segments ||= @path.gsub(/\A\//, '').split('/')
  end

  def find_status_url_by_id(id)
    status = Status.find_by(id: id)
    ActivityPub::TagManager.instance.url_for(status) if status&.distributable? && !status.account.local?
  end

  def find_account_url_by_id(id)
    account = Account.find_by(id: id)
    ActivityPub::TagManager.instance.url_for(account) if account.present? && !account.local?
  end

  def find_account_url_by_name(name)
    username, domain = name.gsub(/\A@/, '').split('@')
    domain           = nil if TagManager.instance.local_domain?(domain)
    account          = Account.find_remote(username, domain)

    ActivityPub::TagManager.instance.url_for(account) if account.present? && !account.local?
  end
end