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