Merge branch 'develop' into dtluna/pleroma-feature/unfollow-activity
[akkoma] / lib / pleroma / web / websub / websub.ex
1 defmodule Pleroma.Web.Websub do
2 alias Ecto.Changeset
3 alias Pleroma.Repo
4 alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription}
5 alias Pleroma.Web.OStatus.FeedRepresenter
6 alias Pleroma.Web.{XML, Endpoint, OStatus}
7 alias Pleroma.Web.Router.Helpers
8 require Logger
9
10 import Ecto.Query
11
12 @httpoison Application.get_env(:pleroma, :httpoison)
13
14 def verify(subscription, getter \\ &@httpoison.get/3) do
15 challenge = Base.encode16(:crypto.strong_rand_bytes(8))
16 lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at)
17 lease_seconds = lease_seconds |> to_string
18
19 params = %{
20 "hub.challenge": challenge,
21 "hub.lease_seconds": lease_seconds,
22 "hub.topic": subscription.topic,
23 "hub.mode": "subscribe"
24 }
25
26 url = hd(String.split(subscription.callback, "?"))
27 query = URI.parse(subscription.callback).query || ""
28 params = Map.merge(params, URI.decode_query(query))
29 with {:ok, response} <- getter.(url, [], [params: params]),
30 ^challenge <- response.body
31 do
32 changeset = Changeset.change(subscription, %{state: "active"})
33 Repo.update(changeset)
34 else _e ->
35 changeset = Changeset.change(subscription, %{state: "rejected"})
36 {:ok, subscription} = Repo.update(changeset)
37 {:error, subscription}
38 end
39 end
40
41 def publish(topic, user, activity) do
42 query = from sub in WebsubServerSubscription,
43 where: sub.topic == ^topic and sub.state == "active"
44 subscriptions = Repo.all(query)
45 Enum.each(subscriptions, fn(sub) ->
46 response = user
47 |> FeedRepresenter.to_simple_form([activity], [user])
48 |> :xmerl.export_simple(:xmerl_xml)
49 |> to_string
50
51 signature = sign(sub.secret || "", response)
52 Logger.debug(fn -> "Pushing to #{sub.callback}" end)
53
54 Task.start(fn ->
55 @httpoison.post(sub.callback, response, [
56 {"Content-Type", "application/atom+xml"},
57 {"X-Hub-Signature", "sha1=#{signature}"}
58 ])
59 end)
60 end)
61 end
62
63 def sign(secret, doc) do
64 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16 |> String.downcase
65 end
66
67 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
68 with {:ok, topic} <- valid_topic(params, user),
69 {:ok, lease_time} <- lease_time(params),
70 secret <- params["hub.secret"],
71 callback <- params["hub.callback"]
72 do
73 subscription = get_subscription(topic, callback)
74 data = %{
75 state: subscription.state || "requested",
76 topic: topic,
77 secret: secret,
78 callback: callback
79 }
80
81 change = Changeset.change(subscription, data)
82 websub = Repo.insert_or_update!(change)
83
84 change = Changeset.change(websub, %{valid_until:
85 NaiveDateTime.add(websub.updated_at, lease_time)})
86 websub = Repo.update!(change)
87
88 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
89
90 {:ok, websub}
91 else {:error, reason} ->
92 Logger.debug("Couldn't create subscription.")
93 Logger.debug(inspect(reason))
94
95 {:error, reason}
96 end
97 end
98
99 defp get_subscription(topic, callback) do
100 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
101 %WebsubServerSubscription{}
102 end
103
104 # Temp hack for mastodon.
105 defp lease_time(%{"hub.lease_seconds" => ""}) do
106 {:ok, 60 * 60 * 24 * 3} # three days
107 end
108
109 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
110 {:ok, String.to_integer(lease_seconds)}
111 end
112
113 defp lease_time(_) do
114 {:ok, 60 * 60 * 24 * 3} # three days
115 end
116
117 defp valid_topic(%{"hub.topic" => topic}, user) do
118 if topic == OStatus.feed_path(user) do
119 {:ok, OStatus.feed_path(user)}
120 else
121 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
122 end
123 end
124
125 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
126 topic = subscribed.info["topic"]
127 # FIXME: Race condition, use transactions
128 {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
129 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq
130 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
131 Repo.update(change)
132 else _e ->
133 subscription = %WebsubClientSubscription{
134 topic: topic,
135 hub: subscribed.info["hub"],
136 subscribers: [subscriber.ap_id],
137 state: "requested",
138 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64,
139 user: subscribed
140 }
141 Repo.insert(subscription)
142 end
143 requester.(subscription)
144 end
145
146 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
147 with {:ok, response} <- getter.(topic),
148 status_code when status_code in 200..299 <- response.status_code,
149 body <- response.body,
150 doc <- XML.parse_document(body),
151 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
152 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
153
154 name = XML.string_from_xpath("/feed/author[1]/name", doc)
155 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
156 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
157 avatar = OStatus.make_avatar_object(doc)
158
159 {:ok, %{
160 "uri" => uri,
161 "hub" => hub,
162 "nickname" => preferredUsername || name,
163 "name" => displayName || name,
164 "host" => URI.parse(uri).host,
165 "avatar" => avatar
166 }}
167 else e ->
168 {:error, e}
169 end
170 end
171
172 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
173 data = [
174 "hub.mode": "subscribe",
175 "hub.topic": websub.topic,
176 "hub.secret": websub.secret,
177 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
178 ]
179
180 # This checks once a second if we are confirmed yet
181 websub_checker = fn ->
182 helper = fn (helper) ->
183 :timer.sleep(1000)
184 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
185 if websub, do: websub, else: helper.(helper)
186 end
187 helper.(helper)
188 end
189
190 task = Task.async(websub_checker)
191
192 with {:ok, %{status_code: 202}} <- poster.(websub.hub, {:form, data}, ["Content-type": "application/x-www-form-urlencoded"]),
193 {:ok, websub} <- Task.yield(task, timeout) do
194 {:ok, websub}
195 else e ->
196 Task.shutdown(task)
197
198 change = Ecto.Changeset.change(websub, %{state: "rejected"})
199 {:ok, websub} = Repo.update(change)
200
201 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
202 Logger.debug(fn -> "error: #{inspect(e)}" end)
203
204 {:error, websub}
205 end
206 end
207 end