AP refactoring.
[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 handle_note(entry, doc \\ nil) do
137 content_html = get_content(entry)
138
139 [author] = :xmerl_xpath.string('//author[1]', doc)
140 {:ok, actor} = find_make_or_update_user(author)
141 inReplyTo = string_from_xpath("//thr:in-reply-to[1]/@ref", entry)
142
143 if inReplyTo && !Object.get_cached_by_ap_id(inReplyTo) do
144 inReplyToHref = string_from_xpath("//thr:in-reply-to[1]/@href", entry)
145 if inReplyToHref do
146 fetch_activity_from_html_url(inReplyToHref)
147 else
148 Logger.debug("Couldn't find a href link to #{inReplyTo}")
149 end
150 end
151
152 context = (string_from_xpath("//ostatus:conversation[1]", entry) || "") |> String.trim
153
154 attachments = get_attachments(entry)
155
156 context = with %{data: %{"context" => context}} <- Object.get_cached_by_ap_id(inReplyTo) do
157 context
158 else _e ->
159 if String.length(context) > 0 do
160 context
161 else
162 Utils.generate_context_id
163 end
164 end
165
166 to = [
167 "https://www.w3.org/ns/activitystreams#Public",
168 User.ap_followers(actor)
169 ]
170
171 mentions = :xmerl_xpath.string('//link[@rel="mentioned" and @ostatus:object-type="http://activitystrea.ms/schema/1.0/person"]', entry)
172 |> Enum.map(fn(person) -> string_from_xpath("@href", person) end)
173
174 to = to ++ mentions
175
176 date = string_from_xpath("//published", entry)
177 id = string_from_xpath("//id", entry)
178
179 object = %{
180 "id" => id,
181 "type" => "Note",
182 "to" => to,
183 "content" => content_html,
184 "published" => date,
185 "context" => context,
186 "actor" => actor.ap_id,
187 "attachment" => attachments
188 }
189
190 object = if inReplyTo do
191 Map.put(object, "inReplyTo", inReplyTo)
192 else
193 object
194 end
195
196 # TODO: Bail out sooner and use transaction.
197 if Object.get_by_ap_id(id) do
198 {:ok, Activity.get_create_activity_by_object_ap_id(id)}
199 else
200 ActivityPub.create(to, actor, context, object, %{}, date, false)
201 end
202 end
203
204 def find_make_or_update_user(doc) do
205 uri = string_from_xpath("//author/uri[1]", doc)
206 with {:ok, user} <- find_or_make_user(uri) do
207 avatar = make_avatar_object(doc)
208 if !user.local && user.avatar != avatar do
209 change = Ecto.Changeset.change(user, %{avatar: avatar})
210 Repo.update(change)
211 else
212 {:ok, user}
213 end
214 end
215 end
216
217 def find_or_make_user(uri) do
218 query = from user in User,
219 where: user.ap_id == ^uri
220
221 user = Repo.one(query)
222
223 if is_nil(user) do
224 make_user(uri)
225 else
226 {:ok, user}
227 end
228 end
229
230 def make_user(uri) do
231 with {:ok, info} <- gather_user_info(uri) do
232 data = %{
233 name: info["name"],
234 nickname: info["nickname"] <> "@" <> info["host"],
235 ap_id: info["uri"],
236 info: info,
237 avatar: info["avatar"]
238 }
239 with %User{} = user <- User.get_by_ap_id(data.ap_id) do
240 {:ok, user}
241 else _e ->
242 cs = User.remote_user_creation(data)
243 Repo.insert(cs)
244 end
245 end
246 end
247
248 # TODO: Just takes the first one for now.
249 def make_avatar_object(author_doc) do
250 href = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@href", author_doc)
251 type = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@type", author_doc)
252
253 if href do
254 %{
255 "type" => "Image",
256 "url" =>
257 [%{
258 "type" => "Link",
259 "mediaType" => type,
260 "href" => href
261 }]
262 }
263 else
264 nil
265 end
266 end
267
268 def gather_user_info(username) do
269 with {:ok, webfinger_data} <- WebFinger.finger(username),
270 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
271 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
272 else e ->
273 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
274 {:error, e}
275 end
276 end
277
278 # Regex-based 'parsing' so we don't have to pull in a full html parser
279 # It's a hack anyway. Maybe revisit this in the future
280 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
281 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
282 @gs_classic_regex ~r/<link rel="alternate" href="(.*)" type="application\/atom\+xml" title=.*>/
283 def get_atom_url(body) do
284 cond do
285 Regex.match?(@mastodon_regex, body) ->
286 [[_, match]] = Regex.scan(@mastodon_regex, body)
287 {:ok, match}
288 Regex.match?(@gs_regex, body) ->
289 [[_, match]] = Regex.scan(@gs_regex, body)
290 {:ok, match}
291 Regex.match?(@gs_classic_regex, body) ->
292 [[_, match]] = Regex.scan(@gs_classic_regex, body)
293 {:ok, match}
294 true ->
295 Logger.debug(fn -> "Couldn't find atom link in #{inspect(body)}" end)
296 {:error, "Couldn't find the atom link"}
297 end
298 end
299
300 def fetch_activity_from_html_url(url) do
301 Logger.debug("Trying to fetch #{url}")
302 with {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true),
303 {:ok, atom_url} <- get_atom_url(body),
304 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url, [], follow_redirect: true) do
305 Logger.debug("Got document from #{url}, handling...")
306 handle_incoming(body)
307 else e -> Logger.debug("Couldn't get #{url}: #{inspect(e)}")
308 end
309 end
310 end