Revert "Add remote follow path to webfinger."
[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 handle_incoming(xml_string) do
26 with doc when doc != :error <- parse_document(xml_string) do
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 Logger.debug("Handling #{verb}")
33
34 try do
35 case verb do
36 'http://activitystrea.ms/schema/1.0/delete' ->
37 with {:ok, activity} <- DeleteHandler.handle_delete(entry, doc), do: activity
38 'http://activitystrea.ms/schema/1.0/follow' ->
39 with {:ok, activity} <- FollowHandler.handle(entry, doc), do: activity
40 'http://activitystrea.ms/schema/1.0/share' ->
41 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc), do: [activity, retweeted_activity]
42 'http://activitystrea.ms/schema/1.0/favorite' ->
43 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc), do: [activity, favorited_activity]
44 _ ->
45 case object_type do
46 'http://activitystrea.ms/schema/1.0/note' ->
47 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
48 'http://activitystrea.ms/schema/1.0/comment' ->
49 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
50 _ ->
51 Logger.error("Couldn't parse incoming document")
52 nil
53 end
54 end
55 rescue
56 e ->
57 Logger.error("Error occured while handling activity")
58 Logger.error(xml_string)
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 _ ->
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.
153 """
154 def get_content(entry) do
155 string_from_xpath("//content", entry)
156 end
157
158 @doc """
159 Get the cw that mastodon uses.
160 """
161 def get_cw(entry) do
162 with scope when not is_nil(scope) <- string_from_xpath("//mastodon:scope", entry),
163 cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
164 cw
165 else _e -> nil
166 end
167 end
168
169 def get_tags(entry) do
170 :xmerl_xpath.string('//category', entry)
171 |> Enum.map(fn (category) -> string_from_xpath("/category/@term", category) end)
172 |> Enum.filter(&(&1))
173 |> Enum.map(&String.downcase/1)
174 end
175
176 def maybe_update(doc, user) do
177 old_data = %{
178 avatar: user.avatar,
179 bio: user.bio,
180 name: user.name,
181 info: user.info
182 }
183
184 with false <- user.local,
185 avatar <- make_avatar_object(doc),
186 bio <- string_from_xpath("//author[1]/summary", doc),
187 name <- string_from_xpath("//author[1]/poco:displayName", doc),
188 info <- Map.put(user.info, "banner", make_avatar_object(doc, "header") || user.info["banner"]),
189 new_data <- %{avatar: avatar || old_data.avatar, name: name || old_data.name, bio: bio || old_data.bio, info: info || old_data.info},
190 false <- new_data == old_data do
191 change = Ecto.Changeset.change(user, new_data)
192 Repo.update(change)
193 else _ ->
194 {:ok, user}
195 end
196 end
197
198 def find_make_or_update_user(doc) do
199 uri = string_from_xpath("//author/uri[1]", doc)
200 with {:ok, user} <- find_or_make_user(uri) do
201 maybe_update(doc, user)
202 end
203 end
204
205 def find_or_make_user(uri) do
206 query = from user in User,
207 where: user.ap_id == ^uri
208
209 user = Repo.one(query)
210
211 if is_nil(user) do
212 make_user(uri)
213 else
214 {:ok, user}
215 end
216 end
217
218 def insert_or_update_user(data) do
219 cs = User.remote_user_creation(data)
220 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
221 end
222
223 def make_user(uri, update \\ false) do
224 with {:ok, info} <- gather_user_info(uri) do
225 data = %{
226 name: info["name"],
227 nickname: info["nickname"] <> "@" <> info["host"],
228 ap_id: info["uri"],
229 info: info,
230 avatar: info["avatar"],
231 bio: info["bio"]
232 }
233 with false <- update,
234 %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