diaspora_link_service.rb 1.31 KB
Newer Older
cmrd Senya's avatar
cmrd Senya committed
1 2 3 4 5 6 7 8 9 10 11 12
# frozen_string_literal: true

# Encapsulates logic of processing diaspora:// links
class DiasporaLinkService
  attr_reader :type, :author, :guid

  def initialize(link)
    @link = link.dup
    parse
  end

  def find_or_fetch_entity
13 14
    if type && guid
      entity_finder.find || fetch_entity
15 16
    elsif author
      find_or_fetch_person
17
    end
cmrd Senya's avatar
cmrd Senya committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
  end

  private

  attr_accessor :link

  def fetch_entity
    DiasporaFederation::Federation::Fetcher.fetch_public(author, type, guid)
    entity_finder.find
  rescue DiasporaFederation::Federation::Fetcher::NotFetchable
    nil
  end

  def entity_finder
    @entity_finder ||= Diaspora::EntityFinder.new(type, guid)
  end

35 36 37 38 39 40
  def find_or_fetch_person
    Person.find_or_fetch_by_identifier(author)
  rescue DiasporaFederation::Discovery::DiscoveryError
    nil
  end

cmrd Senya's avatar
cmrd Senya committed
41 42 43 44 45 46 47 48 49 50
  def normalize
    link.gsub!(%r{^web\+diaspora://}, "diaspora://") ||
      link.gsub!(%r{^//}, "diaspora://") ||
      %r{^diaspora://}.match(link) ||
      self.link = "diaspora://#{link}"
  end

  def parse
    normalize
    match = DiasporaFederation::Federation::DiasporaUrlParser::DIASPORA_URL_REGEX.match(link)
51 52
    if match
      @author, @type, @guid = match.captures
53 54
    else
      @author = %r{^diaspora://(#{Validation::Rule::DiasporaId::DIASPORA_ID_REGEX})$}u.match(link)&.captures&.first
55
    end
cmrd Senya's avatar
cmrd Senya committed
56 57
  end
end