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