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([decode_to_string/1, is_bot_request/2, bot_handler/2]).
-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:bot(),
gleam@http@request:request(wisp:connection())
) -> boolean().
is_bot_request(Bot, Req) ->
case fun gleam@http@request:path_segments/1(Req) of
[Segment] ->
case telega:is_webhook_path(Bot, Segment) of
true ->
true;
false ->
false
end;
_ ->
false
end.
-spec is_secret_token_valid(
telega:bot(),
gleam@http@request:request(wisp:connection())
) -> boolean().
is_secret_token_valid(Bot, 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(Bot, Secret_header_value).
-spec bot_handler(telega:bot(), gleam@http@request:request(wisp:connection())) -> gleam@http@response:response(wisp:body()).
bot_handler(Bot, Req) ->
wisp:require_json(Req, fun(Json) -> case telega@message:decode(Json) of
{ok, Message} ->
gleam@bool:lazy_guard(
is_secret_token_valid(Bot, Req),
fun() -> {response, 401, [], empty} end,
fun() ->
telega@log:info(
<<"Received message "/utf8,
(gleam@string:inspect(Message))/binary>>
),
telega:handle_update(Bot, Message),
wisp:ok()
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:ok()
end end).