Add finmoji.
[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=\"#{URI.encode(href)}\" class='attachment'>#{Path.basename(href)}</a>"
15 _ -> ""
16 end)
17 Enum.join([text | attachment_text], "<br>\n")
18 end
19
20 def format_input(text, mentions) do
21 HtmlSanitizeEx.strip_tags(text)
22 |> Formatter.linkify
23 |> String.replace("\n", "<br>\n")
24 |> add_user_links(mentions)
25 |> Formatter.finmojifiy
26 end
27
28 def add_user_links(text, mentions) do
29 mentions = mentions
30 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
31 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
32
33 # This replaces the mention with a unique reference first so it doesn't
34 # contain parts of other replaced mentions. There probably is a better
35 # solution for this...
36 step_one = mentions
37 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
38 String.replace(text, match, uuid)
39 end)
40
41 Enum.reduce(mentions, step_one, fn ({match, %User{ap_id: ap_id}, uuid}, text) ->
42 short_match = String.split(match, "@") |> tl() |> hd()
43 String.replace(text, uuid, "<a href='#{ap_id}'>@#{short_match}</a>")
44 end)
45 end
46
47 def make_content_html(status, mentions, attachments) do
48 status
49 |> format_input(mentions)
50 |> add_attachments(attachments)
51 end
52
53 def make_context(%Activity{data: %{"context" => context}}), do: context
54 def make_context(_), do: Utils.generate_context_id
55
56 # TODO: Move this to a more fitting space
57 def make_note_data(actor, to, context, content_html, attachments, inReplyTo, tags) do
58 object = %{
59 "type" => "Note",
60 "to" => to,
61 "content" => content_html,
62 "context" => context,
63 "attachment" => attachments,
64 "actor" => actor,
65 "tag" => tags |> Enum.map(fn ({_, tag}) -> tag end)
66 }
67
68 if inReplyTo do
69 object
70 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
71 |> Map.put("inReplyToStatusId", inReplyTo.id)
72 else
73 object
74 end
75 end
76 end