Basic queue.
[akkoma] / lib / pleroma / web / ostatus / ostatus.ex
1 defmodule Pleroma.Web.OStatus do
2 @httpoison Application.get_env(:pleroma, :httpoison)
3
4 import Ecto.Query
5 import Pleroma.Web.XML
6 require Logger
7
8 alias Pleroma.{Repo, User, Web, Object, Activity}
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.{WebFinger, Websub}
11
12 def feed_path(user) do
13 "#{user.ap_id}/feed.atom"
14 end
15
16 def pubsub_path(user) do
17 "#{Web.base_url}/push/hub/#{user.nickname}"
18 end
19
20 def salmon_path(user) do
21 "#{user.ap_id}/salmon"
22 end
23
24 def handle_incoming(xml_string) do
25 doc = parse_document(xml_string)
26 entries = :xmerl_xpath.string('//entry', doc)
27
28 activities = Enum.map(entries, fn (entry) ->
29 {:xmlObj, :string, object_type} = :xmerl_xpath.string('string(/entry/activity:object-type[1])', entry)
30 {:xmlObj, :string, verb} = :xmerl_xpath.string('string(/entry/activity:verb[1])', entry)
31
32 case verb do
33 'http://activitystrea.ms/schema/1.0/share' ->
34 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc), do: [activity, retweeted_activity]
35 'http://activitystrea.ms/schema/1.0/favorite' ->
36 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc), do: [activity, favorited_activity]
37 _ ->
38 case object_type do
39 'http://activitystrea.ms/schema/1.0/note' ->
40 with {:ok, activity} <- handle_note(entry, doc), do: activity
41 'http://activitystrea.ms/schema/1.0/comment' ->
42 with {:ok, activity} <- handle_note(entry, doc), do: activity
43 _ ->
44 Logger.error("Couldn't parse incoming document")
45 nil
46 end
47 end
48 end)
49 {:ok, activities}
50 end
51
52 def make_share(_entry, doc, retweeted_activity) do
53 with {:ok, actor} <- find_make_or_update_user(doc),
54 %Object{} = object <- Object.get_cached_by_ap_id(retweeted_activity.data["object"]["id"]),
55 {:ok, activity, _object} = ActivityPub.announce(actor, object, false) do
56 {:ok, activity}
57 end
58 end
59
60 def handle_share(entry, doc) do
61 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry),
62 {:ok, retweeted_activity} <- handle_note(object, object),
63 {:ok, activity} <- make_share(entry, doc, retweeted_activity) do
64 {:ok, activity, retweeted_activity}
65 else
66 e -> {:error, e}
67 end
68 end
69
70 def make_favorite(_entry, doc, favorited_activity) do
71 with {:ok, actor} <- find_make_or_update_user(doc),
72 %Object{} = object <- Object.get_cached_by_ap_id(favorited_activity.data["object"]["id"]),
73 {:ok, activity, _object} = ActivityPub.like(actor, object, false) do
74 {:ok, activity}
75 end
76 end
77
78 def get_or_try_fetching(entry) do
79 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
80 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
81 {:ok, activity}
82 else _e ->
83 with href when not is_nil(href) <- string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
84 {:ok, [favorited_activity]} <- fetch_activity_from_html_url(href) do
85 {:ok, favorited_activity}
86 end
87 end
88 end
89
90 def handle_favorite(entry, doc) do
91 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
92 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
93 {:ok, activity, favorited_activity}
94 else
95 e -> {:error, e}
96 end
97 end
98
99 def get_attachments(entry) do
100 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
101 |> Enum.map(fn (enclosure) ->
102 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
103 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
104 %{
105 "type" => "Attachment",
106 "url" => [%{
107 "type" => "Link",
108 "mediaType" => type,
109 "href" => href
110 }]
111 }
112 end
113 end)
114 |> Enum.filter(&(&1))
115 end
116
117 def handle_note(entry, doc \\ nil) do
118 content_html = string_from_xpath("//content[1]", entry)
119
120 [author] = :xmerl_xpath.string('//author[1]', doc)
121 {:ok, actor} = find_make_or_update_user(author)
122 inReplyTo = string_from_xpath("//thr:in-reply-to[1]/@ref", entry)
123
124 context = (string_from_xpath("//ostatus:conversation[1]", entry) || "") |> String.trim
125
126 attachments = get_attachments(entry)
127
128 context = with %{data: %{"context" => context}} <- Object.get_cached_by_ap_id(inReplyTo) do
129 context
130 else _e ->
131 if String.length(context) > 0 do
132 context
133 else
134 ActivityPub.generate_context_id
135 end
136 end
137
138 to = [
139 "https://www.w3.org/ns/activitystreams#Public"
140 ]
141
142 mentions = :xmerl_xpath.string('//link[@rel="mentioned" and @ostatus:object-type="http://activitystrea.ms/schema/1.0/person"]', entry)
143 |> Enum.map(fn(person) -> string_from_xpath("@href", person) end)
144
145 to = to ++ mentions
146
147 date = string_from_xpath("//published", entry)
148 id = string_from_xpath("//id", entry)
149
150 object = %{
151 "id" => id,
152 "type" => "Note",
153 "to" => to,
154 "content" => content_html,
155 "published" => date,
156 "context" => context,
157 "actor" => actor.ap_id,
158 "attachment" => attachments
159 }
160
161 object = if inReplyTo do
162 Map.put(object, "inReplyTo", inReplyTo)
163 else
164 object
165 end
166
167 # TODO: Bail out sooner and use transaction.
168 if Object.get_by_ap_id(id) do
169 {:error, "duplicate activity"}
170 else
171 ActivityPub.create(to, actor, context, object, %{}, date, false)
172 end
173 end
174
175 def find_make_or_update_user(doc) do
176 uri = string_from_xpath("//author/uri[1]", doc)
177 with {:ok, user} <- find_or_make_user(uri) do
178 avatar = make_avatar_object(doc)
179 if user.avatar != avatar do
180 change = Ecto.Changeset.change(user, %{avatar: avatar})
181 Repo.update(change)
182 else
183 {:ok, user}
184 end
185 end
186 end
187
188 def find_or_make_user(uri) do
189 query = from user in User,
190 where: user.local == false and fragment("? @> ?", user.info, ^%{uri: uri})
191
192 user = Repo.one(query)
193
194 if is_nil(user) do
195 make_user(uri)
196 else
197 {:ok, user}
198 end
199 end
200
201 def make_user(uri) do
202 with {:ok, info} <- gather_user_info(uri) do
203 data = %{
204 local: false,
205 name: info["name"],
206 nickname: info["nickname"] <> "@" <> info["host"],
207 ap_id: info["uri"],
208 info: info,
209 avatar: info["avatar"]
210 }
211 # TODO: Make remote user changeset
212 # SHould enforce fqn nickname
213 Repo.insert(Ecto.Changeset.change(%User{}, data))
214 end
215 end
216
217 # TODO: Just takes the first one for now.
218 def make_avatar_object(author_doc) do
219 href = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@href", author_doc)
220 type = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@type", author_doc)
221
222 if href do
223 %{
224 "type" => "Image",
225 "url" =>
226 [%{
227 "type" => "Link",
228 "mediaType" => type,
229 "href" => href
230 }]
231 }
232 else
233 nil
234 end
235 end
236
237 def gather_user_info(username) do
238 with {:ok, webfinger_data} <- WebFinger.finger(username),
239 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
240 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
241 else e ->
242 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
243 {:error, e}
244 end
245 end
246
247 # Regex-based 'parsing' so we don't have to pull in a full html parser
248 # It's a hack anyway. Maybe revisit this in the future
249 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
250 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
251 def get_atom_url(body) do
252 cond do
253 Regex.match?(@mastodon_regex, body) ->
254 [[_, match]] = Regex.scan(@mastodon_regex, body)
255 {:ok, match}
256 Regex.match?(@gs_regex, body) ->
257 [[_, match]] = Regex.scan(@gs_regex, body)
258 {:ok, match}
259 true ->
260 Logger.debug(fn -> "Couldn't find atom link in #{inspect(body)}" end)
261 {:error, "Couldn't find the atom link"}
262 end
263 end
264
265 def fetch_activity_from_html_url(url) do
266 with {:ok, %{body: body}} <- @httpoison.get(url),
267 {:ok, atom_url} <- get_atom_url(body),
268 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url) do
269 handle_incoming(body)
270 end
271 end
272 end