Skip to main content

src/gdav@discover_principal.erl

-module(gdav@discover_principal).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/gdav/discover_principal.gleam").
-export([request/0, request_at/1, build/2, response/1]).
-export_type([request_builder/0]).

-type request_builder() :: {request_builder, gleam@option:option(binary())}.

-file("src/gdav/discover_principal.gleam", 14).
-spec request() -> request_builder().
request() ->
    {request_builder, none}.

-file("src/gdav/discover_principal.gleam", 18).
-spec request_at(binary()) -> request_builder().
request_at(Path) ->
    {request_builder, {some, Path}}.

-file("src/gdav/discover_principal.gleam", 22).
-spec build(request_builder(), gdav:credentials()) -> gleam@http@request:request(binary()).
build(Builder, Credentials) ->
    Path = gleam@option:unwrap(
        erlang:element(2, Builder),
        erlang:element(5, Credentials)
    ),
    Headers = [{<<"Depth"/utf8>>, <<"0"/utf8>>},
        {<<"Content-Type"/utf8>>, <<"application/xml; charset=utf-8"/utf8>>}],
    Body = <<<<<<<<"<d:propfind xmlns:d=\"DAV:\">"/utf8, "<d:prop>"/utf8>>/binary,
                "<d:current-user-principal />"/utf8>>/binary,
            "</d:prop>"/utf8>>/binary,
        "</d:propfind>"/utf8>>,
    gdav@internal:request(
        Credentials,
        {other, <<"PROPFIND"/utf8>>},
        Path,
        Headers,
        Body
    ).

-file("src/gdav/discover_principal.gleam", 41).
-spec response(gleam@http@response:response(binary())) -> {ok, binary()} |
    {error, gdav:dav_error()}.
response(Res) ->
    case erlang:element(2, Res) of
        S when (S >= 200) andalso (S < 300) ->
            gdav@internal@xml:parse_single_value(
                erlang:element(4, Res),
                {name, <<"DAV:"/utf8>>, <<"current-user-principal"/utf8>>}
            );

        401 ->
            {error, authentication_failed};

        403 ->
            {error, authentication_failed};

        _ ->
            {error, {unexpected_response, Res}}
    end.