Safety measures.
[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.TwitterAPI.Representers.{ActivityRepresenter, UserRepresenter}
5
6 import Ecto.Query
7
8 def to_for_user_and_mentions(user, mentions) do
9 default_to = [
10 User.ap_followers(user),
11 "https://www.w3.org/ns/activitystreams#Public"
12 ]
13
14 default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
15 end
16
17 def format_input(text, mentions) do
18 HtmlSanitizeEx.strip_tags(text)
19 |> String.replace("\n", "<br>")
20 |> add_user_links(mentions)
21 end
22
23 def attachments_from_ids(ids) do
24 Enum.map(ids || [], fn (media_id) ->
25 Repo.get(Object, media_id).data
26 end)
27 end
28
29 def get_replied_to_activity(id) when not is_nil(id) do
30 Repo.get(Activity, id)
31 end
32
33 def get_replied_to_activity(_), do: nil
34
35 def add_attachments(text, attachments) do
36 attachment_text = Enum.map(attachments, fn
37 (%{"url" => [%{"href" => href} | _]}) ->
38 "<a href='#{href}'>#{href}</a>"
39 _ -> ""
40 end)
41 Enum.join([text | attachment_text], "<br>")
42 end
43
44 def create_status(%User{} = user, %{"status" => status} = data) do
45 attachments = attachments_from_ids(data["media_ids"])
46 context = ActivityPub.generate_context_id
47 mentions = parse_mentions(status)
48 content_html = status
49 |> format_input(mentions)
50 |> add_attachments(attachments)
51
52 to = to_for_user_and_mentions(user, mentions)
53 date = make_date()
54
55 inReplyTo = get_replied_to_activity(data["in_reply_to_status_id"])
56
57 # Wire up reply info.
58 [to, context, object, additional] =
59 if inReplyTo do
60 context = inReplyTo.data["context"]
61 to = to ++ [inReplyTo.data["actor"]]
62
63 object = %{
64 "type" => "Note",
65 "to" => to,
66 "content" => content_html,
67 "published" => date,
68 "context" => context,
69 "attachment" => attachments,
70 "actor" => user.ap_id,
71 "inReplyTo" => inReplyTo.data["object"]["id"],
72 "inReplyToStatusId" => inReplyTo.id,
73 }
74 additional = %{}
75
76 [to, context, object, additional]
77 else
78 object = %{
79 "type" => "Note",
80 "to" => to,
81 "content" => content_html,
82 "published" => date,
83 "context" => context,
84 "attachment" => attachments,
85 "actor" => user.ap_id
86 }
87 [to, context, object, %{}]
88 end
89
90 ActivityPub.create(to, user, context, object, additional, data)
91 end
92
93 def fetch_friend_statuses(user, opts \\ %{}) do
94 ActivityPub.fetch_activities([user.ap_id | user.following], opts)
95 |> activities_to_statuses(%{for: user})
96 end
97
98 def fetch_public_statuses(user, opts \\ %{}) do
99 opts = Map.put(opts, "local_only", true)
100 ActivityPub.fetch_public_activities(opts)
101 |> activities_to_statuses(%{for: user})
102 end
103
104 def fetch_public_and_external_statuses(user, opts \\ %{}) do
105 ActivityPub.fetch_public_activities(opts)
106 |> activities_to_statuses(%{for: user})
107 end
108
109 def fetch_user_statuses(user, opts \\ %{}) do
110 ActivityPub.fetch_activities([], opts)
111 |> activities_to_statuses(%{for: user})
112 end
113
114 def fetch_mentions(user, opts \\ %{}) do
115 ActivityPub.fetch_activities([user.ap_id], opts)
116 |> activities_to_statuses(%{for: user})
117 end
118
119 def fetch_conversation(user, id) do
120 with context when is_binary(context) <- conversation_id_to_context(id),
121 activities <- ActivityPub.fetch_activities_for_context(context),
122 statuses <- activities |> activities_to_statuses(%{for: user})
123 do
124 statuses
125 else _e ->
126 []
127 end
128 end
129
130 def fetch_status(user, id) do
131 with %Activity{} = activity <- Repo.get(Activity, id) do
132 activity_to_status(activity, %{for: user})
133 end
134 end
135
136 def follow(%User{} = follower, params) do
137 with {:ok, %User{} = followed} <- get_user(params),
138 {:ok, follower} <- User.follow(follower, followed),
139 {:ok, activity} <- ActivityPub.insert(%{
140 "type" => "Follow",
141 "actor" => follower.ap_id,
142 "to" => [followed.ap_id],
143 "object" => followed.ap_id,
144 "published" => make_date()
145 })
146 do
147 # TODO move all this to ActivityPub
148 Pleroma.Web.Federator.enqueue(:publish, activity)
149 {:ok, follower, followed, activity}
150 else
151 err -> err
152 end
153 end
154
155 def unfollow(%User{} = follower, params) do
156 with {:ok, %User{} = unfollowed} <- get_user(params),
157 {:ok, follower} <- User.unfollow(follower, unfollowed)
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 Enum.reduce(mentions, text, fn ({match, %User{ap_id: ap_id}}, text) -> String.replace(text, match, "<a href='#{ap_id}'>#{match}</a>") end)
248 end
249
250 def register_user(params) do
251 params = %{
252 nickname: params["nickname"],
253 name: params["fullname"],
254 bio: params["bio"],
255 email: params["email"],
256 password: params["password"],
257 password_confirmation: params["confirm"]
258 }
259
260 changeset = User.register_changeset(%User{}, params)
261
262 with {:ok, user} <- Repo.insert(changeset) do
263 {:ok, UserRepresenter.to_map(user)}
264 else
265 {:error, changeset} ->
266 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
267 |> Poison.encode!
268 {:error, %{error: errors}}
269 end
270 end
271
272 def get_user(user \\ nil, params) do
273 case params do
274 %{"user_id" => user_id} ->
275 case target = Repo.get(User, user_id) do
276 nil ->
277 {:error, "No user with such user_id"}
278 _ ->
279 {:ok, target}
280 end
281 %{"screen_name" => nickname} ->
282 case target = Repo.get_by(User, nickname: nickname) do
283 nil ->
284 {:error, "No user with such screen_name"}
285 _ ->
286 {:ok, target}
287 end
288 _ ->
289 if user do
290 {:ok, user}
291 else
292 {:error, "You need to specify screen_name or user_id"}
293 end
294 end
295 end
296
297 defp activities_to_statuses(activities, opts) do
298 Enum.map(activities, fn(activity) ->
299 activity_to_status(activity, opts)
300 end)
301 end
302
303 # For likes, fetch the liked activity, too.
304 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
305 actor = get_in(activity.data, ["actor"])
306 user = User.get_cached_by_ap_id(actor)
307 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
308
309 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
310 end
311
312 # For announces, fetch the announced activity and the user.
313 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
314 actor = get_in(activity.data, ["actor"])
315 user = User.get_cached_by_ap_id(actor)
316 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
317 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
318
319 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
320 end
321
322 defp activity_to_status(activity, opts) do
323 actor = get_in(activity.data, ["actor"])
324 user = User.get_cached_by_ap_id(actor)
325 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
326 mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
327 User.get_cached_by_ap_id(ap_id)
328 end)
329 |> Enum.filter(&(&1))
330
331 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
332 end
333
334 defp make_date do
335 DateTime.utc_now() |> DateTime.to_iso8601
336 end
337
338 def context_to_conversation_id(context) do
339 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
340 id
341 else _e ->
342 changeset = Object.context_mapping(context)
343 {:ok, %{id: id}} = Repo.insert(changeset)
344 id
345 end
346 end
347
348 def conversation_id_to_context(id) do
349 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
350 context
351 else _e ->
352 {:error, "No such conversation"}
353 end
354 end
355 end