2021-07-10 21:16:00 +00:00
|
|
|
defmodule MatrixServer.RoomServer do
|
|
|
|
use GenServer
|
|
|
|
|
2021-07-23 19:00:01 +00:00
|
|
|
alias MatrixServer.{Repo, Room, Event, Account}
|
2021-07-10 21:16:00 +00:00
|
|
|
alias MatrixServerWeb.API.CreateRoom
|
|
|
|
|
2021-07-23 19:00:01 +00:00
|
|
|
@registry MatrixServer.RoomServer.Registry
|
|
|
|
@supervisor MatrixServer.RoomServer.Supervisor
|
|
|
|
|
|
|
|
def start_link(opts) do
|
|
|
|
{name, opts} = Keyword.pop(opts, :name)
|
|
|
|
GenServer.start_link(__MODULE__, opts, name: name)
|
2021-07-10 21:16:00 +00:00
|
|
|
end
|
|
|
|
|
2021-07-23 19:00:01 +00:00
|
|
|
def create_room(input, account) do
|
2021-07-23 22:13:12 +00:00
|
|
|
%Room{id: room_id} = room = Repo.insert!(Room.create_changeset(input))
|
2021-07-23 19:00:01 +00:00
|
|
|
|
2021-07-23 22:13:12 +00:00
|
|
|
opts = [
|
|
|
|
name: {:via, Registry, {@registry, room_id}},
|
|
|
|
input: input,
|
|
|
|
account: account,
|
|
|
|
room: room
|
|
|
|
]
|
|
|
|
|
|
|
|
DynamicSupervisor.start_child(@supervisor, {__MODULE__, opts})
|
2021-07-10 21:16:00 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
2021-07-23 19:00:01 +00:00
|
|
|
def init(opts) do
|
|
|
|
%Room{id: room_id} = Keyword.fetch!(opts, :room)
|
|
|
|
input = Keyword.fetch!(opts, :input)
|
|
|
|
account = Keyword.fetch!(opts, :account)
|
|
|
|
|
|
|
|
Repo.transaction(fn ->
|
2021-07-23 22:13:12 +00:00
|
|
|
with {:ok, state_set} <- insert_create_room_event(account, input, room_id) do
|
|
|
|
{:ok, %{room_id: room_id, state_set: state_set}}
|
2021-07-23 19:00:01 +00:00
|
|
|
end
|
|
|
|
end)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp insert_create_room_event(
|
|
|
|
%Account{localpart: localpart},
|
|
|
|
%CreateRoom{room_version: room_version},
|
2021-07-23 22:13:12 +00:00
|
|
|
room_id
|
2021-07-23 19:00:01 +00:00
|
|
|
) do
|
2021-07-23 22:13:12 +00:00
|
|
|
state_set =
|
|
|
|
Event.create_room(room_id, MatrixServer.get_mxid(localpart), room_version)
|
|
|
|
|> Repo.insert!()
|
|
|
|
|> MatrixServer.StateResolution.resolve(true)
|
|
|
|
|
|
|
|
{:ok, state_set}
|
2021-07-10 21:16:00 +00:00
|
|
|
end
|
|
|
|
end
|