Bio can actually be nil.
[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, NoteHandler}
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 Logger.debug("Handling #{verb}")
34
35 case verb do
36 'http://activitystrea.ms/schema/1.0/follow' ->
37 with {:ok, activity} <- FollowHandler.handle(entry, doc), do: activity
38 'http://activitystrea.ms/schema/1.0/share' ->
39 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc), do: [activity, retweeted_activity]
40 'http://activitystrea.ms/schema/1.0/favorite' ->
41 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc), do: [activity, favorited_activity]
42 _ ->
43 case object_type do
44 'http://activitystrea.ms/schema/1.0/note' ->
45 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
46 'http://activitystrea.ms/schema/1.0/comment' ->
47 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
48 _ ->
49 Logger.error("Couldn't parse incoming document")
50 nil
51 end
52 end
53 end)
54 {:ok, activities}
55 end
56
57 def make_share(entry, doc, retweeted_activity) do
58 with {:ok, actor} <- find_make_or_update_user(doc),
59 %Object{} = object <- Object.get_by_ap_id(retweeted_activity.data["object"]["id"]),
60 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
61 {:ok, activity, _object} = ActivityPub.announce(actor, object, id, false) do
62 {:ok, activity}
63 end
64 end
65
66 def handle_share(entry, doc) do
67 with {:ok, retweeted_activity} <- get_or_build_object(entry),
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_build_object(entry) do
85 with {:ok, activity} <- get_or_try_fetching(entry) do
86 {:ok, activity}
87 else
88 _e ->
89 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry) do
90 NoteHandler.handle_note(object, object)
91 end
92 end
93 end
94
95 def get_or_try_fetching(entry) do
96 Logger.debug("Trying to get entry from db")
97 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
98 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
99 {:ok, activity}
100 else e ->
101 Logger.debug("Couldn't get, will try to fetch")
102 with href when not is_nil(href) <- string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
103 {:ok, [favorited_activity]} <- fetch_activity_from_html_url(href) do
104 {:ok, favorited_activity}
105 else e -> Logger.debug("Couldn't find href: #{inspect(e)}")
106 end
107 end
108 end
109
110 def handle_favorite(entry, doc) do
111 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
112 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
113 {:ok, activity, favorited_activity}
114 else
115 e -> {:error, e}
116 end
117 end
118
119 def get_attachments(entry) do
120 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
121 |> Enum.map(fn (enclosure) ->
122 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
123 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
124 %{
125 "type" => "Attachment",
126 "url" => [%{
127 "type" => "Link",
128 "mediaType" => type,
129 "href" => href
130 }]
131 }
132 end
133 end)
134 |> Enum.filter(&(&1))
135 end
136
137 @doc """
138 Gets the content from a an entry. Will add the cw text to the body for cw'd
139 Mastodon notes.
140 """
141 def get_content(entry) do
142 base_content = string_from_xpath("//content", entry)
143
144 with scope when not is_nil(scope) <- string_from_xpath("//mastodon:scope", entry),
145 cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
146 "<span class='mastodon-cw'>#{cw}</span><br>#{base_content}"
147 else _e -> base_content
148 end
149 end
150
151 def get_tags(entry) do
152 :xmerl_xpath.string('//category', entry)
153 |> Enum.map(fn (category) -> string_from_xpath("/category/@term", category) |> String.downcase end)
154 end
155
156 def maybe_update(doc, user) do
157 old_data = %{
158 avatar: user.avatar,
159 bio: user.bio,
160 name: user.name
161 }
162
163 with false <- user.local,
164 avatar <- make_avatar_object(doc),
165 bio <- string_from_xpath("//author[1]/summary", doc),
166 name when not is_nil(name) <- string_from_xpath("//author[1]/poco:displayName", doc),
167 new_data <- %{avatar: avatar, name: name, bio: bio},
168 false <- new_data == old_data do
169 change = Ecto.Changeset.change(user, new_data)
170 Repo.update(change)
171 else e ->
172 {:ok, user}
173 end
174 end
175
176 def find_make_or_update_user(doc) do
177 uri = string_from_xpath("//author/uri[1]", doc)
178 with {:ok, user} <- find_or_make_user(uri) do
179 maybe_update(doc, user)
180 end
181 end
182
183 def find_or_make_user(uri) do
184 query = from user in User,
185 where: user.ap_id == ^uri
186
187 user = Repo.one(query)
188
189 if is_nil(user) do
190 make_user(uri)
191 else
192 {:ok, user}
193 end
194 end
195
196 def insert_or_update_user(data) do
197 cs = User.remote_user_creation(data)
198 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
199 end
200
201 def make_user(uri) do
202 with {:ok, info} <- gather_user_info(uri) do
203 data = %{
204 name: info["name"],
205 nickname: info["nickname"] <> "@" <> info["host"],
206 ap_id: info["uri"],
207 info: info,
208 avatar: info["avatar"],
209 bio: info["bio"]
210 }
211 with %User{} = user <- User.get_by_ap_id(data.ap_id) do
212 {:ok, user}
213 else _e -> insert_or_update_user(data)
214 end
215 end
216 end
217
218 # TODO: Just takes the first one for now.
219 def make_avatar_object(author_doc) do
220 href = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@href", author_doc)
221 type = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@type", author_doc)
222
223 if href do
224 %{
225 "type" => "Image",
226 "url" =>
227 [%{
228 "type" => "Link",
229 "mediaType" => type,
230 "href" => href
231 }]
232 }
233 else
234 nil
235 end
236 end
237
238 def gather_user_info(username) do
239 with {:ok, webfinger_data} <- WebFinger.finger(username),
240 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
241 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
242 else e ->
243 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
244 {:error, e}
245 end
246 end
247
248 # Regex-based 'parsing' so we don't have to pull in a full html parser
249 # It's a hack anyway. Maybe revisit this in the future
250 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
251 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
252 @gs_classic_regex ~r/<link rel="alternate" href="(.*)" type="application\/atom\+xml" title=.*>/
253 def get_atom_url(body) do
254 cond do
255 Regex.match?(@mastodon_regex, body) ->
256 [[_, match]] = Regex.scan(@mastodon_regex, body)
257 {:ok, match}
258 Regex.match?(@gs_regex, body) ->
259 [[_, match]] = Regex.scan(@gs_regex, body)
260 {:ok, match}
261 Regex.match?(@gs_classic_regex, body) ->
262 [[_, match]] = Regex.scan(@gs_classic_regex, body)
263 {:ok, match}
264 true ->
265 Logger.debug(fn -> "Couldn't find atom link in #{inspect(body)}" end)
266 {:error, "Couldn't find the atom link"}
267 end
268 end
269
270 def fetch_activity_from_html_url(url) do
271 Logger.debug("Trying to fetch #{url}")
272 with {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000),
273 {:ok, atom_url} <- get_atom_url(body),
274 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do
275 Logger.debug("Got document from #{url}, handling...")
276 handle_incoming(body)
277 else e -> Logger.debug("Couldn't get #{url}: #{inspect(e)}")
278 end
279 end
280 end