Add webpush front-end support
Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
@@ -3,45 +3,29 @@ defmodule Mobilizon.Users.PushSubscription do
|
||||
alias Mobilizon.Users.User
|
||||
import Ecto.Changeset
|
||||
|
||||
@primary_key {:id, :binary_id, autogenerate: true}
|
||||
schema "user_push_subscriptions" do
|
||||
field(:digest, :string)
|
||||
belongs_to(:user, User)
|
||||
|
||||
embeds_one :data, Data, on_replace: :delete do
|
||||
field(:endpoint, :string)
|
||||
|
||||
embeds_one :keys, Keys, on_replace: :delete do
|
||||
field(:auth, :string)
|
||||
field(:p256dh, :string)
|
||||
end
|
||||
end
|
||||
|
||||
field(:endpoint, :string)
|
||||
field(:auth, :string)
|
||||
field(:p256dh, :string)
|
||||
timestamps()
|
||||
end
|
||||
|
||||
@doc false
|
||||
def changeset(push_subscription, attrs) do
|
||||
push_subscription
|
||||
|> cast(attrs, [:user_id])
|
||||
|> cast_embed(:data, with: &cast_data/2)
|
||||
|> put_change(:digest, compute_digest(attrs.data))
|
||||
|> validate_required([:digest, :user_id, :data])
|
||||
|> cast(attrs, [:user_id, :endpoint, :auth, :p256dh])
|
||||
|> put_change(:digest, compute_digest(attrs))
|
||||
|> validate_required([:digest, :user_id, :endpoint, :auth, :p256dh])
|
||||
|> unique_constraint([:digest, :user_id], name: :user_push_subscriptions_user_id_digest_index)
|
||||
end
|
||||
|
||||
defp cast_data(schema, attrs) do
|
||||
schema
|
||||
|> cast(attrs, [:endpoint])
|
||||
|> cast_embed(:keys, with: &cast_keys/2)
|
||||
|> validate_required([:endpoint, :keys])
|
||||
end
|
||||
defp compute_digest(attrs) do
|
||||
data =
|
||||
Jason.encode!(%{endpoint: attrs.endpoint, keys: %{auth: attrs.auth, p256dh: attrs.p256dh}})
|
||||
|
||||
defp cast_keys(schema, attrs) do
|
||||
schema
|
||||
|> cast(attrs, [:auth, :p256dh])
|
||||
|> validate_required([:auth, :p256dh])
|
||||
end
|
||||
|
||||
defp compute_digest(data) do
|
||||
:sha256
|
||||
|> :crypto.hash(data)
|
||||
|> Base.encode16()
|
||||
|
||||
@@ -413,17 +413,16 @@ defmodule Mobilizon.Users do
|
||||
def list_user_push_subscriptions(user_id, page \\ nil, limit \\ nil) do
|
||||
PushSubscription
|
||||
|> where([p], p.user_id == ^user_id)
|
||||
|> preload([:user])
|
||||
|> Page.build_page(page, limit)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Get a push subscription by their ID
|
||||
Get a push subscription by their endpoint
|
||||
"""
|
||||
@spec get_push_subscription(String.t() | integer()) :: PushSubscription.t() | nil
|
||||
def get_push_subscription(push_subscription_id) do
|
||||
@spec get_push_subscription_by_endpoint(String.t()) :: PushSubscription.t() | nil
|
||||
def get_push_subscription_by_endpoint(endpoint) do
|
||||
PushSubscription
|
||||
|> Repo.get(push_subscription_id)
|
||||
|> Repo.get_by(endpoint: endpoint)
|
||||
|> Repo.preload([:user])
|
||||
end
|
||||
|
||||
|
||||
Reference in New Issue
Block a user