class WebfingerController < ApplicationController
  before_action :allow_cross_origin_requests, only: [:show]

  layout false

  def show
    resource = params[:resource]

    if resource && @useraddress = resource.match(/acct:(.+)/)&.[](1)
      @username, @domain = @useraddress.split("@")

      unless Rails.env.development?
        # Allow different domains (e.g. localhost:3000) in development only
        head 404 and return unless @domain == Setting.primary_domain
      end

      unless @user = User.where(ou: Setting.primary_domain)
                         .find_by(cn: @username.downcase)
        head 404 and return
      end

      render json: webfinger.to_json,
             content_type: "application/jrd+json"
    else
      head 422 and return
    end
  end

  private

  def webfinger
    jrd = {
      subject: "acct:#{@user.address}",
      aliases: [],
      links: []
    }

    if Setting.mastodon_enabled && @user.service_enabled?(:mastodon)
      # https://docs.joinmastodon.org/spec/webfinger/
      jrd[:aliases] += mastodon_aliases
      jrd[:links] += mastodon_links
    end

    if Setting.remotestorage_enabled && @user.service_enabled?(:remotestorage)
      # https://datatracker.ietf.org/doc/draft-dejong-remotestorage/
      jrd[:links] << remotestorage_link
    end

    jrd
  end

  def mastodon_aliases
    [
      "#{Setting.mastodon_public_url}/@#{@user.cn}",
      "#{Setting.mastodon_public_url}/users/#{@user.cn}"
    ]
  end

  def mastodon_links
    [
      {
        rel: "http://webfinger.net/rel/profile-page",
        type: "text/html",
        href: "#{Setting.mastodon_public_url}/@#{@user.cn}"
      },
      {
        rel: "self",
        type: "application/activity+json",
        href: "#{Setting.mastodon_public_url}/users/#{@user.cn}"
      },
      {
        rel: "http://ostatus.org/schema/1.0/subscribe",
        template: "#{Setting.mastodon_public_url}/authorize_interaction?uri={uri}"
      }
    ]
  end

  def remotestorage_link
    auth_url = new_rs_oauth_url(@username)
    storage_url = "#{Setting.rs_storage_url}/#{@username}"

    {
      rel: "http://tools.ietf.org/id/draft-dejong-remotestorage",
      href: storage_url,
      properties: {
        "http://remotestorage.io/spec/version" => "draft-dejong-remotestorage-13",
        "http://tools.ietf.org/html/rfc6749#section-4.2" => auth_url,
        "http://tools.ietf.org/html/rfc6750#section-2.3" => nil, # access token via a HTTP query parameter
        "http://tools.ietf.org/html/rfc7233": "GET", # content range requests
        "http://remotestorage.io/spec/web-authoring": nil
      }
    }
  end

  def allow_cross_origin_requests
    return unless Rails.env.development?
    headers['Access-Control-Allow-Origin'] = "*"
    headers['Access-Control-Allow-Methods'] = "GET"
  end
end
