* 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>
Этот коммит содержится в:
Claudio Costa
2021-09-01 14:43:12 +02:00
коммит произвёл GitHub
родитель 6861efb47e
Коммит 92837fa1ee
242 изменённых файлов: 2812 добавлений и 3975 удалений

Просмотреть файл

@@ -4,7 +4,6 @@
package model
import (
"encoding/json"
"fmt"
"net/http"
"strings"
@@ -114,12 +113,6 @@ func (b *Bot) Etag() string {
return Etag(b.UserId, b.UpdateAt)
}
// ToJson serializes the bot to json.
func (b *Bot) ToJson() []byte {
data, _ := json.Marshal(b)
return data
}
// Patch modifies an existing bot with optional fields from the given patch.
// TODO 6.0: consider returning a boolean to indicate whether or not the patch
// applied any changes.
@@ -154,16 +147,6 @@ func (b *Bot) WouldPatch(patch *BotPatch) bool {
return false
}
// ToJson serializes the bot patch to json.
func (b *BotPatch) ToJson() []byte {
data, err := json.Marshal(b)
if err != nil {
return nil
}
return data
}
// UserFromBot returns a user model describing the bot fields stored in the User store.
func UserFromBot(b *Bot) *User {
return &User{
@@ -185,12 +168,6 @@ func BotFromUser(u *User) *Bot {
}
}
// ToJson serializes a list of bots to json.
func (l *BotList) ToJson() []byte {
b, _ := json.Marshal(l)
return b
}
// Etag computes the etag for a list of bots.
func (l *BotList) Etag() string {
id := "0"

Просмотреть файл

@@ -6,7 +6,6 @@ package model
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"sort"
@@ -165,11 +164,6 @@ func (o *Channel) DeepCopy() *Channel {
return &copy
}
func (o *Channel) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func (o *Channel) Etag() string {
return Etag(o.Id, o.UpdateAt)
}

Просмотреть файл

@@ -3,20 +3,8 @@
package model
import (
"encoding/json"
)
type ChannelList []*Channel
func (o *ChannelList) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func (o *ChannelList) Etag() string {
id := "0"
@@ -41,14 +29,6 @@ func (o *ChannelList) Etag() string {
type ChannelListWithTeamData []*ChannelWithTeamData
func (o *ChannelListWithTeamData) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func (o *ChannelListWithTeamData) Etag() string {
id := "0"

Просмотреть файл

@@ -4,7 +4,6 @@
package model
import (
"encoding/json"
"net/http"
"strings"
)
@@ -69,11 +68,6 @@ type ChannelMemberForExport struct {
Username string
}
func (o *ChannelMember) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func (o *ChannelMember) IsValid() *AppError {
if !IsValidId(o.ChannelId) {

Просмотреть файл

@@ -3,10 +3,6 @@
package model
import (
"encoding/json"
)
const ChannelSearchDefaultLimit = 50
type ChannelSearch struct {
@@ -24,9 +20,3 @@ type ChannelSearch struct {
Page *int `json:"page,omitempty"`
PerPage *int `json:"per_page,omitempty"`
}
// ToJson convert a Channel to a json string
func (c *ChannelSearch) ToJson() string {
b, _ := json.Marshal(c)
return string(b)
}

Просмотреть файл

@@ -4,7 +4,6 @@
package model
import (
"encoding/json"
"regexp"
)
@@ -73,27 +72,6 @@ type SidebarChannel struct {
type SidebarChannels []*SidebarChannel
type SidebarCategoriesWithChannels []*SidebarCategoryWithChannels
func (o SidebarCategoryWithChannels) ToJson() []byte {
b, _ := json.Marshal(o)
return b
}
func SidebarCategoriesWithChannelsToJson(o []*SidebarCategoryWithChannels) []byte {
b, err := json.Marshal(o)
if err != nil {
return []byte("[]")
}
return b
}
func (o OrderedSidebarCategories) ToJson() []byte {
b, err := json.Marshal(o)
if err != nil {
return []byte("[]")
}
return b
}
var categoryIdPattern = regexp.MustCompile("(favorites|channels|direct_messages)_[a-z0-9]{26}_[a-z0-9]{26}")
func IsValidCategoryId(s string) bool {

Просмотреть файл

@@ -3,20 +3,9 @@
package model
import (
"encoding/json"
"io"
)
type ChannelStats struct {
ChannelId string `json:"channel_id"`
MemberCount int64 `json:"member_count"`
GuestCount int64 `json:"guest_count"`
PinnedPostCount int64 `json:"pinnedpost_count"`
}
func ChannelStatsFromJson(data io.Reader) *ChannelStats {
var o *ChannelStats
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -3,30 +3,13 @@
package model
import (
"encoding/json"
"io"
)
type ChannelView struct {
ChannelId string `json:"channel_id"`
PrevChannelId string `json:"prev_channel_id"`
CollapsedThreadsSupported bool `json:"collapsed_threads_supported"`
}
func ChannelViewFromJson(data io.Reader) *ChannelView {
var o *ChannelView
json.NewDecoder(data).Decode(&o)
return o
}
type ChannelViewResponse struct {
Status string `json:"status"`
LastViewedAtTimes map[string]int64 `json:"last_viewed_at_times"`
}
func ChannelViewResponseFromJson(data io.Reader) *ChannelViewResponse {
var o *ChannelViewResponse
json.NewDecoder(data).Decode(&o)
return o
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@@ -4,6 +4,7 @@
package model
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -48,7 +49,10 @@ func TestClient4CreatePost(t *testing.T) {
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attachments := PostFromJson(r.Body).Attachments()
var post Post
err := json.NewDecoder(r.Body).Decode(&post)
assert.NoError(t, err)
attachments := post.Attachments()
assert.Equal(t, []*SlackAttachment{
{
Actions: []*PostAction{
@@ -64,6 +68,8 @@ func TestClient4CreatePost(t *testing.T) {
},
},
}, attachments)
err = json.NewEncoder(w).Encode(&post)
assert.NoError(t, err)
}))
client := NewAPIv4Client(server.URL)
@@ -85,6 +91,10 @@ func TestClient4SetToken(t *testing.T) {
}
assert.Equal(t, expected, strings.TrimSpace(token[1]))
var user User
err := json.NewEncoder(w).Encode(&user)
assert.NoError(t, err)
}))
client := NewAPIv4Client(server.URL)

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"os"
)
@@ -115,14 +113,3 @@ func (o *ClusterDiscovery) IsValid() *AppError {
return nil
}
func ClusterDiscoveryFromJson(data io.Reader) *ClusterDiscovery {
decoder := json.NewDecoder(data)
var me ClusterDiscovery
err := decoder.Decode(&me)
if err == nil {
return &me
}
return nil
}

Просмотреть файл

@@ -4,12 +4,9 @@
package model
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClusterDiscovery(t *testing.T) {
@@ -19,16 +16,9 @@ func TestClusterDiscovery(t *testing.T) {
Hostname: "test_hostname",
}
buf, err := json.Marshal(o)
require.NoError(t, err)
json := string(buf)
result1 := ClusterDiscoveryFromJson(strings.NewReader(json))
assert.NotNil(t, result1)
assert.Equal(t, "cluster_name", result1.ClusterName)
result2 := ClusterDiscoveryFromJson(strings.NewReader(json))
result3 := ClusterDiscoveryFromJson(strings.NewReader(json))
result1 := o
result2 := o
result3 := o
o.Id = "0"
result1.Id = "1"
@@ -36,13 +26,13 @@ func TestClusterDiscovery(t *testing.T) {
result3.Id = "3"
result3.Hostname = "something_diff"
assert.True(t, o.IsEqual(result1))
assert.True(t, o.IsEqual(&result1))
list := make([]*ClusterDiscovery, 0)
list = append(list, &o)
list = append(list, result1)
list = append(list, result2)
list = append(list, result3)
list = append(list, &result1)
list = append(list, &result2)
list = append(list, &result3)
rlist := FilterClusterDiscovery(list, func(in *ClusterDiscovery) bool {
return !o.IsEqual(in)

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type ClusterInfo struct {
Id string `json:"id"`
Version string `json:"version"`
@@ -15,24 +10,3 @@ type ClusterInfo struct {
IPAddress string `json:"ipaddress"`
Hostname string `json:"hostname"`
}
func ClusterInfoFromJson(data io.Reader) *ClusterInfo {
var ci *ClusterInfo
json.NewDecoder(data).Decode(&ci)
return ci
}
func ClusterInfosToJson(objmap []*ClusterInfo) string {
b, _ := json.Marshal(objmap)
return string(b)
}
func ClusterInfosFromJson(data io.Reader) []*ClusterInfo {
decoder := json.NewDecoder(data)
var objmap []*ClusterInfo
if err := decoder.Decode(&objmap); err != nil {
return make([]*ClusterInfo, 0)
}
return objmap
}

Просмотреть файл

@@ -1,21 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestClusterInfosJson(t *testing.T) {
cluster := ClusterInfo{IPAddress: NewId(), Hostname: NewId()}
clusterInfos := make([]*ClusterInfo, 1)
clusterInfos[0] = &cluster
json := ClusterInfosToJson(clusterInfos)
result := ClusterInfosFromJson(strings.NewReader(json))
assert.Equal(t, clusterInfos[0].IPAddress, result[0].IPAddress, "Ids do not match")
}

Просмотреть файл

@@ -3,20 +3,9 @@
package model
import (
"encoding/json"
"io"
)
type ClusterStats struct {
Id string `json:"id"`
TotalWebsocketConnections int `json:"total_websocket_connections"`
TotalReadDbConnections int `json:"total_read_db_connections"`
TotalMasterDbConnections int `json:"total_master_db_connections"`
}
func ClusterStatsFromJson(data io.Reader) *ClusterStats {
var cs *ClusterStats
json.NewDecoder(data).Decode(&cs)
return cs
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"strings"
)
@@ -43,20 +41,7 @@ type Command struct {
AutocompleteIconData string `db:"-" json:"autocomplete_icon_data,omitempty"`
}
func CommandFromJson(data io.Reader) *Command {
var o *Command
json.NewDecoder(data).Decode(&o)
return o
}
func CommandListFromJson(data io.Reader) []*Command {
var o []*Command
json.NewDecoder(data).Decode(&o)
return o
}
func (o *Command) IsValid() *AppError {
if !IsValidId(o.Id) {
return NewAppError("Command.IsValid", "model.command.is_valid.id.app_error", nil, "", http.StatusBadRequest)
}

Просмотреть файл

@@ -4,9 +4,6 @@
package model
import (
"encoding/json"
"io"
"github.com/mattermost/mattermost-server/v6/shared/i18n"
)
@@ -27,12 +24,6 @@ type CommandArgs struct {
Session Session `json:"-"`
}
func CommandArgsFromJson(data io.Reader) *CommandArgs {
var o *CommandArgs
json.NewDecoder(data).Decode(&o)
return o
}
// AddUserMention adds or overrides an entry in UserMentions with name username
// and identifier userId
func (o *CommandArgs) AddUserMention(username, userId string) {

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"io"
"net/url"
"path"
"reflect"
@@ -291,24 +290,6 @@ func (ad *AutocompleteData) IsValid() error {
return nil
}
// ToJSON encodes AutocompleteData struct to the json
func (ad *AutocompleteData) ToJSON() ([]byte, error) {
b, err := json.Marshal(ad)
if err != nil {
return nil, errors.Wrapf(err, "can't marshal slash command %s", ad.Trigger)
}
return b, nil
}
// AutocompleteDataFromJSON decodes AutocompleteData struct from the json
func AutocompleteDataFromJSON(data []byte) (*AutocompleteData, error) {
var ad AutocompleteData
if err := json.Unmarshal(data, &ad); err != nil {
return nil, errors.Wrap(err, "can't unmarshal AutocompleteData")
}
return &ad, nil
}
// Equals method checks if argument is the same.
func (a *AutocompleteArg) Equals(arg *AutocompleteArg) bool {
if a.Name != arg.Name ||
@@ -419,32 +400,6 @@ func (a *AutocompleteArg) UnmarshalJSON(b []byte) error {
return nil
}
// AutocompleteSuggestionsToJSON returns json for a list of AutocompleteSuggestion objects
func AutocompleteSuggestionsToJSON(suggestions []AutocompleteSuggestion) []byte {
b, _ := json.Marshal(suggestions)
return b
}
// AutocompleteSuggestionsFromJSON returns list of AutocompleteSuggestions from json.
func AutocompleteSuggestionsFromJSON(data io.Reader) []AutocompleteSuggestion {
var o []AutocompleteSuggestion
json.NewDecoder(data).Decode(&o)
return o
}
// AutocompleteStaticListItemsToJSON returns json for a list of AutocompleteStaticListItem objects
func AutocompleteStaticListItemsToJSON(items []AutocompleteListItem) []byte {
b, _ := json.Marshal(items)
return b
}
// AutocompleteStaticListItemsFromJSON returns list of AutocompleteStaticListItem from json.
func AutocompleteStaticListItemsFromJSON(data io.Reader) []AutocompleteListItem {
var o []AutocompleteListItem
json.NewDecoder(data).Decode(&o)
return o
}
func stringNotInSlice(a string, slice []string) bool {
for _, b := range slice {
if b == a {

Просмотреть файл

@@ -65,15 +65,6 @@ func TestAutocompleteData(t *testing.T) {
assert.Error(t, ad.IsValid())
}
func TestAutocompleteDataJSON(t *testing.T) {
ad := getAutocompleteData()
b, err := ad.ToJSON()
assert.NoError(t, err)
ad2, err := AutocompleteDataFromJSON(b)
assert.NoError(t, err)
assert.True(t, ad2.Equals(ad))
}
func getAutocompleteData() *AutocompleteData {
ad := NewAutocompleteData("jira", "", "Available commands:")
ad.RoleID = SystemUserRoleId

Просмотреть файл

@@ -3,21 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type CommandMoveRequest struct {
TeamId string `json:"team_id"`
}
func CommandMoveRequestFromJson(data io.Reader) (*CommandMoveRequest, error) {
decoder := json.NewDecoder(data)
var cmr CommandMoveRequest
err := decoder.Decode(&cmr)
if err != nil {
return nil, err
}
return &cmr, nil
}

Просмотреть файл

@@ -34,7 +34,7 @@ type CommandResponse struct {
func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error) {
if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
return CommandResponseFromJson(body)
return CommandResponseFromJSON(body)
}
if b, err := ioutil.ReadAll(body); err == nil {
return CommandResponseFromPlainText(string(b)), nil
@@ -48,7 +48,7 @@ func CommandResponseFromPlainText(text string) *CommandResponse {
}
}
func CommandResponseFromJson(data io.Reader) (*CommandResponse, error) {
func CommandResponseFromJSON(data io.Reader) (*CommandResponse, error) {
b, err := ioutil.ReadAll(data)
if err != nil {
return nil, err

Просмотреть файл

@@ -35,7 +35,7 @@ func TestCommandResponseFromPlainText(t *testing.T) {
assert.Equal(t, "foo", response.Text)
}
func TestCommandResponseFromJson(t *testing.T) {
func TestCommandResponseFromJSON(t *testing.T) {
t.Parallel()
testCases := []struct {
@@ -208,7 +208,7 @@ func TestCommandResponseFromJson(t *testing.T) {
t.Run(testCase.Description, func(t *testing.T) {
t.Parallel()
response, err := CommandResponseFromJson(strings.NewReader(testCase.Json))
response, err := CommandResponseFromJSON(strings.NewReader(testCase.Json))
if testCase.ShouldError {
assert.Nil(t, response)
} else {

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"strings"
)
@@ -83,7 +81,6 @@ func (c *Compliance) JobName() string {
}
func (c *Compliance) IsValid() *AppError {
if !IsValidId(c.Id) {
return NewAppError("Compliance.IsValid", "model.compliance.is_valid.id.app_error", nil, "", http.StatusBadRequest)
}
@@ -110,15 +107,3 @@ func (c *Compliance) IsValid() *AppError {
return nil
}
func ComplianceFromJson(data io.Reader) *Compliance {
var c *Compliance
json.NewDecoder(data).Decode(&c)
return c
}
func CompliancesFromJson(data io.Reader) Compliances {
var o Compliances
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -3197,7 +3197,7 @@ func (o *Config) Clone() *Config {
return &ret
}
func (o *Config) ToJsonFiltered(tagType, tagValue string) string {
func (o *Config) ToJSONFiltered(tagType, tagValue string) ([]byte, error) {
filteredConfigMap := structToMapFilteredByTag(*o, tagType, tagValue)
for key, value := range filteredConfigMap {
v, ok := value.(map[string]interface{})
@@ -3205,8 +3205,7 @@ func (o *Config) ToJsonFiltered(tagType, tagValue string) string {
delete(filteredConfigMap, key)
}
}
b, _ := json.Marshal(filteredConfigMap)
return string(b)
return json.Marshal(filteredConfigMap)
}
func (o *Config) GetSSOService(service string) *SSOSettings {
@@ -3224,7 +3223,7 @@ func (o *Config) GetSSOService(service string) *SSOSettings {
return nil
}
func ConfigFromJson(data io.Reader) *Config {
func ConfigFromJSON(data io.Reader) *Config {
var o *Config
json.NewDecoder(data).Decode(&o)
return o

Просмотреть файл

@@ -1338,10 +1338,11 @@ func TestConfigToJSONFiltered(t *testing.T) {
c := Config{}
c.SetDefaults()
jsonCfgFiltered := c.ToJsonFiltered(ConfigAccessTagType, ConfigAccessTagCloudRestrictable)
jsonCfgFiltered, err := c.ToJSONFiltered(ConfigAccessTagType, ConfigAccessTagCloudRestrictable)
require.NoError(t, err)
unmarshaledCfg := make(map[string]json.RawMessage)
err := json.Unmarshal([]byte(jsonCfgFiltered), &unmarshaledCfg)
err = json.Unmarshal(jsonCfgFiltered, &unmarshaledCfg)
require.NoError(t, err)
_, ok := unmarshaledCfg["SqlSettings"]

Просмотреть файл

@@ -4,9 +4,9 @@
package model
import (
"bytes"
"encoding/json"
"fmt"
"io"
"time"
)
@@ -49,12 +49,6 @@ func (cs *CustomStatus) PreSave() {
}
}
func (cs *CustomStatus) ToJson() string {
csCopy := *cs
b, _ := json.Marshal(csCopy)
return string(b)
}
func (cs *CustomStatus) AreDurationAndExpirationTimeValid() bool {
if cs.Duration == "" && (cs.ExpiresAt.IsZero() || !cs.ExpiresAt.Before(time.Now())) {
return true
@@ -67,33 +61,38 @@ func (cs *CustomStatus) AreDurationAndExpirationTimeValid() bool {
return false
}
func CustomStatusFromJson(data io.Reader) *CustomStatus {
var cs *CustomStatus
_ = json.NewDecoder(data).Decode(&cs)
return cs
}
func RuneToHexadecimalString(r rune) string {
return fmt.Sprintf("%04x", r)
}
type RecentCustomStatuses []CustomStatus
func (rcs RecentCustomStatuses) Contains(cs *CustomStatus) bool {
var csJSON = cs.ToJson()
func (rcs RecentCustomStatuses) Contains(cs *CustomStatus) (bool, error) {
if cs == nil {
return false, nil
}
csJSON, jsonErr := json.Marshal(cs)
if jsonErr != nil {
return false, jsonErr
}
// status is empty
if cs == nil || csJSON == "" || (cs.Emoji == "" && cs.Text == "") {
return false
if len(csJSON) == 0 || (cs.Emoji == "" && cs.Text == "") {
return false, nil
}
for _, status := range rcs {
if status.ToJson() == csJSON {
return true
js, jsonErr := json.Marshal(status)
if jsonErr != nil {
return false, jsonErr
}
if bytes.Equal(js, csJSON) {
return true, nil
}
}
return false
return false, nil
}
func (rcs RecentCustomStatuses) Add(cs *CustomStatus) RecentCustomStatuses {
@@ -112,29 +111,30 @@ func (rcs RecentCustomStatuses) Add(cs *CustomStatus) RecentCustomStatuses {
return newRCS
}
func (rcs RecentCustomStatuses) Remove(cs *CustomStatus) RecentCustomStatuses {
var csJSON = cs.ToJson()
if csJSON == "" || (cs.Emoji == "" && cs.Text == "") {
return rcs
func (rcs RecentCustomStatuses) Remove(cs *CustomStatus) (RecentCustomStatuses, error) {
if cs == nil {
return rcs, nil
}
csJSON, jsonErr := json.Marshal(cs)
if jsonErr != nil {
return rcs, jsonErr
}
if len(csJSON) == 0 || (cs.Emoji == "" && cs.Text == "") {
return rcs, nil
}
newRCS := rcs[:0]
for _, status := range rcs {
if status.ToJson() != csJSON {
js, jsonErr := json.Marshal(status)
if jsonErr != nil {
return rcs, jsonErr
}
if !bytes.Equal(js, csJSON) {
newRCS = append(newRCS, status)
}
}
return newRCS
}
func (rcs RecentCustomStatuses) ToJson() string {
b, _ := json.Marshal(rcs)
return string(b)
}
func RecentCustomStatusesFromJson(data io.Reader) RecentCustomStatuses {
var rcs RecentCustomStatuses
_ = json.NewDecoder(data).Decode(&rcs)
return rcs
return newRCS, nil
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type GlobalRetentionPolicy struct {
MessageDeletionEnabled bool `json:"message_deletion_enabled"`
FileDeletionEnabled bool `json:"file_deletion_enabled"`
@@ -73,60 +68,3 @@ type RetentionPolicyCursor struct {
TeamPoliciesDone bool
GlobalPoliciesDone bool
}
func (rp *GlobalRetentionPolicy) ToJson() []byte {
b, _ := json.Marshal(rp)
return b
}
func GlobalRetentionPolicyFromJson(data io.Reader) *GlobalRetentionPolicy {
var grp *GlobalRetentionPolicy
json.NewDecoder(data).Decode(&grp)
return grp
}
func RetentionPolicyWithTeamAndChannelCountsFromJson(data io.Reader) (*RetentionPolicyWithTeamAndChannelCounts, error) {
var rp RetentionPolicyWithTeamAndChannelCounts
err := json.NewDecoder(data).Decode(&rp)
return &rp, err
}
func (rp *RetentionPolicyWithTeamAndChannelCounts) ToJson() []byte {
b, _ := json.Marshal(rp)
return b
}
func RetentionPolicyWithTeamAndChannelCountsListFromJson(data io.Reader) (*RetentionPolicyWithTeamAndChannelCountsList, error) {
var rpList *RetentionPolicyWithTeamAndChannelCountsList
err := json.NewDecoder(data).Decode(&rpList)
if err != nil {
return nil, err
}
return rpList, nil
}
func (rpList *RetentionPolicyWithTeamAndChannelCountsList) ToJson() []byte {
b, _ := json.Marshal(rpList)
return b
}
func RetentionPolicyWithTeamAndChannelIdsFromJson(data io.Reader) (*RetentionPolicyWithTeamAndChannelIDs, error) {
var rp *RetentionPolicyWithTeamAndChannelIDs
err := json.NewDecoder(data).Decode(&rp)
return rp, err
}
func (rp *RetentionPolicyWithTeamAndChannelIDs) ToJson() []byte {
b, _ := json.Marshal(rp)
return b
}
func (lst *RetentionPolicyForTeamList) ToJson() []byte {
b, _ := json.Marshal(lst)
return b
}
func (lst *RetentionPolicyForChannelList) ToJson() []byte {
b, _ := json.Marshal(lst)
return b
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"regexp"
"sort"
@@ -95,20 +93,3 @@ func (emoji *Emoji) PreSave() {
emoji.CreateAt = GetMillis()
emoji.UpdateAt = emoji.CreateAt
}
func (emoji *Emoji) ToJson() string {
b, _ := json.Marshal(emoji)
return string(b)
}
func EmojiFromJson(data io.Reader) *Emoji {
var emoji *Emoji
json.NewDecoder(data).Decode(&emoji)
return emoji
}
func EmojiListFromJson(data io.Reader) []*Emoji {
var emojiList []*Emoji
json.NewDecoder(data).Decode(&emojiList)
return emojiList
}

Просмотреть файл

@@ -3,23 +3,7 @@
package model
import (
"encoding/json"
"io"
)
type EmojiSearch struct {
Term string `json:"term"`
PrefixOnly bool `json:"prefix_only"`
}
func (es *EmojiSearch) ToJson() string {
b, _ := json.Marshal(es)
return string(b)
}
func EmojiSearchFromJson(data io.Reader) *EmojiSearch {
var es *EmojiSearch
json.NewDecoder(data).Decode(&es)
return es
}

Просмотреть файл

@@ -1,19 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestEmojiSearchJson(t *testing.T) {
emojiSearch := EmojiSearch{Term: NewId()}
json := emojiSearch.ToJson()
remojiSearch := EmojiSearchFromJson(strings.NewReader(json))
require.Equal(t, emojiSearch.Term, remojiSearch.Term, "Terms do not match")
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
const (
MaxImageSize = int64(6048 * 4032) // 24 megapixels, roughly 36MB as a raw image
)
@@ -16,14 +11,3 @@ type FileUploadResponse struct {
FileInfos []*FileInfo `json:"file_infos"`
ClientIds []string `json:"client_ids"`
}
func FileUploadResponseFromJson(data io.Reader) *FileUploadResponse {
var o *FileUploadResponse
json.NewDecoder(data).Decode(&o)
return o
}
func (o *FileUploadResponse) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}

Просмотреть файл

@@ -4,7 +4,6 @@
package model
import (
"encoding/json"
"image"
"image/gif"
"io"
@@ -58,36 +57,6 @@ type FileInfo struct {
RemoteId *string `json:"remote_id"`
}
func (fi *FileInfo) ToJson() string {
b, _ := json.Marshal(fi)
return string(b)
}
func FileInfoFromJson(data io.Reader) *FileInfo {
decoder := json.NewDecoder(data)
var fi FileInfo
if err := decoder.Decode(&fi); err != nil {
return nil
}
return &fi
}
func FileInfosToJson(infos []*FileInfo) string {
b, _ := json.Marshal(infos)
return string(b)
}
func FileInfosFromJson(data io.Reader) []*FileInfo {
decoder := json.NewDecoder(data)
var infos []*FileInfo
if err := decoder.Decode(&infos); err != nil {
return nil
}
return infos
}
func (fi *FileInfo) PreSave() {
if fi.Id == "" {
fi.Id = NewId()

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"sort"
)
@@ -33,15 +31,6 @@ func (o *FileInfoList) ToSlice() []*FileInfo {
return fileInfos
}
func (o *FileInfoList) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}
func (o *FileInfoList) MakeNonNil() {
if o.Order == nil {
o.Order = make([]string, 0)
@@ -120,9 +109,3 @@ func (o *FileInfoList) Etag() string {
return Etag(orderId, id, t)
}
func FileInfoListFromJson(data io.Reader) *FileInfoList {
var o *FileInfoList
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type FileInfoSearchMatches map[string][]string
type FileInfoSearchResults struct {
@@ -21,17 +16,3 @@ func MakeFileInfoSearchResults(fileInfos *FileInfoList, matches FileInfoSearchMa
matches,
}
}
func (o *FileInfoSearchResults) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}
func FileInfoSearchResultsFromJson(data io.Reader) *FileInfoSearchResults {
var o *FileInfoSearchResults
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -56,7 +56,7 @@ func userFromGitLabUser(glu *GitLabUser) *model.User {
return user
}
func gitLabUserFromJson(data io.Reader) (*GitLabUser, error) {
func gitLabUserFromJSON(data io.Reader) (*GitLabUser, error) {
decoder := json.NewDecoder(data)
var glu GitLabUser
err := decoder.Decode(&glu)
@@ -66,14 +66,6 @@ func gitLabUserFromJson(data io.Reader) (*GitLabUser, error) {
return &glu, nil
}
func (glu *GitLabUser) ToJson() string {
b, err := json.Marshal(glu)
if err != nil {
return ""
}
return string(b)
}
func (glu *GitLabUser) IsValid() error {
if glu.Id == 0 {
return errors.New("user id can't be 0")
@@ -90,8 +82,8 @@ func (glu *GitLabUser) getAuthData() string {
return strconv.FormatInt(glu.Id, 10)
}
func (m *GitLabProvider) GetUserFromJson(data io.Reader, tokenUser *model.User) (*model.User, error) {
glu, err := gitLabUserFromJson(data)
func (m *GitLabProvider) GetUserFromJSON(data io.Reader, tokenUser *model.User) (*model.User, error) {
glu, err := gitLabUserFromJSON(data)
if err != nil {
return nil, err
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"regexp"
)
@@ -171,11 +169,6 @@ func (group *Group) IsValidForUpdate() *AppError {
return nil
}
func (group *Group) ToJson() string {
b, _ := json.Marshal(group)
return string(b)
}
var validGroupnameChars = regexp.MustCompile(`^[a-z0-9\.\-_]+$`)
func (group *Group) IsValidName() *AppError {
@@ -195,27 +188,3 @@ func (group *Group) IsValidName() *AppError {
}
return nil
}
func GroupFromJson(data io.Reader) *Group {
var group *Group
json.NewDecoder(data).Decode(&group)
return group
}
func GroupsFromJson(data io.Reader) []*Group {
var groups []*Group
json.NewDecoder(data).Decode(&groups)
return groups
}
func GroupPatchFromJson(data io.Reader) *GroupPatch {
var groupPatch *GroupPatch
json.NewDecoder(data).Decode(&groupPatch)
return groupPatch
}
func GroupStatsFromJson(data io.Reader) *GroupStats {
var groupStats *GroupStats
json.NewDecoder(data).Decode(&groupStats)
return groupStats
}

Просмотреть файл

@@ -6,8 +6,6 @@ package model
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
@@ -158,20 +156,6 @@ type UserChannelIDPair struct {
ChannelID string
}
func GroupSyncableFromJson(data io.Reader) *GroupSyncable {
groupSyncable := &GroupSyncable{}
bodyBytes, _ := ioutil.ReadAll(data)
json.Unmarshal(bodyBytes, groupSyncable)
return groupSyncable
}
func GroupSyncablesFromJson(data io.Reader) []*GroupSyncable {
groupSyncables := []*GroupSyncable{}
bodyBytes, _ := ioutil.ReadAll(data)
json.Unmarshal(bodyBytes, &groupSyncables)
return groupSyncables
}
func NewGroupTeam(groupID, teamID string, autoAdd bool) *GroupSyncable {
return &GroupSyncable{
GroupId: groupID,

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
)
@@ -39,15 +37,3 @@ func (i *GuestsInvite) IsValid() *AppError {
}
return nil
}
// GuestsInviteFromJson will decode the input and return a GuestsInvite
func GuestsInviteFromJson(data io.Reader) *GuestsInvite {
var i *GuestsInvite
json.NewDecoder(data).Decode(&i)
return i
}
func (i *GuestsInvite) ToJson() string {
b, _ := json.Marshal(i)
return string(b)
}

Просмотреть файл

@@ -41,30 +41,7 @@ type IncomingWebhookRequest struct {
IconEmoji string `json:"icon_emoji"`
}
func (o *IncomingWebhook) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func IncomingWebhookFromJson(data io.Reader) *IncomingWebhook {
var o *IncomingWebhook
json.NewDecoder(data).Decode(&o)
return o
}
func IncomingWebhookListToJson(l []*IncomingWebhook) string {
b, _ := json.Marshal(l)
return string(b)
}
func IncomingWebhookListFromJson(data io.Reader) []*IncomingWebhook {
var o []*IncomingWebhook
json.NewDecoder(data).Decode(&o)
return o
}
func (o *IncomingWebhook) IsValid() *AppError {
if !IsValidId(o.Id) {
return NewAppError("IncomingWebhook.IsValid", "model.incoming_hook.id.app_error", nil, "", http.StatusBadRequest)
@@ -186,7 +163,7 @@ func decodeIncomingWebhookRequest(by []byte) (*IncomingWebhookRequest, error) {
return nil, err
}
func IncomingWebhookRequestFromJson(data io.Reader) (*IncomingWebhookRequest, *AppError) {
func IncomingWebhookRequestFromJSON(data io.Reader) (*IncomingWebhookRequest, *AppError) {
buf := new(bytes.Buffer)
buf.ReadFrom(data)
by := buf.Bytes()
@@ -197,7 +174,7 @@ func IncomingWebhookRequestFromJson(data io.Reader) (*IncomingWebhookRequest, *A
if err != nil {
o, err = decodeIncomingWebhookRequest(escapeControlCharsFromPayload(by))
if err != nil {
return nil, NewAppError("IncomingWebhookRequestFromJson", "model.incoming_hook.parse_data.app_error", nil, err.Error(), http.StatusBadRequest)
return nil, NewAppError("IncomingWebhookRequestFromJSON", "model.incoming_hook.parse_data.app_error", nil, err.Error(), http.StatusBadRequest)
}
}
@@ -205,11 +182,3 @@ func IncomingWebhookRequestFromJson(data io.Reader) (*IncomingWebhookRequest, *A
return o, nil
}
func (o *IncomingWebhookRequest) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}

Просмотреть файл

@@ -10,14 +10,6 @@ import (
"github.com/stretchr/testify/require"
)
func TestIncomingWebhookJson(t *testing.T) {
o := IncomingWebhook{Id: NewId()}
json := o.ToJson()
ro := IncomingWebhookFromJson(strings.NewReader(json))
require.Equal(t, o.Id, ro.Id)
}
func TestIncomingWebhookIsValid(t *testing.T) {
o := IncomingWebhook{}
@@ -85,7 +77,7 @@ func TestIncomingWebhookPreUpdate(t *testing.T) {
o.PreUpdate()
}
func TestIncomingWebhookRequestFromJson(t *testing.T) {
func TestIncomingWebhookRequestFromJSON(t *testing.T) {
texts := []string{
`this is a test`,
`this is a test
@@ -139,7 +131,7 @@ func TestIncomingWebhookRequestFromJson(t *testing.T) {
// try to create an IncomingWebhookRequest from the payload
data := strings.NewReader(payload)
iwr, _ := IncomingWebhookRequestFromJson(data)
iwr, _ := IncomingWebhookRequestFromJSON(data)
// After it has been decoded, the JSON string won't contain the escape char anymore
expected := strings.Replace(text, `\"`, `"`, -1)
@@ -153,7 +145,7 @@ func TestIncomingWebhookRequestFromJson(t *testing.T) {
func TestIncomingWebhookNullArrayItems(t *testing.T) {
payload := `{"attachments":[{"fields":[{"title":"foo","value":"bar","short":true}, null]}, null]}`
iwr, _ := IncomingWebhookRequestFromJson(strings.NewReader(payload))
iwr, _ := IncomingWebhookRequestFromJSON(strings.NewReader(payload))
require.NotNil(t, iwr)
require.Len(t, iwr.Attachments, 1)
require.Len(t, iwr.Attachments[0].Fields, 1)

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type InitialLoad struct {
User *User `json:"user"`
TeamMembers []*TeamMember `json:"team_members"`
@@ -17,14 +12,3 @@ type InitialLoad struct {
LicenseCfg map[string]string `json:"license_cfg"`
NoAccounts bool `json:"no_accounts"`
}
func (il *InitialLoad) ToJson() string {
b, _ := json.Marshal(il)
return string(b)
}
func InitialLoadFromJson(data io.Reader) *InitialLoad {
var il *InitialLoad
json.NewDecoder(data).Decode(&il)
return il
}

Просмотреть файл

@@ -1,20 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestInitialLoadJson(t *testing.T) {
u := &User{Id: NewId()}
o := InitialLoad{User: u}
json := o.ToJson()
ro := InitialLoadFromJson(strings.NewReader(json))
require.Equal(t, o.User.Id, ro.User.Id, "Ids do not match")
}

Просмотреть файл

@@ -323,62 +323,6 @@ func (r *OpenDialogRequest) DecodeAndVerifyTriggerId(s *ecdsa.PrivateKey) (strin
return DecodeAndVerifyTriggerId(r.TriggerId, s)
}
func (r *PostActionIntegrationRequest) ToJson() []byte {
b, _ := json.Marshal(r)
return b
}
func PostActionIntegrationRequestFromJson(data io.Reader) *PostActionIntegrationRequest {
var o *PostActionIntegrationRequest
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func (r *PostActionIntegrationResponse) ToJson() []byte {
b, _ := json.Marshal(r)
return b
}
func PostActionIntegrationResponseFromJson(data io.Reader) *PostActionIntegrationResponse {
var o *PostActionIntegrationResponse
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func SubmitDialogRequestFromJson(data io.Reader) *SubmitDialogRequest {
var o *SubmitDialogRequest
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func (r *SubmitDialogRequest) ToJson() []byte {
b, _ := json.Marshal(r)
return b
}
func SubmitDialogResponseFromJson(data io.Reader) *SubmitDialogResponse {
var o *SubmitDialogResponse
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func (r *SubmitDialogResponse) ToJson() []byte {
b, _ := json.Marshal(r)
return b
}
func (o *Post) StripActionIntegrations() {
attachments := o.Attachments()
if o.GetProp("attachments") != nil {
@@ -524,9 +468,3 @@ func DecryptPostActionCookie(encoded string, secret []byte) (string, error) {
return string(plain), nil
}
func DoPostActionRequestFromJson(data io.Reader) *DoPostActionRequest {
var o *DoPostActionRequest
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -4,12 +4,10 @@
package model
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -17,7 +15,6 @@ import (
)
func TestTriggerIdDecodeAndVerification(t *testing.T) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
@@ -85,84 +82,6 @@ func TestTriggerIdDecodeAndVerification(t *testing.T) {
})
}
func TestPostActionIntegrationRequestToJson(t *testing.T) {
o := PostActionIntegrationRequest{UserId: NewId(), Context: StringInterface{"a": "abc"}}
j := o.ToJson()
ro := PostActionIntegrationRequestFromJson(bytes.NewReader(j))
assert.NotNil(t, ro)
assert.Equal(t, o, *ro)
}
func TestPostActionIntegrationRequestFromJsonError(t *testing.T) {
ro := PostActionIntegrationRequestFromJson(strings.NewReader(""))
assert.Nil(t, ro)
}
func TestPostActionIntegrationResponseToJson(t *testing.T) {
o := PostActionIntegrationResponse{Update: &Post{Id: NewId(), Message: NewId()}, EphemeralText: NewId()}
j := o.ToJson()
ro := PostActionIntegrationResponseFromJson(bytes.NewReader(j))
assert.NotNil(t, ro)
assert.Equal(t, o, *ro)
}
func TestPostActionIntegrationResponseFromJsonError(t *testing.T) {
ro := PostActionIntegrationResponseFromJson(strings.NewReader(""))
assert.Nil(t, ro)
}
func TestSubmitDialogRequestToJson(t *testing.T) {
t.Run("all fine", func(t *testing.T) {
request := SubmitDialogRequest{
URL: "http://example.org",
CallbackId: NewId(),
State: "some state",
UserId: NewId(),
ChannelId: NewId(),
TeamId: NewId(),
Submission: map[string]interface{}{
"text": "some text",
"float": 1.2,
"bool": true,
},
Cancelled: true,
}
jsonRequest := request.ToJson()
r := SubmitDialogRequestFromJson(bytes.NewReader(jsonRequest))
require.NotNil(t, r)
assert.Equal(t, request, *r)
})
t.Run("error", func(t *testing.T) {
r := SubmitDialogRequestFromJson(strings.NewReader(""))
assert.Nil(t, r)
})
}
func TestSubmitDialogResponseToJson(t *testing.T) {
t.Run("all fine", func(t *testing.T) {
request := SubmitDialogResponse{
Error: "some generic error",
Errors: map[string]string{
"text": "some text",
"float": "1.2",
"bool": "true",
},
}
jsonRequest := request.ToJson()
r := SubmitDialogResponseFromJson(bytes.NewReader(jsonRequest))
require.NotNil(t, r)
assert.Equal(t, request, *r)
})
t.Run("error", func(t *testing.T) {
r := SubmitDialogResponseFromJson(strings.NewReader(""))
assert.Nil(t, r)
})
}
func TestPostActionIntegrationEquals(t *testing.T) {
t.Run("equal uncomparable types", func(t *testing.T) {
pa1 := &PostAction{

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"time"
)
@@ -117,37 +115,6 @@ func (j *Job) IsValid() *AppError {
return nil
}
func (j *Job) ToJson() string {
b, _ := json.Marshal(j)
return string(b)
}
func JobFromJson(data io.Reader) *Job {
var job Job
if err := json.NewDecoder(data).Decode(&job); err == nil {
return &job
}
return nil
}
func JobsToJson(jobs []*Job) string {
b, _ := json.Marshal(jobs)
return string(b)
}
func JobsFromJson(data io.Reader) []*Job {
var jobs []*Job
if err := json.NewDecoder(data).Decode(&jobs); err == nil {
return jobs
}
return nil
}
func (j *Job) DataToJson() string {
b, _ := json.Marshal(j.Data)
return string(b)
}
type Worker interface {
Run()
Stop()

Просмотреть файл

@@ -6,7 +6,6 @@ package model
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
@@ -73,11 +72,6 @@ type TrialLicenseRequest struct {
ReceiveEmailsAccepted bool `json:"receive_emails_accepted"`
}
func (tlr *TrialLicenseRequest) ToJson() string {
b, _ := json.Marshal(tlr)
return string(b)
}
type Features struct {
Users *int `json:"users"`
LDAP *bool `json:"ldap"`
@@ -291,11 +285,6 @@ func (l *License) IsStarted() bool {
return l.StartsAt < GetMillis()
}
func (l *License) ToJson() string {
b, _ := json.Marshal(l)
return string(b)
}
func (l *License) IsTrialLicense() bool {
return l.IsTrial || (l.ExpiresAt-l.StartsAt) == trialDuration.Milliseconds() || (l.ExpiresAt-l.StartsAt) == adminTrialDuration.Milliseconds()
}
@@ -333,12 +322,6 @@ func NewTestLicense(features ...string) *License {
return ret
}
func LicenseFromJson(data io.Reader) *License {
var o *License
json.NewDecoder(data).Decode(&o)
return o
}
func (lr *LicenseRecord) IsValid() *AppError {
if !IsValidId(lr.Id) {
return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.id.app_error", nil, "", http.StatusBadRequest)

Просмотреть файл

@@ -143,70 +143,6 @@ func TestLicenseIsStarted(t *testing.T) {
assert.False(t, l1.IsStarted())
}
func TestLicenseToFromJson(t *testing.T) {
f := Features{}
f.SetDefaults()
l := License{
Id: NewId(),
IssuedAt: GetMillis(),
StartsAt: GetMillis(),
ExpiresAt: GetMillis(),
Customer: &Customer{
Id: NewId(),
Name: NewId(),
Email: NewId(),
Company: NewId(),
},
Features: &f,
IsTrial: true,
}
j := l.ToJson()
l1 := LicenseFromJson(strings.NewReader(j))
assert.NotNil(t, l1)
CheckString(t, l1.Id, l.Id)
CheckInt64(t, l1.IssuedAt, l.IssuedAt)
CheckInt64(t, l1.StartsAt, l.StartsAt)
CheckInt64(t, l1.ExpiresAt, l.ExpiresAt)
CheckBool(t, l1.IsTrial, l.IsTrial)
CheckString(t, l1.Customer.Id, l.Customer.Id)
CheckString(t, l1.Customer.Name, l.Customer.Name)
CheckString(t, l1.Customer.Email, l.Customer.Email)
CheckString(t, l1.Customer.Company, l.Customer.Company)
f1 := l1.Features
CheckInt(t, *f1.Users, *f.Users)
CheckBool(t, *f1.LDAP, *f.LDAP)
CheckBool(t, *f1.LDAPGroups, *f.LDAPGroups)
CheckBool(t, *f1.MFA, *f.MFA)
CheckBool(t, *f1.GoogleOAuth, *f.GoogleOAuth)
CheckBool(t, *f1.Office365OAuth, *f.Office365OAuth)
CheckBool(t, *f1.Compliance, *f.Compliance)
CheckBool(t, *f1.Cluster, *f.Cluster)
CheckBool(t, *f1.Metrics, *f.Metrics)
CheckBool(t, *f1.MHPNS, *f.MHPNS)
CheckBool(t, *f1.SAML, *f.SAML)
CheckBool(t, *f1.Elasticsearch, *f.Elasticsearch)
CheckBool(t, *f1.DataRetention, *f.DataRetention)
CheckBool(t, *f1.MessageExport, *f.MessageExport)
CheckBool(t, *f1.CustomPermissionsSchemes, *f.CustomPermissionsSchemes)
CheckBool(t, *f1.GuestAccounts, *f.GuestAccounts)
CheckBool(t, *f1.GuestAccountsPermissions, *f.GuestAccountsPermissions)
CheckBool(t, *f1.IDLoadedPushNotifications, *f.IDLoadedPushNotifications)
CheckBool(t, *f1.SharedChannels, *f.SharedChannels)
CheckBool(t, *f1.RemoteClusterService, *f.RemoteClusterService)
CheckBool(t, *f1.FutureFeatures, *f.FutureFeatures)
invalid := `{"asdf`
l2 := LicenseFromJson(strings.NewReader(invalid))
assert.Nil(t, l2)
}
func TestLicenseRecordIsValid(t *testing.T) {
lr := LicenseRecord{
CreateAt: GetMillis(),

Просмотреть файл

@@ -160,14 +160,16 @@ func TestLinkMetadataDeserializeDataToConcreteType(t *testing.T) {
Width: 500,
}
js, err := json.Marshal(image)
assert.NoError(t, err)
metadata := &LinkMetadata{
Type: LinkMetadataTypeImage,
Data: []byte(image.ToJson()),
Data: js,
}
require.IsType(t, []byte{}, metadata.Data)
err := metadata.DeserializeDataToConcreteType()
err = metadata.DeserializeDataToConcreteType()
assert.NoError(t, err)
assert.IsType(t, &PostImage{}, metadata.Data)

Просмотреть файл

@@ -6,7 +6,6 @@ package model
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
@@ -227,28 +226,6 @@ type ManifestWebapp struct {
BundleHash []byte `json:"-"`
}
func (m *Manifest) ToJson() string {
b, _ := json.Marshal(m)
return string(b)
}
func ManifestListToJson(m []*Manifest) string {
b, _ := json.Marshal(m)
return string(b)
}
func ManifestFromJson(data io.Reader) *Manifest {
var m *Manifest
json.NewDecoder(data).Decode(&m)
return m
}
func ManifestListFromJson(data io.Reader) []*Manifest {
var manifests []*Manifest
json.NewDecoder(data).Decode(&manifests)
return manifests
}
func (m *Manifest) HasClient() bool {
return m.Webapp != nil
}

Просмотреть файл

@@ -436,57 +436,6 @@ func TestFindManifest_FolderPermission(t *testing.T) {
}
}
func TestManifestJson(t *testing.T) {
manifest := &Manifest{
Id: "theid",
Server: &ManifestServer{
Executable: "theexecutable",
Executables: map[string]string{
"linux-amd64": "linux-amd64/path/to/executable",
"darwin-amd64": "darwin-amd64/path/to/executable",
"windows-amd64": "windows-amd64/path/to/executable",
"linux-arm64": "linux-arm64/path/to/executable",
},
},
Webapp: &ManifestWebapp{
BundlePath: "thebundlepath",
},
SettingsSchema: &PluginSettingsSchema{
Header: "theheadertext",
Footer: "thefootertext",
Settings: []*PluginSetting{
{
Key: "thesetting",
DisplayName: "thedisplayname",
Type: "dropdown",
HelpText: "thehelptext",
RegenerateHelpText: "theregeneratehelptext",
Placeholder: "theplaceholder",
Options: []*PluginOption{
{
DisplayName: "theoptiondisplayname",
Value: "thevalue",
},
},
Default: "thedefault",
},
},
},
}
json := manifest.ToJson()
newManifest := ManifestFromJson(strings.NewReader(json))
assert.Equal(t, newManifest, manifest)
assert.Equal(t, newManifest.ToJson(), json)
assert.Equal(t, ManifestFromJson(strings.NewReader("junk")), (*Manifest)(nil))
manifestList := []*Manifest{manifest}
json = ManifestListToJson(manifestList)
newManifestList := ManifestListFromJson(strings.NewReader(json))
assert.Equal(t, newManifestList, manifestList)
assert.Equal(t, ManifestListToJson(newManifestList), json)
}
func TestManifestHasClient(t *testing.T) {
manifest := &Manifest{
Id: "theid",

Просмотреть файл

@@ -125,12 +125,3 @@ func PluginRequestFromReader(reader io.Reader) (*InstallMarketplacePluginRequest
}
return r, nil
}
// ToJson method will return json from plugin request.
func (r *InstallMarketplacePluginRequest) ToJson() (string, error) {
b, err := json.Marshal(r)
if err != nil {
return "", err
}
return string(b), nil
}

Просмотреть файл

@@ -3,23 +3,7 @@
package model
import (
"encoding/json"
"io"
)
type MfaSecret struct {
Secret string `json:"secret"`
QRCode string `json:"qr_code"`
}
func (mfa *MfaSecret) ToJson() string {
b, _ := json.Marshal(mfa)
return string(b)
}
func MfaSecretFromJson(data io.Reader) *MfaSecret {
var mfa *MfaSecret
json.NewDecoder(data).Decode(&mfa)
return mfa
}

Просмотреть файл

@@ -1,19 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestMfaSecretJson(t *testing.T) {
secret := MfaSecret{Secret: NewId(), QRCode: NewId()}
json := secret.ToJson()
result := MfaSecretFromJson(strings.NewReader(json))
require.Equal(t, secret.Secret, result.Secret, "Secrets do not match")
}

Просмотреть файл

@@ -13,10 +13,6 @@ func CheckInt(t *testing.T, got int, expected int) {
assert.Equal(t, got, expected)
}
func CheckInt64(t *testing.T, got int64, expected int64) {
assert.Equal(t, got, expected)
}
func CheckString(t *testing.T, got string, expected string) {
assert.Equal(t, got, expected)
}
@@ -28,7 +24,3 @@ func CheckTrue(t *testing.T, test bool) {
func CheckFalse(t *testing.T, test bool) {
assert.False(t, test)
}
func CheckBool(t *testing.T, got bool, expected bool) {
assert.Equal(t, got, expected)
}

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"fmt"
"io"
"net/http"
"unicode/utf8"
)
@@ -108,11 +106,6 @@ func (a *OAuthApp) PreUpdate() {
a.UpdateAt = GetMillis()
}
func (a *OAuthApp) ToJson() string {
b, _ := json.Marshal(a)
return string(b)
}
// Generate a valid strong etag so the browser can cache the results
func (a *OAuthApp) Etag() string {
return Etag(a.Id, a.UpdateAt)
@@ -132,20 +125,3 @@ func (a *OAuthApp) IsValidRedirectURL(url string) bool {
return false
}
func OAuthAppFromJson(data io.Reader) *OAuthApp {
var app *OAuthApp
json.NewDecoder(data).Decode(&app)
return app
}
func OAuthAppListToJson(l []*OAuthApp) string {
b, _ := json.Marshal(l)
return string(b)
}
func OAuthAppListFromJson(data io.Reader) []*OAuthApp {
var o []*OAuthApp
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -4,27 +4,11 @@
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestOAuthAppJson(t *testing.T) {
a1 := OAuthApp{}
a1.Id = NewId()
a1.Name = "TestOAuthApp" + NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
a1.IconURL = "https://nowhere.com/icon_image.png"
a1.ClientSecret = NewId()
json := a1.ToJson()
ra1 := OAuthAppFromJson(strings.NewReader(json))
require.Equal(t, a1.Id, ra1.Id, "ids did not match")
}
func TestOAuthAppPreSave(t *testing.T) {
a1 := OAuthApp{}
a1.Id = NewId()

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
@@ -59,11 +57,6 @@ type OutgoingWebhookResponse struct {
const OutgoingHookResponseTypeComment = "comment"
func (o *OutgoingWebhookPayload) ToJSON() string {
b, _ := json.Marshal(o)
return string(b)
}
func (o *OutgoingWebhookPayload) ToFormValues() string {
v := url.Values{}
v.Set("token", o.Token)
@@ -82,42 +75,6 @@ func (o *OutgoingWebhookPayload) ToFormValues() string {
return v.Encode()
}
func (o *OutgoingWebhook) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func OutgoingWebhookFromJson(data io.Reader) *OutgoingWebhook {
var o *OutgoingWebhook
json.NewDecoder(data).Decode(&o)
return o
}
func OutgoingWebhookListToJson(l []*OutgoingWebhook) string {
b, _ := json.Marshal(l)
return string(b)
}
func OutgoingWebhookListFromJson(data io.Reader) []*OutgoingWebhook {
var o []*OutgoingWebhook
json.NewDecoder(data).Decode(&o)
return o
}
func (o *OutgoingWebhookResponse) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func OutgoingWebhookResponseFromJson(data io.Reader) (*OutgoingWebhookResponse, error) {
var o *OutgoingWebhookResponse
err := json.NewDecoder(data).Decode(&o)
if err == io.EOF {
return nil, nil
}
return o, err
}
func (o *OutgoingWebhook) IsValid() *AppError {
if !IsValidId(o.Id) {

Просмотреть файл

@@ -11,14 +11,6 @@ import (
"github.com/stretchr/testify/assert"
)
func TestOutgoingWebhookJson(t *testing.T) {
o := OutgoingWebhook{Id: NewId()}
json := o.ToJson()
ro := OutgoingWebhookFromJson(strings.NewReader(json))
assert.Equal(t, o.Id, ro.Id, "Ids do not match")
}
func TestOutgoingWebhookIsValid(t *testing.T) {
o := OutgoingWebhook{}
assert.NotNil(t, o.IsValid(), "empty declaration should be invalid")
@@ -142,13 +134,3 @@ func TestOutgoingWebhookTriggerWordStartsWith(t *testing.T) {
assert.True(t, o.TriggerWordStartsWith("foobar"), "Should return true")
assert.False(t, o.TriggerWordStartsWith("barfoo"), "Should return false")
}
func TestOutgoingWebhookResponseJson(t *testing.T) {
o := OutgoingWebhookResponse{}
o.Text = NewString("some text")
json := o.ToJson()
ro, _ := OutgoingWebhookResponseFromJson(strings.NewReader(json))
assert.Equal(t, *o.Text, *ro.Text, "Text does not match")
}

Просмотреть файл

@@ -3,8 +3,6 @@
package model
import "encoding/json"
type Permalink struct {
PreviewPost *PreviewPost `json:"preview_post"`
}
@@ -27,8 +25,3 @@ func NewPreviewPost(post *Post, team *Team, channel *Channel) *PreviewPost {
ChannelDisplayName: channel.DisplayName,
}
}
func (o *Permalink) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}

Просмотреть файл

@@ -3,23 +3,7 @@
package model
import (
"encoding/json"
"io"
)
// PluginEventData used to notify peers about plugin changes.
type PluginEventData struct {
Id string `json:"id"`
}
func (p *PluginEventData) ToJson() string {
b, _ := json.Marshal(p)
return string(b)
}
func PluginEventDataFromJson(data io.Reader) PluginEventData {
var m PluginEventData
json.NewDecoder(data).Decode(&m)
return m
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
const (
PluginStateNotRunning = 0
PluginStateStarting = 1 // unused by server
@@ -29,14 +24,3 @@ type PluginStatus struct {
}
type PluginStatuses []*PluginStatus
func (m *PluginStatuses) ToJson() string {
b, _ := json.Marshal(m)
return string(b)
}
func PluginStatusesFromJson(data io.Reader) PluginStatuses {
var m PluginStatuses
json.NewDecoder(data).Decode(&m)
return m
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type PluginInfo struct {
Manifest
}
@@ -16,14 +11,3 @@ type PluginsResponse struct {
Active []*PluginInfo `json:"active"`
Inactive []*PluginInfo `json:"inactive"`
}
func (m *PluginsResponse) ToJson() string {
b, _ := json.Marshal(m)
return string(b)
}
func PluginsResponseFromJson(data io.Reader) *PluginsResponse {
var m *PluginsResponse
json.NewDecoder(data).Decode(&m)
return m
}

Просмотреть файл

@@ -1,34 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPluginsResponseJson(t *testing.T) {
manifest := &Manifest{
Id: "theid",
Server: &ManifestServer{
Executable: "theexecutable",
},
Webapp: &ManifestWebapp{
BundlePath: "thebundlepath",
},
}
response := &PluginsResponse{
Active: []*PluginInfo{{Manifest: *manifest}},
Inactive: []*PluginInfo{},
}
json := response.ToJson()
newResponse := PluginsResponseFromJson(strings.NewReader(json))
assert.Equal(t, newResponse, response)
assert.Equal(t, newResponse.ToJson(), json)
assert.Equal(t, PluginsResponseFromJson(strings.NewReader("junk")), (*PluginsResponse)(nil))
}

Просмотреть файл

@@ -6,7 +6,6 @@ package model
import (
"encoding/json"
"errors"
"io"
"net/http"
"regexp"
"sort"
@@ -221,16 +220,11 @@ func (o *Post) Clone() *Post {
return copy
}
func (o *Post) ToJson() string {
func (o *Post) ToJSON() (string, error) {
copy := o.Clone()
copy.StripActionIntegrations()
b, _ := json.Marshal(copy)
return string(b)
}
func (o *Post) ToUnsanitizedJson() string {
b, _ := json.Marshal(o)
return string(b)
b, err := json.Marshal(copy)
return string(b), err
}
type GetPostsSinceOptions struct {
@@ -265,12 +259,6 @@ type GetPostsOptions struct {
CollapsedThreadsExtended bool
}
func PostFromJson(data io.Reader) *Post {
var o *Post
json.NewDecoder(data).Decode(&o)
return o
}
func (o *Post) Etag() string {
return Etag(o.Id, o.UpdateAt)
}
@@ -347,15 +335,15 @@ func (o *Post) IsValid(maxPostSize int) *AppError {
}
}
if utf8.RuneCountInString(ArrayToJson(o.Filenames)) > PostFilenamesMaxRunes {
if utf8.RuneCountInString(ArrayToJSON(o.Filenames)) > PostFilenamesMaxRunes {
return NewAppError("Post.IsValid", "model.post.is_valid.filenames.app_error", nil, "id="+o.Id, http.StatusBadRequest)
}
if utf8.RuneCountInString(ArrayToJson(o.FileIds)) > PostFileidsMaxRunes {
if utf8.RuneCountInString(ArrayToJSON(o.FileIds)) > PostFileidsMaxRunes {
return NewAppError("Post.IsValid", "model.post.is_valid.file_ids.app_error", nil, "id="+o.Id, http.StatusBadRequest)
}
if utf8.RuneCountInString(StringInterfaceToJson(o.GetProps())) > PostPropsMaxRunes {
if utf8.RuneCountInString(StringInterfaceToJSON(o.GetProps())) > PostPropsMaxRunes {
return NewAppError("Post.IsValid", "model.post.is_valid.props.app_error", nil, "id="+o.Id, http.StatusBadRequest)
}
@@ -513,45 +501,6 @@ func (o *Post) Patch(patch *PostPatch) {
}
}
func (o *PostPatch) ToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}
func PostPatchFromJson(data io.Reader) *PostPatch {
decoder := json.NewDecoder(data)
var post PostPatch
err := decoder.Decode(&post)
if err != nil {
return nil
}
return &post
}
func (o *SearchParameter) SearchParameterToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}
func SearchParameterFromJson(data io.Reader) (*SearchParameter, error) {
decoder := json.NewDecoder(data)
var searchParam SearchParameter
if err := decoder.Decode(&searchParam); err != nil {
return nil, err
}
return &searchParam, nil
}
func (o *Post) ChannelMentions() []string {
return ChannelMentions(o.Message)
}
@@ -660,11 +609,6 @@ func (o *Post) WithRewrittenImageURLs(f func(string) string) *Post {
return copy
}
func (o *PostEphemeral) ToUnsanitizedJson() string {
b, _ := json.Marshal(o)
return string(b)
}
// RewriteImageURLs takes a message and returns a copy that has all of the image URLs replaced
// according to the function f. For each image URL, f will be invoked, and the resulting markdown
// will contain the URL returned by that invocation instead.

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"io"
"sort"
)
@@ -74,14 +73,11 @@ func (o *PostList) StripActionIntegrations() {
}
}
func (o *PostList) ToJson() string {
func (o *PostList) ToJSON() (string, error) {
copy := *o
copy.StripActionIntegrations()
b, err := json.Marshal(&copy)
if err != nil {
return ""
}
return string(b)
return string(b), err
}
func (o *PostList) MakeNonNil() {
@@ -179,9 +175,3 @@ func (o *PostList) IsChannelId(channelId string) bool {
return true
}
func PostListFromJson(data io.Reader) *PostList {
var o *PostList
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -4,14 +4,13 @@
package model
import (
"strings"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPostListJson(t *testing.T) {
pl := PostList{}
p1 := &Post{Id: NewId(), Message: NewId()}
pl.AddPost(p1)
@@ -21,8 +20,12 @@ func TestPostListJson(t *testing.T) {
pl.AddOrder(p1.Id)
pl.AddOrder(p2.Id)
json := pl.ToJson()
rpl := PostListFromJson(strings.NewReader(json))
js, err := pl.ToJSON()
assert.NoError(t, err)
var rpl PostList
err = json.Unmarshal([]byte(js), &rpl)
assert.NoError(t, err)
assert.Equal(t, p1.Message, rpl.Posts[p1.Id].Message, "failed to serialize p1 message")
assert.Equal(t, p2.Message, rpl.Posts[p2.Id].Message, "failed to serialize p2 message")

Просмотреть файл

@@ -3,10 +3,6 @@
package model
import (
"encoding/json"
)
type PostMetadata struct {
// Embeds holds information required to render content embedded in the post. This includes the OpenGraph metadata
// for links in the post.
@@ -38,8 +34,3 @@ type PostImage struct {
// FrameCount stores the number of frames in this image, if it is an animated gif. It will be 0 for other formats.
FrameCount int `json:"frame_count"`
}
func (o *PostImage) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"io"
)
type PostSearchMatches map[string][]string
@@ -22,18 +21,9 @@ func MakePostSearchResults(posts *PostList, matches PostSearchMatches) *PostSear
}
}
func (o *PostSearchResults) ToJson() string {
func (o *PostSearchResults) ToJSON() (string, error) {
copy := *o
copy.PostList.StripActionIntegrations()
b, err := json.Marshal(&copy)
if err != nil {
return ""
}
return string(b)
}
func PostSearchResultsFromJson(data io.Reader) *PostSearchResults {
var o *PostSearchResults
json.NewDecoder(data).Decode(&o)
return o
return string(b), err
}

Просмотреть файл

@@ -4,6 +4,7 @@
package model
import (
"encoding/json"
"io/ioutil"
"strings"
"sync"
@@ -13,20 +14,16 @@ import (
"github.com/stretchr/testify/require"
)
func TestPostToJson(t *testing.T) {
func TestPostToJSON(t *testing.T) {
o := Post{Id: NewId(), Message: NewId()}
j := o.ToJson()
ro := PostFromJson(strings.NewReader(j))
assert.NotNil(t, ro)
j, err := o.ToJSON()
assert.NoError(t, err)
var ro Post
err = json.Unmarshal([]byte(j), &ro)
assert.NoError(t, err)
assert.Equal(t, &o, ro.Clone())
}
func TestPostFromJsonError(t *testing.T) {
ro := PostFromJson(strings.NewReader(""))
assert.Nil(t, ro)
}
func TestPostIsValid(t *testing.T) {
o := Post{}
maxPostSize := 10000
@@ -849,34 +846,6 @@ func TestPostPatchDisableMentionHighlights(t *testing.T) {
})
}
func TestSearchParameterFromJson(t *testing.T) {
t.Run("empty input", func(t *testing.T) {
params, err := SearchParameterFromJson(strings.NewReader(""))
require.Nil(t, params)
require.Error(t, err)
})
t.Run("invalid json", func(t *testing.T) {
params, err := SearchParameterFromJson(strings.NewReader("invalid"))
require.Nil(t, params)
require.Error(t, err)
})
t.Run("valid empty input", func(t *testing.T) {
params, err := SearchParameterFromJson(strings.NewReader("{}"))
require.NoError(t, err)
require.NotNil(t, params)
require.Equal(t, &SearchParameter{}, params)
})
t.Run("valid non-empty input", func(t *testing.T) {
params, err := SearchParameterFromJson(strings.NewReader("{\"terms\": \"test\"}"))
require.NoError(t, err)
require.NotNil(t, params)
require.Equal(t, "test", *params.Terms)
})
}
func TestPostAttachments(t *testing.T) {
p := &Post{
Props: map[string]interface{}{

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"io"
"net/http"
"regexp"
"strings"
@@ -65,16 +64,7 @@ type Preference struct {
Value string `json:"value"`
}
func (o *Preference) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func PreferenceFromJson(data io.Reader) *Preference {
var o *Preference
json.NewDecoder(data).Decode(&o)
return o
}
type Preferences []Preference
func (o *Preference) IsValid() *AppError {
if !IsValidId(o.UserId) {

Просмотреть файл

@@ -1,26 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"encoding/json"
"io"
)
type Preferences []Preference
func (o *Preferences) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func PreferencesFromJson(data io.Reader) (Preferences, error) {
decoder := json.NewDecoder(data)
var o Preferences
err := decoder.Decode(&o)
if err != nil {
return nil, err
}
return o, nil
}

Просмотреть файл

@@ -4,9 +4,6 @@
package model
import (
"encoding/json"
"errors"
"io"
"strings"
)
@@ -70,18 +67,12 @@ type PushNotification struct {
IsIdLoaded bool `json:"is_id_loaded"`
}
func (pn *PushNotification) ToJson() string {
b, _ := json.Marshal(pn)
return string(b)
}
func (pn *PushNotification) DeepCopy() *PushNotification {
copy := *pn
return &copy
}
func (pn *PushNotification) SetDeviceIdAndPlatform(deviceId string) {
index := strings.Index(deviceId, ":")
if index > -1 {
@@ -89,30 +80,3 @@ func (pn *PushNotification) SetDeviceIdAndPlatform(deviceId string) {
pn.DeviceId = deviceId[index+1:]
}
}
func PushNotificationFromJson(data io.Reader) (*PushNotification, error) {
if data == nil {
return nil, errors.New("push notification data can't be nil")
}
var pn *PushNotification
if err := json.NewDecoder(data).Decode(&pn); err != nil {
return nil, err
}
return pn, nil
}
func PushNotificationAckFromJson(data io.Reader) (*PushNotificationAck, error) {
if data == nil {
return nil, errors.New("push notification data can't be nil")
}
var ack *PushNotificationAck
if err := json.NewDecoder(data).Decode(&ack); err != nil {
return nil, err
}
return ack, nil
}
func (ack *PushNotificationAck) ToJson() string {
b, _ := json.Marshal(ack)
return string(b)
}

Просмотреть файл

@@ -4,58 +4,11 @@
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestPushNotification(t *testing.T) {
t.Run("should build a push notification from JSON", func(t *testing.T) {
msg := PushNotification{Platform: "test"}
json := msg.ToJson()
result, err := PushNotificationFromJson(strings.NewReader(json))
require.NoError(t, err)
require.Equal(t, msg.Platform, result.Platform, "ids do not match")
})
t.Run("should throw an error when the message is nil", func(t *testing.T) {
_, err := PushNotificationFromJson(nil)
require.Error(t, err)
require.Equal(t, "push notification data can't be nil", err.Error())
})
t.Run("should throw an error when the message parsing fails", func(t *testing.T) {
_, err := PushNotificationFromJson(strings.NewReader(""))
require.Error(t, err)
require.Equal(t, "EOF", err.Error())
})
}
func TestPushNotificationAck(t *testing.T) {
t.Run("should build a push notification ack from JSON", func(t *testing.T) {
msg := PushNotificationAck{ClientPlatform: "test"}
json := msg.ToJson()
result, err := PushNotificationAckFromJson(strings.NewReader(json))
require.NoError(t, err)
require.Equal(t, msg.ClientPlatform, result.ClientPlatform, "ids do not match")
})
t.Run("should throw an error when the message is nil", func(t *testing.T) {
_, err := PushNotificationAckFromJson(nil)
require.Error(t, err)
require.Equal(t, "push notification data can't be nil", err.Error())
})
t.Run("should throw an error when the message parsing fails", func(t *testing.T) {
_, err := PushNotificationAckFromJson(strings.NewReader(""))
require.Error(t, err)
require.Equal(t, "EOF", err.Error())
})
}
func TestPushNotificationDeviceId(t *testing.T) {
msg := PushNotification{Platform: "test"}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
const (
PushStatus = "status"
PushStatusOk = "OK"
@@ -36,18 +31,3 @@ func NewErrorPushResponse(message string) PushResponse {
m[PushStatusErrorMsg] = message
return m
}
func (pr *PushResponse) ToJson() string {
b, _ := json.Marshal(pr)
return string(b)
}
func PushResponseFromJson(data io.Reader) PushResponse {
decoder := json.NewDecoder(data)
var objmap PushResponse
if err := decoder.Decode(&objmap); err != nil {
return make(map[string]string)
}
return objmap
}

Просмотреть файл

@@ -4,7 +4,6 @@
package model
import (
"strings"
"testing"
)
@@ -23,12 +22,3 @@ func TestNewErrorPushResponse(t *testing.T) {
CheckString(t, r["status"], "FAIL")
CheckString(t, r["error"], "error message")
}
func TestPushResponseToFromJson(t *testing.T) {
r := NewErrorPushResponse("error message")
j := r.ToJson()
r1 := PushResponseFromJson(strings.NewReader(j))
CheckString(t, r1["status"], r["status"])
CheckString(t, r1["error"], r["error"])
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"regexp"
)
@@ -20,49 +18,6 @@ type Reaction struct {
RemoteId *string `json:"remote_id"`
}
func (o *Reaction) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func ReactionFromJson(data io.Reader) *Reaction {
var o Reaction
if err := json.NewDecoder(data).Decode(&o); err != nil {
return nil
}
return &o
}
func ReactionsToJson(o []*Reaction) string {
b, _ := json.Marshal(o)
return string(b)
}
func MapPostIdToReactionsToJson(o map[string][]*Reaction) string {
b, _ := json.Marshal(o)
return string(b)
}
func MapPostIdToReactionsFromJson(data io.Reader) map[string][]*Reaction {
decoder := json.NewDecoder(data)
var objmap map[string][]*Reaction
if err := decoder.Decode(&objmap); err != nil {
return make(map[string][]*Reaction)
}
return objmap
}
func ReactionsFromJson(data io.Reader) []*Reaction {
var o []*Reaction
if err := json.NewDecoder(data).Decode(&o); err != nil {
return nil
}
return o
}
func (o *Reaction) IsValid() *AppError {
if !IsValidId(o.UserId) {
return NewAppError("Reaction.IsValid", "model.reaction.is_valid.user_id.app_error", nil, "user_id="+o.UserId, http.StatusBadRequest)

Просмотреть файл

@@ -127,14 +127,6 @@ func (rc *RemoteCluster) fixTopics() {
rc.Topics = sb.String()
}
func (rc *RemoteCluster) ToJSON() (string, error) {
b, err := json.Marshal(rc)
if err != nil {
return "", err
}
return string(b), nil
}
func (rc *RemoteCluster) ToRemoteClusterInfo() RemoteClusterInfo {
return RemoteClusterInfo{
Name: rc.Name,
@@ -148,15 +140,6 @@ func NormalizeRemoteName(name string) string {
return strings.ToLower(name)
}
func RemoteClusterFromJSON(data io.Reader) (*RemoteCluster, *AppError) {
var rc RemoteCluster
err := json.NewDecoder(data).Decode(&rc)
if err != nil {
return nil, NewAppError("RemoteClusterFromJSON", "model.utils.decode_json.app_error", nil, err.Error(), http.StatusBadRequest)
}
return &rc, nil
}
// RemoteClusterInfo provides a subset of RemoteCluster fields suitable for sending to clients.
type RemoteClusterInfo struct {
Name string `json:"name"`
@@ -183,15 +166,6 @@ func (f *RemoteClusterFrame) IsValid() *AppError {
return nil
}
func RemoteClusterFrameFromJSON(data io.Reader) (*RemoteClusterFrame, *AppError) {
var frame RemoteClusterFrame
err := json.NewDecoder(data).Decode(&frame)
if err != nil {
return nil, NewAppError("RemoteClusterFrameFromJSON", "model.utils.decode_json.app_error", nil, err.Error(), http.StatusBadRequest)
}
return &frame, nil
}
// RemoteClusterMsg represents a message that is sent and received between clusters.
// These are processed and routed via the RemoteClusters service.
type RemoteClusterMsg struct {
@@ -226,15 +200,6 @@ func (m RemoteClusterMsg) IsValid() *AppError {
return nil
}
func RemoteClusterMsgFromJSON(data io.Reader) (RemoteClusterMsg, *AppError) {
var msg RemoteClusterMsg
err := json.NewDecoder(data).Decode(&msg)
if err != nil {
return RemoteClusterMsg{}, NewAppError("RemoteClusterMsgFromJSON", "model.utils.decode_json.app_error", nil, err.Error(), http.StatusBadRequest)
}
return msg, nil
}
// RemoteClusterPing represents a ping that is sent and received between clusters
// to indicate a connection is alive. This is the payload for a `RemoteClusterMsg`.
type RemoteClusterPing struct {
@@ -242,15 +207,6 @@ type RemoteClusterPing struct {
RecvAt int64 `json:"recv_at"`
}
func RemoteClusterPingFromRawJSON(raw json.RawMessage) (RemoteClusterPing, *AppError) {
var ping RemoteClusterPing
err := json.Unmarshal(raw, &ping)
if err != nil {
return RemoteClusterPing{}, NewAppError("RemoteClusterPingFromRawJSON", "model.utils.decode_json.app_error", nil, err.Error(), http.StatusBadRequest)
}
return ping, nil
}
// RemoteClusterInvite represents an invitation to establish a simple trust with a remote cluster.
type RemoteClusterInvite struct {
RemoteId string `json:"remote_id"`
@@ -259,15 +215,6 @@ type RemoteClusterInvite struct {
Token string `json:"token"`
}
func RemoteClusterInviteFromRawJSON(raw json.RawMessage) (*RemoteClusterInvite, *AppError) {
var invite RemoteClusterInvite
err := json.Unmarshal(raw, &invite)
if err != nil {
return nil, NewAppError("RemoteClusterInviteFromRawJSON", "model.utils.decode_json.app_error", nil, err.Error(), http.StatusBadRequest)
}
return &invite, nil
}
func (rci *RemoteClusterInvite) Encrypt(password string) ([]byte, error) {
raw, err := json.Marshal(&rci)
if err != nil {

Просмотреть файл

@@ -5,28 +5,13 @@ package model
import (
"crypto/rand"
"encoding/json"
"io"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRemoteClusterJson(t *testing.T) {
o := RemoteCluster{RemoteId: NewId(), Name: "test"}
json, err := o.ToJSON()
require.NoError(t, err)
ro, appErr := RemoteClusterFromJSON(strings.NewReader(json))
require.Nil(t, appErr)
require.Equal(t, o.RemoteId, ro.RemoteId)
require.Equal(t, o.Name, ro.Name)
}
func TestRemoteClusterIsValid(t *testing.T) {
id := NewId()
creator := NewId()
@@ -66,20 +51,6 @@ func TestRemoteClusterPreSave(t *testing.T) {
require.GreaterOrEqual(t, o.CreateAt, now)
}
func TestRemoteClusterMsgJson(t *testing.T) {
o := NewRemoteClusterMsg("shared_channel", []byte("{\"hello\":\"world\"}"))
json, err := json.Marshal(o)
require.NoError(t, err)
ro, appErr := RemoteClusterMsgFromJSON(strings.NewReader(string(json)))
require.Nil(t, appErr)
require.Equal(t, o.Id, ro.Id)
require.Equal(t, o.CreateAt, ro.CreateAt)
require.Equal(t, o.Topic, ro.Topic)
}
func TestRemoteClusterMsgIsValid(t *testing.T) {
id := NewId()
now := GetMillis()

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"strings"
)
@@ -399,39 +397,6 @@ type RolePermissions struct {
Permissions []string
}
func (r *Role) ToJson() string {
b, _ := json.Marshal(r)
return string(b)
}
func RoleFromJson(data io.Reader) *Role {
var r *Role
json.NewDecoder(data).Decode(&r)
return r
}
func RoleListToJson(r []*Role) string {
b, _ := json.Marshal(r)
return string(b)
}
func RoleListFromJson(data io.Reader) []*Role {
var roles []*Role
json.NewDecoder(data).Decode(&roles)
return roles
}
func (r *RolePatch) ToJson() string {
b, _ := json.Marshal(r)
return string(b)
}
func RolePatchFromJson(data io.Reader) *RolePatch {
var rolePatch *RolePatch
json.NewDecoder(data).Decode(&rolePatch)
return rolePatch
}
func (r *Role) Patch(patch *RolePatch) {
if patch.Permissions != nil {
r.Permissions = *patch.Permissions

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"encoding/xml"
"io"
"time"
)
@@ -176,25 +174,3 @@ type EntityDescriptor struct {
Organization Organization `xml:"Organization"`
ContactPerson ContactPerson `xml:"ContactPerson"`
}
func (s *SamlCertificateStatus) ToJson() string {
b, _ := json.Marshal(s)
return string(b)
}
func SamlCertificateStatusFromJson(data io.Reader) *SamlCertificateStatus {
var status *SamlCertificateStatus
json.NewDecoder(data).Decode(&status)
return status
}
func (s *SamlMetadataResponse) ToJson() string {
b, _ := json.Marshal(s)
return string(b)
}
func SamlMetadataResponseFromJson(data io.Reader) *SamlMetadataResponse {
var status *SamlMetadataResponse
json.NewDecoder(data).Decode(&status)
return status
}

Просмотреть файл

@@ -1,22 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestSamlCertificateStatusJson(t *testing.T) {
status := &SamlCertificateStatus{IdpCertificateFile: true, PrivateKeyFile: true, PublicCertificateFile: true}
json := status.ToJson()
rstatus := SamlCertificateStatusFromJson(strings.NewReader(json))
require.Equal(t, status.IdpCertificateFile, rstatus.IdpCertificateFile, "IdpCertificateFile do not match")
rstatus = SamlCertificateStatusFromJson(strings.NewReader("junk"))
require.Nil(t, rstatus, "should be nil")
}

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"fmt"
"io"
"regexp"
)
@@ -81,30 +79,6 @@ type SchemeRoles struct {
SchemeGuest bool `json:"scheme_guest"`
}
func (scheme *Scheme) ToJson() string {
b, _ := json.Marshal(scheme)
return string(b)
}
func SchemeFromJson(data io.Reader) *Scheme {
var scheme *Scheme
json.NewDecoder(data).Decode(&scheme)
return scheme
}
func SchemesToJson(schemes []*Scheme) string {
b, _ := json.Marshal(schemes)
return string(b)
}
func SchemesFromJson(data io.Reader) []*Scheme {
var schemes []*Scheme
if err := json.NewDecoder(data).Decode(&schemes); err == nil {
return schemes
}
return nil
}
func (scheme *Scheme) IsValid() bool {
if !IsValidId(scheme.Id) {
return false
@@ -187,40 +161,7 @@ func (scheme *Scheme) Patch(patch *SchemePatch) {
}
}
func (patch *SchemePatch) ToJson() string {
b, _ := json.Marshal(patch)
return string(b)
}
func SchemePatchFromJson(data io.Reader) *SchemePatch {
var patch *SchemePatch
json.NewDecoder(data).Decode(&patch)
return patch
}
func SchemeIDFromJson(data io.Reader) *string {
var p *SchemeIDPatch
json.NewDecoder(data).Decode(&p)
return p.SchemeID
}
func (p *SchemeIDPatch) ToJson() string {
b, _ := json.Marshal(p)
return string(b)
}
func IsValidSchemeName(name string) bool {
re := regexp.MustCompile(fmt.Sprintf("^[a-z0-9_]{2,%d}$", SchemeNameMaxLength))
return re.MatchString(name)
}
func (schemeRoles *SchemeRoles) ToJson() string {
b, _ := json.Marshal(schemeRoles)
return string(b)
}
func SchemeRolesFromJson(data io.Reader) *SchemeRoles {
var schemeRoles *SchemeRoles
json.NewDecoder(data).Decode(&schemeRoles)
return schemeRoles
}

Просмотреть файл

@@ -3,39 +3,9 @@
package model
import (
"encoding/json"
"io"
)
type SecurityBulletin struct {
Id string `json:"id"`
AppliesToVersion string `json:"applies_to_version"`
}
type SecurityBulletins []SecurityBulletin
func (sb *SecurityBulletin) ToJson() string {
b, _ := json.Marshal(sb)
return string(b)
}
func SecurityBulletinFromJson(data io.Reader) *SecurityBulletin {
var o *SecurityBulletin
json.NewDecoder(data).Decode(&o)
return o
}
func (sb SecurityBulletins) ToJson() string {
b, err := json.Marshal(sb)
if err != nil {
return "[]"
}
return string(b)
}
func SecurityBulletinsFromJson(data io.Reader) SecurityBulletins {
var o SecurityBulletins
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -1,53 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestSecurityBulletinToFromJson(t *testing.T) {
b := SecurityBulletin{
Id: NewId(),
AppliesToVersion: NewId(),
}
j := b.ToJson()
b1 := SecurityBulletinFromJson(strings.NewReader(j))
require.Equal(t, b, *b1)
// Malformed JSON
s2 := `{"wat"`
b2 := SecurityBulletinFromJson(strings.NewReader(s2))
require.Nil(t, b2)
}
func TestSecurityBulletinsToFromJson(t *testing.T) {
b := SecurityBulletins{
{
Id: NewId(),
AppliesToVersion: NewId(),
},
{
Id: NewId(),
AppliesToVersion: NewId(),
},
}
j := b.ToJson()
b1 := SecurityBulletinsFromJson(strings.NewReader(j))
require.Len(t, b1, 2)
// Malformed JSON
s2 := `{"wat"`
b2 := SecurityBulletinsFromJson(strings.NewReader(s2))
require.Empty(t, b2)
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"strconv"
"strings"
@@ -80,17 +78,6 @@ func (s *Session) DeepCopy() *Session {
return &copySession
}
func (s *Session) ToJson() string {
b, _ := json.Marshal(s)
return string(b)
}
func SessionFromJson(data io.Reader) *Session {
var s *Session
json.NewDecoder(data).Decode(&s)
return s
}
func (s *Session) PreSave() {
if s.Id == "" {
s.Id = NewId()
@@ -208,17 +195,3 @@ func (s *Session) GetCSRF() string {
return s.Props["csrf"]
}
func SessionsToJson(o []*Session) string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func SessionsFromJson(data io.Reader) []*Session {
var o []*Session
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -5,9 +5,7 @@ package model
import (
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -41,24 +39,6 @@ func TestSessionDeepCopy(t *testing.T) {
assert.Equal(t, 0, len(copySession.TeamMembers))
}
func TestSessionJson(t *testing.T) {
session := Session{}
session.PreSave()
json := session.ToJson()
rsession := SessionFromJson(strings.NewReader(json))
require.Equal(t, rsession.Id, session.Id, "Ids do not match")
session.Sanitize()
require.False(t, session.IsExpired(), "Shouldn't expire")
session.ExpiresAt = GetMillis()
time.Sleep(10 * time.Millisecond)
require.True(t, session.IsExpired(), "Should expire")
}
func TestSessionCSRF(t *testing.T) {
s := Session{}
token := s.GetCSRF()

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"net/http"
"unicode/utf8"
)
@@ -31,17 +29,6 @@ type SharedChannel struct {
Type ChannelType `db:"-"`
}
func (sc *SharedChannel) ToJson() string {
b, _ := json.Marshal(sc)
return string(b)
}
func SharedChannelFromJson(data io.Reader) (*SharedChannel, error) {
var sc *SharedChannel
err := json.NewDecoder(data).Decode(&sc)
return sc, err
}
func (sc *SharedChannel) IsValid() *AppError {
if !IsValidId(sc.ChannelId) {
return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.id.app_error", nil, "ChannelId="+sc.ChannelId, http.StatusBadRequest)
@@ -116,17 +103,6 @@ type SharedChannelRemote struct {
LastPostId string `json:"last_post_id"`
}
func (sc *SharedChannelRemote) ToJson() string {
b, _ := json.Marshal(sc)
return string(b)
}
func SharedChannelRemoteFromJson(data io.Reader) (*SharedChannelRemote, error) {
var sc *SharedChannelRemote
err := json.NewDecoder(data).Decode(&sc)
return sc, err
}
func (sc *SharedChannelRemote) IsValid() *AppError {
if !IsValidId(sc.Id) {
return NewAppError("SharedChannelRemote.IsValid", "model.channel.is_valid.id.app_error", nil, "Id="+sc.Id, http.StatusBadRequest)

Просмотреть файл

@@ -11,16 +11,6 @@ import (
"github.com/stretchr/testify/require"
)
func TestSharedChannelJson(t *testing.T) {
o := SharedChannel{ChannelId: NewId(), ShareName: NewId()}
json := o.ToJson()
ro, err := SharedChannelFromJson(strings.NewReader(json))
require.NoError(t, err)
require.Equal(t, o.ChannelId, ro.ChannelId)
require.Equal(t, o.ShareName, ro.ShareName)
}
func TestSharedChannelIsValid(t *testing.T) {
id := NewId()
now := GetMillis()
@@ -74,13 +64,3 @@ func TestSharedChannelPreUpdate(t *testing.T) {
require.GreaterOrEqual(t, o.UpdateAt, now)
}
func TestSharedChannelRemoteJson(t *testing.T) {
o := SharedChannelRemote{Id: NewId(), ChannelId: NewId()}
json := o.ToJson()
ro, err := SharedChannelRemoteFromJson(strings.NewReader(json))
require.NoError(t, err)
require.Equal(t, o.Id, ro.Id)
require.Equal(t, o.ChannelId, ro.ChannelId)
}

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"io"
)
const (
@@ -29,41 +28,19 @@ type Status struct {
PrevStatus string `json:"-"`
}
func (o *Status) ToJson() string {
oCopy := *o
oCopy.ActiveChannel = ""
b, _ := json.Marshal(oCopy)
return string(b)
func (s *Status) ToJSON() ([]byte, error) {
sCopy := *s
sCopy.ActiveChannel = ""
return json.Marshal(sCopy)
}
func (o *Status) ToClusterJson() string {
oCopy := *o
b, _ := json.Marshal(oCopy)
return string(b)
}
func StatusFromJson(data io.Reader) *Status {
var o *Status
json.NewDecoder(data).Decode(&o)
return o
}
func StatusListToJson(u []*Status) string {
uCopy := make([]Status, len(u))
func StatusListToJSON(u []*Status) ([]byte, error) {
list := make([]Status, len(u))
for i, s := range u {
sCopy := *s
sCopy.ActiveChannel = ""
uCopy[i] = sCopy
list[i] = *s
list[i].ActiveChannel = ""
}
b, _ := json.Marshal(uCopy)
return string(b)
}
func StatusListFromJson(data io.Reader) []*Status {
var statuses []*Status
json.NewDecoder(data).Decode(&statuses)
return statuses
return json.Marshal(list)
}
func StatusMapToInterfaceMap(statusMap map[string]*Status) map[string]interface{} {

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -13,27 +12,26 @@ import (
func TestStatus(t *testing.T) {
status := Status{NewId(), StatusOnline, true, 0, "123", 0, ""}
json := status.ToJson()
status2 := StatusFromJson(strings.NewReader(json))
js, err := status.ToJSON()
assert.NoError(t, err)
var status2 Status
err = json.Unmarshal(js, &status2)
assert.NoError(t, err)
assert.Equal(t, status.UserId, status2.UserId, "UserId should have matched")
assert.Equal(t, status.Status, status2.Status, "Status should have matched")
assert.Equal(t, status.LastActivityAt, status2.LastActivityAt, "LastActivityAt should have matched")
assert.Equal(t, status.Manual, status2.Manual, "Manual should have matched")
assert.Equal(t, "", status2.ActiveChannel)
json = status.ToClusterJson()
status2 = StatusFromJson(strings.NewReader(json))
assert.Equal(t, status.ActiveChannel, status2.ActiveChannel)
}
func TestStatusListToJson(t *testing.T) {
func TestStatusListToJSON(t *testing.T) {
statuses := []*Status{{NewId(), StatusOnline, true, 0, "123", 0, ""}, {NewId(), StatusOffline, true, 0, "", 0, ""}}
jsonStatuses := StatusListToJson(statuses)
jsonStatuses, err := StatusListToJSON(statuses)
assert.NoError(t, err)
var dat []map[string]interface{}
if err := json.Unmarshal([]byte(jsonStatuses), &dat); err != nil {
if err := json.Unmarshal(jsonStatuses, &dat); err != nil {
panic(err)
}
@@ -45,19 +43,3 @@ func TestStatusListToJson(t *testing.T) {
assert.Equal(t, statuses[0].UserId, dat[0]["user_id"])
assert.Equal(t, statuses[1].UserId, dat[1]["user_id"])
}
func TestStatusListFromJson(t *testing.T) {
const jsonStream = `
[{"user_id":"k39fowpzhfffjxeaw8ecyrygme","status":"online","manual":true,"last_activity_at":0},{"user_id":"e9f1bbg8wfno7b3k7yk79bbwfy","status":"offline","manual":true,"last_activity_at":0}]
`
var dat []map[string]interface{}
if err := json.Unmarshal([]byte(jsonStream), &dat); err != nil {
panic(err)
}
toDec := strings.NewReader(jsonStream)
statusesFromJson := StatusListFromJson(toDec)
assert.Equal(t, statusesFromJson[0].UserId, dat[0]["user_id"], "UserId should be equal")
assert.Equal(t, statusesFromJson[1].UserId, dat[1]["user_id"], "UserId should be equal")
}

Просмотреть файл

@@ -3,23 +3,7 @@
package model
import (
"encoding/json"
"io"
)
type SuggestCommand struct {
Suggestion string `json:"suggestion"`
Description string `json:"description"`
}
func (o *SuggestCommand) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func SuggestCommandFromJson(data io.Reader) *SuggestCommand {
var o *SuggestCommand
json.NewDecoder(data).Decode(&o)
return o
}

Просмотреть файл

@@ -1,19 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSuggestCommandJson(t *testing.T) {
command := &SuggestCommand{Suggestion: NewId()}
json := command.ToJson()
result := SuggestCommandFromJson(strings.NewReader(json))
assert.Equal(t, command.Suggestion, result.Suggestion, "Ids do not match")
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type SwitchRequest struct {
CurrentService string `json:"current_service"`
NewService string `json:"new_service"`
@@ -18,17 +13,6 @@ type SwitchRequest struct {
LdapLoginId string `json:"ldap_id"`
}
func (o *SwitchRequest) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func SwitchRequestFromJson(data io.Reader) *SwitchRequest {
var o *SwitchRequest
json.NewDecoder(data).Decode(&o)
return o
}
func (o *SwitchRequest) EmailToOAuth() bool {
return o.CurrentService == UserAuthServiceEmail &&
(o.NewService == UserAuthServiceSaml ||

Просмотреть файл

@@ -1,19 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestSwitchRequestJson(t *testing.T) {
o := SwitchRequest{Email: NewId(), Password: NewId()}
json := o.ToJson()
ro := SwitchRequestFromJson(strings.NewReader(json))
require.Equal(t, o.Email, ro.Email, "Emails do not match")
}

Просмотреть файл

@@ -4,8 +4,6 @@
package model
import (
"encoding/json"
"io"
"math/big"
)
@@ -56,17 +54,6 @@ type System struct {
Value string `json:"value"`
}
func (o *System) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func SystemFromJson(data io.Reader) *System {
var o *System
json.NewDecoder(data).Decode(&o)
return o
}
type SystemPostActionCookieSecret struct {
Secret []byte `json:"key,omitempty"`
}
@@ -105,17 +92,6 @@ type FileData struct {
Body []byte
}
func (sbs *ServerBusyState) ToJson() string {
b, _ := json.Marshal(sbs)
return string(b)
}
func ServerBusyStateFromJson(r io.Reader) *ServerBusyState {
var sbs *ServerBusyState
json.NewDecoder(r).Decode(&sbs)
return sbs
}
var WarnMetricsTable = map[string]WarnMetric{
SystemWarnMetricMfa: {
Id: SystemWarnMetricMfa,
@@ -201,35 +177,6 @@ type WarnMetricStatus struct {
StoreStatus string `json:"store_status,omitempty"`
}
func (wms *WarnMetricStatus) ToJson() string {
b, _ := json.Marshal(wms)
return string(b)
}
func WarnMetricStatusFromJson(data io.Reader) *WarnMetricStatus {
var o WarnMetricStatus
if err := json.NewDecoder(data).Decode(&o); err != nil {
return nil
}
return &o
}
func MapWarnMetricStatusToJson(o map[string]*WarnMetricStatus) string {
b, _ := json.Marshal(o)
return string(b)
}
type SendWarnMetricAck struct {
ForceAck bool `json:"forceAck"`
}
func (swma *SendWarnMetricAck) ToJson() string {
b, _ := json.Marshal(swma)
return string(b)
}
func SendWarnMetricAckFromJson(r io.Reader) *SendWarnMetricAck {
var swma *SendWarnMetricAck
json.NewDecoder(r).Decode(&swma)
return swma
}

Просмотреть файл

@@ -1,30 +0,0 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestSystemJson(t *testing.T) {
system := System{Name: "test", Value: NewId()}
json := system.ToJson()
result := SystemFromJson(strings.NewReader(json))
require.Equal(t, "test", result.Name, "ids do not match")
}
func TestServerBusyJson(t *testing.T) {
now := time.Now()
sbs := ServerBusyState{Busy: true, Expires: now.Unix()}
json := sbs.ToJson()
result := ServerBusyStateFromJson(strings.NewReader(json))
require.Equal(t, sbs.Busy, result.Busy, "busy state does not match")
require.Equal(t, sbs.Expires, result.Expires, "expiry does not match")
}

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strings"
@@ -68,12 +66,6 @@ type TeamsWithCount struct {
TotalCount int64 `json:"total_count"`
}
func InvitesFromJson(data io.Reader) *Invites {
var o *Invites
json.NewDecoder(data).Decode(&o)
return o
}
func (o *Invites) ToEmailList() []string {
emailList := make([]string, len(o.Invites))
for _, invite := range o.Invites {
@@ -82,61 +74,11 @@ func (o *Invites) ToEmailList() []string {
return emailList
}
func (o *Invites) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func (o *Team) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func TeamFromJson(data io.Reader) *Team {
var o *Team
json.NewDecoder(data).Decode(&o)
return o
}
func TeamMapToJson(u map[string]*Team) string {
b, _ := json.Marshal(u)
return string(b)
}
func TeamMapFromJson(data io.Reader) map[string]*Team {
var teams map[string]*Team
json.NewDecoder(data).Decode(&teams)
return teams
}
func TeamListToJson(t []*Team) string {
b, _ := json.Marshal(t)
return string(b)
}
func TeamsWithCountToJson(tlc *TeamsWithCount) []byte {
b, _ := json.Marshal(tlc)
return b
}
func TeamsWithCountFromJson(data io.Reader) *TeamsWithCount {
var twc *TeamsWithCount
json.NewDecoder(data).Decode(&twc)
return twc
}
func TeamListFromJson(data io.Reader) []*Team {
var teams []*Team
json.NewDecoder(data).Decode(&teams)
return teams
}
func (o *Team) Etag() string {
return Etag(o.Id, o.UpdateAt)
}
func (o *Team) IsValid() *AppError {
if !IsValidId(o.Id) {
return NewAppError("Team.IsValid", "model.team.is_valid.id.app_error", nil, "", http.StatusBadRequest)
}
@@ -309,23 +251,3 @@ func (o *Team) Patch(patch *TeamPatch) {
func (o *Team) IsGroupConstrained() bool {
return o.GroupConstrained != nil && *o.GroupConstrained
}
func (t *TeamPatch) ToJson() string {
b, err := json.Marshal(t)
if err != nil {
return ""
}
return string(b)
}
func TeamPatchFromJson(data io.Reader) *TeamPatch {
decoder := json.NewDecoder(data)
var team TeamPatch
err := decoder.Decode(&team)
if err != nil {
return nil
}
return &team
}

Просмотреть файл

@@ -4,9 +4,7 @@
package model
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
@@ -71,34 +69,6 @@ type TeamMembersGetOptions struct {
ViewRestrictions *ViewUsersRestrictions
}
func (o *TeamMember) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func (o *TeamUnread) ToJson() string {
b, _ := json.Marshal(o)
return string(b)
}
func TeamMemberFromJson(data io.Reader) *TeamMember {
var o *TeamMember
json.NewDecoder(data).Decode(&o)
return o
}
func TeamUnreadFromJson(data io.Reader) *TeamUnread {
var o *TeamUnread
json.NewDecoder(data).Decode(&o)
return o
}
func EmailInviteWithErrorFromJson(data io.Reader) []*EmailInviteWithError {
var o []*EmailInviteWithError
json.NewDecoder(data).Decode(&o)
return o
}
func EmailInviteWithErrorToEmails(o []*EmailInviteWithError) []string {
var ret []string
for _, o := range o {
@@ -109,14 +79,6 @@ func EmailInviteWithErrorToEmails(o []*EmailInviteWithError) []string {
return ret
}
func EmailInviteWithErrorToJson(o []*EmailInviteWithError) string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func EmailInviteWithErrorToString(o *EmailInviteWithError) string {
return fmt.Sprintf("%s:%s", o.Email, o.Error.Error())
}
@@ -131,52 +93,10 @@ func TeamMembersWithErrorToTeamMembers(o []*TeamMemberWithError) []*TeamMember {
return ret
}
func TeamMembersWithErrorToJson(o []*TeamMemberWithError) string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func TeamMemberWithErrorToString(o *TeamMemberWithError) string {
return fmt.Sprintf("%s:%s", o.UserId, o.Error.Error())
}
func TeamMembersWithErrorFromJson(data io.Reader) []*TeamMemberWithError {
var o []*TeamMemberWithError
json.NewDecoder(data).Decode(&o)
return o
}
func TeamMembersToJson(o []*TeamMember) string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func TeamMembersFromJson(data io.Reader) []*TeamMember {
var o []*TeamMember
json.NewDecoder(data).Decode(&o)
return o
}
func TeamsUnreadToJson(o []*TeamUnread) string {
b, err := json.Marshal(o)
if err != nil {
return "[]"
}
return string(b)
}
func TeamsUnreadFromJson(data io.Reader) []*TeamUnread {
var o []*TeamUnread
json.NewDecoder(data).Decode(&o)
return o
}
func (o *TeamMember) IsValid() *AppError {
if !IsValidId(o.TeamId) {

Просмотреть файл

@@ -4,37 +4,14 @@
package model
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestTeamMemberJson(t *testing.T) {
o := TeamMember{TeamId: NewId(), UserId: NewId()}
json := o.ToJson()
ro := TeamMemberFromJson(strings.NewReader(json))
require.Equal(t, o.TeamId, ro.TeamId, "Ids do not match")
}
func TestTeamMemberIsValid(t *testing.T) {
o := TeamMember{}
require.NotNil(t, o.IsValid(), "should be invalid")
o.TeamId = NewId()
require.NotNil(t, o.IsValid(), "should be invalid")
}
func TestUnreadMemberJson(t *testing.T) {
o := TeamUnread{TeamId: NewId(), MsgCount: 5, MentionCount: 3}
json := o.ToJson()
r := TeamUnreadFromJson(strings.NewReader(json))
require.Equal(t, o.TeamId, r.TeamId, "Ids do not match")
require.Equal(t, o.MsgCount, r.MsgCount, "MsgCount do not match")
}

Просмотреть файл

@@ -3,11 +3,6 @@
package model
import (
"encoding/json"
"io"
)
type TeamSearch struct {
Term string `json:"term"`
Page *int `json:"page,omitempty"`
@@ -25,25 +20,3 @@ type TeamSearch struct {
func (t *TeamSearch) IsPaginated() bool {
return t.Page != nil && t.PerPage != nil
}
// ToJson convert a TeamSearch to json string
func (t *TeamSearch) ToJson() string {
b, err := json.Marshal(t)
if err != nil {
return ""
}
return string(b)
}
// TeamSearchFromJson decodes the input and returns a TeamSearch
func TeamSearchFromJson(data io.Reader) *TeamSearch {
decoder := json.NewDecoder(data)
var cs TeamSearch
err := decoder.Decode(&cs)
if err == nil {
return &cs
}
return nil
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше