2021-12-05 00:36:13 +01:00
|
|
|
defmodule Bump.Messages do
|
|
|
|
alias Bump.Repo
|
2021-12-10 12:46:34 +01:00
|
|
|
alias Bump.Messages.Message
|
2021-12-05 00:36:13 +01:00
|
|
|
import Ecto.Query
|
|
|
|
|
2021-12-10 15:34:38 +01:00
|
|
|
def pop(sender) do
|
2021-12-10 12:46:34 +01:00
|
|
|
query = from m in "messages",
|
|
|
|
where: m.sender == ^sender,
|
|
|
|
order_by: [desc: m.timestamp],
|
|
|
|
limit: 1,
|
2021-12-10 15:34:38 +01:00
|
|
|
select: %{id: m.id, data: m.data, timestamp: m.timestamp}
|
|
|
|
|
|
|
|
res = Repo.one(query)
|
|
|
|
|
|
|
|
if not is_nil(res) do
|
|
|
|
Repo.delete_all(from m in "messages", where: m.id == ^res.id)
|
|
|
|
%{data: res.data, timestamp: res.timestamp}
|
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
def peak(sender) do
|
|
|
|
query = from m in "messages",
|
|
|
|
where: m.sender == ^sender,
|
|
|
|
order_by: [desc: m.timestamp],
|
|
|
|
limit: 1,
|
|
|
|
select: %{data: m.data, timestamp: m.timestamp}
|
2021-12-10 12:46:34 +01:00
|
|
|
Repo.one(query)
|
2021-12-05 00:36:13 +01:00
|
|
|
end
|
|
|
|
|
2021-12-10 15:34:38 +01:00
|
|
|
def list(sender, minutes) do
|
2021-12-05 00:36:13 +01:00
|
|
|
|
|
|
|
ago = DateTime.utc_now
|
|
|
|
|> Timex.shift(minutes: -minutes)
|
|
|
|
|> DateTime.truncate(:second)
|
|
|
|
|
|
|
|
query = from m in "messages",
|
2021-12-10 15:34:38 +01:00
|
|
|
where: m.sender == ^sender and
|
|
|
|
m.timestamp >= ^ago,
|
|
|
|
select: %{data: m.data, timestamp: m.timestamp}
|
|
|
|
|
2021-12-05 00:36:13 +01:00
|
|
|
Repo.all(query)
|
|
|
|
end
|
|
|
|
|
2021-12-10 15:34:38 +01:00
|
|
|
def clear(sender) do
|
2021-12-10 12:46:34 +01:00
|
|
|
query = from m in "messages",
|
2021-12-10 15:34:38 +01:00
|
|
|
where: m.sender == ^sender
|
|
|
|
|
2021-12-10 12:46:34 +01:00
|
|
|
Repo.delete_all(query)
|
2021-12-05 00:36:13 +01:00
|
|
|
end
|
|
|
|
|
2021-12-10 15:34:38 +01:00
|
|
|
def push(sender, message) do
|
|
|
|
time = DateTime.utc_now |> DateTime.truncate(:second)
|
2021-12-10 12:46:34 +01:00
|
|
|
|
|
|
|
Repo.insert(%Message{sender: sender, data: message, timestamp: time})
|
|
|
|
|
2021-12-05 00:36:13 +01:00
|
|
|
end
|
|
|
|
|
2021-12-10 12:46:34 +01:00
|
|
|
|
2021-12-05 00:36:13 +01:00
|
|
|
end
|