github.com/gigforks/mattermost-server@v4.9.1-0.20180619094218-800d97fa55d0+incompatible/api/preference.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package api 5 6 import ( 7 "net/http" 8 9 "github.com/gorilla/mux" 10 "github.com/mattermost/mattermost-server/model" 11 ) 12 13 func (api *API) InitPreference() { 14 api.BaseRoutes.Preferences.Handle("/", api.ApiUserRequired(getAllPreferences)).Methods("GET") 15 api.BaseRoutes.Preferences.Handle("/save", api.ApiUserRequired(savePreferences)).Methods("POST") 16 api.BaseRoutes.Preferences.Handle("/delete", api.ApiUserRequired(deletePreferences)).Methods("POST") 17 api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", api.ApiUserRequired(getPreferenceCategory)).Methods("GET") 18 api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/{name:[A-Za-z0-9_]+}", api.ApiUserRequired(getPreference)).Methods("GET") 19 } 20 21 func getAllPreferences(c *Context, w http.ResponseWriter, r *http.Request) { 22 if result := <-c.App.Srv.Store.Preference().GetAll(c.Session.UserId); result.Err != nil { 23 c.Err = result.Err 24 } else { 25 data := result.Data.(model.Preferences) 26 27 w.Write([]byte(data.ToJson())) 28 } 29 } 30 31 func savePreferences(c *Context, w http.ResponseWriter, r *http.Request) { 32 preferences, err := model.PreferencesFromJson(r.Body) 33 if err != nil { 34 c.Err = model.NewAppError("savePreferences", "api.preference.save_preferences.decode.app_error", nil, err.Error(), http.StatusBadRequest) 35 return 36 } 37 38 if err := c.App.UpdatePreferences(c.Session.UserId, preferences); err != nil { 39 c.Err = err 40 return 41 } 42 43 w.Write([]byte("true")) 44 } 45 46 func getPreferenceCategory(c *Context, w http.ResponseWriter, r *http.Request) { 47 params := mux.Vars(r) 48 category := params["category"] 49 50 if result := <-c.App.Srv.Store.Preference().GetCategory(c.Session.UserId, category); result.Err != nil { 51 c.Err = result.Err 52 } else { 53 data := result.Data.(model.Preferences) 54 55 w.Write([]byte(data.ToJson())) 56 } 57 } 58 59 func getPreference(c *Context, w http.ResponseWriter, r *http.Request) { 60 params := mux.Vars(r) 61 category := params["category"] 62 name := params["name"] 63 64 if result := <-c.App.Srv.Store.Preference().Get(c.Session.UserId, category, name); result.Err != nil { 65 c.Err = result.Err 66 } else { 67 data := result.Data.(model.Preference) 68 w.Write([]byte(data.ToJson())) 69 } 70 } 71 72 func deletePreferences(c *Context, w http.ResponseWriter, r *http.Request) { 73 preferences, err := model.PreferencesFromJson(r.Body) 74 if err != nil { 75 c.Err = model.NewAppError("savePreferences", "api.preference.delete_preferences.decode.app_error", nil, err.Error(), http.StatusBadRequest) 76 return 77 } 78 79 if err := c.App.DeletePreferences(c.Session.UserId, preferences); err != nil { 80 c.Err = err 81 return 82 } 83 84 ReturnStatusOK(w) 85 }