github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/model/mention_map.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 "fmt" 8 "net/url" 9 ) 10 11 type UserMentionMap map[string]string 12 type ChannelMentionMap map[string]string 13 14 const ( 15 userMentionsKey = "user_mentions" 16 userMentionsIdsKey = "user_mentions_ids" 17 channelMentionsKey = "channel_mentions" 18 channelMentionsIdsKey = "channel_mentions_ids" 19 ) 20 21 func UserMentionMapFromURLValues(values url.Values) (UserMentionMap, error) { 22 return mentionsFromURLValues(values, userMentionsKey, userMentionsIdsKey) 23 } 24 25 func (m UserMentionMap) ToURLValues() url.Values { 26 return mentionsToURLValues(m, userMentionsKey, userMentionsIdsKey) 27 } 28 29 func ChannelMentionMapFromURLValues(values url.Values) (ChannelMentionMap, error) { 30 return mentionsFromURLValues(values, channelMentionsKey, channelMentionsIdsKey) 31 } 32 33 func (m ChannelMentionMap) ToURLValues() url.Values { 34 return mentionsToURLValues(m, channelMentionsKey, channelMentionsIdsKey) 35 } 36 37 func mentionsFromURLValues(values url.Values, mentionKey, idKey string) (map[string]string, error) { 38 mentions, mentionsOk := values[mentionKey] 39 ids, idsOk := values[idKey] 40 41 if !mentionsOk && !idsOk { 42 return map[string]string{}, nil 43 } 44 45 if !mentionsOk { 46 return nil, fmt.Errorf("%s key not found", mentionKey) 47 } 48 49 if !idsOk { 50 return nil, fmt.Errorf("%s key not found", idKey) 51 } 52 53 if len(mentions) != len(ids) { 54 return nil, fmt.Errorf("keys %s and %s have different length", mentionKey, idKey) 55 } 56 57 mentionsMap := make(map[string]string) 58 for i, mention := range mentions { 59 id := ids[i] 60 61 if oldId, ok := mentionsMap[mention]; ok && oldId != id { 62 return nil, fmt.Errorf("key %s has two different values: %s and %s", mention, oldId, id) 63 } 64 65 mentionsMap[mention] = id 66 } 67 68 return mentionsMap, nil 69 } 70 71 func mentionsToURLValues(mentions map[string]string, mentionKey, idKey string) url.Values { 72 values := url.Values{} 73 74 for mention, id := range mentions { 75 values.Add(mentionKey, mention) 76 values.Add(idKey, id) 77 } 78 79 return values 80 }