- @doc "Parses mentions text and returns list {nickname, user}."
- @spec parse_mentions(binary()) :: list({binary(), User.t()})
- def parse_mentions(text) do
- Regex.scan(@mentions_regex, text)
- |> List.flatten()
- |> Enum.uniq()
- |> Enum.map(fn nickname ->
- with nickname <- String.trim_leading(nickname, "@"),
- do: {"@" <> nickname, User.get_cached_by_nickname(nickname)}
- end)
- |> Enum.filter(fn {_match, user} -> user end)
+ def mention_handler("@" <> nickname, buffer, opts, acc) do
+ case User.get_cached_by_nickname(nickname) do
+ %User{id: id} = user ->
+ ap_id = get_ap_id(user)
+ nickname_text = get_nickname_text(nickname, opts)
+
+ link =
+ "<span class='h-card'><a data-user='#{id}' class='u-url mention' href='#{ap_id}'>@<span>#{
+ nickname_text
+ }</span></a></span>"
+
+ {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, user})}}
+
+ _ ->
+ {buffer, acc}
+ end
+ end
+
+ def hashtag_handler("#" <> tag = tag_text, _buffer, _opts, acc) do
+ tag = String.downcase(tag)
+ url = "#{Pleroma.Web.base_url()}/tag/#{tag}"
+ link = "<a class='hashtag' data-tag='#{tag}' href='#{url}' rel='tag'>#{tag_text}</a>"
+
+ {link, %{acc | tags: MapSet.put(acc.tags, {tag_text, tag})}}
+ end
+
+ @doc """
+ Parses a text and replace plain text links with HTML. Returns a tuple with a result text, mentions, and hashtags.
+
+ If the 'safe_mention' option is given, only consecutive mentions at the start the post are actually mentioned.
+ """
+ @spec linkify(String.t(), keyword()) ::
+ {String.t(), [{String.t(), User.t()}], [{String.t(), String.t()}]}
+ def linkify(text, options \\ []) do
+ options = options ++ @auto_linker_config
+
+ if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
+ %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
+ acc = %{mentions: MapSet.new(), tags: MapSet.new()}
+
+ {text_mentions, %{mentions: mentions}} = AutoLinker.link_map(mentions, acc, options)
+ {text_rest, %{tags: tags}} = AutoLinker.link_map(rest, acc, options)
+
+ {text_mentions <> text_rest, MapSet.to_list(mentions), MapSet.to_list(tags)}
+ else
+ acc = %{mentions: MapSet.new(), tags: MapSet.new()}
+ {text, %{mentions: mentions, tags: tags}} = AutoLinker.link_map(text, acc, options)
+
+ {text, MapSet.to_list(mentions), MapSet.to_list(tags)}
+ end
+ end
+
+ @doc """
+ Escapes a special characters in mention names.
+ """
+ def mentions_escape(text, options \\ []) do
+ options =
+ Keyword.merge(options,
+ mention: true,
+ url: false,
+ mention_handler: &Pleroma.Formatter.escape_mention_handler/4
+ )
+
+ if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
+ %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
+ AutoLinker.link(mentions, options) <> AutoLinker.link(rest, options)
+ else
+ AutoLinker.link(text, options)
+ end