4a35ca8fc30a351602c0f7eb78adf1b26e854467
[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.OStatus
6 alias Pleroma.Web.XML
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 = :crypto.hmac(:sha, sub.secret, response) |> Base.encode16
46
47 HTTPoison.post(sub.callback, response, [
48 {"Content-Type", "application/atom+xml"},
49 {"X-Hub-Signature", "sha1=#{signature}"}
50 ])
51 end)
52 end
53
54 def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
55 with {:ok, topic} <- valid_topic(params, user),
56 {:ok, lease_time} <- lease_time(params),
57 secret <- params["hub.secret"],
58 callback <- params["hub.callback"]
59 do
60 subscription = get_subscription(topic, callback)
61 data = %{
62 state: subscription.state || "requested",
63 topic: topic,
64 secret: secret,
65 callback: callback
66 }
67
68 change = Ecto.Changeset.change(subscription, data)
69 websub = Repo.insert_or_update!(change)
70
71 change = Ecto.Changeset.change(websub, %{valid_until: NaiveDateTime.add(websub.updated_at, lease_time)})
72 websub = Repo.update!(change)
73
74 Pleroma.Web.Federator.enqueue(:verify_websub, websub)
75
76 {:ok, websub}
77 else {:error, reason} ->
78 {:error, reason}
79 end
80 end
81
82 defp get_subscription(topic, callback) do
83 Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) || %WebsubServerSubscription{}
84 end
85
86 defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
87 {:ok, String.to_integer(lease_seconds)}
88 end
89
90 defp lease_time(_) do
91 {:ok, 60 * 60 * 24 * 3} # three days
92 end
93
94 defp valid_topic(%{"hub.topic" => topic}, user) do
95 if topic == OStatus.feed_path(user) do
96 {:ok, topic}
97 else
98 {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
99 end
100 end
101
102 def subscribe(user, topic, requester \\ &request_subscription/1) do
103 # FIXME: Race condition, use transactions
104 {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
105 subscribers = [user.ap_id, subscription.subcribers] |> Enum.uniq
106 change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
107 Repo.update(change)
108 else _e ->
109 subscription = %WebsubClientSubscription{
110 topic: topic,
111 subscribers: [user.ap_id],
112 state: "requested",
113 secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64,
114 user: user
115 }
116 Repo.insert(subscription)
117 end
118 requester.(subscription)
119 end
120
121 def discover(topic, getter \\ &HTTPoison.get/1) do
122 with {:ok, response} <- getter.(topic),
123 status_code when status_code in 200..299 <- response.status_code,
124 body <- response.body,
125 doc <- XML.parse_document(body),
126 url when not is_nil(url) <- XML.string_from_xpath(~S{/feed/link[@rel="self"]/@href}, doc),
127 hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
128 {:ok, %{url: url, hub: hub}}
129 else e ->
130 {:error, e}
131 end
132 end
133
134 def request_subscription(websub, poster \\ &HTTPoison.post/3, timeout \\ 10_000) do
135 data = [
136 "hub.mode": "subscribe",
137 "hub.topic": websub.topic,
138 "hub.secret": websub.secret,
139 "hub.callback": "https://social.heldscal.la/callback"
140 ]
141
142 # This checks once a second if we are confirmed yet
143 websub_checker = fn ->
144 helper = fn (helper) ->
145 :timer.sleep(1000)
146 websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
147 if websub, do: websub, else: helper.(helper)
148 end
149 helper.(helper)
150 end
151
152 task = Task.async(websub_checker)
153
154 with {:ok, %{status_code: 202}} <- poster.(websub.hub, {:form, data}, ["Content-type": "application/x-www-form-urlencoded"]),
155 {:ok, websub} <- Task.yield(task, timeout) do
156 {:ok, websub}
157 else e ->
158 Task.shutdown(task)
159
160 change = Ecto.Changeset.change(websub, %{state: "rejected"})
161 {:ok, websub} = Repo.update(change)
162
163 Logger.debug("Couldn't confirm subscription: #{inspect(websub)}")
164 Logger.debug("error: #{inspect(e)}")
165
166 {:error, websub}
167 end
168 end
169 end