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