Merge branch 'develop' into 'develop'
[akkoma] / lib / pleroma / user.ex
index f28f0deb0cad55c2b418f444cef94b28522f77e3..938b57d90c47322e754e02704cc8c459519e4edd 100644 (file)
@@ -2,7 +2,7 @@ defmodule Pleroma.User do
   use Ecto.Schema
 
   import Ecto.{Changeset, Query}
-  alias Pleroma.{Repo, User, Object, Web}
+  alias Pleroma.{Repo, User, Object, Web, Activity, Notification}
   alias Comeonin.Pbkdf2
   alias Pleroma.Web.{OStatus, Websub}
   alias Pleroma.Web.ActivityPub.ActivityPub
@@ -22,6 +22,7 @@ defmodule Pleroma.User do
     field :local, :boolean, default: true
     field :info, :map, default: %{}
     field :follower_address, :string
+    has_many :notifications, Notification
 
     timestamps()
   end
@@ -33,6 +34,13 @@ defmodule Pleroma.User do
     end
   end
 
+  def banner_url(user) do
+    case user.info["banner"] do
+      %{"url" => [%{"href" => href} | _]} -> href
+      _ -> nil
+    end
+  end
+
   def ap_id(%User{nickname: nickname}) do
     "#{Web.base_url}/users/#{nickname}"
   end
@@ -80,6 +88,34 @@ defmodule Pleroma.User do
     end
   end
 
+  def update_changeset(struct, params \\ %{}) do
+    changeset = struct
+    |> cast(params, [:bio, :name])
+    |> unique_constraint(:nickname)
+    |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
+    |> validate_length(:bio, min: 1, max: 1000)
+    |> validate_length(:name, min: 1, max: 100)
+  end
+
+  def password_update_changeset(struct, params) do
+    changeset = struct
+    |> cast(params, [:password, :password_confirmation])
+    |> validate_required([:password, :password_confirmation])
+    |> validate_confirmation(:password)
+
+    if changeset.valid? do
+      hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
+      changeset
+      |> put_change(:password_hash, hashed)
+    else
+      changeset
+    end
+  end
+
+  def reset_password(user, data) do
+    Repo.update(password_update_changeset(user, data))
+  end
+
   def register_changeset(struct, params \\ %{}) do
     changeset = struct
     |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
@@ -89,8 +125,8 @@ defmodule Pleroma.User do
     |> unique_constraint(:nickname)
     |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
     |> validate_format(:email, @email_regex)
-    |> validate_length(:bio, max: 1000)
-    |> validate_length(:name, max: 100)
+    |> validate_length(:bio, min: 1, max: 1000)
+    |> validate_length(:name, min: 1, max: 100)
 
     if changeset.valid? do
       hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
@@ -230,4 +266,12 @@ defmodule Pleroma.User do
 
     Repo.update(cs)
   end
+
+  def get_notified_from_activity(%Activity{data: %{"to" => to}} = activity) do
+    query = from u in User,
+      where: u.ap_id in ^to,
+      where: u.local == true
+
+    Repo.all(query)
+  end
 end