Merge branch 'feature/unfollow-by-screen-name' of ssh.gitgud.io:dtluna/pleroma into...
[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, params) do
112 with { :ok, %User{} = followed } <- get_user(params),
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, %{ "user_id" => 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 unfollow(%User{} = follower, %{ "screen_name" => followed_name }) do
138 with %User{} = followed <- Repo.get_by(User, nickname: followed_name),
139 { :ok, follower } <- User.unfollow(follower, followed)
140 do
141 { :ok, follower, followed }
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 defp add_conversation_id(activity) do
231 if is_integer(activity.data["statusnetConversationId"]) do
232 {:ok, activity}
233 else
234 data = activity.data
235 |> put_in(["object", "statusnetConversationId"], activity.id)
236 |> put_in(["statusnetConversationId"], activity.id)
237
238 object = Object.get_by_ap_id(activity.data["object"]["id"])
239
240 changeset = Ecto.Changeset.change(object, data: data["object"])
241 Repo.update(changeset)
242
243 changeset = Ecto.Changeset.change(activity, data: data)
244 Repo.update(changeset)
245 end
246 end
247
248 def register_user(params) do
249 params = %{
250 nickname: params["nickname"],
251 name: params["fullname"],
252 bio: params["bio"],
253 email: params["email"],
254 password: params["password"],
255 password_confirmation: params["confirm"]
256 }
257
258 changeset = User.register_changeset(%User{}, params)
259
260 with {:ok, user} <- Repo.insert(changeset) do
261 {:ok, UserRepresenter.to_map(user)}
262 else
263 {:error, changeset} ->
264 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
265 |> Poison.encode!
266 {:error, %{error: errors}}
267 end
268 end
269
270 def get_user(user \\ nil, params) do
271 case params do
272 %{ "user_id" => user_id } ->
273 case target = Repo.get(User, user_id) do
274 nil ->
275 {:error, "No user with such user_id"}
276 _ ->
277 {:ok, target}
278 end
279 %{ "screen_name" => nickname } ->
280 case target = Repo.get_by(User, nickname: nickname) do
281 nil ->
282 {:error, "No user with such screen_name"}
283 _ ->
284 {:ok, target}
285 end
286 _ ->
287 if user do
288 {:ok, user}
289 else
290 {:error, "You need to specify screen_name or user_id"}
291 end
292 end
293 end
294
295 defp activities_to_statuses(activities, opts) do
296 Enum.map(activities, fn(activity) ->
297 activity_to_status(activity, opts)
298 end)
299 end
300
301 # For likes, fetch the liked activity, too.
302 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
303 actor = get_in(activity.data, ["actor"])
304 user = User.get_cached_by_ap_id(actor)
305 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
306
307 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
308 end
309
310 # For announces, fetch the announced activity and the user.
311 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
312 actor = get_in(activity.data, ["actor"])
313 user = User.get_cached_by_ap_id(actor)
314 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
315 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
316
317 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
318 end
319
320 defp activity_to_status(activity, opts) do
321 actor = get_in(activity.data, ["actor"])
322 user = User.get_cached_by_ap_id(actor)
323 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
324 mentioned_users = Enum.map(activity.data["to"], fn (ap_id) ->
325 User.get_cached_by_ap_id(ap_id)
326 end)
327 |> Enum.filter(&(&1))
328
329 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
330 end
331
332 defp make_date do
333 DateTime.utc_now() |> DateTime.to_iso8601
334 end
335 end