github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/model/at_mentions.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"regexp"
     8  	"strings"
     9  )
    10  
    11  var atMentionRegexp = regexp.MustCompile(`\B@[[:alnum:]][[:alnum:]\.\-_]*`)
    12  
    13  const usernameSpecialChars = ".-_"
    14  
    15  // PossibleAtMentions returns all substrings in message that look like valid @
    16  // mentions.
    17  func PossibleAtMentions(message string) []string {
    18  	var names []string
    19  
    20  	if !strings.Contains(message, "@") {
    21  		return names
    22  	}
    23  
    24  	alreadyMentioned := make(map[string]bool)
    25  	for _, match := range atMentionRegexp.FindAllString(message, -1) {
    26  		name := NormalizeUsername(match[1:])
    27  		if !alreadyMentioned[name] && IsValidUsername(name) {
    28  			names = append(names, name)
    29  			alreadyMentioned[name] = true
    30  		}
    31  	}
    32  
    33  	return names
    34  }
    35  
    36  // TrimUsernameSpecialChar tries to remove the last character from word if it
    37  // is a special character for usernames (dot, dash or underscore). If not, it
    38  // returns the same string.
    39  func TrimUsernameSpecialChar(word string) (string, bool) {
    40  	len := len(word)
    41  
    42  	if len > 0 && strings.LastIndexAny(word, usernameSpecialChars) == (len-1) {
    43  		return word[:len-1], true
    44  	}
    45  
    46  	return word, false
    47  }