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