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