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