defmodule FrenzyWeb.FeedController do use FrenzyWeb, :controller alias Frenzy.{Repo, Group, Feed, Filter, Item} alias FrenzyWeb.Router.Helpers, as: Routes alias FrenzyWeb.Endpoint import Ecto.Query plug :user_owns_feed defp user_owns_feed(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do user = conn.assigns[:user] feed = Repo.get(Feed, id) if Enum.any?(user.groups, fn g -> g.id == feed.group_id end) do conn |> assign(:feed, feed) 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_feed(conn, _opts), do: conn def show(conn, %{"id" => id}) do feed = conn.assigns[:feed] items = Repo.all(from Item, where: [feed_id: ^id, tombstone: false], order_by: [desc: :date]) render(conn, "show.html", %{ feed: feed, items: items }) end def create(conn, %{"feed" => %{"group_id" => group_id, "feed_url" => feed_url}}) do group = Repo.get(Group, group_id) changeset = Ecto.build_assoc(group, :feeds, %{ feed_url: feed_url, filter: %Filter{ mode: "reject", score: 0 } }) {:ok, feed} = Repo.insert(changeset) redirect(conn, to: Routes.group_path(Endpoint, :show, group_id)) end def delete(conn, _params) do feed = conn.assigns[:feed] {:ok, _} = Repo.delete(feed) redirect(conn, to: Routes.group_path(Endpoint, :show, feed.group_id)) end def enable_filter(conn, _params) do feed = conn.assigns[:feed] |> Repo.preload(:filter) changeset = Feed.changeset(feed, %{filter_enabled: true}) Repo.update(changeset) redirect(conn, to: Routes.feed_path(Endpoint, :show, feed.id)) end def disable_filter(conn, _params) do feed = conn.assigns[:feed] |> Repo.preload(:filter) changeset = Feed.changeset(feed, %{filter_enabled: false}) Repo.update(changeset) redirect(conn, to: Routes.feed_path(Endpoint, :show, feed.id)) end def refresh(conn, _params) do feed = conn.assigns[:feed] |> Repo.preload(:filter) feed = Frenzy.UpdateFeeds.refresh(Frenzy.UpdateFeeds, feed) redirect(conn, to: Routes.feed_path(Endpoint, :show, feed.id)) end end