Skip to content

Commit 04ee17c

Browse files
committed
Add feed given its url
1 parent 8e88177 commit 04ee17c

File tree

3 files changed

+94
-2
lines changed

3 files changed

+94
-2
lines changed

lib/ex_rss_web/feed_live/new.ex

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
defmodule ExRssWeb.FeedLive.New do
2+
use ExRssWeb, :live_view
3+
4+
alias ExRss.{Repo, User}
5+
alias ExRss.FeedAdder
6+
7+
def mount(
8+
%{"url" => url},
9+
%{"current_user" => current_user},
10+
socket
11+
) do
12+
candidate =
13+
case FeedAdder.discover_feed(url) do
14+
{:ok, candidate} -> candidate
15+
_ -> nil
16+
end
17+
18+
socket =
19+
socket
20+
|> assign(:current_user, current_user)
21+
|> assign(:candidate, candidate)
22+
|> assign(:added_feed, nil)
23+
24+
{:ok, socket}
25+
end
26+
27+
def mount(
28+
_params,
29+
_session,
30+
socket
31+
) do
32+
socket =
33+
socket
34+
|> assign(:candidate, nil)
35+
|> assign(:added_feed, nil)
36+
37+
{:ok, socket}
38+
end
39+
40+
def handle_event("add_feed", feed_params, socket) do
41+
multi =
42+
Repo.get!(User, socket.assigns.current_user.id)
43+
|> FeedAdder.add_feed(feed_params)
44+
45+
case Repo.transaction(multi) do
46+
{:ok, %{feed: added_feed}} ->
47+
socket =
48+
socket
49+
|> assign(:candidate, nil)
50+
|> assign(:added_feed, added_feed)
51+
52+
{:noreply, socket}
53+
54+
{:error, _error} ->
55+
{:noreply, socket}
56+
end
57+
end
58+
59+
def format_frequency(%{seconds: seconds, posts: posts}) do
60+
duration =
61+
if seconds < 2 * 86400 do
62+
"#{(seconds / 3600) |> round} hours"
63+
else
64+
"#{(seconds / 86400) |> round} days"
65+
end
66+
67+
"#{posts} posts in #{duration}"
68+
end
69+
end
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<%= if @candidate do %>
2+
<h1 class="text-m">This feed can be added</h1>
3+
4+
{@candidate.title}
5+
6+
<small class="inline-block ml-6">{format_frequency(@candidate.frequency)}</small>
7+
<p><code>{@candidate.url}</code></p>
8+
9+
<button
10+
class="px-4 py-2 text-sm font-extrabold bg-blue-700 text-white"
11+
type="button"
12+
phx-click="add_feed"
13+
phx-value-title={@candidate.title}
14+
phx-value-url={@candidate.url}
15+
>
16+
Add
17+
</button>
18+
<% end %>
19+
20+
<%= if @added_feed do %>
21+
<h1 class="text-m">This feed has been added</h1>
22+
23+
<p><code>{@added_feed.url}</code></p>
24+
<% end %>

lib/ex_rss_web/router.ex

+1-2
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,7 @@ defmodule ExRssWeb.Router do
4646

4747
scope "/feeds" do
4848
live "/", FeedLive.Index, :index
49-
50-
get "/new", FeedController, :new
49+
live "/new", FeedLive.New, :new
5150
end
5251
end
5352
end

0 commit comments

Comments
 (0)