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