Merge branch 'develop' into feature/activitypub
[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 Logger.debug("Couldn't verify subscription")
36 Logger.debug(inspect(e))
37 {:error, subscription}
38 end
39 end
40
41 @supported_activities [
42 "Create",
43 "Follow",
44 "Like",
45 "Announce",
46 "Undo",
47 "Delete"
48 ]
49 def publish(topic, user, %{data: %{"type" => type}} = activity) when type in @supported_activities do
50 # TODO: Only send to still valid subscriptions.
51 query = from sub in WebsubServerSubscription,
52 where: sub.topic == ^topic and sub.state == "active"
53 subscriptions = Repo.all(query)
54 Enum.each(subscriptions, fn(sub) ->
55 response = user
56 |> FeedRepresenter.to_simple_form([activity], [user])
57 |> :xmerl.export_simple(:xmerl_xml)
58 |> to_string
59
60 data = %{
61 xml: response,
62 topic: topic,
63 callback: sub.callback,
64 secret: sub.secret
65 }
66 Pleroma.Web.Federator.enqueue(:publish_single_websub, data)
67 end)
68 end
69 def publish(_,_,_), do: ""
70
71 def sign(secret, doc) do
72 :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16 |> String.downcase
73 end
74
75 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
76 with {:ok, topic} <- valid_topic(params, user),
77 {:ok, lease_time} <- lease_time(params),
78 secret <- params["hub.secret"],
79 callback <- params["hub.callback"]
80 do
81 subscription = get_subscription(topic, callback)
82 data = %{
83 state: subscription.state || "requested",
84 topic: topic,
85 secret: secret,
86 callback: callback
87 }
88
89 change = Changeset.change(subscription, data)
90 websub = Repo.insert_or_update!(change)
91
92 change = Changeset.change(websub, %{valid_until:
93 NaiveDateTime.add(websub.updated_at, lease_time)})
94 websub = Repo.update!(change)
95
96 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
97
98 {:ok, websub}
99 else {:error, reason} ->
100 Logger.debug("Couldn't create subscription.")
101 Logger.debug(inspect(reason))
102
103 {:error, reason}
104 end
105 end
106
107 defp get_subscription(topic, callback) do
108 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
109 %WebsubServerSubscription{}
110 end
111
112 # Temp hack for mastodon.
113 defp lease_time(%{"hub.lease_seconds" => ""}) do
114 {:ok, 60 * 60 * 24 * 3} # three days
115 end
116
117 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
118 {:ok, String.to_integer(lease_seconds)}
119 end
120
121 defp lease_time(_) do
122 {:ok, 60 * 60 * 24 * 3} # three days
123 end
124
125 defp valid_topic(%{"hub.topic" => topic}, user) do
126 if topic == OStatus.feed_path(user) do
127 {:ok, OStatus.feed_path(user)}
128 else
129 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
130 end
131 end
132
133 def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
134 topic = subscribed.info["topic"]
135 # FIXME: Race condition, use transactions
136 {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
137 subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq
138 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
139 Repo.update(change)
140 else _e ->
141 subscription = %WebsubClientSubscription{
142 topic: topic,
143 hub: subscribed.info["hub"],
144 subscribers: [subscriber.ap_id],
145 state: "requested",
146 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64,
147 user: subscribed
148 }
149 Repo.insert(subscription)
150 end
151 requester.(subscription)
152 end
153
154 def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
155 with {:ok, response} <- getter.(topic),
156 status_code when status_code in 200..299 <- response.status_code,
157 body <- response.body,
158 doc <- XML.parse_document(body),
159 uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
160 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
161
162 name = XML.string_from_xpath("/feed/author[1]/name", doc)
163 preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
164 displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
165 avatar = OStatus.make_avatar_object(doc)
166 bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
167
168 {:ok, %{
169 "uri" => uri,
170 "hub" => hub,
171 "nickname" => preferredUsername || name,
172 "name" => displayName || name,
173 "host" => URI.parse(uri).host,
174 "avatar" => avatar,
175 "bio" => bio
176 }}
177 else e ->
178 {:error, e}
179 end
180 end
181
182 def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
183 data = [
184 "hub.mode": "subscribe",
185 "hub.topic": websub.topic,
186 "hub.secret": websub.secret,
187 "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
188 ]
189
190 # This checks once a second if we are confirmed yet
191 websub_checker = fn ->
192 helper = fn (helper) ->
193 :timer.sleep(1000)
194 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
195 if websub, do: websub, else: helper.(helper)
196 end
197 helper.(helper)
198 end
199
200 task = Task.async(websub_checker)
201
202 with {:ok, %{status_code: 202}} <- poster.(websub.hub, {:form, data}, ["Content-type": "application/x-www-form-urlencoded"]),
203 {:ok, websub} <- Task.yield(task, timeout) do
204 {:ok, websub}
205 else e ->
206 Task.shutdown(task)
207
208 change = Ecto.Changeset.change(websub, %{state: "rejected"})
209 {:ok, websub} = Repo.update(change)
210
211 Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
212 Logger.debug(fn -> "error: #{inspect(e)}" end)
213
214 {:error, websub}
215 end
216 end
217
218 def refresh_subscriptions(delta \\ 60 * 60 * 24) do
219 Logger.debug("Refreshing subscriptions")
220
221 cut_off = NaiveDateTime.add(NaiveDateTime.utc_now, delta)
222
223 query = from sub in WebsubClientSubscription,
224 where: sub.valid_until < ^cut_off
225
226 subs = Repo.all(query)
227
228 Enum.each(subs, fn (sub) ->
229 Pleroma.Web.Federator.enqueue(:request_subscription, sub)
230 end)
231 end
232 end