0a4361393b3bacc601a10b670c60f0e882ea263a
[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}
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 {:ok, activity, _object} = ActivityPub.announce(actor, object, false) do
56 {:ok, activity}
57 end
58 end
59
60 def handle_share(entry, doc) do
61 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry),
62 {:ok, retweeted_activity} <- handle_note(object, object),
63 {:ok, activity} <- make_share(entry, doc, retweeted_activity) do
64 {:ok, activity, retweeted_activity}
65 else
66 e -> {:error, e}
67 end
68 end
69
70 def make_favorite(_entry, doc, favorited_activity) do
71 with {:ok, actor} <- find_make_or_update_user(doc),
72 %Object{} = object <- Object.get_cached_by_ap_id(favorited_activity.data["object"]["id"]),
73 {:ok, activity, _object} = ActivityPub.like(actor, object, false) do
74 {:ok, activity}
75 end
76 end
77
78 def handle_favorite(entry, doc) do
79 with href when not is_nil(href) <- string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
80 {:ok, [favorited_activity]} <- fetch_activity_from_html_url(href),
81 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
82 {:ok, activity, favorited_activity}
83 else
84 e -> {:error, e}
85 end
86 end
87
88 def get_attachments(entry) do
89 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
90 |> Enum.map(fn (enclosure) ->
91 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
92 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
93 %{
94 "type" => "Attachment",
95 "url" => [%{
96 "type" => "Link",
97 "mediaType" => type,
98 "href" => href
99 }]
100 }
101 end
102 end)
103 |> Enum.filter(&(&1))
104 end
105
106 def handle_note(entry, doc \\ nil) do
107 content_html = string_from_xpath("//content[1]", entry)
108
109 [author] = :xmerl_xpath.string('//author[1]', doc)
110 {:ok, actor} = find_make_or_update_user(author)
111 inReplyTo = string_from_xpath("//thr:in-reply-to[1]/@ref", entry)
112
113 context = (string_from_xpath("//ostatus:conversation[1]", entry) || "") |> String.trim
114
115 attachments = get_attachments(entry)
116
117 context = with %{data: %{"context" => context}} <- Object.get_cached_by_ap_id(inReplyTo) do
118 context
119 else _e ->
120 if String.length(context) > 0 do
121 context
122 else
123 ActivityPub.generate_context_id
124 end
125 end
126
127 to = [
128 "https://www.w3.org/ns/activitystreams#Public"
129 ]
130
131 mentions = :xmerl_xpath.string('//link[@rel="mentioned" and @ostatus:object-type="http://activitystrea.ms/schema/1.0/person"]', entry)
132 |> Enum.map(fn(person) -> string_from_xpath("@href", person) end)
133
134 to = to ++ mentions
135
136 date = string_from_xpath("//published", entry)
137 id = string_from_xpath("//id", entry)
138
139 object = %{
140 "id" => id,
141 "type" => "Note",
142 "to" => to,
143 "content" => content_html,
144 "published" => date,
145 "context" => context,
146 "actor" => actor.ap_id,
147 "attachment" => attachments
148 }
149
150 object = if inReplyTo do
151 Map.put(object, "inReplyTo", inReplyTo)
152 else
153 object
154 end
155
156 # TODO: Bail out sooner and use transaction.
157 if Object.get_by_ap_id(id) do
158 {:error, "duplicate activity"}
159 else
160 ActivityPub.create(to, actor, context, object, %{}, date, false)
161 end
162 end
163
164 def find_make_or_update_user(doc) do
165 uri = string_from_xpath("//author/uri[1]", doc)
166 with {:ok, user} <- find_or_make_user(uri) do
167 avatar = make_avatar_object(doc)
168 if user.avatar != avatar do
169 change = Ecto.Changeset.change(user, %{avatar: avatar})
170 Repo.update(change)
171 else
172 {:ok, user}
173 end
174 end
175 end
176
177 def find_or_make_user(uri) do
178 query = from user in User,
179 where: user.local == false and fragment("? @> ?", user.info, ^%{uri: uri})
180
181 user = Repo.one(query)
182
183 if is_nil(user) do
184 make_user(uri)
185 else
186 {:ok, user}
187 end
188 end
189
190 def make_user(uri) do
191 with {:ok, info} <- gather_user_info(uri) do
192 data = %{
193 local: false,
194 name: info["name"],
195 nickname: info["nickname"] <> "@" <> info["host"],
196 ap_id: info["uri"],
197 info: info,
198 avatar: info["avatar"]
199 }
200 # TODO: Make remote user changeset
201 # SHould enforce fqn nickname
202 Repo.insert(Ecto.Changeset.change(%User{}, data))
203 end
204 end
205
206 # TODO: Just takes the first one for now.
207 def make_avatar_object(author_doc) do
208 href = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@href", author_doc)
209 type = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@type", author_doc)
210
211 if href do
212 %{
213 "type" => "Image",
214 "url" =>
215 [%{
216 "type" => "Link",
217 "mediaType" => type,
218 "href" => href
219 }]
220 }
221 else
222 nil
223 end
224 end
225
226 def gather_user_info(username) do
227 with {:ok, webfinger_data} <- WebFinger.finger(username),
228 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
229 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
230 else e ->
231 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
232 {:error, e}
233 end
234 end
235
236 # Regex-based 'parsing' so we don't have to pull in a full html parser
237 # It's a hack anyway. Maybe revisit this in the future
238 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
239 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
240 def get_atom_url(body) do
241 cond do
242 Regex.match?(@mastodon_regex, body) ->
243 [[_, match]] = Regex.scan(@mastodon_regex, body)
244 {:ok, match}
245 Regex.match?(@gs_regex, body) ->
246 [[_, match]] = Regex.scan(@gs_regex, body)
247 {:ok, match}
248 true ->
249 Logger.debug(fn -> "Couldn't find atom link in #{inspect(body)}" end)
250 {:error, "Couldn't find the atom link"}
251 end
252 end
253
254 def fetch_activity_from_html_url(url) do
255 with {:ok, %{body: body}} <- @httpoison.get(url),
256 {:ok, atom_url} <- get_atom_url(body),
257 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url) do
258 handle_incoming(body)
259 end
260 end
261 end