github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/store/storetest/channel_store_test.go (about)

     1  package storetest
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"sort"
     7  	"strconv"
     8  	"strings"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/masterhung0112/hk_server/v5/model"
    13  	"github.com/masterhung0112/hk_server/v5/services/timezones"
    14  	"github.com/masterhung0112/hk_server/v5/store"
    15  	"github.com/masterhung0112/hk_server/v5/utils"
    16  )
    17  
    18  // type ChannelStoreTestSuite struct {
    19  // 	suite.Suite
    20  // 	StoreTestSuite
    21  // }
    22  
    23  func (s *ChannelStoreTestSuite) SetupTest() {
    24  	createDefaultRoles(s.Store())
    25  }
    26  
    27  // func TestChannelStoreTestSuite(t *testing.T) {
    28  // 	StoreTestSuiteWithSqlSupplier(&ChannelStoreTestSuite{}, func(t *testing.T, testSuite StoreTestBaseSuite) {
    29  // 		suite.Run(testSuite)
    30  // 	})
    31  // }
    32  
    33  func (s *ChannelStoreTestSuite) cleanupChannels() {
    34  	list, err := s.Store().Channel().GetAllChannels(0, 100000, store.ChannelSearchOpts{IncludeDeleted: true})
    35  	s.Require().Nilf(err, "error cleaning all channels: %v", err)
    36  	for _, channel := range *list {
    37  		err = s.Store().Channel().PermanentDelete(channel.Id)
    38  		s.Assert().NoError(err)
    39  	}
    40  }
    41  
    42  func (s *ChannelStoreTestSuite) TestStoreSave() {
    43  	teamId := model.NewId()
    44  
    45  	o1 := model.Channel{}
    46  	o1.TeamId = teamId
    47  	o1.DisplayName = "Name"
    48  	o1.Name = "zz" + model.NewId() + "b"
    49  	o1.Type = model.CHANNEL_OPEN
    50  
    51  	_, nErr := s.Store().Channel().Save(&o1, -1)
    52  	s.Require().Nil(nErr, "couldn't save item", nErr)
    53  
    54  	_, nErr = s.Store().Channel().Save(&o1, -1)
    55  	s.Require().NotNil(nErr, "shouldn't be able to update from save")
    56  
    57  	o1.Id = ""
    58  	_, nErr = s.Store().Channel().Save(&o1, -1)
    59  	s.Require().NotNil(nErr, "should be unique name")
    60  
    61  	o1.Id = ""
    62  	o1.Name = "zz" + model.NewId() + "b"
    63  	o1.Type = model.CHANNEL_DIRECT
    64  	_, nErr = s.Store().Channel().Save(&o1, -1)
    65  	s.Require().NotNil(nErr, "should not be able to save direct channel")
    66  
    67  	o1 = model.Channel{}
    68  	o1.TeamId = teamId
    69  	o1.DisplayName = "Name"
    70  	o1.Name = "zz" + model.NewId() + "b"
    71  	o1.Type = model.CHANNEL_OPEN
    72  
    73  	_, nErr = s.Store().Channel().Save(&o1, -1)
    74  	s.Require().Nil(nErr, "should have saved channel")
    75  
    76  	o2 := o1
    77  	o2.Id = ""
    78  
    79  	_, nErr = s.Store().Channel().Save(&o2, -1)
    80  	s.Require().NotNil(nErr, "should have failed to save a duplicate channel")
    81  	var cErr *store.ErrConflict
    82  	s.Require().True(errors.As(nErr, &cErr))
    83  
    84  	err := s.Store().Channel().Delete(o1.Id, 100)
    85  	s.Require().Nil(err, "should have deleted channel")
    86  
    87  	o2.Id = ""
    88  	_, nErr = s.Store().Channel().Save(&o2, -1)
    89  	s.Require().NotNil(nErr, "should have failed to save a duplicate of an archived channel")
    90  	s.Require().True(errors.As(nErr, &cErr))
    91  }
    92  
    93  func (s *ChannelStoreTestSuite) TestStoreSaveDirectChannel() {
    94  	teamId := model.NewId()
    95  
    96  	o1 := model.Channel{}
    97  	o1.TeamId = teamId
    98  	o1.DisplayName = "Name"
    99  	o1.Name = "zz" + model.NewId() + "b"
   100  	o1.Type = model.CHANNEL_DIRECT
   101  
   102  	u1 := &model.User{}
   103  	u1.Email = MakeEmail()
   104  	u1.Nickname = model.NewId()
   105  	_, err := s.Store().User().Save(u1)
   106  	s.Require().Nil(err)
   107  	_, nErr := s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
   108  	s.Require().Nil(nErr)
   109  
   110  	u2 := &model.User{}
   111  	u2.Email = MakeEmail()
   112  	u2.Nickname = model.NewId()
   113  	_, err = s.Store().User().Save(u2)
   114  	s.Require().Nil(err)
   115  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
   116  	s.Require().Nil(nErr)
   117  
   118  	m1 := model.ChannelMember{}
   119  	m1.ChannelId = o1.Id
   120  	m1.UserId = u1.Id
   121  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
   122  
   123  	m2 := model.ChannelMember{}
   124  	m2.ChannelId = o1.Id
   125  	m2.UserId = u2.Id
   126  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
   127  
   128  	_, nErr = s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
   129  	s.Require().Nil(nErr, "couldn't save direct channel", nErr)
   130  
   131  	members, nErr := s.Store().Channel().GetMembers(o1.Id, 0, 100)
   132  	s.Require().Nil(nErr)
   133  	s.Require().Len(*members, 2, "should have saved 2 members")
   134  
   135  	_, nErr = s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
   136  	s.Require().NotNil(nErr, "shoudn't be a able to update from save")
   137  
   138  	// Attempt to save a direct channel that already exists
   139  	o1a := model.Channel{
   140  		TeamId:      o1.TeamId,
   141  		DisplayName: o1.DisplayName,
   142  		Name:        o1.Name,
   143  		Type:        o1.Type,
   144  	}
   145  
   146  	returnedChannel, nErr := s.Store().Channel().SaveDirectChannel(&o1a, &m1, &m2)
   147  	s.Require().NotNil(nErr, "should've failed to save a duplicate direct channel")
   148  	var cErr *store.ErrConflict
   149  	s.Require().Truef(errors.As(nErr, &cErr), "should've returned ChannelExistsError")
   150  	s.Require().Equal(o1.Id, returnedChannel.Id, "should've failed to save a duplicate direct channel")
   151  
   152  	// Attempt to save a non-direct channel
   153  	o1.Id = ""
   154  	o1.Name = "zz" + model.NewId() + "b"
   155  	o1.Type = model.CHANNEL_OPEN
   156  	_, nErr = s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
   157  	s.Require().NotNil(nErr, "Should not be able to save non-direct channel")
   158  
   159  	// Save yourself Direct Message
   160  	o1.Id = ""
   161  	o1.DisplayName = "Myself"
   162  	o1.Name = "zz" + model.NewId() + "b"
   163  	o1.Type = model.CHANNEL_DIRECT
   164  	_, nErr = s.Store().Channel().SaveDirectChannel(&o1, &m1, &m1)
   165  	s.Require().Nil(nErr, "couldn't save direct channel", nErr)
   166  
   167  	members, nErr = s.Store().Channel().GetMembers(o1.Id, 0, 100)
   168  	s.Require().Nil(nErr)
   169  	s.Require().Len(*members, 1, "should have saved just 1 member")
   170  
   171  	// Manually truncate Channels table until testlib can handle cleanups
   172  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
   173  }
   174  
   175  func (s *ChannelStoreTestSuite) TestStoreCreateDirectChannel() {
   176  	u1 := &model.User{}
   177  	u1.Email = MakeEmail()
   178  	u1.Nickname = model.NewId()
   179  	_, err := s.Store().User().Save(u1)
   180  	s.Require().Nil(err)
   181  	_, nErr := s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
   182  	s.Require().Nil(nErr)
   183  
   184  	u2 := &model.User{}
   185  	u2.Email = MakeEmail()
   186  	u2.Nickname = model.NewId()
   187  	_, err = s.Store().User().Save(u2)
   188  	s.Require().Nil(err)
   189  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
   190  	s.Require().Nil(nErr)
   191  
   192  	c1, nErr := s.Store().Channel().CreateDirectChannel(u1, u2)
   193  	s.Require().Nil(nErr, "couldn't create direct channel", nErr)
   194  	defer func() {
   195  		s.Store().Channel().PermanentDeleteMembersByChannel(c1.Id)
   196  		s.Store().Channel().PermanentDelete(c1.Id)
   197  	}()
   198  
   199  	members, nErr := s.Store().Channel().GetMembers(c1.Id, 0, 100)
   200  	s.Require().Nil(nErr)
   201  	s.Require().Len(*members, 2, "should have saved 2 members")
   202  }
   203  
   204  func (s *ChannelStoreTestSuite) TestStoreUpdate() {
   205  	o1 := model.Channel{}
   206  	o1.TeamId = model.NewId()
   207  	o1.DisplayName = "Name"
   208  	o1.Name = "zz" + model.NewId() + "b"
   209  	o1.Type = model.CHANNEL_OPEN
   210  
   211  	_, nErr := s.Store().Channel().Save(&o1, -1)
   212  	s.Require().Nil(nErr)
   213  
   214  	o2 := model.Channel{}
   215  	o2.TeamId = o1.TeamId
   216  	o2.DisplayName = "Name"
   217  	o2.Name = "zz" + model.NewId() + "b"
   218  	o2.Type = model.CHANNEL_OPEN
   219  
   220  	_, nErr = s.Store().Channel().Save(&o2, -1)
   221  	s.Require().Nil(nErr)
   222  
   223  	time.Sleep(100 * time.Millisecond)
   224  
   225  	_, err := s.Store().Channel().Update(&o1)
   226  	s.Require().Nil(err, err)
   227  
   228  	o1.DeleteAt = 100
   229  	_, err = s.Store().Channel().Update(&o1)
   230  	s.Require().NotNil(err, "update should have failed because channel is archived")
   231  
   232  	o1.DeleteAt = 0
   233  	o1.Id = "missing"
   234  	_, err = s.Store().Channel().Update(&o1)
   235  	s.Require().NotNil(err, "Update should have failed because of missing key")
   236  
   237  	o2.Name = o1.Name
   238  	_, err = s.Store().Channel().Update(&o2)
   239  	s.Require().NotNil(err, "update should have failed because of existing name")
   240  }
   241  
   242  func (s *ChannelStoreTestSuite) TestGetChannelUnread() {
   243  	teamId1 := model.NewId()
   244  	teamId2 := model.NewId()
   245  
   246  	uid := model.NewId()
   247  	m1 := &model.TeamMember{TeamId: teamId1, UserId: uid}
   248  	m2 := &model.TeamMember{TeamId: teamId2, UserId: uid}
   249  	_, nErr := s.Store().Team().SaveMember(m1, -1)
   250  	s.Require().Nil(nErr)
   251  	_, nErr = s.Store().Team().SaveMember(m2, -1)
   252  	s.Require().Nil(nErr)
   253  	notifyPropsModel := model.GetDefaultChannelNotifyProps()
   254  
   255  	// Setup Channel 1
   256  	c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Downtown", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
   257  	_, nErr = s.Store().Channel().Save(c1, -1)
   258  	s.Require().Nil(nErr)
   259  
   260  	cm1 := &model.ChannelMember{ChannelId: c1.Id, UserId: m1.UserId, NotifyProps: notifyPropsModel, MsgCount: 90}
   261  	_, err := s.Store().Channel().SaveMember(cm1)
   262  	s.Require().Nil(err)
   263  
   264  	// Setup Channel 2
   265  	c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Cultural", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
   266  	_, nErr = s.Store().Channel().Save(c2, -1)
   267  	s.Require().Nil(nErr)
   268  
   269  	cm2 := &model.ChannelMember{ChannelId: c2.Id, UserId: m2.UserId, NotifyProps: notifyPropsModel, MsgCount: 90, MentionCount: 5}
   270  	_, err = s.Store().Channel().SaveMember(cm2)
   271  	s.Require().Nil(err)
   272  
   273  	// Check for Channel 1
   274  	ch, nErr := s.Store().Channel().GetChannelUnread(c1.Id, uid)
   275  
   276  	s.Require().Nil(nErr, nErr)
   277  	s.Require().Equal(c1.Id, ch.ChannelId, "Wrong channel id")
   278  	s.Require().Equal(teamId1, ch.TeamId, "Wrong team id for channel 1")
   279  	s.Require().NotNil(ch.NotifyProps, "wrong props for channel 1")
   280  	s.Require().EqualValues(0, ch.MentionCount, "wrong MentionCount for channel 1")
   281  	s.Require().EqualValues(10, ch.MsgCount, "wrong MsgCount for channel 1")
   282  
   283  	// Check for Channel 2
   284  	ch2, nErr := s.Store().Channel().GetChannelUnread(c2.Id, uid)
   285  
   286  	s.Require().Nil(nErr, nErr)
   287  	s.Require().Equal(c2.Id, ch2.ChannelId, "Wrong channel id")
   288  	s.Require().Equal(teamId2, ch2.TeamId, "Wrong team id")
   289  	s.Require().EqualValues(5, ch2.MentionCount, "wrong MentionCount for channel 2")
   290  	s.Require().EqualValues(10, ch2.MsgCount, "wrong MsgCount for channel 2")
   291  }
   292  
   293  func (s *ChannelStoreTestSuite) TestStoreGet() {
   294  	o1 := model.Channel{}
   295  	o1.TeamId = model.NewId()
   296  	o1.DisplayName = "Name"
   297  	o1.Name = "zz" + model.NewId() + "b"
   298  	o1.Type = model.CHANNEL_OPEN
   299  	_, nErr := s.Store().Channel().Save(&o1, -1)
   300  	s.Require().Nil(nErr)
   301  
   302  	c1 := &model.Channel{}
   303  	c1, err := s.Store().Channel().Get(o1.Id, false)
   304  	s.Require().Nil(err, err)
   305  	s.Require().Equal(o1.ToJson(), c1.ToJson(), "invalid returned channel")
   306  
   307  	_, err = s.Store().Channel().Get("", false)
   308  	s.Require().NotNil(err, "missing id should have failed")
   309  
   310  	u1 := &model.User{}
   311  	u1.Email = MakeEmail()
   312  	u1.Nickname = model.NewId()
   313  	_, err = s.Store().User().Save(u1)
   314  	s.Require().Nil(err)
   315  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
   316  	s.Require().Nil(nErr)
   317  
   318  	u2 := model.User{}
   319  	u2.Email = MakeEmail()
   320  	u2.Nickname = model.NewId()
   321  	_, err = s.Store().User().Save(&u2)
   322  	s.Require().Nil(err)
   323  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
   324  	s.Require().Nil(nErr)
   325  
   326  	o2 := model.Channel{}
   327  	o2.TeamId = model.NewId()
   328  	o2.DisplayName = "Direct Name"
   329  	o2.Name = "zz" + model.NewId() + "b"
   330  	o2.Type = model.CHANNEL_DIRECT
   331  
   332  	m1 := model.ChannelMember{}
   333  	m1.ChannelId = o2.Id
   334  	m1.UserId = u1.Id
   335  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
   336  
   337  	m2 := model.ChannelMember{}
   338  	m2.ChannelId = o2.Id
   339  	m2.UserId = u2.Id
   340  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
   341  
   342  	_, nErr = s.Store().Channel().SaveDirectChannel(&o2, &m1, &m2)
   343  	s.Require().Nil(nErr)
   344  
   345  	c2, err := s.Store().Channel().Get(o2.Id, false)
   346  	s.Require().Nil(err, err)
   347  	s.Require().Equal(o2.ToJson(), c2.ToJson(), "invalid returned channel")
   348  
   349  	c4, err := s.Store().Channel().Get(o2.Id, true)
   350  	s.Require().Nil(err, err)
   351  	s.Require().Equal(o2.ToJson(), c4.ToJson(), "invalid returned channel")
   352  
   353  	channels, chanErr := s.Store().Channel().GetAll(o1.TeamId)
   354  	s.Require().Nil(chanErr, chanErr)
   355  	s.Require().Greater(len(channels), 0, "too little")
   356  
   357  	channelsTeam, err := s.Store().Channel().GetTeamChannels(o1.TeamId)
   358  	s.Require().Nil(err, err)
   359  	s.Require().Greater(len(*channelsTeam), 0, "too little")
   360  
   361  	// Manually truncate Channels table until testlib can handle cleanups
   362  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
   363  }
   364  
   365  func (s *ChannelStoreTestSuite) TestStoreGetChannelsByIds() {
   366  	o1 := model.Channel{}
   367  	o1.TeamId = model.NewId()
   368  	o1.DisplayName = "Name"
   369  	o1.Name = "aa" + model.NewId() + "b"
   370  	o1.Type = model.CHANNEL_OPEN
   371  	_, nErr := s.Store().Channel().Save(&o1, -1)
   372  	s.Require().Nil(nErr)
   373  
   374  	u1 := &model.User{}
   375  	u1.Email = MakeEmail()
   376  	u1.Nickname = model.NewId()
   377  	_, err := s.Store().User().Save(u1)
   378  	s.Require().Nil(err)
   379  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
   380  	s.Require().Nil(nErr)
   381  
   382  	u2 := model.User{}
   383  	u2.Email = MakeEmail()
   384  	u2.Nickname = model.NewId()
   385  	_, err = s.Store().User().Save(&u2)
   386  	s.Require().Nil(err)
   387  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
   388  	s.Require().Nil(nErr)
   389  
   390  	o2 := model.Channel{}
   391  	o2.TeamId = model.NewId()
   392  	o2.DisplayName = "Direct Name"
   393  	o2.Name = "bb" + model.NewId() + "b"
   394  	o2.Type = model.CHANNEL_DIRECT
   395  
   396  	o3 := model.Channel{}
   397  	o3.TeamId = model.NewId()
   398  	o3.DisplayName = "Deleted channel"
   399  	o3.Name = "cc" + model.NewId() + "b"
   400  	o3.Type = model.CHANNEL_OPEN
   401  	_, nErr = s.Store().Channel().Save(&o3, -1)
   402  	s.Require().Nil(nErr)
   403  	nErr = s.Store().Channel().Delete(o3.Id, 123)
   404  	s.Require().Nil(nErr)
   405  	o3.DeleteAt = 123
   406  	o3.UpdateAt = 123
   407  
   408  	m1 := model.ChannelMember{}
   409  	m1.ChannelId = o2.Id
   410  	m1.UserId = u1.Id
   411  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
   412  
   413  	m2 := model.ChannelMember{}
   414  	m2.ChannelId = o2.Id
   415  	m2.UserId = u2.Id
   416  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
   417  
   418  	_, nErr = s.Store().Channel().SaveDirectChannel(&o2, &m1, &m2)
   419  	s.Require().Nil(nErr)
   420  
   421  	s.T().Run("Get 2 existing channels", func(t *testing.T) {
   422  		r1, err := s.Store().Channel().GetChannelsByIds([]string{o1.Id, o2.Id}, false)
   423  		s.Require().Nil(err, err)
   424  		s.Require().Len(r1, 2, "invalid returned channels, exepected 2 and got "+strconv.Itoa(len(r1)))
   425  		s.Require().Equal(o1.ToJson(), r1[0].ToJson())
   426  		s.Require().Equal(o2.ToJson(), r1[1].ToJson())
   427  	})
   428  
   429  	s.T().Run("Get 1 existing and 1 not existing channel", func(t *testing.T) {
   430  		nonexistentId := "abcd1234"
   431  		r2, err := s.Store().Channel().GetChannelsByIds([]string{o1.Id, nonexistentId}, false)
   432  		s.Require().Nil(err, err)
   433  		s.Require().Len(r2, 1, "invalid returned channels, expected 1 and got "+strconv.Itoa(len(r2)))
   434  		s.Require().Equal(o1.ToJson(), r2[0].ToJson(), "invalid returned channel")
   435  	})
   436  
   437  	s.T().Run("Get 2 existing and 1 deleted channel", func(t *testing.T) {
   438  		r1, err := s.Store().Channel().GetChannelsByIds([]string{o1.Id, o2.Id, o3.Id}, true)
   439  		s.Require().Nil(err, err)
   440  		s.Require().Len(r1, 3, "invalid returned channels, exepected 3 and got "+strconv.Itoa(len(r1)))
   441  		s.Require().Equal(o1.ToJson(), r1[0].ToJson())
   442  		s.Require().Equal(o2.ToJson(), r1[1].ToJson())
   443  		s.Require().Equal(o3.ToJson(), r1[2].ToJson())
   444  	})
   445  }
   446  
   447  func (s *ChannelStoreTestSuite) TestStoreGetForPost() {
   448  
   449  	ch := &model.Channel{
   450  		TeamId:      model.NewId(),
   451  		DisplayName: "Name",
   452  		Name:        "zz" + model.NewId() + "b",
   453  		Type:        model.CHANNEL_OPEN,
   454  	}
   455  	o1, nErr := s.Store().Channel().Save(ch, -1)
   456  	s.Require().Nil(nErr)
   457  
   458  	p1, err := s.Store().Post().Save(&model.Post{
   459  		UserId:    model.NewId(),
   460  		ChannelId: o1.Id,
   461  		Message:   "test",
   462  	})
   463  	s.Require().Nil(err)
   464  
   465  	channel, chanErr := s.Store().Channel().GetForPost(p1.Id)
   466  	s.Require().Nil(chanErr, chanErr)
   467  	s.Require().Equal(o1.Id, channel.Id, "incorrect channel returned")
   468  }
   469  
   470  func (s *ChannelStoreTestSuite) TestStoreRestore() {
   471  	o1 := model.Channel{}
   472  	o1.TeamId = model.NewId()
   473  	o1.DisplayName = "Channel1"
   474  	o1.Name = "zz" + model.NewId() + "b"
   475  	o1.Type = model.CHANNEL_OPEN
   476  	_, nErr := s.Store().Channel().Save(&o1, -1)
   477  	s.Require().Nil(nErr)
   478  
   479  	err := s.Store().Channel().Delete(o1.Id, model.GetMillis())
   480  	s.Require().Nil(err, err)
   481  
   482  	c, _ := s.Store().Channel().Get(o1.Id, false)
   483  	s.Require().NotEqual(0, c.DeleteAt, "should have been deleted")
   484  
   485  	err = s.Store().Channel().Restore(o1.Id, model.GetMillis())
   486  	s.Require().Nil(err, err)
   487  
   488  	c, _ = s.Store().Channel().Get(o1.Id, false)
   489  	s.Require().EqualValues(0, c.DeleteAt, "should have been restored")
   490  }
   491  
   492  func (s *ChannelStoreTestSuite) TestStoreDelete() {
   493  	o1 := model.Channel{}
   494  	o1.TeamId = model.NewId()
   495  	o1.DisplayName = "Channel1"
   496  	o1.Name = "zz" + model.NewId() + "b"
   497  	o1.Type = model.CHANNEL_OPEN
   498  	_, nErr := s.Store().Channel().Save(&o1, -1)
   499  	s.Require().Nil(nErr)
   500  
   501  	o2 := model.Channel{}
   502  	o2.TeamId = o1.TeamId
   503  	o2.DisplayName = "Channel2"
   504  	o2.Name = "zz" + model.NewId() + "b"
   505  	o2.Type = model.CHANNEL_OPEN
   506  	_, nErr = s.Store().Channel().Save(&o2, -1)
   507  	s.Require().Nil(nErr)
   508  
   509  	o3 := model.Channel{}
   510  	o3.TeamId = o1.TeamId
   511  	o3.DisplayName = "Channel3"
   512  	o3.Name = "zz" + model.NewId() + "b"
   513  	o3.Type = model.CHANNEL_OPEN
   514  	_, nErr = s.Store().Channel().Save(&o3, -1)
   515  	s.Require().Nil(nErr)
   516  
   517  	o4 := model.Channel{}
   518  	o4.TeamId = o1.TeamId
   519  	o4.DisplayName = "Channel4"
   520  	o4.Name = "zz" + model.NewId() + "b"
   521  	o4.Type = model.CHANNEL_OPEN
   522  	_, nErr = s.Store().Channel().Save(&o4, -1)
   523  	s.Require().Nil(nErr)
   524  
   525  	m1 := model.ChannelMember{}
   526  	m1.ChannelId = o1.Id
   527  	m1.UserId = model.NewId()
   528  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
   529  	_, err := s.Store().Channel().SaveMember(&m1)
   530  	s.Require().Nil(err)
   531  
   532  	m2 := model.ChannelMember{}
   533  	m2.ChannelId = o2.Id
   534  	m2.UserId = m1.UserId
   535  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
   536  	_, err = s.Store().Channel().SaveMember(&m2)
   537  	s.Require().Nil(err)
   538  
   539  	nErr = s.Store().Channel().Delete(o1.Id, model.GetMillis())
   540  	s.Require().Nil(nErr, nErr)
   541  
   542  	c, _ := s.Store().Channel().Get(o1.Id, false)
   543  	s.Require().NotEqual(0, c.DeleteAt, "should have been deleted")
   544  
   545  	nErr = s.Store().Channel().Delete(o3.Id, model.GetMillis())
   546  	s.Require().Nil(nErr, nErr)
   547  
   548  	list, nErr := s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, false, 0)
   549  	s.Require().Nil(nErr)
   550  	s.Require().Len(*list, 1, "invalid number of channels")
   551  
   552  	list, nErr = s.Store().Channel().GetMoreChannels(o1.TeamId, m1.UserId, 0, 100)
   553  	s.Require().Nil(nErr)
   554  	s.Require().Len(*list, 1, "invalid number of channels")
   555  
   556  	cresult := s.Store().Channel().PermanentDelete(o2.Id)
   557  	s.Require().Nil(cresult)
   558  
   559  	list, nErr = s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, false, 0)
   560  	if s.Assert().NotNil(nErr) {
   561  		var nfErr *store.ErrNotFound
   562  		s.Require().True(errors.As(nErr, &nfErr))
   563  	} else {
   564  		s.Require().Equal(&model.ChannelList{}, list)
   565  	}
   566  
   567  	nErr = s.Store().Channel().PermanentDeleteByTeam(o1.TeamId)
   568  	s.Require().Nil(nErr, nErr)
   569  }
   570  
   571  func (s *ChannelStoreTestSuite) TestStoreGetByName() {
   572  	o1 := model.Channel{}
   573  	o1.TeamId = model.NewId()
   574  	o1.DisplayName = "Name"
   575  	o1.Name = "zz" + model.NewId() + "b"
   576  	o1.Type = model.CHANNEL_OPEN
   577  	_, nErr := s.Store().Channel().Save(&o1, -1)
   578  	s.Require().Nil(nErr)
   579  
   580  	result, err := s.Store().Channel().GetByName(o1.TeamId, o1.Name, true)
   581  	s.Require().Nil(err)
   582  	s.Require().Equal(o1.ToJson(), result.ToJson(), "invalid returned channel")
   583  
   584  	channelID := result.Id
   585  
   586  	result, err = s.Store().Channel().GetByName(o1.TeamId, "", true)
   587  	s.Require().NotNil(err, "Missing id should have failed")
   588  
   589  	result, err = s.Store().Channel().GetByName(o1.TeamId, o1.Name, false)
   590  	s.Require().Nil(err)
   591  	s.Require().Equal(o1.ToJson(), result.ToJson(), "invalid returned channel")
   592  
   593  	result, err = s.Store().Channel().GetByName(o1.TeamId, "", false)
   594  	s.Require().NotNil(err, "Missing id should have failed")
   595  
   596  	nErr = s.Store().Channel().Delete(channelID, model.GetMillis())
   597  	s.Require().Nil(nErr, "channel should have been deleted")
   598  
   599  	result, err = s.Store().Channel().GetByName(o1.TeamId, o1.Name, false)
   600  	s.Require().NotNil(err, "Deleted channel should not be returned by GetByName()")
   601  }
   602  
   603  func (s *ChannelStoreTestSuite) TestStoreGetByNames() {
   604  	o1 := model.Channel{
   605  		TeamId:      model.NewId(),
   606  		DisplayName: "Name",
   607  		Name:        "zz" + model.NewId() + "b",
   608  		Type:        model.CHANNEL_OPEN,
   609  	}
   610  	_, nErr := s.Store().Channel().Save(&o1, -1)
   611  	s.Require().Nil(nErr)
   612  
   613  	o2 := model.Channel{
   614  		TeamId:      o1.TeamId,
   615  		DisplayName: "Name",
   616  		Name:        "zz" + model.NewId() + "b",
   617  		Type:        model.CHANNEL_OPEN,
   618  	}
   619  	_, nErr = s.Store().Channel().Save(&o2, -1)
   620  	s.Require().Nil(nErr)
   621  
   622  	for index, tc := range []struct {
   623  		TeamId      string
   624  		Names       []string
   625  		ExpectedIds []string
   626  	}{
   627  		{o1.TeamId, []string{o1.Name}, []string{o1.Id}},
   628  		{o1.TeamId, []string{o1.Name, o2.Name}, []string{o1.Id, o2.Id}},
   629  		{o1.TeamId, nil, nil},
   630  		{o1.TeamId, []string{"foo"}, nil},
   631  		{o1.TeamId, []string{o1.Name, "foo", o2.Name, o2.Name}, []string{o1.Id, o2.Id}},
   632  		{"", []string{o1.Name, "foo", o2.Name, o2.Name}, []string{o1.Id, o2.Id}},
   633  		{"asd", []string{o1.Name, "foo", o2.Name, o2.Name}, nil},
   634  	} {
   635  		var channels []*model.Channel
   636  		channels, err := s.Store().Channel().GetByNames(tc.TeamId, tc.Names, true)
   637  		s.Require().Nil(err)
   638  		var ids []string
   639  		for _, channel := range channels {
   640  			ids = append(ids, channel.Id)
   641  		}
   642  		sort.Strings(ids)
   643  		sort.Strings(tc.ExpectedIds)
   644  		s.Assert().Equal(tc.ExpectedIds, ids, "tc %v", index)
   645  	}
   646  
   647  	err := s.Store().Channel().Delete(o1.Id, model.GetMillis())
   648  	s.Require().Nil(err, "channel should have been deleted")
   649  
   650  	err = s.Store().Channel().Delete(o2.Id, model.GetMillis())
   651  	s.Require().Nil(err, "channel should have been deleted")
   652  
   653  	channels, nErr := s.Store().Channel().GetByNames(o1.TeamId, []string{o1.Name}, false)
   654  	s.Require().Nil(nErr)
   655  	s.Assert().Empty(channels)
   656  }
   657  
   658  func (s *ChannelStoreTestSuite) TestStoreGetDeletedByName() {
   659  	o1 := &model.Channel{}
   660  	o1.TeamId = model.NewId()
   661  	o1.DisplayName = "Name"
   662  	o1.Name = "zz" + model.NewId() + "b"
   663  	o1.Type = model.CHANNEL_OPEN
   664  	_, nErr := s.Store().Channel().Save(o1, -1)
   665  	s.Require().Nil(nErr)
   666  
   667  	now := model.GetMillis()
   668  	err := s.Store().Channel().Delete(o1.Id, now)
   669  	s.Require().Nil(err, "channel should have been deleted")
   670  	o1.DeleteAt = now
   671  	o1.UpdateAt = now
   672  
   673  	r1, nErr := s.Store().Channel().GetDeletedByName(o1.TeamId, o1.Name)
   674  	s.Require().Nil(nErr)
   675  	s.Require().Equal(o1, r1)
   676  
   677  	_, nErr = s.Store().Channel().GetDeletedByName(o1.TeamId, "")
   678  	s.Require().NotNil(nErr, "missing id should have failed")
   679  }
   680  
   681  func (s *ChannelStoreTestSuite) TestStoreGetDeleted() {
   682  	o1 := model.Channel{}
   683  	o1.TeamId = model.NewId()
   684  	o1.DisplayName = "Channel1"
   685  	o1.Name = "zz" + model.NewId() + "b"
   686  	o1.Type = model.CHANNEL_OPEN
   687  
   688  	userId := model.NewId()
   689  
   690  	_, nErr := s.Store().Channel().Save(&o1, -1)
   691  	s.Require().Nil(nErr)
   692  
   693  	err := s.Store().Channel().Delete(o1.Id, model.GetMillis())
   694  	s.Require().Nil(err, "channel should have been deleted")
   695  
   696  	list, nErr := s.Store().Channel().GetDeleted(o1.TeamId, 0, 100, userId)
   697  	s.Require().Nil(nErr, nErr)
   698  	s.Require().Len(*list, 1, "wrong list")
   699  	s.Require().Equal(o1.Name, (*list)[0].Name, "missing channel")
   700  
   701  	o2 := model.Channel{}
   702  	o2.TeamId = o1.TeamId
   703  	o2.DisplayName = "Channel2"
   704  	o2.Name = "zz" + model.NewId() + "b"
   705  	o2.Type = model.CHANNEL_OPEN
   706  	_, nErr = s.Store().Channel().Save(&o2, -1)
   707  	s.Require().Nil(nErr)
   708  
   709  	list, nErr = s.Store().Channel().GetDeleted(o1.TeamId, 0, 100, userId)
   710  	s.Require().Nil(nErr, nErr)
   711  	s.Require().Len(*list, 1, "wrong list")
   712  
   713  	o3 := model.Channel{}
   714  	o3.TeamId = o1.TeamId
   715  	o3.DisplayName = "Channel3"
   716  	o3.Name = "zz" + model.NewId() + "b"
   717  	o3.Type = model.CHANNEL_OPEN
   718  
   719  	_, nErr = s.Store().Channel().Save(&o3, -1)
   720  	s.Require().Nil(nErr)
   721  
   722  	err = s.Store().Channel().Delete(o3.Id, model.GetMillis())
   723  	s.Require().Nil(err, "channel should have been deleted")
   724  
   725  	list, nErr = s.Store().Channel().GetDeleted(o1.TeamId, 0, 100, userId)
   726  	s.Require().Nil(nErr, nErr)
   727  	s.Require().Len(*list, 2, "wrong list length")
   728  
   729  	list, nErr = s.Store().Channel().GetDeleted(o1.TeamId, 0, 1, userId)
   730  	s.Require().Nil(nErr, nErr)
   731  	s.Require().Len(*list, 1, "wrong list length")
   732  
   733  	list, nErr = s.Store().Channel().GetDeleted(o1.TeamId, 1, 1, userId)
   734  	s.Require().Nil(nErr, nErr)
   735  	s.Require().Len(*list, 1, "wrong list length")
   736  
   737  }
   738  
   739  func (s *ChannelStoreTestSuite) TestMemberStore() {
   740  	c1 := &model.Channel{}
   741  	c1.TeamId = model.NewId()
   742  	c1.DisplayName = "NameName"
   743  	c1.Name = "zz" + model.NewId() + "b"
   744  	c1.Type = model.CHANNEL_OPEN
   745  	c1, nErr := s.Store().Channel().Save(c1, -1)
   746  	s.Require().Nil(nErr)
   747  
   748  	c1t1, _ := s.Store().Channel().Get(c1.Id, false)
   749  	s.Assert().EqualValues(0, c1t1.ExtraUpdateAt, "ExtraUpdateAt should be 0")
   750  
   751  	u1 := model.User{}
   752  	u1.Email = MakeEmail()
   753  	u1.Nickname = model.NewId()
   754  	_, err := s.Store().User().Save(&u1)
   755  	s.Require().Nil(err)
   756  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
   757  	s.Require().Nil(nErr)
   758  
   759  	u2 := model.User{}
   760  	u2.Email = MakeEmail()
   761  	u2.Nickname = model.NewId()
   762  	_, err = s.Store().User().Save(&u2)
   763  	s.Require().Nil(err)
   764  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
   765  	s.Require().Nil(nErr)
   766  
   767  	o1 := model.ChannelMember{}
   768  	o1.ChannelId = c1.Id
   769  	o1.UserId = u1.Id
   770  	o1.NotifyProps = model.GetDefaultChannelNotifyProps()
   771  	_, nErr = s.Store().Channel().SaveMember(&o1)
   772  	s.Require().Nil(nErr)
   773  
   774  	o2 := model.ChannelMember{}
   775  	o2.ChannelId = c1.Id
   776  	o2.UserId = u2.Id
   777  	o2.NotifyProps = model.GetDefaultChannelNotifyProps()
   778  	_, nErr = s.Store().Channel().SaveMember(&o2)
   779  	s.Require().Nil(nErr)
   780  
   781  	c1t2, _ := s.Store().Channel().Get(c1.Id, false)
   782  	s.Assert().EqualValues(0, c1t2.ExtraUpdateAt, "ExtraUpdateAt should be 0")
   783  
   784  	count, nErr := s.Store().Channel().GetMemberCount(o1.ChannelId, true)
   785  	s.Require().Nil(nErr)
   786  	s.Require().EqualValues(2, count, "should have saved 2 members")
   787  
   788  	count, nErr = s.Store().Channel().GetMemberCount(o1.ChannelId, true)
   789  	s.Require().Nil(nErr)
   790  	s.Require().EqualValues(2, count, "should have saved 2 members")
   791  	s.Require().EqualValues(
   792  		2,
   793  		s.Store().Channel().GetMemberCountFromCache(o1.ChannelId),
   794  		"should have saved 2 members")
   795  
   796  	s.Require().EqualValues(
   797  		0,
   798  		s.Store().Channel().GetMemberCountFromCache("junk"),
   799  		"should have saved 0 members")
   800  
   801  	count, nErr = s.Store().Channel().GetMemberCount(o1.ChannelId, false)
   802  	s.Require().Nil(nErr)
   803  	s.Require().EqualValues(2, count, "should have saved 2 members")
   804  
   805  	nErr = s.Store().Channel().RemoveMember(o2.ChannelId, o2.UserId)
   806  	s.Require().Nil(nErr)
   807  
   808  	count, nErr = s.Store().Channel().GetMemberCount(o1.ChannelId, false)
   809  	s.Require().Nil(nErr)
   810  	s.Require().EqualValues(1, count, "should have removed 1 member")
   811  
   812  	c1t3, _ := s.Store().Channel().Get(c1.Id, false)
   813  	s.Assert().EqualValues(0, c1t3.ExtraUpdateAt, "ExtraUpdateAt should be 0")
   814  
   815  	member, _ := s.Store().Channel().GetMember(context.Background(), o1.ChannelId, o1.UserId)
   816  	s.Require().Equal(o1.ChannelId, member.ChannelId, "should have go member")
   817  
   818  	_, nErr = s.Store().Channel().SaveMember(&o1)
   819  	s.Require().NotNil(nErr, "should have been a duplicate")
   820  
   821  	c1t4, _ := s.Store().Channel().Get(c1.Id, false)
   822  	s.Assert().EqualValues(0, c1t4.ExtraUpdateAt, "ExtraUpdateAt should be 0")
   823  }
   824  
   825  func (s *ChannelStoreTestSuite) TestSaveMember() {
   826  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
   827  	s.Require().Nil(err)
   828  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
   829  
   830  	s.T().Run("not valid channel member", func(t *testing.T) {
   831  		member := &model.ChannelMember{ChannelId: "wrong", UserId: u1.Id, NotifyProps: defaultNotifyProps}
   832  		_, nErr := s.Store().Channel().SaveMember(member)
   833  		s.Require().NotNil(nErr)
   834  		var appErr *model.AppError
   835  		s.Require().True(errors.As(nErr, &appErr))
   836  		s.Require().Equal("model.channel_member.is_valid.channel_id.app_error", appErr.Id)
   837  	})
   838  
   839  	s.T().Run("duplicated entries should fail", func(t *testing.T) {
   840  		channelID1 := model.NewId()
   841  		m1 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
   842  		_, nErr := s.Store().Channel().SaveMember(m1)
   843  		s.Require().Nil(nErr)
   844  		m2 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
   845  		_, nErr = s.Store().Channel().SaveMember(m2)
   846  		s.Require().NotNil(nErr)
   847  		s.Require().IsType(&store.ErrConflict{}, nErr)
   848  	})
   849  
   850  	s.T().Run("insert member correctly (in channel without channel scheme and team without scheme)", func(t *testing.T) {
   851  		team := &model.Team{
   852  			DisplayName: "Name",
   853  			Name:        "zz" + model.NewId(),
   854  			Email:       MakeEmail(),
   855  			Type:        model.TEAM_OPEN,
   856  		}
   857  
   858  		team, nErr := s.Store().Team().Save(team)
   859  		s.Require().Nil(nErr)
   860  
   861  		channel := &model.Channel{
   862  			DisplayName: "DisplayName",
   863  			Name:        "z-z-z" + model.NewId() + "b",
   864  			Type:        model.CHANNEL_OPEN,
   865  			TeamId:      team.Id,
   866  		}
   867  		channel, nErr = s.Store().Channel().Save(channel, -1)
   868  		s.Require().Nil(nErr)
   869  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
   870  
   871  		testCases := []struct {
   872  			Name                  string
   873  			SchemeGuest           bool
   874  			SchemeUser            bool
   875  			SchemeAdmin           bool
   876  			ExplicitRoles         string
   877  			ExpectedRoles         string
   878  			ExpectedExplicitRoles string
   879  			ExpectedSchemeGuest   bool
   880  			ExpectedSchemeUser    bool
   881  			ExpectedSchemeAdmin   bool
   882  		}{
   883  			{
   884  				Name:               "channel user implicit",
   885  				SchemeUser:         true,
   886  				ExpectedRoles:      "channel_user",
   887  				ExpectedSchemeUser: true,
   888  			},
   889  			{
   890  				Name:               "channel user explicit",
   891  				ExplicitRoles:      "channel_user",
   892  				ExpectedRoles:      "channel_user",
   893  				ExpectedSchemeUser: true,
   894  			},
   895  			{
   896  				Name:                "channel guest implicit",
   897  				SchemeGuest:         true,
   898  				ExpectedRoles:       "channel_guest",
   899  				ExpectedSchemeGuest: true,
   900  			},
   901  			{
   902  				Name:                "channel guest explicit",
   903  				ExplicitRoles:       "channel_guest",
   904  				ExpectedRoles:       "channel_guest",
   905  				ExpectedSchemeGuest: true,
   906  			},
   907  			{
   908  				Name:                "channel admin implicit",
   909  				SchemeUser:          true,
   910  				SchemeAdmin:         true,
   911  				ExpectedRoles:       "channel_user channel_admin",
   912  				ExpectedSchemeUser:  true,
   913  				ExpectedSchemeAdmin: true,
   914  			},
   915  			{
   916  				Name:                "channel admin explicit",
   917  				ExplicitRoles:       "channel_user channel_admin",
   918  				ExpectedRoles:       "channel_user channel_admin",
   919  				ExpectedSchemeUser:  true,
   920  				ExpectedSchemeAdmin: true,
   921  			},
   922  			{
   923  				Name:                  "channel user implicit and explicit custom role",
   924  				SchemeUser:            true,
   925  				ExplicitRoles:         "test",
   926  				ExpectedRoles:         "test channel_user",
   927  				ExpectedExplicitRoles: "test",
   928  				ExpectedSchemeUser:    true,
   929  			},
   930  			{
   931  				Name:                  "channel user explicit and explicit custom role",
   932  				ExplicitRoles:         "channel_user test",
   933  				ExpectedRoles:         "test channel_user",
   934  				ExpectedExplicitRoles: "test",
   935  				ExpectedSchemeUser:    true,
   936  			},
   937  			{
   938  				Name:                  "channel guest implicit and explicit custom role",
   939  				SchemeGuest:           true,
   940  				ExplicitRoles:         "test",
   941  				ExpectedRoles:         "test channel_guest",
   942  				ExpectedExplicitRoles: "test",
   943  				ExpectedSchemeGuest:   true,
   944  			},
   945  			{
   946  				Name:                  "channel guest explicit and explicit custom role",
   947  				ExplicitRoles:         "channel_guest test",
   948  				ExpectedRoles:         "test channel_guest",
   949  				ExpectedExplicitRoles: "test",
   950  				ExpectedSchemeGuest:   true,
   951  			},
   952  			{
   953  				Name:                  "channel admin implicit and explicit custom role",
   954  				SchemeUser:            true,
   955  				SchemeAdmin:           true,
   956  				ExplicitRoles:         "test",
   957  				ExpectedRoles:         "test channel_user channel_admin",
   958  				ExpectedExplicitRoles: "test",
   959  				ExpectedSchemeUser:    true,
   960  				ExpectedSchemeAdmin:   true,
   961  			},
   962  			{
   963  				Name:                  "channel admin explicit and explicit custom role",
   964  				ExplicitRoles:         "channel_user channel_admin test",
   965  				ExpectedRoles:         "test channel_user channel_admin",
   966  				ExpectedExplicitRoles: "test",
   967  				ExpectedSchemeUser:    true,
   968  				ExpectedSchemeAdmin:   true,
   969  			},
   970  			{
   971  				Name:                  "channel member with only explicit custom roles",
   972  				ExplicitRoles:         "test test2",
   973  				ExpectedRoles:         "test test2",
   974  				ExpectedExplicitRoles: "test test2",
   975  			},
   976  		}
   977  
   978  		for _, tc := range testCases {
   979  			s.T().Run(tc.Name, func(t *testing.T) {
   980  				member := &model.ChannelMember{
   981  					ChannelId:     channel.Id,
   982  					UserId:        u1.Id,
   983  					SchemeGuest:   tc.SchemeGuest,
   984  					SchemeUser:    tc.SchemeUser,
   985  					SchemeAdmin:   tc.SchemeAdmin,
   986  					ExplicitRoles: tc.ExplicitRoles,
   987  					NotifyProps:   defaultNotifyProps,
   988  				}
   989  				member, nErr = s.Store().Channel().SaveMember(member)
   990  				s.Require().Nil(nErr)
   991  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
   992  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
   993  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
   994  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
   995  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
   996  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
   997  			})
   998  		}
   999  	})
  1000  
  1001  	s.T().Run("insert member correctly (in channel without scheme and team with scheme)", func(t *testing.T) {
  1002  		ts := &model.Scheme{
  1003  			Name:        model.NewId(),
  1004  			DisplayName: model.NewId(),
  1005  			Description: model.NewId(),
  1006  			Scope:       model.SCHEME_SCOPE_TEAM,
  1007  		}
  1008  		ts, nErr := s.Store().Scheme().Save(ts)
  1009  		s.Require().Nil(nErr)
  1010  
  1011  		team := &model.Team{
  1012  			DisplayName: "Name",
  1013  			Name:        "zz" + model.NewId(),
  1014  			Email:       MakeEmail(),
  1015  			Type:        model.TEAM_OPEN,
  1016  			SchemeId:    &ts.Id,
  1017  		}
  1018  
  1019  		team, nErr = s.Store().Team().Save(team)
  1020  		s.Require().Nil(nErr)
  1021  
  1022  		channel := &model.Channel{
  1023  			DisplayName: "DisplayName",
  1024  			Name:        "z-z-z" + model.NewId() + "b",
  1025  			Type:        model.CHANNEL_OPEN,
  1026  			TeamId:      team.Id,
  1027  		}
  1028  		channel, nErr = s.Store().Channel().Save(channel, -1)
  1029  		s.Require().Nil(nErr)
  1030  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1031  
  1032  		testCases := []struct {
  1033  			Name                  string
  1034  			SchemeGuest           bool
  1035  			SchemeUser            bool
  1036  			SchemeAdmin           bool
  1037  			ExplicitRoles         string
  1038  			ExpectedRoles         string
  1039  			ExpectedExplicitRoles string
  1040  			ExpectedSchemeGuest   bool
  1041  			ExpectedSchemeUser    bool
  1042  			ExpectedSchemeAdmin   bool
  1043  		}{
  1044  			{
  1045  				Name:               "channel user implicit",
  1046  				SchemeUser:         true,
  1047  				ExpectedRoles:      ts.DefaultChannelUserRole,
  1048  				ExpectedSchemeUser: true,
  1049  			},
  1050  			{
  1051  				Name:               "channel user explicit",
  1052  				ExplicitRoles:      "channel_user",
  1053  				ExpectedRoles:      ts.DefaultChannelUserRole,
  1054  				ExpectedSchemeUser: true,
  1055  			},
  1056  			{
  1057  				Name:                "channel guest implicit",
  1058  				SchemeGuest:         true,
  1059  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  1060  				ExpectedSchemeGuest: true,
  1061  			},
  1062  			{
  1063  				Name:                "channel guest explicit",
  1064  				ExplicitRoles:       "channel_guest",
  1065  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  1066  				ExpectedSchemeGuest: true,
  1067  			},
  1068  			{
  1069  				Name:                "channel admin implicit",
  1070  				SchemeUser:          true,
  1071  				SchemeAdmin:         true,
  1072  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1073  				ExpectedSchemeUser:  true,
  1074  				ExpectedSchemeAdmin: true,
  1075  			},
  1076  			{
  1077  				Name:                "channel admin explicit",
  1078  				ExplicitRoles:       "channel_user channel_admin",
  1079  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1080  				ExpectedSchemeUser:  true,
  1081  				ExpectedSchemeAdmin: true,
  1082  			},
  1083  			{
  1084  				Name:                  "channel user implicit and explicit custom role",
  1085  				SchemeUser:            true,
  1086  				ExplicitRoles:         "test",
  1087  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  1088  				ExpectedExplicitRoles: "test",
  1089  				ExpectedSchemeUser:    true,
  1090  			},
  1091  			{
  1092  				Name:                  "channel user explicit and explicit custom role",
  1093  				ExplicitRoles:         "channel_user test",
  1094  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  1095  				ExpectedExplicitRoles: "test",
  1096  				ExpectedSchemeUser:    true,
  1097  			},
  1098  			{
  1099  				Name:                  "channel guest implicit and explicit custom role",
  1100  				SchemeGuest:           true,
  1101  				ExplicitRoles:         "test",
  1102  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  1103  				ExpectedExplicitRoles: "test",
  1104  				ExpectedSchemeGuest:   true,
  1105  			},
  1106  			{
  1107  				Name:                  "channel guest explicit and explicit custom role",
  1108  				ExplicitRoles:         "channel_guest test",
  1109  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  1110  				ExpectedExplicitRoles: "test",
  1111  				ExpectedSchemeGuest:   true,
  1112  			},
  1113  			{
  1114  				Name:                  "channel admin implicit and explicit custom role",
  1115  				SchemeUser:            true,
  1116  				SchemeAdmin:           true,
  1117  				ExplicitRoles:         "test",
  1118  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1119  				ExpectedExplicitRoles: "test",
  1120  				ExpectedSchemeUser:    true,
  1121  				ExpectedSchemeAdmin:   true,
  1122  			},
  1123  			{
  1124  				Name:                  "channel admin explicit and explicit custom role",
  1125  				ExplicitRoles:         "channel_user channel_admin test",
  1126  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1127  				ExpectedExplicitRoles: "test",
  1128  				ExpectedSchemeUser:    true,
  1129  				ExpectedSchemeAdmin:   true,
  1130  			},
  1131  			{
  1132  				Name:                  "channel member with only explicit custom roles",
  1133  				ExplicitRoles:         "test test2",
  1134  				ExpectedRoles:         "test test2",
  1135  				ExpectedExplicitRoles: "test test2",
  1136  			},
  1137  		}
  1138  
  1139  		for _, tc := range testCases {
  1140  			s.T().Run(tc.Name, func(t *testing.T) {
  1141  				member := &model.ChannelMember{
  1142  					ChannelId:     channel.Id,
  1143  					UserId:        u1.Id,
  1144  					SchemeGuest:   tc.SchemeGuest,
  1145  					SchemeUser:    tc.SchemeUser,
  1146  					SchemeAdmin:   tc.SchemeAdmin,
  1147  					ExplicitRoles: tc.ExplicitRoles,
  1148  					NotifyProps:   defaultNotifyProps,
  1149  				}
  1150  				member, nErr = s.Store().Channel().SaveMember(member)
  1151  				s.Require().Nil(nErr)
  1152  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  1153  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  1154  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  1155  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  1156  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  1157  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  1158  			})
  1159  		}
  1160  	})
  1161  
  1162  	s.T().Run("insert member correctly (in channel with channel scheme)", func(t *testing.T) {
  1163  		cs := &model.Scheme{
  1164  			Name:        model.NewId(),
  1165  			DisplayName: model.NewId(),
  1166  			Description: model.NewId(),
  1167  			Scope:       model.SCHEME_SCOPE_CHANNEL,
  1168  		}
  1169  		cs, nErr := s.Store().Scheme().Save(cs)
  1170  		s.Require().Nil(nErr)
  1171  
  1172  		team := &model.Team{
  1173  			DisplayName: "Name",
  1174  			Name:        "zz" + model.NewId(),
  1175  			Email:       MakeEmail(),
  1176  			Type:        model.TEAM_OPEN,
  1177  		}
  1178  
  1179  		team, nErr = s.Store().Team().Save(team)
  1180  		s.Require().Nil(nErr)
  1181  
  1182  		channel, nErr := s.Store().Channel().Save(&model.Channel{
  1183  			DisplayName: "DisplayName",
  1184  			Name:        "z-z-z" + model.NewId() + "b",
  1185  			Type:        model.CHANNEL_OPEN,
  1186  			TeamId:      team.Id,
  1187  			SchemeId:    &cs.Id,
  1188  		}, -1)
  1189  		s.Require().Nil(nErr)
  1190  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1191  
  1192  		testCases := []struct {
  1193  			Name                  string
  1194  			SchemeGuest           bool
  1195  			SchemeUser            bool
  1196  			SchemeAdmin           bool
  1197  			ExplicitRoles         string
  1198  			ExpectedRoles         string
  1199  			ExpectedExplicitRoles string
  1200  			ExpectedSchemeGuest   bool
  1201  			ExpectedSchemeUser    bool
  1202  			ExpectedSchemeAdmin   bool
  1203  		}{
  1204  			{
  1205  				Name:               "channel user implicit",
  1206  				SchemeUser:         true,
  1207  				ExpectedRoles:      cs.DefaultChannelUserRole,
  1208  				ExpectedSchemeUser: true,
  1209  			},
  1210  			{
  1211  				Name:               "channel user explicit",
  1212  				ExplicitRoles:      "channel_user",
  1213  				ExpectedRoles:      cs.DefaultChannelUserRole,
  1214  				ExpectedSchemeUser: true,
  1215  			},
  1216  			{
  1217  				Name:                "channel guest implicit",
  1218  				SchemeGuest:         true,
  1219  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  1220  				ExpectedSchemeGuest: true,
  1221  			},
  1222  			{
  1223  				Name:                "channel guest explicit",
  1224  				ExplicitRoles:       "channel_guest",
  1225  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  1226  				ExpectedSchemeGuest: true,
  1227  			},
  1228  			{
  1229  				Name:                "channel admin implicit",
  1230  				SchemeUser:          true,
  1231  				SchemeAdmin:         true,
  1232  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1233  				ExpectedSchemeUser:  true,
  1234  				ExpectedSchemeAdmin: true,
  1235  			},
  1236  			{
  1237  				Name:                "channel admin explicit",
  1238  				ExplicitRoles:       "channel_user channel_admin",
  1239  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1240  				ExpectedSchemeUser:  true,
  1241  				ExpectedSchemeAdmin: true,
  1242  			},
  1243  			{
  1244  				Name:                  "channel user implicit and explicit custom role",
  1245  				SchemeUser:            true,
  1246  				ExplicitRoles:         "test",
  1247  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  1248  				ExpectedExplicitRoles: "test",
  1249  				ExpectedSchemeUser:    true,
  1250  			},
  1251  			{
  1252  				Name:                  "channel user explicit and explicit custom role",
  1253  				ExplicitRoles:         "channel_user test",
  1254  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  1255  				ExpectedExplicitRoles: "test",
  1256  				ExpectedSchemeUser:    true,
  1257  			},
  1258  			{
  1259  				Name:                  "channel guest implicit and explicit custom role",
  1260  				SchemeGuest:           true,
  1261  				ExplicitRoles:         "test",
  1262  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  1263  				ExpectedExplicitRoles: "test",
  1264  				ExpectedSchemeGuest:   true,
  1265  			},
  1266  			{
  1267  				Name:                  "channel guest explicit and explicit custom role",
  1268  				ExplicitRoles:         "channel_guest test",
  1269  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  1270  				ExpectedExplicitRoles: "test",
  1271  				ExpectedSchemeGuest:   true,
  1272  			},
  1273  			{
  1274  				Name:                  "channel admin implicit and explicit custom role",
  1275  				SchemeUser:            true,
  1276  				SchemeAdmin:           true,
  1277  				ExplicitRoles:         "test",
  1278  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1279  				ExpectedExplicitRoles: "test",
  1280  				ExpectedSchemeUser:    true,
  1281  				ExpectedSchemeAdmin:   true,
  1282  			},
  1283  			{
  1284  				Name:                  "channel admin explicit and explicit custom role",
  1285  				ExplicitRoles:         "channel_user channel_admin test",
  1286  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1287  				ExpectedExplicitRoles: "test",
  1288  				ExpectedSchemeUser:    true,
  1289  				ExpectedSchemeAdmin:   true,
  1290  			},
  1291  			{
  1292  				Name:                  "channel member with only explicit custom roles",
  1293  				ExplicitRoles:         "test test2",
  1294  				ExpectedRoles:         "test test2",
  1295  				ExpectedExplicitRoles: "test test2",
  1296  			},
  1297  		}
  1298  
  1299  		for _, tc := range testCases {
  1300  			s.T().Run(tc.Name, func(t *testing.T) {
  1301  				member := &model.ChannelMember{
  1302  					ChannelId:     channel.Id,
  1303  					UserId:        u1.Id,
  1304  					SchemeGuest:   tc.SchemeGuest,
  1305  					SchemeUser:    tc.SchemeUser,
  1306  					SchemeAdmin:   tc.SchemeAdmin,
  1307  					ExplicitRoles: tc.ExplicitRoles,
  1308  					NotifyProps:   defaultNotifyProps,
  1309  				}
  1310  				member, nErr = s.Store().Channel().SaveMember(member)
  1311  				s.Require().Nil(nErr)
  1312  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  1313  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  1314  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  1315  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  1316  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  1317  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  1318  			})
  1319  		}
  1320  	})
  1321  }
  1322  
  1323  func (s *ChannelStoreTestSuite) TestSaveMultipleMembers() {
  1324  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  1325  	s.Require().Nil(err)
  1326  	u2, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  1327  	s.Require().Nil(err)
  1328  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
  1329  
  1330  	s.T().Run("any not valid channel member", func(t *testing.T) {
  1331  		m1 := &model.ChannelMember{ChannelId: "wrong", UserId: u1.Id, NotifyProps: defaultNotifyProps}
  1332  		m2 := &model.ChannelMember{ChannelId: model.NewId(), UserId: u2.Id, NotifyProps: defaultNotifyProps}
  1333  		_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2})
  1334  		s.Require().NotNil(nErr)
  1335  		var appErr *model.AppError
  1336  		s.Require().True(errors.As(nErr, &appErr))
  1337  		s.Require().Equal("model.channel_member.is_valid.channel_id.app_error", appErr.Id)
  1338  	})
  1339  
  1340  	s.T().Run("duplicated entries should fail", func(t *testing.T) {
  1341  		channelID1 := model.NewId()
  1342  		m1 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  1343  		m2 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  1344  		_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2})
  1345  		s.Require().NotNil(nErr)
  1346  		s.Require().IsType(&store.ErrConflict{}, nErr)
  1347  	})
  1348  
  1349  	s.T().Run("insert members correctly (in channel without channel scheme and team without scheme)", func(t *testing.T) {
  1350  		team := &model.Team{
  1351  			DisplayName: "Name",
  1352  			Name:        "zz" + model.NewId(),
  1353  			Email:       MakeEmail(),
  1354  			Type:        model.TEAM_OPEN,
  1355  		}
  1356  
  1357  		team, nErr := s.Store().Team().Save(team)
  1358  		s.Require().Nil(nErr)
  1359  
  1360  		channel := &model.Channel{
  1361  			DisplayName: "DisplayName",
  1362  			Name:        "z-z-z" + model.NewId() + "b",
  1363  			Type:        model.CHANNEL_OPEN,
  1364  			TeamId:      team.Id,
  1365  		}
  1366  		channel, nErr = s.Store().Channel().Save(channel, -1)
  1367  		s.Require().Nil(nErr)
  1368  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1369  
  1370  		testCases := []struct {
  1371  			Name                  string
  1372  			SchemeGuest           bool
  1373  			SchemeUser            bool
  1374  			SchemeAdmin           bool
  1375  			ExplicitRoles         string
  1376  			ExpectedRoles         string
  1377  			ExpectedExplicitRoles string
  1378  			ExpectedSchemeGuest   bool
  1379  			ExpectedSchemeUser    bool
  1380  			ExpectedSchemeAdmin   bool
  1381  		}{
  1382  			{
  1383  				Name:               "channel user implicit",
  1384  				SchemeUser:         true,
  1385  				ExpectedRoles:      "channel_user",
  1386  				ExpectedSchemeUser: true,
  1387  			},
  1388  			{
  1389  				Name:               "channel user explicit",
  1390  				ExplicitRoles:      "channel_user",
  1391  				ExpectedRoles:      "channel_user",
  1392  				ExpectedSchemeUser: true,
  1393  			},
  1394  			{
  1395  				Name:                "channel guest implicit",
  1396  				SchemeGuest:         true,
  1397  				ExpectedRoles:       "channel_guest",
  1398  				ExpectedSchemeGuest: true,
  1399  			},
  1400  			{
  1401  				Name:                "channel guest explicit",
  1402  				ExplicitRoles:       "channel_guest",
  1403  				ExpectedRoles:       "channel_guest",
  1404  				ExpectedSchemeGuest: true,
  1405  			},
  1406  			{
  1407  				Name:                "channel admin implicit",
  1408  				SchemeUser:          true,
  1409  				SchemeAdmin:         true,
  1410  				ExpectedRoles:       "channel_user channel_admin",
  1411  				ExpectedSchemeUser:  true,
  1412  				ExpectedSchemeAdmin: true,
  1413  			},
  1414  			{
  1415  				Name:                "channel admin explicit",
  1416  				ExplicitRoles:       "channel_user channel_admin",
  1417  				ExpectedRoles:       "channel_user channel_admin",
  1418  				ExpectedSchemeUser:  true,
  1419  				ExpectedSchemeAdmin: true,
  1420  			},
  1421  			{
  1422  				Name:                  "channel user implicit and explicit custom role",
  1423  				SchemeUser:            true,
  1424  				ExplicitRoles:         "test",
  1425  				ExpectedRoles:         "test channel_user",
  1426  				ExpectedExplicitRoles: "test",
  1427  				ExpectedSchemeUser:    true,
  1428  			},
  1429  			{
  1430  				Name:                  "channel user explicit and explicit custom role",
  1431  				ExplicitRoles:         "channel_user test",
  1432  				ExpectedRoles:         "test channel_user",
  1433  				ExpectedExplicitRoles: "test",
  1434  				ExpectedSchemeUser:    true,
  1435  			},
  1436  			{
  1437  				Name:                  "channel guest implicit and explicit custom role",
  1438  				SchemeGuest:           true,
  1439  				ExplicitRoles:         "test",
  1440  				ExpectedRoles:         "test channel_guest",
  1441  				ExpectedExplicitRoles: "test",
  1442  				ExpectedSchemeGuest:   true,
  1443  			},
  1444  			{
  1445  				Name:                  "channel guest explicit and explicit custom role",
  1446  				ExplicitRoles:         "channel_guest test",
  1447  				ExpectedRoles:         "test channel_guest",
  1448  				ExpectedExplicitRoles: "test",
  1449  				ExpectedSchemeGuest:   true,
  1450  			},
  1451  			{
  1452  				Name:                  "channel admin implicit and explicit custom role",
  1453  				SchemeUser:            true,
  1454  				SchemeAdmin:           true,
  1455  				ExplicitRoles:         "test",
  1456  				ExpectedRoles:         "test channel_user channel_admin",
  1457  				ExpectedExplicitRoles: "test",
  1458  				ExpectedSchemeUser:    true,
  1459  				ExpectedSchemeAdmin:   true,
  1460  			},
  1461  			{
  1462  				Name:                  "channel admin explicit and explicit custom role",
  1463  				ExplicitRoles:         "channel_user channel_admin test",
  1464  				ExpectedRoles:         "test channel_user channel_admin",
  1465  				ExpectedExplicitRoles: "test",
  1466  				ExpectedSchemeUser:    true,
  1467  				ExpectedSchemeAdmin:   true,
  1468  			},
  1469  			{
  1470  				Name:                  "channel member with only explicit custom roles",
  1471  				ExplicitRoles:         "test test2",
  1472  				ExpectedRoles:         "test test2",
  1473  				ExpectedExplicitRoles: "test test2",
  1474  			},
  1475  		}
  1476  
  1477  		for _, tc := range testCases {
  1478  			s.T().Run(tc.Name, func(t *testing.T) {
  1479  				member := &model.ChannelMember{
  1480  					ChannelId:     channel.Id,
  1481  					UserId:        u1.Id,
  1482  					SchemeGuest:   tc.SchemeGuest,
  1483  					SchemeUser:    tc.SchemeUser,
  1484  					SchemeAdmin:   tc.SchemeAdmin,
  1485  					ExplicitRoles: tc.ExplicitRoles,
  1486  					NotifyProps:   defaultNotifyProps,
  1487  				}
  1488  				otherMember := &model.ChannelMember{
  1489  					ChannelId:     channel.Id,
  1490  					UserId:        u2.Id,
  1491  					SchemeGuest:   tc.SchemeGuest,
  1492  					SchemeUser:    tc.SchemeUser,
  1493  					SchemeAdmin:   tc.SchemeAdmin,
  1494  					ExplicitRoles: tc.ExplicitRoles,
  1495  					NotifyProps:   defaultNotifyProps,
  1496  				}
  1497  				var members []*model.ChannelMember
  1498  				members, nErr = s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  1499  				s.Require().Nil(nErr)
  1500  				s.Require().Len(members, 2)
  1501  				member = members[0]
  1502  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  1503  				defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  1504  
  1505  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  1506  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  1507  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  1508  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  1509  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  1510  			})
  1511  		}
  1512  	})
  1513  
  1514  	s.T().Run("insert members correctly (in channel without scheme and team with scheme)", func(t *testing.T) {
  1515  		ts := &model.Scheme{
  1516  			Name:        model.NewId(),
  1517  			DisplayName: model.NewId(),
  1518  			Description: model.NewId(),
  1519  			Scope:       model.SCHEME_SCOPE_TEAM,
  1520  		}
  1521  		ts, nErr := s.Store().Scheme().Save(ts)
  1522  		s.Require().Nil(nErr)
  1523  
  1524  		team := &model.Team{
  1525  			DisplayName: "Name",
  1526  			Name:        "zz" + model.NewId(),
  1527  			Email:       MakeEmail(),
  1528  			Type:        model.TEAM_OPEN,
  1529  			SchemeId:    &ts.Id,
  1530  		}
  1531  
  1532  		team, nErr = s.Store().Team().Save(team)
  1533  		s.Require().Nil(nErr)
  1534  
  1535  		channel := &model.Channel{
  1536  			DisplayName: "DisplayName",
  1537  			Name:        "z-z-z" + model.NewId() + "b",
  1538  			Type:        model.CHANNEL_OPEN,
  1539  			TeamId:      team.Id,
  1540  		}
  1541  		channel, nErr = s.Store().Channel().Save(channel, -1)
  1542  		s.Require().Nil(nErr)
  1543  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1544  
  1545  		testCases := []struct {
  1546  			Name                  string
  1547  			SchemeGuest           bool
  1548  			SchemeUser            bool
  1549  			SchemeAdmin           bool
  1550  			ExplicitRoles         string
  1551  			ExpectedRoles         string
  1552  			ExpectedExplicitRoles string
  1553  			ExpectedSchemeGuest   bool
  1554  			ExpectedSchemeUser    bool
  1555  			ExpectedSchemeAdmin   bool
  1556  		}{
  1557  			{
  1558  				Name:               "channel user implicit",
  1559  				SchemeUser:         true,
  1560  				ExpectedRoles:      ts.DefaultChannelUserRole,
  1561  				ExpectedSchemeUser: true,
  1562  			},
  1563  			{
  1564  				Name:               "channel user explicit",
  1565  				ExplicitRoles:      "channel_user",
  1566  				ExpectedRoles:      ts.DefaultChannelUserRole,
  1567  				ExpectedSchemeUser: true,
  1568  			},
  1569  			{
  1570  				Name:                "channel guest implicit",
  1571  				SchemeGuest:         true,
  1572  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  1573  				ExpectedSchemeGuest: true,
  1574  			},
  1575  			{
  1576  				Name:                "channel guest explicit",
  1577  				ExplicitRoles:       "channel_guest",
  1578  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  1579  				ExpectedSchemeGuest: true,
  1580  			},
  1581  			{
  1582  				Name:                "channel admin implicit",
  1583  				SchemeUser:          true,
  1584  				SchemeAdmin:         true,
  1585  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1586  				ExpectedSchemeUser:  true,
  1587  				ExpectedSchemeAdmin: true,
  1588  			},
  1589  			{
  1590  				Name:                "channel admin explicit",
  1591  				ExplicitRoles:       "channel_user channel_admin",
  1592  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1593  				ExpectedSchemeUser:  true,
  1594  				ExpectedSchemeAdmin: true,
  1595  			},
  1596  			{
  1597  				Name:                  "channel user implicit and explicit custom role",
  1598  				SchemeUser:            true,
  1599  				ExplicitRoles:         "test",
  1600  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  1601  				ExpectedExplicitRoles: "test",
  1602  				ExpectedSchemeUser:    true,
  1603  			},
  1604  			{
  1605  				Name:                  "channel user explicit and explicit custom role",
  1606  				ExplicitRoles:         "channel_user test",
  1607  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  1608  				ExpectedExplicitRoles: "test",
  1609  				ExpectedSchemeUser:    true,
  1610  			},
  1611  			{
  1612  				Name:                  "channel guest implicit and explicit custom role",
  1613  				SchemeGuest:           true,
  1614  				ExplicitRoles:         "test",
  1615  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  1616  				ExpectedExplicitRoles: "test",
  1617  				ExpectedSchemeGuest:   true,
  1618  			},
  1619  			{
  1620  				Name:                  "channel guest explicit and explicit custom role",
  1621  				ExplicitRoles:         "channel_guest test",
  1622  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  1623  				ExpectedExplicitRoles: "test",
  1624  				ExpectedSchemeGuest:   true,
  1625  			},
  1626  			{
  1627  				Name:                  "channel admin implicit and explicit custom role",
  1628  				SchemeUser:            true,
  1629  				SchemeAdmin:           true,
  1630  				ExplicitRoles:         "test",
  1631  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1632  				ExpectedExplicitRoles: "test",
  1633  				ExpectedSchemeUser:    true,
  1634  				ExpectedSchemeAdmin:   true,
  1635  			},
  1636  			{
  1637  				Name:                  "channel admin explicit and explicit custom role",
  1638  				ExplicitRoles:         "channel_user channel_admin test",
  1639  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  1640  				ExpectedExplicitRoles: "test",
  1641  				ExpectedSchemeUser:    true,
  1642  				ExpectedSchemeAdmin:   true,
  1643  			},
  1644  			{
  1645  				Name:                  "channel member with only explicit custom roles",
  1646  				ExplicitRoles:         "test test2",
  1647  				ExpectedRoles:         "test test2",
  1648  				ExpectedExplicitRoles: "test test2",
  1649  			},
  1650  		}
  1651  
  1652  		for _, tc := range testCases {
  1653  			s.T().Run(tc.Name, func(t *testing.T) {
  1654  				member := &model.ChannelMember{
  1655  					ChannelId:     channel.Id,
  1656  					UserId:        u1.Id,
  1657  					SchemeGuest:   tc.SchemeGuest,
  1658  					SchemeUser:    tc.SchemeUser,
  1659  					SchemeAdmin:   tc.SchemeAdmin,
  1660  					ExplicitRoles: tc.ExplicitRoles,
  1661  					NotifyProps:   defaultNotifyProps,
  1662  				}
  1663  				otherMember := &model.ChannelMember{
  1664  					ChannelId:     channel.Id,
  1665  					UserId:        u2.Id,
  1666  					SchemeGuest:   tc.SchemeGuest,
  1667  					SchemeUser:    tc.SchemeUser,
  1668  					SchemeAdmin:   tc.SchemeAdmin,
  1669  					ExplicitRoles: tc.ExplicitRoles,
  1670  					NotifyProps:   defaultNotifyProps,
  1671  				}
  1672  				var members []*model.ChannelMember
  1673  				members, nErr = s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  1674  				s.Require().Nil(nErr)
  1675  				s.Require().Len(members, 2)
  1676  				member = members[0]
  1677  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  1678  				defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  1679  
  1680  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  1681  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  1682  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  1683  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  1684  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  1685  			})
  1686  		}
  1687  	})
  1688  
  1689  	s.T().Run("insert members correctly (in channel with channel scheme)", func(t *testing.T) {
  1690  		cs := &model.Scheme{
  1691  			Name:        model.NewId(),
  1692  			DisplayName: model.NewId(),
  1693  			Description: model.NewId(),
  1694  			Scope:       model.SCHEME_SCOPE_CHANNEL,
  1695  		}
  1696  		cs, nErr := s.Store().Scheme().Save(cs)
  1697  		s.Require().Nil(nErr)
  1698  
  1699  		team := &model.Team{
  1700  			DisplayName: "Name",
  1701  			Name:        "zz" + model.NewId(),
  1702  			Email:       MakeEmail(),
  1703  			Type:        model.TEAM_OPEN,
  1704  		}
  1705  
  1706  		team, nErr = s.Store().Team().Save(team)
  1707  		s.Require().Nil(nErr)
  1708  
  1709  		channel, nErr := s.Store().Channel().Save(&model.Channel{
  1710  			DisplayName: "DisplayName",
  1711  			Name:        "z-z-z" + model.NewId() + "b",
  1712  			Type:        model.CHANNEL_OPEN,
  1713  			TeamId:      team.Id,
  1714  			SchemeId:    &cs.Id,
  1715  		}, -1)
  1716  		s.Require().Nil(nErr)
  1717  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1718  
  1719  		testCases := []struct {
  1720  			Name                  string
  1721  			SchemeGuest           bool
  1722  			SchemeUser            bool
  1723  			SchemeAdmin           bool
  1724  			ExplicitRoles         string
  1725  			ExpectedRoles         string
  1726  			ExpectedExplicitRoles string
  1727  			ExpectedSchemeGuest   bool
  1728  			ExpectedSchemeUser    bool
  1729  			ExpectedSchemeAdmin   bool
  1730  		}{
  1731  			{
  1732  				Name:               "channel user implicit",
  1733  				SchemeUser:         true,
  1734  				ExpectedRoles:      cs.DefaultChannelUserRole,
  1735  				ExpectedSchemeUser: true,
  1736  			},
  1737  			{
  1738  				Name:               "channel user explicit",
  1739  				ExplicitRoles:      "channel_user",
  1740  				ExpectedRoles:      cs.DefaultChannelUserRole,
  1741  				ExpectedSchemeUser: true,
  1742  			},
  1743  			{
  1744  				Name:                "channel guest implicit",
  1745  				SchemeGuest:         true,
  1746  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  1747  				ExpectedSchemeGuest: true,
  1748  			},
  1749  			{
  1750  				Name:                "channel guest explicit",
  1751  				ExplicitRoles:       "channel_guest",
  1752  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  1753  				ExpectedSchemeGuest: true,
  1754  			},
  1755  			{
  1756  				Name:                "channel admin implicit",
  1757  				SchemeUser:          true,
  1758  				SchemeAdmin:         true,
  1759  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1760  				ExpectedSchemeUser:  true,
  1761  				ExpectedSchemeAdmin: true,
  1762  			},
  1763  			{
  1764  				Name:                "channel admin explicit",
  1765  				ExplicitRoles:       "channel_user channel_admin",
  1766  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1767  				ExpectedSchemeUser:  true,
  1768  				ExpectedSchemeAdmin: true,
  1769  			},
  1770  			{
  1771  				Name:                  "channel user implicit and explicit custom role",
  1772  				SchemeUser:            true,
  1773  				ExplicitRoles:         "test",
  1774  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  1775  				ExpectedExplicitRoles: "test",
  1776  				ExpectedSchemeUser:    true,
  1777  			},
  1778  			{
  1779  				Name:                  "channel user explicit and explicit custom role",
  1780  				ExplicitRoles:         "channel_user test",
  1781  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  1782  				ExpectedExplicitRoles: "test",
  1783  				ExpectedSchemeUser:    true,
  1784  			},
  1785  			{
  1786  				Name:                  "channel guest implicit and explicit custom role",
  1787  				SchemeGuest:           true,
  1788  				ExplicitRoles:         "test",
  1789  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  1790  				ExpectedExplicitRoles: "test",
  1791  				ExpectedSchemeGuest:   true,
  1792  			},
  1793  			{
  1794  				Name:                  "channel guest explicit and explicit custom role",
  1795  				ExplicitRoles:         "channel_guest test",
  1796  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  1797  				ExpectedExplicitRoles: "test",
  1798  				ExpectedSchemeGuest:   true,
  1799  			},
  1800  			{
  1801  				Name:                  "channel admin implicit and explicit custom role",
  1802  				SchemeUser:            true,
  1803  				SchemeAdmin:           true,
  1804  				ExplicitRoles:         "test",
  1805  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1806  				ExpectedExplicitRoles: "test",
  1807  				ExpectedSchemeUser:    true,
  1808  				ExpectedSchemeAdmin:   true,
  1809  			},
  1810  			{
  1811  				Name:                  "channel admin explicit and explicit custom role",
  1812  				ExplicitRoles:         "channel_user channel_admin test",
  1813  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  1814  				ExpectedExplicitRoles: "test",
  1815  				ExpectedSchemeUser:    true,
  1816  				ExpectedSchemeAdmin:   true,
  1817  			},
  1818  			{
  1819  				Name:                  "channel member with only explicit custom roles",
  1820  				ExplicitRoles:         "test test2",
  1821  				ExpectedRoles:         "test test2",
  1822  				ExpectedExplicitRoles: "test test2",
  1823  			},
  1824  		}
  1825  
  1826  		for _, tc := range testCases {
  1827  			s.T().Run(tc.Name, func(t *testing.T) {
  1828  				member := &model.ChannelMember{
  1829  					ChannelId:     channel.Id,
  1830  					UserId:        u1.Id,
  1831  					SchemeGuest:   tc.SchemeGuest,
  1832  					SchemeUser:    tc.SchemeUser,
  1833  					SchemeAdmin:   tc.SchemeAdmin,
  1834  					ExplicitRoles: tc.ExplicitRoles,
  1835  					NotifyProps:   defaultNotifyProps,
  1836  				}
  1837  				otherMember := &model.ChannelMember{
  1838  					ChannelId:     channel.Id,
  1839  					UserId:        u2.Id,
  1840  					SchemeGuest:   tc.SchemeGuest,
  1841  					SchemeUser:    tc.SchemeUser,
  1842  					SchemeAdmin:   tc.SchemeAdmin,
  1843  					ExplicitRoles: tc.ExplicitRoles,
  1844  					NotifyProps:   defaultNotifyProps,
  1845  				}
  1846  				members, err := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  1847  				s.Require().Nil(err)
  1848  				s.Require().Len(members, 2)
  1849  				member = members[0]
  1850  				defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  1851  				defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  1852  
  1853  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  1854  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  1855  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  1856  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  1857  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  1858  			})
  1859  		}
  1860  	})
  1861  }
  1862  
  1863  func (s *ChannelStoreTestSuite) TestUpdateMember() {
  1864  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  1865  	s.Require().Nil(err)
  1866  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
  1867  
  1868  	s.T().Run("not valid channel member", func(t *testing.T) {
  1869  		member := &model.ChannelMember{ChannelId: "wrong", UserId: u1.Id, NotifyProps: defaultNotifyProps}
  1870  		_, nErr := s.Store().Channel().UpdateMember(member)
  1871  		s.Require().NotNil(nErr)
  1872  		var appErr *model.AppError
  1873  		s.Require().True(errors.As(nErr, &appErr))
  1874  		s.Require().Equal("model.channel_member.is_valid.channel_id.app_error", appErr.Id)
  1875  	})
  1876  
  1877  	s.T().Run("insert member correctly (in channel without channel scheme and team without scheme)", func(t *testing.T) {
  1878  		team := &model.Team{
  1879  			DisplayName: "Name",
  1880  			Name:        "zz" + model.NewId(),
  1881  			Email:       MakeEmail(),
  1882  			Type:        model.TEAM_OPEN,
  1883  		}
  1884  
  1885  		team, nErr := s.Store().Team().Save(team)
  1886  		s.Require().Nil(nErr)
  1887  
  1888  		channel := &model.Channel{
  1889  			DisplayName: "DisplayName",
  1890  			Name:        "z-z-z" + model.NewId() + "b",
  1891  			Type:        model.CHANNEL_OPEN,
  1892  			TeamId:      team.Id,
  1893  		}
  1894  		channel, nErr = s.Store().Channel().Save(channel, -1)
  1895  		s.Require().Nil(nErr)
  1896  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  1897  
  1898  		member := &model.ChannelMember{
  1899  			ChannelId:   channel.Id,
  1900  			UserId:      u1.Id,
  1901  			NotifyProps: defaultNotifyProps,
  1902  		}
  1903  		member, nErr = s.Store().Channel().SaveMember(member)
  1904  		s.Require().Nil(nErr)
  1905  
  1906  		testCases := []struct {
  1907  			Name                  string
  1908  			SchemeGuest           bool
  1909  			SchemeUser            bool
  1910  			SchemeAdmin           bool
  1911  			ExplicitRoles         string
  1912  			ExpectedRoles         string
  1913  			ExpectedExplicitRoles string
  1914  			ExpectedSchemeGuest   bool
  1915  			ExpectedSchemeUser    bool
  1916  			ExpectedSchemeAdmin   bool
  1917  		}{
  1918  			{
  1919  				Name:               "channel user implicit",
  1920  				SchemeUser:         true,
  1921  				ExpectedRoles:      "channel_user",
  1922  				ExpectedSchemeUser: true,
  1923  			},
  1924  			{
  1925  				Name:               "channel user explicit",
  1926  				ExplicitRoles:      "channel_user",
  1927  				ExpectedRoles:      "channel_user",
  1928  				ExpectedSchemeUser: true,
  1929  			},
  1930  			{
  1931  				Name:                "channel guest implicit",
  1932  				SchemeGuest:         true,
  1933  				ExpectedRoles:       "channel_guest",
  1934  				ExpectedSchemeGuest: true,
  1935  			},
  1936  			{
  1937  				Name:                "channel guest explicit",
  1938  				ExplicitRoles:       "channel_guest",
  1939  				ExpectedRoles:       "channel_guest",
  1940  				ExpectedSchemeGuest: true,
  1941  			},
  1942  			{
  1943  				Name:                "channel admin implicit",
  1944  				SchemeUser:          true,
  1945  				SchemeAdmin:         true,
  1946  				ExpectedRoles:       "channel_user channel_admin",
  1947  				ExpectedSchemeUser:  true,
  1948  				ExpectedSchemeAdmin: true,
  1949  			},
  1950  			{
  1951  				Name:                "channel admin explicit",
  1952  				ExplicitRoles:       "channel_user channel_admin",
  1953  				ExpectedRoles:       "channel_user channel_admin",
  1954  				ExpectedSchemeUser:  true,
  1955  				ExpectedSchemeAdmin: true,
  1956  			},
  1957  			{
  1958  				Name:                  "channel user implicit and explicit custom role",
  1959  				SchemeUser:            true,
  1960  				ExplicitRoles:         "test",
  1961  				ExpectedRoles:         "test channel_user",
  1962  				ExpectedExplicitRoles: "test",
  1963  				ExpectedSchemeUser:    true,
  1964  			},
  1965  			{
  1966  				Name:                  "channel user explicit and explicit custom role",
  1967  				ExplicitRoles:         "channel_user test",
  1968  				ExpectedRoles:         "test channel_user",
  1969  				ExpectedExplicitRoles: "test",
  1970  				ExpectedSchemeUser:    true,
  1971  			},
  1972  			{
  1973  				Name:                  "channel guest implicit and explicit custom role",
  1974  				SchemeGuest:           true,
  1975  				ExplicitRoles:         "test",
  1976  				ExpectedRoles:         "test channel_guest",
  1977  				ExpectedExplicitRoles: "test",
  1978  				ExpectedSchemeGuest:   true,
  1979  			},
  1980  			{
  1981  				Name:                  "channel guest explicit and explicit custom role",
  1982  				ExplicitRoles:         "channel_guest test",
  1983  				ExpectedRoles:         "test channel_guest",
  1984  				ExpectedExplicitRoles: "test",
  1985  				ExpectedSchemeGuest:   true,
  1986  			},
  1987  			{
  1988  				Name:                  "channel admin implicit and explicit custom role",
  1989  				SchemeUser:            true,
  1990  				SchemeAdmin:           true,
  1991  				ExplicitRoles:         "test",
  1992  				ExpectedRoles:         "test channel_user channel_admin",
  1993  				ExpectedExplicitRoles: "test",
  1994  				ExpectedSchemeUser:    true,
  1995  				ExpectedSchemeAdmin:   true,
  1996  			},
  1997  			{
  1998  				Name:                  "channel admin explicit and explicit custom role",
  1999  				ExplicitRoles:         "channel_user channel_admin test",
  2000  				ExpectedRoles:         "test channel_user channel_admin",
  2001  				ExpectedExplicitRoles: "test",
  2002  				ExpectedSchemeUser:    true,
  2003  				ExpectedSchemeAdmin:   true,
  2004  			},
  2005  			{
  2006  				Name:                  "channel member with only explicit custom roles",
  2007  				ExplicitRoles:         "test test2",
  2008  				ExpectedRoles:         "test test2",
  2009  				ExpectedExplicitRoles: "test test2",
  2010  			},
  2011  		}
  2012  
  2013  		for _, tc := range testCases {
  2014  			s.T().Run(tc.Name, func(t *testing.T) {
  2015  				member.SchemeGuest = tc.SchemeGuest
  2016  				member.SchemeUser = tc.SchemeUser
  2017  				member.SchemeAdmin = tc.SchemeAdmin
  2018  				member.ExplicitRoles = tc.ExplicitRoles
  2019  				member, nErr = s.Store().Channel().UpdateMember(member)
  2020  				s.Require().Nil(nErr)
  2021  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2022  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2023  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2024  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2025  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2026  			})
  2027  		}
  2028  	})
  2029  
  2030  	s.T().Run("insert member correctly (in channel without scheme and team with scheme)", func(t *testing.T) {
  2031  		ts := &model.Scheme{
  2032  			Name:        model.NewId(),
  2033  			DisplayName: model.NewId(),
  2034  			Description: model.NewId(),
  2035  			Scope:       model.SCHEME_SCOPE_TEAM,
  2036  		}
  2037  		ts, nErr := s.Store().Scheme().Save(ts)
  2038  		s.Require().Nil(nErr)
  2039  
  2040  		team := &model.Team{
  2041  			DisplayName: "Name",
  2042  			Name:        "zz" + model.NewId(),
  2043  			Email:       MakeEmail(),
  2044  			Type:        model.TEAM_OPEN,
  2045  			SchemeId:    &ts.Id,
  2046  		}
  2047  
  2048  		team, nErr = s.Store().Team().Save(team)
  2049  		s.Require().Nil(nErr)
  2050  
  2051  		channel := &model.Channel{
  2052  			DisplayName: "DisplayName",
  2053  			Name:        "z-z-z" + model.NewId() + "b",
  2054  			Type:        model.CHANNEL_OPEN,
  2055  			TeamId:      team.Id,
  2056  		}
  2057  		channel, nErr = s.Store().Channel().Save(channel, -1)
  2058  		s.Require().Nil(nErr)
  2059  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  2060  
  2061  		member := &model.ChannelMember{
  2062  			ChannelId:   channel.Id,
  2063  			UserId:      u1.Id,
  2064  			NotifyProps: defaultNotifyProps,
  2065  		}
  2066  		member, nErr = s.Store().Channel().SaveMember(member)
  2067  		s.Require().Nil(nErr)
  2068  
  2069  		testCases := []struct {
  2070  			Name                  string
  2071  			SchemeGuest           bool
  2072  			SchemeUser            bool
  2073  			SchemeAdmin           bool
  2074  			ExplicitRoles         string
  2075  			ExpectedRoles         string
  2076  			ExpectedExplicitRoles string
  2077  			ExpectedSchemeGuest   bool
  2078  			ExpectedSchemeUser    bool
  2079  			ExpectedSchemeAdmin   bool
  2080  		}{
  2081  			{
  2082  				Name:               "channel user implicit",
  2083  				SchemeUser:         true,
  2084  				ExpectedRoles:      ts.DefaultChannelUserRole,
  2085  				ExpectedSchemeUser: true,
  2086  			},
  2087  			{
  2088  				Name:               "channel user explicit",
  2089  				ExplicitRoles:      "channel_user",
  2090  				ExpectedRoles:      ts.DefaultChannelUserRole,
  2091  				ExpectedSchemeUser: true,
  2092  			},
  2093  			{
  2094  				Name:                "channel guest implicit",
  2095  				SchemeGuest:         true,
  2096  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  2097  				ExpectedSchemeGuest: true,
  2098  			},
  2099  			{
  2100  				Name:                "channel guest explicit",
  2101  				ExplicitRoles:       "channel_guest",
  2102  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  2103  				ExpectedSchemeGuest: true,
  2104  			},
  2105  			{
  2106  				Name:                "channel admin implicit",
  2107  				SchemeUser:          true,
  2108  				SchemeAdmin:         true,
  2109  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2110  				ExpectedSchemeUser:  true,
  2111  				ExpectedSchemeAdmin: true,
  2112  			},
  2113  			{
  2114  				Name:                "channel admin explicit",
  2115  				ExplicitRoles:       "channel_user channel_admin",
  2116  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2117  				ExpectedSchemeUser:  true,
  2118  				ExpectedSchemeAdmin: true,
  2119  			},
  2120  			{
  2121  				Name:                  "channel user implicit and explicit custom role",
  2122  				SchemeUser:            true,
  2123  				ExplicitRoles:         "test",
  2124  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  2125  				ExpectedExplicitRoles: "test",
  2126  				ExpectedSchemeUser:    true,
  2127  			},
  2128  			{
  2129  				Name:                  "channel user explicit and explicit custom role",
  2130  				ExplicitRoles:         "channel_user test",
  2131  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  2132  				ExpectedExplicitRoles: "test",
  2133  				ExpectedSchemeUser:    true,
  2134  			},
  2135  			{
  2136  				Name:                  "channel guest implicit and explicit custom role",
  2137  				SchemeGuest:           true,
  2138  				ExplicitRoles:         "test",
  2139  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  2140  				ExpectedExplicitRoles: "test",
  2141  				ExpectedSchemeGuest:   true,
  2142  			},
  2143  			{
  2144  				Name:                  "channel guest explicit and explicit custom role",
  2145  				ExplicitRoles:         "channel_guest test",
  2146  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  2147  				ExpectedExplicitRoles: "test",
  2148  				ExpectedSchemeGuest:   true,
  2149  			},
  2150  			{
  2151  				Name:                  "channel admin implicit and explicit custom role",
  2152  				SchemeUser:            true,
  2153  				SchemeAdmin:           true,
  2154  				ExplicitRoles:         "test",
  2155  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2156  				ExpectedExplicitRoles: "test",
  2157  				ExpectedSchemeUser:    true,
  2158  				ExpectedSchemeAdmin:   true,
  2159  			},
  2160  			{
  2161  				Name:                  "channel admin explicit and explicit custom role",
  2162  				ExplicitRoles:         "channel_user channel_admin test",
  2163  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2164  				ExpectedExplicitRoles: "test",
  2165  				ExpectedSchemeUser:    true,
  2166  				ExpectedSchemeAdmin:   true,
  2167  			},
  2168  			{
  2169  				Name:                  "channel member with only explicit custom roles",
  2170  				ExplicitRoles:         "test test2",
  2171  				ExpectedRoles:         "test test2",
  2172  				ExpectedExplicitRoles: "test test2",
  2173  			},
  2174  		}
  2175  
  2176  		for _, tc := range testCases {
  2177  			s.T().Run(tc.Name, func(t *testing.T) {
  2178  				member.SchemeGuest = tc.SchemeGuest
  2179  				member.SchemeUser = tc.SchemeUser
  2180  				member.SchemeAdmin = tc.SchemeAdmin
  2181  				member.ExplicitRoles = tc.ExplicitRoles
  2182  				member, nErr = s.Store().Channel().UpdateMember(member)
  2183  				s.Require().Nil(nErr)
  2184  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2185  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2186  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2187  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2188  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2189  			})
  2190  		}
  2191  	})
  2192  
  2193  	s.T().Run("insert member correctly (in channel with channel scheme)", func(t *testing.T) {
  2194  		cs := &model.Scheme{
  2195  			Name:        model.NewId(),
  2196  			DisplayName: model.NewId(),
  2197  			Description: model.NewId(),
  2198  			Scope:       model.SCHEME_SCOPE_CHANNEL,
  2199  		}
  2200  		cs, nErr := s.Store().Scheme().Save(cs)
  2201  		s.Require().Nil(nErr)
  2202  
  2203  		team := &model.Team{
  2204  			DisplayName: "Name",
  2205  			Name:        "zz" + model.NewId(),
  2206  			Email:       MakeEmail(),
  2207  			Type:        model.TEAM_OPEN,
  2208  		}
  2209  
  2210  		team, nErr = s.Store().Team().Save(team)
  2211  		s.Require().Nil(nErr)
  2212  
  2213  		channel, nErr := s.Store().Channel().Save(&model.Channel{
  2214  			DisplayName: "DisplayName",
  2215  			Name:        "z-z-z" + model.NewId() + "b",
  2216  			Type:        model.CHANNEL_OPEN,
  2217  			TeamId:      team.Id,
  2218  			SchemeId:    &cs.Id,
  2219  		}, -1)
  2220  		s.Require().Nil(nErr)
  2221  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  2222  
  2223  		member := &model.ChannelMember{
  2224  			ChannelId:   channel.Id,
  2225  			UserId:      u1.Id,
  2226  			NotifyProps: defaultNotifyProps,
  2227  		}
  2228  		member, nErr = s.Store().Channel().SaveMember(member)
  2229  		s.Require().Nil(nErr)
  2230  
  2231  		testCases := []struct {
  2232  			Name                  string
  2233  			SchemeGuest           bool
  2234  			SchemeUser            bool
  2235  			SchemeAdmin           bool
  2236  			ExplicitRoles         string
  2237  			ExpectedRoles         string
  2238  			ExpectedExplicitRoles string
  2239  			ExpectedSchemeGuest   bool
  2240  			ExpectedSchemeUser    bool
  2241  			ExpectedSchemeAdmin   bool
  2242  		}{
  2243  			{
  2244  				Name:               "channel user implicit",
  2245  				SchemeUser:         true,
  2246  				ExpectedRoles:      cs.DefaultChannelUserRole,
  2247  				ExpectedSchemeUser: true,
  2248  			},
  2249  			{
  2250  				Name:               "channel user explicit",
  2251  				ExplicitRoles:      "channel_user",
  2252  				ExpectedRoles:      cs.DefaultChannelUserRole,
  2253  				ExpectedSchemeUser: true,
  2254  			},
  2255  			{
  2256  				Name:                "channel guest implicit",
  2257  				SchemeGuest:         true,
  2258  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  2259  				ExpectedSchemeGuest: true,
  2260  			},
  2261  			{
  2262  				Name:                "channel guest explicit",
  2263  				ExplicitRoles:       "channel_guest",
  2264  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  2265  				ExpectedSchemeGuest: true,
  2266  			},
  2267  			{
  2268  				Name:                "channel admin implicit",
  2269  				SchemeUser:          true,
  2270  				SchemeAdmin:         true,
  2271  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2272  				ExpectedSchemeUser:  true,
  2273  				ExpectedSchemeAdmin: true,
  2274  			},
  2275  			{
  2276  				Name:                "channel admin explicit",
  2277  				ExplicitRoles:       "channel_user channel_admin",
  2278  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2279  				ExpectedSchemeUser:  true,
  2280  				ExpectedSchemeAdmin: true,
  2281  			},
  2282  			{
  2283  				Name:                  "channel user implicit and explicit custom role",
  2284  				SchemeUser:            true,
  2285  				ExplicitRoles:         "test",
  2286  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  2287  				ExpectedExplicitRoles: "test",
  2288  				ExpectedSchemeUser:    true,
  2289  			},
  2290  			{
  2291  				Name:                  "channel user explicit and explicit custom role",
  2292  				ExplicitRoles:         "channel_user test",
  2293  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  2294  				ExpectedExplicitRoles: "test",
  2295  				ExpectedSchemeUser:    true,
  2296  			},
  2297  			{
  2298  				Name:                  "channel guest implicit and explicit custom role",
  2299  				SchemeGuest:           true,
  2300  				ExplicitRoles:         "test",
  2301  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  2302  				ExpectedExplicitRoles: "test",
  2303  				ExpectedSchemeGuest:   true,
  2304  			},
  2305  			{
  2306  				Name:                  "channel guest explicit and explicit custom role",
  2307  				ExplicitRoles:         "channel_guest test",
  2308  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  2309  				ExpectedExplicitRoles: "test",
  2310  				ExpectedSchemeGuest:   true,
  2311  			},
  2312  			{
  2313  				Name:                  "channel admin implicit and explicit custom role",
  2314  				SchemeUser:            true,
  2315  				SchemeAdmin:           true,
  2316  				ExplicitRoles:         "test",
  2317  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2318  				ExpectedExplicitRoles: "test",
  2319  				ExpectedSchemeUser:    true,
  2320  				ExpectedSchemeAdmin:   true,
  2321  			},
  2322  			{
  2323  				Name:                  "channel admin explicit and explicit custom role",
  2324  				ExplicitRoles:         "channel_user channel_admin test",
  2325  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2326  				ExpectedExplicitRoles: "test",
  2327  				ExpectedSchemeUser:    true,
  2328  				ExpectedSchemeAdmin:   true,
  2329  			},
  2330  			{
  2331  				Name:                  "channel member with only explicit custom roles",
  2332  				ExplicitRoles:         "test test2",
  2333  				ExpectedRoles:         "test test2",
  2334  				ExpectedExplicitRoles: "test test2",
  2335  			},
  2336  		}
  2337  
  2338  		for _, tc := range testCases {
  2339  			s.T().Run(tc.Name, func(t *testing.T) {
  2340  				member.SchemeGuest = tc.SchemeGuest
  2341  				member.SchemeUser = tc.SchemeUser
  2342  				member.SchemeAdmin = tc.SchemeAdmin
  2343  				member.ExplicitRoles = tc.ExplicitRoles
  2344  				member, nErr = s.Store().Channel().UpdateMember(member)
  2345  				s.Require().Nil(nErr)
  2346  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2347  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2348  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2349  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2350  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2351  			})
  2352  		}
  2353  	})
  2354  }
  2355  
  2356  func (s *ChannelStoreTestSuite) TestUpdateMultipleMembers() {
  2357  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2358  	s.Require().Nil(err)
  2359  	u2, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2360  	s.Require().Nil(err)
  2361  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
  2362  
  2363  	s.T().Run("any not valid channel member", func(t *testing.T) {
  2364  		m1 := &model.ChannelMember{ChannelId: "wrong", UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2365  		m2 := &model.ChannelMember{ChannelId: model.NewId(), UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2366  		_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2})
  2367  		s.Require().NotNil(nErr)
  2368  		var appErr *model.AppError
  2369  		s.Require().True(errors.As(nErr, &appErr))
  2370  		s.Require().Equal("model.channel_member.is_valid.channel_id.app_error", appErr.Id)
  2371  	})
  2372  
  2373  	s.T().Run("duplicated entries should fail", func(t *testing.T) {
  2374  		channelID1 := model.NewId()
  2375  		m1 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2376  		m2 := &model.ChannelMember{ChannelId: channelID1, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2377  		_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2})
  2378  		s.Require().NotNil(nErr)
  2379  		s.Require().IsType(&store.ErrConflict{}, nErr)
  2380  	})
  2381  
  2382  	s.T().Run("insert members correctly (in channel without channel scheme and team without scheme)", func(t *testing.T) {
  2383  		team := &model.Team{
  2384  			DisplayName: "Name",
  2385  			Name:        "zz" + model.NewId(),
  2386  			Email:       MakeEmail(),
  2387  			Type:        model.TEAM_OPEN,
  2388  		}
  2389  
  2390  		team, nErr := s.Store().Team().Save(team)
  2391  		s.Require().Nil(nErr)
  2392  
  2393  		channel := &model.Channel{
  2394  			DisplayName: "DisplayName",
  2395  			Name:        "z-z-z" + model.NewId() + "b",
  2396  			Type:        model.CHANNEL_OPEN,
  2397  			TeamId:      team.Id,
  2398  		}
  2399  		channel, nErr = s.Store().Channel().Save(channel, -1)
  2400  		s.Require().Nil(nErr)
  2401  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  2402  
  2403  		member := &model.ChannelMember{ChannelId: channel.Id, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2404  		otherMember := &model.ChannelMember{ChannelId: channel.Id, UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2405  		var members []*model.ChannelMember
  2406  		members, nErr = s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  2407  		s.Require().Nil(nErr)
  2408  		defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  2409  		defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  2410  		s.Require().Len(members, 2)
  2411  		member = members[0]
  2412  		otherMember = members[1]
  2413  
  2414  		testCases := []struct {
  2415  			Name                  string
  2416  			SchemeGuest           bool
  2417  			SchemeUser            bool
  2418  			SchemeAdmin           bool
  2419  			ExplicitRoles         string
  2420  			ExpectedRoles         string
  2421  			ExpectedExplicitRoles string
  2422  			ExpectedSchemeGuest   bool
  2423  			ExpectedSchemeUser    bool
  2424  			ExpectedSchemeAdmin   bool
  2425  		}{
  2426  			{
  2427  				Name:               "channel user implicit",
  2428  				SchemeUser:         true,
  2429  				ExpectedRoles:      "channel_user",
  2430  				ExpectedSchemeUser: true,
  2431  			},
  2432  			{
  2433  				Name:               "channel user explicit",
  2434  				ExplicitRoles:      "channel_user",
  2435  				ExpectedRoles:      "channel_user",
  2436  				ExpectedSchemeUser: true,
  2437  			},
  2438  			{
  2439  				Name:                "channel guest implicit",
  2440  				SchemeGuest:         true,
  2441  				ExpectedRoles:       "channel_guest",
  2442  				ExpectedSchemeGuest: true,
  2443  			},
  2444  			{
  2445  				Name:                "channel guest explicit",
  2446  				ExplicitRoles:       "channel_guest",
  2447  				ExpectedRoles:       "channel_guest",
  2448  				ExpectedSchemeGuest: true,
  2449  			},
  2450  			{
  2451  				Name:                "channel admin implicit",
  2452  				SchemeUser:          true,
  2453  				SchemeAdmin:         true,
  2454  				ExpectedRoles:       "channel_user channel_admin",
  2455  				ExpectedSchemeUser:  true,
  2456  				ExpectedSchemeAdmin: true,
  2457  			},
  2458  			{
  2459  				Name:                "channel admin explicit",
  2460  				ExplicitRoles:       "channel_user channel_admin",
  2461  				ExpectedRoles:       "channel_user channel_admin",
  2462  				ExpectedSchemeUser:  true,
  2463  				ExpectedSchemeAdmin: true,
  2464  			},
  2465  			{
  2466  				Name:                  "channel user implicit and explicit custom role",
  2467  				SchemeUser:            true,
  2468  				ExplicitRoles:         "test",
  2469  				ExpectedRoles:         "test channel_user",
  2470  				ExpectedExplicitRoles: "test",
  2471  				ExpectedSchemeUser:    true,
  2472  			},
  2473  			{
  2474  				Name:                  "channel user explicit and explicit custom role",
  2475  				ExplicitRoles:         "channel_user test",
  2476  				ExpectedRoles:         "test channel_user",
  2477  				ExpectedExplicitRoles: "test",
  2478  				ExpectedSchemeUser:    true,
  2479  			},
  2480  			{
  2481  				Name:                  "channel guest implicit and explicit custom role",
  2482  				SchemeGuest:           true,
  2483  				ExplicitRoles:         "test",
  2484  				ExpectedRoles:         "test channel_guest",
  2485  				ExpectedExplicitRoles: "test",
  2486  				ExpectedSchemeGuest:   true,
  2487  			},
  2488  			{
  2489  				Name:                  "channel guest explicit and explicit custom role",
  2490  				ExplicitRoles:         "channel_guest test",
  2491  				ExpectedRoles:         "test channel_guest",
  2492  				ExpectedExplicitRoles: "test",
  2493  				ExpectedSchemeGuest:   true,
  2494  			},
  2495  			{
  2496  				Name:                  "channel admin implicit and explicit custom role",
  2497  				SchemeUser:            true,
  2498  				SchemeAdmin:           true,
  2499  				ExplicitRoles:         "test",
  2500  				ExpectedRoles:         "test channel_user channel_admin",
  2501  				ExpectedExplicitRoles: "test",
  2502  				ExpectedSchemeUser:    true,
  2503  				ExpectedSchemeAdmin:   true,
  2504  			},
  2505  			{
  2506  				Name:                  "channel admin explicit and explicit custom role",
  2507  				ExplicitRoles:         "channel_user channel_admin test",
  2508  				ExpectedRoles:         "test channel_user channel_admin",
  2509  				ExpectedExplicitRoles: "test",
  2510  				ExpectedSchemeUser:    true,
  2511  				ExpectedSchemeAdmin:   true,
  2512  			},
  2513  			{
  2514  				Name:                  "channel member with only explicit custom roles",
  2515  				ExplicitRoles:         "test test2",
  2516  				ExpectedRoles:         "test test2",
  2517  				ExpectedExplicitRoles: "test test2",
  2518  			},
  2519  		}
  2520  
  2521  		for _, tc := range testCases {
  2522  			s.T().Run(tc.Name, func(t *testing.T) {
  2523  				member.SchemeGuest = tc.SchemeGuest
  2524  				member.SchemeUser = tc.SchemeUser
  2525  				member.SchemeAdmin = tc.SchemeAdmin
  2526  				member.ExplicitRoles = tc.ExplicitRoles
  2527  				var members []*model.ChannelMember
  2528  				members, nErr = s.Store().Channel().UpdateMultipleMembers([]*model.ChannelMember{member, otherMember})
  2529  				s.Require().Nil(nErr)
  2530  				s.Require().Len(members, 2)
  2531  				member = members[0]
  2532  
  2533  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2534  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2535  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2536  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2537  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2538  			})
  2539  		}
  2540  	})
  2541  
  2542  	s.T().Run("insert members correctly (in channel without scheme and team with scheme)", func(t *testing.T) {
  2543  		ts := &model.Scheme{
  2544  			Name:        model.NewId(),
  2545  			DisplayName: model.NewId(),
  2546  			Description: model.NewId(),
  2547  			Scope:       model.SCHEME_SCOPE_TEAM,
  2548  		}
  2549  		ts, nErr := s.Store().Scheme().Save(ts)
  2550  		s.Require().Nil(nErr)
  2551  
  2552  		team := &model.Team{
  2553  			DisplayName: "Name",
  2554  			Name:        "zz" + model.NewId(),
  2555  			Email:       MakeEmail(),
  2556  			Type:        model.TEAM_OPEN,
  2557  			SchemeId:    &ts.Id,
  2558  		}
  2559  
  2560  		team, nErr = s.Store().Team().Save(team)
  2561  		s.Require().Nil(nErr)
  2562  
  2563  		channel := &model.Channel{
  2564  			DisplayName: "DisplayName",
  2565  			Name:        "z-z-z" + model.NewId() + "b",
  2566  			Type:        model.CHANNEL_OPEN,
  2567  			TeamId:      team.Id,
  2568  		}
  2569  		channel, nErr = s.Store().Channel().Save(channel, -1)
  2570  		s.Require().Nil(nErr)
  2571  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  2572  
  2573  		member := &model.ChannelMember{ChannelId: channel.Id, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2574  		otherMember := &model.ChannelMember{ChannelId: channel.Id, UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2575  		var members []*model.ChannelMember
  2576  		members, nErr = s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  2577  		s.Require().Nil(nErr)
  2578  		defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  2579  		defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  2580  		s.Require().Len(members, 2)
  2581  		member = members[0]
  2582  		otherMember = members[1]
  2583  
  2584  		testCases := []struct {
  2585  			Name                  string
  2586  			SchemeGuest           bool
  2587  			SchemeUser            bool
  2588  			SchemeAdmin           bool
  2589  			ExplicitRoles         string
  2590  			ExpectedRoles         string
  2591  			ExpectedExplicitRoles string
  2592  			ExpectedSchemeGuest   bool
  2593  			ExpectedSchemeUser    bool
  2594  			ExpectedSchemeAdmin   bool
  2595  		}{
  2596  			{
  2597  				Name:               "channel user implicit",
  2598  				SchemeUser:         true,
  2599  				ExpectedRoles:      ts.DefaultChannelUserRole,
  2600  				ExpectedSchemeUser: true,
  2601  			},
  2602  			{
  2603  				Name:               "channel user explicit",
  2604  				ExplicitRoles:      "channel_user",
  2605  				ExpectedRoles:      ts.DefaultChannelUserRole,
  2606  				ExpectedSchemeUser: true,
  2607  			},
  2608  			{
  2609  				Name:                "channel guest implicit",
  2610  				SchemeGuest:         true,
  2611  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  2612  				ExpectedSchemeGuest: true,
  2613  			},
  2614  			{
  2615  				Name:                "channel guest explicit",
  2616  				ExplicitRoles:       "channel_guest",
  2617  				ExpectedRoles:       ts.DefaultChannelGuestRole,
  2618  				ExpectedSchemeGuest: true,
  2619  			},
  2620  			{
  2621  				Name:                "channel admin implicit",
  2622  				SchemeUser:          true,
  2623  				SchemeAdmin:         true,
  2624  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2625  				ExpectedSchemeUser:  true,
  2626  				ExpectedSchemeAdmin: true,
  2627  			},
  2628  			{
  2629  				Name:                "channel admin explicit",
  2630  				ExplicitRoles:       "channel_user channel_admin",
  2631  				ExpectedRoles:       ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2632  				ExpectedSchemeUser:  true,
  2633  				ExpectedSchemeAdmin: true,
  2634  			},
  2635  			{
  2636  				Name:                  "channel user implicit and explicit custom role",
  2637  				SchemeUser:            true,
  2638  				ExplicitRoles:         "test",
  2639  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  2640  				ExpectedExplicitRoles: "test",
  2641  				ExpectedSchemeUser:    true,
  2642  			},
  2643  			{
  2644  				Name:                  "channel user explicit and explicit custom role",
  2645  				ExplicitRoles:         "channel_user test",
  2646  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole,
  2647  				ExpectedExplicitRoles: "test",
  2648  				ExpectedSchemeUser:    true,
  2649  			},
  2650  			{
  2651  				Name:                  "channel guest implicit and explicit custom role",
  2652  				SchemeGuest:           true,
  2653  				ExplicitRoles:         "test",
  2654  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  2655  				ExpectedExplicitRoles: "test",
  2656  				ExpectedSchemeGuest:   true,
  2657  			},
  2658  			{
  2659  				Name:                  "channel guest explicit and explicit custom role",
  2660  				ExplicitRoles:         "channel_guest test",
  2661  				ExpectedRoles:         "test " + ts.DefaultChannelGuestRole,
  2662  				ExpectedExplicitRoles: "test",
  2663  				ExpectedSchemeGuest:   true,
  2664  			},
  2665  			{
  2666  				Name:                  "channel admin implicit and explicit custom role",
  2667  				SchemeUser:            true,
  2668  				SchemeAdmin:           true,
  2669  				ExplicitRoles:         "test",
  2670  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2671  				ExpectedExplicitRoles: "test",
  2672  				ExpectedSchemeUser:    true,
  2673  				ExpectedSchemeAdmin:   true,
  2674  			},
  2675  			{
  2676  				Name:                  "channel admin explicit and explicit custom role",
  2677  				ExplicitRoles:         "channel_user channel_admin test",
  2678  				ExpectedRoles:         "test " + ts.DefaultChannelUserRole + " " + ts.DefaultChannelAdminRole,
  2679  				ExpectedExplicitRoles: "test",
  2680  				ExpectedSchemeUser:    true,
  2681  				ExpectedSchemeAdmin:   true,
  2682  			},
  2683  			{
  2684  				Name:                  "channel member with only explicit custom roles",
  2685  				ExplicitRoles:         "test test2",
  2686  				ExpectedRoles:         "test test2",
  2687  				ExpectedExplicitRoles: "test test2",
  2688  			},
  2689  		}
  2690  
  2691  		for _, tc := range testCases {
  2692  			s.T().Run(tc.Name, func(t *testing.T) {
  2693  				member.SchemeGuest = tc.SchemeGuest
  2694  				member.SchemeUser = tc.SchemeUser
  2695  				member.SchemeAdmin = tc.SchemeAdmin
  2696  				member.ExplicitRoles = tc.ExplicitRoles
  2697  				var members []*model.ChannelMember
  2698  				members, nErr = s.Store().Channel().UpdateMultipleMembers([]*model.ChannelMember{member, otherMember})
  2699  				s.Require().Nil(nErr)
  2700  				s.Require().Len(members, 2)
  2701  				member = members[0]
  2702  
  2703  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2704  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2705  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2706  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2707  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2708  			})
  2709  		}
  2710  	})
  2711  
  2712  	s.T().Run("insert members correctly (in channel with channel scheme)", func(t *testing.T) {
  2713  		cs := &model.Scheme{
  2714  			Name:        model.NewId(),
  2715  			DisplayName: model.NewId(),
  2716  			Description: model.NewId(),
  2717  			Scope:       model.SCHEME_SCOPE_CHANNEL,
  2718  		}
  2719  		cs, nErr := s.Store().Scheme().Save(cs)
  2720  		s.Require().Nil(nErr)
  2721  
  2722  		team := &model.Team{
  2723  			DisplayName: "Name",
  2724  			Name:        "zz" + model.NewId(),
  2725  			Email:       MakeEmail(),
  2726  			Type:        model.TEAM_OPEN,
  2727  		}
  2728  
  2729  		team, nErr = s.Store().Team().Save(team)
  2730  		s.Require().Nil(nErr)
  2731  
  2732  		channel, nErr := s.Store().Channel().Save(&model.Channel{
  2733  			DisplayName: "DisplayName",
  2734  			Name:        "z-z-z" + model.NewId() + "b",
  2735  			Type:        model.CHANNEL_OPEN,
  2736  			TeamId:      team.Id,
  2737  			SchemeId:    &cs.Id,
  2738  		}, -1)
  2739  		s.Require().Nil(nErr)
  2740  		defer func() { s.Store().Channel().PermanentDelete(channel.Id) }()
  2741  
  2742  		member := &model.ChannelMember{ChannelId: channel.Id, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2743  		otherMember := &model.ChannelMember{ChannelId: channel.Id, UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2744  		members, err := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{member, otherMember})
  2745  		s.Require().Nil(err)
  2746  		defer s.Store().Channel().RemoveMember(channel.Id, u1.Id)
  2747  		defer s.Store().Channel().RemoveMember(channel.Id, u2.Id)
  2748  		s.Require().Len(members, 2)
  2749  		member = members[0]
  2750  		otherMember = members[1]
  2751  
  2752  		testCases := []struct {
  2753  			Name                  string
  2754  			SchemeGuest           bool
  2755  			SchemeUser            bool
  2756  			SchemeAdmin           bool
  2757  			ExplicitRoles         string
  2758  			ExpectedRoles         string
  2759  			ExpectedExplicitRoles string
  2760  			ExpectedSchemeGuest   bool
  2761  			ExpectedSchemeUser    bool
  2762  			ExpectedSchemeAdmin   bool
  2763  		}{
  2764  			{
  2765  				Name:               "channel user implicit",
  2766  				SchemeUser:         true,
  2767  				ExpectedRoles:      cs.DefaultChannelUserRole,
  2768  				ExpectedSchemeUser: true,
  2769  			},
  2770  			{
  2771  				Name:               "channel user explicit",
  2772  				ExplicitRoles:      "channel_user",
  2773  				ExpectedRoles:      cs.DefaultChannelUserRole,
  2774  				ExpectedSchemeUser: true,
  2775  			},
  2776  			{
  2777  				Name:                "channel guest implicit",
  2778  				SchemeGuest:         true,
  2779  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  2780  				ExpectedSchemeGuest: true,
  2781  			},
  2782  			{
  2783  				Name:                "channel guest explicit",
  2784  				ExplicitRoles:       "channel_guest",
  2785  				ExpectedRoles:       cs.DefaultChannelGuestRole,
  2786  				ExpectedSchemeGuest: true,
  2787  			},
  2788  			{
  2789  				Name:                "channel admin implicit",
  2790  				SchemeUser:          true,
  2791  				SchemeAdmin:         true,
  2792  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2793  				ExpectedSchemeUser:  true,
  2794  				ExpectedSchemeAdmin: true,
  2795  			},
  2796  			{
  2797  				Name:                "channel admin explicit",
  2798  				ExplicitRoles:       "channel_user channel_admin",
  2799  				ExpectedRoles:       cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2800  				ExpectedSchemeUser:  true,
  2801  				ExpectedSchemeAdmin: true,
  2802  			},
  2803  			{
  2804  				Name:                  "channel user implicit and explicit custom role",
  2805  				SchemeUser:            true,
  2806  				ExplicitRoles:         "test",
  2807  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  2808  				ExpectedExplicitRoles: "test",
  2809  				ExpectedSchemeUser:    true,
  2810  			},
  2811  			{
  2812  				Name:                  "channel user explicit and explicit custom role",
  2813  				ExplicitRoles:         "channel_user test",
  2814  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole,
  2815  				ExpectedExplicitRoles: "test",
  2816  				ExpectedSchemeUser:    true,
  2817  			},
  2818  			{
  2819  				Name:                  "channel guest implicit and explicit custom role",
  2820  				SchemeGuest:           true,
  2821  				ExplicitRoles:         "test",
  2822  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  2823  				ExpectedExplicitRoles: "test",
  2824  				ExpectedSchemeGuest:   true,
  2825  			},
  2826  			{
  2827  				Name:                  "channel guest explicit and explicit custom role",
  2828  				ExplicitRoles:         "channel_guest test",
  2829  				ExpectedRoles:         "test " + cs.DefaultChannelGuestRole,
  2830  				ExpectedExplicitRoles: "test",
  2831  				ExpectedSchemeGuest:   true,
  2832  			},
  2833  			{
  2834  				Name:                  "channel admin implicit and explicit custom role",
  2835  				SchemeUser:            true,
  2836  				SchemeAdmin:           true,
  2837  				ExplicitRoles:         "test",
  2838  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2839  				ExpectedExplicitRoles: "test",
  2840  				ExpectedSchemeUser:    true,
  2841  				ExpectedSchemeAdmin:   true,
  2842  			},
  2843  			{
  2844  				Name:                  "channel admin explicit and explicit custom role",
  2845  				ExplicitRoles:         "channel_user channel_admin test",
  2846  				ExpectedRoles:         "test " + cs.DefaultChannelUserRole + " " + cs.DefaultChannelAdminRole,
  2847  				ExpectedExplicitRoles: "test",
  2848  				ExpectedSchemeUser:    true,
  2849  				ExpectedSchemeAdmin:   true,
  2850  			},
  2851  			{
  2852  				Name:                  "channel member with only explicit custom roles",
  2853  				ExplicitRoles:         "test test2",
  2854  				ExpectedRoles:         "test test2",
  2855  				ExpectedExplicitRoles: "test test2",
  2856  			},
  2857  		}
  2858  
  2859  		for _, tc := range testCases {
  2860  			s.T().Run(tc.Name, func(t *testing.T) {
  2861  				member.SchemeGuest = tc.SchemeGuest
  2862  				member.SchemeUser = tc.SchemeUser
  2863  				member.SchemeAdmin = tc.SchemeAdmin
  2864  				member.ExplicitRoles = tc.ExplicitRoles
  2865  				members, err := s.Store().Channel().UpdateMultipleMembers([]*model.ChannelMember{member, otherMember})
  2866  				s.Require().Nil(err)
  2867  				s.Require().Len(members, 2)
  2868  				member = members[0]
  2869  
  2870  				s.Assert().Equal(tc.ExpectedRoles, member.Roles)
  2871  				s.Assert().Equal(tc.ExpectedExplicitRoles, member.ExplicitRoles)
  2872  				s.Assert().Equal(tc.ExpectedSchemeGuest, member.SchemeGuest)
  2873  				s.Assert().Equal(tc.ExpectedSchemeUser, member.SchemeUser)
  2874  				s.Assert().Equal(tc.ExpectedSchemeAdmin, member.SchemeAdmin)
  2875  			})
  2876  		}
  2877  	})
  2878  }
  2879  
  2880  func (s *ChannelStoreTestSuite) TestRemoveMember() {
  2881  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2882  	s.Require().NoError(err)
  2883  	u2, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2884  	s.Require().NoError(err)
  2885  	u3, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2886  	s.Require().NoError(err)
  2887  	u4, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2888  	s.Require().NoError(err)
  2889  	channelID := model.NewId()
  2890  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
  2891  	m1 := &model.ChannelMember{ChannelId: channelID, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2892  	m2 := &model.ChannelMember{ChannelId: channelID, UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2893  	m3 := &model.ChannelMember{ChannelId: channelID, UserId: u3.Id, NotifyProps: defaultNotifyProps}
  2894  	m4 := &model.ChannelMember{ChannelId: channelID, UserId: u4.Id, NotifyProps: defaultNotifyProps}
  2895  	_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2, m3, m4})
  2896  	s.Require().NoError(nErr)
  2897  
  2898  	s.T().Run("remove member from not existing channel", func(t *testing.T) {
  2899  		nErr = s.Store().Channel().RemoveMember("not-existing-channel", u1.Id)
  2900  		s.Require().NoError(nErr)
  2901  		var membersCount int64
  2902  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2903  		s.Require().NoError(nErr)
  2904  		s.Require().Equal(int64(4), membersCount)
  2905  	})
  2906  
  2907  	s.T().Run("remove not existing member from an existing channel", func(t *testing.T) {
  2908  		nErr = s.Store().Channel().RemoveMember(channelID, model.NewId())
  2909  		s.Require().NoError(nErr)
  2910  		var membersCount int64
  2911  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2912  		s.Require().NoError(nErr)
  2913  		s.Require().Equal(int64(4), membersCount)
  2914  	})
  2915  
  2916  	s.T().Run("remove existing member from an existing channel", func(t *testing.T) {
  2917  		nErr = s.Store().Channel().RemoveMember(channelID, u1.Id)
  2918  		s.Require().Nil(nErr)
  2919  		defer s.Store().Channel().SaveMember(m1)
  2920  		var membersCount int64
  2921  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2922  		s.Require().Nil(nErr)
  2923  		s.Require().Equal(int64(3), membersCount)
  2924  	})
  2925  }
  2926  
  2927  func (s *ChannelStoreTestSuite) TestRemoveMembers() {
  2928  	u1, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2929  	s.Require().Nil(err)
  2930  	u2, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2931  	s.Require().Nil(err)
  2932  	u3, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2933  	s.Require().Nil(err)
  2934  	u4, err := s.Store().User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
  2935  	s.Require().Nil(err)
  2936  	channelID := model.NewId()
  2937  	defaultNotifyProps := model.GetDefaultChannelNotifyProps()
  2938  	m1 := &model.ChannelMember{ChannelId: channelID, UserId: u1.Id, NotifyProps: defaultNotifyProps}
  2939  	m2 := &model.ChannelMember{ChannelId: channelID, UserId: u2.Id, NotifyProps: defaultNotifyProps}
  2940  	m3 := &model.ChannelMember{ChannelId: channelID, UserId: u3.Id, NotifyProps: defaultNotifyProps}
  2941  	m4 := &model.ChannelMember{ChannelId: channelID, UserId: u4.Id, NotifyProps: defaultNotifyProps}
  2942  	_, nErr := s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2, m3, m4})
  2943  	s.Require().NoError(nErr)
  2944  
  2945  	s.T().Run("remove members from not existing channel", func(t *testing.T) {
  2946  		nErr = s.Store().Channel().RemoveMembers("not-existing-channel", []string{u1.Id, u2.Id, u3.Id, u4.Id})
  2947  		s.Require().NoError(nErr)
  2948  		var membersCount int64
  2949  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2950  		s.Require().NoError(nErr)
  2951  		s.Require().Equal(int64(4), membersCount)
  2952  	})
  2953  
  2954  	s.T().Run("remove not existing members from an existing channel", func(t *testing.T) {
  2955  		nErr = s.Store().Channel().RemoveMembers(channelID, []string{model.NewId(), model.NewId()})
  2956  		s.Require().NoError(nErr)
  2957  		var membersCount int64
  2958  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2959  		s.Require().NoError(nErr)
  2960  		s.Require().Equal(int64(4), membersCount)
  2961  	})
  2962  
  2963  	s.T().Run("remove not existing and not existing members from an existing channel", func(t *testing.T) {
  2964  		nErr = s.Store().Channel().RemoveMembers(channelID, []string{u1.Id, u2.Id, model.NewId(), model.NewId()})
  2965  		s.Require().Nil(nErr)
  2966  		defer s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2})
  2967  		var membersCount int64
  2968  		membersCount, nErr = s.Store().Channel().GetMemberCount(channelID, false)
  2969  		s.Require().Nil(nErr)
  2970  		s.Require().Equal(int64(2), membersCount)
  2971  	})
  2972  	s.T().Run("remove existing members from an existing channel", func(t *testing.T) {
  2973  		nErr = s.Store().Channel().RemoveMembers(channelID, []string{u1.Id, u2.Id, u3.Id})
  2974  		s.Require().Nil(nErr)
  2975  		defer s.Store().Channel().SaveMultipleMembers([]*model.ChannelMember{m1, m2, m3})
  2976  		membersCount, err := s.Store().Channel().GetMemberCount(channelID, false)
  2977  		s.Require().Nil(err)
  2978  		s.Require().Equal(int64(1), membersCount)
  2979  	})
  2980  }
  2981  
  2982  func (s *ChannelStoreTestSuite) TestDeleteMemberStore() {
  2983  	c1 := &model.Channel{}
  2984  	c1.TeamId = model.NewId()
  2985  	c1.DisplayName = "NameName"
  2986  	c1.Name = "zz" + model.NewId() + "b"
  2987  	c1.Type = model.CHANNEL_OPEN
  2988  	c1, nErr := s.Store().Channel().Save(c1, -1)
  2989  	s.Require().Nil(nErr)
  2990  
  2991  	c1t1, _ := s.Store().Channel().Get(c1.Id, false)
  2992  	s.Assert().EqualValues(0, c1t1.ExtraUpdateAt, "ExtraUpdateAt should be 0")
  2993  
  2994  	u1 := model.User{}
  2995  	u1.Email = MakeEmail()
  2996  	u1.Nickname = model.NewId()
  2997  	_, err := s.Store().User().Save(&u1)
  2998  	s.Require().Nil(err)
  2999  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
  3000  	s.Require().Nil(nErr)
  3001  
  3002  	u2 := model.User{}
  3003  	u2.Email = MakeEmail()
  3004  	u2.Nickname = model.NewId()
  3005  	_, err = s.Store().User().Save(&u2)
  3006  	s.Require().Nil(err)
  3007  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
  3008  	s.Require().Nil(nErr)
  3009  
  3010  	o1 := model.ChannelMember{}
  3011  	o1.ChannelId = c1.Id
  3012  	o1.UserId = u1.Id
  3013  	o1.NotifyProps = model.GetDefaultChannelNotifyProps()
  3014  	_, nErr = s.Store().Channel().SaveMember(&o1)
  3015  	s.Require().Nil(nErr)
  3016  
  3017  	o2 := model.ChannelMember{}
  3018  	o2.ChannelId = c1.Id
  3019  	o2.UserId = u2.Id
  3020  	o2.NotifyProps = model.GetDefaultChannelNotifyProps()
  3021  	_, nErr = s.Store().Channel().SaveMember(&o2)
  3022  	s.Require().Nil(nErr)
  3023  
  3024  	c1t2, _ := s.Store().Channel().Get(c1.Id, false)
  3025  	s.Assert().EqualValues(0, c1t2.ExtraUpdateAt, "ExtraUpdateAt should be 0")
  3026  
  3027  	count, nErr := s.Store().Channel().GetMemberCount(o1.ChannelId, false)
  3028  	s.Require().Nil(nErr)
  3029  	s.Require().EqualValues(2, count, "should have saved 2 members")
  3030  
  3031  	nErr = s.Store().Channel().PermanentDeleteMembersByUser(o2.UserId)
  3032  	s.Require().Nil(nErr)
  3033  
  3034  	count, nErr = s.Store().Channel().GetMemberCount(o1.ChannelId, false)
  3035  	s.Require().Nil(nErr)
  3036  	s.Require().EqualValues(1, count, "should have removed 1 member")
  3037  
  3038  	nErr = s.Store().Channel().PermanentDeleteMembersByChannel(o1.ChannelId)
  3039  	s.Require().Nil(nErr)
  3040  
  3041  	count, nErr = s.Store().Channel().GetMemberCount(o1.ChannelId, false)
  3042  	s.Require().Nil(nErr)
  3043  	s.Require().EqualValues(0, count, "should have removed all members")
  3044  }
  3045  
  3046  func (s *ChannelStoreTestSuite) TestStoreGetChannels() {
  3047  	team := model.NewId()
  3048  	o1 := model.Channel{}
  3049  	o1.TeamId = team
  3050  	o1.DisplayName = "Channel1"
  3051  	o1.Name = "zz" + model.NewId() + "b"
  3052  	o1.Type = model.CHANNEL_OPEN
  3053  	_, nErr := s.Store().Channel().Save(&o1, -1)
  3054  	s.Require().Nil(nErr)
  3055  
  3056  	o2 := model.Channel{}
  3057  	o2.TeamId = team
  3058  	o2.DisplayName = "Channel2"
  3059  	o2.Name = "zz" + model.NewId() + "b"
  3060  	o2.Type = model.CHANNEL_OPEN
  3061  	_, nErr = s.Store().Channel().Save(&o2, -1)
  3062  	s.Require().Nil(nErr)
  3063  
  3064  	o3 := model.Channel{}
  3065  	o3.TeamId = team
  3066  	o3.DisplayName = "Channel3"
  3067  	o3.Name = "zz" + model.NewId() + "b"
  3068  	o3.Type = model.CHANNEL_OPEN
  3069  	_, nErr = s.Store().Channel().Save(&o3, -1)
  3070  	s.Require().Nil(nErr)
  3071  
  3072  	m1 := model.ChannelMember{}
  3073  	m1.ChannelId = o1.Id
  3074  	m1.UserId = model.NewId()
  3075  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  3076  	_, err := s.Store().Channel().SaveMember(&m1)
  3077  	s.Require().Nil(err)
  3078  
  3079  	m2 := model.ChannelMember{}
  3080  	m2.ChannelId = o1.Id
  3081  	m2.UserId = model.NewId()
  3082  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  3083  	_, err = s.Store().Channel().SaveMember(&m2)
  3084  	s.Require().Nil(err)
  3085  
  3086  	m3 := model.ChannelMember{}
  3087  	m3.ChannelId = o2.Id
  3088  	m3.UserId = m1.UserId
  3089  	m3.NotifyProps = model.GetDefaultChannelNotifyProps()
  3090  	_, err = s.Store().Channel().SaveMember(&m3)
  3091  	s.Require().Nil(err)
  3092  
  3093  	m4 := model.ChannelMember{}
  3094  	m4.ChannelId = o3.Id
  3095  	m4.UserId = m1.UserId
  3096  	m4.NotifyProps = model.GetDefaultChannelNotifyProps()
  3097  	_, err = s.Store().Channel().SaveMember(&m4)
  3098  	s.Require().Nil(err)
  3099  
  3100  	list, nErr := s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, false, 0)
  3101  	s.Require().Nil(nErr)
  3102  	s.Require().Len(*list, 3)
  3103  	s.Require().Equal(o1.Id, (*list)[0].Id, "missing channel")
  3104  	s.Require().Equal(o2.Id, (*list)[1].Id, "missing channel")
  3105  	s.Require().Equal(o3.Id, (*list)[2].Id, "missing channel")
  3106  
  3107  	ids, err := s.Store().Channel().GetAllChannelMembersForUser(m1.UserId, false, false)
  3108  	s.Require().Nil(err)
  3109  	_, ok := ids[o1.Id]
  3110  	s.Require().True(ok, "missing channel")
  3111  
  3112  	ids2, err := s.Store().Channel().GetAllChannelMembersForUser(m1.UserId, true, false)
  3113  	s.Require().Nil(err)
  3114  	_, ok = ids2[o1.Id]
  3115  	s.Require().True(ok, "missing channel")
  3116  
  3117  	ids3, err := s.Store().Channel().GetAllChannelMembersForUser(m1.UserId, true, false)
  3118  	s.Require().Nil(err)
  3119  	_, ok = ids3[o1.Id]
  3120  	s.Require().True(ok, "missing channel")
  3121  
  3122  	ids4, err := s.Store().Channel().GetAllChannelMembersForUser(m1.UserId, true, true)
  3123  	s.Require().Nil(err)
  3124  	_, ok = ids4[o1.Id]
  3125  	s.Require().True(ok, "missing channel")
  3126  
  3127  	nErr = s.Store().Channel().Delete(o2.Id, 10)
  3128  	s.Require().NoError(nErr)
  3129  
  3130  	nErr = s.Store().Channel().Delete(o3.Id, 20)
  3131  	s.Require().NoError(nErr)
  3132  
  3133  	// should return 1
  3134  	list, nErr = s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, false, 0)
  3135  	s.Require().Nil(nErr)
  3136  	s.Require().Len(*list, 1)
  3137  	s.Require().Equal(o1.Id, (*list)[0].Id, "missing channel")
  3138  
  3139  	// Should return all
  3140  	list, nErr = s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, true, 0)
  3141  	s.Require().Nil(nErr)
  3142  	s.Require().Len(*list, 3)
  3143  	s.Require().Equal(o1.Id, (*list)[0].Id, "missing channel")
  3144  	s.Require().Equal(o2.Id, (*list)[1].Id, "missing channel")
  3145  	s.Require().Equal(o3.Id, (*list)[2].Id, "missing channel")
  3146  
  3147  	// Should still return all
  3148  	list, nErr = s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, true, 10)
  3149  	s.Require().Nil(nErr)
  3150  	s.Require().Len(*list, 3)
  3151  	s.Require().Equal(o1.Id, (*list)[0].Id, "missing channel")
  3152  	s.Require().Equal(o2.Id, (*list)[1].Id, "missing channel")
  3153  	s.Require().Equal(o3.Id, (*list)[2].Id, "missing channel")
  3154  
  3155  	// Should return 2
  3156  	list, nErr = s.Store().Channel().GetChannels(o1.TeamId, m1.UserId, true, 20)
  3157  	s.Require().Nil(nErr)
  3158  	s.Require().Len(*list, 2)
  3159  	s.Require().Equal(o1.Id, (*list)[0].Id, "missing channel")
  3160  	s.Require().Equal(o3.Id, (*list)[1].Id, "missing channel")
  3161  
  3162  	s.Require().True(
  3163  		s.Store().Channel().IsUserInChannelUseCache(m1.UserId, o1.Id),
  3164  		"missing channel")
  3165  	s.Require().True(
  3166  		s.Store().Channel().IsUserInChannelUseCache(m1.UserId, o2.Id),
  3167  		"missing channel")
  3168  
  3169  	s.Require().False(
  3170  		s.Store().Channel().IsUserInChannelUseCache(m1.UserId, "blahblah"),
  3171  		"missing channel")
  3172  
  3173  	s.Require().False(
  3174  		s.Store().Channel().IsUserInChannelUseCache("blahblah", "blahblah"),
  3175  		"missing channel")
  3176  
  3177  	s.Store().Channel().InvalidateAllChannelMembersForUser(m1.UserId)
  3178  }
  3179  
  3180  func (s *ChannelStoreTestSuite) TestStoreGetAllChannels() {
  3181  	s.cleanupChannels()
  3182  
  3183  	t1 := model.Team{}
  3184  	t1.DisplayName = "Name"
  3185  	t1.Name = "zz" + model.NewId()
  3186  	t1.Email = MakeEmail()
  3187  	t1.Type = model.TEAM_OPEN
  3188  	_, err := s.Store().Team().Save(&t1)
  3189  	s.Require().Nil(err)
  3190  
  3191  	t2 := model.Team{}
  3192  	t2.DisplayName = "Name2"
  3193  	t2.Name = "zz" + model.NewId()
  3194  	t2.Email = MakeEmail()
  3195  	t2.Type = model.TEAM_OPEN
  3196  	_, err = s.Store().Team().Save(&t2)
  3197  	s.Require().Nil(err)
  3198  
  3199  	c1 := model.Channel{}
  3200  	c1.TeamId = t1.Id
  3201  	c1.DisplayName = "Channel1" + model.NewId()
  3202  	c1.Name = "zz" + model.NewId() + "b"
  3203  	c1.Type = model.CHANNEL_OPEN
  3204  	_, nErr := s.Store().Channel().Save(&c1, -1)
  3205  	s.Require().Nil(nErr)
  3206  
  3207  	group := &model.Group{
  3208  		Name:        model.NewString(model.NewId()),
  3209  		DisplayName: model.NewId(),
  3210  		Source:      model.GroupSourceLdap,
  3211  		RemoteId:    model.NewId(),
  3212  	}
  3213  	_, err = s.Store().Group().Create(group)
  3214  	s.Require().Nil(err)
  3215  
  3216  	_, err = s.Store().Group().CreateGroupSyncable(model.NewGroupChannel(group.Id, c1.Id, true))
  3217  	s.Require().Nil(err)
  3218  
  3219  	c2 := model.Channel{}
  3220  	c2.TeamId = t1.Id
  3221  	c2.DisplayName = "Channel2" + model.NewId()
  3222  	c2.Name = "zz" + model.NewId() + "b"
  3223  	c2.Type = model.CHANNEL_OPEN
  3224  	_, nErr = s.Store().Channel().Save(&c2, -1)
  3225  	s.Require().Nil(nErr)
  3226  	c2.DeleteAt = model.GetMillis()
  3227  	c2.UpdateAt = c2.DeleteAt
  3228  	nErr = s.Store().Channel().Delete(c2.Id, c2.DeleteAt)
  3229  	s.Require().Nil(nErr, "channel should have been deleted")
  3230  
  3231  	c3 := model.Channel{}
  3232  	c3.TeamId = t2.Id
  3233  	c3.DisplayName = "Channel3" + model.NewId()
  3234  	c3.Name = "zz" + model.NewId() + "b"
  3235  	c3.Type = model.CHANNEL_PRIVATE
  3236  	_, nErr = s.Store().Channel().Save(&c3, -1)
  3237  	s.Require().Nil(nErr)
  3238  
  3239  	u1 := model.User{Id: model.NewId()}
  3240  	u2 := model.User{Id: model.NewId()}
  3241  	_, nErr = s.Store().Channel().CreateDirectChannel(&u1, &u2)
  3242  	s.Require().Nil(nErr)
  3243  
  3244  	userIds := []string{model.NewId(), model.NewId(), model.NewId()}
  3245  
  3246  	c5 := model.Channel{}
  3247  	c5.Name = model.GetGroupNameFromUserIds(userIds)
  3248  	c5.DisplayName = "GroupChannel" + model.NewId()
  3249  	c5.Name = "zz" + model.NewId() + "b"
  3250  	c5.Type = model.CHANNEL_GROUP
  3251  	_, nErr = s.Store().Channel().Save(&c5, -1)
  3252  	s.Require().Nil(nErr)
  3253  
  3254  	list, nErr := s.Store().Channel().GetAllChannels(0, 10, store.ChannelSearchOpts{})
  3255  	s.Require().Nil(nErr)
  3256  	s.Assert().Len(*list, 2)
  3257  	s.Assert().Equal(c1.Id, (*list)[0].Id)
  3258  	s.Assert().Equal("Name", (*list)[0].TeamDisplayName)
  3259  	s.Assert().Equal(c3.Id, (*list)[1].Id)
  3260  	s.Assert().Equal("Name2", (*list)[1].TeamDisplayName)
  3261  
  3262  	count1, nErr := s.Store().Channel().GetAllChannelsCount(store.ChannelSearchOpts{})
  3263  	s.Require().Nil(nErr)
  3264  
  3265  	list, nErr = s.Store().Channel().GetAllChannels(0, 10, store.ChannelSearchOpts{IncludeDeleted: true})
  3266  	s.Require().Nil(nErr)
  3267  	s.Assert().Len(*list, 3)
  3268  	s.Assert().Equal(c1.Id, (*list)[0].Id)
  3269  	s.Assert().Equal("Name", (*list)[0].TeamDisplayName)
  3270  	s.Assert().Equal(c2.Id, (*list)[1].Id)
  3271  	s.Assert().Equal(c3.Id, (*list)[2].Id)
  3272  
  3273  	count2, nErr := s.Store().Channel().GetAllChannelsCount(store.ChannelSearchOpts{IncludeDeleted: true})
  3274  	s.Require().Nil(nErr)
  3275  	s.Require().True(func() bool {
  3276  		return count2 > count1
  3277  	}())
  3278  
  3279  	list, nErr = s.Store().Channel().GetAllChannels(0, 1, store.ChannelSearchOpts{IncludeDeleted: true})
  3280  	s.Require().Nil(nErr)
  3281  	s.Assert().Len(*list, 1)
  3282  	s.Assert().Equal(c1.Id, (*list)[0].Id)
  3283  	s.Assert().Equal("Name", (*list)[0].TeamDisplayName)
  3284  
  3285  	// Not associated to group
  3286  	list, nErr = s.Store().Channel().GetAllChannels(0, 10, store.ChannelSearchOpts{NotAssociatedToGroup: group.Id})
  3287  	s.Require().Nil(nErr)
  3288  	s.Assert().Len(*list, 1)
  3289  
  3290  	// Exclude channel names
  3291  	list, nErr = s.Store().Channel().GetAllChannels(0, 10, store.ChannelSearchOpts{ExcludeChannelNames: []string{c1.Name}})
  3292  	s.Require().Nil(nErr)
  3293  	s.Assert().Len(*list, 1)
  3294  
  3295  	// Manually truncate Channels table until testlib can handle cleanups
  3296  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
  3297  }
  3298  
  3299  func (s *ChannelStoreTestSuite) TestStoreGetMoreChannels() {
  3300  	teamId := model.NewId()
  3301  	otherTeamId := model.NewId()
  3302  	userId := model.NewId()
  3303  	otherUserId1 := model.NewId()
  3304  	otherUserId2 := model.NewId()
  3305  
  3306  	// o1 is a channel on the team to which the user (and the other user 1) belongs
  3307  	o1 := model.Channel{
  3308  		TeamId:      teamId,
  3309  		DisplayName: "Channel1",
  3310  		Name:        "zz" + model.NewId() + "b",
  3311  		Type:        model.CHANNEL_OPEN,
  3312  	}
  3313  	_, nErr := s.Store().Channel().Save(&o1, -1)
  3314  	s.Require().Nil(nErr)
  3315  
  3316  	_, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  3317  		ChannelId:   o1.Id,
  3318  		UserId:      userId,
  3319  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  3320  	})
  3321  	s.Require().Nil(err)
  3322  
  3323  	_, err = s.Store().Channel().SaveMember(&model.ChannelMember{
  3324  		ChannelId:   o1.Id,
  3325  		UserId:      otherUserId1,
  3326  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  3327  	})
  3328  	s.Require().Nil(err)
  3329  
  3330  	// o2 is a channel on the other team to which the user belongs
  3331  	o2 := model.Channel{
  3332  		TeamId:      otherTeamId,
  3333  		DisplayName: "Channel2",
  3334  		Name:        "zz" + model.NewId() + "b",
  3335  		Type:        model.CHANNEL_OPEN,
  3336  	}
  3337  	_, nErr = s.Store().Channel().Save(&o2, -1)
  3338  	s.Require().Nil(nErr)
  3339  
  3340  	_, err = s.Store().Channel().SaveMember(&model.ChannelMember{
  3341  		ChannelId:   o2.Id,
  3342  		UserId:      otherUserId2,
  3343  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  3344  	})
  3345  	s.Require().Nil(err)
  3346  
  3347  	// o3 is a channel on the team to which the user does not belong, and thus should show up
  3348  	// in "more channels"
  3349  	o3 := model.Channel{
  3350  		TeamId:      teamId,
  3351  		DisplayName: "ChannelA",
  3352  		Name:        "zz" + model.NewId() + "b",
  3353  		Type:        model.CHANNEL_OPEN,
  3354  	}
  3355  	_, nErr = s.Store().Channel().Save(&o3, -1)
  3356  	s.Require().Nil(nErr)
  3357  
  3358  	// o4 is a private channel on the team to which the user does not belong
  3359  	o4 := model.Channel{
  3360  		TeamId:      teamId,
  3361  		DisplayName: "ChannelB",
  3362  		Name:        "zz" + model.NewId() + "b",
  3363  		Type:        model.CHANNEL_PRIVATE,
  3364  	}
  3365  	_, nErr = s.Store().Channel().Save(&o4, -1)
  3366  	s.Require().Nil(nErr)
  3367  
  3368  	// o5 is another private channel on the team to which the user does belong
  3369  	o5 := model.Channel{
  3370  		TeamId:      teamId,
  3371  		DisplayName: "ChannelC",
  3372  		Name:        "zz" + model.NewId() + "b",
  3373  		Type:        model.CHANNEL_PRIVATE,
  3374  	}
  3375  	_, nErr = s.Store().Channel().Save(&o5, -1)
  3376  	s.Require().Nil(nErr)
  3377  
  3378  	_, err = s.Store().Channel().SaveMember(&model.ChannelMember{
  3379  		ChannelId:   o5.Id,
  3380  		UserId:      userId,
  3381  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  3382  	})
  3383  	s.Require().Nil(err)
  3384  
  3385  	s.T().Run("only o3 listed in more channels", func(t *testing.T) {
  3386  		list, channelErr := s.Store().Channel().GetMoreChannels(teamId, userId, 0, 100)
  3387  		s.Require().Nil(channelErr)
  3388  		s.Require().Equal(&model.ChannelList{&o3}, list)
  3389  	})
  3390  
  3391  	// o6 is another channel on the team to which the user does not belong, and would thus
  3392  	// start showing up in "more channels".
  3393  	o6 := model.Channel{
  3394  		TeamId:      teamId,
  3395  		DisplayName: "ChannelD",
  3396  		Name:        "zz" + model.NewId() + "b",
  3397  		Type:        model.CHANNEL_OPEN,
  3398  	}
  3399  	_, nErr = s.Store().Channel().Save(&o6, -1)
  3400  	s.Require().Nil(nErr)
  3401  
  3402  	// o7 is another channel on the team to which the user does not belong, but is deleted,
  3403  	// and thus would not start showing up in "more channels"
  3404  	o7 := model.Channel{
  3405  		TeamId:      teamId,
  3406  		DisplayName: "ChannelD",
  3407  		Name:        "zz" + model.NewId() + "b",
  3408  		Type:        model.CHANNEL_OPEN,
  3409  	}
  3410  	_, nErr = s.Store().Channel().Save(&o7, -1)
  3411  	s.Require().Nil(nErr)
  3412  
  3413  	nErr = s.Store().Channel().Delete(o7.Id, model.GetMillis())
  3414  	s.Require().Nil(nErr, "channel should have been deleted")
  3415  
  3416  	s.T().Run("both o3 and o6 listed in more channels", func(t *testing.T) {
  3417  		list, err := s.Store().Channel().GetMoreChannels(teamId, userId, 0, 100)
  3418  		s.Require().Nil(err)
  3419  		s.Require().Equal(&model.ChannelList{&o3, &o6}, list)
  3420  	})
  3421  
  3422  	s.T().Run("only o3 listed in more channels with offset 0, limit 1", func(t *testing.T) {
  3423  		list, err := s.Store().Channel().GetMoreChannels(teamId, userId, 0, 1)
  3424  		s.Require().Nil(err)
  3425  		s.Require().Equal(&model.ChannelList{&o3}, list)
  3426  	})
  3427  
  3428  	s.T().Run("only o6 listed in more channels with offset 1, limit 1", func(t *testing.T) {
  3429  		list, err := s.Store().Channel().GetMoreChannels(teamId, userId, 1, 1)
  3430  		s.Require().Nil(err)
  3431  		s.Require().Equal(&model.ChannelList{&o6}, list)
  3432  	})
  3433  
  3434  	s.T().Run("verify analytics for open channels", func(t *testing.T) {
  3435  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN)
  3436  		s.Require().Nil(err)
  3437  		s.Require().EqualValues(4, count)
  3438  	})
  3439  
  3440  	s.T().Run("verify analytics for private channels", func(t *testing.T) {
  3441  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE)
  3442  		s.Require().Nil(err)
  3443  		s.Require().EqualValues(2, count)
  3444  	})
  3445  }
  3446  
  3447  func (s *ChannelStoreTestSuite) TestStoreGetPrivateChannelsForTeam() {
  3448  	teamId := model.NewId()
  3449  
  3450  	// p1 is a private channel on the team
  3451  	p1 := model.Channel{
  3452  		TeamId:      teamId,
  3453  		DisplayName: "PrivateChannel1Team1",
  3454  		Name:        "zz" + model.NewId() + "b",
  3455  		Type:        model.CHANNEL_PRIVATE,
  3456  	}
  3457  	_, nErr := s.Store().Channel().Save(&p1, -1)
  3458  	s.Require().Nil(nErr)
  3459  
  3460  	// p2 is a private channel on another team
  3461  	p2 := model.Channel{
  3462  		TeamId:      model.NewId(),
  3463  		DisplayName: "PrivateChannel1Team2",
  3464  		Name:        "zz" + model.NewId() + "b",
  3465  		Type:        model.CHANNEL_PRIVATE,
  3466  	}
  3467  	_, nErr = s.Store().Channel().Save(&p2, -1)
  3468  	s.Require().Nil(nErr)
  3469  
  3470  	// o1 is a public channel on the team
  3471  	o1 := model.Channel{
  3472  		TeamId:      teamId,
  3473  		DisplayName: "OpenChannel1Team1",
  3474  		Name:        "zz" + model.NewId() + "b",
  3475  		Type:        model.CHANNEL_OPEN,
  3476  	}
  3477  	_, nErr = s.Store().Channel().Save(&o1, -1)
  3478  	s.Require().Nil(nErr)
  3479  
  3480  	s.T().Run("only p1 initially listed in private channels", func(t *testing.T) {
  3481  		list, channelErr := s.Store().Channel().GetPrivateChannelsForTeam(teamId, 0, 100)
  3482  		s.Require().Nil(channelErr)
  3483  		s.Require().Equal(&model.ChannelList{&p1}, list)
  3484  	})
  3485  
  3486  	// p3 is another private channel on the team
  3487  	p3 := model.Channel{
  3488  		TeamId:      teamId,
  3489  		DisplayName: "PrivateChannel2Team1",
  3490  		Name:        "zz" + model.NewId() + "b",
  3491  		Type:        model.CHANNEL_PRIVATE,
  3492  	}
  3493  	_, nErr = s.Store().Channel().Save(&p3, -1)
  3494  	s.Require().Nil(nErr)
  3495  
  3496  	// p4 is another private, but deleted channel on the team
  3497  	p4 := model.Channel{
  3498  		TeamId:      teamId,
  3499  		DisplayName: "PrivateChannel3Team1",
  3500  		Name:        "zz" + model.NewId() + "b",
  3501  		Type:        model.CHANNEL_PRIVATE,
  3502  	}
  3503  	_, nErr = s.Store().Channel().Save(&p4, -1)
  3504  	s.Require().Nil(nErr)
  3505  	err := s.Store().Channel().Delete(p4.Id, model.GetMillis())
  3506  	s.Require().Nil(err, "channel should have been deleted")
  3507  
  3508  	s.T().Run("both p1 and p3 listed in private channels", func(t *testing.T) {
  3509  		list, err := s.Store().Channel().GetPrivateChannelsForTeam(teamId, 0, 100)
  3510  		s.Require().Nil(err)
  3511  		s.Require().Equal(&model.ChannelList{&p1, &p3}, list)
  3512  	})
  3513  
  3514  	s.T().Run("only p1 listed in private channels with offset 0, limit 1", func(t *testing.T) {
  3515  		list, err := s.Store().Channel().GetPrivateChannelsForTeam(teamId, 0, 1)
  3516  		s.Require().Nil(err)
  3517  		s.Require().Equal(&model.ChannelList{&p1}, list)
  3518  	})
  3519  
  3520  	s.T().Run("only p3 listed in private channels with offset 1, limit 1", func(t *testing.T) {
  3521  		list, err := s.Store().Channel().GetPrivateChannelsForTeam(teamId, 1, 1)
  3522  		s.Require().Nil(err)
  3523  		s.Require().Equal(&model.ChannelList{&p3}, list)
  3524  	})
  3525  
  3526  	s.T().Run("verify analytics for private channels", func(t *testing.T) {
  3527  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE)
  3528  		s.Require().Nil(err)
  3529  		s.Require().EqualValues(3, count)
  3530  	})
  3531  
  3532  	s.T().Run("verify analytics for open open channels", func(t *testing.T) {
  3533  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN)
  3534  		s.Require().Nil(err)
  3535  		s.Require().EqualValues(1, count)
  3536  	})
  3537  }
  3538  
  3539  func (s *ChannelStoreTestSuite) TestStoreGetPublicChannelsForTeam() {
  3540  	teamId := model.NewId()
  3541  
  3542  	// o1 is a public channel on the team
  3543  	o1 := model.Channel{
  3544  		TeamId:      teamId,
  3545  		DisplayName: "OpenChannel1Team1",
  3546  		Name:        "zz" + model.NewId() + "b",
  3547  		Type:        model.CHANNEL_OPEN,
  3548  	}
  3549  	_, nErr := s.Store().Channel().Save(&o1, -1)
  3550  	s.Require().Nil(nErr)
  3551  
  3552  	// o2 is a public channel on another team
  3553  	o2 := model.Channel{
  3554  		TeamId:      model.NewId(),
  3555  		DisplayName: "OpenChannel1Team2",
  3556  		Name:        "zz" + model.NewId() + "b",
  3557  		Type:        model.CHANNEL_OPEN,
  3558  	}
  3559  	_, nErr = s.Store().Channel().Save(&o2, -1)
  3560  	s.Require().Nil(nErr)
  3561  
  3562  	// o3 is a private channel on the team
  3563  	o3 := model.Channel{
  3564  		TeamId:      teamId,
  3565  		DisplayName: "PrivateChannel1Team1",
  3566  		Name:        "zz" + model.NewId() + "b",
  3567  		Type:        model.CHANNEL_PRIVATE,
  3568  	}
  3569  	_, nErr = s.Store().Channel().Save(&o3, -1)
  3570  	s.Require().Nil(nErr)
  3571  
  3572  	s.T().Run("only o1 initially listed in public channels", func(t *testing.T) {
  3573  		list, channelErr := s.Store().Channel().GetPublicChannelsForTeam(teamId, 0, 100)
  3574  		s.Require().Nil(channelErr)
  3575  		s.Require().Equal(&model.ChannelList{&o1}, list)
  3576  	})
  3577  
  3578  	// o4 is another public channel on the team
  3579  	o4 := model.Channel{
  3580  		TeamId:      teamId,
  3581  		DisplayName: "OpenChannel2Team1",
  3582  		Name:        "zz" + model.NewId() + "b",
  3583  		Type:        model.CHANNEL_OPEN,
  3584  	}
  3585  	_, nErr = s.Store().Channel().Save(&o4, -1)
  3586  	s.Require().Nil(nErr)
  3587  
  3588  	// o5 is another public, but deleted channel on the team
  3589  	o5 := model.Channel{
  3590  		TeamId:      teamId,
  3591  		DisplayName: "OpenChannel3Team1",
  3592  		Name:        "zz" + model.NewId() + "b",
  3593  		Type:        model.CHANNEL_OPEN,
  3594  	}
  3595  	_, nErr = s.Store().Channel().Save(&o5, -1)
  3596  	s.Require().Nil(nErr)
  3597  	err := s.Store().Channel().Delete(o5.Id, model.GetMillis())
  3598  	s.Require().Nil(err, "channel should have been deleted")
  3599  
  3600  	s.T().Run("both o1 and o4 listed in public channels", func(t *testing.T) {
  3601  		list, err := s.Store().Channel().GetPublicChannelsForTeam(teamId, 0, 100)
  3602  		s.Require().Nil(err)
  3603  		s.Require().Equal(&model.ChannelList{&o1, &o4}, list)
  3604  	})
  3605  
  3606  	s.T().Run("only o1 listed in public channels with offset 0, limit 1", func(t *testing.T) {
  3607  		list, err := s.Store().Channel().GetPublicChannelsForTeam(teamId, 0, 1)
  3608  		s.Require().Nil(err)
  3609  		s.Require().Equal(&model.ChannelList{&o1}, list)
  3610  	})
  3611  
  3612  	s.T().Run("only o4 listed in public channels with offset 1, limit 1", func(t *testing.T) {
  3613  		list, err := s.Store().Channel().GetPublicChannelsForTeam(teamId, 1, 1)
  3614  		s.Require().Nil(err)
  3615  		s.Require().Equal(&model.ChannelList{&o4}, list)
  3616  	})
  3617  
  3618  	s.T().Run("verify analytics for open channels", func(t *testing.T) {
  3619  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN)
  3620  		s.Require().Nil(err)
  3621  		s.Require().EqualValues(3, count)
  3622  	})
  3623  
  3624  	s.T().Run("verify analytics for private channels", func(t *testing.T) {
  3625  		count, err := s.Store().Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE)
  3626  		s.Require().Nil(err)
  3627  		s.Require().EqualValues(1, count)
  3628  	})
  3629  }
  3630  
  3631  func (s *ChannelStoreTestSuite) TestStoreGetPublicChannelsByIdsForTeam() {
  3632  	teamId := model.NewId()
  3633  
  3634  	// oc1 is a public channel on the team
  3635  	oc1 := model.Channel{
  3636  		TeamId:      teamId,
  3637  		DisplayName: "OpenChannel1Team1",
  3638  		Name:        "zz" + model.NewId() + "b",
  3639  		Type:        model.CHANNEL_OPEN,
  3640  	}
  3641  	_, nErr := s.Store().Channel().Save(&oc1, -1)
  3642  	s.Require().Nil(nErr)
  3643  
  3644  	// oc2 is a public channel on another team
  3645  	oc2 := model.Channel{
  3646  		TeamId:      model.NewId(),
  3647  		DisplayName: "OpenChannel2TeamOther",
  3648  		Name:        "zz" + model.NewId() + "b",
  3649  		Type:        model.CHANNEL_OPEN,
  3650  	}
  3651  	_, nErr = s.Store().Channel().Save(&oc2, -1)
  3652  	s.Require().Nil(nErr)
  3653  
  3654  	// pc3 is a private channel on the team
  3655  	pc3 := model.Channel{
  3656  		TeamId:      teamId,
  3657  		DisplayName: "PrivateChannel3Team1",
  3658  		Name:        "zz" + model.NewId() + "b",
  3659  		Type:        model.CHANNEL_PRIVATE,
  3660  	}
  3661  	_, nErr = s.Store().Channel().Save(&pc3, -1)
  3662  	s.Require().Nil(nErr)
  3663  
  3664  	s.T().Run("oc1 by itself should be found as a public channel in the team", func(t *testing.T) {
  3665  		list, channelErr := s.Store().Channel().GetPublicChannelsByIdsForTeam(teamId, []string{oc1.Id})
  3666  		s.Require().Nil(channelErr)
  3667  		s.Require().Equal(&model.ChannelList{&oc1}, list)
  3668  	})
  3669  
  3670  	s.T().Run("only oc1, among others, should be found as a public channel in the team", func(t *testing.T) {
  3671  		list, channelErr := s.Store().Channel().GetPublicChannelsByIdsForTeam(teamId, []string{oc1.Id, oc2.Id, model.NewId(), pc3.Id})
  3672  		s.Require().Nil(channelErr)
  3673  		s.Require().Equal(&model.ChannelList{&oc1}, list)
  3674  	})
  3675  
  3676  	// oc4 is another public channel on the team
  3677  	oc4 := model.Channel{
  3678  		TeamId:      teamId,
  3679  		DisplayName: "OpenChannel4Team1",
  3680  		Name:        "zz" + model.NewId() + "b",
  3681  		Type:        model.CHANNEL_OPEN,
  3682  	}
  3683  	_, nErr = s.Store().Channel().Save(&oc4, -1)
  3684  	s.Require().Nil(nErr)
  3685  
  3686  	// oc4 is another public, but deleted channel on the team
  3687  	oc5 := model.Channel{
  3688  		TeamId:      teamId,
  3689  		DisplayName: "OpenChannel4Team1",
  3690  		Name:        "zz" + model.NewId() + "b",
  3691  		Type:        model.CHANNEL_OPEN,
  3692  	}
  3693  	_, nErr = s.Store().Channel().Save(&oc5, -1)
  3694  	s.Require().Nil(nErr)
  3695  
  3696  	err := s.Store().Channel().Delete(oc5.Id, model.GetMillis())
  3697  	s.Require().Nil(err, "channel should have been deleted")
  3698  
  3699  	s.T().Run("only oc1 and oc4, among others, should be found as a public channel in the team", func(t *testing.T) {
  3700  		list, err := s.Store().Channel().GetPublicChannelsByIdsForTeam(teamId, []string{oc1.Id, oc2.Id, model.NewId(), pc3.Id, oc4.Id})
  3701  		s.Require().Nil(err)
  3702  		s.Require().Equal(&model.ChannelList{&oc1, &oc4}, list)
  3703  	})
  3704  
  3705  	s.T().Run("random channel id should not be found as a public channel in the team", func(t *testing.T) {
  3706  		_, err := s.Store().Channel().GetPublicChannelsByIdsForTeam(teamId, []string{model.NewId()})
  3707  		s.Require().NotNil(err)
  3708  		var nfErr *store.ErrNotFound
  3709  		s.Require().True(errors.As(err, &nfErr))
  3710  	})
  3711  }
  3712  
  3713  func (s *ChannelStoreTestSuite) TestStoreGetChannelCounts() {
  3714  	o2 := model.Channel{}
  3715  	o2.TeamId = model.NewId()
  3716  	o2.DisplayName = "Channel2"
  3717  	o2.Name = "zz" + model.NewId() + "b"
  3718  	o2.Type = model.CHANNEL_OPEN
  3719  	_, nErr := s.Store().Channel().Save(&o2, -1)
  3720  	s.Require().Nil(nErr)
  3721  
  3722  	o1 := model.Channel{}
  3723  	o1.TeamId = model.NewId()
  3724  	o1.DisplayName = "Channel1"
  3725  	o1.Name = "zz" + model.NewId() + "b"
  3726  	o1.Type = model.CHANNEL_OPEN
  3727  	_, nErr = s.Store().Channel().Save(&o1, -1)
  3728  	s.Require().Nil(nErr)
  3729  
  3730  	m1 := model.ChannelMember{}
  3731  	m1.ChannelId = o1.Id
  3732  	m1.UserId = model.NewId()
  3733  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  3734  	_, err := s.Store().Channel().SaveMember(&m1)
  3735  	s.Require().Nil(err)
  3736  
  3737  	m2 := model.ChannelMember{}
  3738  	m2.ChannelId = o1.Id
  3739  	m2.UserId = model.NewId()
  3740  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  3741  	_, err = s.Store().Channel().SaveMember(&m2)
  3742  	s.Require().Nil(err)
  3743  
  3744  	m3 := model.ChannelMember{}
  3745  	m3.ChannelId = o2.Id
  3746  	m3.UserId = model.NewId()
  3747  	m3.NotifyProps = model.GetDefaultChannelNotifyProps()
  3748  	_, err = s.Store().Channel().SaveMember(&m3)
  3749  	s.Require().Nil(err)
  3750  
  3751  	counts, _ := s.Store().Channel().GetChannelCounts(o1.TeamId, m1.UserId)
  3752  
  3753  	s.Require().Len(counts.Counts, 1, "wrong number of counts")
  3754  	s.Require().Len(counts.UpdateTimes, 1, "wrong number of update times")
  3755  }
  3756  
  3757  func (s *ChannelStoreTestSuite) TestStoreGetMembersForUser() {
  3758  	t1 := model.Team{}
  3759  	t1.DisplayName = "Name"
  3760  	t1.Name = "zz" + model.NewId()
  3761  	t1.Email = MakeEmail()
  3762  	t1.Type = model.TEAM_OPEN
  3763  	_, err := s.Store().Team().Save(&t1)
  3764  	s.Require().Nil(err)
  3765  
  3766  	o1 := model.Channel{}
  3767  	o1.TeamId = t1.Id
  3768  	o1.DisplayName = "Channel1"
  3769  	o1.Name = "zz" + model.NewId() + "b"
  3770  	o1.Type = model.CHANNEL_OPEN
  3771  	_, nErr := s.Store().Channel().Save(&o1, -1)
  3772  	s.Require().Nil(nErr)
  3773  
  3774  	o2 := model.Channel{}
  3775  	o2.TeamId = o1.TeamId
  3776  	o2.DisplayName = "Channel2"
  3777  	o2.Name = "zz" + model.NewId() + "b"
  3778  	o2.Type = model.CHANNEL_OPEN
  3779  	_, nErr = s.Store().Channel().Save(&o2, -1)
  3780  	s.Require().Nil(nErr)
  3781  
  3782  	m1 := model.ChannelMember{}
  3783  	m1.ChannelId = o1.Id
  3784  	m1.UserId = model.NewId()
  3785  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  3786  	_, err = s.Store().Channel().SaveMember(&m1)
  3787  	s.Require().Nil(err)
  3788  
  3789  	m2 := model.ChannelMember{}
  3790  	m2.ChannelId = o2.Id
  3791  	m2.UserId = m1.UserId
  3792  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  3793  	_, err = s.Store().Channel().SaveMember(&m2)
  3794  	s.Require().Nil(err)
  3795  
  3796  	s.T().Run("with channels", func(t *testing.T) {
  3797  		var members *model.ChannelMembers
  3798  		members, err = s.Store().Channel().GetMembersForUser(o1.TeamId, m1.UserId)
  3799  		s.Require().Nil(err)
  3800  
  3801  		s.Assert().Len(*members, 2)
  3802  	})
  3803  
  3804  	s.T().Run("with channels and direct messages", func(t *testing.T) {
  3805  		user := model.User{Id: m1.UserId}
  3806  		u1 := model.User{Id: model.NewId()}
  3807  		u2 := model.User{Id: model.NewId()}
  3808  		u3 := model.User{Id: model.NewId()}
  3809  		u4 := model.User{Id: model.NewId()}
  3810  		_, nErr = s.Store().Channel().CreateDirectChannel(&u1, &user)
  3811  		s.Require().Nil(nErr)
  3812  		_, nErr = s.Store().Channel().CreateDirectChannel(&u2, &user)
  3813  		s.Require().Nil(nErr)
  3814  		// other user direct message
  3815  		_, nErr = s.Store().Channel().CreateDirectChannel(&u3, &u4)
  3816  		s.Require().Nil(nErr)
  3817  
  3818  		var members *model.ChannelMembers
  3819  		members, err = s.Store().Channel().GetMembersForUser(o1.TeamId, m1.UserId)
  3820  		s.Require().Nil(err)
  3821  
  3822  		s.Assert().Len(*members, 4)
  3823  	})
  3824  
  3825  	s.T().Run("with channels, direct channels and group messages", func(t *testing.T) {
  3826  		userIds := []string{model.NewId(), model.NewId(), model.NewId(), m1.UserId}
  3827  		group := &model.Channel{
  3828  			Name:        model.GetGroupNameFromUserIds(userIds),
  3829  			DisplayName: "test",
  3830  			Type:        model.CHANNEL_GROUP,
  3831  		}
  3832  		var channel *model.Channel
  3833  		channel, nErr = s.Store().Channel().Save(group, 10000)
  3834  		s.Require().Nil(nErr)
  3835  		for _, userId := range userIds {
  3836  			cm := &model.ChannelMember{
  3837  				UserId:      userId,
  3838  				ChannelId:   channel.Id,
  3839  				NotifyProps: model.GetDefaultChannelNotifyProps(),
  3840  				SchemeUser:  true,
  3841  			}
  3842  
  3843  			_, err = s.Store().Channel().SaveMember(cm)
  3844  			s.Require().Nil(err)
  3845  		}
  3846  		var members *model.ChannelMembers
  3847  		members, err = s.Store().Channel().GetMembersForUser(o1.TeamId, m1.UserId)
  3848  		s.Require().Nil(err)
  3849  
  3850  		s.Assert().Len(*members, 5)
  3851  	})
  3852  }
  3853  
  3854  func (s *ChannelStoreTestSuite) TestStoreGetMembersForUserWithPagination() {
  3855  	t1 := model.Team{}
  3856  	t1.DisplayName = "Name"
  3857  	t1.Name = "zz" + model.NewId()
  3858  	t1.Email = MakeEmail()
  3859  	t1.Type = model.TEAM_OPEN
  3860  	_, err := s.Store().Team().Save(&t1)
  3861  	s.Require().Nil(err)
  3862  
  3863  	o1 := model.Channel{}
  3864  	o1.TeamId = t1.Id
  3865  	o1.DisplayName = "Channel1"
  3866  	o1.Name = "zz" + model.NewId() + "b"
  3867  	o1.Type = model.CHANNEL_OPEN
  3868  	_, nErr := s.Store().Channel().Save(&o1, -1)
  3869  	s.Require().Nil(nErr)
  3870  
  3871  	o2 := model.Channel{}
  3872  	o2.TeamId = o1.TeamId
  3873  	o2.DisplayName = "Channel2"
  3874  	o2.Name = "zz" + model.NewId() + "b"
  3875  	o2.Type = model.CHANNEL_OPEN
  3876  	_, nErr = s.Store().Channel().Save(&o2, -1)
  3877  	s.Require().Nil(nErr)
  3878  
  3879  	m1 := model.ChannelMember{}
  3880  	m1.ChannelId = o1.Id
  3881  	m1.UserId = model.NewId()
  3882  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  3883  	_, err = s.Store().Channel().SaveMember(&m1)
  3884  	s.Require().Nil(err)
  3885  
  3886  	m2 := model.ChannelMember{}
  3887  	m2.ChannelId = o2.Id
  3888  	m2.UserId = m1.UserId
  3889  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  3890  	_, err = s.Store().Channel().SaveMember(&m2)
  3891  	s.Require().Nil(err)
  3892  
  3893  	members, err := s.Store().Channel().GetMembersForUserWithPagination(o1.TeamId, m1.UserId, 0, 1)
  3894  	s.Require().Nil(err)
  3895  	s.Assert().Len(*members, 1)
  3896  
  3897  	members, err = s.Store().Channel().GetMembersForUserWithPagination(o1.TeamId, m1.UserId, 1, 1)
  3898  	s.Require().Nil(err)
  3899  	s.Assert().Len(*members, 1)
  3900  }
  3901  
  3902  func (s *ChannelStoreTestSuite) TestCountPostsAfter() {
  3903  	s.T().Run("should count all posts with or without the given user ID", func(t *testing.T) {
  3904  		userId1 := model.NewId()
  3905  		userId2 := model.NewId()
  3906  
  3907  		channelId := model.NewId()
  3908  
  3909  		p1, err := s.Store().Post().Save(&model.Post{
  3910  			UserId:    userId1,
  3911  			ChannelId: channelId,
  3912  			CreateAt:  1000,
  3913  		})
  3914  		s.Require().Nil(err)
  3915  
  3916  		_, err = s.Store().Post().Save(&model.Post{
  3917  			UserId:    userId1,
  3918  			ChannelId: channelId,
  3919  			CreateAt:  1001,
  3920  		})
  3921  		s.Require().Nil(err)
  3922  
  3923  		_, err = s.Store().Post().Save(&model.Post{
  3924  			UserId:    userId2,
  3925  			ChannelId: channelId,
  3926  			CreateAt:  1002,
  3927  		})
  3928  		s.Require().Nil(err)
  3929  
  3930  		count, _, err := s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt-1, "")
  3931  		s.Require().Nil(err)
  3932  		s.Assert().Equal(3, count)
  3933  
  3934  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt, "")
  3935  		s.Require().Nil(err)
  3936  		s.Assert().Equal(2, count)
  3937  
  3938  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt-1, userId1)
  3939  		s.Require().Nil(err)
  3940  		s.Assert().Equal(2, count)
  3941  
  3942  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt, userId1)
  3943  		s.Require().Nil(err)
  3944  		s.Assert().Equal(1, count)
  3945  	})
  3946  
  3947  	s.T().Run("should not count deleted posts", func(t *testing.T) {
  3948  		userId1 := model.NewId()
  3949  
  3950  		channelId := model.NewId()
  3951  
  3952  		p1, err := s.Store().Post().Save(&model.Post{
  3953  			UserId:    userId1,
  3954  			ChannelId: channelId,
  3955  			CreateAt:  1000,
  3956  		})
  3957  		s.Require().Nil(err)
  3958  
  3959  		_, err = s.Store().Post().Save(&model.Post{
  3960  			UserId:    userId1,
  3961  			ChannelId: channelId,
  3962  			CreateAt:  1001,
  3963  			DeleteAt:  1001,
  3964  		})
  3965  		s.Require().Nil(err)
  3966  
  3967  		count, _, err := s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt-1, "")
  3968  		s.Require().Nil(err)
  3969  		s.Assert().Equal(1, count)
  3970  
  3971  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt, "")
  3972  		s.Require().Nil(err)
  3973  		s.Assert().Equal(0, count)
  3974  	})
  3975  
  3976  	s.T().Run("should count system/bot messages, but not join/leave messages", func(t *testing.T) {
  3977  		userId1 := model.NewId()
  3978  
  3979  		channelId := model.NewId()
  3980  
  3981  		p1, err := s.Store().Post().Save(&model.Post{
  3982  			UserId:    userId1,
  3983  			ChannelId: channelId,
  3984  			CreateAt:  1000,
  3985  		})
  3986  		s.Require().Nil(err)
  3987  
  3988  		_, err = s.Store().Post().Save(&model.Post{
  3989  			UserId:    userId1,
  3990  			ChannelId: channelId,
  3991  			CreateAt:  1001,
  3992  			Type:      model.POST_JOIN_CHANNEL,
  3993  		})
  3994  		s.Require().Nil(err)
  3995  
  3996  		_, err = s.Store().Post().Save(&model.Post{
  3997  			UserId:    userId1,
  3998  			ChannelId: channelId,
  3999  			CreateAt:  1002,
  4000  			Type:      model.POST_REMOVE_FROM_CHANNEL,
  4001  		})
  4002  		s.Require().Nil(err)
  4003  
  4004  		_, err = s.Store().Post().Save(&model.Post{
  4005  			UserId:    userId1,
  4006  			ChannelId: channelId,
  4007  			CreateAt:  1003,
  4008  			Type:      model.POST_LEAVE_TEAM,
  4009  		})
  4010  		s.Require().Nil(err)
  4011  
  4012  		p5, err := s.Store().Post().Save(&model.Post{
  4013  			UserId:    userId1,
  4014  			ChannelId: channelId,
  4015  			CreateAt:  1004,
  4016  			Type:      model.POST_HEADER_CHANGE,
  4017  		})
  4018  		s.Require().Nil(err)
  4019  
  4020  		_, err = s.Store().Post().Save(&model.Post{
  4021  			UserId:    userId1,
  4022  			ChannelId: channelId,
  4023  			CreateAt:  1005,
  4024  			Type:      "custom_nps_survey",
  4025  		})
  4026  		s.Require().Nil(err)
  4027  
  4028  		count, _, err := s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt-1, "")
  4029  		s.Require().Nil(err)
  4030  		s.Assert().Equal(3, count)
  4031  
  4032  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p1.CreateAt, "")
  4033  		s.Require().Nil(err)
  4034  		s.Assert().Equal(2, count)
  4035  
  4036  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p5.CreateAt-1, "")
  4037  		s.Require().Nil(err)
  4038  		s.Assert().Equal(2, count)
  4039  
  4040  		count, _, err = s.Store().Channel().CountPostsAfter(channelId, p5.CreateAt, "")
  4041  		s.Require().Nil(err)
  4042  		s.Assert().Equal(1, count)
  4043  	})
  4044  }
  4045  
  4046  func (s *ChannelStoreTestSuite) TestStoreUpdateLastViewedAt() {
  4047  	o1 := model.Channel{}
  4048  	o1.TeamId = model.NewId()
  4049  	o1.DisplayName = "Channel1"
  4050  	o1.Name = "zz" + model.NewId() + "b"
  4051  	o1.Type = model.CHANNEL_OPEN
  4052  	o1.TotalMsgCount = 25
  4053  	o1.LastPostAt = 12345
  4054  	_, nErr := s.Store().Channel().Save(&o1, -1)
  4055  	s.Require().Nil(nErr)
  4056  
  4057  	m1 := model.ChannelMember{}
  4058  	m1.ChannelId = o1.Id
  4059  	m1.UserId = model.NewId()
  4060  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  4061  	_, err := s.Store().Channel().SaveMember(&m1)
  4062  	s.Require().Nil(err)
  4063  
  4064  	o2 := model.Channel{}
  4065  	o2.TeamId = model.NewId()
  4066  	o2.DisplayName = "Channel1"
  4067  	o2.Name = "zz" + model.NewId() + "c"
  4068  	o2.Type = model.CHANNEL_OPEN
  4069  	o2.TotalMsgCount = 26
  4070  	o2.LastPostAt = 123456
  4071  	_, nErr = s.Store().Channel().Save(&o2, -1)
  4072  	s.Require().Nil(nErr)
  4073  
  4074  	m2 := model.ChannelMember{}
  4075  	m2.ChannelId = o2.Id
  4076  	m2.UserId = m1.UserId
  4077  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  4078  	_, err = s.Store().Channel().SaveMember(&m2)
  4079  	s.Require().Nil(err)
  4080  
  4081  	var times map[string]int64
  4082  	times, err = s.Store().Channel().UpdateLastViewedAt([]string{m1.ChannelId}, m1.UserId, false)
  4083  	s.Require().Nil(err, "failed to update ", err)
  4084  	s.Require().Equal(o1.LastPostAt, times[o1.Id], "last viewed at time incorrect")
  4085  
  4086  	times, err = s.Store().Channel().UpdateLastViewedAt([]string{m1.ChannelId, m2.ChannelId}, m1.UserId, false)
  4087  	s.Require().Nil(err, "failed to update ", err)
  4088  	s.Require().Equal(o2.LastPostAt, times[o2.Id], "last viewed at time incorrect")
  4089  
  4090  	rm1, err := s.Store().Channel().GetMember(context.Background(), m1.ChannelId, m1.UserId)
  4091  	s.Assert().Nil(err)
  4092  	s.Assert().Equal(o1.LastPostAt, rm1.LastViewedAt)
  4093  	s.Assert().Equal(o1.LastPostAt, rm1.LastUpdateAt)
  4094  	s.Assert().Equal(o1.TotalMsgCount, rm1.MsgCount)
  4095  
  4096  	rm2, err := s.Store().Channel().GetMember(context.Background(), m2.ChannelId, m2.UserId)
  4097  	s.Assert().Nil(err)
  4098  	s.Assert().Equal(o2.LastPostAt, rm2.LastViewedAt)
  4099  	s.Assert().Equal(o2.LastPostAt, rm2.LastUpdateAt)
  4100  	s.Assert().Equal(o2.TotalMsgCount, rm2.MsgCount)
  4101  
  4102  	_, err = s.Store().Channel().UpdateLastViewedAt([]string{m1.ChannelId}, "missing id", false)
  4103  	s.Require().Nil(err, "failed to update")
  4104  }
  4105  
  4106  func (s *ChannelStoreTestSuite) TestStoreIncrementMentionCount() {
  4107  	o1 := model.Channel{}
  4108  	o1.TeamId = model.NewId()
  4109  	o1.DisplayName = "Channel1"
  4110  	o1.Name = "zz" + model.NewId() + "b"
  4111  	o1.Type = model.CHANNEL_OPEN
  4112  	o1.TotalMsgCount = 25
  4113  	_, nErr := s.Store().Channel().Save(&o1, -1)
  4114  	s.Require().Nil(nErr)
  4115  
  4116  	m1 := model.ChannelMember{}
  4117  	m1.ChannelId = o1.Id
  4118  	m1.UserId = model.NewId()
  4119  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  4120  	_, err := s.Store().Channel().SaveMember(&m1)
  4121  	s.Require().Nil(err)
  4122  
  4123  	err = s.Store().Channel().IncrementMentionCount(m1.ChannelId, m1.UserId, false, false)
  4124  	s.Require().Nil(err, "failed to update")
  4125  
  4126  	err = s.Store().Channel().IncrementMentionCount(m1.ChannelId, "missing id", false, false)
  4127  	s.Require().Nil(err, "failed to update")
  4128  
  4129  	err = s.Store().Channel().IncrementMentionCount("missing id", m1.UserId, false, false)
  4130  	s.Require().Nil(err, "failed to update")
  4131  
  4132  	err = s.Store().Channel().IncrementMentionCount("missing id", "missing id", false, false)
  4133  	s.Require().Nil(err, "failed to update")
  4134  }
  4135  
  4136  func (s *ChannelStoreTestSuite) TestUpdateChannelMember() {
  4137  	userId := model.NewId()
  4138  
  4139  	c1 := &model.Channel{
  4140  		TeamId:      model.NewId(),
  4141  		DisplayName: model.NewId(),
  4142  		Name:        model.NewId(),
  4143  		Type:        model.CHANNEL_OPEN,
  4144  	}
  4145  	_, nErr := s.Store().Channel().Save(c1, -1)
  4146  	s.Require().Nil(nErr)
  4147  
  4148  	m1 := &model.ChannelMember{
  4149  		ChannelId:   c1.Id,
  4150  		UserId:      userId,
  4151  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4152  	}
  4153  	_, err := s.Store().Channel().SaveMember(m1)
  4154  	s.Require().Nil(err)
  4155  
  4156  	m1.NotifyProps["test"] = "sometext"
  4157  	_, err = s.Store().Channel().UpdateMember(m1)
  4158  	s.Require().Nil(err, err)
  4159  
  4160  	m1.UserId = ""
  4161  	_, err = s.Store().Channel().UpdateMember(m1)
  4162  	s.Require().NotNil(err, "bad user id - should fail")
  4163  }
  4164  
  4165  func (s *ChannelStoreTestSuite) TestGetMember() {
  4166  	userId := model.NewId()
  4167  
  4168  	c1 := &model.Channel{
  4169  		TeamId:      model.NewId(),
  4170  		DisplayName: model.NewId(),
  4171  		Name:        model.NewId(),
  4172  		Type:        model.CHANNEL_OPEN,
  4173  	}
  4174  	_, nErr := s.Store().Channel().Save(c1, -1)
  4175  	s.Require().Nil(nErr)
  4176  
  4177  	c2 := &model.Channel{
  4178  		TeamId:      c1.TeamId,
  4179  		DisplayName: model.NewId(),
  4180  		Name:        model.NewId(),
  4181  		Type:        model.CHANNEL_OPEN,
  4182  	}
  4183  	_, nErr = s.Store().Channel().Save(c2, -1)
  4184  	s.Require().Nil(nErr)
  4185  
  4186  	m1 := &model.ChannelMember{
  4187  		ChannelId:   c1.Id,
  4188  		UserId:      userId,
  4189  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4190  	}
  4191  	_, err := s.Store().Channel().SaveMember(m1)
  4192  	s.Require().Nil(err)
  4193  
  4194  	m2 := &model.ChannelMember{
  4195  		ChannelId:   c2.Id,
  4196  		UserId:      userId,
  4197  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4198  	}
  4199  	_, err = s.Store().Channel().SaveMember(m2)
  4200  	s.Require().Nil(err)
  4201  
  4202  	_, err = s.Store().Channel().GetMember(context.Background(), model.NewId(), userId)
  4203  	s.Require().NotNil(err, "should've failed to get member for non-existent channel")
  4204  
  4205  	_, err = s.Store().Channel().GetMember(context.Background(), c1.Id, model.NewId())
  4206  	s.Require().NotNil(err, "should've failed to get member for non-existent user")
  4207  
  4208  	member, err := s.Store().Channel().GetMember(context.Background(), c1.Id, userId)
  4209  	s.Require().Nil(err, "shouldn't have errored when getting member", err)
  4210  	s.Require().Equal(c1.Id, member.ChannelId, "should've gotten member of channel 1")
  4211  	s.Require().Equal(userId, member.UserId, "should've have gotten member for user")
  4212  
  4213  	member, err = s.Store().Channel().GetMember(context.Background(), c2.Id, userId)
  4214  	s.Require().Nil(err, "should'nt have errored when getting member", err)
  4215  	s.Require().Equal(c2.Id, member.ChannelId, "should've gotten member of channel 2")
  4216  	s.Require().Equal(userId, member.UserId, "should've gotten member for user")
  4217  
  4218  	props, err := s.Store().Channel().GetAllChannelMembersNotifyPropsForChannel(c2.Id, false)
  4219  	s.Require().Nil(err, err)
  4220  	s.Require().NotEqual(0, len(props), "should not be empty")
  4221  
  4222  	props, err = s.Store().Channel().GetAllChannelMembersNotifyPropsForChannel(c2.Id, true)
  4223  	s.Require().Nil(err, err)
  4224  	s.Require().NotEqual(0, len(props), "should not be empty")
  4225  
  4226  	s.Store().Channel().InvalidateCacheForChannelMembersNotifyProps(c2.Id)
  4227  }
  4228  
  4229  func (s *ChannelStoreTestSuite) TestStoreGetMemberForPost() {
  4230  	ch := &model.Channel{
  4231  		TeamId:      model.NewId(),
  4232  		DisplayName: "Name",
  4233  		Name:        "zz" + model.NewId() + "b",
  4234  		Type:        model.CHANNEL_OPEN,
  4235  	}
  4236  
  4237  	o1, nErr := s.Store().Channel().Save(ch, -1)
  4238  	s.Require().Nil(nErr)
  4239  
  4240  	m1, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  4241  		ChannelId:   o1.Id,
  4242  		UserId:      model.NewId(),
  4243  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4244  	})
  4245  	s.Require().Nil(err)
  4246  
  4247  	p1, nErr := s.Store().Post().Save(&model.Post{
  4248  		UserId:    model.NewId(),
  4249  		ChannelId: o1.Id,
  4250  		Message:   "test",
  4251  	})
  4252  	s.Require().Nil(nErr)
  4253  
  4254  	r1, err := s.Store().Channel().GetMemberForPost(p1.Id, m1.UserId)
  4255  	s.Require().Nil(err, err)
  4256  	s.Require().Equal(m1.ToJson(), r1.ToJson(), "invalid returned channel member")
  4257  
  4258  	_, err = s.Store().Channel().GetMemberForPost(p1.Id, model.NewId())
  4259  	s.Require().NotNil(err, "shouldn't have returned a member")
  4260  }
  4261  
  4262  func (s *ChannelStoreTestSuite) TestGetMemberCount() {
  4263  	teamId := model.NewId()
  4264  
  4265  	c1 := model.Channel{
  4266  		TeamId:      teamId,
  4267  		DisplayName: "Channel1",
  4268  		Name:        "zz" + model.NewId() + "b",
  4269  		Type:        model.CHANNEL_OPEN,
  4270  	}
  4271  	_, nErr := s.Store().Channel().Save(&c1, -1)
  4272  	s.Require().Nil(nErr)
  4273  
  4274  	c2 := model.Channel{
  4275  		TeamId:      teamId,
  4276  		DisplayName: "Channel2",
  4277  		Name:        "zz" + model.NewId() + "b",
  4278  		Type:        model.CHANNEL_OPEN,
  4279  	}
  4280  	_, nErr = s.Store().Channel().Save(&c2, -1)
  4281  	s.Require().Nil(nErr)
  4282  
  4283  	u1 := &model.User{
  4284  		Email:    MakeEmail(),
  4285  		DeleteAt: 0,
  4286  	}
  4287  	_, err := s.Store().User().Save(u1)
  4288  	s.Require().Nil(err)
  4289  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u1.Id}, -1)
  4290  	s.Require().Nil(nErr)
  4291  
  4292  	m1 := model.ChannelMember{
  4293  		ChannelId:   c1.Id,
  4294  		UserId:      u1.Id,
  4295  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4296  	}
  4297  	_, nErr = s.Store().Channel().SaveMember(&m1)
  4298  	s.Require().Nil(nErr)
  4299  
  4300  	count, channelErr := s.Store().Channel().GetMemberCount(c1.Id, false)
  4301  	s.Require().Nilf(channelErr, "failed to get member count: %v", channelErr)
  4302  	s.Require().EqualValuesf(1, count, "got incorrect member count %v", count)
  4303  
  4304  	u2 := model.User{
  4305  		Email:    MakeEmail(),
  4306  		DeleteAt: 0,
  4307  	}
  4308  	_, err = s.Store().User().Save(&u2)
  4309  	s.Require().Nil(err)
  4310  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u2.Id}, -1)
  4311  	s.Require().Nil(nErr)
  4312  
  4313  	m2 := model.ChannelMember{
  4314  		ChannelId:   c1.Id,
  4315  		UserId:      u2.Id,
  4316  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4317  	}
  4318  	_, nErr = s.Store().Channel().SaveMember(&m2)
  4319  	s.Require().Nil(nErr)
  4320  
  4321  	count, channelErr = s.Store().Channel().GetMemberCount(c1.Id, false)
  4322  	s.Require().Nilf(channelErr, "failed to get member count: %v", channelErr)
  4323  	s.Require().EqualValuesf(2, count, "got incorrect member count %v", count)
  4324  
  4325  	// make sure members of other channels aren't counted
  4326  	u3 := model.User{
  4327  		Email:    MakeEmail(),
  4328  		DeleteAt: 0,
  4329  	}
  4330  	_, err = s.Store().User().Save(&u3)
  4331  	s.Require().Nil(err)
  4332  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1)
  4333  	s.Require().Nil(nErr)
  4334  
  4335  	m3 := model.ChannelMember{
  4336  		ChannelId:   c2.Id,
  4337  		UserId:      u3.Id,
  4338  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4339  	}
  4340  	_, nErr = s.Store().Channel().SaveMember(&m3)
  4341  	s.Require().Nil(nErr)
  4342  
  4343  	count, channelErr = s.Store().Channel().GetMemberCount(c1.Id, false)
  4344  	s.Require().Nilf(channelErr, "failed to get member count: %v", channelErr)
  4345  	s.Require().EqualValuesf(2, count, "got incorrect member count %v", count)
  4346  
  4347  	// make sure inactive users aren't counted
  4348  	u4 := &model.User{
  4349  		Email:    MakeEmail(),
  4350  		DeleteAt: 10000,
  4351  	}
  4352  	_, err = s.Store().User().Save(u4)
  4353  	s.Require().Nil(err)
  4354  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u4.Id}, -1)
  4355  	s.Require().Nil(nErr)
  4356  
  4357  	m4 := model.ChannelMember{
  4358  		ChannelId:   c1.Id,
  4359  		UserId:      u4.Id,
  4360  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4361  	}
  4362  	_, nErr = s.Store().Channel().SaveMember(&m4)
  4363  	s.Require().Nil(nErr)
  4364  
  4365  	count, nErr = s.Store().Channel().GetMemberCount(c1.Id, false)
  4366  	s.Require().Nilf(nErr, "failed to get member count: %v", nErr)
  4367  	s.Require().EqualValuesf(2, count, "got incorrect member count %v", count)
  4368  }
  4369  
  4370  func (s *ChannelStoreTestSuite) TestGetMemberCountsByGroup() {
  4371  	var memberCounts []*model.ChannelMemberCountByGroup
  4372  	teamId := model.NewId()
  4373  	g1 := &model.Group{
  4374  		Name:        model.NewString(model.NewId()),
  4375  		DisplayName: model.NewId(),
  4376  		Source:      model.GroupSourceLdap,
  4377  		RemoteId:    model.NewId(),
  4378  	}
  4379  	_, err := s.Store().Group().Create(g1)
  4380  	s.Require().Nil(err)
  4381  
  4382  	c1 := model.Channel{
  4383  		TeamId:      teamId,
  4384  		DisplayName: "Channel1",
  4385  		Name:        "zz" + model.NewId() + "b",
  4386  		Type:        model.CHANNEL_OPEN,
  4387  	}
  4388  	_, nErr := s.Store().Channel().Save(&c1, -1)
  4389  	s.Require().Nil(nErr)
  4390  
  4391  	u1 := &model.User{
  4392  		Timezone: timezones.DefaultUserTimezone(),
  4393  		Email:    MakeEmail(),
  4394  		DeleteAt: 0,
  4395  	}
  4396  	_, nErr = s.Store().User().Save(u1)
  4397  	s.Require().Nil(nErr)
  4398  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u1.Id}, -1)
  4399  	s.Require().Nil(nErr)
  4400  
  4401  	m1 := model.ChannelMember{
  4402  		ChannelId:   c1.Id,
  4403  		UserId:      u1.Id,
  4404  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4405  	}
  4406  	_, nErr = s.Store().Channel().SaveMember(&m1)
  4407  	s.Require().Nil(nErr)
  4408  
  4409  	s.T().Run("empty slice for channel with no groups", func(t *testing.T) {
  4410  		memberCounts, nErr = s.Store().Channel().GetMemberCountsByGroup(context.Background(), c1.Id, false)
  4411  		expectedMemberCounts := []*model.ChannelMemberCountByGroup{}
  4412  		s.Require().Nil(nErr)
  4413  		s.Require().Equal(expectedMemberCounts, memberCounts)
  4414  	})
  4415  
  4416  	_, err = s.Store().Group().UpsertMember(g1.Id, u1.Id)
  4417  	s.Require().Nil(err)
  4418  
  4419  	s.T().Run("returns memberCountsByGroup without timezones", func(t *testing.T) {
  4420  		memberCounts, nErr = s.Store().Channel().GetMemberCountsByGroup(context.Background(), c1.Id, false)
  4421  		expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  4422  			{
  4423  				GroupId:                     g1.Id,
  4424  				ChannelMemberCount:          1,
  4425  				ChannelMemberTimezonesCount: 0,
  4426  			},
  4427  		}
  4428  		s.Require().Nil(nErr)
  4429  		s.Require().Equal(expectedMemberCounts, memberCounts)
  4430  	})
  4431  
  4432  	s.T().Run("returns memberCountsByGroup with timezones when no timezones set", func(t *testing.T) {
  4433  		memberCounts, nErr = s.Store().Channel().GetMemberCountsByGroup(context.Background(), c1.Id, true)
  4434  		expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  4435  			{
  4436  				GroupId:                     g1.Id,
  4437  				ChannelMemberCount:          1,
  4438  				ChannelMemberTimezonesCount: 0,
  4439  			},
  4440  		}
  4441  		s.Require().Nil(nErr)
  4442  		s.Require().Equal(expectedMemberCounts, memberCounts)
  4443  	})
  4444  
  4445  	g2 := &model.Group{
  4446  		Name:        model.NewString(model.NewId()),
  4447  		DisplayName: model.NewId(),
  4448  		Source:      model.GroupSourceLdap,
  4449  		RemoteId:    model.NewId(),
  4450  	}
  4451  	_, err = s.Store().Group().Create(g2)
  4452  	s.Require().Nil(err)
  4453  
  4454  	// create 5 different users with 2 different timezones for group 2
  4455  	for i := 1; i <= 5; i++ {
  4456  		timeZone := timezones.DefaultUserTimezone()
  4457  		if i == 1 {
  4458  			timeZone["manualTimezone"] = "EDT"
  4459  			timeZone["useAutomaticTimezone"] = "false"
  4460  		}
  4461  
  4462  		u := &model.User{
  4463  			Timezone: timeZone,
  4464  			Email:    MakeEmail(),
  4465  			DeleteAt: 0,
  4466  		}
  4467  		_, nErr = s.Store().User().Save(u)
  4468  		s.Require().Nil(nErr)
  4469  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u.Id}, -1)
  4470  		s.Require().Nil(nErr)
  4471  
  4472  		m := model.ChannelMember{
  4473  			ChannelId:   c1.Id,
  4474  			UserId:      u.Id,
  4475  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4476  		}
  4477  		_, nErr = s.Store().Channel().SaveMember(&m)
  4478  		s.Require().Nil(nErr)
  4479  
  4480  		_, err = s.Store().Group().UpsertMember(g2.Id, u.Id)
  4481  		s.Require().Nil(err)
  4482  	}
  4483  
  4484  	g3 := &model.Group{
  4485  		Name:        model.NewString(model.NewId()),
  4486  		DisplayName: model.NewId(),
  4487  		Source:      model.GroupSourceLdap,
  4488  		RemoteId:    model.NewId(),
  4489  	}
  4490  
  4491  	_, err = s.Store().Group().Create(g3)
  4492  	s.Require().Nil(err)
  4493  
  4494  	// create 10 different users with 3 different timezones for group 3
  4495  	for i := 1; i <= 10; i++ {
  4496  		timeZone := timezones.DefaultUserTimezone()
  4497  
  4498  		if i == 1 || i == 2 {
  4499  			timeZone["manualTimezone"] = "EDT"
  4500  			timeZone["useAutomaticTimezone"] = "false"
  4501  		} else if i == 3 || i == 4 {
  4502  			timeZone["manualTimezone"] = "PST"
  4503  			timeZone["useAutomaticTimezone"] = "false"
  4504  		} else if i == 5 || i == 6 {
  4505  			timeZone["autoTimezone"] = "PST"
  4506  			timeZone["useAutomaticTimezone"] = "true"
  4507  		} else {
  4508  			// Give every user with auto timezone set to true a random manual timezone to ensure that manual timezone is not looked at if auto is set
  4509  			timeZone["useAutomaticTimezone"] = "true"
  4510  			timeZone["manualTimezone"] = "PST" + utils.RandomName(utils.Range{Begin: 5, End: 5}, utils.ALPHANUMERIC)
  4511  		}
  4512  
  4513  		u := &model.User{
  4514  			Timezone: timeZone,
  4515  			Email:    MakeEmail(),
  4516  			DeleteAt: 0,
  4517  		}
  4518  		_, nErr = s.Store().User().Save(u)
  4519  		s.Require().Nil(nErr)
  4520  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u.Id}, -1)
  4521  		s.Require().Nil(nErr)
  4522  
  4523  		m := model.ChannelMember{
  4524  			ChannelId:   c1.Id,
  4525  			UserId:      u.Id,
  4526  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4527  		}
  4528  		_, nErr = s.Store().Channel().SaveMember(&m)
  4529  		s.Require().Nil(nErr)
  4530  
  4531  		_, err = s.Store().Group().UpsertMember(g3.Id, u.Id)
  4532  		s.Require().Nil(err)
  4533  	}
  4534  
  4535  	s.T().Run("returns memberCountsByGroup for multiple groups with lots of users without timezones", func(t *testing.T) {
  4536  		memberCounts, nErr = s.Store().Channel().GetMemberCountsByGroup(context.Background(), c1.Id, false)
  4537  		expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  4538  			{
  4539  				GroupId:                     g1.Id,
  4540  				ChannelMemberCount:          1,
  4541  				ChannelMemberTimezonesCount: 0,
  4542  			},
  4543  			{
  4544  				GroupId:                     g2.Id,
  4545  				ChannelMemberCount:          5,
  4546  				ChannelMemberTimezonesCount: 0,
  4547  			},
  4548  			{
  4549  				GroupId:                     g3.Id,
  4550  				ChannelMemberCount:          10,
  4551  				ChannelMemberTimezonesCount: 0,
  4552  			},
  4553  		}
  4554  		s.Require().Nil(nErr)
  4555  		s.Require().ElementsMatch(expectedMemberCounts, memberCounts)
  4556  	})
  4557  
  4558  	s.T().Run("returns memberCountsByGroup for multiple groups with lots of users with timezones", func(t *testing.T) {
  4559  		memberCounts, nErr = s.Store().Channel().GetMemberCountsByGroup(context.Background(), c1.Id, true)
  4560  		expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  4561  			{
  4562  				GroupId:                     g1.Id,
  4563  				ChannelMemberCount:          1,
  4564  				ChannelMemberTimezonesCount: 0,
  4565  			},
  4566  			{
  4567  				GroupId:                     g2.Id,
  4568  				ChannelMemberCount:          5,
  4569  				ChannelMemberTimezonesCount: 1,
  4570  			},
  4571  			{
  4572  				GroupId:                     g3.Id,
  4573  				ChannelMemberCount:          10,
  4574  				ChannelMemberTimezonesCount: 3,
  4575  			},
  4576  		}
  4577  		s.Require().Nil(nErr)
  4578  		s.Require().ElementsMatch(expectedMemberCounts, memberCounts)
  4579  	})
  4580  }
  4581  
  4582  func (s *ChannelStoreTestSuite) TestGetGuestCount() {
  4583  	teamId := model.NewId()
  4584  
  4585  	c1 := model.Channel{
  4586  		TeamId:      teamId,
  4587  		DisplayName: "Channel1",
  4588  		Name:        "zz" + model.NewId() + "b",
  4589  		Type:        model.CHANNEL_OPEN,
  4590  	}
  4591  	_, nErr := s.Store().Channel().Save(&c1, -1)
  4592  	s.Require().Nil(nErr)
  4593  
  4594  	c2 := model.Channel{
  4595  		TeamId:      teamId,
  4596  		DisplayName: "Channel2",
  4597  		Name:        "zz" + model.NewId() + "b",
  4598  		Type:        model.CHANNEL_OPEN,
  4599  	}
  4600  	_, nErr = s.Store().Channel().Save(&c2, -1)
  4601  	s.Require().Nil(nErr)
  4602  
  4603  	s.T().Run("Regular member doesn't count", func(t *testing.T) {
  4604  		u1 := &model.User{
  4605  			Email:    MakeEmail(),
  4606  			DeleteAt: 0,
  4607  			Roles:    model.SYSTEM_USER_ROLE_ID,
  4608  		}
  4609  		_, err := s.Store().User().Save(u1)
  4610  		s.Require().Nil(err)
  4611  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u1.Id}, -1)
  4612  		s.Require().Nil(nErr)
  4613  
  4614  		m1 := model.ChannelMember{
  4615  			ChannelId:   c1.Id,
  4616  			UserId:      u1.Id,
  4617  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4618  			SchemeGuest: false,
  4619  		}
  4620  		_, nErr = s.Store().Channel().SaveMember(&m1)
  4621  		s.Require().Nil(nErr)
  4622  
  4623  		count, channelErr := s.Store().Channel().GetGuestCount(c1.Id, false)
  4624  		s.Require().Nil(channelErr)
  4625  		s.Require().Equal(int64(0), count)
  4626  	})
  4627  
  4628  	s.T().Run("Guest member does count", func(t *testing.T) {
  4629  		u2 := model.User{
  4630  			Email:    MakeEmail(),
  4631  			DeleteAt: 0,
  4632  			Roles:    model.SYSTEM_GUEST_ROLE_ID,
  4633  		}
  4634  		_, err := s.Store().User().Save(&u2)
  4635  		s.Require().Nil(err)
  4636  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u2.Id}, -1)
  4637  		s.Require().Nil(nErr)
  4638  
  4639  		m2 := model.ChannelMember{
  4640  			ChannelId:   c1.Id,
  4641  			UserId:      u2.Id,
  4642  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4643  			SchemeGuest: true,
  4644  		}
  4645  		_, nErr = s.Store().Channel().SaveMember(&m2)
  4646  		s.Require().Nil(nErr)
  4647  
  4648  		count, channelErr := s.Store().Channel().GetGuestCount(c1.Id, false)
  4649  		s.Require().Nil(channelErr)
  4650  		s.Require().Equal(int64(1), count)
  4651  	})
  4652  
  4653  	s.T().Run("make sure members of other channels aren't counted", func(t *testing.T) {
  4654  		u3 := model.User{
  4655  			Email:    MakeEmail(),
  4656  			DeleteAt: 0,
  4657  			Roles:    model.SYSTEM_GUEST_ROLE_ID,
  4658  		}
  4659  		_, err := s.Store().User().Save(&u3)
  4660  		s.Require().Nil(err)
  4661  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1)
  4662  		s.Require().Nil(nErr)
  4663  
  4664  		m3 := model.ChannelMember{
  4665  			ChannelId:   c2.Id,
  4666  			UserId:      u3.Id,
  4667  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4668  			SchemeGuest: true,
  4669  		}
  4670  		_, nErr = s.Store().Channel().SaveMember(&m3)
  4671  		s.Require().Nil(nErr)
  4672  
  4673  		count, channelErr := s.Store().Channel().GetGuestCount(c1.Id, false)
  4674  		s.Require().Nil(channelErr)
  4675  		s.Require().Equal(int64(1), count)
  4676  	})
  4677  
  4678  	s.T().Run("make sure inactive users aren't counted", func(t *testing.T) {
  4679  		u4 := &model.User{
  4680  			Email:    MakeEmail(),
  4681  			DeleteAt: 10000,
  4682  			Roles:    model.SYSTEM_GUEST_ROLE_ID,
  4683  		}
  4684  		_, err := s.Store().User().Save(u4)
  4685  		s.Require().Nil(err)
  4686  		_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u4.Id}, -1)
  4687  		s.Require().Nil(nErr)
  4688  
  4689  		m4 := model.ChannelMember{
  4690  			ChannelId:   c1.Id,
  4691  			UserId:      u4.Id,
  4692  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  4693  			SchemeGuest: true,
  4694  		}
  4695  		_, nErr = s.Store().Channel().SaveMember(&m4)
  4696  		s.Require().Nil(nErr)
  4697  
  4698  		count, channelErr := s.Store().Channel().GetGuestCount(c1.Id, false)
  4699  		s.Require().Nil(channelErr)
  4700  		s.Require().Equal(int64(1), count)
  4701  	})
  4702  }
  4703  
  4704  func (s *ChannelStoreTestSuite) TestStoreSearchMore() {
  4705  	teamId := model.NewId()
  4706  	otherTeamId := model.NewId()
  4707  
  4708  	o1 := model.Channel{
  4709  		TeamId:      teamId,
  4710  		DisplayName: "ChannelA",
  4711  		Name:        "zz" + model.NewId() + "b",
  4712  		Type:        model.CHANNEL_OPEN,
  4713  	}
  4714  	_, nErr := s.Store().Channel().Save(&o1, -1)
  4715  	s.Require().Nil(nErr)
  4716  
  4717  	m1 := model.ChannelMember{
  4718  		ChannelId:   o1.Id,
  4719  		UserId:      model.NewId(),
  4720  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4721  	}
  4722  	_, err := s.Store().Channel().SaveMember(&m1)
  4723  	s.Require().Nil(err)
  4724  
  4725  	m2 := model.ChannelMember{
  4726  		ChannelId:   o1.Id,
  4727  		UserId:      model.NewId(),
  4728  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4729  	}
  4730  	_, err = s.Store().Channel().SaveMember(&m2)
  4731  	s.Require().Nil(err)
  4732  
  4733  	o2 := model.Channel{
  4734  		TeamId:      otherTeamId,
  4735  		DisplayName: "Channel2",
  4736  		Name:        "zz" + model.NewId() + "b",
  4737  		Type:        model.CHANNEL_OPEN,
  4738  	}
  4739  	_, nErr = s.Store().Channel().Save(&o2, -1)
  4740  	s.Require().Nil(nErr)
  4741  
  4742  	m3 := model.ChannelMember{
  4743  		ChannelId:   o2.Id,
  4744  		UserId:      model.NewId(),
  4745  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4746  	}
  4747  	_, err = s.Store().Channel().SaveMember(&m3)
  4748  	s.Require().Nil(err)
  4749  
  4750  	o3 := model.Channel{
  4751  		TeamId:      teamId,
  4752  		DisplayName: "ChannelA",
  4753  		Name:        "zz" + model.NewId() + "b",
  4754  		Type:        model.CHANNEL_OPEN,
  4755  	}
  4756  	_, nErr = s.Store().Channel().Save(&o3, -1)
  4757  	s.Require().Nil(nErr)
  4758  
  4759  	o4 := model.Channel{
  4760  		TeamId:      teamId,
  4761  		DisplayName: "ChannelB",
  4762  		Name:        "zz" + model.NewId() + "b",
  4763  		Type:        model.CHANNEL_PRIVATE,
  4764  	}
  4765  	_, nErr = s.Store().Channel().Save(&o4, -1)
  4766  	s.Require().Nil(nErr)
  4767  
  4768  	o5 := model.Channel{
  4769  		TeamId:      teamId,
  4770  		DisplayName: "ChannelC",
  4771  		Name:        "zz" + model.NewId() + "b",
  4772  		Type:        model.CHANNEL_PRIVATE,
  4773  	}
  4774  	_, nErr = s.Store().Channel().Save(&o5, -1)
  4775  	s.Require().Nil(nErr)
  4776  
  4777  	o6 := model.Channel{
  4778  		TeamId:      teamId,
  4779  		DisplayName: "Off-Topic",
  4780  		Name:        "off-topic",
  4781  		Type:        model.CHANNEL_OPEN,
  4782  	}
  4783  	_, nErr = s.Store().Channel().Save(&o6, -1)
  4784  	s.Require().Nil(nErr)
  4785  
  4786  	o7 := model.Channel{
  4787  		TeamId:      teamId,
  4788  		DisplayName: "Off-Set",
  4789  		Name:        "off-set",
  4790  		Type:        model.CHANNEL_OPEN,
  4791  	}
  4792  	_, nErr = s.Store().Channel().Save(&o7, -1)
  4793  	s.Require().Nil(nErr)
  4794  
  4795  	o8 := model.Channel{
  4796  		TeamId:      teamId,
  4797  		DisplayName: "Off-Limit",
  4798  		Name:        "off-limit",
  4799  		Type:        model.CHANNEL_PRIVATE,
  4800  	}
  4801  	_, nErr = s.Store().Channel().Save(&o8, -1)
  4802  	s.Require().Nil(nErr)
  4803  
  4804  	o9 := model.Channel{
  4805  		TeamId:      teamId,
  4806  		DisplayName: "Channel With Purpose",
  4807  		Purpose:     "This can now be searchable!",
  4808  		Name:        "with-purpose",
  4809  		Type:        model.CHANNEL_OPEN,
  4810  	}
  4811  	_, nErr = s.Store().Channel().Save(&o9, -1)
  4812  	s.Require().Nil(nErr)
  4813  
  4814  	o10 := model.Channel{
  4815  		TeamId:      teamId,
  4816  		DisplayName: "ChannelA",
  4817  		Name:        "channel-a-deleted",
  4818  		Type:        model.CHANNEL_OPEN,
  4819  	}
  4820  	_, nErr = s.Store().Channel().Save(&o10, -1)
  4821  	s.Require().Nil(nErr)
  4822  
  4823  	o10.DeleteAt = model.GetMillis()
  4824  	o10.UpdateAt = o10.DeleteAt
  4825  	nErr = s.Store().Channel().Delete(o10.Id, o10.DeleteAt)
  4826  	s.Require().Nil(nErr, "channel should have been deleted")
  4827  
  4828  	s.T().Run("three public channels matching 'ChannelA', but already a member of one and one deleted", func(t *testing.T) {
  4829  		channels, err := s.Store().Channel().SearchMore(m1.UserId, teamId, "ChannelA")
  4830  		s.Require().Nil(err)
  4831  		s.Require().Equal(&model.ChannelList{&o3}, channels)
  4832  	})
  4833  
  4834  	s.T().Run("one public channels, but already a member", func(t *testing.T) {
  4835  		channels, err := s.Store().Channel().SearchMore(m1.UserId, teamId, o4.Name)
  4836  		s.Require().Nil(err)
  4837  		s.Require().Equal(&model.ChannelList{}, channels)
  4838  	})
  4839  
  4840  	s.T().Run("three matching channels, but only two public", func(t *testing.T) {
  4841  		channels, err := s.Store().Channel().SearchMore(m1.UserId, teamId, "off-")
  4842  		s.Require().Nil(err)
  4843  		s.Require().Equal(&model.ChannelList{&o7, &o6}, channels)
  4844  	})
  4845  
  4846  	s.T().Run("one channel matching 'off-topic'", func(t *testing.T) {
  4847  		channels, err := s.Store().Channel().SearchMore(m1.UserId, teamId, "off-topic")
  4848  		s.Require().Nil(err)
  4849  		s.Require().Equal(&model.ChannelList{&o6}, channels)
  4850  	})
  4851  
  4852  	s.T().Run("search purpose", func(t *testing.T) {
  4853  		channels, err := s.Store().Channel().SearchMore(m1.UserId, teamId, "now searchable")
  4854  		s.Require().Nil(err)
  4855  		s.Require().Equal(&model.ChannelList{&o9}, channels)
  4856  	})
  4857  }
  4858  
  4859  type ByChannelDisplayName model.ChannelList
  4860  
  4861  func (s ByChannelDisplayName) Len() int { return len(s) }
  4862  func (s ByChannelDisplayName) Swap(i, j int) {
  4863  	s[i], s[j] = s[j], s[i]
  4864  }
  4865  func (s ByChannelDisplayName) Less(i, j int) bool {
  4866  	if s[i].DisplayName != s[j].DisplayName {
  4867  		return s[i].DisplayName < s[j].DisplayName
  4868  	}
  4869  
  4870  	return s[i].Id < s[j].Id
  4871  }
  4872  
  4873  func (s *ChannelStoreTestSuite) TestStoreSearchArchivedInTeam() {
  4874  	teamId := model.NewId()
  4875  	userId := model.NewId()
  4876  
  4877  	s.T().Run("empty result", func(t *testing.T) {
  4878  		list, err := s.Store().Channel().SearchArchivedInTeam(teamId, "term", userId)
  4879  		s.Require().Nil(err)
  4880  		s.Require().NotNil(list)
  4881  		s.Require().Empty(list)
  4882  	})
  4883  
  4884  	s.T().Run("error", func(t *testing.T) {
  4885  		// trigger a SQL error
  4886  		s.SqlStore().GetMaster().Exec("ALTER TABLE Channels RENAME TO Channels_renamed")
  4887  		defer s.SqlStore().GetMaster().Exec("ALTER TABLE Channels_renamed RENAME TO Channels")
  4888  
  4889  		list, err := s.Store().Channel().SearchArchivedInTeam(teamId, "term", userId)
  4890  		s.Require().NotNil(err)
  4891  		s.Require().Nil(list)
  4892  	})
  4893  }
  4894  
  4895  func (s *ChannelStoreTestSuite) TestStoreSearchInTeam() {
  4896  	teamId := model.NewId()
  4897  	otherTeamId := model.NewId()
  4898  
  4899  	o1 := model.Channel{
  4900  		TeamId:      teamId,
  4901  		DisplayName: "ChannelA",
  4902  		Name:        "zz" + model.NewId() + "b",
  4903  		Type:        model.CHANNEL_OPEN,
  4904  	}
  4905  	_, nErr := s.Store().Channel().Save(&o1, -1)
  4906  	s.Require().Nil(nErr)
  4907  
  4908  	o2 := model.Channel{
  4909  		TeamId:      otherTeamId,
  4910  		DisplayName: "ChannelA",
  4911  		Name:        "zz" + model.NewId() + "b",
  4912  		Type:        model.CHANNEL_OPEN,
  4913  	}
  4914  	_, nErr = s.Store().Channel().Save(&o2, -1)
  4915  	s.Require().Nil(nErr)
  4916  
  4917  	m1 := model.ChannelMember{
  4918  		ChannelId:   o1.Id,
  4919  		UserId:      model.NewId(),
  4920  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4921  	}
  4922  	_, err := s.Store().Channel().SaveMember(&m1)
  4923  	s.Require().Nil(err)
  4924  
  4925  	m2 := model.ChannelMember{
  4926  		ChannelId:   o1.Id,
  4927  		UserId:      model.NewId(),
  4928  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4929  	}
  4930  	_, err = s.Store().Channel().SaveMember(&m2)
  4931  	s.Require().Nil(err)
  4932  
  4933  	m3 := model.ChannelMember{
  4934  		ChannelId:   o2.Id,
  4935  		UserId:      model.NewId(),
  4936  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  4937  	}
  4938  	_, err = s.Store().Channel().SaveMember(&m3)
  4939  	s.Require().Nil(err)
  4940  
  4941  	o3 := model.Channel{
  4942  		TeamId:      teamId,
  4943  		DisplayName: "ChannelA (alternate)",
  4944  		Name:        "zz" + model.NewId() + "b",
  4945  		Type:        model.CHANNEL_OPEN,
  4946  	}
  4947  	_, nErr = s.Store().Channel().Save(&o3, -1)
  4948  	s.Require().Nil(nErr)
  4949  
  4950  	o4 := model.Channel{
  4951  		TeamId:      teamId,
  4952  		DisplayName: "Channel B",
  4953  		Name:        "zz" + model.NewId() + "b",
  4954  		Type:        model.CHANNEL_PRIVATE,
  4955  	}
  4956  	_, nErr = s.Store().Channel().Save(&o4, -1)
  4957  	s.Require().Nil(nErr)
  4958  
  4959  	o5 := model.Channel{
  4960  		TeamId:      teamId,
  4961  		DisplayName: "Channel C",
  4962  		Name:        "zz" + model.NewId() + "b",
  4963  		Type:        model.CHANNEL_PRIVATE,
  4964  	}
  4965  	_, nErr = s.Store().Channel().Save(&o5, -1)
  4966  	s.Require().Nil(nErr)
  4967  
  4968  	o6 := model.Channel{
  4969  		TeamId:      teamId,
  4970  		DisplayName: "Off-Topic",
  4971  		Name:        "off-topic",
  4972  		Type:        model.CHANNEL_OPEN,
  4973  	}
  4974  	_, nErr = s.Store().Channel().Save(&o6, -1)
  4975  	s.Require().Nil(nErr)
  4976  
  4977  	o7 := model.Channel{
  4978  		TeamId:      teamId,
  4979  		DisplayName: "Off-Set",
  4980  		Name:        "off-set",
  4981  		Type:        model.CHANNEL_OPEN,
  4982  	}
  4983  	_, nErr = s.Store().Channel().Save(&o7, -1)
  4984  	s.Require().Nil(nErr)
  4985  
  4986  	o8 := model.Channel{
  4987  		TeamId:      teamId,
  4988  		DisplayName: "Off-Limit",
  4989  		Name:        "off-limit",
  4990  		Type:        model.CHANNEL_PRIVATE,
  4991  	}
  4992  	_, nErr = s.Store().Channel().Save(&o8, -1)
  4993  	s.Require().Nil(nErr)
  4994  
  4995  	o9 := model.Channel{
  4996  		TeamId:      teamId,
  4997  		DisplayName: "Town Square",
  4998  		Name:        "town-square",
  4999  		Type:        model.CHANNEL_OPEN,
  5000  	}
  5001  	_, nErr = s.Store().Channel().Save(&o9, -1)
  5002  	s.Require().Nil(nErr)
  5003  
  5004  	o10 := model.Channel{
  5005  		TeamId:      teamId,
  5006  		DisplayName: "The",
  5007  		Name:        "thename",
  5008  		Type:        model.CHANNEL_OPEN,
  5009  	}
  5010  	_, nErr = s.Store().Channel().Save(&o10, -1)
  5011  	s.Require().Nil(nErr)
  5012  
  5013  	o11 := model.Channel{
  5014  		TeamId:      teamId,
  5015  		DisplayName: "Native Mobile Apps",
  5016  		Name:        "native-mobile-apps",
  5017  		Type:        model.CHANNEL_OPEN,
  5018  	}
  5019  	_, nErr = s.Store().Channel().Save(&o11, -1)
  5020  	s.Require().Nil(nErr)
  5021  
  5022  	o12 := model.Channel{
  5023  		TeamId:      teamId,
  5024  		DisplayName: "ChannelZ",
  5025  		Purpose:     "This can now be searchable!",
  5026  		Name:        "with-purpose",
  5027  		Type:        model.CHANNEL_OPEN,
  5028  	}
  5029  	_, nErr = s.Store().Channel().Save(&o12, -1)
  5030  	s.Require().Nil(nErr)
  5031  
  5032  	o13 := model.Channel{
  5033  		TeamId:      teamId,
  5034  		DisplayName: "ChannelA (deleted)",
  5035  		Name:        model.NewId(),
  5036  		Type:        model.CHANNEL_OPEN,
  5037  	}
  5038  	_, nErr = s.Store().Channel().Save(&o13, -1)
  5039  	s.Require().Nil(nErr)
  5040  	o13.DeleteAt = model.GetMillis()
  5041  	o13.UpdateAt = o13.DeleteAt
  5042  	nErr = s.Store().Channel().Delete(o13.Id, o13.DeleteAt)
  5043  	s.Require().Nil(nErr, "channel should have been deleted")
  5044  
  5045  	testCases := []struct {
  5046  		Description     string
  5047  		TeamId          string
  5048  		Term            string
  5049  		IncludeDeleted  bool
  5050  		ExpectedResults *model.ChannelList
  5051  	}{
  5052  		{"ChannelA", teamId, "ChannelA", false, &model.ChannelList{&o1, &o3}},
  5053  		{"ChannelA, include deleted", teamId, "ChannelA", true, &model.ChannelList{&o1, &o3, &o13}},
  5054  		{"ChannelA, other team", otherTeamId, "ChannelA", false, &model.ChannelList{&o2}},
  5055  		{"empty string", teamId, "", false, &model.ChannelList{&o1, &o3, &o12, &o11, &o7, &o6, &o10, &o9}},
  5056  		{"no matches", teamId, "blargh", false, &model.ChannelList{}},
  5057  		{"prefix", teamId, "off-", false, &model.ChannelList{&o7, &o6}},
  5058  		{"full match with dash", teamId, "off-topic", false, &model.ChannelList{&o6}},
  5059  		{"town square", teamId, "town square", false, &model.ChannelList{&o9}},
  5060  		{"the in name", teamId, "thename", false, &model.ChannelList{&o10}},
  5061  		{"Mobile", teamId, "Mobile", false, &model.ChannelList{&o11}},
  5062  		{"search purpose", teamId, "now searchable", false, &model.ChannelList{&o12}},
  5063  		{"pipe ignored", teamId, "town square |", false, &model.ChannelList{&o9}},
  5064  	}
  5065  
  5066  	for name, search := range map[string]func(teamId string, term string, includeDeleted bool) (*model.ChannelList, error){
  5067  		"AutocompleteInTeam": s.Store().Channel().AutocompleteInTeam,
  5068  		"SearchInTeam":       s.Store().Channel().SearchInTeam,
  5069  	} {
  5070  		for _, testCase := range testCases {
  5071  			s.T().Run(name+"/"+testCase.Description, func(t *testing.T) {
  5072  				channels, err := search(testCase.TeamId, testCase.Term, testCase.IncludeDeleted)
  5073  				s.Require().Nil(err)
  5074  
  5075  				// AutoCompleteInTeam doesn't currently sort its output results.
  5076  				if name == "AutocompleteInTeam" {
  5077  					sort.Sort(ByChannelDisplayName(*channels))
  5078  				}
  5079  
  5080  				s.Require().Equal(testCase.ExpectedResults, channels)
  5081  			})
  5082  		}
  5083  	}
  5084  }
  5085  
  5086  func (s *ChannelStoreTestSuite) TestStoreSearchForUserInTeam() {
  5087  	userId := model.NewId()
  5088  	teamId := model.NewId()
  5089  	otherTeamId := model.NewId()
  5090  
  5091  	// create 4 channels for the same team and one for other team
  5092  	o1 := model.Channel{
  5093  		TeamId:      teamId,
  5094  		DisplayName: "test-dev-1",
  5095  		Name:        "zz" + model.NewId() + "b",
  5096  		Type:        model.CHANNEL_OPEN,
  5097  	}
  5098  	_, nErr := s.Store().Channel().Save(&o1, -1)
  5099  	s.Require().Nil(nErr)
  5100  
  5101  	o2 := model.Channel{
  5102  		TeamId:      teamId,
  5103  		DisplayName: "test-dev-2",
  5104  		Name:        "zz" + model.NewId() + "b",
  5105  		Type:        model.CHANNEL_OPEN,
  5106  	}
  5107  	_, nErr = s.Store().Channel().Save(&o2, -1)
  5108  	s.Require().Nil(nErr)
  5109  
  5110  	o3 := model.Channel{
  5111  		TeamId:      teamId,
  5112  		DisplayName: "dev-3",
  5113  		Name:        "zz" + model.NewId() + "b",
  5114  		Type:        model.CHANNEL_OPEN,
  5115  	}
  5116  	_, nErr = s.Store().Channel().Save(&o3, -1)
  5117  	s.Require().Nil(nErr)
  5118  
  5119  	o4 := model.Channel{
  5120  		TeamId:      teamId,
  5121  		DisplayName: "dev-4",
  5122  		Name:        "zz" + model.NewId() + "b",
  5123  		Type:        model.CHANNEL_OPEN,
  5124  	}
  5125  	_, nErr = s.Store().Channel().Save(&o4, -1)
  5126  	s.Require().Nil(nErr)
  5127  
  5128  	o5 := model.Channel{
  5129  		TeamId:      otherTeamId,
  5130  		DisplayName: "other-team-dev-5",
  5131  		Name:        "zz" + model.NewId() + "b",
  5132  		Type:        model.CHANNEL_OPEN,
  5133  	}
  5134  	_, nErr = s.Store().Channel().Save(&o5, -1)
  5135  	s.Require().Nil(nErr)
  5136  
  5137  	// add the user to the first 3 channels and the other team channel
  5138  	for _, c := range []model.Channel{o1, o2, o3, o5} {
  5139  		_, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  5140  			ChannelId:   c.Id,
  5141  			UserId:      userId,
  5142  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  5143  		})
  5144  		s.Require().Nil(err)
  5145  	}
  5146  
  5147  	searchAndCheck := func(term string, includeDeleted bool, expectedDisplayNames []string) {
  5148  		res, searchErr := s.Store().Channel().SearchForUserInTeam(userId, teamId, term, includeDeleted)
  5149  		s.Require().Nil(searchErr)
  5150  		s.Require().Len(*res, len(expectedDisplayNames))
  5151  
  5152  		resultDisplayNames := []string{}
  5153  		for _, c := range *res {
  5154  			resultDisplayNames = append(resultDisplayNames, c.DisplayName)
  5155  		}
  5156  		s.Require().ElementsMatch(expectedDisplayNames, resultDisplayNames)
  5157  	}
  5158  
  5159  	s.T().Run("Search for test, get channels 1 and 2", func(t *testing.T) {
  5160  		searchAndCheck("test", false, []string{o1.DisplayName, o2.DisplayName})
  5161  	})
  5162  
  5163  	s.T().Run("Search for dev, get channels 1, 2 and 3", func(t *testing.T) {
  5164  		searchAndCheck("dev", false, []string{o1.DisplayName, o2.DisplayName, o3.DisplayName})
  5165  	})
  5166  
  5167  	s.T().Run("After adding user to channel 4, search for dev, get channels 1, 2, 3 and 4", func(t *testing.T) {
  5168  		_, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  5169  			ChannelId:   o4.Id,
  5170  			UserId:      userId,
  5171  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  5172  		})
  5173  		s.Require().Nil(err)
  5174  
  5175  		searchAndCheck("dev", false, []string{o1.DisplayName, o2.DisplayName, o3.DisplayName, o4.DisplayName})
  5176  	})
  5177  
  5178  	s.T().Run("Mark channel 1 as deleted, search for dev, get channels 2, 3 and 4", func(t *testing.T) {
  5179  		o1.DeleteAt = model.GetMillis()
  5180  		o1.UpdateAt = o1.DeleteAt
  5181  		err := s.Store().Channel().Delete(o1.Id, o1.DeleteAt)
  5182  		s.Require().Nil(err)
  5183  
  5184  		searchAndCheck("dev", false, []string{o2.DisplayName, o3.DisplayName, o4.DisplayName})
  5185  	})
  5186  
  5187  	s.T().Run("With includeDeleted, search for dev, get channels 1, 2, 3 and 4", func(t *testing.T) {
  5188  		searchAndCheck("dev", true, []string{o1.DisplayName, o2.DisplayName, o3.DisplayName, o4.DisplayName})
  5189  	})
  5190  }
  5191  
  5192  func (s *ChannelStoreTestSuite) TestStoreSearchAllChannels() {
  5193  	s.cleanupChannels()
  5194  
  5195  	t1 := model.Team{}
  5196  	t1.DisplayName = "Name"
  5197  	t1.Name = "zz" + model.NewId()
  5198  	t1.Email = MakeEmail()
  5199  	t1.Type = model.TEAM_OPEN
  5200  	_, err := s.Store().Team().Save(&t1)
  5201  	s.Require().Nil(err)
  5202  
  5203  	t2 := model.Team{}
  5204  	t2.DisplayName = "Name2"
  5205  	t2.Name = "zz" + model.NewId()
  5206  	t2.Email = MakeEmail()
  5207  	t2.Type = model.TEAM_OPEN
  5208  	_, err = s.Store().Team().Save(&t2)
  5209  	s.Require().Nil(err)
  5210  
  5211  	o1 := model.Channel{
  5212  		TeamId:      t1.Id,
  5213  		DisplayName: "A1 ChannelA",
  5214  		Name:        "zz" + model.NewId() + "b",
  5215  		Type:        model.CHANNEL_OPEN,
  5216  	}
  5217  	_, nErr := s.Store().Channel().Save(&o1, -1)
  5218  	s.Require().Nil(nErr)
  5219  
  5220  	o2 := model.Channel{
  5221  		TeamId:      t2.Id,
  5222  		DisplayName: "A2 ChannelA",
  5223  		Name:        "zz" + model.NewId() + "b",
  5224  		Type:        model.CHANNEL_OPEN,
  5225  	}
  5226  	_, nErr = s.Store().Channel().Save(&o2, -1)
  5227  	s.Require().Nil(nErr)
  5228  
  5229  	m1 := model.ChannelMember{
  5230  		ChannelId:   o1.Id,
  5231  		UserId:      model.NewId(),
  5232  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  5233  	}
  5234  	_, err = s.Store().Channel().SaveMember(&m1)
  5235  	s.Require().Nil(err)
  5236  
  5237  	m2 := model.ChannelMember{
  5238  		ChannelId:   o1.Id,
  5239  		UserId:      model.NewId(),
  5240  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  5241  	}
  5242  	_, err = s.Store().Channel().SaveMember(&m2)
  5243  	s.Require().Nil(err)
  5244  
  5245  	m3 := model.ChannelMember{
  5246  		ChannelId:   o2.Id,
  5247  		UserId:      model.NewId(),
  5248  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  5249  	}
  5250  	_, err = s.Store().Channel().SaveMember(&m3)
  5251  	s.Require().Nil(err)
  5252  
  5253  	o3 := model.Channel{
  5254  		TeamId:      t1.Id,
  5255  		DisplayName: "A3 ChannelA (alternate)",
  5256  		Name:        "zz" + model.NewId() + "b",
  5257  		Type:        model.CHANNEL_OPEN,
  5258  	}
  5259  	_, nErr = s.Store().Channel().Save(&o3, -1)
  5260  	s.Require().Nil(nErr)
  5261  
  5262  	o4 := model.Channel{
  5263  		TeamId:      t1.Id,
  5264  		DisplayName: "A4 ChannelB",
  5265  		Name:        "zz" + model.NewId() + "b",
  5266  		Type:        model.CHANNEL_PRIVATE,
  5267  	}
  5268  	_, nErr = s.Store().Channel().Save(&o4, -1)
  5269  	s.Require().Nil(nErr)
  5270  
  5271  	o5 := model.Channel{
  5272  		TeamId:           t1.Id,
  5273  		DisplayName:      "A5 ChannelC",
  5274  		Name:             "zz" + model.NewId() + "b",
  5275  		Type:             model.CHANNEL_PRIVATE,
  5276  		GroupConstrained: model.NewBool(true),
  5277  	}
  5278  	_, nErr = s.Store().Channel().Save(&o5, -1)
  5279  	s.Require().Nil(nErr)
  5280  
  5281  	o6 := model.Channel{
  5282  		TeamId:      t1.Id,
  5283  		DisplayName: "A6 Off-Topic",
  5284  		Name:        "off-topic",
  5285  		Type:        model.CHANNEL_OPEN,
  5286  	}
  5287  	_, nErr = s.Store().Channel().Save(&o6, -1)
  5288  	s.Require().Nil(nErr)
  5289  
  5290  	o7 := model.Channel{
  5291  		TeamId:      t1.Id,
  5292  		DisplayName: "A7 Off-Set",
  5293  		Name:        "off-set",
  5294  		Type:        model.CHANNEL_OPEN,
  5295  	}
  5296  	_, nErr = s.Store().Channel().Save(&o7, -1)
  5297  	s.Require().Nil(nErr)
  5298  
  5299  	group := &model.Group{
  5300  		Name:        model.NewString(model.NewId()),
  5301  		DisplayName: model.NewId(),
  5302  		Source:      model.GroupSourceLdap,
  5303  		RemoteId:    model.NewId(),
  5304  	}
  5305  	_, err = s.Store().Group().Create(group)
  5306  	s.Require().Nil(err)
  5307  
  5308  	_, err = s.Store().Group().CreateGroupSyncable(model.NewGroupChannel(group.Id, o7.Id, true))
  5309  	s.Require().Nil(err)
  5310  
  5311  	o8 := model.Channel{
  5312  		TeamId:      t1.Id,
  5313  		DisplayName: "A8 Off-Limit",
  5314  		Name:        "off-limit",
  5315  		Type:        model.CHANNEL_PRIVATE,
  5316  	}
  5317  	_, nErr = s.Store().Channel().Save(&o8, -1)
  5318  	s.Require().Nil(nErr)
  5319  
  5320  	o9 := model.Channel{
  5321  		TeamId:      t1.Id,
  5322  		DisplayName: "A9 Town Square",
  5323  		Name:        "town-square",
  5324  		Type:        model.CHANNEL_OPEN,
  5325  	}
  5326  	_, nErr = s.Store().Channel().Save(&o9, -1)
  5327  	s.Require().Nil(nErr)
  5328  
  5329  	o10 := model.Channel{
  5330  		TeamId:      t1.Id,
  5331  		DisplayName: "B10 That",
  5332  		Name:        "that",
  5333  		Type:        model.CHANNEL_OPEN,
  5334  	}
  5335  	_, nErr = s.Store().Channel().Save(&o10, -1)
  5336  	s.Require().Nil(nErr)
  5337  
  5338  	o11 := model.Channel{
  5339  		TeamId:      t1.Id,
  5340  		DisplayName: "B11 Native Mobile Apps",
  5341  		Name:        "native-mobile-apps",
  5342  		Type:        model.CHANNEL_OPEN,
  5343  	}
  5344  	_, nErr = s.Store().Channel().Save(&o11, -1)
  5345  	s.Require().Nil(nErr)
  5346  
  5347  	o12 := model.Channel{
  5348  		TeamId:      t1.Id,
  5349  		DisplayName: "B12 ChannelZ",
  5350  		Purpose:     "This can now be searchable!",
  5351  		Name:        "with-purpose",
  5352  		Type:        model.CHANNEL_OPEN,
  5353  	}
  5354  	_, nErr = s.Store().Channel().Save(&o12, -1)
  5355  	s.Require().Nil(nErr)
  5356  
  5357  	o13 := model.Channel{
  5358  		TeamId:      t1.Id,
  5359  		DisplayName: "B13 ChannelA (deleted)",
  5360  		Name:        model.NewId(),
  5361  		Type:        model.CHANNEL_OPEN,
  5362  	}
  5363  	_, nErr = s.Store().Channel().Save(&o13, -1)
  5364  	s.Require().Nil(nErr)
  5365  
  5366  	o13.DeleteAt = model.GetMillis()
  5367  	o13.UpdateAt = o13.DeleteAt
  5368  	nErr = s.Store().Channel().Delete(o13.Id, o13.DeleteAt)
  5369  	s.Require().Nil(nErr, "channel should have been deleted")
  5370  
  5371  	o14 := model.Channel{
  5372  		TeamId:      t2.Id,
  5373  		DisplayName: "B14 FOOBARDISPLAYNAME",
  5374  		Name:        "whatever",
  5375  		Type:        model.CHANNEL_OPEN,
  5376  	}
  5377  	_, nErr = s.Store().Channel().Save(&o14, -1)
  5378  	s.Require().Nil(nErr)
  5379  	testCases := []struct {
  5380  		Description     string
  5381  		Term            string
  5382  		Opts            store.ChannelSearchOpts
  5383  		ExpectedResults *model.ChannelList
  5384  		TotalCount      int
  5385  	}{
  5386  		{"Search FooBar by display name", "bardisplay", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o14}, 1},
  5387  		{"Search FooBar by display name2", "foobar", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o14}, 1},
  5388  		{"Search FooBar by display name3", "displayname", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o14}, 1},
  5389  		{"Search FooBar by name", "what", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o14}, 1},
  5390  		{"Search FooBar by name2", "ever", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o14}, 1},
  5391  		{"ChannelA", "ChannelA", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o1, &o2, &o3}, 0},
  5392  		{"ChannelA, include deleted", "ChannelA", store.ChannelSearchOpts{IncludeDeleted: true}, &model.ChannelList{&o1, &o2, &o3, &o13}, 0},
  5393  		{"empty string", "", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o1, &o2, &o3, &o4, &o5, &o6, &o7, &o8, &o9, &o10, &o11, &o12, &o14}, 0},
  5394  		{"no matches", "blargh", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{}, 0},
  5395  		{"prefix", "off-", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o6, &o7, &o8}, 0},
  5396  		{"full match with dash", "off-topic", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o6}, 0},
  5397  		{"town square", "town square", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o9}, 0},
  5398  		{"that in name", "that", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o10}, 0},
  5399  		{"Mobile", "Mobile", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o11}, 0},
  5400  		{"search purpose", "now searchable", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o12}, 0},
  5401  		{"pipe ignored", "town square |", store.ChannelSearchOpts{IncludeDeleted: false}, &model.ChannelList{&o9}, 0},
  5402  		{"exclude defaults search 'off'", "off-", store.ChannelSearchOpts{IncludeDeleted: false, ExcludeChannelNames: []string{"off-topic"}}, &model.ChannelList{&o7, &o8}, 0},
  5403  		{"exclude defaults search 'town'", "town", store.ChannelSearchOpts{IncludeDeleted: false, ExcludeChannelNames: []string{"town-square"}}, &model.ChannelList{}, 0},
  5404  		{"exclude by group association", "off-", store.ChannelSearchOpts{IncludeDeleted: false, NotAssociatedToGroup: group.Id}, &model.ChannelList{&o6, &o8}, 0},
  5405  		{"paginate includes count", "off-", store.ChannelSearchOpts{IncludeDeleted: false, PerPage: model.NewInt(100)}, &model.ChannelList{&o6, &o7, &o8}, 3},
  5406  		{"paginate, page 2 correct entries and count", "off-", store.ChannelSearchOpts{IncludeDeleted: false, PerPage: model.NewInt(2), Page: model.NewInt(1)}, &model.ChannelList{&o8}, 3},
  5407  		{"Filter private", "", store.ChannelSearchOpts{IncludeDeleted: false, Private: true}, &model.ChannelList{&o4, &o5, &o8}, 3},
  5408  		{"Filter public", "", store.ChannelSearchOpts{IncludeDeleted: false, Public: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o6, &o7}, 10},
  5409  		{"Filter public and private", "", store.ChannelSearchOpts{IncludeDeleted: false, Public: true, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o4, &o5}, 13},
  5410  		{"Filter public and private and include deleted", "", store.ChannelSearchOpts{IncludeDeleted: true, Public: true, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o4, &o5}, 14},
  5411  		{"Filter group constrained", "", store.ChannelSearchOpts{IncludeDeleted: false, GroupConstrained: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o5}, 1},
  5412  		{"Filter exclude group constrained and include deleted", "", store.ChannelSearchOpts{IncludeDeleted: true, ExcludeGroupConstrained: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o4, &o6}, 13},
  5413  		{"Filter private and exclude group constrained", "", store.ChannelSearchOpts{IncludeDeleted: false, ExcludeGroupConstrained: true, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o4, &o8}, 2},
  5414  		{"Filter team 2", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t2.Id}, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o2, &o14}, 2},
  5415  		{"Filter team 2, private", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t2.Id}, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{}, 0},
  5416  		{"Filter team 1 and team 2, private", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t1.Id, t2.Id}, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o4, &o5, &o8}, 3},
  5417  		{"Filter team 1 and team 2, public and private", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t1.Id, t2.Id}, Public: true, Private: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o4, &o5}, 13},
  5418  		{"Filter team 1 and team 2, public and private and group constrained", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t1.Id, t2.Id}, Public: true, Private: true, GroupConstrained: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o5}, 1},
  5419  		{"Filter team 1 and team 2, public and private and exclude group constrained", "", store.ChannelSearchOpts{IncludeDeleted: false, TeamIds: []string{t1.Id, t2.Id}, Public: true, Private: true, ExcludeGroupConstrained: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o1, &o2, &o3, &o4, &o6}, 12},
  5420  		{"Filter deleted returns only deleted channels", "", store.ChannelSearchOpts{Deleted: true, Page: model.NewInt(0), PerPage: model.NewInt(5)}, &model.ChannelList{&o13}, 1},
  5421  	}
  5422  
  5423  	for _, testCase := range testCases {
  5424  		s.T().Run(testCase.Description, func(t *testing.T) {
  5425  			channels, count, err := s.Store().Channel().SearchAllChannels(testCase.Term, testCase.Opts)
  5426  			s.Require().Nil(err)
  5427  			s.Require().Equal(len(*testCase.ExpectedResults), len(*channels))
  5428  			for i, expected := range *testCase.ExpectedResults {
  5429  				s.Require().Equal(expected.Id, (*channels)[i].Id)
  5430  			}
  5431  			if testCase.Opts.Page != nil || testCase.Opts.PerPage != nil {
  5432  				s.Require().Equal(int64(testCase.TotalCount), count)
  5433  			}
  5434  		})
  5435  	}
  5436  }
  5437  
  5438  func (s *ChannelStoreTestSuite) TestStoreGetMembersByIds() {
  5439  	o1 := model.Channel{}
  5440  	o1.TeamId = model.NewId()
  5441  	o1.DisplayName = "ChannelA"
  5442  	o1.Name = "zz" + model.NewId() + "b"
  5443  	o1.Type = model.CHANNEL_OPEN
  5444  	_, nErr := s.Store().Channel().Save(&o1, -1)
  5445  	s.Require().Nil(nErr)
  5446  
  5447  	m1 := &model.ChannelMember{ChannelId: o1.Id, UserId: model.NewId(), NotifyProps: model.GetDefaultChannelNotifyProps()}
  5448  	_, err := s.Store().Channel().SaveMember(m1)
  5449  	s.Require().Nil(err)
  5450  
  5451  	var members *model.ChannelMembers
  5452  	members, nErr = s.Store().Channel().GetMembersByIds(m1.ChannelId, []string{m1.UserId})
  5453  	s.Require().Nil(nErr, nErr)
  5454  	rm1 := (*members)[0]
  5455  
  5456  	s.Require().Equal(m1.ChannelId, rm1.ChannelId, "bad team id")
  5457  	s.Require().Equal(m1.UserId, rm1.UserId, "bad user id")
  5458  
  5459  	m2 := &model.ChannelMember{ChannelId: o1.Id, UserId: model.NewId(), NotifyProps: model.GetDefaultChannelNotifyProps()}
  5460  	_, err = s.Store().Channel().SaveMember(m2)
  5461  	s.Require().Nil(err)
  5462  
  5463  	members, nErr = s.Store().Channel().GetMembersByIds(m1.ChannelId, []string{m1.UserId, m2.UserId, model.NewId()})
  5464  	s.Require().Nil(nErr, nErr)
  5465  	s.Require().Len(*members, 2, "return wrong number of results")
  5466  
  5467  	_, nErr = s.Store().Channel().GetMembersByIds(m1.ChannelId, []string{})
  5468  	s.Require().NotNil(nErr, "empty user ids - should have failed")
  5469  }
  5470  
  5471  func (s *ChannelStoreTestSuite) TestStoreGetMembersByChannelIds() {
  5472  	userId := model.NewId()
  5473  
  5474  	// Create a couple channels and add the user to them
  5475  	channel1, err := s.Store().Channel().Save(&model.Channel{
  5476  		TeamId:      model.NewId(),
  5477  		DisplayName: model.NewId(),
  5478  		Name:        model.NewId(),
  5479  		Type:        model.CHANNEL_OPEN,
  5480  	}, -1)
  5481  	s.Require().Nil(err)
  5482  
  5483  	channel2, err := s.Store().Channel().Save(&model.Channel{
  5484  		TeamId:      model.NewId(),
  5485  		DisplayName: model.NewId(),
  5486  		Name:        model.NewId(),
  5487  		Type:        model.CHANNEL_OPEN,
  5488  	}, -1)
  5489  	s.Require().Nil(err)
  5490  
  5491  	_, err = s.Store().Channel().SaveMember(&model.ChannelMember{
  5492  		ChannelId:   channel1.Id,
  5493  		UserId:      userId,
  5494  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  5495  	})
  5496  	s.Require().Nil(err)
  5497  
  5498  	_, err = s.Store().Channel().SaveMember(&model.ChannelMember{
  5499  		ChannelId:   channel2.Id,
  5500  		UserId:      userId,
  5501  		NotifyProps: model.GetDefaultChannelNotifyProps(),
  5502  	})
  5503  	s.Require().Nil(err)
  5504  
  5505  	s.T().Run("should return the user's members for the given channels", func(t *testing.T) {
  5506  		result, nErr := s.Store().Channel().GetMembersByChannelIds([]string{channel1.Id, channel2.Id}, userId)
  5507  		s.Require().Nil(nErr)
  5508  		s.Assert().Len(*result, 2)
  5509  
  5510  		s.Assert().Equal(userId, (*result)[0].UserId)
  5511  		s.Assert().True((*result)[0].ChannelId == channel1.Id || (*result)[1].ChannelId == channel1.Id)
  5512  		s.Assert().Equal(userId, (*result)[1].UserId)
  5513  		s.Assert().True((*result)[0].ChannelId == channel2.Id || (*result)[1].ChannelId == channel2.Id)
  5514  	})
  5515  
  5516  	s.T().Run("should not error or return anything for invalid channel IDs", func(t *testing.T) {
  5517  		result, nErr := s.Store().Channel().GetMembersByChannelIds([]string{model.NewId(), model.NewId()}, userId)
  5518  		s.Require().Nil(nErr)
  5519  		s.Assert().Len(*result, 0)
  5520  	})
  5521  
  5522  	s.T().Run("should not error or return anything for invalid user IDs", func(t *testing.T) {
  5523  		result, nErr := s.Store().Channel().GetMembersByChannelIds([]string{channel1.Id, channel2.Id}, model.NewId())
  5524  		s.Require().Nil(nErr)
  5525  		s.Assert().Len(*result, 0)
  5526  	})
  5527  }
  5528  
  5529  func (s *ChannelStoreTestSuite) TestStoreSearchGroupChannels() {
  5530  	// Users
  5531  	u1 := &model.User{}
  5532  	u1.Username = "user.one"
  5533  	u1.Email = MakeEmail()
  5534  	u1.Nickname = model.NewId()
  5535  	_, err := s.Store().User().Save(u1)
  5536  	s.Require().Nil(err)
  5537  
  5538  	u2 := &model.User{}
  5539  	u2.Username = "user.two"
  5540  	u2.Email = MakeEmail()
  5541  	u2.Nickname = model.NewId()
  5542  	_, err = s.Store().User().Save(u2)
  5543  	s.Require().Nil(err)
  5544  
  5545  	u3 := &model.User{}
  5546  	u3.Username = "user.three"
  5547  	u3.Email = MakeEmail()
  5548  	u3.Nickname = model.NewId()
  5549  	_, err = s.Store().User().Save(u3)
  5550  	s.Require().Nil(err)
  5551  
  5552  	u4 := &model.User{}
  5553  	u4.Username = "user.four"
  5554  	u4.Email = MakeEmail()
  5555  	u4.Nickname = model.NewId()
  5556  	_, err = s.Store().User().Save(u4)
  5557  	s.Require().Nil(err)
  5558  
  5559  	// Group channels
  5560  	userIds := []string{u1.Id, u2.Id, u3.Id}
  5561  	gc1 := model.Channel{}
  5562  	gc1.Name = model.GetGroupNameFromUserIds(userIds)
  5563  	gc1.DisplayName = "GroupChannel" + model.NewId()
  5564  	gc1.Type = model.CHANNEL_GROUP
  5565  	_, nErr := s.Store().Channel().Save(&gc1, -1)
  5566  	s.Require().Nil(nErr)
  5567  
  5568  	for _, userId := range userIds {
  5569  		_, nErr = s.Store().Channel().SaveMember(&model.ChannelMember{
  5570  			ChannelId:   gc1.Id,
  5571  			UserId:      userId,
  5572  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  5573  		})
  5574  		s.Require().Nil(nErr)
  5575  	}
  5576  
  5577  	userIds = []string{u1.Id, u4.Id}
  5578  	gc2 := model.Channel{}
  5579  	gc2.Name = model.GetGroupNameFromUserIds(userIds)
  5580  	gc2.DisplayName = "GroupChannel" + model.NewId()
  5581  	gc2.Type = model.CHANNEL_GROUP
  5582  	_, nErr = s.Store().Channel().Save(&gc2, -1)
  5583  	s.Require().Nil(nErr)
  5584  
  5585  	for _, userId := range userIds {
  5586  		_, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  5587  			ChannelId:   gc2.Id,
  5588  			UserId:      userId,
  5589  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  5590  		})
  5591  		s.Require().Nil(err)
  5592  	}
  5593  
  5594  	userIds = []string{u1.Id, u2.Id, u3.Id, u4.Id}
  5595  	gc3 := model.Channel{}
  5596  	gc3.Name = model.GetGroupNameFromUserIds(userIds)
  5597  	gc3.DisplayName = "GroupChannel" + model.NewId()
  5598  	gc3.Type = model.CHANNEL_GROUP
  5599  	_, nErr = s.Store().Channel().Save(&gc3, -1)
  5600  	s.Require().Nil(nErr)
  5601  
  5602  	for _, userId := range userIds {
  5603  		_, err := s.Store().Channel().SaveMember(&model.ChannelMember{
  5604  			ChannelId:   gc3.Id,
  5605  			UserId:      userId,
  5606  			NotifyProps: model.GetDefaultChannelNotifyProps(),
  5607  		})
  5608  		s.Require().Nil(err)
  5609  	}
  5610  
  5611  	defer func() {
  5612  		for _, gc := range []model.Channel{gc1, gc2, gc3} {
  5613  			s.Store().Channel().PermanentDeleteMembersByChannel(gc3.Id)
  5614  			s.Store().Channel().PermanentDelete(gc.Id)
  5615  		}
  5616  	}()
  5617  
  5618  	testCases := []struct {
  5619  		Name           string
  5620  		UserId         string
  5621  		Term           string
  5622  		ExpectedResult []string
  5623  	}{
  5624  		{
  5625  			Name:           "Get all group channels for user1",
  5626  			UserId:         u1.Id,
  5627  			Term:           "",
  5628  			ExpectedResult: []string{gc1.Id, gc2.Id, gc3.Id},
  5629  		},
  5630  		{
  5631  			Name:           "Get group channels for user1 and term 'three'",
  5632  			UserId:         u1.Id,
  5633  			Term:           "three",
  5634  			ExpectedResult: []string{gc1.Id, gc3.Id},
  5635  		},
  5636  		{
  5637  			Name:           "Get group channels for user1 and term 'four two'",
  5638  			UserId:         u1.Id,
  5639  			Term:           "four two",
  5640  			ExpectedResult: []string{gc3.Id},
  5641  		},
  5642  		{
  5643  			Name:           "Get all group channels for user2",
  5644  			UserId:         u2.Id,
  5645  			Term:           "",
  5646  			ExpectedResult: []string{gc1.Id, gc3.Id},
  5647  		},
  5648  		{
  5649  			Name:           "Get group channels for user2 and term 'four'",
  5650  			UserId:         u2.Id,
  5651  			Term:           "four",
  5652  			ExpectedResult: []string{gc3.Id},
  5653  		},
  5654  		{
  5655  			Name:           "Get all group channels for user4",
  5656  			UserId:         u4.Id,
  5657  			Term:           "",
  5658  			ExpectedResult: []string{gc2.Id, gc3.Id},
  5659  		},
  5660  		{
  5661  			Name:           "Get group channels for user4 and term 'one five'",
  5662  			UserId:         u4.Id,
  5663  			Term:           "one five",
  5664  			ExpectedResult: []string{},
  5665  		},
  5666  	}
  5667  
  5668  	for _, tc := range testCases {
  5669  		s.T().Run(tc.Name, func(t *testing.T) {
  5670  			result, err := s.Store().Channel().SearchGroupChannels(tc.UserId, tc.Term)
  5671  			s.Require().Nil(err)
  5672  
  5673  			resultIds := []string{}
  5674  			for _, gc := range *result {
  5675  				resultIds = append(resultIds, gc.Id)
  5676  			}
  5677  
  5678  			s.Require().ElementsMatch(tc.ExpectedResult, resultIds)
  5679  		})
  5680  	}
  5681  }
  5682  
  5683  func (s *ChannelStoreTestSuite) TestStoreAnalyticsDeletedTypeCount() {
  5684  	o1 := model.Channel{}
  5685  	o1.TeamId = model.NewId()
  5686  	o1.DisplayName = "ChannelA"
  5687  	o1.Name = "zz" + model.NewId() + "b"
  5688  	o1.Type = model.CHANNEL_OPEN
  5689  	_, nErr := s.Store().Channel().Save(&o1, -1)
  5690  	s.Require().Nil(nErr)
  5691  
  5692  	o2 := model.Channel{}
  5693  	o2.TeamId = model.NewId()
  5694  	o2.DisplayName = "Channel2"
  5695  	o2.Name = "zz" + model.NewId() + "b"
  5696  	o2.Type = model.CHANNEL_OPEN
  5697  	_, nErr = s.Store().Channel().Save(&o2, -1)
  5698  	s.Require().Nil(nErr)
  5699  
  5700  	p3 := model.Channel{}
  5701  	p3.TeamId = model.NewId()
  5702  	p3.DisplayName = "Channel3"
  5703  	p3.Name = "zz" + model.NewId() + "b"
  5704  	p3.Type = model.CHANNEL_PRIVATE
  5705  	_, nErr = s.Store().Channel().Save(&p3, -1)
  5706  	s.Require().Nil(nErr)
  5707  
  5708  	u1 := &model.User{}
  5709  	u1.Email = MakeEmail()
  5710  	u1.Nickname = model.NewId()
  5711  	_, err := s.Store().User().Save(u1)
  5712  	s.Require().Nil(err)
  5713  
  5714  	u2 := &model.User{}
  5715  	u2.Email = MakeEmail()
  5716  	u2.Nickname = model.NewId()
  5717  	_, err = s.Store().User().Save(u2)
  5718  	s.Require().Nil(err)
  5719  
  5720  	d4, nErr := s.Store().Channel().CreateDirectChannel(u1, u2)
  5721  	s.Require().Nil(nErr)
  5722  	defer func() {
  5723  		s.Store().Channel().PermanentDeleteMembersByChannel(d4.Id)
  5724  		s.Store().Channel().PermanentDelete(d4.Id)
  5725  	}()
  5726  
  5727  	var openStartCount int64
  5728  	openStartCount, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "O")
  5729  	s.Require().Nil(nErr, nErr)
  5730  
  5731  	var privateStartCount int64
  5732  	privateStartCount, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "P")
  5733  	s.Require().Nil(nErr, nErr)
  5734  
  5735  	var directStartCount int64
  5736  	directStartCount, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "D")
  5737  	s.Require().Nil(nErr, nErr)
  5738  
  5739  	nErr = s.Store().Channel().Delete(o1.Id, model.GetMillis())
  5740  	s.Require().Nil(nErr, "channel should have been deleted")
  5741  	nErr = s.Store().Channel().Delete(o2.Id, model.GetMillis())
  5742  	s.Require().Nil(nErr, "channel should have been deleted")
  5743  	nErr = s.Store().Channel().Delete(p3.Id, model.GetMillis())
  5744  	s.Require().Nil(nErr, "channel should have been deleted")
  5745  	nErr = s.Store().Channel().Delete(d4.Id, model.GetMillis())
  5746  	s.Require().Nil(nErr, "channel should have been deleted")
  5747  
  5748  	var count int64
  5749  
  5750  	count, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "O")
  5751  	s.Require().Nil(err, nErr)
  5752  	s.Assert().Equal(openStartCount+2, count, "Wrong open channel deleted count.")
  5753  
  5754  	count, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "P")
  5755  	s.Require().Nil(nErr, nErr)
  5756  	s.Assert().Equal(privateStartCount+1, count, "Wrong private channel deleted count.")
  5757  
  5758  	count, nErr = s.Store().Channel().AnalyticsDeletedTypeCount("", "D")
  5759  	s.Require().Nil(nErr, nErr)
  5760  	s.Assert().Equal(directStartCount+1, count, "Wrong direct channel deleted count.")
  5761  }
  5762  
  5763  func (s *ChannelStoreTestSuite) TestStoreGetPinnedPosts() {
  5764  	ch1 := &model.Channel{
  5765  		TeamId:      model.NewId(),
  5766  		DisplayName: "Name",
  5767  		Name:        "zz" + model.NewId() + "b",
  5768  		Type:        model.CHANNEL_OPEN,
  5769  	}
  5770  
  5771  	o1, nErr := s.Store().Channel().Save(ch1, -1)
  5772  	s.Require().Nil(nErr)
  5773  
  5774  	p1, err := s.Store().Post().Save(&model.Post{
  5775  		UserId:    model.NewId(),
  5776  		ChannelId: o1.Id,
  5777  		Message:   "test",
  5778  		IsPinned:  true,
  5779  	})
  5780  	s.Require().Nil(err)
  5781  
  5782  	pl, errGet := s.Store().Channel().GetPinnedPosts(o1.Id)
  5783  	s.Require().Nil(errGet, errGet)
  5784  	s.Require().NotNil(pl.Posts[p1.Id], "didn't return relevant pinned posts")
  5785  
  5786  	ch2 := &model.Channel{
  5787  		TeamId:      model.NewId(),
  5788  		DisplayName: "Name",
  5789  		Name:        "zz" + model.NewId() + "b",
  5790  		Type:        model.CHANNEL_OPEN,
  5791  	}
  5792  
  5793  	o2, nErr := s.Store().Channel().Save(ch2, -1)
  5794  	s.Require().Nil(nErr)
  5795  
  5796  	_, err = s.Store().Post().Save(&model.Post{
  5797  		UserId:    model.NewId(),
  5798  		ChannelId: o2.Id,
  5799  		Message:   "test",
  5800  	})
  5801  	s.Require().Nil(err)
  5802  
  5803  	pl, errGet = s.Store().Channel().GetPinnedPosts(o2.Id)
  5804  	s.Require().Nil(errGet, errGet)
  5805  	s.Require().Empty(pl.Posts, "wasn't supposed to return posts")
  5806  
  5807  	s.T().Run("with correct ReplyCount", func(t *testing.T) {
  5808  		channelId := model.NewId()
  5809  		userId := model.NewId()
  5810  
  5811  		post1, err := s.Store().Post().Save(&model.Post{
  5812  			ChannelId: channelId,
  5813  			UserId:    userId,
  5814  			Message:   "message",
  5815  			IsPinned:  true,
  5816  		})
  5817  		s.Require().Nil(err)
  5818  		time.Sleep(time.Millisecond)
  5819  
  5820  		post2, err := s.Store().Post().Save(&model.Post{
  5821  			ChannelId: channelId,
  5822  			UserId:    userId,
  5823  			Message:   "message",
  5824  			IsPinned:  true,
  5825  		})
  5826  		s.Require().Nil(err)
  5827  		time.Sleep(time.Millisecond)
  5828  
  5829  		post3, err := s.Store().Post().Save(&model.Post{
  5830  			ChannelId: channelId,
  5831  			UserId:    userId,
  5832  			ParentId:  post1.Id,
  5833  			RootId:    post1.Id,
  5834  			Message:   "message",
  5835  			IsPinned:  true,
  5836  		})
  5837  		s.Require().Nil(err)
  5838  		time.Sleep(time.Millisecond)
  5839  
  5840  		posts, err := s.Store().Channel().GetPinnedPosts(channelId)
  5841  		s.Require().Nil(err)
  5842  		s.Require().Len(posts.Posts, 3)
  5843  		s.Require().Equal(posts.Posts[post1.Id].ReplyCount, int64(1))
  5844  		s.Require().Equal(posts.Posts[post2.Id].ReplyCount, int64(0))
  5845  		s.Require().Equal(posts.Posts[post3.Id].ReplyCount, int64(1))
  5846  	})
  5847  }
  5848  
  5849  func (s *ChannelStoreTestSuite) TestStoreGetPinnedPostCount() {
  5850  	ch1 := &model.Channel{
  5851  		TeamId:      model.NewId(),
  5852  		DisplayName: "Name",
  5853  		Name:        "zz" + model.NewId() + "b",
  5854  		Type:        model.CHANNEL_OPEN,
  5855  	}
  5856  
  5857  	o1, nErr := s.Store().Channel().Save(ch1, -1)
  5858  	s.Require().Nil(nErr)
  5859  
  5860  	_, err := s.Store().Post().Save(&model.Post{
  5861  		UserId:    model.NewId(),
  5862  		ChannelId: o1.Id,
  5863  		Message:   "test",
  5864  		IsPinned:  true,
  5865  	})
  5866  	s.Require().Nil(err)
  5867  
  5868  	_, err = s.Store().Post().Save(&model.Post{
  5869  		UserId:    model.NewId(),
  5870  		ChannelId: o1.Id,
  5871  		Message:   "test",
  5872  		IsPinned:  true,
  5873  	})
  5874  	s.Require().Nil(err)
  5875  
  5876  	count, errGet := s.Store().Channel().GetPinnedPostCount(o1.Id, true)
  5877  	s.Require().Nil(errGet, errGet)
  5878  	s.Require().EqualValues(2, count, "didn't return right count")
  5879  
  5880  	ch2 := &model.Channel{
  5881  		TeamId:      model.NewId(),
  5882  		DisplayName: "Name",
  5883  		Name:        "zz" + model.NewId() + "b",
  5884  		Type:        model.CHANNEL_OPEN,
  5885  	}
  5886  
  5887  	o2, nErr := s.Store().Channel().Save(ch2, -1)
  5888  	s.Require().Nil(nErr)
  5889  
  5890  	_, err = s.Store().Post().Save(&model.Post{
  5891  		UserId:    model.NewId(),
  5892  		ChannelId: o2.Id,
  5893  		Message:   "test",
  5894  	})
  5895  	s.Require().Nil(err)
  5896  
  5897  	_, err = s.Store().Post().Save(&model.Post{
  5898  		UserId:    model.NewId(),
  5899  		ChannelId: o2.Id,
  5900  		Message:   "test",
  5901  	})
  5902  	s.Require().Nil(err)
  5903  
  5904  	count, errGet = s.Store().Channel().GetPinnedPostCount(o2.Id, true)
  5905  	s.Require().Nil(errGet, errGet)
  5906  	s.Require().EqualValues(0, count, "should return 0")
  5907  }
  5908  
  5909  func (s *ChannelStoreTestSuite) TestStoreMaxChannelsPerTeam() {
  5910  	channel := &model.Channel{
  5911  		TeamId:      model.NewId(),
  5912  		DisplayName: "Channel",
  5913  		Name:        model.NewId(),
  5914  		Type:        model.CHANNEL_OPEN,
  5915  	}
  5916  	_, nErr := s.Store().Channel().Save(channel, 0)
  5917  	s.Assert().NotNil(nErr)
  5918  	var ltErr *store.ErrLimitExceeded
  5919  	s.Assert().True(errors.As(nErr, &ltErr))
  5920  
  5921  	channel.Id = ""
  5922  	_, nErr = s.Store().Channel().Save(channel, 1)
  5923  	s.Assert().Nil(nErr)
  5924  }
  5925  
  5926  func (s *ChannelStoreTestSuite) TestStoreGetChannelsByScheme() {
  5927  	// Create some schemes.
  5928  	s1 := &model.Scheme{
  5929  		DisplayName: model.NewId(),
  5930  		Name:        model.NewId(),
  5931  		Description: model.NewId(),
  5932  		Scope:       model.SCHEME_SCOPE_CHANNEL,
  5933  	}
  5934  
  5935  	s2 := &model.Scheme{
  5936  		DisplayName: model.NewId(),
  5937  		Name:        model.NewId(),
  5938  		Description: model.NewId(),
  5939  		Scope:       model.SCHEME_SCOPE_CHANNEL,
  5940  	}
  5941  
  5942  	s1, err := s.Store().Scheme().Save(s1)
  5943  	s.Require().Nil(err)
  5944  	s2, err = s.Store().Scheme().Save(s2)
  5945  	s.Require().Nil(err)
  5946  
  5947  	// Create and save some teams.
  5948  	c1 := &model.Channel{
  5949  		TeamId:      model.NewId(),
  5950  		DisplayName: "Name",
  5951  		Name:        model.NewId(),
  5952  		Type:        model.CHANNEL_OPEN,
  5953  		SchemeId:    &s1.Id,
  5954  	}
  5955  
  5956  	c2 := &model.Channel{
  5957  		TeamId:      model.NewId(),
  5958  		DisplayName: "Name",
  5959  		Name:        model.NewId(),
  5960  		Type:        model.CHANNEL_OPEN,
  5961  		SchemeId:    &s1.Id,
  5962  	}
  5963  
  5964  	c3 := &model.Channel{
  5965  		TeamId:      model.NewId(),
  5966  		DisplayName: "Name",
  5967  		Name:        model.NewId(),
  5968  		Type:        model.CHANNEL_OPEN,
  5969  	}
  5970  
  5971  	_, _ = s.Store().Channel().Save(c1, 100)
  5972  	_, _ = s.Store().Channel().Save(c2, 100)
  5973  	_, _ = s.Store().Channel().Save(c3, 100)
  5974  
  5975  	// Get the channels by a valid Scheme ID.
  5976  	d1, err := s.Store().Channel().GetChannelsByScheme(s1.Id, 0, 100)
  5977  	s.Assert().Nil(err)
  5978  	s.Assert().Len(d1, 2)
  5979  
  5980  	// Get the channels by a valid Scheme ID where there aren't any matching Channel.
  5981  	d2, err := s.Store().Channel().GetChannelsByScheme(s2.Id, 0, 100)
  5982  	s.Assert().Nil(err)
  5983  	s.Assert().Empty(d2)
  5984  
  5985  	// Get the channels by an invalid Scheme ID.
  5986  	d3, err := s.Store().Channel().GetChannelsByScheme(model.NewId(), 0, 100)
  5987  	s.Assert().Nil(err)
  5988  	s.Assert().Empty(d3)
  5989  }
  5990  
  5991  func (s *ChannelStoreTestSuite) TestStoreMigrateChannelMembers() {
  5992  	s1 := model.NewId()
  5993  	c1 := &model.Channel{
  5994  		TeamId:      model.NewId(),
  5995  		DisplayName: "Name",
  5996  		Name:        model.NewId(),
  5997  		Type:        model.CHANNEL_OPEN,
  5998  		SchemeId:    &s1,
  5999  	}
  6000  	c1, _ = s.Store().Channel().Save(c1, 100)
  6001  
  6002  	cm1 := &model.ChannelMember{
  6003  		ChannelId:     c1.Id,
  6004  		UserId:        model.NewId(),
  6005  		ExplicitRoles: "channel_admin channel_user",
  6006  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6007  	}
  6008  	cm2 := &model.ChannelMember{
  6009  		ChannelId:     c1.Id,
  6010  		UserId:        model.NewId(),
  6011  		ExplicitRoles: "channel_user",
  6012  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6013  	}
  6014  	cm3 := &model.ChannelMember{
  6015  		ChannelId:     c1.Id,
  6016  		UserId:        model.NewId(),
  6017  		ExplicitRoles: "something_else",
  6018  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6019  	}
  6020  
  6021  	cm1, _ = s.Store().Channel().SaveMember(cm1)
  6022  	cm2, _ = s.Store().Channel().SaveMember(cm2)
  6023  	cm3, _ = s.Store().Channel().SaveMember(cm3)
  6024  
  6025  	lastDoneChannelId := strings.Repeat("0", 26)
  6026  	lastDoneUserId := strings.Repeat("0", 26)
  6027  
  6028  	for {
  6029  		data, err := s.Store().Channel().MigrateChannelMembers(lastDoneChannelId, lastDoneUserId)
  6030  		if s.Assert().Nil(err) {
  6031  			if data == nil {
  6032  				break
  6033  			}
  6034  			lastDoneChannelId = data["ChannelId"]
  6035  			lastDoneUserId = data["UserId"]
  6036  		}
  6037  	}
  6038  
  6039  	s.Store().Channel().ClearCaches()
  6040  
  6041  	cm1b, err := s.Store().Channel().GetMember(context.Background(), cm1.ChannelId, cm1.UserId)
  6042  	s.Assert().Nil(err)
  6043  	s.Assert().Equal("", cm1b.ExplicitRoles)
  6044  	s.Assert().False(cm1b.SchemeGuest)
  6045  	s.Assert().True(cm1b.SchemeUser)
  6046  	s.Assert().True(cm1b.SchemeAdmin)
  6047  
  6048  	cm2b, err := s.Store().Channel().GetMember(context.Background(), cm2.ChannelId, cm2.UserId)
  6049  	s.Assert().Nil(err)
  6050  	s.Assert().Equal("", cm2b.ExplicitRoles)
  6051  	s.Assert().False(cm1b.SchemeGuest)
  6052  	s.Assert().True(cm2b.SchemeUser)
  6053  	s.Assert().False(cm2b.SchemeAdmin)
  6054  
  6055  	cm3b, err := s.Store().Channel().GetMember(context.Background(), cm3.ChannelId, cm3.UserId)
  6056  	s.Assert().Nil(err)
  6057  	s.Assert().Equal("something_else", cm3b.ExplicitRoles)
  6058  	s.Assert().False(cm1b.SchemeGuest)
  6059  	s.Assert().False(cm3b.SchemeUser)
  6060  	s.Assert().False(cm3b.SchemeAdmin)
  6061  }
  6062  
  6063  func (s *ChannelStoreTestSuite) TestResetAllChannelSchemes() {
  6064  	s1 := &model.Scheme{
  6065  		Name:        model.NewId(),
  6066  		DisplayName: model.NewId(),
  6067  		Description: model.NewId(),
  6068  		Scope:       model.SCHEME_SCOPE_CHANNEL,
  6069  	}
  6070  	s1, err := s.Store().Scheme().Save(s1)
  6071  	s.Require().Nil(err)
  6072  
  6073  	c1 := &model.Channel{
  6074  		TeamId:      model.NewId(),
  6075  		DisplayName: "Name",
  6076  		Name:        model.NewId(),
  6077  		Type:        model.CHANNEL_OPEN,
  6078  		SchemeId:    &s1.Id,
  6079  	}
  6080  
  6081  	c2 := &model.Channel{
  6082  		TeamId:      model.NewId(),
  6083  		DisplayName: "Name",
  6084  		Name:        model.NewId(),
  6085  		Type:        model.CHANNEL_OPEN,
  6086  		SchemeId:    &s1.Id,
  6087  	}
  6088  
  6089  	c1, _ = s.Store().Channel().Save(c1, 100)
  6090  	c2, _ = s.Store().Channel().Save(c2, 100)
  6091  
  6092  	s.Assert().Equal(s1.Id, *c1.SchemeId)
  6093  	s.Assert().Equal(s1.Id, *c2.SchemeId)
  6094  
  6095  	err = s.Store().Channel().ResetAllChannelSchemes()
  6096  	s.Assert().Nil(err)
  6097  
  6098  	c1, _ = s.Store().Channel().Get(c1.Id, true)
  6099  	c2, _ = s.Store().Channel().Get(c2.Id, true)
  6100  
  6101  	s.Assert().Equal("", *c1.SchemeId)
  6102  	s.Assert().Equal("", *c2.SchemeId)
  6103  }
  6104  
  6105  func (s *ChannelStoreTestSuite) TestStoreClearAllCustomRoleAssignments() {
  6106  	c := &model.Channel{
  6107  		TeamId:      model.NewId(),
  6108  		DisplayName: "Name",
  6109  		Name:        model.NewId(),
  6110  		Type:        model.CHANNEL_OPEN,
  6111  	}
  6112  
  6113  	c, _ = s.Store().Channel().Save(c, 100)
  6114  
  6115  	m1 := &model.ChannelMember{
  6116  		ChannelId:     c.Id,
  6117  		UserId:        model.NewId(),
  6118  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6119  		ExplicitRoles: "system_user_access_token channel_user channel_admin",
  6120  	}
  6121  	m2 := &model.ChannelMember{
  6122  		ChannelId:     c.Id,
  6123  		UserId:        model.NewId(),
  6124  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6125  		ExplicitRoles: "channel_user custom_role channel_admin another_custom_role",
  6126  	}
  6127  	m3 := &model.ChannelMember{
  6128  		ChannelId:     c.Id,
  6129  		UserId:        model.NewId(),
  6130  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6131  		ExplicitRoles: "channel_user",
  6132  	}
  6133  	m4 := &model.ChannelMember{
  6134  		ChannelId:     c.Id,
  6135  		UserId:        model.NewId(),
  6136  		NotifyProps:   model.GetDefaultChannelNotifyProps(),
  6137  		ExplicitRoles: "custom_only",
  6138  	}
  6139  
  6140  	_, err := s.Store().Channel().SaveMember(m1)
  6141  	s.Require().Nil(err)
  6142  	_, err = s.Store().Channel().SaveMember(m2)
  6143  	s.Require().Nil(err)
  6144  	_, err = s.Store().Channel().SaveMember(m3)
  6145  	s.Require().Nil(err)
  6146  	_, err = s.Store().Channel().SaveMember(m4)
  6147  	s.Require().Nil(err)
  6148  
  6149  	s.Require().Nil(s.Store().Channel().ClearAllCustomRoleAssignments())
  6150  
  6151  	member, err := s.Store().Channel().GetMember(context.Background(), m1.ChannelId, m1.UserId)
  6152  	s.Require().Nil(err)
  6153  	s.Assert().Equal(m1.ExplicitRoles, member.Roles)
  6154  
  6155  	member, err = s.Store().Channel().GetMember(context.Background(), m2.ChannelId, m2.UserId)
  6156  	s.Require().Nil(err)
  6157  	s.Assert().Equal("channel_user channel_admin", member.Roles)
  6158  
  6159  	member, err = s.Store().Channel().GetMember(context.Background(), m3.ChannelId, m3.UserId)
  6160  	s.Require().Nil(err)
  6161  	s.Assert().Equal(m3.ExplicitRoles, member.Roles)
  6162  
  6163  	member, err = s.Store().Channel().GetMember(context.Background(), m4.ChannelId, m4.UserId)
  6164  	s.Require().Nil(err)
  6165  	s.Assert().Equal("", member.Roles)
  6166  }
  6167  
  6168  // testMaterializedPublicChannels tests edge cases involving the triggers and stored procedures
  6169  // that materialize the PublicChannels table.
  6170  func (s *ChannelStoreTestSuite) TestMaterializedPublicChannels() {
  6171  	teamId := model.NewId()
  6172  
  6173  	// o1 is a public channel on the team
  6174  	o1 := model.Channel{
  6175  		TeamId:      teamId,
  6176  		DisplayName: "Open Channel",
  6177  		Name:        model.NewId(),
  6178  		Type:        model.CHANNEL_OPEN,
  6179  	}
  6180  	_, nErr := s.Store().Channel().Save(&o1, -1)
  6181  	s.Require().Nil(nErr)
  6182  
  6183  	// o2 is another public channel on the team
  6184  	o2 := model.Channel{
  6185  		TeamId:      teamId,
  6186  		DisplayName: "Open Channel 2",
  6187  		Name:        model.NewId(),
  6188  		Type:        model.CHANNEL_OPEN,
  6189  	}
  6190  	_, nErr = s.Store().Channel().Save(&o2, -1)
  6191  	s.Require().Nil(nErr)
  6192  
  6193  	s.T().Run("o1 and o2 initially listed in public channels", func(t *testing.T) {
  6194  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6195  		s.Require().Nil(channelErr)
  6196  		s.Require().Equal(&model.ChannelList{&o1, &o2}, channels)
  6197  	})
  6198  
  6199  	o1.DeleteAt = model.GetMillis()
  6200  	o1.UpdateAt = o1.DeleteAt
  6201  
  6202  	e := s.Store().Channel().Delete(o1.Id, o1.DeleteAt)
  6203  	s.Require().Nil(e, "channel should have been deleted")
  6204  
  6205  	s.T().Run("o1 still listed in public channels when marked as deleted", func(t *testing.T) {
  6206  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6207  		s.Require().Nil(channelErr)
  6208  		s.Require().Equal(&model.ChannelList{&o1, &o2}, channels)
  6209  	})
  6210  
  6211  	s.Store().Channel().PermanentDelete(o1.Id)
  6212  
  6213  	s.T().Run("o1 no longer listed in public channels when permanently deleted", func(t *testing.T) {
  6214  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6215  		s.Require().Nil(channelErr)
  6216  		s.Require().Equal(&model.ChannelList{&o2}, channels)
  6217  	})
  6218  
  6219  	o2.Type = model.CHANNEL_PRIVATE
  6220  	_, appErr := s.Store().Channel().Update(&o2)
  6221  	s.Require().Nil(appErr)
  6222  
  6223  	s.T().Run("o2 no longer listed since now private", func(t *testing.T) {
  6224  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6225  		s.Require().Nil(channelErr)
  6226  		s.Require().Equal(&model.ChannelList{}, channels)
  6227  	})
  6228  
  6229  	o2.Type = model.CHANNEL_OPEN
  6230  	_, appErr = s.Store().Channel().Update(&o2)
  6231  	s.Require().Nil(appErr)
  6232  
  6233  	s.T().Run("o2 listed once again since now public", func(t *testing.T) {
  6234  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6235  		s.Require().Nil(channelErr)
  6236  		s.Require().Equal(&model.ChannelList{&o2}, channels)
  6237  	})
  6238  
  6239  	// o3 is a public channel on the team that already existed in the PublicChannels table.
  6240  	o3 := model.Channel{
  6241  		Id:          model.NewId(),
  6242  		TeamId:      teamId,
  6243  		DisplayName: "Open Channel 3",
  6244  		Name:        model.NewId(),
  6245  		Type:        model.CHANNEL_OPEN,
  6246  	}
  6247  
  6248  	_, execerr := s.SqlStore().GetMaster().ExecNoTimeout(`
  6249  		INSERT INTO
  6250  		    PublicChannels(Id, DeleteAt, TeamId, DisplayName, Name, Header, Purpose)
  6251  		VALUES
  6252  		    (:Id, :DeleteAt, :TeamId, :DisplayName, :Name, :Header, :Purpose);
  6253  	`, map[string]interface{}{
  6254  		"Id":          o3.Id,
  6255  		"DeleteAt":    o3.DeleteAt,
  6256  		"TeamId":      o3.TeamId,
  6257  		"DisplayName": o3.DisplayName,
  6258  		"Name":        o3.Name,
  6259  		"Header":      o3.Header,
  6260  		"Purpose":     o3.Purpose,
  6261  	})
  6262  	s.Require().Nil(execerr)
  6263  
  6264  	o3.DisplayName = "Open Channel 3 - Modified"
  6265  
  6266  	_, execerr = s.SqlStore().GetMaster().ExecNoTimeout(`
  6267  		INSERT INTO
  6268  		    Channels(Id, CreateAt, UpdateAt, DeleteAt, TeamId, Type, DisplayName, Name, Header, Purpose, LastPostAt, TotalMsgCount, ExtraUpdateAt, CreatorId)
  6269  		VALUES
  6270  		    (:Id, :CreateAt, :UpdateAt, :DeleteAt, :TeamId, :Type, :DisplayName, :Name, :Header, :Purpose, :LastPostAt, :TotalMsgCount, :ExtraUpdateAt, :CreatorId);
  6271  	`, map[string]interface{}{
  6272  		"Id":            o3.Id,
  6273  		"CreateAt":      o3.CreateAt,
  6274  		"UpdateAt":      o3.UpdateAt,
  6275  		"DeleteAt":      o3.DeleteAt,
  6276  		"TeamId":        o3.TeamId,
  6277  		"Type":          o3.Type,
  6278  		"DisplayName":   o3.DisplayName,
  6279  		"Name":          o3.Name,
  6280  		"Header":        o3.Header,
  6281  		"Purpose":       o3.Purpose,
  6282  		"LastPostAt":    o3.LastPostAt,
  6283  		"TotalMsgCount": o3.TotalMsgCount,
  6284  		"ExtraUpdateAt": o3.ExtraUpdateAt,
  6285  		"CreatorId":     o3.CreatorId,
  6286  	})
  6287  	s.Require().Nil(execerr)
  6288  
  6289  	s.T().Run("verify o3 INSERT converted to UPDATE", func(t *testing.T) {
  6290  		channels, channelErr := s.Store().Channel().SearchInTeam(teamId, "", true)
  6291  		s.Require().Nil(channelErr)
  6292  		s.Require().Equal(&model.ChannelList{&o2, &o3}, channels)
  6293  	})
  6294  
  6295  	// o4 is a public channel on the team that existed in the Channels table but was omitted from the PublicChannels table.
  6296  	o4 := model.Channel{
  6297  		TeamId:      teamId,
  6298  		DisplayName: "Open Channel 4",
  6299  		Name:        model.NewId(),
  6300  		Type:        model.CHANNEL_OPEN,
  6301  	}
  6302  
  6303  	_, nErr = s.Store().Channel().Save(&o4, -1)
  6304  	s.Require().Nil(nErr)
  6305  
  6306  	_, execerr = s.SqlStore().GetMaster().ExecNoTimeout(`
  6307  		DELETE FROM
  6308  		    PublicChannels
  6309  		WHERE
  6310  		    Id = :Id
  6311  	`, map[string]interface{}{
  6312  		"Id": o4.Id,
  6313  	})
  6314  	s.Require().Nil(execerr)
  6315  
  6316  	o4.DisplayName += " - Modified"
  6317  	_, appErr = s.Store().Channel().Update(&o4)
  6318  	s.Require().Nil(appErr)
  6319  
  6320  	s.T().Run("verify o4 UPDATE converted to INSERT", func(t *testing.T) {
  6321  		channels, err := s.Store().Channel().SearchInTeam(teamId, "", true)
  6322  		s.Require().Nil(err)
  6323  		s.Require().Equal(&model.ChannelList{&o2, &o3, &o4}, channels)
  6324  	})
  6325  }
  6326  
  6327  func (s *ChannelStoreTestSuite) TestStoreGetAllChannelsForExportAfter() {
  6328  	t1 := model.Team{}
  6329  	t1.DisplayName = "Name"
  6330  	t1.Name = "zz" + model.NewId()
  6331  	t1.Email = MakeEmail()
  6332  	t1.Type = model.TEAM_OPEN
  6333  	_, err := s.Store().Team().Save(&t1)
  6334  	s.Require().Nil(err)
  6335  
  6336  	c1 := model.Channel{}
  6337  	c1.TeamId = t1.Id
  6338  	c1.DisplayName = "Channel1"
  6339  	c1.Name = "zz" + model.NewId() + "b"
  6340  	c1.Type = model.CHANNEL_OPEN
  6341  	_, nErr := s.Store().Channel().Save(&c1, -1)
  6342  	s.Require().Nil(nErr)
  6343  
  6344  	d1, err := s.Store().Channel().GetAllChannelsForExportAfter(10000, strings.Repeat("0", 26))
  6345  	s.Assert().Nil(err)
  6346  
  6347  	found := false
  6348  	for _, c := range d1 {
  6349  		if c.Id == c1.Id {
  6350  			found = true
  6351  			s.Assert().Equal(t1.Id, c.TeamId)
  6352  			s.Assert().Nil(c.SchemeId)
  6353  			s.Assert().Equal(t1.Name, c.TeamName)
  6354  		}
  6355  	}
  6356  	s.Assert().True(found)
  6357  }
  6358  
  6359  func (s *ChannelStoreTestSuite) TestStoreGetChannelMembersForExport() {
  6360  	t1 := model.Team{}
  6361  	t1.DisplayName = "Name"
  6362  	t1.Name = "zz" + model.NewId()
  6363  	t1.Email = MakeEmail()
  6364  	t1.Type = model.TEAM_OPEN
  6365  	_, err := s.Store().Team().Save(&t1)
  6366  	s.Require().Nil(err)
  6367  
  6368  	c1 := model.Channel{}
  6369  	c1.TeamId = t1.Id
  6370  	c1.DisplayName = "Channel1"
  6371  	c1.Name = "zz" + model.NewId() + "b"
  6372  	c1.Type = model.CHANNEL_OPEN
  6373  	_, nErr := s.Store().Channel().Save(&c1, -1)
  6374  	s.Require().Nil(nErr)
  6375  
  6376  	c2 := model.Channel{}
  6377  	c2.TeamId = model.NewId()
  6378  	c2.DisplayName = "Channel2"
  6379  	c2.Name = "zz" + model.NewId() + "b"
  6380  	c2.Type = model.CHANNEL_OPEN
  6381  	_, nErr = s.Store().Channel().Save(&c2, -1)
  6382  	s.Require().Nil(nErr)
  6383  
  6384  	u1 := model.User{}
  6385  	u1.Email = MakeEmail()
  6386  	u1.Nickname = model.NewId()
  6387  	_, err = s.Store().User().Save(&u1)
  6388  	s.Require().Nil(err)
  6389  
  6390  	m1 := model.ChannelMember{}
  6391  	m1.ChannelId = c1.Id
  6392  	m1.UserId = u1.Id
  6393  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  6394  	_, err = s.Store().Channel().SaveMember(&m1)
  6395  	s.Require().Nil(err)
  6396  
  6397  	m2 := model.ChannelMember{}
  6398  	m2.ChannelId = c2.Id
  6399  	m2.UserId = u1.Id
  6400  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  6401  	_, err = s.Store().Channel().SaveMember(&m2)
  6402  	s.Require().Nil(err)
  6403  
  6404  	d1, err := s.Store().Channel().GetChannelMembersForExport(u1.Id, t1.Id)
  6405  	s.Assert().Nil(err)
  6406  
  6407  	s.Assert().Len(d1, 1)
  6408  
  6409  	cmfe1 := d1[0]
  6410  	s.Assert().Equal(c1.Name, cmfe1.ChannelName)
  6411  	s.Assert().Equal(c1.Id, cmfe1.ChannelId)
  6412  	s.Assert().Equal(u1.Id, cmfe1.UserId)
  6413  }
  6414  
  6415  func (s *ChannelStoreTestSuite) TestStoreRemoveAllDeactivatedMembers() {
  6416  	// Set up all the objects needed in the store.
  6417  	t1 := model.Team{}
  6418  	t1.DisplayName = "Name"
  6419  	t1.Name = "zz" + model.NewId()
  6420  	t1.Email = MakeEmail()
  6421  	t1.Type = model.TEAM_OPEN
  6422  	_, err := s.Store().Team().Save(&t1)
  6423  	s.Require().Nil(err)
  6424  
  6425  	c1 := model.Channel{}
  6426  	c1.TeamId = t1.Id
  6427  	c1.DisplayName = "Channel1"
  6428  	c1.Name = "zz" + model.NewId() + "b"
  6429  	c1.Type = model.CHANNEL_OPEN
  6430  	_, nErr := s.Store().Channel().Save(&c1, -1)
  6431  	s.Require().Nil(nErr)
  6432  
  6433  	u1 := model.User{}
  6434  	u1.Email = MakeEmail()
  6435  	u1.Nickname = model.NewId()
  6436  	_, err = s.Store().User().Save(&u1)
  6437  	s.Require().Nil(err)
  6438  
  6439  	u2 := model.User{}
  6440  	u2.Email = MakeEmail()
  6441  	u2.Nickname = model.NewId()
  6442  	_, err = s.Store().User().Save(&u2)
  6443  	s.Require().Nil(err)
  6444  
  6445  	u3 := model.User{}
  6446  	u3.Email = MakeEmail()
  6447  	u3.Nickname = model.NewId()
  6448  	_, err = s.Store().User().Save(&u3)
  6449  	s.Require().Nil(err)
  6450  
  6451  	m1 := model.ChannelMember{}
  6452  	m1.ChannelId = c1.Id
  6453  	m1.UserId = u1.Id
  6454  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  6455  	_, err = s.Store().Channel().SaveMember(&m1)
  6456  	s.Require().Nil(err)
  6457  
  6458  	m2 := model.ChannelMember{}
  6459  	m2.ChannelId = c1.Id
  6460  	m2.UserId = u2.Id
  6461  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  6462  	_, err = s.Store().Channel().SaveMember(&m2)
  6463  	s.Require().Nil(err)
  6464  
  6465  	m3 := model.ChannelMember{}
  6466  	m3.ChannelId = c1.Id
  6467  	m3.UserId = u3.Id
  6468  	m3.NotifyProps = model.GetDefaultChannelNotifyProps()
  6469  	_, err = s.Store().Channel().SaveMember(&m3)
  6470  	s.Require().Nil(err)
  6471  
  6472  	// Get all the channel members. Check there are 3.
  6473  	d1, err := s.Store().Channel().GetMembers(c1.Id, 0, 1000)
  6474  	s.Assert().Nil(err)
  6475  	s.Assert().Len(*d1, 3)
  6476  
  6477  	// Deactivate users 1 & 2.
  6478  	u1.DeleteAt = model.GetMillis()
  6479  	u2.DeleteAt = model.GetMillis()
  6480  	_, err = s.Store().User().Update(&u1, true)
  6481  	s.Require().Nil(err)
  6482  	_, err = s.Store().User().Update(&u2, true)
  6483  	s.Require().Nil(err)
  6484  
  6485  	// Remove all deactivated users from the channel.
  6486  	s.Assert().Nil(s.Store().Channel().RemoveAllDeactivatedMembers(c1.Id))
  6487  
  6488  	// Get all the channel members. Check there is now only 1: m3.
  6489  	d2, err := s.Store().Channel().GetMembers(c1.Id, 0, 1000)
  6490  	s.Assert().Nil(err)
  6491  	s.Assert().Len(*d2, 1)
  6492  	s.Assert().Equal(u3.Id, (*d2)[0].UserId)
  6493  
  6494  	// Manually truncate Channels table until testlib can handle cleanups
  6495  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
  6496  }
  6497  
  6498  func (s *ChannelStoreTestSuite) TestStoreExportAllDirectChannels() {
  6499  	teamId := model.NewId()
  6500  
  6501  	o1 := model.Channel{}
  6502  	o1.TeamId = teamId
  6503  	o1.DisplayName = "Name" + model.NewId()
  6504  	o1.Name = "zz" + model.NewId() + "b"
  6505  	o1.Type = model.CHANNEL_DIRECT
  6506  
  6507  	userIds := []string{model.NewId(), model.NewId(), model.NewId()}
  6508  
  6509  	o2 := model.Channel{}
  6510  	o2.Name = model.GetGroupNameFromUserIds(userIds)
  6511  	o2.DisplayName = "GroupChannel" + model.NewId()
  6512  	o2.Name = "zz" + model.NewId() + "b"
  6513  	o2.Type = model.CHANNEL_GROUP
  6514  	_, nErr := s.Store().Channel().Save(&o2, -1)
  6515  	s.Require().Nil(nErr)
  6516  
  6517  	u1 := &model.User{}
  6518  	u1.Email = MakeEmail()
  6519  	u1.Nickname = model.NewId()
  6520  	_, err := s.Store().User().Save(u1)
  6521  	s.Require().Nil(err)
  6522  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
  6523  	s.Require().Nil(nErr)
  6524  
  6525  	u2 := &model.User{}
  6526  	u2.Email = MakeEmail()
  6527  	u2.Nickname = model.NewId()
  6528  	_, err = s.Store().User().Save(u2)
  6529  	s.Require().Nil(err)
  6530  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
  6531  	s.Require().Nil(nErr)
  6532  
  6533  	m1 := model.ChannelMember{}
  6534  	m1.ChannelId = o1.Id
  6535  	m1.UserId = u1.Id
  6536  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  6537  
  6538  	m2 := model.ChannelMember{}
  6539  	m2.ChannelId = o1.Id
  6540  	m2.UserId = u2.Id
  6541  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  6542  
  6543  	s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
  6544  
  6545  	d1, nErr := s.Store().Channel().GetAllDirectChannelsForExportAfter(10000, strings.Repeat("0", 26))
  6546  	s.Assert().Nil(nErr)
  6547  
  6548  	s.Assert().Len(d1, 2)
  6549  	s.Assert().ElementsMatch([]string{o1.DisplayName, o2.DisplayName}, []string{d1[0].DisplayName, d1[1].DisplayName})
  6550  
  6551  	// Manually truncate Channels table until testlib can handle cleanups
  6552  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
  6553  }
  6554  
  6555  func (s *ChannelStoreTestSuite) TestStoreExportAllDirectChannelsExcludePrivateAndPublic() {
  6556  	teamId := model.NewId()
  6557  
  6558  	o1 := model.Channel{}
  6559  	o1.TeamId = teamId
  6560  	o1.DisplayName = "The Direct Channel" + model.NewId()
  6561  	o1.Name = "zz" + model.NewId() + "b"
  6562  	o1.Type = model.CHANNEL_DIRECT
  6563  
  6564  	o2 := model.Channel{}
  6565  	o2.TeamId = teamId
  6566  	o2.DisplayName = "Channel2" + model.NewId()
  6567  	o2.Name = "zz" + model.NewId() + "b"
  6568  	o2.Type = model.CHANNEL_OPEN
  6569  	_, nErr := s.Store().Channel().Save(&o2, -1)
  6570  	s.Require().Nil(nErr)
  6571  
  6572  	o3 := model.Channel{}
  6573  	o3.TeamId = teamId
  6574  	o3.DisplayName = "Channel3" + model.NewId()
  6575  	o3.Name = "zz" + model.NewId() + "b"
  6576  	o3.Type = model.CHANNEL_PRIVATE
  6577  	_, nErr = s.Store().Channel().Save(&o3, -1)
  6578  	s.Require().Nil(nErr)
  6579  
  6580  	u1 := &model.User{}
  6581  	u1.Email = MakeEmail()
  6582  	u1.Nickname = model.NewId()
  6583  	_, err := s.Store().User().Save(u1)
  6584  	s.Require().Nil(err)
  6585  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
  6586  	s.Require().Nil(nErr)
  6587  
  6588  	u2 := &model.User{}
  6589  	u2.Email = MakeEmail()
  6590  	u2.Nickname = model.NewId()
  6591  	_, err = s.Store().User().Save(u2)
  6592  	s.Require().Nil(err)
  6593  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
  6594  	s.Require().Nil(nErr)
  6595  
  6596  	m1 := model.ChannelMember{}
  6597  	m1.ChannelId = o1.Id
  6598  	m1.UserId = u1.Id
  6599  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  6600  
  6601  	m2 := model.ChannelMember{}
  6602  	m2.ChannelId = o1.Id
  6603  	m2.UserId = u2.Id
  6604  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  6605  
  6606  	s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
  6607  
  6608  	d1, nErr := s.Store().Channel().GetAllDirectChannelsForExportAfter(10000, strings.Repeat("0", 26))
  6609  	s.Assert().Nil(nErr)
  6610  	s.Assert().Len(d1, 1)
  6611  	s.Assert().Equal(o1.DisplayName, d1[0].DisplayName)
  6612  
  6613  	// Manually truncate Channels table until testlib can handle cleanups
  6614  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
  6615  }
  6616  
  6617  func (s *ChannelStoreTestSuite) TestStoreExportAllDirectChannelsDeletedChannel() {
  6618  	teamId := model.NewId()
  6619  
  6620  	o1 := model.Channel{}
  6621  	o1.TeamId = teamId
  6622  	o1.DisplayName = "Different Name" + model.NewId()
  6623  	o1.Name = "zz" + model.NewId() + "b"
  6624  	o1.Type = model.CHANNEL_DIRECT
  6625  
  6626  	u1 := &model.User{}
  6627  	u1.Email = MakeEmail()
  6628  	u1.Nickname = model.NewId()
  6629  	_, err := s.Store().User().Save(u1)
  6630  	s.Require().Nil(err)
  6631  	_, nErr := s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1)
  6632  	s.Require().Nil(nErr)
  6633  
  6634  	u2 := &model.User{}
  6635  	u2.Email = MakeEmail()
  6636  	u2.Nickname = model.NewId()
  6637  	_, err = s.Store().User().Save(u2)
  6638  	s.Require().Nil(err)
  6639  	_, nErr = s.Store().Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u2.Id}, -1)
  6640  	s.Require().Nil(nErr)
  6641  
  6642  	m1 := model.ChannelMember{}
  6643  	m1.ChannelId = o1.Id
  6644  	m1.UserId = u1.Id
  6645  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
  6646  
  6647  	m2 := model.ChannelMember{}
  6648  	m2.ChannelId = o1.Id
  6649  	m2.UserId = u2.Id
  6650  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
  6651  
  6652  	s.Store().Channel().SaveDirectChannel(&o1, &m1, &m2)
  6653  
  6654  	o1.DeleteAt = 1
  6655  	nErr = s.Store().Channel().SetDeleteAt(o1.Id, 1, 1)
  6656  	s.Require().Nil(nErr, "channel should have been deleted")
  6657  
  6658  	d1, nErr := s.Store().Channel().GetAllDirectChannelsForExportAfter(10000, strings.Repeat("0", 26))
  6659  	s.Assert().NoError(nErr)
  6660  
  6661  	s.Assert().Equal(0, len(d1))
  6662  
  6663  	// Manually truncate Channels table until testlib can handle cleanups
  6664  	s.SqlStore().GetMaster().Exec("TRUNCATE Channels")
  6665  }
  6666  
  6667  func (s *ChannelStoreTestSuite) TestStoreGetChannelsBatchForIndexing() {
  6668  	// Set up all the objects needed
  6669  	c1 := &model.Channel{}
  6670  	c1.DisplayName = "Channel1"
  6671  	c1.Name = "zz" + model.NewId() + "b"
  6672  	c1.Type = model.CHANNEL_OPEN
  6673  	_, nErr := s.Store().Channel().Save(c1, -1)
  6674  	s.Require().Nil(nErr)
  6675  
  6676  	time.Sleep(10 * time.Millisecond)
  6677  
  6678  	c2 := &model.Channel{}
  6679  	c2.DisplayName = "Channel2"
  6680  	c2.Name = "zz" + model.NewId() + "b"
  6681  	c2.Type = model.CHANNEL_OPEN
  6682  	_, nErr = s.Store().Channel().Save(c2, -1)
  6683  	s.Require().Nil(nErr)
  6684  
  6685  	time.Sleep(10 * time.Millisecond)
  6686  	startTime := c2.CreateAt
  6687  
  6688  	c3 := &model.Channel{}
  6689  	c3.DisplayName = "Channel3"
  6690  	c3.Name = "zz" + model.NewId() + "b"
  6691  	c3.Type = model.CHANNEL_OPEN
  6692  	_, nErr = s.Store().Channel().Save(c3, -1)
  6693  	s.Require().Nil(nErr)
  6694  
  6695  	c4 := &model.Channel{}
  6696  	c4.DisplayName = "Channel4"
  6697  	c4.Name = "zz" + model.NewId() + "b"
  6698  	c4.Type = model.CHANNEL_PRIVATE
  6699  	_, nErr = s.Store().Channel().Save(c4, -1)
  6700  	s.Require().Nil(nErr)
  6701  
  6702  	c5 := &model.Channel{}
  6703  	c5.DisplayName = "Channel5"
  6704  	c5.Name = "zz" + model.NewId() + "b"
  6705  	c5.Type = model.CHANNEL_OPEN
  6706  	_, nErr = s.Store().Channel().Save(c5, -1)
  6707  	s.Require().Nil(nErr)
  6708  
  6709  	time.Sleep(10 * time.Millisecond)
  6710  
  6711  	c6 := &model.Channel{}
  6712  	c6.DisplayName = "Channel6"
  6713  	c6.Name = "zz" + model.NewId() + "b"
  6714  	c6.Type = model.CHANNEL_OPEN
  6715  	_, nErr = s.Store().Channel().Save(c6, -1)
  6716  	s.Require().NoError(nErr)
  6717  
  6718  	endTime := c6.CreateAt
  6719  
  6720  	// First and last channel should be outside the range
  6721  	channels, err := s.Store().Channel().GetChannelsBatchForIndexing(startTime, endTime, 1000)
  6722  	s.Assert().NoError(err)
  6723  	s.Assert().ElementsMatch([]*model.Channel{c2, c3, c5}, channels)
  6724  
  6725  	// Update the endTime, last channel should be in
  6726  	endTime = model.GetMillis()
  6727  	channels, err = s.Store().Channel().GetChannelsBatchForIndexing(startTime, endTime, 1000)
  6728  	s.Assert().NoError(err)
  6729  	s.Assert().ElementsMatch([]*model.Channel{c2, c3, c5, c6}, channels)
  6730  
  6731  	// Testing the limit
  6732  	channels, err = s.Store().Channel().GetChannelsBatchForIndexing(startTime, endTime, 2)
  6733  	s.Assert().NoError(err)
  6734  	s.Assert().ElementsMatch([]*model.Channel{c2, c3}, channels)
  6735  }
  6736  
  6737  func (s *ChannelStoreTestSuite) TestGroupSyncedChannelCount() {
  6738  	channel1, nErr := s.Store().Channel().Save(&model.Channel{
  6739  		DisplayName:      model.NewId(),
  6740  		Name:             model.NewId(),
  6741  		Type:             model.CHANNEL_PRIVATE,
  6742  		GroupConstrained: model.NewBool(true),
  6743  	}, 999)
  6744  	s.Require().Nil(nErr)
  6745  	s.Require().True(channel1.IsGroupConstrained())
  6746  	defer s.Store().Channel().PermanentDelete(channel1.Id)
  6747  
  6748  	channel2, nErr := s.Store().Channel().Save(&model.Channel{
  6749  		DisplayName: model.NewId(),
  6750  		Name:        model.NewId(),
  6751  		Type:        model.CHANNEL_PRIVATE,
  6752  	}, 999)
  6753  	s.Require().NoError(nErr)
  6754  	s.Require().False(channel2.IsGroupConstrained())
  6755  	defer s.Store().Channel().PermanentDelete(channel2.Id)
  6756  
  6757  	count, appErr := s.Store().Channel().GroupSyncedChannelCount()
  6758  	s.Require().Nil(appErr)
  6759  	s.Require().GreaterOrEqual(count, int64(1))
  6760  
  6761  	channel2.GroupConstrained = model.NewBool(true)
  6762  	channel2, err := s.Store().Channel().Update(channel2)
  6763  	s.Require().NoError(err)
  6764  	s.Require().True(channel2.IsGroupConstrained())
  6765  
  6766  	countAfter, err := s.Store().Channel().GroupSyncedChannelCount()
  6767  	s.Require().NoError(err)
  6768  	s.Require().GreaterOrEqual(countAfter, count+1)
  6769  }
  6770  
  6771  func (s *ChannelStoreTestSuite) TestSetShared() {
  6772  	channel := &model.Channel{
  6773  		TeamId:      model.NewId(),
  6774  		DisplayName: "test_share_flag",
  6775  		Name:        "test_share_flag",
  6776  		Type:        model.CHANNEL_OPEN,
  6777  	}
  6778  	channelSaved, err := s.Store().Channel().Save(channel, 999)
  6779  	s.Require().NoError(err)
  6780  
  6781  	s.T().Run("Check default", func(t *testing.T) {
  6782  		s.Assert().False(channelSaved.IsShared())
  6783  	})
  6784  
  6785  	s.T().Run("Set Shared flag", func(t *testing.T) {
  6786  		err := s.Store().Channel().SetShared(channelSaved.Id, true)
  6787  		s.Require().NoError(err)
  6788  
  6789  		channelMod, err := s.Store().Channel().Get(channelSaved.Id, false)
  6790  		s.Require().NoError(err)
  6791  
  6792  		s.Assert().True(channelMod.IsShared())
  6793  	})
  6794  
  6795  	s.T().Run("Set Shared for invalid id", func(t *testing.T) {
  6796  		err := s.Store().Channel().SetShared(model.NewId(), true)
  6797  		s.Require().Error(err)
  6798  	})
  6799  }
  6800  
  6801  func (s *ChannelStoreTestSuite) TestGetTeamForChannel() {
  6802  	team, err := s.Store().Team().Save(&model.Team{
  6803  		Name:        "myteam",
  6804  		DisplayName: "DisplayName",
  6805  		Email:       MakeEmail(),
  6806  		Type:        model.TEAM_OPEN,
  6807  	})
  6808  	s.Require().NoError(err)
  6809  
  6810  	channel := &model.Channel{
  6811  		TeamId:      team.Id,
  6812  		DisplayName: "test_share_flag",
  6813  		Name:        "test_share_flag",
  6814  		Type:        model.CHANNEL_OPEN,
  6815  	}
  6816  	channelSaved, err := s.Store().Channel().Save(channel, 999)
  6817  	s.Require().NoError(err)
  6818  
  6819  	got, err := s.Store().Channel().GetTeamForChannel(channelSaved.Id)
  6820  	s.Require().NoError(err)
  6821  	s.Assert().Equal(team.Id, got.Id)
  6822  
  6823  	_, err = s.Store().Channel().GetTeamForChannel("notfound")
  6824  	var nfErr *store.ErrNotFound
  6825  	s.Require().True(errors.As(err, &nfErr))
  6826  }