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