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