- 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 when status in 200..299 <- response.status,
+ 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)
+ preferred_username = XML.string_from_xpath("/feed/author[1]/poco:preferredUsername", doc)
+ display_name = 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" => preferred_username || name,
+ "name" => display_name || name,
+ "host" => URI.parse(uri).host,
+ "avatar" => avatar,
+ "bio" => bio
+ }}
+ else
+ e ->
+ {:error, e}