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