Merge branch 'develop' of ssh.gitgud.io:lambadalambda/pleroma into develop
[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
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} <- NoteHandler.handle_note(entry, doc), do: activity
45 'http://activitystrea.ms/schema/1.0/comment' ->
46 with {:ok, activity} <- NoteHandler.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 {:ok, retweeted_activity} <- get_or_build_object(entry),
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_build_object(entry) do
84 with {:ok, activity} <- get_or_try_fetching(entry) do
85 {:ok, activity}
86 else
87 _e ->
88 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry) do
89 NoteHandler.handle_note(object, object)
90 end
91 end
92 end
93
94 def get_or_try_fetching(entry) do
95 Logger.debug("Trying to get entry from db")
96 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
97 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
98 {:ok, activity}
99 else e ->
100 Logger.debug("Couldn't get, will try to fetch")
101 with href when not is_nil(href) <- string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
102 {:ok, [favorited_activity]} <- fetch_activity_from_html_url(href) do
103 {:ok, favorited_activity}
104 else e -> Logger.debug("Couldn't find href: #{inspect(e)}")
105 end
106 end
107 end
108
109 def handle_favorite(entry, doc) do
110 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
111 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
112 {:ok, activity, favorited_activity}
113 else
114 e -> {:error, e}
115 end
116 end
117
118 def get_attachments(entry) do
119 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
120 |> Enum.map(fn (enclosure) ->
121 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
122 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
123 %{
124 "type" => "Attachment",
125 "url" => [%{
126 "type" => "Link",
127 "mediaType" => type,
128 "href" => href
129 }]
130 }
131 end
132 end)
133 |> Enum.filter(&(&1))
134 end
135
136 @doc """
137 Gets the content from a an entry. Will add the cw text to the body for cw'd
138 Mastodon notes.
139 """
140 def get_content(entry) do
141 base_content = string_from_xpath("//content", entry)
142
143 with scope when not is_nil(scope) <- string_from_xpath("//mastodon:scope", entry),
144 cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
145 "<span class='mastodon-cw'>#{cw}</span><br>#{base_content}"
146 else _e -> base_content
147 end
148 end
149
150 def get_tags(entry) do
151 :xmerl_xpath.string('//category', entry)
152 |> Enum.map(fn (category) -> string_from_xpath("/category/@term", category) end)
153 end
154
155 def find_make_or_update_user(doc) do
156 uri = string_from_xpath("//author/uri[1]", doc)
157 with {:ok, user} <- find_or_make_user(uri) do
158 avatar = make_avatar_object(doc)
159 if !user.local && user.avatar != avatar do
160 change = Ecto.Changeset.change(user, %{avatar: avatar})
161 Repo.update(change)
162 else
163 {:ok, user}
164 end
165 end
166 end
167
168 def find_or_make_user(uri) do
169 query = from user in User,
170 where: user.ap_id == ^uri
171
172 user = Repo.one(query)
173
174 if is_nil(user) do
175 make_user(uri)
176 else
177 {:ok, user}
178 end
179 end
180
181 def make_user(uri) do
182 with {:ok, info} <- gather_user_info(uri) do
183 data = %{
184 name: info["name"],
185 nickname: info["nickname"] <> "@" <> info["host"],
186 ap_id: info["uri"],
187 info: info,
188 avatar: info["avatar"]
189 }
190 with %User{} = user <- User.get_by_ap_id(data.ap_id) do
191 {:ok, user}
192 else _e ->
193 cs = User.remote_user_creation(data)
194 Repo.insert(cs)
195 end
196 end
197 end
198
199 # TODO: Just takes the first one for now.
200 def make_avatar_object(author_doc) do
201 href = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@href", author_doc)
202 type = string_from_xpath("//author[1]/link[@rel=\"avatar\"]/@type", author_doc)
203
204 if href do
205 %{
206 "type" => "Image",
207 "url" =>
208 [%{
209 "type" => "Link",
210 "mediaType" => type,
211 "href" => href
212 }]
213 }
214 else
215 nil
216 end
217 end
218
219 def gather_user_info(username) do
220 with {:ok, webfinger_data} <- WebFinger.finger(username),
221 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
222 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
223 else e ->
224 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
225 {:error, e}
226 end
227 end
228
229 # Regex-based 'parsing' so we don't have to pull in a full html parser
230 # It's a hack anyway. Maybe revisit this in the future
231 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
232 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
233 @gs_classic_regex ~r/<link rel="alternate" href="(.*)" type="application\/atom\+xml" title=.*>/
234 def get_atom_url(body) do
235 cond do
236 Regex.match?(@mastodon_regex, body) ->
237 [[_, match]] = Regex.scan(@mastodon_regex, body)
238 {:ok, match}
239 Regex.match?(@gs_regex, body) ->
240 [[_, match]] = Regex.scan(@gs_regex, body)
241 {:ok, match}
242 Regex.match?(@gs_classic_regex, body) ->
243 [[_, match]] = Regex.scan(@gs_classic_regex, body)
244 {:ok, match}
245 true ->
246 Logger.debug(fn -> "Couldn't find atom link in #{inspect(body)}" end)
247 {:error, "Couldn't find the atom link"}
248 end
249 end
250
251 def fetch_activity_from_html_url(url) do
252 Logger.debug("Trying to fetch #{url}")
253 with {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true),
254 {:ok, atom_url} <- get_atom_url(body),
255 {:ok, %{status_code: code, body: body}} when code in 200..299 <- @httpoison.get(atom_url, [], follow_redirect: true) do
256 Logger.debug("Got document from #{url}, handling...")
257 handle_incoming(body)
258 else e -> Logger.debug("Couldn't get #{url}: #{inspect(e)}")
259 end
260 end
261 end