frenzy/lib/frenzy_web/controllers/item_controller.ex

64 lines
1.5 KiB
Elixir

defmodule FrenzyWeb.ItemController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, Feed, Item}
alias FrenzyWeb.Router.Helpers, as: Routes
alias FrenzyWeb.Endpoint
plug :user_owns_item
defp user_owns_item(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do
user = conn.assigns[:user]
item = Repo.get(Item, id)
feeds = Enum.flat_map(user.groups, fn g -> g.feeds end)
if Enum.any?(feeds, fn f -> f.id == item.feed_id end) do
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)
render(conn, "show.html", %{
item: item,
feed: item.feed
})
end
def read(conn, _params) do
item = conn.assigns[:item] |> Repo.preload(:feed)
changeset =
Item.changeset(item, %{
read: true,
read_date: Timex.now()
})
{:ok, item} = Repo.update(changeset)
redirect(conn, to: Routes.item_path(Endpoint, :show, item.id))
end
def unread(conn, _params) do
item = conn.assigns[:item] |> Repo.preload(:feed)
changeset =
Item.changeset(item, %{
read: false,
read_date: nil
})
Repo.update(changeset)
redirect(conn, to: Routes.item_path(Endpoint, :show, item.id))
end
end