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