Preserve ids on favorites / 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
12 def feed_path(user) do
13 "#{user.ap_id}/feed.atom"
14 end
15
16 def pubsub_path(user) do
17 "#{Web.base_url}/push/hub/#{user.nickname}"
18 end
19
20 def salmon_path(user) do
21 "#{user.ap_id}/salmon"
22 end
23
24 def handle_incoming(xml_string) do
25 doc = parse_document(xml_string)
26 entries = :xmerl_xpath.string('//entry', doc)
27
28 activities = Enum.map(entries, fn (entry) ->
29 {:xmlObj, :string, object_type} = :xmerl_xpath.string('string(/entry/activity:object-type[1])', entry)
30 {:xmlObj, :string, verb} = :xmerl_xpath.string('string(/entry/activity:verb[1])', entry)
31
32 case verb do
33 'http://activitystrea.ms/schema/1.0/share' ->
34 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc), do: [activity, retweeted_activity]
35 'http://activitystrea.ms/schema/1.0/favorite' ->
36 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc), do: [activity, favorited_activity]
37 _ ->
38 case object_type do
39 'http://activitystrea.ms/schema/1.0/note' ->
40 with {:ok, activity} <- handle_note(entry, doc), do: activity
41 'http://activitystrea.ms/schema/1.0/comment' ->
42 with {:ok, activity} <- handle_note(entry, doc), do: activity
43 _ ->
44 Logger.error("Couldn't parse incoming document")
45 nil
46 end
47 end
48 end)
49 {:ok, activities}
50 end
51
52 def make_share(entry, doc, retweeted_activity) do
53 with {:ok, actor} <- find_make_or_update_user(doc),
54 %Object{} = object <- Object.get_cached_by_ap_id(retweeted_activity.data["object"]["id"]),
55 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
56 {:ok, activity, _object} = ActivityPub.announce(actor, object, id, false) do
57 {:ok, activity}
58 end
59 end
60
61 def handle_share(entry, doc) do
62 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry),
63 {:ok, retweeted_activity} <- handle_note(object, object),
64 {:ok, activity} <- make_share(entry, doc, retweeted_activity) do
65 {:ok, activity, retweeted_activity}
66 else
67 e -> {:error, e}
68 end
69 end
70
71 def make_favorite(entry, doc, favorited_activity) do
72 with {:ok, actor} <- find_make_or_update_user(doc),
73 %Object{} = object <- Object.get_cached_by_ap_id(favorited_activity.data["object"]["id"]),
74 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
75 {:ok, activity, _object} = ActivityPub.like(actor, object, id, false) do
76 {:ok, activity}
77 end
78 end
79
80 def get_or_try_fetching(entry) do
81 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
82 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
83 {:ok, activity}
84 else _e ->
85 with href when not is_nil(href) <- string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
86 {:ok, [favorited_activity]} <- fetch_activity_from_html_url(href) do
87 {:ok, favorited_activity}
88 end
89 end
90 end
91
92 def handle_favorite(entry, doc) do
93 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
94 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
95 {:ok, activity, favorited_activity}
96 else
97 e -> {:error, e}
98 end
99 end
100
101 def get_attachments(entry) do
102 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
103 |> Enum.map(fn (enclosure) ->
104 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
105 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
106 %{
107 "type" => "Attachment",
108 "url" => [%{
109 "type" => "Link",
110 "mediaType" => type,
111 "href" => href
112 }]
113 }
114 end
115 end)
116 |> Enum.filter(&(&1))
117 end
118
119 def handle_note(entry, doc \\ nil) do
120 content_html = string_from_xpath("//content[1]", entry)
121
122 [author] = :xmerl_xpath.string('//author[1]', doc)
123 {:ok, actor} = find_make_or_update_user(author)
124 inReplyTo = string_from_xpath("//thr:in-reply-to[1]/@ref", entry)
125
126 if !Object.get_cached_by_ap_id(inReplyTo) do
127 inReplyToHref = string_from_xpath("//thr:in-reply-to[1]/@href", entry)
128 if inReplyToHref do
129 fetch_activity_from_html_url(inReplyToHref)
130 end
131 end
132
133 context = (string_from_xpath("//ostatus:conversation[1]", entry) || "") |> String.trim
134
135 attachments = get_attachments(entry)
136
137 context = with %{data: %{"context" => context}} <- Object.get_cached_by_ap_id(inReplyTo) do
138 context
139 else _e ->
140 if String.length(context) > 0 do
141 context
142 else
143 ActivityPub.generate_context_id
144 end
145 end
146
147 to = [
148 "https://www.w3.org/ns/activitystreams#Public",
149 User.ap_followers(actor)
150 ]
151
152 mentions = :xmerl_xpath.string('//link[@rel="mentioned" and @ostatus:object-type="http://activitystrea.ms/schema/1.0/person"]', entry)
153 |> Enum.map(fn(person) -> string_from_xpath("@href", person) end)
154
155 to = to ++ mentions
156
157 date = string_from_xpath("//published", entry)
158 id = string_from_xpath("//id", entry)
159
160 object = %{
161 "id" => id,
162 "type" => "Note",
163 "to" => to,
164 "content" => content_html,
165 "published" => date,
166 "context" => context,
167 "actor" => actor.ap_id,
168 "attachment" => attachments
169 }
170
171 object = if inReplyTo do
172 Map.put(object, "inReplyTo", inReplyTo)
173 else
174 object
175 end
176
177 # TODO: Bail out sooner and use transaction.
178 if Object.get_by_ap_id(id) do
179 {:error, "duplicate activity"}
180 else
181 ActivityPub.create(to, actor, context, object, %{}, date, false)
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 avatar = make_avatar_object(doc)
189 if !user.local && user.avatar != avatar do
190 change = Ecto.Changeset.change(user, %{avatar: avatar})
191 Repo.update(change)
192 else
193 {:ok, user}
194 end
195 end
196 end
197
198 def find_or_make_user(uri) do
199 query = from user in User,
200 where: user.ap_id == ^uri
201
202 user = Repo.one(query)
203
204 if is_nil(user) do
205 make_user(uri)
206 else
207 {:ok, user}
208 end
209 end
210
211 def make_user(uri) do
212 with {:ok, info} <- gather_user_info(uri) do
213 data = %{
214 local: false,
215 name: info["name"],
216 nickname: info["nickname"] <> "@" <> info["host"],
217 ap_id: info["uri"],
218 info: info,
219 avatar: info["avatar"]
220 }
221 # TODO: Make remote user changeset
222 # SHould enforce fqn nickname
223 Repo.insert(Ecto.Changeset.change(%User{}, data))
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 with {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true),
281 {:ok, atom_url} <- get_atom_url(body),
282 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url, [], follow_redirect: true) do
283 handle_incoming(body)
284 end
285 end
286 end