89 lines
3.7 KiB
Erlang
89 lines
3.7 KiB
Erlang
-module(webfinger_handler).
|
|
-behaviour(cowboy_handler).
|
|
-export([init/2]).
|
|
|
|
-include("db_safe_insert.hrl").
|
|
|
|
init(Req, State) ->
|
|
Params = cowboy_req:parse_qs(Req),
|
|
Resource = proplists:get_value(<<"resource">>, Params),
|
|
case Resource of
|
|
undefined ->
|
|
reply_json(400, <<"Missing resource parameter">>, Req, State);
|
|
_ ->
|
|
case parse_acct(Resource) of
|
|
{ok, Username, Domain} ->
|
|
case user_db:get_user(Username) of
|
|
{ok, User} ->
|
|
%% Estrai i campi dal record
|
|
ProfileUrl = to_binary(User#ap_users.profile_url),
|
|
ActorUrl = to_binary(User#ap_users.actor_url),
|
|
AvatarUrl = to_binary(User#ap_users.avatar_url),
|
|
Subject = <<"acct:", Username/binary, "@", Domain/binary>>,
|
|
WebfingerMap = #{
|
|
<<"subject">> => Subject,
|
|
<<"aliases">> => [ProfileUrl, ActorUrl],
|
|
<<"links">> => [
|
|
#{
|
|
<<"rel">> => <<"self">>,
|
|
<<"type">> => <<"application/activity+json">>,
|
|
<<"href">> => ActorUrl
|
|
},
|
|
#{
|
|
<<"rel">> => <<"http://webfinger.net/rel/profile-page">>,
|
|
<<"type">> => <<"text/html">>,
|
|
<<"href">> => ProfileUrl
|
|
}
|
|
] ++
|
|
(case AvatarUrl of
|
|
<<>> -> [];
|
|
_ -> [
|
|
#{
|
|
<<"rel">> => <<"http://webfinger.net/rel/avatar">>,
|
|
<<"type">> => <<"image/jpeg">>,
|
|
<<"href">> => AvatarUrl
|
|
}
|
|
]
|
|
end)
|
|
},
|
|
Json = jsx:encode(WebfingerMap),
|
|
{ok, Resp} = cowboy_req:reply(
|
|
200,
|
|
#{<<"content-type">> => <<"application/jrd+json">>},
|
|
Json,
|
|
Req
|
|
),
|
|
{ok, Resp, State};
|
|
not_found ->
|
|
reply_json(404, <<"User not found">>, Req, State)
|
|
end;
|
|
error ->
|
|
reply_json(400, <<"Invalid resource format">>, Req, State)
|
|
end
|
|
end.
|
|
|
|
reply_json(Status, Msg, Req, State) ->
|
|
{ok, Resp} = cowboy_req:reply(
|
|
Status,
|
|
#{<<"content-type">> => <<"application/json">>},
|
|
jsx:encode(#{<<"error">> => Msg}),
|
|
Req
|
|
),
|
|
{ok, Resp, State}.
|
|
|
|
%% Utility per estrarre username e dominio da "acct:username@domain"
|
|
parse_acct(<<"acct:", Rest/binary>>) ->
|
|
case binary:split(Rest, <<"@">>) of
|
|
[Username, Domain] when Username =/= <<>>, Domain =/= <<>> ->
|
|
{ok, Username, Domain};
|
|
_ ->
|
|
error
|
|
end;
|
|
parse_acct(_) ->
|
|
error.
|
|
|
|
%% Utility per gestire stringhe/binary
|
|
to_binary(undefined) -> <<>>;
|
|
to_binary(Str) when is_list(Str) -> unicode:characters_to_binary(Str);
|
|
to_binary(Bin) when is_binary(Bin) -> Bin.
|