websub.ex 7.4 KB
Newer Older
lain's avatar
lain committed
1
defmodule Pleroma.Web.Websub do
2
  alias Ecto.Changeset
lain's avatar
lain committed
3
  alias Pleroma.Repo
4
  alias Pleroma.Web.Websub.{WebsubServerSubscription, WebsubClientSubscription}
lain's avatar
lain committed
5
  alias Pleroma.Web.OStatus.FeedRepresenter
6
7
  alias Pleroma.Web.{XML, Endpoint, OStatus}
  alias Pleroma.Web.Router.Helpers
8
  require Logger
lain's avatar
lain committed
9
10

  import Ecto.Query
lain's avatar
lain committed
11

lain's avatar
lain committed
12
  @httpoison Application.get_env(:pleroma, :httpoison)
13

lain's avatar
lain committed
14
  def verify(subscription, getter \\ &@httpoison.get/3) do
lain's avatar
lain committed
15
    challenge = Base.encode16(:crypto.strong_rand_bytes(8))
16
17
    lease_seconds = NaiveDateTime.diff(subscription.valid_until, subscription.updated_at)
    lease_seconds = lease_seconds |> to_string
lain's avatar
lain committed
18
19
20
21
22
23
24
25
26
27
28
29

    params = %{
      "hub.challenge": challenge,
      "hub.lease_seconds": lease_seconds,
      "hub.topic": subscription.topic,
      "hub.mode": "subscribe"
    }

    url = hd(String.split(subscription.callback, "?"))
    query = URI.parse(subscription.callback).query || ""
    params = Map.merge(params, URI.decode_query(query))
    with {:ok, response} <- getter.(url, [], [params: params]),
lain's avatar
lain committed
30
31
         ^challenge <- response.body
    do
32
      changeset = Changeset.change(subscription, %{state: "active"})
lain's avatar
lain committed
33
      Repo.update(changeset)
34
35
36
    else e ->
      Logger.debug("Couldn't verify subscription")
      Logger.debug(inspect(e))
lain's avatar
lain committed
37
38
39
      {:error, subscription}
    end
  end
lain's avatar
lain committed
40

41
42
43
44
45
46
47
48
49
  @supported_activities [
    "Create",
    "Follow",
    "Like",
    "Announce",
    "Undo",
    "Delete"
  ]
  def publish(topic, user, %{data: %{"type" => type}} = activity) when type in @supported_activities do
lain's avatar
lain committed
50
    # TODO: Only send to still valid subscriptions.
lain's avatar
lain committed
51
    query = from sub in WebsubServerSubscription,
52
53
      where: sub.topic == ^topic and sub.state == "active",
      where: fragment("? > NOW()", sub.valid_until)
lain's avatar
lain committed
54
55
    subscriptions = Repo.all(query)
    Enum.each(subscriptions, fn(sub) ->
56
57
      response = user
      |> FeedRepresenter.to_simple_form([activity], [user])
lain's avatar
lain committed
58
      |> :xmerl.export_simple(:xmerl_xml)
lain's avatar
lain committed
59
      |> to_string
lain's avatar
lain committed
60

lain's avatar
lain committed
61
62
63
64
65
66
67
      data = %{
        xml: response,
        topic: topic,
        callback: sub.callback,
        secret: sub.secret
      }
      Pleroma.Web.Federator.enqueue(:publish_single_websub, data)
lain's avatar
lain committed
68
69
    end)
  end
70
  def publish(_,_,_), do: ""
71

lain's avatar
lain committed
72
  def sign(secret, doc) do
lain's avatar
lain committed
73
    :crypto.hmac(:sha, secret, to_string(doc)) |> Base.encode16 |> String.downcase
lain's avatar
lain committed
74
75
  end

76
  def incoming_subscription_request(user, %{"hub.mode" => "subscribe"} = params) do
77
78
79
80
81
82
83
84
85
86
87
88
89
    with {:ok, topic} <- valid_topic(params, user),
         {:ok, lease_time} <- lease_time(params),
         secret <- params["hub.secret"],
         callback <- params["hub.callback"]
    do
      subscription = get_subscription(topic, callback)
      data = %{
        state: subscription.state || "requested",
        topic: topic,
        secret: secret,
        callback: callback
      }

90
      change = Changeset.change(subscription, data)
91
92
      websub = Repo.insert_or_update!(change)

93
94
      change = Changeset.change(websub, %{valid_until:
                                          NaiveDateTime.add(websub.updated_at, lease_time)})
95
96
      websub = Repo.update!(change)

97
      Pleroma.Web.Federator.enqueue(:verify_websub, websub)
98
99
100

      {:ok, websub}
    else {:error, reason} ->
feld's avatar
feld committed
101
      Logger.debug("Couldn't create subscription")
lain's avatar
lain committed
102
103
      Logger.debug(inspect(reason))

