Merge branch 'develop' of ssh.gitgud.io:lambadalambda/pleroma into bugfix/repeated...
[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_conversation(user, id) do
84 query = from activity in Activity,
85 where: fragment("? @> ?", activity.data, ^%{ statusnetConversationId: id}),
86 limit: 1
87
88 with %Activity{} = activity <- Repo.one(query),
89 context <- activity.data["context"],
90 activities <- ActivityPub.fetch_activities_for_context(context),
91 statuses <- activities |> activities_to_statuses(%{for: user})
92 do
93 statuses
94 else e ->
95 IO.inspect(e)
96 []
97 end
98 end
99
100 def fetch_status(user, id) do
101 with %Activity{} = activity <- Repo.get(Activity, id) do
102 activity_to_status(activity, %{for: user})
103 end
104 end
105
106 def follow(%User{} = follower, followed_id) do
107 with %User{} = followed <- Repo.get(User, followed_id),
108 { :ok, follower } <- User.follow(follower, followed),
109 { :ok, activity } <- ActivityPub.insert(%{
110 "type" => "Follow",
111 "actor" => follower.ap_id,
112 "object" => followed.ap_id,
113 "published" => make_date()
114 })
115 do
116 { :ok, follower, followed, activity }
117 else
118 err -> err
119 end
120 end
121
122 def unfollow(%User{} = follower, followed_id) do
123 with %User{} = followed <- Repo.get(User, followed_id),
124 { :ok, follower } <- User.unfollow(follower, followed)
125 do
126 { :ok, follower, followed }
127 else
128 err -> err
129 end
130 end
131
132 def favorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
133 object = Object.get_by_ap_id(object["id"])
134
135 {:ok, _like_activity, object} = ActivityPub.like(user, object)
136 new_data = activity.data
137 |> Map.put("object", object.data)
138
139 status = %{activity | data: new_data}
140 |> activity_to_status(%{for: user})
141
142 {:ok, status}
143 end
144
145 def unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
146 object = Object.get_by_ap_id(object["id"])
147
148 {:ok, object} = ActivityPub.unlike(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 retweet(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
159 object = Object.get_by_ap_id(object["id"])
160
161 {:ok, _announce_activity, object} = ActivityPub.announce(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 upload(%Plug.Upload{} = file, format \\ "xml") do
172 {:ok, object} = ActivityPub.upload(file)
173
174 url = List.first(object.data["url"])
175 href = url["href"]
176 type = url["mediaType"]
177
178 case format do
179 "xml" ->
180 # Fake this as good as possible...
181 """
182 <?xml version="1.0" encoding="UTF-8"?>
183 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
184 <mediaid>#{object.id}</mediaid>
185 <media_id>#{object.id}</media_id>
186 <media_id_string>#{object.id}</media_id_string>
187 <media_url>#{href}</media_url>
188 <mediaurl>#{href}</mediaurl>
189 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
190 </rsp>
191 """
192 "json" ->
193 %{
194 media_id: object.id,
195 media_id_string: "#{object.id}}",
196 media_url: href,
197 size: 0
198 } |> Poison.encode!
199 end
200 end
201
202 def parse_mentions(text) do
203 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
204 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])?)*/
205
206 Regex.scan(regex, text)
207 |> List.flatten
208 |> Enum.uniq
209 |> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
210 |> Enum.filter(fn ({_match, user}) -> user end)
211 end
212
213 def add_user_links(text, mentions) do
214 Enum.reduce(mentions, text, fn ({match, %User{ap_id: ap_id}}, text) -> String.replace(text, match, "<a href='#{ap_id}'>#{match}</a>") end)
215 end
216
217 defp add_conversation_id(activity) do
218 if is_integer(activity.data["statusnetConversationId"]) do
219 {:ok, activity}
220 else
221 data = activity.data
222 |> put_in(["object", "statusnetConversationId"], activity.id)
223 |> put_in(["statusnetConversationId"], activity.id)
224
225 object = Object.get_by_ap_id(activity.data["object"]["id"])
226
227 changeset = Ecto.Changeset.change(object, data: data["object"])
228 Repo.update(changeset)
229
230 changeset = Ecto.Changeset.change(activity, data: data)
231 Repo.update(changeset)
232 end
233 end
234
235 def register_user(params) do
236 params = %{
237 nickname: params["nickname"],
238 name: params["fullname"],
239 bio: params["bio"],
240 email: params["email"],
241 password: params["password"],
242 password_confirmation: params["confirm"]
243 }
244
245 changeset = User.register_changeset(%User{}, params)
246
247 with {:ok, user} <- Repo.insert(changeset) do
248 {:ok, UserRepresenter.to_map(user)}
249 else
250 {:error, changeset} ->
251 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} -> msg end)
252 |> Poison.encode!
253 {:error, %{error: errors}}
254 end
255 end
256
257 defp activities_to_statuses(activities, opts) do
258 Enum.map(activities, fn(activity) ->
259 activity_to_status(activity, opts)
260 end)
261 end
262
263 # For likes, fetch the liked activity, too.
264 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
265 actor = get_in(activity.data, ["actor"])
266 user = User.get_cached_by_ap_id(actor)
267 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
268
269 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
270 end
271
272 # For announces, fetch the announced activity and the user.
273 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
274 actor = get_in(activity.data, ["actor"])
275 user = User.get_cached_by_ap_id(actor)
276 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
277 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
278
279 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
280 end
281
282 defp activity_to_status(activity, opts) do
283 actor = get_in(activity.data, ["actor"])
284 user = User.get_cached_by_ap_id(actor)
285 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
286 mentioned_users = Enum.map(activity.data["to"], fn (ap_id) ->
287 User.get_cached_by_ap_id(ap_id)
288 end)
289 |> Enum.filter(&(&1))
290
291 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
292 end
293
294 defp make_date do
295 DateTime.utc_now() |> DateTime.to_iso8601
296 end
297 end