Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

don't crash when discord leaks a struct #512

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions lib/nostrum/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,26 @@ defmodule Nostrum.Util do
"""
@spec safe_atom_map(map) :: map
def safe_atom_map(term) do
cond do
is_map(term) ->
case term do
# to handle the rare occasion that discord leaks a `:__struct__` key
# rather than outright crashing, we'll just log a warning and continue
%{__struct__: struct_name} ->
Logger.warning(
"Discord's gateway leaked a struct with name #{inspect(struct_name)}, please report this to the library maintainer"
)

term = Map.from_struct(term)
for {key, value} <- term, into: %{}, do: {maybe_to_atom(key), safe_atom_map(value)}

is_list(term) ->
# if we have a regular map
%{} ->
for {key, value} <- term, into: %{}, do: {maybe_to_atom(key), safe_atom_map(value)}

# if we have a non-empty list
[_ | _] ->
Enum.map(term, fn item -> safe_atom_map(item) end)

true ->
_ ->
term
end
end
Expand Down