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