Current section
Files
Jump to
Current section
Files
src/telega@adapters@wisp.erl
-module(telega@adapters@wisp).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([handle_bot/3]).
-spec decode_to_string(gleam@dynamic:decode_error()) -> binary().
decode_to_string(Error) ->
{decode_error, Expected, Found, Path} = Error,
Path_string = gleam@string:join(Path, <<"."/utf8>>),
<<<<<<<<<<"Expected "/utf8, Expected/binary>>/binary, ", found "/utf8>>/binary,
Found/binary>>/binary,
" at "/utf8>>/binary,
Path_string/binary>>.
-spec is_bot_request(
telega:telega(any()),
gleam@http@request:request(wisp:connection())
) -> boolean().
is_bot_request(Telega, Req) ->
case fun gleam@http@request:path_segments/1(Req) of
[Segment] ->
case telega:is_webhook_path(Telega, Segment) of
true ->
true;
false ->
false
end;
_ ->
false
end.
-spec is_secret_token_valid(
telega:telega(any()),
gleam@http@request:request(wisp:connection())
) -> boolean().
is_secret_token_valid(Telega, Req) ->
Secret_header_value = begin
_pipe = gleam@http@request:get_header(
Req,
<<"x-relegram-bot-api-secret-token"/utf8>>
),
gleam@result:unwrap(_pipe, <<""/utf8>>)
end,
telega:is_secret_token_valid(Telega, Secret_header_value).
-spec handle_bot(
gleam@http@request:request(wisp:connection()),
telega:telega(any()),
fun(() -> gleam@http@response:response(wisp:body()))
) -> gleam@http@response:response(wisp:body()).
handle_bot(Req, Telega, Handler) ->
telega@log:info(<<"Received request from Telegram API"/utf8>>),
gleam@bool:lazy_guard(
not is_bot_request(Telega, Req),
fun() -> Handler() end,
fun() ->
wisp:require_json(
Req,
fun(Json) -> case telega@message:decode(Json) of
{ok, Message} ->
gleam@bool:lazy_guard(
is_secret_token_valid(Telega, Req),
fun() -> {response, 401, [], empty} end,
fun() ->
case telega:handle_update(Telega, Message) of
{ok, _} ->
wisp:ok();
{error, Error} ->
telega@log:error(
<<"Failed to handle message: "/utf8,
Error/binary>>
),
wisp:internal_server_error()
end
end
);
{error, Errors} ->
Error_message = begin
_pipe = Errors,
_pipe@1 = gleam@list:map(
_pipe,
fun decode_to_string/1
),
gleam@string:join(_pipe@1, <<"\n"/utf8>>)
end,
telega@log:error(
<<"Failed to decode message:\n"/utf8,
Error_message/binary>>
),
wisp:internal_server_error()
end end
)
end
).