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