frenzy/lib/frenzy_web/controllers/item_controller.ex

64 lines
1.5 KiB
Elixir
Raw Normal View History

2019-02-11 22:22:35 +00:00
defmodule FrenzyWeb.ItemController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, Feed, Item}
alias FrenzyWeb.Router.Helpers, as: Routes
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
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)
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
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
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