1 defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
2 alias Pleroma.{User, Activity, Repo, Object}
3 alias Pleroma.Web.ActivityPub.ActivityPub
4 alias Pleroma.Web.ActivityPub.Utils
5 alias Pleroma.Web.TwitterAPI.Representers.{ActivityRepresenter, UserRepresenter}
6 alias Pleroma.Web.OStatus
10 def to_for_user_and_mentions(user, mentions) do
12 User.ap_followers(user),
13 "https://www.w3.org/ns/activitystreams#Public"
16 default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
19 def format_input(text, mentions) do
20 HtmlSanitizeEx.strip_tags(text)
21 |> String.replace("\n", "<br>")
22 |> add_user_links(mentions)
25 def attachments_from_ids(ids) do
26 Enum.map(ids || [], fn (media_id) ->
27 Repo.get(Object, media_id).data
31 def get_replied_to_activity(id) when not is_nil(id) do
32 Repo.get(Activity, id)
35 def get_replied_to_activity(_), do: nil
37 def add_attachments(text, attachments) do
38 attachment_text = Enum.map(attachments, fn
39 (%{"url" => [%{"href" => href} | _]}) ->
40 "<a href='#{href}' class='attachment'>#{href}</a>"
43 Enum.join([text | attachment_text], "<br>")
46 def create_status(%User{} = user, %{"status" => status} = data) do
47 attachments = attachments_from_ids(data["media_ids"])
48 context = Utils.generate_context_id
49 mentions = parse_mentions(status)
51 |> format_input(mentions)
52 |> add_attachments(attachments)
54 to = to_for_user_and_mentions(user, mentions)
57 inReplyTo = get_replied_to_activity(data["in_reply_to_status_id"])
60 [to, context, object, additional] =
62 context = inReplyTo.data["context"]
63 to = to ++ [inReplyTo.data["actor"]]
68 "content" => content_html,
71 "attachment" => attachments,
72 "actor" => user.ap_id,
73 "inReplyTo" => inReplyTo.data["object"]["id"],
74 "inReplyToStatusId" => inReplyTo.id,
78 [to, context, object, additional]
83 "content" => content_html,
86 "attachment" => attachments,
89 [to, context, object, %{}]
92 ActivityPub.create(to, user, context, object, additional, data)
95 def fetch_friend_statuses(user, opts \\ %{}) do
96 ActivityPub.fetch_activities([user.ap_id | user.following], opts)
97 |> activities_to_statuses(%{for: user})
100 def fetch_public_statuses(user, opts \\ %{}) do
101 opts = Map.put(opts, "local_only", true)
102 ActivityPub.fetch_public_activities(opts)
103 |> activities_to_statuses(%{for: user})
106 def fetch_public_and_external_statuses(user, opts \\ %{}) do
107 ActivityPub.fetch_public_activities(opts)
108 |> activities_to_statuses(%{for: user})
111 def fetch_user_statuses(user, opts \\ %{}) do
112 ActivityPub.fetch_activities([], opts)
113 |> activities_to_statuses(%{for: user})
116 def fetch_mentions(user, opts \\ %{}) do
117 ActivityPub.fetch_activities([user.ap_id], opts)
118 |> activities_to_statuses(%{for: user})
121 def fetch_conversation(user, id) do
122 with context when is_binary(context) <- conversation_id_to_context(id),
123 activities <- ActivityPub.fetch_activities_for_context(context),
124 statuses <- activities |> activities_to_statuses(%{for: user})
132 def fetch_status(user, id) do
133 with %Activity{} = activity <- Repo.get(Activity, id) do
134 activity_to_status(activity, %{for: user})
138 def follow(%User{} = follower, params) do
139 with {:ok, %User{} = followed} <- get_user(params),
140 {:ok, follower} <- User.follow(follower, followed),
141 {:ok, activity} <- ActivityPub.follow(follower, followed)
143 {:ok, follower, followed, activity}
149 def unfollow(%User{} = follower, params) do
150 with { :ok, %User{} = unfollowed } <- get_user(params),
151 { :ok, follower, follow_activity } <- User.unfollow(follower, unfollowed),
152 { :ok, _activity } <- ActivityPub.insert(%{
154 "actor" => follower.ap_id,
155 "object" => follow_activity.data["id"], # get latest Follow for these users
156 "published" => make_date()
159 { :ok, follower, unfollowed }
165 def favorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
166 object = Object.get_by_ap_id(object["id"])
168 {:ok, _like_activity, object} = ActivityPub.like(user, object)
169 new_data = activity.data
170 |> Map.put("object", object.data)
172 status = %{activity | data: new_data}
173 |> activity_to_status(%{for: user})
178 def unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
179 object = Object.get_by_ap_id(object["id"])
181 {:ok, object} = ActivityPub.unlike(user, object)
182 new_data = activity.data
183 |> Map.put("object", object.data)
185 status = %{activity | data: new_data}
186 |> activity_to_status(%{for: user})
191 def retweet(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
192 object = Object.get_by_ap_id(object["id"])
194 {:ok, _announce_activity, object} = ActivityPub.announce(user, object)
195 new_data = activity.data
196 |> Map.put("object", object.data)
198 status = %{activity | data: new_data}
199 |> activity_to_status(%{for: user})
204 def upload(%Plug.Upload{} = file, format \\ "xml") do
205 {:ok, object} = ActivityPub.upload(file)
207 url = List.first(object.data["url"])
209 type = url["mediaType"]
213 # Fake this as good as possible...
215 <?xml version="1.0" encoding="UTF-8"?>
216 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
217 <mediaid>#{object.id}</mediaid>
218 <media_id>#{object.id}</media_id>
219 <media_id_string>#{object.id}</media_id_string>
220 <media_url>#{href}</media_url>
221 <mediaurl>#{href}</mediaurl>
222 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
228 media_id_string: "#{object.id}}",
235 def parse_mentions(text) do
236 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
237 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])?)*/
239 Regex.scan(regex, text)
242 |> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
243 |> Enum.filter(fn ({_match, user}) -> user end)
246 def add_user_links(text, mentions) do
248 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
249 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
251 # This replaces the mention with a unique reference first so it doesn't
252 # contain parts of other replaced mentions. There probably is a better
253 # solution for this...
255 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
256 String.replace(text, match, uuid)
259 Enum.reduce(mentions, step_one, fn ({match, %User{ap_id: ap_id}, uuid}, text) ->
260 String.replace(text, uuid, "<a href='#{ap_id}'>#{match}</a>")
264 def register_user(params) do
266 nickname: params["nickname"],
267 name: params["fullname"],
269 email: params["email"],
270 password: params["password"],
271 password_confirmation: params["confirm"]
274 changeset = User.register_changeset(%User{}, params)
276 with {:ok, user} <- Repo.insert(changeset) do
277 {:ok, UserRepresenter.to_map(user)}
279 {:error, changeset} ->
280 errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
282 {:error, %{error: errors}}
286 def get_user(user \\ nil, params) do
288 %{"user_id" => user_id} ->
289 case target = Repo.get(User, user_id) do
291 {:error, "No user with such user_id"}
295 %{"screen_name" => nickname} ->
296 case target = Repo.get_by(User, nickname: nickname) do
298 {:error, "No user with such screen_name"}
306 {:error, "You need to specify screen_name or user_id"}
311 defp activities_to_statuses(activities, opts) do
312 Enum.map(activities, fn(activity) ->
313 activity_to_status(activity, opts)
317 # For likes, fetch the liked activity, too.
318 defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
319 actor = get_in(activity.data, ["actor"])
320 user = User.get_cached_by_ap_id(actor)
321 [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])
323 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
326 # For announces, fetch the announced activity and the user.
327 defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
328 actor = get_in(activity.data, ["actor"])
329 user = User.get_cached_by_ap_id(actor)
330 [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
331 announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])
333 ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
336 defp activity_to_status(activity, opts) do
337 actor = get_in(activity.data, ["actor"])
338 user = User.get_cached_by_ap_id(actor)
339 # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
340 mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
341 User.get_cached_by_ap_id(ap_id)
343 |> Enum.filter(&(&1))
345 ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
349 DateTime.utc_now() |> DateTime.to_iso8601
352 def context_to_conversation_id(context) do
353 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
356 changeset = Object.context_mapping(context)
357 {:ok, %{id: id}} = Repo.insert(changeset)
362 def conversation_id_to_context(id) do
363 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
366 {:error, "No such conversation"}
370 def get_external_profile(for_user, uri) do
371 with {:ok, %User{} = user} <- OStatus.find_or_make_user(uri) do
372 {:ok, UserRepresenter.to_map(user, %{for: for_user})}
374 {:error, "Couldn't find user"}