frenzy/lib/frenzy_web/controllers/item_controller.ex

61 lines
1.4 KiB
Elixir
Raw Normal View History

2019-02-11 22:22:35 +00:00
defmodule FrenzyWeb.ItemController do
use FrenzyWeb, :controller
2020-06-07 15:14:01 +00:00
alias Frenzy.{Repo, Item}
2019-02-11 22:22:35 +00:00
alias FrenzyWeb.Endpoint
2019-03-23 23:42:38 +00:00
plug :user_owns_item
defp user_owns_item(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do
user = conn.assigns[:user]
2019-02-11 22:22:35 +00:00
item = Repo.get(Item, id)
2019-03-23 23:42:38 +00:00
if Enum.any?(user.feeds, fn f -> f.id == item.feed_id end) do
2019-03-23 23:42:38 +00:00
conn
|> assign(:item, item)
else
conn
|> put_flash(:error, "You do not have permission to access that resource.")
|> redirect(to: Routes.group_path(Endpoint, :index))
|> halt()
end
end
defp user_owns_item(conn, _opts), do: conn
def show(conn, _params) do
item = conn.assigns[:item] |> Repo.preload(:feed)
2019-02-11 22:22:35 +00:00
render(conn, "show.html", %{
item: item,
2019-03-23 23:42:38 +00:00
feed: item.feed
})
2019-02-11 22:22:35 +00:00
end
2019-03-23 23:42:38 +00:00
def read(conn, _params) do
item = conn.assigns[:item] |> Repo.preload(:feed)
changeset =
Item.changeset(item, %{
read: true,
read_date: Timex.now()
2019-02-11 22:22:35 +00:00
})
2019-03-23 23:42:38 +00:00
{:ok, item} = Repo.update(changeset)
2019-03-23 23:42:38 +00:00
redirect(conn, to: Routes.item_path(Endpoint, :show, item.id))
2019-02-11 22:22:35 +00:00
end
2019-03-23 23:42:38 +00:00
def unread(conn, _params) do
item = conn.assigns[:item] |> Repo.preload(:feed)
changeset =
Item.changeset(item, %{
read: false,
read_date: nil
2019-02-11 22:22:35 +00:00
})
2019-03-23 23:42:38 +00:00
2019-02-11 22:22:35 +00:00
Repo.update(changeset)
2019-03-23 23:42:38 +00:00
redirect(conn, to: Routes.item_path(Endpoint, :show, item.id))
2019-02-11 22:22:35 +00:00
end
2019-03-23 23:42:38 +00:00
end