A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
%% SPDX-License-Identifier: AGPL-3.0-or-later
-module(custom_status_expiry).
-typing([eqwalizer]).
-export([
clear_if_expired/1,
clear_if_expired/2,
remaining_ms/2,
next_wakeup_ms/1,
reconcile_message/0
]).
-export_type([custom_status/0, wakeup/0, offset/0]).
-type custom_status() :: map() | null.
-type wakeup() :: {ok, pos_integer()} | none.
-type offset() :: {ok, integer()} | none.
-define(MAX_TIMER_MS, 86400000).
-define(WAKEUP_JITTER_MS, 5000).
-spec clear_if_expired(term()) -> custom_status().
clear_if_expired(CustomStatus) ->
clear_if_expired(CustomStatus, erlang:system_time(millisecond)).
-spec clear_if_expired(term(), term()) -> custom_status().
clear_if_expired(CustomStatus, NowMs) when is_map(CustomStatus), is_integer(NowMs) ->
keep_or_clear(expired(CustomStatus, NowMs), CustomStatus);
clear_if_expired(CustomStatus, _NowMs) when is_map(CustomStatus) ->
CustomStatus;
clear_if_expired(_CustomStatus, _NowMs) ->
null.
-spec keep_or_clear(boolean(), map()) -> custom_status().
keep_or_clear(true, _CustomStatus) -> null;
keep_or_clear(false, CustomStatus) -> CustomStatus.
-spec expired(map(), integer()) -> boolean().
expired(CustomStatus, NowMs) ->
case remaining_ms(CustomStatus, NowMs) of
{ok, RemainingMs} -> RemainingMs =< 0;
none -> false
end.
-spec remaining_ms(term(), term()) -> offset().
remaining_ms(CustomStatus, NowMs) when is_map(CustomStatus), is_integer(NowMs) ->
offset_from(expires_at_ms(maps:get(<<"expires_at">>, CustomStatus, undefined)), NowMs);
remaining_ms(_CustomStatus, _NowMs) ->
none.
-spec offset_from(offset(), integer()) -> offset().
offset_from({ok, ExpiryMs}, NowMs) -> {ok, ExpiryMs - NowMs};
offset_from(none, _NowMs) -> none.
-spec expires_at_ms(term()) -> offset().
expires_at_ms(Value) when is_binary(Value) ->
parse_rfc3339(binary_to_list(Value));
expires_at_ms(Value) when is_list(Value) ->
parse_rfc3339(Value);
expires_at_ms(_Value) ->
none.
-spec parse_rfc3339(term()) -> offset().
parse_rfc3339(Chars) ->
try calendar:rfc3339_to_system_time(eqwalizer:dynamic_cast(Chars), [{unit, millisecond}]) of
Ms -> {ok, Ms}
catch
_Class:_Reason -> none
end.
-spec next_wakeup_ms(term()) -> wakeup().
next_wakeup_ms(CustomStatus) ->
wakeup_delay(remaining_ms(CustomStatus, erlang:system_time(millisecond))).
-spec wakeup_delay(offset()) -> wakeup().
wakeup_delay(none) ->
none;
wakeup_delay({ok, RemainingMs}) when RemainingMs =< 0 ->
none;
wakeup_delay({ok, RemainingMs}) when RemainingMs > ?MAX_TIMER_MS ->
{ok, jittered(?MAX_TIMER_MS)};
wakeup_delay({ok, RemainingMs}) ->
{ok, jittered(RemainingMs)}.
-spec jittered(pos_integer()) -> pos_integer().
jittered(DelayMs) ->
DelayMs + rand:uniform(?WAKEUP_JITTER_MS).
-spec reconcile_message() -> {'$gen_cast', reconcile_flattened_presence}.
reconcile_message() ->
{'$gen_cast', reconcile_flattened_presence}.