Add instance config options.
[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 alias Calendar.Strftime
5
6 def attachments_from_ids(ids) do
7 Enum.map(ids || [], fn (media_id) ->
8 Repo.get(Object, media_id).data
9 end)
10 end
11
12 defp shortname(name) do
13 if String.length(name) < 30 do
14 name
15 else
16 String.slice(name, 0..30) <> "…"
17 end
18 end
19
20 def add_attachments(text, attachments) do
21 attachment_text = Enum.map(attachments, fn
22 (%{"url" => [%{"href" => href} | _]}) ->
23 name = URI.decode(Path.basename(href))
24 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
25 _ -> ""
26 end)
27 Enum.join([text | attachment_text], "<br>\n")
28 end
29
30 def format_input(text, mentions) do
31 HtmlSanitizeEx.strip_tags(text)
32 |> Formatter.linkify
33 |> String.replace("\n", "<br>\n")
34 |> add_user_links(mentions)
35 end
36
37 def add_user_links(text, mentions) do
38 mentions = mentions
39 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
40 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
41
42 # This replaces the mention with a unique reference first so it doesn't
43 # contain parts of other replaced mentions. There probably is a better
44 # solution for this...
45 step_one = mentions
46 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
47 String.replace(text, match, uuid)
48 end)
49
50 Enum.reduce(mentions, step_one, fn ({match, %User{ap_id: ap_id}, uuid}, text) ->
51 short_match = String.split(match, "@") |> tl() |> hd()
52 String.replace(text, uuid, "<a href='#{ap_id}'>@#{short_match}</a>")
53 end)
54 end
55
56 def make_content_html(status, mentions, attachments) do
57 status
58 |> format_input(mentions)
59 |> add_attachments(attachments)
60 end
61
62 def make_context(%Activity{data: %{"context" => context}}), do: context
63 def make_context(_), do: Utils.generate_context_id
64
65 # TODO: Move this to a more fitting space
66 def make_note_data(actor, to, context, content_html, attachments, inReplyTo, tags) do
67 object = %{
68 "type" => "Note",
69 "to" => to,
70 "content" => content_html,
71 "context" => context,
72 "attachment" => attachments,
73 "actor" => actor,
74 "tag" => tags |> Enum.map(fn ({_, tag}) -> tag end)
75 }
76
77 if inReplyTo do
78 object
79 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
80 |> Map.put("inReplyToStatusId", inReplyTo.id)
81 else
82 object
83 end
84 end
85
86 def format_naive_asctime(date) do
87 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
88 end
89
90 def format_asctime(date) do
91 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
92 end
93
94 def date_to_asctime(date) do
95 with {:ok, date, _offset} <- date |> DateTime.from_iso8601 do
96 format_asctime(date)
97 else _e ->
98 ""
99 end
100 end
101 end