Add unfav to Mastodon API.
[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
5 alias Pleroma.Web.TwitterAPI.UserView
6 alias Pleroma.Web.{OStatus, CommonAPI}
7 alias Pleroma.Formatter
8
9 import Pleroma.Web.TwitterAPI.Utils
10
11 @httpoison Application.get_env(:pleroma, :httpoison)
12
13 def to_for_user_and_mentions(user, mentions, inReplyTo) do
14 default_to = [
15 user.follower_address,
16 "https://www.w3.org/ns/activitystreams#Public"
17 ]
18
19 to = default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
20 if inReplyTo do
21 Enum.uniq([inReplyTo.data["actor"] | to])
22 else
23 to
24 end
25 end
26
27 def get_replied_to_activity(id) when not is_nil(id) do
28 Repo.get(Activity, id)
29 end
30
31 def get_replied_to_activity(_), do: nil
32
33 def create_status(%User{} = user, %{"status" => status} = data) do
34 with attachments <- attachments_from_ids(data["media_ids"]),
35 mentions <- Formatter.parse_mentions(status),
36 inReplyTo <- get_replied_to_activity(data["in_reply_to_status_id"]),
37 to <- to_for_user_and_mentions(user, mentions, inReplyTo),
38 content_html <- make_content_html(status, mentions, attachments),
39 context <- make_context(inReplyTo),
40 tags <- Formatter.parse_tags(status),
41 object <- make_note_data(user.ap_id, to, context, content_html, attachments, inReplyTo, tags) do
42 res = ActivityPub.create(to, user, context, object)
43 User.update_note_count(user)
44 res
45 end
46 end
47
48 def fetch_friend_statuses(user, opts \\ %{}) do
49 ActivityPub.fetch_activities([user.ap_id | user.following], opts)
50 |> activities_to_statuses(%{for: user})
51 end
52
53 def fetch_public_statuses(user, opts \\ %{}) do
54 opts = Map.put(opts, "local_only", true)
55 ActivityPub.fetch_public_activities(opts)
56 |> activities_to_statuses(%{for: user})
57 end
58
59 def fetch_public_and_external_statuses(user, opts \\ %{}) do
60 ActivityPub.fetch_public_activities(opts)
61 |> activities_to_statuses(%{for: user})
62 end
63
64 def fetch_user_statuses(user, opts \\ %{}) do
65 ActivityPub.fetch_activities([], opts)
66 |> activities_to_statuses(%{for: user})
67 end
68
69 def fetch_mentions(user, opts \\ %{}) do
70 ActivityPub.fetch_activities([user.ap_id], opts)
71 |> activities_to_statuses(%{for: user})
72 end
73
74 def fetch_conversation(user, id) do
75 with context when is_binary(context) <- conversation_id_to_context(id),
76 activities <- ActivityPub.fetch_activities_for_context(context),
77 statuses <- activities |> activities_to_statuses(%{for: user})
78 do
79 statuses
80 else _e ->
81 []
82 end
83 end
84
85 def fetch_status(user, id) do
86 with %Activity{} = activity <- Repo.get(Activity, id) do
87 activity_to_status(activity, %{for: user})
88 end
89 end
90
91 def follow(%User{} = follower, params) do
92 with {:ok, %User{} = followed} <- get_user(params),
93 {:ok, follower} <- User.follow(follower, followed),
94 {:ok, activity} <- ActivityPub.follow(follower, followed)
95 do
96 {:ok, follower, followed, activity}
97 else
98 err -> err
99 end
100 end
101
102 def unfollow(%User{} = follower, params) do
103 with { :ok, %User{} = unfollowed } <- get_user(params),
104 { :ok, follower, follow_activity } <- User.unfollow(follower, unfollowed),
105 { :ok, _activity } <- ActivityPub.insert(%{
106 "type" => "Undo",
107 "actor" => follower.ap_id,
108 "object" => follow_activity.data["id"], # get latest Follow for these users
109 "published" => make_date()
110 })
111 do
112 { :ok, follower, unfollowed }
113 else
114 err -> err
115 end
116 end
117
118 def repeat(%User{} = user, ap_id_or_id) do
119 with {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(ap_id_or_id, user),
120 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id),
121 status <- activity_to_status(activity, %{for: user}) do
122 {:ok, status}
123 end
124 end
125
126 def fav(%User{} = user, ap_id_or_id) do
127 with {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
128 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id),
129 status <- activity_to_status(activity, %{for: user}) do
130 {:ok, status}
131 end
132 end
133
134 def unfav(%User{} = user, ap_id_or_id) do
135 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
136 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id),
137 status <- activity_to_status(activity, %{for: user}) do
138 {:ok, status}
139 end
140 end
141
142 def upload(%Plug.Upload{} = file, format \\ "xml") do
143 {:ok, object} = ActivityPub.upload(file)
144
145 url = List.first(object.data["url"])
146 href = url["href"]
147 type = url["mediaType"]
148
149 case format do
150 "xml" ->
151 # Fake this as good as possible...
152 """
153 <?xml version="1.0" encoding="UTF-8"?>
154 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
155 <mediaid>#{object.id}</mediaid>
156 <media_id>#{object.id}</media_id>
157 <media_id_string>#{object.id}</media_id_string>
158 <media_url>#{href}</media_url>
159 <mediaurl>#{href}</mediaurl>
160 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
161 </rsp>
162 """
163 "json" ->
164 %{
165 media_id: object.id,
166 media_id_string: "#{object.id}}",
167 media_url: href,
168 size: 0
169 } |> Poison.encode!
170 end
171 end
172
173 def register_user(params) do
174 params = %{
175 nickname: params["nickname"],
176 name: params["fullname"],
177 bio: params["bio"],
178 email: params["email"],
179 password: params["password"],
180 password_confirmation: params["confirm"]
181 }
182
183 changeset = User.register_changeset(%User{}, params)
184
185 with {:ok, user} <- Repo.insert(changeset) do
186 {:ok, user}
187 else
188 {:error, changeset} ->
189 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
190 |> Poison.encode!
191 {:error, %{error: errors}}
192 end
193 end
194
195 def get_by_id_or_nickname(id_or_nickname) do
196 if !is_integer(id_or_nickname) && :error == Integer.parse(id_or_nickname) do
197 Repo.get_by(User, nickname: id_or_nickname)
198 else
199 Repo.get(User, id_or_nickname)
200 end
201 end
202
203 def get_user(user \\ nil, params) do
204 case params do
205 %{"user_id" => user_id} ->
206 case target = get_by_id_or_nickname(user_id) do
207 nil ->
208 {:error, "No user with such user_id"}
209 _ ->
210 {:ok, target}
211 end
212 %{"screen_name" => nickname} ->
213 case target = Repo.get_by(User, nickname: nickname) do
214 nil ->
215 {:error, "No user with such screen_name"}
216 _ ->
217 {:ok, target}
218 end
219 _ ->
220 if user do
221 {:ok, user}
222 else
223 {:error, "You need to specify screen_name or user_id"}
224 end
225 end
226 end
227
228 defp activities_to_statuses(activities, opts) do
229 Enum.map(activities, fn(activity) ->
230 activity_to_status(activity, opts)
231 end)
232 end
233
234 # For likes, fetch the liked activity, too.
235 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
236 actor = get_in(activity.data, ["actor"])
237 user = User.get_cached_by_ap_id(actor)
238 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
239
240 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
241 end
242
243 # For announces, fetch the announced activity and the user.
244 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
245 actor = get_in(activity.data, ["actor"])
246 user = User.get_cached_by_ap_id(actor)
247 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
248 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
249
250 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
251 end
252
253 defp activity_to_status(%Activity{data: %{"type" => "Delete"}} = activity, opts) do
254 actor = get_in(activity.data, ["actor"])
255 user = User.get_cached_by_ap_id(actor)
256 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user}))
257 end
258
259 defp activity_to_status(activity, opts) do
260 actor = get_in(activity.data, ["actor"])
261 user = User.get_cached_by_ap_id(actor)
262 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
263 mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
264 if ap_id do
265 User.get_cached_by_ap_id(ap_id)
266 else
267 nil
268 end
269 end)
270 |> Enum.filter(&(&1))
271
272 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
273 end
274
275 defp make_date do
276 DateTime.utc_now() |> DateTime.to_iso8601
277 end
278
279 def context_to_conversation_id(context) do
280 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
281 id
282 else _e ->
283 changeset = Object.context_mapping(context)
284 case Repo.insert(changeset) do
285 {:ok, %{id: id}} -> id
286 # This should be solved by an upsert, but it seems ecto
287 # has problems accessing the constraint inside the jsonb.
288 {:error, _} -> Object.get_cached_by_ap_id(context).id
289 end
290 end
291 end
292
293 def conversation_id_to_context(id) do
294 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
295 context
296 else _e ->
297 {:error, "No such conversation"}
298 end
299 end
300
301 def get_external_profile(for_user, uri) do
302 with {:ok, %User{} = user} <- OStatus.find_or_make_user(uri) do
303 with url <- user.info["topic"],
304 {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do
305 OStatus.handle_incoming(body)
306 end
307 {:ok, UserView.render("show.json", %{user: user, for: for_user})}
308 else _e ->
309 {:error, "Couldn't find user"}
310 end
311 end
312 end