Skip to content

Commit

Permalink
notify studio followers whenever a new work is published (#797)
Browse files Browse the repository at this point in the history
Fixes: #792
  • Loading branch information
zkat authored Apr 1, 2024
1 parent 54f7687 commit 430e402
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
19 changes: 19 additions & 0 deletions lib/banchan/studios/notifications.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,25 @@ defmodule Banchan.Studios.Notifications do
)
end

@doc """
Stream of studio followers. Intended for notification use.
"""
def stream_followers(%Studio{} = studio) do
from(u in User,
as: :user,
join: f in StudioFollower,
on: f.user_id == u.id and f.studio_id == ^studio.id,
left_join: settings in assoc(u, :notification_settings),
where: is_nil(u.deactivated_at),
select: %User{
id: u.id,
email: u.email,
notification_settings: settings
}
)
|> Repo.stream()
end

@doc """
Adds a user to the given studio's followers.
"""
Expand Down
46 changes: 46 additions & 0 deletions lib/banchan/works/notifications.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
defmodule Banchan.Works.Notifications do
@moduledoc """
Notifications related to Works (new works, etc).
"""
import Ecto.Query, warn: false

alias Banchan.Notifications
alias Banchan.Repo
alias Banchan.Studios
alias Banchan.Works.Work

# Unfortunate, but needed for crafting URLs for notifications
use BanchanWeb, :verified_routes

def work_created(%Work{} = work, actor \\ nil) do
Notifications.with_task(fn ->
{:ok, _} =
Repo.transaction(fn ->
work = Repo.preload(work, :studio)

studio = work.studio

subs = Studios.Notifications.stream_followers(studio)

url = url(~p"/studios/#{studio.handle}/works/#{work.public_id}")

{:safe, safe_url} = Phoenix.HTML.html_escape(url)

Notifications.notify_subscribers!(
actor,
subs,
%Notifications.UserNotification{
type: "work_created",
title: "New work published",
short_body: "#{studio.name} published a new work.",
text_body: "#{studio.name} published a new work, #{work.title}:\n\n#{url}",
html_body:
"<p>#{studio.name} published a new work: <a href=\"#{safe_url}\">#{work.title}</a></p>",
url: url,
read: false
}
)
end)
end)
end
end
10 changes: 9 additions & 1 deletion lib/banchan/works/works.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ defmodule Banchan.Works do
alias Banchan.Uploads
alias Banchan.Uploads.Upload
alias Banchan.Workers.Thumbnailer
alias Banchan.Works.{Work, WorkUpload}
alias Banchan.Works.{Notifications, Work, WorkUpload}

@public_id_size Work.rand_id() |> byte_size()

Expand Down Expand Up @@ -86,6 +86,14 @@ defmodule Banchan.Works do
end)

ret
|> case do
{:ok, work} ->
Notifications.work_created(work, actor)
{:ok, work}

{:error, changeset} ->
{:error, changeset}
end
end

## Getting/Listing
Expand Down

0 comments on commit 430e402

Please sign in to comment.