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