This commit is contained in:
Chris McCord 2021-11-15 12:42:12 -05:00
parent 458900b522
commit 8f63fa842b
3 changed files with 53 additions and 3 deletions

View file

@ -1,6 +1,14 @@
# LiveBeats
To start your Phoenix server:
Play music together with Phoenix LiveView!
Visit [todo]() to try it out, or run locally:
* Create a [Github OAuth app](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app)
* Export your GitHub client ID and secret:
export LIVE_BEATS_GITHUB_CLIENT_ID="..."
export LIVE_BEATS_GITHUB_CLIENT_SECRET="..."
* Install dependencies with `mix deps.get`
* Create and migrate your database with `mix ecto.setup`

View file

@ -1,6 +1,36 @@
defmodule LiveBeats do
@moduledoc """
The main interface for shared functionality.
"""
require Logger
@doc """
Attaches a modules to another for listening of events.
Events are executed in the caller's process. Accepts
the `:to` option which a tuple of the form: {ContextModule, StructModule}
You attached to conctext modules on a struct-by-struct basis for granular
events. The struct module passed must implement a valid struct or an error
is raised.
Events that executed are sent to a `handle_execute/2`, callback, which the
source module and executed event as arguments.
## Examples
defmodule MyModule do
def handle_execute({Accounts, %Accounts.Events.UpdateUpdated{user: user}}) do
IO.inspect({:user_updated, user})
end
end
iex> LiveBeats.attach(MyModule, to: {Accounts, Accounts.Events.UserUpdated})
:ok
iex> LiveBeats.execute(Accounts, %Accounts.Events.UserUpdated{user: new_user})
"""
def attach(target_mod, opts) when is_atom(target_mod) do
{src_mod, struct_mod} = Keyword.fetch!(opts, :to)
_ = struct_mod.__struct__
@ -11,6 +41,18 @@ defmodule LiveBeats do
})
end
@doc """
Executes an event from the context module with an event struct.
Events are exected *in the caller's process*, for every attached listener.
## Examples
iex> LiveBeats.attach(MyModule, to: {Accounts, Accounts.Events.UserUpdated})
:ok
iex> LiveBeats.execute(Accounts, %Accounts.Events.UserUpdated{user: new_user})
"""
def execute(src_mod, event_struct) when is_struct(event_struct) do
:telemetry.execute([src_mod, event_struct.__struct__], event_struct, %{})
end

View file

@ -130,8 +130,6 @@ defmodule LiveBeats.MediaLibrary do
end
end
defp topic(user_id) when is_integer(user_id), do: "profile:#{user_id}"
def store_mp3(%Song{} = song, tmp_path) do
File.mkdir_p!(Path.dirname(song.mp3_filepath))
File.cp!(tmp_path, song.mp3_filepath)
@ -331,4 +329,6 @@ defmodule LiveBeats.MediaLibrary do
defp broadcast!(user_id, msg) when is_integer(user_id) do
Phoenix.PubSub.broadcast!(@pubsub, topic(user_id), {__MODULE__, msg})
end
defp topic(user_id) when is_integer(user_id), do: "profile:#{user_id}"
end