104
105
106
107
108
      {:error, reason}
    end
  end

  defp get_subscription(topic, callback) do
109
110
    Repo.get_by(WebsubServerSubscription, topic: topic, callback: callback) ||
      %WebsubServerSubscription{}
111
112
  end

113
114
115
116
117
  # Temp hack for mastodon.
  defp lease_time(%{"hub.lease_seconds" => ""}) do
    {:ok, 60 * 60 * 24 * 3} # three days
  end

118
119
120
121
122
123
124
125
126
127
  defp lease_time(%{"hub.lease_seconds" => lease_seconds}) do
    {:ok, String.to_integer(lease_seconds)}
  end

  defp lease_time(_) do
    {:ok, 60 * 60 * 24 * 3} # three days
  end

  defp valid_topic(%{"hub.topic" => topic}, user) do
    if topic == OStatus.feed_path(user) do
128
      {:ok, OStatus.feed_path(user)}
129
130
131
132
    else
      {:error, "Wrong topic requested, expected #{OStatus.feed_path(user)}, got #{topic}"}
    end
  end
133

lain's avatar
lain committed
134
135
  def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
    topic = subscribed.info["topic"]
136
    # FIXME: Race condition, use transactions
137
    {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
lain's avatar
lain committed
138
      subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq
139
140
141
142
143
      change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
      Repo.update(change)
    else _e ->
      subscription = %WebsubClientSubscription{
        topic: topic,
lain's avatar
lain committed
144
145
        hub: subscribed.info["hub"],
        subscribers: [subscriber.ap_id],
146
        state: "requested",
147
        secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64,
lain's avatar
lain committed
148
        user: subscribed
149
150
151
      }
      Repo.insert(subscription)
    end
152
153
154
    requester.(subscription)
  end

155
  def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
156
157
158
159
    with {:ok, response} <- getter.(topic),
         status_code when status_code in 200..299 <- response.status_code,
         body <- response.body,
         doc <- XML.parse_document(body),
lain's avatar
lain committed
160
         uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
161
         hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
lain's avatar
lain committed
162
163
164
165

      name = XML.string_from_xpath("/feed/author[1]/name", doc)
      preferredUsername = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
      displayName = XML.string_from_xpath("/feed/author[1]/poco:displayName", doc)
lain's avatar
lain committed
166
      avatar = OStatus.make_avatar_object(doc)
167
      bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
lain's avatar
lain committed
168
169

      {:ok, %{
170
171
172
173
174
        "uri" => uri,
        "hub" => hub,
        "nickname" => preferredUsername || name,
        "name" => displayName || name,
        "host" => URI.parse(uri).host,
175
176
        "avatar" => avatar,
        "bio" => bio
lain's avatar
lain committed
177
      }}
178
179
180
181
182
    else e ->
      {:error, e}
    end
  end

lain's avatar
lain committed
183
  def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
184
185
186
187
    data = [
      "hub.mode": "subscribe",
      "hub.topic": websub.topic,
      "hub.secret": websub.secret,
188
      "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
189
190
191
192
193
194
195
196
197
198
199
    ]

    # This checks once a second if we are confirmed yet
    websub_checker = fn ->
      helper = fn (helper) ->
        :timer.sleep(1000)
        websub = Repo.get_by(WebsubClientSubscription, id: websub.id, state: "accepted")
        if websub, do: websub, else: helper.(helper)
      end
      helper.(helper)
    end
200

201
202
203
204
205
206
207
208
209
210
211
    task = Task.async(websub_checker)

    with {:ok, %{status_code: 202}} <- poster.(websub.hub, {:form, data}, ["Content-type": "application/x-www-form-urlencoded"]),
         {:ok, websub} <- Task.yield(task, timeout) do
      {:ok, websub}
    else e ->
      Task.shutdown(task)

      change = Ecto.Changeset.change(websub, %{state: "rejected"})
      {:ok, websub} = Repo.update(change)

lain's avatar
lain committed
212
213
      Logger.debug(fn -> "Couldn't confirm subscription: #{inspect(websub)}" end)
      Logger.debug(fn -> "error: #{inspect(e)}" end)
214
215
216

      {:error, websub}
    end
217
  end
lain's avatar
lain committed
218
219
220
221
222
223
224

  def refresh_subscriptions(delta \\ 60 * 60 * 24) do
    Logger.debug("Refreshing subscriptions")

    cut_off = NaiveDateTime.add(NaiveDateTime.utc_now, delta)

    query = from sub in WebsubClientSubscription,
lain's avatar
lain committed
225
      where: sub.valid_until < ^cut_off
lain's avatar
lain committed
226
227
228

    subs = Repo.all(query)

lain's avatar
lain committed
229
230
    Enum.each(subs, fn (sub) ->
      Pleroma.Web.Federator.enqueue(:request_subscription, sub)
lain's avatar
lain committed
231
232
    end)
  end
lain's avatar
lain committed
233
end