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