AP refactoring.
[akkoma] / lib / pleroma / web / twitter_api / twitter_api.ex
1 defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
2 alias Pleroma.{User, Activity, Repo, Object}
3 alias Pleroma.Web.ActivityPub.ActivityPub
4 alias Pleroma.Web.ActivityPub.Utils
5 alias Pleroma.Web.TwitterAPI.Representers.{ActivityRepresenter, UserRepresenter}
6 alias Pleroma.Web.OStatus
7
8 import Ecto.Query
9
10 def to_for_user_and_mentions(user, mentions) do
11 default_to = [
12 User.ap_followers(user),
13 "https://www.w3.org/ns/activitystreams#Public"
14 ]
15
16 default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
17 end
18
19 def format_input(text, mentions) do
20 HtmlSanitizeEx.strip_tags(text)
21 |> String.replace("\n", "<br>")
22 |> add_user_links(mentions)
23 end
24
25 def attachments_from_ids(ids) do
26 Enum.map(ids || [], fn (media_id) ->
27 Repo.get(Object, media_id).data
28 end)
29 end
30
31 def get_replied_to_activity(id) when not is_nil(id) do
32 Repo.get(Activity, id)
33 end
34
35 def get_replied_to_activity(_), do: nil
36
37 def add_attachments(text, attachments) do
38 attachment_text = Enum.map(attachments, fn
39 (%{"url" => [%{"href" => href} | _]}) ->
40 "<a href='#{href}' class='attachment'>#{href}</a>"
41 _ -> ""
42 end)
43 Enum.join([text | attachment_text], "<br>")
44 end
45
46 def create_status(%User{} = user, %{"status" => status} = data) do
47 attachments = attachments_from_ids(data["media_ids"])
48 context = Utils.generate_context_id
49 mentions = parse_mentions(status)
50 content_html = status
51 |> format_input(mentions)
52 |> add_attachments(attachments)
53
54 to = to_for_user_and_mentions(user, mentions)
55 date = make_date()
56
57 inReplyTo = get_replied_to_activity(data["in_reply_to_status_id"])
58
59 # Wire up reply info.
60 [to, context, object, additional] =
61 if inReplyTo do
62 context = inReplyTo.data["context"]
63 to = to ++ [inReplyTo.data["actor"]]
64
65 object = %{
66 "type" => "Note",
67 "to" => to,
68 "content" => content_html,
69 "published" => date,
70 "context" => context,
71 "attachment" => attachments,
72 "actor" => user.ap_id,
73 "inReplyTo" => inReplyTo.data["object"]["id"],
74 "inReplyToStatusId" => inReplyTo.id,
75 }
76 additional = %{}
77
78 [to, context, object, additional]
79 else
80 object = %{
81 "type" => "Note",
82 "to" => to,
83 "content" => content_html,
84 "published" => date,
85 "context" => context,
86 "attachment" => attachments,
87 "actor" => user.ap_id
88 }
89 [to, context, object, %{}]
90 end
91
92 ActivityPub.create(to, user, context, object, additional, data)
93 end
94
95 def fetch_friend_statuses(user, opts \\ %{}) do
96 ActivityPub.fetch_activities([user.ap_id | user.following], opts)
97 |> activities_to_statuses(%{for: user})
98 end
99
100 def fetch_public_statuses(user, opts \\ %{}) do
101 opts = Map.put(opts, "local_only", true)
102 ActivityPub.fetch_public_activities(opts)
103 |> activities_to_statuses(%{for: user})
104 end
105
106 def fetch_public_and_external_statuses(user, opts \\ %{}) do
107 ActivityPub.fetch_public_activities(opts)
108 |> activities_to_statuses(%{for: user})
109 end
110
111 def fetch_user_statuses(user, opts \\ %{}) do
112 ActivityPub.fetch_activities([], opts)
113 |> activities_to_statuses(%{for: user})
114 end
115
116 def fetch_mentions(user, opts \\ %{}) do
117 ActivityPub.fetch_activities([user.ap_id], opts)
118 |> activities_to_statuses(%{for: user})
119 end
120
121 def fetch_conversation(user, id) do
122 with context when is_binary(context) <- conversation_id_to_context(id),
123 activities <- ActivityPub.fetch_activities_for_context(context),
124 statuses <- activities |> activities_to_statuses(%{for: user})
125 do
126 statuses
127 else _e ->
128 []
129 end
130 end
131
132 def fetch_status(user, id) do
133 with %Activity{} = activity <- Repo.get(Activity, id) do
134 activity_to_status(activity, %{for: user})
135 end
136 end
137
138 def follow(%User{} = follower, params) do
139 with {:ok, %User{} = followed} <- get_user(params),
140 {:ok, follower} <- User.follow(follower, followed),
141 {:ok, activity} <- ActivityPub.follow(follower, followed)
142 do
143 {:ok, follower, followed, activity}
144 else
145 err -> err
146 end
147 end
148
149 def unfollow(%User{} = follower, params) do
150 with { :ok, %User{} = unfollowed } <- get_user(params),
151 { :ok, follower, follow_activity } <- User.unfollow(follower, unfollowed),
152 { :ok, _activity } <- ActivityPub.insert(%{
153 "type" => "Undo",
154 "actor" => follower.ap_id,
155 "object" => follow_activity.data["id"], # get latest Follow for these users
156 "published" => make_date()
157 })
158 do
159 { :ok, follower, unfollowed }
160 else
161 err -> err
162 end
163 end
164
165 def favorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
166 object = Object.get_by_ap_id(object["id"])
167
168 {:ok, _like_activity, object} = ActivityPub.like(user, object)
169 new_data = activity.data
170 |> Map.put("object", object.data)
171
172 status = %{activity | data: new_data}
173 |> activity_to_status(%{for: user})
174
175 {:ok, status}
176 end
177
178 def unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
179 object = Object.get_by_ap_id(object["id"])
180
181 {:ok, object} = ActivityPub.unlike(user, object)
182 new_data = activity.data
183 |> Map.put("object", object.data)
184
185 status = %{activity | data: new_data}
186 |> activity_to_status(%{for: user})
187
188 {:ok, status}
189 end
190
191 def retweet(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
192 object = Object.get_by_ap_id(object["id"])
193
194 {:ok, _announce_activity, object} = ActivityPub.announce(user, object)
195 new_data = activity.data
196 |> Map.put("object", object.data)
197
198 status = %{activity | data: new_data}
199 |> activity_to_status(%{for: user})
200
201 {:ok, status}
202 end
203
204 def upload(%Plug.Upload{} = file, format \\ "xml") do
205 {:ok, object} = ActivityPub.upload(file)
206
207 url = List.first(object.data["url"])
208 href = url["href"]
209 type = url["mediaType"]
210
211 case format do
212 "xml" ->
213 # Fake this as good as possible...
214 """
215 <?xml version="1.0" encoding="UTF-8"?>
216 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
217 <mediaid>#{object.id}</mediaid>
218 <media_id>#{object.id}</media_id>
219 <media_id_string>#{object.id}</media_id_string>
220 <media_url>#{href}</media_url>
221 <mediaurl>#{href}</mediaurl>
222 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
223 </rsp>
224 """
225 "json" ->
226 %{
227 media_id: object.id,
228 media_id_string: "#{object.id}}",
229 media_url: href,
230 size: 0
231 } |> Poison.encode!
232 end
233 end
234
235 def parse_mentions(text) do
236 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
237 regex = ~r/@[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/
238
239 Regex.scan(regex, text)
240 |> List.flatten
241 |> Enum.uniq
242 |> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
243 |> Enum.filter(fn ({_match, user}) -> user end)
244 end
245
246 def add_user_links(text, mentions) do
247 mentions = mentions
248 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
249 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
250
251 # This replaces the mention with a unique reference first so it doesn't
252 # contain parts of other replaced mentions. There probably is a better
253 # solution for this...
254 step_one = mentions
255 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
256 String.replace(text, match, uuid)
257 end)
258
259 Enum.reduce(mentions, step_one, fn ({match, %User{ap_id: ap_id}, uuid}, text) ->
260 String.replace(text, uuid, "<a href='#{ap_id}'>#{match}</a>")
261 end)
262 end
263
264 def register_user(params) do
265 params = %{
266 nickname: params["nickname"],
267 name: params["fullname"],
268 bio: params["bio"],
269 email: params["email"],
270 password: params["password"],
271 password_confirmation: params["confirm"]
272 }
273
274 changeset = User.register_changeset(%User{}, params)
275
276 with {:ok, user} <- Repo.insert(changeset) do
277 {:ok, UserRepresenter.to_map(user)}
278 else
279 {:error, changeset} ->
280 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
281 |> Poison.encode!
282 {:error, %{error: errors}}
283 end
284 end
285
286 def get_user(user \\ nil, params) do
287 case params do
288 %{"user_id" => user_id} ->
289 case target = Repo.get(User, user_id) do
290 nil ->
291 {:error, "No user with such user_id"}
292 _ ->
293 {:ok, target}
294 end
295 %{"screen_name" => nickname} ->
296 case target = Repo.get_by(User, nickname: nickname) do
297 nil ->
298 {:error, "No user with such screen_name"}
299 _ ->
300 {:ok, target}
301 end
302 _ ->
303 if user do
304 {:ok, user}
305 else
306 {:error, "You need to specify screen_name or user_id"}
307 end
308 end
309 end
310
311 defp activities_to_statuses(activities, opts) do
312 Enum.map(activities, fn(activity) ->
313 activity_to_status(activity, opts)
314 end)
315 end
316
317 # For likes, fetch the liked activity, too.
318 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
319 actor = get_in(activity.data, ["actor"])
320 user = User.get_cached_by_ap_id(actor)
321 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
322
323 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
324 end
325
326 # For announces, fetch the announced activity and the user.
327 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
328 actor = get_in(activity.data, ["actor"])
329 user = User.get_cached_by_ap_id(actor)
330 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
331 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
332
333 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
334 end
335
336 defp activity_to_status(activity, opts) do
337 actor = get_in(activity.data, ["actor"])
338 user = User.get_cached_by_ap_id(actor)
339 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
340 mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
341 User.get_cached_by_ap_id(ap_id)
342 end)
343 |> Enum.filter(&(&1))
344
345 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
346 end
347
348 defp make_date do
349 DateTime.utc_now() |> DateTime.to_iso8601
350 end
351
352 def context_to_conversation_id(context) do
353 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
354 id
355 else _e ->
356 changeset = Object.context_mapping(context)
357 {:ok, %{id: id}} = Repo.insert(changeset)
358 id
359 end
360 end
361
362 def conversation_id_to_context(id) do
363 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
364 context
365 else _e ->
366 {:error, "No such conversation"}
367 end
368 end
369
370 def get_external_profile(for_user, uri) do
371 with {:ok, %User{} = user} <- OStatus.find_or_make_user(uri) do
372 {:ok, UserRepresenter.to_map(user, %{for: for_user})}
373 else _e ->
374 {:error, "Couldn't find user"}
375 end
376 end
377 end