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