twitter/mastodon api: always use mediaproxy URLs in attachments
[akkoma] / lib / pleroma / web / twitter_api / twitter_api.ex
1 defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
2 alias Pleroma.{UserInviteToken, User, Activity, Repo, Object}
3 alias Pleroma.Web.ActivityPub.ActivityPub
4 alias Pleroma.Web.TwitterAPI.UserView
5 alias Pleroma.Web.{OStatus, CommonAPI}
6 alias Pleroma.Web.MediaProxy
7 import Ecto.Query
8
9 @instance Application.get_env(:pleroma, :instance)
10 @httpoison Application.get_env(:pleroma, :httpoison)
11 @registrations_open Keyword.get(@instance, :registrations_open)
12
13 def create_status(%User{} = user, %{"status" => _} = data) do
14 CommonAPI.post(user, data)
15 end
16
17 def delete(%User{} = user, id) do
18 with %Activity{data: %{"type" => type}} <- Repo.get(Activity, id),
19 {:ok, activity} <- CommonAPI.delete(id, user) do
20 {:ok, activity}
21 end
22 end
23
24 @activitypub Application.get_env(:pleroma, :activitypub)
25 @follow_handshake_timeout Keyword.get(@activitypub, :follow_handshake_timeout)
26
27 def follow(%User{} = follower, params) do
28 with {:ok, %User{} = followed} <- get_user(params),
29 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
30 {:ok, activity} <- ActivityPub.follow(follower, followed),
31 {:ok, follower, followed} <-
32 User.wait_and_refresh(@follow_handshake_timeout, follower, followed) do
33 {:ok, follower, followed, activity}
34 else
35 err -> err
36 end
37 end
38
39 def unfollow(%User{} = follower, params) do
40 with {:ok, %User{} = unfollowed} <- get_user(params),
41 {:ok, follower, follow_activity} <- User.unfollow(follower, unfollowed),
42 {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed) do
43 {:ok, follower, unfollowed}
44 else
45 err -> err
46 end
47 end
48
49 def block(%User{} = blocker, params) do
50 with {:ok, %User{} = blocked} <- get_user(params),
51 {:ok, blocker} <- User.block(blocker, blocked),
52 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
53 {:ok, blocker, blocked}
54 else
55 err -> err
56 end
57 end
58
59 def unblock(%User{} = blocker, params) do
60 with {:ok, %User{} = blocked} <- get_user(params),
61 {:ok, blocker} <- User.unblock(blocker, blocked),
62 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
63 {:ok, blocker, blocked}
64 else
65 err -> err
66 end
67 end
68
69 def repeat(%User{} = user, ap_id_or_id) do
70 with {:ok, _announce, %{data: %{"id" => id}}} <- CommonAPI.repeat(ap_id_or_id, user),
71 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
72 {:ok, activity}
73 end
74 end
75
76 def unrepeat(%User{} = user, ap_id_or_id) do
77 with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
78 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
79 {:ok, activity}
80 end
81 end
82
83 def fav(%User{} = user, ap_id_or_id) do
84 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
85 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
86 {:ok, activity}
87 end
88 end
89
90 def unfav(%User{} = user, ap_id_or_id) do
91 with {:ok, _unfav, _fav, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
92 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
93 {:ok, activity}
94 end
95 end
96
97 def upload(%Plug.Upload{} = file, format \\ "xml") do
98 {:ok, object} = ActivityPub.upload(file)
99
100 url = List.first(object.data["url"])
101 href = url["href"] |> MediaProxy.url()
102 type = url["mediaType"]
103
104 case format do
105 "xml" ->
106 # Fake this as good as possible...
107 """
108 <?xml version="1.0" encoding="UTF-8"?>
109 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
110 <mediaid>#{object.id}</mediaid>
111 <media_id>#{object.id}</media_id>
112 <media_id_string>#{object.id}</media_id_string>
113 <media_url>#{href}</media_url>
114 <mediaurl>#{href}</mediaurl>
115 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
116 </rsp>
117 """
118
119 "json" ->
120 %{
121 media_id: object.id,
122 media_id_string: "#{object.id}}",
123 media_url: href,
124 size: 0
125 }
126 |> Jason.encode!()
127 end
128 end
129
130 def register_user(params) do
131 tokenString = params["token"]
132
133 params = %{
134 nickname: params["nickname"],
135 name: params["fullname"],
136 bio: params["bio"],
137 email: params["email"],
138 password: params["password"],
139 password_confirmation: params["confirm"]
140 }
141
142 # no need to query DB if registration is open
143 token =
144 unless @registrations_open || is_nil(tokenString) do
145 Repo.get_by(UserInviteToken, %{token: tokenString})
146 end
147
148 cond do
149 @registrations_open || (!is_nil(token) && !token.used) ->
150 changeset = User.register_changeset(%User{}, params)
151
152 with {:ok, user} <- Repo.insert(changeset) do
153 !@registrations_open && UserInviteToken.mark_as_used(token.token)
154 {:ok, user}
155 else
156 {:error, changeset} ->
157 errors =
158 Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
159 |> Jason.encode!()
160
161 {:error, %{error: errors}}
162 end
163
164 !@registrations_open && is_nil(token) ->
165 {:error, "Invalid token"}
166
167 !@registrations_open && token.used ->
168 {:error, "Expired token"}
169 end
170 end
171
172 def get_by_id_or_nickname(id_or_nickname) do
173 if !is_integer(id_or_nickname) && :error == Integer.parse(id_or_nickname) do
174 Repo.get_by(User, nickname: id_or_nickname)
175 else
176 Repo.get(User, id_or_nickname)
177 end
178 end
179
180 def get_user(user \\ nil, params) do
181 case params do
182 %{"user_id" => user_id} ->
183 case target = get_by_id_or_nickname(user_id) do
184 nil ->
185 {:error, "No user with such user_id"}
186
187 _ ->
188 {:ok, target}
189 end
190
191 %{"screen_name" => nickname} ->
192 case target = Repo.get_by(User, nickname: nickname) do
193 nil ->
194 {:error, "No user with such screen_name"}
195
196 _ ->
197 {:ok, target}
198 end
199
200 _ ->
201 if user do
202 {:ok, user}
203 else
204 {:error, "You need to specify screen_name or user_id"}
205 end
206 end
207 end
208
209 defp parse_int(string, default)
210
211 defp parse_int(string, default) when is_binary(string) do
212 with {n, _} <- Integer.parse(string) do
213 n
214 else
215 _e -> default
216 end
217 end
218
219 defp parse_int(_, default), do: default
220
221 def search(_user, %{"q" => query} = params) do
222 limit = parse_int(params["rpp"], 20)
223 page = parse_int(params["page"], 1)
224 offset = (page - 1) * limit
225
226 q =
227 from(
228 a in Activity,
229 where: fragment("?->>'type' = 'Create'", a.data),
230 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
231 where:
232 fragment(
233 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
234 a.data,
235 ^query
236 ),
237 limit: ^limit,
238 offset: ^offset,
239 # this one isn't indexed so psql won't take the wrong index.
240 order_by: [desc: :inserted_at]
241 )
242
243 _activities = Repo.all(q)
244 end
245
246 defp make_date do
247 DateTime.utc_now() |> DateTime.to_iso8601()
248 end
249
250 # DEPRECATED mostly, context objects are now created at insertion time.
251 def context_to_conversation_id(context) do
252 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
253 id
254 else
255 _e ->
256 changeset = Object.context_mapping(context)
257
258 case Repo.insert(changeset) do
259 {:ok, %{id: id}} ->
260 id
261
262 # This should be solved by an upsert, but it seems ecto
263 # has problems accessing the constraint inside the jsonb.
264 {:error, _} ->
265 Object.get_cached_by_ap_id(context).id
266 end
267 end
268 end
269
270 def conversation_id_to_context(id) do
271 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
272 context
273 else
274 _e ->
275 {:error, "No such conversation"}
276 end
277 end
278
279 def get_external_profile(for_user, uri) do
280 with %User{} = user <- User.get_or_fetch(uri) do
281 spawn(fn ->
282 with url <- user.info["topic"],
283 {:ok, %{body: body}} <-
284 @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do
285 OStatus.handle_incoming(body)
286 end
287 end)
288
289 {:ok, UserView.render("show.json", %{user: user, for: for_user})}
290 else
291 _e ->
292 {:error, "Couldn't find user"}
293 end
294 end
295 end