summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/mattermost/mattermost-server/v6/model/mention_map.go
blob: 2f3444dd2f29cb0519bdbe4e581197794543ab38 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package model

import (
	"fmt"
	"net/url"
)

type UserMentionMap map[string]string
type ChannelMentionMap map[string]string

const (
	userMentionsKey       = "user_mentions"
	userMentionsIdsKey    = "user_mentions_ids"
	channelMentionsKey    = "channel_mentions"
	channelMentionsIdsKey = "channel_mentions_ids"
)

func UserMentionMapFromURLValues(values url.Values) (UserMentionMap, error) {
	return mentionsFromURLValues(values, userMentionsKey, userMentionsIdsKey)
}

func (m UserMentionMap) ToURLValues() url.Values {
	return mentionsToURLValues(m, userMentionsKey, userMentionsIdsKey)
}

func ChannelMentionMapFromURLValues(values url.Values) (ChannelMentionMap, error) {
	return mentionsFromURLValues(values, channelMentionsKey, channelMentionsIdsKey)
}

func (m ChannelMentionMap) ToURLValues() url.Values {
	return mentionsToURLValues(m, channelMentionsKey, channelMentionsIdsKey)
}

func mentionsFromURLValues(values url.Values, mentionKey, idKey string) (map[string]string, error) {
	mentions, mentionsOk := values[mentionKey]
	ids, idsOk := values[idKey]

	if !mentionsOk && !idsOk {
		return map[string]string{}, nil
	}

	if !mentionsOk {
		return nil, fmt.Errorf("%s key not found", mentionKey)
	}

	if !idsOk {
		return nil, fmt.Errorf("%s key not found", idKey)
	}

	if len(mentions) != len(ids) {
		return nil, fmt.Errorf("keys %s and %s have different length", mentionKey, idKey)
	}

	mentionsMap := make(map[string]string)
	for i, mention := range mentions {
		id := ids[i]

		if oldId, ok := mentionsMap[mention]; ok && oldId != id {
			return nil, fmt.Errorf("key %s has two different values: %s and %s", mention, oldId, id)
		}

		mentionsMap[mention] = id
	}

	return mentionsMap, nil
}

func mentionsToURLValues(mentions map[string]string, mentionKey, idKey string) url.Values {
	values := url.Values{}

	for mention, id := range mentions {
		values.Add(mentionKey, mention)
		values.Add(idKey, id)
	}

	return values
}