6f5c9f72722afac75f77432026c449b89a456c6c
[akkoma] / lib / pleroma / web / twitter_api / utils.ex
1 defmodule Pleroma.Web.TwitterAPI.Utils do
2 alias Pleroma.{Repo, Object, Formatter, User, Activity}
3 alias Pleroma.Web.ActivityPub.Utils
4
5 def attachments_from_ids(ids) do
6 Enum.map(ids || [], fn (media_id) ->
7 Repo.get(Object, media_id).data
8 end)
9 end
10
11 def add_attachments(text, attachments) do
12 attachment_text = Enum.map(attachments, fn
13 (%{"url" => [%{"href" => href} | _]}) ->
14 "<a href='#{href}' class='attachment'>#{href}</a>"
15 _ -> ""
16 end)
17 Enum.join([text | attachment_text], "<br>")
18 end
19
20 def format_input(text, mentions) do
21 HtmlSanitizeEx.strip_tags(text)
22 |> Formatter.linkify
23 |> String.replace("\n", "<br>")
24 |> add_user_links(mentions)
25 end
26
27 def add_user_links(text, mentions) do
28 mentions = mentions
29 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
30 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
31
32 # This replaces the mention with a unique reference first so it doesn't
33 # contain parts of other replaced mentions. There probably is a better
34 # solution for this...
35 step_one = mentions
36 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
37 String.replace(text, match, uuid)
38 end)
39
40 Enum.reduce(mentions, step_one, fn ({match, %User{ap_id: ap_id}, uuid}, text) ->
41 String.replace(text, uuid, "<a href='#{ap_id}'>#{match}</a>")
42 end)
43 end
44
45 def make_content_html(status, mentions, attachments) do
46 status
47 |> format_input(mentions)
48 |> add_attachments(attachments)
49 end
50
51 def make_context(%Activity{data: %{"context" => context}}), do: context
52 def make_context(_), do: Utils.generate_context_id
53
54 def make_note_data(actor, to, context, content_html, attachments, inReplyTo) do
55 object = %{
56 "type" => "Note",
57 "to" => to,
58 "content" => content_html,
59 "context" => context,
60 "attachment" => attachments,
61 "actor" => actor
62 }
63
64 if inReplyTo do
65 object
66 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
67 |> Map.put("inReplyToStatusId", inReplyTo.id)
68 else
69 object
70 end
71 end
72 end