Merge branch 'develop' into oembed_provider
[akkoma] / lib / pleroma / formatter.ex
index 5b03e9aeb7b469903d12284d5e096fc3df722b8e..8024d97c2dc716454592cd5fc8e739d1962f4765 100644 (file)
@@ -5,6 +5,8 @@ defmodule Pleroma.Formatter do
   alias Pleroma.Emoji
 
   @tag_regex ~r/\#\w+/u
+  @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
+
   def parse_tags(text, data \\ %{}) do
     Regex.scan(@tag_regex, text)
     |> Enum.map(fn ["#" <> tag = full_tag] -> {full_tag, String.downcase(tag)} end)
@@ -18,7 +20,7 @@ defmodule Pleroma.Formatter do
   def parse_mentions(text) do
     # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
     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])?)*/u
+      ~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])?)*/u
 
     Regex.scan(regex, text)
     |> List.flatten()
@@ -76,6 +78,18 @@ defmodule Pleroma.Formatter do
     |> Enum.join("")
   end
 
+  @doc """
+  Escapes a special characters in mention names.
+  """
+  @spec mentions_escape(String.t(), list({String.t(), any()})) :: String.t()
+  def mentions_escape(text, mentions) do
+    mentions
+    |> Enum.reduce(text, fn {name, _}, acc ->
+      escape_name = String.replace(name, @markdown_characters_regex, "\\\\\\1")
+      String.replace(acc, name, escape_name)
+    end)
+  end
+
   @doc "changes scheme:... urls to html links"
   def add_links({subs, text}) do
     links =
@@ -163,4 +177,22 @@ defmodule Pleroma.Formatter do
       String.replace(result_text, uuid, replacement)
     end)
   end
+
+  def truncate(text, opts \\ []) do
+    max_length = opts[:max_length] || 200
+    omission = opts[:omission] || "..."
+
+    cond do
+      not String.valid?(text) ->
+        text
+
+      String.length(text) < max_length ->
+        text
+
+      true ->
+        length_with_omission = max_length - String.length(omission)
+
+        "#{String.slice(text, 0, length_with_omission)}#{omission}"
+    end
+  end
 end