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