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