Merge branch 'develop' of ssh.gitgud.io:lambadalambda/pleroma into feature/user-timeline
[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 create_status(user = %User{}, data = %{}) do
9 attachments = Enum.map(data["media_ids"] || [], fn (media_id) ->
10 Repo.get(Object, media_id).data
11 end)
12
13 context = ActivityPub.generate_context_id
14
15 content = HtmlSanitizeEx.strip_tags(data["status"])
16 |> String.replace("\n", "<br>")
17
18 mentions = parse_mentions(content)
19
20 default_to = [
21 User.ap_followers(user),
22 "https://www.w3.org/ns/activitystreams#Public"
23 ]
24
25 to = default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
26
27 content_html = add_user_links(content, mentions)
28
29 date = make_date()
30
31 activity = %{
32 "type" => "Create",
33 "to" => to,
34 "actor" => user.ap_id,
35 "object" => %{
36 "type" => "Note",
37 "to" => to,
38 "content" => content_html,
39 "published" => date,
40 "context" => context,
41 "attachment" => attachments,
42 "actor" => user.ap_id
43 },
44 "published" => date,
45 "context" => context
46 }
47
48 # Wire up reply info.
49 activity = with inReplyToId when not is_nil(inReplyToId) <- data["in_reply_to_status_id"],
50 inReplyTo <- Repo.get(Activity, inReplyToId),
51 context <- inReplyTo.data["context"]
52 do
53
54 to = activity["to"] ++ [inReplyTo.data["actor"]]
55
56 activity
57 |> put_in(["to"], to)
58 |> put_in(["context"], context)
59 |> put_in(["object", "context"], context)
60 |> put_in(["object", "inReplyTo"], inReplyTo.data["object"]["id"])
61 |> put_in(["object", "inReplyToStatusId"], inReplyToId)
62 |> put_in(["statusnetConversationId"], inReplyTo.data["statusnetConversationId"])
63 |> put_in(["object", "statusnetConversationId"], inReplyTo.data["statusnetConversationId"])
64 else _e ->
65 activity
66 end
67
68 with {:ok, activity} <- ActivityPub.insert(activity) do
69 add_conversation_id(activity)
70 end
71 end
72
73 def fetch_friend_statuses(user, opts \\ %{}) do
74 ActivityPub.fetch_activities([user.ap_id | user.following], opts)
75 |> activities_to_statuses(%{for: user})
76 end
77
78 def fetch_public_statuses(user, opts \\ %{}) do
79 ActivityPub.fetch_public_activities(opts)
80 |> activities_to_statuses(%{for: user})
81 end
82
83 def fetch_user_statuses(user, opts \\ %{}) do
84 ActivityPub.fetch_activities([], opts)
85 |> activities_to_statuses(%{for: user})
86 end
87
88 def fetch_conversation(user, id) do
89 query = from activity in Activity,
90 where: fragment("? @> ?", activity.data, ^%{ statusnetConversationId: id}),
91 limit: 1
92
93 with %Activity{} = activity <- Repo.one(query),
94 context <- activity.data["context"],
95 activities <- ActivityPub.fetch_activities_for_context(context),
96 statuses <- activities |> activities_to_statuses(%{for: user})
97 do
98 statuses
99 else e ->
100 IO.inspect(e)
101 []
102 end
103 end
104
105 def fetch_status(user, id) do
106 with %Activity{} = activity <- Repo.get(Activity, id) do
107 activity_to_status(activity, %{for: user})
108 end
109 end
110
111 def follow(%User{} = follower, followed_id) do
112 with %User{} = followed <- Repo.get(User, followed_id),
113 { :ok, follower } <- User.follow(follower, followed),
114 { :ok, activity } <- ActivityPub.insert(%{
115 "type" => "Follow",
116 "actor" => follower.ap_id,
117 "object" => followed.ap_id,
118 "published" => make_date()
119 })
120 do
121 { :ok, follower, followed, activity }
122 end
123 end
124
125 def unfollow(%User{} = follower, followed_id) do
126 with %User{} = followed <- Repo.get(User, followed_id),
127 { :ok, follower } <- User.unfollow(follower, followed)
128 do
129 { :ok, follower, followed }
130 end
131 end
132
133 def favorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
134 object = Object.get_by_ap_id(object["id"])
135
136 {:ok, _like_activity, object} = ActivityPub.like(user, object)
137 new_data = activity.data
138 |> Map.put("object", object.data)
139
140 status = %{activity | data: new_data}
141 |> activity_to_status(%{for: user})
142
143 {:ok, status}
144 end
145
146 def unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
147 object = Object.get_by_ap_id(object["id"])
148
149 {:ok, object} = ActivityPub.unlike(user, object)
150 new_data = activity.data
151 |> Map.put("object", object.data)
152
153 status = %{activity | data: new_data}
154 |> activity_to_status(%{for: user})
155
156 {:ok, status}
157 end
158
159 def retweet(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
160 object = Object.get_by_ap_id(object["id"])
161
162 {:ok, _announce_activity, object} = ActivityPub.announce(user, object)
163 new_data = activity.data
164 |> Map.put("object", object.data)
165
166 status = %{activity | data: new_data}
167 |> activity_to_status(%{for: user})
168
169 {:ok, status}
170 end
171
172 def upload(%Plug.Upload{} = file, format \\ "xml") do
173 {:ok, object} = ActivityPub.upload(file)
174
175 url = List.first(object.data["url"])
176 href = url["href"]
177 type = url["mediaType"]
178
179 case format do
180 "xml" ->
181 # Fake this as good as possible...
182 """
183 <?xml version="1.0" encoding="UTF-8"?>
184 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
185 <mediaid>#{object.id}</mediaid>
186 <media_id>#{object.id}</media_id>
187 <media_id_string>#{object.id}</media_id_string>
188 <media_url>#{href}</media_url>
189 <mediaurl>#{href}</mediaurl>
190 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
191 </rsp>
192 """
193 "json" ->
194 %{
195 media_id: object.id,
196 media_id_string: "#{object.id}}",
197 media_url: href,
198 size: 0
199 } |> Poison.encode!
200 end
201 end
202
203 def parse_mentions(text) do
204 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
205 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])?)*/
206
207 Regex.scan(regex, text)
208 |> List.flatten
209 |> Enum.uniq
210 |> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
211 |> Enum.filter(fn ({_match, user}) -> user end)
212 end
213
214 def add_user_links(text, mentions) do
215 Enum.reduce(mentions, text, fn ({match, %User{ap_id: ap_id}}, text) -> String.replace(text, match, "<a href='#{ap_id}'>#{match}</a>") end)
216 end
217
218 defp add_conversation_id(activity) do
219 if is_integer(activity.data["statusnetConversationId"]) do
220 {:ok, activity}
221 else
222 data = activity.data
223 |> put_in(["object", "statusnetConversationId"], activity.id)
224 |> put_in(["statusnetConversationId"], activity.id)
225
226 object = Object.get_by_ap_id(activity.data["object"]["id"])
227
228 changeset = Ecto.Changeset.change(object, data: data["object"])
229 Repo.update(changeset)
230
231 changeset = Ecto.Changeset.change(activity, data: data)
232 Repo.update(changeset)
233 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, 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 end