- def subscribe(user, topic) do
- # Race condition, use transactions
- {:ok, subscription} = with subscription when not is_nil(subscription) <- Repo.get_by(WebsubClientSubscription, topic: topic) do
- subscribers = [user.ap_id, subscription.subcribers] |> Enum.uniq
- change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
- Repo.update(change)
- else _e ->
- subscription = %WebsubClientSubscription{
- topic: topic,
- subscribers: [user.ap_id],
- state: "requested",
- secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64
- }
- Repo.insert(subscription)
+ def subscribe(subscriber, subscribed, requester \\ &request_subscription/1) do
+ topic = subscribed.info["topic"]
+ # FIXME: Race condition, use transactions
+ {:ok, subscription} =
+ with subscription when not is_nil(subscription) <-
+ Repo.get_by(WebsubClientSubscription, topic: topic) do
+ subscribers = [subscriber.ap_id | subscription.subscribers] |> Enum.uniq()
+ change = Ecto.Changeset.change(subscription, %{subscribers: subscribers})
+ Repo.update(change)
+ else
+ _e ->
+ subscription = %WebsubClientSubscription{
+ topic: topic,
+ hub: subscribed.info["hub"],
+ subscribers: [subscriber.ap_id],
+ state: "requested",
+ secret: :crypto.strong_rand_bytes(8) |> Base.url_encode64(),
+ user: subscribed
+ }
+
+ Repo.insert(subscription)
+ end
+
+ requester.(subscription)
+ end
+
+ def gather_feed_data(topic, getter \\ &@httpoison.get/1) do
+ with {:ok, response} <- getter.(topic),
+ status_code when status_code in 200..299 <- response.status_code,
+ body <- response.body,
+ doc <- XML.parse_document(body),
+ uri when not is_nil(uri) <- XML.string_from_xpath("/feed/author[1]/uri", doc),
+ hub when not is_nil(hub) <- XML.string_from_xpath(~S{/feed/link[@rel="hub"]/@href}, doc) do
+ 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)
+ avatar = OStatus.make_avatar_object(doc)
+ bio = XML.string_from_xpath("/feed/author[1]/summary", doc)
+
+ {:ok,
+ %{
+ "uri" => uri,
+ "hub" => hub,
+ "nickname" => preferredUsername || name,
+ "name" => displayName || name,
+ "host" => URI.parse(uri).host,
+ "avatar" => avatar,
+ "bio" => bio
+ }}
+ else
+ e ->
+ {:error, e}
+ end
+ end
+
+ def request_subscription(websub, poster \\ &@httpoison.post/3, timeout \\ 10_000) do
+ data = [
+ "hub.mode": "subscribe",
+ "hub.topic": websub.topic,
+ "hub.secret": websub.secret,
+ "hub.callback": Helpers.websub_url(Endpoint, :websub_subscription_confirmation, websub.id)
+ ]
+
+ # 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)