[MM-22051] Remove To/From JSON (#18070)
* Posts * Add missing translation * Fix internal store marshaling * [MM-22051] Remove To/From JSON (Channels) (#18116) * Channels * Channel members * ChannelSearch * Channel categories, list, sidebar, stats, view * Fix conversions * [MM-22051] Remove To/From JSON (Users) (#18121) * User related structs * Fix return * Team related structures (#18127) * [MM-22051] Remove To/From JSON (Status, Bot, Reaction, Thread, FileInfo) (#18130) * Status * Bot * Reaction * Thread * FileInfo * Some fixes * Translations update from Weblate (#18143) * Translated using Weblate (German) Currently translated at 100.0% (2309 of 2309 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/de/ * Translated using Weblate (Turkish) Currently translated at 100.0% (2309 of 2309 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/tr/ * Translated using Weblate (Hungarian) Currently translated at 100.0% (2309 of 2309 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/hu/ * Update translation files Updated by "Cleanup translation files" hook in Weblate. Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ Update translation files Updated by "Cleanup translation files" hook in Weblate. Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ Update translation files Updated by "Cleanup translation files" hook in Weblate. Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ Update translation files Updated by "Cleanup translation files" hook in Weblate. Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ * Translated using Weblate (German) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/de/ * Translated using Weblate (Turkish) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/tr/ * Translated using Weblate (Hungarian) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/hu/ * Translated using Weblate (English (Australia)) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/en_AU/ * Translated using Weblate (Bulgarian) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/bg/ * Translated using Weblate (Japanese) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ja/ * Translated using Weblate (Chinese (Simplified)) Currently translated at 100.0% (2301 of 2301 strings) Translation: mattermost-languages-shipped/mattermost-server Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/zh_Hans/ Co-authored-by: JtheBAB <srast@bioc.uzh.ch> Co-authored-by: Kaya Zeren <kayazeren@gmail.com> Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu> Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au> Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com> Co-authored-by: kaakaa <stooner.hoe@gmail.com> Co-authored-by: aeomin <lin@aeomin.net> Co-authored-by: Weblate (bot) <hosted@weblate.org> Co-authored-by: JtheBAB <srast@bioc.uzh.ch> Co-authored-by: Kaya Zeren <kayazeren@gmail.com> Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu> Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au> Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com> Co-authored-by: kaakaa <stooner.hoe@gmail.com> Co-authored-by: aeomin <lin@aeomin.net> * [MM-22051] Remove To/From JSON methods from model (#18138) * Scheme * Role * Session * Config * Status * Fix logic * Emoji * GuestsInvite * Group * Command * ClusterInfo * License * Job * System * Plugin * Command2 * IncomingWebhook * OutgoingWebhook * Fix tests * Update traslation * Some fixes * Add missing return * Simplify * Make Config.ToJSONFiltered() return []byte * Make Busy.ToJSON() return []byte * Include error in log * Split logic * [MM-22051] Remove To/From JSON (final) (#18150) * SwitchRequest * PluginEventData * Permalink * PushNotification * SuggestCommand * PluginsResponse * WebSocketMessage * RemoteCluster * SharedChannel * PluginStatuses * InitialLoad * ClusterDiscovery * ClusterStats * MfaSecret * GroupSyncable * SAML * WebSocketRequest * TypingRequest * SecurityBulletin * OAuthApp * IntegrationAction * DataRetention * Preference * FileInfoList * Compliance * Preferences * FileInfoSearchResults * TermsOfService * InstallMarketplacePluginRequest * GitLabUser * UploadSessions * Remove unused helpers * Fix tests * [MM-23280] Fix linting for ToJSON/FromJSON (#18153) * SwitchRequest * PluginEventData * Permalink * PushNotification * SuggestCommand * PluginsResponse * WebSocketMessage * RemoteCluster * SharedChannel * PluginStatuses * InitialLoad * ClusterDiscovery * ClusterStats * MfaSecret * GroupSyncable * SAML * WebSocketRequest * TypingRequest * SecurityBulletin * OAuthApp * IntegrationAction * DataRetention * Preference * FileInfoList * Compliance * Preferences * FileInfoSearchResults * TermsOfService * InstallMarketplacePluginRequest * GitLabUser * UploadSessions * Remove unused helpers * Fix tests * Fix linting for ToJSON/FromJSON * Fix conversions Co-authored-by: Weblate (bot) <hosted@weblate.org> Co-authored-by: JtheBAB <srast@bioc.uzh.ch> Co-authored-by: Kaya Zeren <kayazeren@gmail.com> Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu> Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au> Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com> Co-authored-by: kaakaa <stooner.hoe@gmail.com> Co-authored-by: aeomin <lin@aeomin.net> Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
6861efb47e
Коммит
92837fa1ee
10
app/busy.go
10
app/busy.go
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -136,7 +137,7 @@ func (b *Busy) ClusterEventChanged(sbs *model.ServerBusyState) {
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Busy) ToJson() string {
|
||||
func (b *Busy) ToJSON() ([]byte, error) {
|
||||
b.mux.RLock()
|
||||
defer b.mux.RUnlock()
|
||||
|
||||
@@ -145,5 +146,10 @@ func (b *Busy) ToJson() string {
|
||||
Expires: b.expires.Unix(),
|
||||
ExpiresTS: b.expires.UTC().Format(TimestampFormat),
|
||||
}
|
||||
return sbs.ToJson()
|
||||
sbsJSON, jsonErr := json.Marshal(sbs)
|
||||
if jsonErr != nil {
|
||||
return []byte{}, fmt.Errorf("failed to encode server busy state to JSON: %w", jsonErr)
|
||||
}
|
||||
|
||||
return sbsJSON, nil
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -100,11 +100,15 @@ func TestBusyRace(t *testing.T) {
|
||||
func compareBusyState(t *testing.T, busy1 *Busy, busy2 *Busy) bool {
|
||||
t.Helper()
|
||||
if busy1.IsBusy() != busy2.IsBusy() {
|
||||
t.Logf("busy1:%s; busy2:%s\n", busy1.ToJson(), busy2.ToJson())
|
||||
busy1JSON, _ := busy1.ToJSON()
|
||||
busy2JSON, _ := busy2.ToJSON()
|
||||
t.Logf("busy1:%s; busy2:%s\n", busy1JSON, busy2JSON)
|
||||
return false
|
||||
}
|
||||
if busy1.Expires().Unix() != busy2.Expires().Unix() {
|
||||
t.Logf("busy1:%s; busy2:%s\n", busy1.ToJson(), busy2.ToJson())
|
||||
busy1JSON, _ := busy1.ToJSON()
|
||||
busy2JSON, _ := busy2.ToJSON()
|
||||
t.Logf("busy1:%s; busy2:%s\n", busy1JSON, busy2JSON)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -116,8 +120,9 @@ type ClusterMock struct {
|
||||
}
|
||||
|
||||
func (c *ClusterMock) SendClusterMessage(msg *model.ClusterMessage) {
|
||||
sbs := model.ServerBusyStateFromJson(bytes.NewReader(msg.Data))
|
||||
c.Busy.ClusterEventChanged(sbs)
|
||||
var sbs model.ServerBusyState
|
||||
json.Unmarshal(msg.Data, &sbs)
|
||||
c.Busy.ClusterEventChanged(&sbs)
|
||||
}
|
||||
|
||||
func (c *ClusterMock) SendClusterMessageToNode(nodeID string, msg *model.ClusterMessage) error {
|
||||
|
||||
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -510,7 +511,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha
|
||||
}
|
||||
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventGroupAdded, "", channel.Id, "", nil)
|
||||
message.Add("teammate_ids", model.ArrayToJson(userIDs))
|
||||
message.Add("teammate_ids", model.ArrayToJSON(userIDs))
|
||||
a.Publish(message)
|
||||
|
||||
return channel, nil
|
||||
@@ -527,7 +528,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr
|
||||
}
|
||||
|
||||
if len(users) != len(userIDs) {
|
||||
return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_user.app_error", nil, "user_ids="+model.ArrayToJson(userIDs), http.StatusBadRequest)
|
||||
return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_user.app_error", nil, "user_ids="+model.ArrayToJSON(userIDs), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
group := &model.Channel{
|
||||
@@ -606,7 +607,7 @@ func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError
|
||||
}
|
||||
|
||||
if len(users) != len(userIDs) {
|
||||
return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_user.app_error", nil, "user_ids="+model.ArrayToJson(userIDs), http.StatusBadRequest)
|
||||
return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_user.app_error", nil, "user_ids="+model.ArrayToJSON(userIDs), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
channel, appErr := a.GetChannelByName(model.GetGroupNameFromUserIds(userIDs), "", true)
|
||||
@@ -636,7 +637,11 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE
|
||||
a.invalidateCacheForChannel(channel)
|
||||
|
||||
messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelUpdated, "", channel.Id, "", nil)
|
||||
messageWs.Add("channel", channel.ToJson())
|
||||
channelJSON, jsonErr := json.Marshal(channel)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
messageWs.Add("channel", string(channelJSON))
|
||||
a.Publish(messageWs)
|
||||
|
||||
return channel, nil
|
||||
@@ -1248,7 +1253,11 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID s
|
||||
|
||||
// Notify the clients that the member notify props changed
|
||||
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil)
|
||||
evt.Add("channelMember", member.ToJson())
|
||||
memberJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
evt.Add("channelMember", string(memberJSON))
|
||||
a.Publish(evt)
|
||||
|
||||
return member, nil
|
||||
@@ -1273,7 +1282,11 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe
|
||||
|
||||
// Notify the clients that the member notify props changed
|
||||
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil)
|
||||
evt.Add("channelMember", member.ToJson())
|
||||
memberJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
evt.Add("channelMember", string(memberJSON))
|
||||
a.Publish(evt)
|
||||
|
||||
return member, nil
|
||||
@@ -2545,10 +2558,12 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapse
|
||||
}
|
||||
a.sanitizeProfiles(thread.Participants, false)
|
||||
thread.Post.SanitizeProps()
|
||||
|
||||
payload := thread.ToJson()
|
||||
payload, jsonErr := json.Marshal(thread)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode thread to JSON")
|
||||
}
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil)
|
||||
message.Add("thread", payload)
|
||||
message.Add("thread", string(payload))
|
||||
a.Publish(message)
|
||||
}
|
||||
} else if !threadMembership.Following && followThread {
|
||||
@@ -2661,10 +2676,13 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st
|
||||
a.sanitizeProfiles(thread.Participants, false)
|
||||
thread.Post.SanitizeProps()
|
||||
|
||||
payload := thread.ToJson()
|
||||
if a.isCRTEnabledForUser(userID) {
|
||||
payload, jsonErr := json.Marshal(thread)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode thread to JSON")
|
||||
}
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil)
|
||||
message.Add("thread", payload)
|
||||
message.Add("thread", string(payload))
|
||||
a.Publish(message)
|
||||
}
|
||||
channelUnread, nErr := a.Srv().Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, 0, false, false)
|
||||
@@ -3190,7 +3208,13 @@ func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) (
|
||||
a.invalidateCacheForChannelMembersNotifyProps(member.ChannelId)
|
||||
|
||||
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil)
|
||||
evt.Add("channelMember", member.ToJson())
|
||||
|
||||
memberJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
|
||||
evt.Add("channelMember", string(memberJSON))
|
||||
a.Publish(evt)
|
||||
}
|
||||
|
||||
@@ -3292,7 +3316,11 @@ func (a *App) ClearChannelMembersCache(channelID string) {
|
||||
clearSessionCache := func(channelMember model.ChannelMember) error {
|
||||
a.ClearSessionCacheForUser(channelMember.UserId)
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", channelMember.UserId, nil)
|
||||
message.Add("channelMember", channelMember.ToJson())
|
||||
memberJSON, jsonErr := json.Marshal(channelMember)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("channelMember", string(memberJSON))
|
||||
a.Publish(message)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/plugin"
|
||||
@@ -12,11 +13,19 @@ import (
|
||||
)
|
||||
|
||||
func (s *Server) clusterInstallPluginHandler(msg *model.ClusterMessage) {
|
||||
s.installPluginFromData(model.PluginEventDataFromJson(bytes.NewReader(msg.Data)))
|
||||
var data model.PluginEventData
|
||||
if jsonErr := json.Unmarshal(msg.Data, &data); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode from JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
s.installPluginFromData(data)
|
||||
}
|
||||
|
||||
func (s *Server) clusterRemovePluginHandler(msg *model.ClusterMessage) {
|
||||
s.removePluginFromData(model.PluginEventDataFromJson(bytes.NewReader(msg.Data)))
|
||||
var data model.PluginEventData
|
||||
if jsonErr := json.Unmarshal(msg.Data, &data); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode from JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
s.removePluginFromData(data)
|
||||
}
|
||||
|
||||
func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
|
||||
@@ -69,15 +78,19 @@ func (s *Server) registerClusterHandlers() {
|
||||
}
|
||||
|
||||
func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) {
|
||||
event := model.WebSocketEventFromJson(bytes.NewReader(msg.Data))
|
||||
if event == nil {
|
||||
event, err := model.WebSocketEventFromJSON(bytes.NewReader(msg.Data))
|
||||
if err != nil {
|
||||
mlog.Warn("Failed to decode event from JSON", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
s.PublishSkipClusterSend(event)
|
||||
}
|
||||
|
||||
func (s *Server) clusterUpdateStatusHandler(msg *model.ClusterMessage) {
|
||||
status := model.StatusFromJson(bytes.NewReader(msg.Data))
|
||||
var status model.Status
|
||||
if jsonErr := json.Unmarshal(msg.Data, &status); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode status from JSON")
|
||||
}
|
||||
s.statusCache.Set(status.UserId, status)
|
||||
}
|
||||
|
||||
@@ -120,7 +133,11 @@ func (s *Server) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMe
|
||||
}
|
||||
|
||||
func (s *Server) clusterBusyStateChgHandler(msg *model.ClusterMessage) {
|
||||
s.serverBusyStateChanged(model.ServerBusyStateFromJson(bytes.NewReader(msg.Data)))
|
||||
var sbs model.ServerBusyState
|
||||
if jsonErr := json.Unmarshal(msg.Data, &sbs); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode server busy state from JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
s.serverBusyStateChanged(&sbs)
|
||||
}
|
||||
|
||||
func (s *Server) invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelID string) {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -277,7 +278,10 @@ func (a *App) getDynamicListArgument(c *request.Context, commandArgs *model.Comm
|
||||
return false, parsed, toBeParsed, []model.AutocompleteSuggestion{}
|
||||
}
|
||||
|
||||
listItems := model.AutocompleteStaticListItemsFromJSON(resp.Body)
|
||||
var listItems []model.AutocompleteListItem
|
||||
if jsonErr := json.NewDecoder(resp.Body).Decode(&listItems); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode from JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
|
||||
return parseListItems(listItems, parsed, toBeParsed)
|
||||
}
|
||||
|
||||
@@ -460,14 +460,14 @@ func (es *Service) SendInviteEmails(team *model.Team, senderName string, senderU
|
||||
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": team.Id, "email": invite}),
|
||||
model.MapToJSON(map[string]string{"teamId": team.Id, "email": invite}),
|
||||
)
|
||||
|
||||
tokenProps := make(map[string]string)
|
||||
tokenProps["email"] = invite
|
||||
tokenProps["display_name"] = team.DisplayName
|
||||
tokenProps["name"] = team.Name
|
||||
tokenData := model.MapToJson(tokenProps)
|
||||
tokenData := model.MapToJSON(tokenProps)
|
||||
|
||||
if err := es.store.Token().Save(token); err != nil {
|
||||
mlog.Error("Failed to send invite email successfully ", mlog.Err(err))
|
||||
@@ -531,7 +531,7 @@ func (es *Service) SendGuestInviteEmails(team *model.Team, channels []*model.Cha
|
||||
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{
|
||||
model.MapToJSON(map[string]string{
|
||||
"teamId": team.Id,
|
||||
"channels": strings.Join(channelIDs, " "),
|
||||
"email": invite,
|
||||
@@ -543,7 +543,7 @@ func (es *Service) SendGuestInviteEmails(team *model.Team, channels []*model.Cha
|
||||
tokenProps["email"] = invite
|
||||
tokenProps["display_name"] = team.DisplayName
|
||||
tokenProps["name"] = team.Name
|
||||
tokenData := model.MapToJson(tokenProps)
|
||||
tokenData := model.MapToJSON(tokenProps)
|
||||
|
||||
if err := es.store.Token().Save(token); err != nil {
|
||||
mlog.Error("Failed to send invite email successfully ", mlog.Err(err))
|
||||
|
||||
@@ -6,6 +6,7 @@ package app
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
@@ -78,7 +79,11 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma
|
||||
}
|
||||
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventEmojiAdded, "", "", "", nil)
|
||||
message.Add("emoji", emoji.ToJson())
|
||||
emojiJSON, jsonErr := json.Marshal(emoji)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode emoji to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("emoji", string(emojiJSON))
|
||||
a.Publish(message)
|
||||
return emoji, nil
|
||||
}
|
||||
|
||||
14
app/group.go
14
app/group.go
@@ -4,10 +4,12 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
"github.com/mattermost/mattermost-server/v6/store"
|
||||
)
|
||||
|
||||
@@ -97,7 +99,11 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) {
|
||||
|
||||
if err == nil {
|
||||
messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil)
|
||||
messageWs.Add("group", updatedGroup.ToJson())
|
||||
groupJSON, jsonErr := json.Marshal(updatedGroup)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode group to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
messageWs.Add("group", string(groupJSON))
|
||||
a.Publish(messageWs)
|
||||
}
|
||||
|
||||
@@ -122,7 +128,11 @@ func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) {
|
||||
|
||||
if err == nil {
|
||||
messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil)
|
||||
messageWs.Add("group", deletedGroup.ToJson())
|
||||
groupJSON, jsonErr := json.Marshal(deletedGroup)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode group to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
messageWs.Add("group", string(groupJSON))
|
||||
a.Publish(messageWs)
|
||||
}
|
||||
|
||||
|
||||
@@ -457,7 +457,7 @@ func validatePostImportData(data *PostImportData, maxPostSize int) *model.AppErr
|
||||
}
|
||||
}
|
||||
|
||||
if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJson(*data.Props)) > model.PostPropsMaxRunes {
|
||||
if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJSON(*data.Props)) > model.PostPropsMaxRunes {
|
||||
return model.NewAppError("BulkImport", "app.import.validate_post_import_data.props_too_large.error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
|
||||
@@ -242,7 +242,11 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
resp, appErr = a.DoActionRequest(c, upstreamURL, upstreamRequest.ToJson())
|
||||
requestJSON, jsonErr := json.Marshal(upstreamRequest)
|
||||
if jsonErr != nil {
|
||||
return "", model.NewAppError("DoPostActionWithCookie", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
resp, appErr = a.DoActionRequest(c, upstreamURL, requestJSON)
|
||||
if appErr != nil {
|
||||
return "", appErr
|
||||
}
|
||||
@@ -530,7 +534,7 @@ type MailToLinkContent struct {
|
||||
MailBody string `json:"mail_body"`
|
||||
}
|
||||
|
||||
func (mlc *MailToLinkContent) ToJson() string {
|
||||
func (mlc *MailToLinkContent) ToJSON() string {
|
||||
b, _ := json.Marshal(mlc)
|
||||
return string(b)
|
||||
}
|
||||
@@ -569,7 +573,7 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s
|
||||
MailBody: mailBody,
|
||||
}
|
||||
|
||||
return mailToLinkContent.ToJson()
|
||||
return mailToLinkContent.ToJSON()
|
||||
}
|
||||
|
||||
func (a *App) DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
|
||||
@@ -29,8 +29,9 @@ func TestPostActionInvalidURL(t *testing.T) {
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
request := model.PostActionIntegrationRequestFromJson(r.Body)
|
||||
assert.NotNil(t, request)
|
||||
var request model.PostActionIntegrationRequest
|
||||
jsonErr := json.NewDecoder(r.Body).Decode(&request)
|
||||
assert.NoError(t, jsonErr)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
@@ -155,8 +156,9 @@ func TestPostAction(t *testing.T) {
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
request := model.PostActionIntegrationRequestFromJson(r.Body)
|
||||
assert.NotNil(t, request)
|
||||
var request model.PostActionIntegrationRequest
|
||||
jsonErr := json.NewDecoder(r.Body).Decode(&request)
|
||||
assert.NoError(t, jsonErr)
|
||||
|
||||
assert.Equal(t, request.UserId, th.BasicUser.Id)
|
||||
assert.Equal(t, request.UserName, th.BasicUser.Username)
|
||||
@@ -410,8 +412,9 @@ func TestPostActionProps(t *testing.T) {
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
request := model.PostActionIntegrationRequestFromJson(r.Body)
|
||||
assert.NotNil(t, request)
|
||||
var request model.PostActionIntegrationRequest
|
||||
jsonErr := json.NewDecoder(r.Body).Decode(&request)
|
||||
assert.NoError(t, jsonErr)
|
||||
|
||||
fmt.Fprintf(w, `{
|
||||
"update": {
|
||||
@@ -536,6 +539,8 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/plugin"
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
)
|
||||
@@ -553,7 +558,8 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
Errors: map[string]string{"name1": errReply},
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(response.ToJson())
|
||||
responseJSON, _ := json.Marshal(response)
|
||||
_, _ = w.Write(responseJSON)
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -606,8 +612,9 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
request := model.PostActionIntegrationRequestFromJson(r.Body)
|
||||
assert.NotNil(t, request)
|
||||
var request model.PostActionIntegrationRequest
|
||||
jsonErr := json.NewDecoder(r.Body).Decode(&request)
|
||||
assert.NoError(t, jsonErr)
|
||||
fmt.Fprintf(w, `{"post": {"message": "updated"}, "ephemeral_text": "foo"}`)
|
||||
}))
|
||||
defer ts.Close()
|
||||
@@ -824,6 +831,8 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/plugin"
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
)
|
||||
@@ -835,7 +844,8 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
func (p *MyPlugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
||||
response := &model.PostActionIntegrationResponse{}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(response.ToJson())
|
||||
responseJSON, _ := json.Marshal(response)
|
||||
_, _ = w.Write(responseJSON)
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
@@ -5,9 +5,9 @@ package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
@@ -100,7 +100,11 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr
|
||||
if !success {
|
||||
return nil, model.NewAppError("addLicense", model.InvalidLicenseError, nil, "", http.StatusBadRequest)
|
||||
}
|
||||
license := model.LicenseFromJson(strings.NewReader(licenseStr))
|
||||
|
||||
var license model.License
|
||||
if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil {
|
||||
return nil, model.NewAppError("addLicense", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
uniqueUserCount, err := s.Store.User().Count(model.UserCountOptions{})
|
||||
if err != nil {
|
||||
@@ -111,11 +115,11 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr
|
||||
return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]interface{}{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if license != nil && license.IsExpired() {
|
||||
if license.IsExpired() {
|
||||
return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if ok := s.SetLicense(license); !ok {
|
||||
if ok := s.SetLicense(&license); !ok {
|
||||
return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
@@ -165,7 +169,7 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr
|
||||
}
|
||||
}
|
||||
|
||||
return license, nil
|
||||
return &license, nil
|
||||
}
|
||||
|
||||
func (s *Server) SetLicense(license *model.License) bool {
|
||||
@@ -196,8 +200,12 @@ func (s *Server) SetLicense(license *model.License) bool {
|
||||
|
||||
func (s *Server) ValidateAndSetLicenseBytes(b []byte) bool {
|
||||
if success, licenseStr := utils.LicenseValidator.ValidateLicense(b); success {
|
||||
license := model.LicenseFromJson(strings.NewReader(licenseStr))
|
||||
s.SetLicense(license)
|
||||
var license model.License
|
||||
if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil {
|
||||
mlog.Warn("Failed to decode license from JSON", mlog.Err(jsonErr))
|
||||
return false
|
||||
}
|
||||
s.SetLicense(&license)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -254,12 +262,17 @@ func (s *Server) GetSanitizedClientLicense() map[string]string {
|
||||
|
||||
// RequestTrialLicense request a trial license from the mattermost official license server
|
||||
func (s *Server) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError {
|
||||
resp, err := http.Post(RequestTrialURL, "application/json", bytes.NewBuffer([]byte(trialRequest.ToJson())))
|
||||
trialRequestJSON, jsonErr := json.Marshal(trialRequest)
|
||||
if jsonErr != nil {
|
||||
return model.NewAppError("RequestTrialLicense", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
resp, err := http.Post(RequestTrialURL, "application/json", bytes.NewBuffer(trialRequestJSON))
|
||||
if err != nil {
|
||||
return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
licenseResponse := model.MapFromJson(resp.Body)
|
||||
licenseResponse := model.MapFromJSON(resp.Body)
|
||||
|
||||
if _, ok := licenseResponse["license"]; !ok {
|
||||
return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, licenseResponse["message"], http.StatusBadRequest)
|
||||
|
||||
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -524,7 +525,11 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventPosted, "", post.ChannelId, "", nil)
|
||||
|
||||
// Note that PreparePostForClient should've already been called by this point
|
||||
message.Add("post", post.ToJson())
|
||||
postJSON, jsonErr := post.ToJSON()
|
||||
if jsonErr != nil {
|
||||
return nil, errors.Wrapf(jsonErr, "failed to encode post to JSON")
|
||||
}
|
||||
message.Add("post", postJSON)
|
||||
|
||||
message.Add("channel_type", channel.Type)
|
||||
message.Add("channel_display_name", notification.GetChannelName(model.ShowUsername, ""))
|
||||
@@ -552,11 +557,11 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
|
||||
}
|
||||
|
||||
if len(mentionedUsersList) != 0 {
|
||||
message.Add("mentions", model.ArrayToJson(mentionedUsersList))
|
||||
message.Add("mentions", model.ArrayToJSON(mentionedUsersList))
|
||||
}
|
||||
|
||||
if len(notificationsForCRT.Desktop) != 0 {
|
||||
message.Add("followers", model.ArrayToJson(notificationsForCRT.Desktop))
|
||||
message.Add("followers", model.ArrayToJSON(notificationsForCRT.Desktop))
|
||||
}
|
||||
|
||||
published, err := a.publishWebsocketEventForPermalinkPost(post, message)
|
||||
@@ -607,7 +612,12 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
|
||||
}
|
||||
}
|
||||
|
||||
message.Add("thread", userThread.ToJson())
|
||||
payload, jsonErr := json.Marshal(userThread)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode thread to JSON")
|
||||
}
|
||||
message.Add("thread", string(payload))
|
||||
|
||||
a.Publish(message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
@@ -367,8 +369,13 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio
|
||||
mlog.String("status", model.PushSendPrepare),
|
||||
)
|
||||
|
||||
msgJSON, jsonErr := json.Marshal(msg)
|
||||
if jsonErr != nil {
|
||||
return errors.Wrap(jsonErr, "failed to encode to JSON")
|
||||
}
|
||||
|
||||
url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.APIURLSuffixV1 + "/send_push"
|
||||
request, err := http.NewRequest("POST", url, strings.NewReader(msg.ToJson()))
|
||||
request, err := http.NewRequest("POST", url, bytes.NewReader(msgJSON))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -379,7 +386,10 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
pushResponse := model.PushResponseFromJson(resp.Body)
|
||||
var pushResponse model.PushResponse
|
||||
if jsonErr := json.NewDecoder(resp.Body).Decode(&pushResponse); jsonErr != nil {
|
||||
return errors.Wrap(jsonErr, "failed to decode from JSON")
|
||||
}
|
||||
|
||||
switch pushResponse[model.PushStatus] {
|
||||
case model.PushStatusRemove:
|
||||
@@ -405,10 +415,15 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error {
|
||||
mlog.String("status", model.PushReceived),
|
||||
)
|
||||
|
||||
ackJSON, jsonErr := json.Marshal(ack)
|
||||
if jsonErr != nil {
|
||||
return errors.Wrap(jsonErr, "failed to encode to JSON")
|
||||
}
|
||||
|
||||
request, err := http.NewRequest(
|
||||
"POST",
|
||||
strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.APIURLSuffixV1+"/ack",
|
||||
strings.NewReader(ack.ToJson()),
|
||||
bytes.NewReader(ackJSON),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -1024,18 +1025,19 @@ func (h *testPushNotificationHandler) handleReq(w http.ResponseWriter, r *http.R
|
||||
// Don't do any checking if it's a benchmark
|
||||
if _, ok := h.t.(*testing.B); ok {
|
||||
resp := model.NewOkPushResponse()
|
||||
fmt.Fprintln(w, (&resp).ToJson())
|
||||
jsonData, _ := json.Marshal(&resp)
|
||||
fmt.Fprintln(w, jsonData)
|
||||
return
|
||||
}
|
||||
|
||||
var notification *model.PushNotification
|
||||
var notificationAck *model.PushNotificationAck
|
||||
var notification model.PushNotification
|
||||
var notificationAck model.PushNotificationAck
|
||||
var err error
|
||||
if r.URL.Path == "/api/v1/send_push" {
|
||||
notification, err = model.PushNotificationFromJson(r.Body)
|
||||
if err != nil {
|
||||
if err = json.NewDecoder(r.Body).Decode(¬ification); err != nil {
|
||||
resp := model.NewErrorPushResponse("fail")
|
||||
fmt.Fprintln(w, (&resp).ToJson())
|
||||
jsonData, _ := json.Marshal(&resp)
|
||||
fmt.Fprintln(w, jsonData)
|
||||
return
|
||||
}
|
||||
// We verify that messages are being sent in order per-device.
|
||||
@@ -1047,10 +1049,10 @@ func (h *testPushNotificationHandler) handleReq(w http.ResponseWriter, r *http.R
|
||||
defer h.serialUserMap.Delete(notification.DeviceId)
|
||||
}
|
||||
} else {
|
||||
notificationAck, err = model.PushNotificationAckFromJson(r.Body)
|
||||
if err != nil {
|
||||
if err = json.NewDecoder(r.Body).Decode(¬ificationAck); err != nil {
|
||||
resp := model.NewErrorPushResponse("fail")
|
||||
fmt.Fprintln(w, (&resp).ToJson())
|
||||
jsonData, _ := json.Marshal(&resp)
|
||||
fmt.Fprintln(w, jsonData)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1061,9 +1063,9 @@ func (h *testPushNotificationHandler) handleReq(w http.ResponseWriter, r *http.R
|
||||
// Little bit of duplicate condition check so that we can check the in-order property
|
||||
// first.
|
||||
if r.URL.Path == "/api/v1/send_push" {
|
||||
h._notifications = append(h._notifications, notification)
|
||||
h._notifications = append(h._notifications, ¬ification)
|
||||
} else {
|
||||
h._notificationAcks = append(h._notificationAcks, notificationAck)
|
||||
h._notificationAcks = append(h._notificationAcks, ¬ificationAck)
|
||||
}
|
||||
|
||||
var resp model.PushResponse
|
||||
@@ -1077,7 +1079,8 @@ func (h *testPushNotificationHandler) handleReq(w http.ResponseWriter, r *http.R
|
||||
resp = model.NewRemovePushResponse()
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(w, (&resp).ToJson())
|
||||
jsonData, _ := json.Marshal(&resp)
|
||||
fmt.Fprintln(w, jsonData)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -582,7 +582,7 @@ func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reade
|
||||
map[string]interface{}{"Service": service}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
authUser, err1 := provider.GetUserFromJson(bytes.NewReader(buf.Bytes()), tokenUser)
|
||||
authUser, err1 := provider.GetUserFromJSON(bytes.NewReader(buf.Bytes()), tokenUser)
|
||||
if err1 != nil {
|
||||
return nil, model.NewAppError("LoginByOAuth", "api.user.login_by_oauth.parse.app_error",
|
||||
map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest)
|
||||
@@ -633,7 +633,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email
|
||||
return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.blank_email.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
ssoUser, err1 := provider.GetUserFromJson(userData, tokenUser)
|
||||
ssoUser, err1 := provider.GetUserFromJSON(userData, tokenUser)
|
||||
if err1 != nil {
|
||||
return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.parse.app_error",
|
||||
map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest)
|
||||
@@ -744,7 +744,7 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi
|
||||
}
|
||||
|
||||
props["token"] = stateToken.Token
|
||||
state := b64.StdEncoding.EncodeToString([]byte(model.MapToJson(props)))
|
||||
state := b64.StdEncoding.EncodeToString([]byte(model.MapToJSON(props)))
|
||||
|
||||
siteURL := a.GetSiteURL()
|
||||
if strings.TrimSpace(siteURL) == "" {
|
||||
@@ -783,7 +783,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
|
||||
}
|
||||
|
||||
stateStr := string(b)
|
||||
stateProps := model.MapFromJson(strings.NewReader(stateStr))
|
||||
stateProps := model.MapFromJSON(strings.NewReader(stateStr))
|
||||
|
||||
expectedToken, appErr := a.GetOAuthStateToken(stateProps["token"])
|
||||
if appErr != nil {
|
||||
|
||||
@@ -152,7 +152,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
|
||||
}
|
||||
|
||||
makeState := func(token *model.Token) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(model.MapToJson(map[string]string{
|
||||
return base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(map[string]string{
|
||||
"token": token.Token,
|
||||
})))
|
||||
}
|
||||
@@ -199,7 +199,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
|
||||
th := setup(t, true, true, true, "")
|
||||
defer th.TearDown()
|
||||
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(map[string]string{
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(map[string]string{
|
||||
"token": model.NewId(),
|
||||
})))
|
||||
|
||||
@@ -235,7 +235,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
|
||||
token, err := th.App.CreateOAuthStateToken(generateOAuthStateTokenExtra(email, action, cookie))
|
||||
require.Nil(t, err)
|
||||
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(map[string]string{
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(map[string]string{
|
||||
"action": action,
|
||||
"email": email,
|
||||
"token": token.Token,
|
||||
@@ -489,7 +489,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
|
||||
"team_id": model.NewId(),
|
||||
"token": makeToken(th, cookie).Token,
|
||||
}
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
|
||||
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJSON(stateProps)))
|
||||
|
||||
recorder := httptest.ResponseRecorder{}
|
||||
body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
@@ -32,9 +32,17 @@ func (p *Plugin) ServeHTTP(_ *plugin.Context, w http.ResponseWriter, r *http.Req
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
req := model.WebSocketRequestFromJson(bytes.NewReader(msg))
|
||||
var req model.WebSocketRequest
|
||||
err = json.Unmarshal(msg, &req)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
resp := model.NewWebSocketResponse("OK", req.Seq, map[string]interface{}{"action": req.Action, "value": req.Data["value"]})
|
||||
if err = ws.WriteMessage(mt, resp.ToJson()); err != nil {
|
||||
respJSON, err := resp.ToJSON()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if err = ws.WriteMessage(mt, respJSON); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -99,8 +100,10 @@ func TestInstallPluginLocally(t *testing.T) {
|
||||
Id: id,
|
||||
Version: version,
|
||||
}
|
||||
manifestJSON, jsonErr := json.Marshal(manifest)
|
||||
require.NoError(t, jsonErr)
|
||||
reader := makeInMemoryGzipTarFile(t, []testFile{
|
||||
{"plugin.json", manifest.ToJson()},
|
||||
{"plugin.json", string(manifestJSON)},
|
||||
})
|
||||
|
||||
actualManifest, appError := th.App.installPluginLocally(reader, nil, installationStrategy)
|
||||
|
||||
@@ -27,7 +27,7 @@ func (s *Server) ServePluginRequest(w http.ResponseWriter, r *http.Request) {
|
||||
s.Log.Error(err.Error())
|
||||
w.WriteHeader(err.StatusCode)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(err.ToJson()))
|
||||
w.Write([]byte(err.ToJSON()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func (a *App) ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, so
|
||||
a.Log().Error(err.Error())
|
||||
w.WriteHeader(err.StatusCode)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(err.ToJson()))
|
||||
w.Write([]byte(err.ToJSON()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
32
app/post.go
32
app/post.go
@@ -522,7 +522,12 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post {
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventEphemeralMessage, "", post.ChannelId, userID, nil)
|
||||
post = a.PreparePostForClient(post, true, false)
|
||||
post = model.AddPostActionCookies(post, a.PostActionCookieSecret())
|
||||
message.Add("post", post.ToJson())
|
||||
|
||||
postJSON, jsonErr := post.ToJSON()
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("post", postJSON)
|
||||
a.Publish(message)
|
||||
|
||||
return post
|
||||
@@ -540,7 +545,11 @@ func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post {
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", post.ChannelId, userID, nil)
|
||||
post = a.PreparePostForClient(post, true, false)
|
||||
post = model.AddPostActionCookies(post, a.PostActionCookieSecret())
|
||||
message.Add("post", post.ToJson())
|
||||
postJSON, jsonErr := post.ToJSON()
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("post", postJSON)
|
||||
a.Publish(message)
|
||||
|
||||
return post
|
||||
@@ -556,7 +565,11 @@ func (a *App) DeleteEphemeralPost(userID, postID string) {
|
||||
}
|
||||
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", "", userID, nil)
|
||||
message.Add("post", post.ToJson())
|
||||
postJSON, jsonErr := post.ToJSON()
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("post", postJSON)
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
@@ -684,7 +697,11 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool)
|
||||
}
|
||||
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", rpost.ChannelId, "", nil)
|
||||
message.Add("post", rpost.ToJson())
|
||||
postJSON, jsonErr := rpost.ToJSON()
|
||||
if jsonErr != nil {
|
||||
return nil, model.NewAppError("UpdatePost", "app.post.marshal.app_error", nil, jsonErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
message.Add("post", postJSON)
|
||||
|
||||
published, err := a.publishWebsocketEventForPermalinkPost(rpost, message)
|
||||
if err != nil {
|
||||
@@ -744,7 +761,12 @@ func (a *App) publishWebsocketEventForPermalinkPost(post *model.Post, message *m
|
||||
broadcastCopy := messageCopy.GetBroadcast()
|
||||
broadcastCopy.UserId = cm.UserId
|
||||
messageCopy.SetBroadcast(broadcastCopy)
|
||||
messageCopy.Add("post", postForUser.ToJson())
|
||||
|
||||
postJSON, jsonErr := postForUser.ToJSON()
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
messageCopy.Add("post", postJSON)
|
||||
a.Publish(messageCopy)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
)
|
||||
|
||||
func (a *App) GetPreferencesForUser(userID string) (model.Preferences, *model.AppError) {
|
||||
@@ -65,7 +67,11 @@ func (a *App) UpdatePreferences(userID string, preferences model.Preferences) *m
|
||||
a.Publish(message)
|
||||
|
||||
message = model.NewWebSocketEvent(model.WebsocketEventPreferencesChanged, "", "", userID, nil)
|
||||
message.Add("preferences", preferences.ToJson())
|
||||
prefsJSON, jsonErr := json.Marshal(preferences)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("preferences", string(prefsJSON))
|
||||
a.Publish(message)
|
||||
|
||||
return nil
|
||||
@@ -95,7 +101,11 @@ func (a *App) DeletePreferences(userID string, preferences model.Preferences) *m
|
||||
a.Publish(message)
|
||||
|
||||
message = model.NewWebSocketEvent(model.WebsocketEventPreferencesDeleted, "", "", userID, nil)
|
||||
message.Add("preferences", preferences.ToJson())
|
||||
prefsJSON, jsonErr := json.Marshal(preferences)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("preferences", string(prefsJSON))
|
||||
a.Publish(message)
|
||||
|
||||
return nil
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/app/request"
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/plugin"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
)
|
||||
|
||||
func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) {
|
||||
@@ -159,6 +161,10 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction
|
||||
func (a *App) sendReactionEvent(event string, reaction *model.Reaction, post *model.Post) {
|
||||
// send out that a reaction has been added/removed
|
||||
message := model.NewWebSocketEvent(event, "", post.ChannelId, "", nil)
|
||||
message.Add("reaction", reaction.ToJson())
|
||||
reactionJSON, jsonErr := json.Marshal(reaction)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode reaction to JSON")
|
||||
}
|
||||
message.Add("reaction", string(reactionJSON))
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
"github.com/mattermost/mattermost-server/v6/store"
|
||||
"github.com/mattermost/mattermost-server/v6/utils"
|
||||
)
|
||||
@@ -240,7 +242,11 @@ func (a *App) CheckRolesExist(roleNames []string) *model.AppError {
|
||||
|
||||
func (a *App) sendUpdatedRoleEvent(role *model.Role) {
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventRoleUpdated, "", "", "", nil)
|
||||
message.Add("role", role.ToJson())
|
||||
roleJSON, jsonErr := json.Marshal(role)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode role to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("role", string(roleJSON))
|
||||
|
||||
a.Srv().Go(func() {
|
||||
a.Publish(message)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -88,7 +89,11 @@ func (s *Server) DoSecurityUpdateCheck() {
|
||||
|
||||
defer res.Body.Close()
|
||||
|
||||
bulletins := model.SecurityBulletinsFromJson(res.Body)
|
||||
var bulletins model.SecurityBulletins
|
||||
if jsonErr := json.NewDecoder(res.Body).Decode(&bulletins); jsonErr != nil {
|
||||
mlog.Error("Failed to decode JSON", mlog.Err(jsonErr))
|
||||
return
|
||||
}
|
||||
|
||||
for _, bulletin := range bulletins {
|
||||
if bulletin.AppliesToVersion == model.CurrentVersion {
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/app"
|
||||
"github.com/mattermost/mattermost-server/v6/app/request"
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
)
|
||||
|
||||
type ExpandProvider struct {
|
||||
@@ -75,7 +77,12 @@ func setCollapsePreference(a *app.App, args *model.CommandArgs, isCollapse bool)
|
||||
}
|
||||
|
||||
socketMessage := model.NewWebSocketEvent(model.WebsocketEventPreferenceChanged, "", "", args.UserId, nil)
|
||||
socketMessage.Add("preference", pref.ToJson())
|
||||
|
||||
prefJSON, jsonErr := json.Marshal(pref)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
socketMessage.Add("preference", string(prefJSON))
|
||||
a.Publish(socketMessage)
|
||||
|
||||
var rmsg string
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
@@ -542,8 +543,8 @@ func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model
|
||||
r.Body.Close()
|
||||
}()
|
||||
|
||||
post := model.PostFromJson(r.Body)
|
||||
if post == nil {
|
||||
var post model.Post
|
||||
if jsonErr := json.NewDecoder(r.Body).Decode(&post); jsonErr != nil {
|
||||
return &model.CommandResponse{Text: "Unable to decode post", ResponseType: model.CommandResponseTypeEphemeral}, errors.Errorf("could not decode post from json")
|
||||
}
|
||||
post.ChannelId = args.ChannelId
|
||||
@@ -552,7 +553,7 @@ func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model
|
||||
post.Message = message
|
||||
}
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(c, post, false); err != nil {
|
||||
if _, err := a.CreatePostMissingChannel(c, &post, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.CommandResponseTypeEphemeral}, err
|
||||
}
|
||||
|
||||
|
||||
@@ -50,8 +50,8 @@ func TestShareProviderDoCommand(t *testing.T) {
|
||||
require.Equal(t, "##### "+args.T("api.command_share.channel_shared"), response.Text)
|
||||
|
||||
channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool {
|
||||
event := model.WebSocketEventFromJson(bytes.NewReader(msg.Data))
|
||||
return event != nil && event.EventType() == model.WebsocketEventChannelConverted
|
||||
event, err := model.WebSocketEventFromJSON(bytes.NewReader(msg.Data))
|
||||
return err == nil && event.EventType() == model.WebsocketEventChannelConverted
|
||||
})
|
||||
assert.Len(t, channelConvertedMessages, 1)
|
||||
})
|
||||
@@ -85,8 +85,8 @@ func TestShareProviderDoCommand(t *testing.T) {
|
||||
require.Equal(t, "##### "+args.T("api.command_share.shared_channel_unavailable"), response.Text)
|
||||
|
||||
channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool {
|
||||
event := model.WebSocketEventFromJson(bytes.NewReader(msg.Data))
|
||||
return event != nil && event.EventType() == model.WebsocketEventChannelConverted
|
||||
event, err := model.WebSocketEventFromJSON(bytes.NewReader(msg.Data))
|
||||
return err == nil && event.EventType() == model.WebsocketEventChannelConverted
|
||||
})
|
||||
require.Len(t, channelConvertedMessages, 1)
|
||||
})
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/shared/mlog"
|
||||
@@ -21,10 +21,14 @@ func (a *App) AddStatusCache(status *model.Status) {
|
||||
a.AddStatusCacheSkipClusterSend(status)
|
||||
|
||||
if a.Cluster() != nil {
|
||||
statusJSON, jsonErr := json.Marshal(status)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode status to JSON")
|
||||
}
|
||||
msg := &model.ClusterMessage{
|
||||
Event: model.ClusterEventUpdateStatus,
|
||||
SendType: model.ClusterSendBestEffort,
|
||||
Data: []byte(status.ToClusterJson()),
|
||||
Data: statusJSON,
|
||||
}
|
||||
a.Cluster().SendClusterMessage(msg)
|
||||
}
|
||||
@@ -443,15 +447,22 @@ func (a *App) addRecentCustomStatus(userID string, status *model.CustomStatus) *
|
||||
if err != nil || pref.Value == "" {
|
||||
newRCS = model.RecentCustomStatuses{*status}
|
||||
} else {
|
||||
existingRCS := model.RecentCustomStatusesFromJson(strings.NewReader(pref.Value))
|
||||
var existingRCS model.RecentCustomStatuses
|
||||
if jsonErr := json.Unmarshal([]byte(pref.Value), &existingRCS); jsonErr != nil {
|
||||
return model.NewAppError("addRecentCustomStatus", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
newRCS = existingRCS.Add(status)
|
||||
}
|
||||
|
||||
newRCSJSON, jsonErr := json.Marshal(newRCS)
|
||||
if jsonErr != nil {
|
||||
return model.NewAppError("addRecentCustomStatus", "api.marshal_error", nil, jsonErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
pref = &model.Preference{
|
||||
UserId: userID,
|
||||
Category: model.PreferenceCategoryCustomStatus,
|
||||
Name: model.PreferenceNameRecentCustomStatuses,
|
||||
Value: newRCS.ToJson(),
|
||||
Value: string(newRCSJSON),
|
||||
}
|
||||
if err := a.UpdatePreferences(userID, model.Preferences{*pref}); err != nil {
|
||||
return err
|
||||
@@ -470,14 +481,25 @@ func (a *App) RemoveRecentCustomStatus(userID string, status *model.CustomStatus
|
||||
return model.NewAppError("RemoveRecentCustomStatus", "api.custom_status.recent_custom_statuses.delete.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
existingRCS := model.RecentCustomStatusesFromJson(strings.NewReader(pref.Value))
|
||||
if !existingRCS.Contains(status) {
|
||||
var existingRCS model.RecentCustomStatuses
|
||||
if jsonErr := json.Unmarshal([]byte(pref.Value), &existingRCS); jsonErr != nil {
|
||||
return model.NewAppError("RemoveRecentCustomStatus", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if ok, err := existingRCS.Contains(status); !ok || err != nil {
|
||||
return model.NewAppError("RemoveRecentCustomStatus", "api.custom_status.recent_custom_statuses.delete.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
newRCS := existingRCS.Remove(status)
|
||||
pref.Value = newRCS.ToJson()
|
||||
newRCS, removeErr := existingRCS.Remove(status)
|
||||
if removeErr != nil {
|
||||
return model.NewAppError("RemoveRecentCustomStatus", "api.custom_status.recent_custom_statuses.delete.app_error", nil, removeErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
newRCSJSON, jsonErr := json.Marshal(newRCS)
|
||||
if jsonErr != nil {
|
||||
return model.NewAppError("RemoveRecentCustomStatus", "api.marshal_error", nil, jsonErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
pref.Value = string(newRCSJSON)
|
||||
if err := a.UpdatePreferences(userID, model.Preferences{*pref}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
23
app/team.go
23
app/team.go
@@ -6,6 +6,7 @@ package app
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
@@ -337,7 +338,11 @@ func (a *App) sendTeamEvent(team *model.Team, event string) {
|
||||
teamID = team.Id
|
||||
}
|
||||
message := model.NewWebSocketEvent(event, teamID, "", "", nil)
|
||||
message.Add("team", sanitizedTeam.ToJson())
|
||||
teamJSON, jsonErr := json.Marshal(team)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode team to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("team", string(teamJSON))
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
@@ -479,7 +484,11 @@ func (a *App) UpdateTeamMemberSchemeRoles(teamID string, userID string, isScheme
|
||||
|
||||
func (a *App) sendUpdatedMemberRoleEvent(userID string, member *model.TeamMember) {
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventMemberroleUpdated, "", "", userID, nil)
|
||||
message.Add("member", member.ToJson())
|
||||
tmJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode team member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("member", string(tmJSON))
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
@@ -563,7 +572,7 @@ func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID st
|
||||
return nil, nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
tokenData := model.MapFromJson(strings.NewReader(token.Extra))
|
||||
tokenData := model.MapFromJSON(strings.NewReader(token.Extra))
|
||||
|
||||
tchan := make(chan store.StoreResult, 1)
|
||||
go func() {
|
||||
@@ -1862,7 +1871,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) {
|
||||
return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.expired_link.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
tokenData := model.MapFromJson(strings.NewReader(token.Extra))
|
||||
tokenData := model.MapFromJSON(strings.NewReader(token.Extra))
|
||||
|
||||
return tokenData["teamId"], nil
|
||||
}
|
||||
@@ -2027,7 +2036,11 @@ func (a *App) ClearTeamMembersCache(teamID string) {
|
||||
a.ClearSessionCacheForUser(teamMember.UserId)
|
||||
|
||||
message := model.NewWebSocketEvent(model.WebsocketEventMemberroleUpdated, "", "", teamMember.UserId, nil)
|
||||
message.Add("member", teamMember.ToJson())
|
||||
tmJSON, jsonErr := json.Marshal(teamMember)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode team member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
message.Add("member", string(tmJSON))
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
|
||||
@@ -202,7 +202,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("invalid token type", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeVerifyEmail,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
@@ -215,7 +215,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("expired token", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
|
||||
token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1
|
||||
@@ -229,7 +229,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("invalid team id", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": model.NewId()}),
|
||||
model.MapToJSON(map[string]string{"teamId": model.NewId()}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
defer th.App.DeleteToken(token)
|
||||
@@ -241,7 +241,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("invalid user id", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
defer th.App.DeleteToken(token)
|
||||
@@ -253,7 +253,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("valid request", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
_, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token)
|
||||
@@ -270,7 +270,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("invalid add a guest using a regular invite", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
_, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token)
|
||||
@@ -280,7 +280,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("invalid add a regular user using a guest invite", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
_, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token)
|
||||
@@ -295,7 +295,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" })
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
_, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token)
|
||||
@@ -311,7 +311,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" })
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
guestEmail := rguest.Email
|
||||
rguest.Email = "test@restricted.com"
|
||||
@@ -337,7 +337,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "restricted.com" })
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
_, err = th.App.Srv().Store.User().Update(rguest, false)
|
||||
require.NoError(t, err)
|
||||
@@ -352,7 +352,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
t.Run("valid request from guest invite", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
|
||||
@@ -375,7 +375,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
|
||||
@@ -399,7 +399,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
|
||||
@@ -414,7 +414,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
|
||||
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": team.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": team.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
|
||||
|
||||
18
app/user.go
18
app/user.go
@@ -54,7 +54,7 @@ func (a *App) CreateUserWithToken(c *request.Context, user *model.User, token *m
|
||||
return nil, model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
tokenData := model.MapFromJson(strings.NewReader(token.Extra))
|
||||
tokenData := model.MapFromJSON(strings.NewReader(token.Extra))
|
||||
|
||||
team, nErr := a.Srv().Store.Team().Get(tokenData["teamId"])
|
||||
if nErr != nil {
|
||||
@@ -294,7 +294,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
user, err1 := provider.GetUserFromJson(userData, tokenUser)
|
||||
user, err1 := provider.GetUserFromJSON(userData, tokenUser)
|
||||
if err1 != nil {
|
||||
return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]interface{}{"Service": service}, err1.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -1816,7 +1816,7 @@ func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model
|
||||
}
|
||||
|
||||
func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError {
|
||||
oauthUser, err1 := provider.GetUserFromJson(userData, tokenUser)
|
||||
oauthUser, err1 := provider.GetUserFromJSON(userData, tokenUser)
|
||||
if err1 != nil {
|
||||
return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest)
|
||||
}
|
||||
@@ -2060,7 +2060,11 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor
|
||||
a.invalidateCacheForChannelMembers(member.ChannelId)
|
||||
|
||||
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", user.Id, nil)
|
||||
evt.Add("channelMember", member.ToJson())
|
||||
memberJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
evt.Add("channelMember", string(memberJSON))
|
||||
a.Publish(evt)
|
||||
}
|
||||
}
|
||||
@@ -2101,7 +2105,11 @@ func (a *App) DemoteUserToGuest(user *model.User) *model.AppError {
|
||||
a.invalidateCacheForChannelMembers(member.ChannelId)
|
||||
|
||||
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", user.Id, nil)
|
||||
evt.Add("channelMember", member.ToJson())
|
||||
memberJSON, jsonErr := json.Marshal(member)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
evt.Add("channelMember", string(memberJSON))
|
||||
a.Publish(evt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +38,10 @@ func TestCreateOAuthUser(t *testing.T) {
|
||||
|
||||
t.Run("create user successfully", func(t *testing.T) {
|
||||
glUser := oauthgitlab.GitLabUser{Id: 42, Username: "o" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", Name: "Joram Wilander"}
|
||||
json := glUser.ToJson()
|
||||
js, jsonErr := json.Marshal(glUser)
|
||||
require.NoError(t, jsonErr)
|
||||
|
||||
user, err := th.App.CreateOAuthUser(th.Context, model.UserAuthServiceGitlab, strings.NewReader(json), th.BasicTeam.Id, nil)
|
||||
user, err := th.App.CreateOAuthUser(th.Context, model.UserAuthServiceGitlab, bytes.NewReader(js), th.BasicTeam.Id, nil)
|
||||
require.Nil(t, err)
|
||||
|
||||
require.Equal(t, glUser.Username, user.Username, "usernames didn't match")
|
||||
@@ -59,7 +60,7 @@ func TestCreateOAuthUser(t *testing.T) {
|
||||
mockUser := &model.User{Id: "abcdef", AuthData: model.NewString("e7110007-64be-43d8-9840-4a7e9c26b710"), Email: dbUser.Email}
|
||||
providerMock := &mocks.OAuthProvider{}
|
||||
providerMock.On("IsSameUser", mock.Anything, mock.Anything).Return(true)
|
||||
providerMock.On("GetUserFromJson", mock.Anything, mock.Anything).Return(mockUser, nil)
|
||||
providerMock.On("GetUserFromJSON", mock.Anything, mock.Anything).Return(mockUser, nil)
|
||||
einterfaces.RegisterOAuthProvider(model.ServiceOffice365, providerMock)
|
||||
|
||||
// Update user to be OAuth, formatting to match Office365 OAuth data
|
||||
@@ -734,7 +735,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
t.Run("invalid token type", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeVerifyEmail,
|
||||
model.MapToJson(map[string]string{"teamID": th.BasicTeam.Id, "email": user.Email}),
|
||||
model.MapToJSON(map[string]string{"teamID": th.BasicTeam.Id, "email": user.Email}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
defer th.App.DeleteToken(token)
|
||||
@@ -745,7 +746,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
t.Run("expired token", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
|
||||
)
|
||||
token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
@@ -757,7 +758,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
t.Run("invalid team id", func(t *testing.T) {
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": model.NewId(), "email": user.Email}),
|
||||
model.MapToJSON(map[string]string{"teamId": model.NewId(), "email": user.Email}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
defer th.App.DeleteToken(token)
|
||||
@@ -769,7 +770,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
invitationEmail := model.NewId() + "other-email@test.com"
|
||||
token := model.NewToken(
|
||||
TokenTypeTeamInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
newUser, err := th.App.CreateUserWithToken(th.Context, &user, token)
|
||||
@@ -789,7 +790,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
invitationEmail := model.NewId() + "other-email@test.com"
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
guest := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
@@ -819,11 +820,11 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
grantedInvitationEmail := model.NewId() + "other-email@restricted.com"
|
||||
forbiddenDomainToken := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": forbiddenInvitationEmail, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": forbiddenInvitationEmail, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
grantedDomainToken := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(forbiddenDomainToken))
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(grantedDomainToken))
|
||||
@@ -866,7 +867,7 @@ func TestCreateUserWithToken(t *testing.T) {
|
||||
invitationEmail := model.NewId() + "other-email@test.com"
|
||||
token := model.NewToken(
|
||||
TokenTypeGuestInvitation,
|
||||
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
|
||||
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
|
||||
)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
guest := model.User{
|
||||
|
||||
@@ -254,10 +254,13 @@ func TestWebConnDrainDeadQueue(t *testing.T) {
|
||||
i := seqNum
|
||||
for err == nil {
|
||||
_, buf, err = conn.ReadMessage()
|
||||
ev := model.WebSocketEventFromJson(bytes.NewReader(buf))
|
||||
require.LessOrEqual(t, int(i), limit)
|
||||
assert.Equal(t, i, ev.GetSequence())
|
||||
i++
|
||||
if err != nil && len(buf) > 0 {
|
||||
ev, jsonErr := model.WebSocketEventFromJSON(bytes.NewReader(buf))
|
||||
require.NoError(t, jsonErr)
|
||||
require.LessOrEqual(t, int(i), limit)
|
||||
assert.Equal(t, i, ev.GetSequence())
|
||||
i++
|
||||
}
|
||||
}
|
||||
if _, ok := err.(*websocket.CloseError); !ok {
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -168,10 +168,14 @@ func (s *Server) Publish(message *model.WebSocketEvent) {
|
||||
s.PublishSkipClusterSend(message)
|
||||
|
||||
if s.Cluster != nil {
|
||||
data, err := message.ToJSON()
|
||||
if err != nil {
|
||||
mlog.Warn("Failed to encode message to JSON", mlog.Err(err))
|
||||
}
|
||||
cm := &model.ClusterMessage{
|
||||
Event: model.ClusterEventPublish,
|
||||
SendType: model.ClusterSendBestEffort,
|
||||
Data: message.ToJson(),
|
||||
Data: data,
|
||||
}
|
||||
|
||||
if message.EventType() == model.WebsocketEventPosted ||
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -96,7 +98,11 @@ func (a *App) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookP
|
||||
var body io.Reader
|
||||
var contentType string
|
||||
if hook.ContentType == "application/json" {
|
||||
body = strings.NewReader(payload.ToJSON())
|
||||
js, jsonErr := json.Marshal(payload)
|
||||
if jsonErr != nil {
|
||||
mlog.Warn("Failed to encode to JSON", mlog.Err(jsonErr))
|
||||
}
|
||||
body = bytes.NewReader(js)
|
||||
contentType = "application/json"
|
||||
} else {
|
||||
body = strings.NewReader(payload.ToFormValues())
|
||||
@@ -164,7 +170,15 @@ func (a *App) doOutgoingWebhookRequest(url string, body io.Reader, contentType s
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
return model.OutgoingWebhookResponseFromJson(io.LimitReader(resp.Body, MaxIntegrationResponseSize))
|
||||
var hookResp model.OutgoingWebhookResponse
|
||||
if jsonErr := json.NewDecoder(io.LimitReader(resp.Body, MaxIntegrationResponseSize)).Decode(&hookResp); jsonErr != nil {
|
||||
if jsonErr == io.EOF {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, model.NewAppError("doOutgoingWebhookRequest", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return &hookResp, nil
|
||||
}
|
||||
|
||||
func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model.AppError) {
|
||||
@@ -180,7 +194,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model.
|
||||
}
|
||||
}
|
||||
|
||||
if utf8.RuneCountInString(model.StringInterfaceToJson(base.GetProps())) > model.PostPropsMaxUserRunes {
|
||||
if utf8.RuneCountInString(model.StringInterfaceToJSON(base.GetProps())) > model.PostPropsMaxUserRunes {
|
||||
return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
@@ -213,7 +227,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model.
|
||||
}
|
||||
origAttachments, _ := newProps["attachments"].([]*model.SlackAttachment)
|
||||
newProps["attachments"] = append(origAttachments, &newAttachment)
|
||||
newPropsString := model.StringInterfaceToJson(newProps)
|
||||
newPropsString := model.StringInterfaceToJSON(newProps)
|
||||
runeCount := utf8.RuneCountInString(newPropsString)
|
||||
|
||||
if runeCount <= model.PostPropsMaxUserRunes {
|
||||
|
||||
@@ -673,7 +673,9 @@ func TestTriggerOutGoingWebhookWithUsernameAndIconURL(t *testing.T) {
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if testCase.WebhookResponse != nil {
|
||||
w.Write([]byte(testCase.WebhookResponse.ToJson()))
|
||||
js, jsonErr := json.Marshal(testCase.WebhookResponse)
|
||||
require.NoError(t, jsonErr)
|
||||
w.Write(js)
|
||||
} else {
|
||||
w.Write([]byte(`{"text": "sample response text from test server"}`))
|
||||
}
|
||||
@@ -755,7 +757,7 @@ func TestDoOutgoingWebhookRequest(t *testing.T) {
|
||||
|
||||
_, err := th.App.doOutgoingWebhookRequest(server.URL, strings.NewReader(""), "application/json")
|
||||
require.Error(t, err)
|
||||
require.IsType(t, &json.SyntaxError{}, err)
|
||||
require.Equal(t, "api.unmarshal_error", err.(*model.AppError).Id)
|
||||
})
|
||||
|
||||
t.Run("with a large, valid response", func(t *testing.T) {
|
||||
@@ -766,7 +768,7 @@ func TestDoOutgoingWebhookRequest(t *testing.T) {
|
||||
|
||||
_, err := th.App.doOutgoingWebhookRequest(server.URL, strings.NewReader(""), "application/json")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, io.ErrUnexpectedEOF, err)
|
||||
require.Equal(t, "api.unmarshal_error", err.(*model.AppError).Id)
|
||||
})
|
||||
|
||||
t.Run("with a large, invalid response", func(t *testing.T) {
|
||||
@@ -777,7 +779,7 @@ func TestDoOutgoingWebhookRequest(t *testing.T) {
|
||||
|
||||
_, err := th.App.doOutgoingWebhookRequest(server.URL, strings.NewReader(""), "application/json")
|
||||
require.Error(t, err)
|
||||
require.IsType(t, &json.SyntaxError{}, err)
|
||||
require.Equal(t, "api.unmarshal_error", err.(*model.AppError).Id)
|
||||
})
|
||||
|
||||
t.Run("with a slow response", func(t *testing.T) {
|
||||
|
||||
Ссылка в новой задаче
Block a user