This repository has been archived by the owner on Jun 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
utils.ex
83 lines (72 loc) · 1.93 KB
/
utils.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
defmodule Helix.Event.Loggable.Utils do
@moduledoc """
Utils for the Loggable protocol and underlying implementations.
"""
import HELL.Macros
alias HELL.IPv4
alias Helix.Network.Model.Network
alias Helix.Server.Model.Server
alias Helix.Server.Query.Server, as: ServerQuery
alias Helix.Software.Model.File
@type log_file_name :: String.t
@type unknown_ip :: String.t
@unknown_ip "Unknown"
def format_ip(ip),
do: "[" <> ip <> "]"
@spec censor_ip(IPv4.t | unknown_ip) ::
censored_ip :: IPv4.t | unknown_ip
@doc """
Replaces the last 5 numbers of the IP address with an 'x'.
### Examples:
"123.123.123.123" => "123.123.1xx.xxx"
"123.123.12.12" => "123.12x.xx.xx"
"1.2.3.4" => "x.x.x.x"
"""
def censor_ip(ip) do
ip
|> String.to_charlist()
|> Enum.reverse()
|> Enum.reduce({[], 0}, fn char, {output, num_replaces} ->
if char_is_number?(char) and num_replaces < 5 do
{output ++ 'x', num_replaces + 1}
else
{output ++ [char], num_replaces}
end
end)
|> elem(0)
|> Enum.reverse
|> List.to_string()
end
@spec get_ip(Server.id, Network.id) ::
IPv4.t
| unknown_ip :: String.t
@doc """
Log-focused method to fetch a server IP address. Returns an empty string if
the IP was not found.
"""
def get_ip(server_id, network_id) do
case ServerQuery.get_ip(server_id, network_id) do
ip when is_binary(ip) ->
ip
nil ->
@unknown_ip
end
|> format_ip()
end
@doc """
Log-focused method to figure out the file name that should be logged.
"""
@spec get_file_name(File.t) ::
log_file_name
def get_file_name(file = %File{}) do
file.full_path
|> String.split("/")
|> List.last()
end
docp """
Helper to verify whether the ASCII char is a number.
"""
defp char_is_number?(char),
# do: char in [48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
do: char >= 48 and char <= 57
end