X-Git-Url: http://git.squeep.com/?a=blobdiff_plain;f=lib%2Fpleroma%2Fformatter.ex;h=8024d97c2dc716454592cd5fc8e739d1962f4765;hb=a3003364598b42849e384a216948dad810481f51;hp=26bb17377094340d69a0280086cc146ee4e85f83;hpb=5c8b8f6cb7212bd202924b535cd2a263416e78d4;p=akkoma diff --git a/lib/pleroma/formatter.ex b/lib/pleroma/formatter.ex index 26bb17377..8024d97c2 100644 --- a/lib/pleroma/formatter.ex +++ b/lib/pleroma/formatter.ex @@ -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 = @@ -114,10 +128,10 @@ defmodule Pleroma.Formatter do subs = subs ++ - Enum.map(mentions, fn {match, %User{ap_id: ap_id, info: info}, uuid} -> + Enum.map(mentions, fn {match, %User{id: id, ap_id: ap_id, info: info}, uuid} -> ap_id = - if is_binary(info["source_data"]["url"]) do - info["source_data"]["url"] + if is_binary(info.source_data["url"]) do + info.source_data["url"] else ap_id end @@ -125,7 +139,7 @@ defmodule Pleroma.Formatter do short_match = String.split(match, "@") |> tl() |> hd() {uuid, - "@#{short_match}"} + "@#{short_match}"} end) {subs, uuid_text} @@ -147,7 +161,11 @@ defmodule Pleroma.Formatter do subs = subs ++ Enum.map(tags, fn {tag_text, tag, uuid} -> - url = "" + url = + "" + {uuid, url} end) @@ -159,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