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
6 def attachments_from_ids(ids) do
7 Enum.map(ids || [], fn (media_id) ->
8 Repo.get(Object, media_id).data
12 defp shortname(name) do
13 if String.length(name) < 30 do
16 String.slice(name, 0..30) <> "…"
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>"
27 Enum.join([text | attachment_text], "<br>\n")
30 def format_input(text, mentions) do
31 HtmlSanitizeEx.strip_tags(text)
33 |> String.replace("\n", "<br>\n")
34 |> add_user_links(mentions)
37 def add_user_links(text, mentions) do
39 |> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
40 |> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
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...
46 |> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
47 String.replace(text, match, uuid)
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>")
56 def make_content_html(status, mentions, attachments) do
58 |> format_input(mentions)
59 |> add_attachments(attachments)
62 def make_context(%Activity{data: %{"context" => context}}), do: context
63 def make_context(_), do: Utils.generate_context_id
65 # TODO: Move this to a more fitting space
66 def make_note_data(actor, to, context, content_html, attachments, inReplyTo, tags) do
70 "content" => content_html,
72 "attachment" => attachments,
74 "tag" => tags |> Enum.map(fn ({_, tag}) -> tag end)
79 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
80 |> Map.put("inReplyToStatusId", inReplyTo.id)
86 def format_naive_asctime(date) do
87 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
90 def format_asctime(date) do
91 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
94 def date_to_asctime(date) do
95 with {:ok, date, _offset} <- date |> DateTime.from_iso8601 do