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