0c77e092cf6a4e718628c35326335e33d6711723
[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 unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
119 object = Object.get_by_ap_id(object["id"])
120
121 {:ok, object} = ActivityPub.unlike(user, object)
122 new_data = activity.data
123 |> Map.put("object", object.data)
124
125 status = %{activity | data: new_data}
126 |> activity_to_status(%{for: user})
127
128 {:ok, status}
129 end
130
131 def repeat(%User{} = user, ap_id_or_id) do
132 with {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(ap_id_or_id, user),
133 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id),
134 status <- activity_to_status(activity, %{for: user}) do
135 {:ok, status}
136 end
137 end
138
139 def fav(%User{} = user, ap_id_or_id) do
140 with {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
141 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id),
142 status <- activity_to_status(activity, %{for: user}) do
143 {:ok, status}
144 end
145 end
146
147 def upload(%Plug.Upload{} = file, format \\ "xml") do
148 {:ok, object} = ActivityPub.upload(file)
149
150 url = List.first(object.data["url"])
151 href = url["href"]
152 type = url["mediaType"]
153
154 case format do
155 "xml" ->
156 # Fake this as good as possible...
157 """
158 <?xml version="1.0" encoding="UTF-8"?>
159 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
160 <mediaid>#{object.id}</mediaid>
161 <media_id>#{object.id}</media_id>
162 <media_id_string>#{object.id}</media_id_string>
163 <media_url>#{href}</media_url>
164 <mediaurl>#{href}</mediaurl>
165 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
166 </rsp>
167 """
168 "json" ->
169 %{
170 media_id: object.id,
171 media_id_string: "#{object.id}}",
172 media_url: href,
173 size: 0
174 } |> Poison.encode!
175 end
176 end
177
178 def register_user(params) do
179 params = %{
180 nickname: params["nickname"],
181 name: params["fullname"],
182 bio: params["bio"],
183 email: params["email"],
184 password: params["password"],
185 password_confirmation: params["confirm"]
186 }
187
188 changeset = User.register_changeset(%User{}, params)
189
190 with {:ok, user} <- Repo.insert(changeset) do
191 {:ok, user}
192 else
193 {:error, changeset} ->
194 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
195 |> Poison.encode!
196 {:error, %{error: errors}}
197 end
198 end
199
200 def get_by_id_or_nickname(id_or_nickname) do
201 if !is_integer(id_or_nickname) && :error == Integer.parse(id_or_nickname) do
202 Repo.get_by(User, nickname: id_or_nickname)
203 else
204 Repo.get(User, id_or_nickname)
205 end
206 end
207
208 def get_user(user \\ nil, params) do
209 case params do
210 %{"user_id" => user_id} ->
211 case target = get_by_id_or_nickname(user_id) do
212 nil ->
213 {:error, "No user with such user_id"}
214 _ ->
215 {:ok, target}
216 end
217 %{"screen_name" => nickname} ->
218 case target = Repo.get_by(User, nickname: nickname) do
219 nil ->
220 {:error, "No user with such screen_name"}
221 _ ->
222 {:ok, target}
223 end
224 _ ->
225 if user do
226 {:ok, user}
227 else
228 {:error, "You need to specify screen_name or user_id"}
229 end
230 end
231 end
232
233 defp activities_to_statuses(activities, opts) do
234 Enum.map(activities, fn(activity) ->
235 activity_to_status(activity, opts)
236 end)
237 end
238
239 # For likes, fetch the liked activity, too.
240 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
241 actor = get_in(activity.data, ["actor"])
242 user = User.get_cached_by_ap_id(actor)
243 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
244
245 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
246 end
247
248 # For announces, fetch the announced activity and the user.
249 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
250 actor = get_in(activity.data, ["actor"])
251 user = User.get_cached_by_ap_id(actor)
252 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
253 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
254
255 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
256 end
257
258 defp activity_to_status(%Activity{data: %{"type" => "Delete"}} = activity, opts) do
259 actor = get_in(activity.data, ["actor"])
260 user = User.get_cached_by_ap_id(actor)
261 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user}))
262 end
263
264 defp activity_to_status(activity, opts) do
265 actor = get_in(activity.data, ["actor"])
266 user = User.get_cached_by_ap_id(actor)
267 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
268 mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
269 if ap_id do
270 User.get_cached_by_ap_id(ap_id)
271 else
272 nil
273 end
274 end)
275 |> Enum.filter(&(&1))
276
277 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
278 end
279
280 defp make_date do
281 DateTime.utc_now() |> DateTime.to_iso8601
282 end
283
284 def context_to_conversation_id(context) do
285 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
286 id
287 else _e ->
288 changeset = Object.context_mapping(context)
289 case Repo.insert(changeset) do
290 {:ok, %{id: id}} -> id
291 # This should be solved by an upsert, but it seems ecto
292 # has problems accessing the constraint inside the jsonb.
293 {:error, _} -> Object.get_cached_by_ap_id(context).id
294 end
295 end
296 end
297
298 def conversation_id_to_context(id) do
299 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
300 context
301 else _e ->
302 {:error, "No such conversation"}
303 end
304 end
305
306 def get_external_profile(for_user, uri) do
307 with {:ok, %User{} = user} <- OStatus.find_or_make_user(uri) do
308 with url <- user.info["topic"],
309 {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do
310 OStatus.handle_incoming(body)
311 end
312 {:ok, UserView.render("show.json", %{user: user, for: for_user})}
313 else _e ->
314 {:error, "Couldn't find user"}
315 end
316 end
317 end