summaryrefslogtreecommitdiffstats
path: root/api/preference.go
blob: 84cfc130c76a664325e9b3b2577af3e0ad5d8d8a (plain)
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
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.

package api

import (
	l4g "code.google.com/p/log4go"
	"encoding/json"
	"github.com/gorilla/mux"
	"github.com/mattermost/platform/model"
	"net/http"
)

func InitPreference(r *mux.Router) {
	l4g.Debug("Initializing preference api routes")

	sr := r.PathPrefix("/preferences").Subrouter()
	sr.Handle("/set", ApiAppHandler(setPreferences)).Methods("POST")
	sr.Handle("/{category:[A-Za-z0-9_]+}/{name:[A-Za-z0-9_]+}", ApiAppHandler(getPreferencesByName)).Methods("GET")
}

func setPreferences(c *Context, w http.ResponseWriter, r *http.Request) {
	var preferences []model.Preference

	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&preferences); err != nil {
		c.Err = model.NewAppError("setPreferences", "Unable to decode preferences from request", err.Error())
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	// just attempt to save/update them one by one and abort if one fails
	// in the future, this could probably be done in a transaction, but that's unnecessary now
	for _, preference := range preferences {
		if c.Session.UserId != preference.UserId {
			c.Err = model.NewAppError("setPreferences", "Unable to set preferences for other user", "session.user_id="+c.Session.UserId+", preference.user_id="+preference.UserId)
			c.Err.StatusCode = http.StatusUnauthorized
			return
		}

		if result := <-Srv.Store.Preference().Save(&preference); result.Err != nil {
			if result = <-Srv.Store.Preference().Update(&preference); result.Err != nil {
				c.Err = result.Err
				return
			}
		}
	}

	w.Write([]byte("true"))
}

func getPreferencesByName(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	category := params["category"]
	name := params["name"]

	if result := <-Srv.Store.Preference().GetByName(c.Session.UserId, category, name); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		data := result.Data.([]*model.Preference)

		if len(data) == 0 {
			if category == model.PREFERENCE_CATEGORY_DIRECT_CHANNELS && name == model.PREFERENCE_NAME_SHOW {
				// add direct channels for a user that existed before preferences were added
				data = AddDirectChannels(c.Session.UserId, c.Session.TeamId)
			}
		}

		w.Write([]byte(model.PreferenceListToJson(data)))
	}
}