post_test.go 42.4 KB
Newer Older
1
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
2 3 4 5 6
// See License.txt for license information.

package api4

import (
7
	"encoding/json"
8
	"net/http"
9 10
	"net/http/httptest"
	"net/url"
11
	"reflect"
12
	"strconv"
13
	"strings"
14
	"testing"
15
	"time"
16

Christopher Speller's avatar
Christopher Speller committed
17 18 19
	"github.com/mattermost/mattermost-server/app"
	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/utils"
20 21 22 23
)

func TestCreatePost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
24
	defer th.TearDown()
25 26
	Client := th.Client

27
	post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a", Props: model.StringInterface{model.PROPS_ADD_CHANNEL_MEMBER: "no good"}}
28 29
	rpost, resp := Client.CreatePost(post)
	CheckNoError(t, resp)
30
	CheckCreatedStatus(t, resp)
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

	if rpost.Message != post.Message {
		t.Fatal("message didn't match")
	}

	if rpost.Hashtags != "#hashtag" {
		t.Fatal("hashtag didn't match")
	}

	if len(rpost.FileIds) != 0 {
		t.Fatal("shouldn't have files")
	}

	if rpost.EditAt != 0 {
		t.Fatal("newly created post shouldn't have EditAt set")
	}

48 49 50 51
	if rpost.Props[model.PROPS_ADD_CHANNEL_MEMBER] != nil {
		t.Fatal("newly created post shouldn't have Props['add_channel_member'] set")
	}

52 53 54 55 56 57 58 59 60 61 62 63 64 65
	post.RootId = rpost.Id
	post.ParentId = rpost.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.RootId = "junk"
	_, resp = Client.CreatePost(post)
	CheckBadRequestStatus(t, resp)

	post.RootId = rpost.Id
	post.ParentId = "junk"
	_, resp = Client.CreatePost(post)
	CheckBadRequestStatus(t, resp)

66
	post2 := &model.Post{ChannelId: th.BasicChannel2.Id, Message: "zz" + model.NewId() + "a", CreateAt: 123}
67 68 69 70 71 72
	rpost2, resp := Client.CreatePost(post2)

	if rpost2.CreateAt == post2.CreateAt {
		t.Fatal("create at should not match")
	}

73 74 75 76 77 78 79
	post.RootId = ""
	post.ParentId = ""
	post.Type = model.POST_SYSTEM_GENERIC
	_, resp = Client.CreatePost(post)
	CheckBadRequestStatus(t, resp)

	post.Type = ""
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
	post.RootId = rpost2.Id
	post.ParentId = rpost2.Id
	_, resp = Client.CreatePost(post)
	CheckBadRequestStatus(t, resp)

	post.RootId = ""
	post.ParentId = ""
	post.ChannelId = "junk"
	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

	post.ChannelId = model.NewId()
	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

	if r, err := Client.DoApiPost("/posts", "garbage"); err == nil {
		t.Fatal("should have errored")
	} else {
		if r.StatusCode != http.StatusBadRequest {
			t.Log("actual: " + strconv.Itoa(r.StatusCode))
			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
			t.Fatal("wrong status code")
		}
	}

	Client.Logout()
	_, resp = Client.CreatePost(post)
	CheckUnauthorizedStatus(t, resp)

	post.ChannelId = th.BasicChannel.Id
	post.CreateAt = 123
	rpost, resp = th.SystemAdminClient.CreatePost(post)
	CheckNoError(t, resp)

	if rpost.CreateAt != post.CreateAt {
		t.Fatal("create at should match")
	}
}

119 120 121 122 123 124 125
func testCreatePostWithOutgoingHook(
	t *testing.T,
	hookContentType, expectedContentType, message, triggerWord string,
	fileIds []string,
	triggerWhen int,
) {
	th := Setup().InitBasic().InitSystemAdmin()
126
	defer th.TearDown()
127 128 129 130
	user := th.SystemAdminUser
	team := th.BasicTeam
	channel := th.BasicChannel

Chris's avatar
Chris committed
131 132 133
	enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks
	enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations
	allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections
134
	defer func() {
Chris's avatar
Chris committed
135 136
		th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks })
		th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks })
137
		utils.SetDefaultRolesBasedOnConfig()
Chris's avatar
Chris committed
138 139 140
		th.App.UpdateConfig(func(cfg *model.Config) {
			cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections
		})
141
	}()
Chris's avatar
Chris committed
142 143
	th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true })
	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true })
144
	utils.SetDefaultRolesBasedOnConfig()
Chris's avatar
Chris committed
145 146 147
	th.App.UpdateConfig(func(cfg *model.Config) {
		*cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1"
	})
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

	var hook *model.OutgoingWebhook
	var post *model.Post

	// Create a test server that is the target of the outgoing webhook. It will
	// validate the webhook body fields and write to the success channel on
	// success/failure.
	success := make(chan bool)
	wait := make(chan bool, 1)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		<-wait

		requestContentType := r.Header.Get("Content-Type")
		if requestContentType != expectedContentType {
			t.Logf("Content-Type is %s, should be %s", requestContentType, expectedContentType)
			success <- false
			return
		}

		expectedPayload := &model.OutgoingWebhookPayload{
			Token:       hook.Token,
			TeamId:      hook.TeamId,
			TeamDomain:  team.Name,
			ChannelId:   post.ChannelId,
			ChannelName: channel.Name,
			Timestamp:   post.CreateAt,
			UserId:      post.UserId,
			UserName:    user.Username,
			PostId:      post.Id,
			Text:        post.Message,
			TriggerWord: triggerWord,
			FileIds:     strings.Join(post.FileIds, ","),
		}

		// depending on the Content-Type, we expect to find a JSON or form encoded payload
		if requestContentType == "application/json" {
			decoder := json.NewDecoder(r.Body)
			o := &model.OutgoingWebhookPayload{}
			decoder.Decode(&o)

			if !reflect.DeepEqual(expectedPayload, o) {
				t.Logf("JSON payload is %+v, should be %+v", o, expectedPayload)
				success <- false
				return
			}
		} else {
			err := r.ParseForm()
			if err != nil {
				t.Logf("Error parsing form: %q", err)
				success <- false
				return
			}

			expectedFormValues, _ := url.ParseQuery(expectedPayload.ToFormValues())
			if !reflect.DeepEqual(expectedFormValues, r.Form) {
				t.Logf("Form values are: %q\n, should be: %q\n", r.Form, expectedFormValues)
				success <- false
				return
			}
		}

		success <- true
	}))
	defer ts.Close()

	// create an outgoing webhook, passing it the test server URL
	var triggerWords []string
	if triggerWord != "" {
		triggerWords = []string{triggerWord}
	}
218

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	hook = &model.OutgoingWebhook{
		ChannelId:    channel.Id,
		TeamId:       team.Id,
		ContentType:  hookContentType,
		TriggerWords: triggerWords,
		TriggerWhen:  triggerWhen,
		CallbackURLs: []string{ts.URL},
	}

	hook, resp := th.SystemAdminClient.CreateOutgoingWebhook(hook)
	CheckNoError(t, resp)

	// create a post to trigger the webhook
	post = &model.Post{
		ChannelId: channel.Id,
		Message:   message,
		FileIds:   fileIds,
	}

	post, resp = th.SystemAdminClient.CreatePost(post)
	CheckNoError(t, resp)

	wait <- true

	// We wait for the test server to write to the success channel and we make
	// the test fail if that doesn't happen before the timeout.
	select {
	case ok := <-success:
		if !ok {
			t.Fatal("Test server did send an invalid webhook.")
		}
	case <-time.After(time.Second):
		t.Fatal("Timeout, test server did not send the webhook.")
	}
}

func TestCreatePostWithOutgoingHook_form_urlencoded(t *testing.T) {
	testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH)
	testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH)
}

func TestCreatePostWithOutgoingHook_json(t *testing.T) {
	testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH)
	testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH)
}

// hooks created before we added the ContentType field should be considered as
// application/x-www-form-urlencoded
func TestCreatePostWithOutgoingHook_no_content_type(t *testing.T) {
	testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH)
	testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH)
	testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH)
}

278 279
func TestCreatePostPublic(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
280
	defer th.TearDown()
281 282 283 284 285 286 287 288 289 290 291 292 293 294
	Client := th.Client

	post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"}

	user := model.User{Email: GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.ROLE_SYSTEM_USER.Id}

	ruser, resp := Client.CreateUser(&user)
	CheckNoError(t, resp)

	Client.Login(user.Email, user.Password)

	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

Chris's avatar
Chris committed
295 296
	th.App.UpdateUserRoles(ruser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_POST_ALL_PUBLIC.Id)
	th.App.InvalidateAllCaches()
297 298 299 300 301 302 303 304 305 306

	Client.Login(user.Email, user.Password)

	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.ChannelId = th.BasicPrivateChannel.Id
	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

Chris's avatar
Chris committed
307 308 309 310
	th.App.UpdateUserRoles(ruser.Id, model.ROLE_SYSTEM_USER.Id)
	th.App.JoinUserToTeam(th.BasicTeam, ruser, "")
	th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.ROLE_TEAM_USER.Id+" "+model.ROLE_TEAM_POST_ALL_PUBLIC.Id)
	th.App.InvalidateAllCaches()
311 312 313 314 315 316 317 318 319 320 321 322

	Client.Login(user.Email, user.Password)

	post.ChannelId = th.BasicPrivateChannel.Id
	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

	post.ChannelId = th.BasicChannel.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)
}

323 324
func TestCreatePostAll(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
325
	defer th.TearDown()
326 327 328 329 330 331
	Client := th.Client

	post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"}

	user := model.User{Email: GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.ROLE_SYSTEM_USER.Id}

Chris's avatar
Chris committed
332
	directChannel, _ := th.App.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
333 334 335 336 337 338 339 340 341

	ruser, resp := Client.CreateUser(&user)
	CheckNoError(t, resp)

	Client.Login(user.Email, user.Password)

	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)

Chris's avatar
Chris committed
342 343
	th.App.UpdateUserRoles(ruser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_POST_ALL.Id)
	th.App.InvalidateAllCaches()
344 345 346 347 348 349 350 351 352 353 354 355 356 357

	Client.Login(user.Email, user.Password)

	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.ChannelId = th.BasicPrivateChannel.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.ChannelId = directChannel.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

Chris's avatar
Chris committed
358 359 360 361
	th.App.UpdateUserRoles(ruser.Id, model.ROLE_SYSTEM_USER.Id)
	th.App.JoinUserToTeam(th.BasicTeam, ruser, "")
	th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.ROLE_TEAM_USER.Id+" "+model.ROLE_TEAM_POST_ALL.Id)
	th.App.InvalidateAllCaches()
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

	Client.Login(user.Email, user.Password)

	post.ChannelId = th.BasicPrivateChannel.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.ChannelId = th.BasicChannel.Id
	_, resp = Client.CreatePost(post)
	CheckNoError(t, resp)

	post.ChannelId = directChannel.Id
	_, resp = Client.CreatePost(post)
	CheckForbiddenStatus(t, resp)
}

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
func TestCreatePostSendOutOfChannelMentions(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
	defer th.TearDown()
	Client := th.Client

	WebSocketClient, err := th.CreateWebSocketClient()
	if err != nil {
		t.Fatal(err)
	}
	WebSocketClient.Listen()

	inChannelUser := th.CreateUser()
	th.LinkUserToTeam(inChannelUser, th.BasicTeam)
	th.App.AddUserToChannel(inChannelUser, th.BasicChannel)

	post1 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "@" + inChannelUser.Username}
	_, resp := Client.CreatePost(post1)
	CheckNoError(t, resp)
	CheckCreatedStatus(t, resp)

	timeout := time.After(300 * time.Millisecond)
	waiting := true
	for waiting {
		select {
		case event := <-WebSocketClient.EventChannel:
			if event.Event == model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE {
				t.Fatal("should not have ephemeral message event")
			}

		case <-timeout:
			waiting = false
		}
	}

	outOfChannelUser := th.CreateUser()
	th.LinkUserToTeam(outOfChannelUser, th.BasicTeam)

	post2 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "@" + outOfChannelUser.Username}
	_, resp = Client.CreatePost(post2)
	CheckNoError(t, resp)
	CheckCreatedStatus(t, resp)

	timeout = time.After(300 * time.Millisecond)
	waiting = true
	for waiting {
		select {
		case event := <-WebSocketClient.EventChannel:
			if event.Event != model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE {
				// Ignore any other events
				continue
			}

			wpost := model.PostFromJson(strings.NewReader(event.Data["post"].(string)))
			if acm, ok := wpost.Props[model.PROPS_ADD_CHANNEL_MEMBER].(map[string]interface{}); !ok {
				t.Fatal("should have received ephemeral post with 'add_channel_member' in props")
			} else {
				if acm["post_id"] == nil || acm["user_ids"] == nil || acm["usernames"] == nil {
					t.Fatal("should not be nil")
				}
			}
			waiting = false
		case <-timeout:
			t.Fatal("timed out waiting for ephemeral message event")
		}
	}
}

445 446
func TestUpdatePost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
447
	defer th.TearDown()
448 449 450
	Client := th.Client
	channel := th.BasicChannel

451 452
	isLicensed := utils.IsLicensed()
	license := utils.License()
Chris's avatar
Chris committed
453
	allowEditPost := *th.App.Config().ServiceSettings.AllowEditPost
454
	defer func() {
455 456
		utils.SetIsLicensed(isLicensed)
		utils.SetLicense(license)
Chris's avatar
Chris committed
457
		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = allowEditPost })
458 459
		utils.SetDefaultRolesBasedOnConfig()
	}()
460 461 462
	utils.SetIsLicensed(true)
	utils.SetLicense(&model.License{Features: &model.Features{}})
	utils.License().Features.SetDefaults()
463

Chris's avatar
Chris committed
464
	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS })
465 466
	utils.SetDefaultRolesBasedOnConfig()

467
	post := &model.Post{ChannelId: channel.Id, Message: "zz" + model.NewId() + "a"}
468 469 470 471 472 473 474 475 476 477 478
	rpost, resp := Client.CreatePost(post)
	CheckNoError(t, resp)

	if rpost.Message != post.Message {
		t.Fatal("full name didn't match")
	}

	if rpost.EditAt != 0 {
		t.Fatal("Newly created post shouldn't have EditAt set")
	}

479
	msg := "zz" + model.NewId() + " update post"
480
	rpost.Message = msg
481 482
	rpost.UserId = ""

483
	rupost, resp := Client.UpdatePost(rpost.Id, rpost)
484 485 486 487 488 489 490 491 492 493 494
	CheckNoError(t, resp)

	if rupost.Message != msg {
		t.Fatal("failed to updates")
	}
	if rupost.EditAt == 0 {
		t.Fatal("EditAt not updated for post")
	}

	msg1 := "#hashtag a" + model.NewId() + " update post again"
	rpost.Message = msg1
495
	rpost.Props[model.PROPS_ADD_CHANNEL_MEMBER] = "no good"
496
	rrupost, resp := Client.UpdatePost(rpost.Id, rpost)
497 498 499 500 501 502
	CheckNoError(t, resp)

	if rrupost.Message != msg1 && rrupost.Hashtags != "#hashtag" {
		t.Fatal("failed to updates")
	}

503 504 505 506
	if rrupost.Props[model.PROPS_ADD_CHANNEL_MEMBER] != nil {
		t.Fatal("failed to sanitize Props['add_channel_member'], should be nil")
	}

507 508 509 510
	rpost2, err := th.App.CreatePost(&model.Post{ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", Type: model.POST_JOIN_LEAVE, UserId: th.BasicUser.Id}, channel, false)
	if err != nil {
		t.Fatal(err)
	}
511

512
	up2 := &model.Post{Id: rpost2.Id, ChannelId: channel.Id, Message: "zz" + model.NewId() + " update post 2"}
513
	_, resp = Client.UpdatePost(rpost2.Id, up2)
514 515 516 517 518
	CheckBadRequestStatus(t, resp)

	Client.Logout()
	_, resp = Client.UpdatePost(rpost.Id, rpost)
	CheckUnauthorizedStatus(t, resp)
519 520 521 522 523 524 525 526 527

	th.LoginBasic2()
	_, resp = Client.UpdatePost(rpost.Id, rpost)
	CheckForbiddenStatus(t, resp)

	Client.Logout()

	_, resp = th.SystemAdminClient.UpdatePost(rpost.Id, rpost)
	CheckNoError(t, resp)
528 529
}

530 531
func TestPatchPost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
532
	defer th.TearDown()
533 534 535
	Client := th.Client
	channel := th.BasicChannel

536 537
	isLicensed := utils.IsLicensed()
	license := utils.License()
Chris's avatar
Chris committed
538
	allowEditPost := *th.App.Config().ServiceSettings.AllowEditPost
539
	defer func() {
540 541
		utils.SetIsLicensed(isLicensed)
		utils.SetLicense(license)
Chris's avatar
Chris committed
542
		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = allowEditPost })
543 544
		utils.SetDefaultRolesBasedOnConfig()
	}()
545 546 547
	utils.SetIsLicensed(true)
	utils.SetLicense(&model.License{Features: &model.Features{}})
	utils.License().Features.SetDefaults()
548

Chris's avatar
Chris committed
549
	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS })
550 551 552 553 554 555 556 557 558 559 560 561 562 563
	utils.SetDefaultRolesBasedOnConfig()

	post := &model.Post{
		ChannelId:    channel.Id,
		IsPinned:     true,
		Message:      "#hashtag a message",
		Props:        model.StringInterface{"channel_header": "old_header"},
		FileIds:      model.StringArray{"file1", "file2"},
		HasReactions: true,
	}
	post, _ = Client.CreatePost(post)

	patch := &model.PostPatch{}

564 565
	patch.IsPinned = model.NewBool(false)
	patch.Message = model.NewString("#otherhashtag other message")
566 567 568 569
	patch.Props = new(model.StringInterface)
	*patch.Props = model.StringInterface{"channel_header": "new_header"}
	patch.FileIds = new(model.StringArray)
	*patch.FileIds = model.StringArray{"file1", "otherfile2", "otherfile3"}
570
	patch.HasReactions = model.NewBool(false)
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

	rpost, resp := Client.PatchPost(post.Id, patch)
	CheckNoError(t, resp)

	if rpost.IsPinned != false {
		t.Fatal("IsPinned did not update properly")
	}
	if rpost.Message != "#otherhashtag other message" {
		t.Fatal("Message did not update properly")
	}
	if len(rpost.Props) != 1 {
		t.Fatal("Props did not update properly")
	}
	if !reflect.DeepEqual(rpost.Props, *patch.Props) {
		t.Fatal("Props did not update properly")
	}
	if rpost.Hashtags != "#otherhashtag" {
		t.Fatal("Message did not update properly")
	}
	if len(rpost.FileIds) != 3 {
		t.Fatal("FileIds did not update properly")
	}
	if !reflect.DeepEqual(rpost.FileIds, *patch.FileIds) {
		t.Fatal("FileIds did not update properly")
	}
	if rpost.HasReactions != false {
		t.Fatal("HasReactions did not update properly")
	}

	if r, err := Client.DoApiPut("/posts/"+post.Id+"/patch", "garbage"); err == nil {
		t.Fatal("should have errored")
	} else {
		if r.StatusCode != http.StatusBadRequest {
			t.Log("actual: " + strconv.Itoa(r.StatusCode))
			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
			t.Fatal("wrong status code")
		}
	}

	_, resp = Client.PatchPost("junk", patch)
	CheckBadRequestStatus(t, resp)

	_, resp = Client.PatchPost(GenerateTestId(), patch)
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.PatchPost(post.Id, patch)
	CheckUnauthorizedStatus(t, resp)

620 621 622 623
	th.LoginBasic2()
	_, resp = Client.PatchPost(post.Id, patch)
	CheckForbiddenStatus(t, resp)

624 625 626 627 628 629 630 631
	th.LoginTeamAdmin()
	_, resp = Client.PatchPost(post.Id, patch)
	CheckNoError(t, resp)

	_, resp = th.SystemAdminClient.PatchPost(post.Id, patch)
	CheckNoError(t, resp)
}

632 633
func TestPinPost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
634
	defer th.TearDown()
635 636 637 638 639 640 641 642 643 644
	Client := th.Client

	post := th.BasicPost
	pass, resp := Client.PinPost(post.Id)
	CheckNoError(t, resp)

	if !pass {
		t.Fatal("should have passed")
	}

Chris's avatar
Chris committed
645
	if rpost, err := th.App.GetSinglePost(post.Id); err != nil && rpost.IsPinned != true {
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
		t.Fatal("failed to pin post")
	}

	pass, resp = Client.PinPost("junk")
	CheckBadRequestStatus(t, resp)

	if pass {
		t.Fatal("should have failed")
	}

	_, resp = Client.PinPost(GenerateTestId())
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.PinPost(post.Id)
	CheckUnauthorizedStatus(t, resp)

	_, resp = th.SystemAdminClient.PinPost(post.Id)
	CheckNoError(t, resp)
}

func TestUnpinPost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
669
	defer th.TearDown()
670 671 672 673 674 675 676 677 678 679
	Client := th.Client

	pinnedPost := th.CreatePinnedPost()
	pass, resp := Client.UnpinPost(pinnedPost.Id)
	CheckNoError(t, resp)

	if !pass {
		t.Fatal("should have passed")
	}

Chris's avatar
Chris committed
680
	if rpost, err := th.App.GetSinglePost(pinnedPost.Id); err != nil && rpost.IsPinned != false {
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
		t.Fatal("failed to pin post")
	}

	pass, resp = Client.UnpinPost("junk")
	CheckBadRequestStatus(t, resp)

	if pass {
		t.Fatal("should have failed")
	}

	_, resp = Client.UnpinPost(GenerateTestId())
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.UnpinPost(pinnedPost.Id)
	CheckUnauthorizedStatus(t, resp)

	_, resp = th.SystemAdminClient.UnpinPost(pinnedPost.Id)
	CheckNoError(t, resp)
}

702 703
func TestGetPostsForChannel(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
704
	defer th.TearDown()
705 706 707 708
	Client := th.Client

	post1 := th.CreatePost()
	post2 := th.CreatePost()
709
	post3 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", RootId: post1.Id}
710 711
	post3, _ = Client.CreatePost(post3)

712 713 714
	time.Sleep(300 * time.Millisecond)
	since := model.GetMillis()
	time.Sleep(300 * time.Millisecond)
715 716

	post4 := th.CreatePost()
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746

	posts, resp := Client.GetPostsForChannel(th.BasicChannel.Id, 0, 60, "")
	CheckNoError(t, resp)

	if posts.Order[0] != post4.Id {
		t.Fatal("wrong order")
	}

	if posts.Order[1] != post3.Id {
		t.Fatal("wrong order")
	}

	if posts.Order[2] != post2.Id {
		t.Fatal("wrong order")
	}

	if posts.Order[3] != post1.Id {
		t.Fatal("wrong order")
	}

	posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 3, resp.Etag)
	CheckEtag(t, posts, resp)

	posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 3, "")
	CheckNoError(t, resp)

	if len(posts.Order) != 3 {
		t.Fatal("wrong number returned")
	}

747
	if _, ok := posts.Posts[post3.Id]; !ok {
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
		t.Fatal("missing comment")
	}

	if _, ok := posts.Posts[post1.Id]; !ok {
		t.Fatal("missing root post")
	}

	posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 1, 1, "")
	CheckNoError(t, resp)

	if posts.Order[0] != post3.Id {
		t.Fatal("wrong order")
	}

	posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 10000, 10000, "")
	CheckNoError(t, resp)

	if len(posts.Order) != 0 {
		t.Fatal("should be no posts")
	}

769 770
	post5 := th.CreatePost()

771
	posts, resp = Client.GetPostsSince(th.BasicChannel.Id, since)
772 773
	CheckNoError(t, resp)

774 775 776 777 778
	if len(posts.Posts) != 2 {
		t.Log(posts.Posts)
		t.Fatal("should return 2 posts")
	}

779 780
	found := make([]bool, 2)
	for _, p := range posts.Posts {
781
		if p.CreateAt < since {
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
			t.Fatal("bad create at for post returned")
		}
		if p.Id == post4.Id {
			found[0] = true
		} else if p.Id == post5.Id {
			found[1] = true
		}
	}

	for _, f := range found {
		if !f {
			t.Fatal("missing post")
		}
	}

797
	_, resp = Client.GetPostsForChannel("", 0, 60, "")
798
	CheckBadRequestStatus(t, resp)
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

	_, resp = Client.GetPostsForChannel("junk", 0, 60, "")
	CheckBadRequestStatus(t, resp)

	_, resp = Client.GetPostsForChannel(model.NewId(), 0, 60, "")
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.GetPostsForChannel(model.NewId(), 0, 60, "")
	CheckUnauthorizedStatus(t, resp)

	_, resp = th.SystemAdminClient.GetPostsForChannel(th.BasicChannel.Id, 0, 60, "")
	CheckNoError(t, resp)
}

814 815
func TestGetFlaggedPostsForUser(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
816
	defer th.TearDown()
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
	Client := th.Client
	user := th.BasicUser
	team1 := th.BasicTeam
	channel1 := th.BasicChannel
	post1 := th.CreatePost()
	channel2 := th.CreatePublicChannel()
	post2 := th.CreatePostWithClient(Client, channel2)

	preference := model.Preference{
		UserId:   user.Id,
		Category: model.PREFERENCE_CATEGORY_FLAGGED_POST,
		Name:     post1.Id,
		Value:    "true",
	}
	Client.UpdatePreferences(user.Id, &model.Preferences{preference})
	preference.Name = post2.Id
	Client.UpdatePreferences(user.Id, &model.Preferences{preference})

	opl := model.NewPostList()
	opl.AddPost(post1)
	opl.AddOrder(post1.Id)

	rpl, resp := Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 1 {
		t.Fatal("should have returned 1 post")
	}

	if !reflect.DeepEqual(rpl.Posts, opl.Posts) {
		t.Fatal("posts should have matched")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 1)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 1 {
		t.Fatal("should have returned 1 post")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 1, 1)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 0 {
		t.Fatal("should be empty")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, GenerateTestId(), 0, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 0 {
		t.Fatal("should be empty")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, "junk", 0, 10)
	CheckBadRequestStatus(t, resp)

	if rpl != nil {
		t.Fatal("should be nil")
	}

	opl.AddPost(post2)
	opl.AddOrder(post2.Id)

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 2 {
		t.Fatal("should have returned 2 posts")
	}

	if !reflect.DeepEqual(rpl.Posts, opl.Posts) {
		t.Fatal("posts should have matched")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 1)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 1 {
		t.Fatal("should have returned 1 post")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 1, 1)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 1 {
		t.Fatal("should have returned 1 post")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 1000, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 0 {
		t.Fatal("should be empty")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, GenerateTestId(), 0, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 0 {
		t.Fatal("should be empty")
	}

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, "junk", 0, 10)
	CheckBadRequestStatus(t, resp)

	if rpl != nil {
		t.Fatal("should be nil")
	}

	channel3 := th.CreatePrivateChannel()
	post4 := th.CreatePostWithClient(Client, channel3)

	preference.Name = post4.Id
	Client.UpdatePreferences(user.Id, &model.Preferences{preference})

	opl.AddPost(post4)
	opl.AddOrder(post4.Id)

	rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 3 {
		t.Fatal("should have returned 3 posts")
	}

	if !reflect.DeepEqual(rpl.Posts, opl.Posts) {
		t.Fatal("posts should have matched")
	}

	rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 2)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 2 {
		t.Fatal("should have returned 2 posts")
	}

	rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 2, 2)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 1 {
		t.Fatal("should have returned 1 post")
	}

	rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 1000, 10)
	CheckNoError(t, resp)

	if len(rpl.Posts) != 0 {
		t.Fatal("should be empty")
	}

	_, resp = Client.GetFlaggedPostsForUser("junk", 0, 10)
	CheckBadRequestStatus(t, resp)

	_, resp = Client.GetFlaggedPostsForUser(GenerateTestId(), 0, 10)
	CheckForbiddenStatus(t, resp)

	Client.Logout()

	rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)
	CheckUnauthorizedStatus(t, resp)

	rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)
	CheckUnauthorizedStatus(t, resp)

	rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)
	CheckUnauthorizedStatus(t, resp)

	rpl, resp = th.SystemAdminClient.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)
	CheckNoError(t, resp)

	rpl, resp = th.SystemAdminClient.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)
	CheckNoError(t, resp)

	rpl, resp = th.SystemAdminClient.GetFlaggedPostsForUser(user.Id, 0, 10)
	CheckNoError(t, resp)
}

995 996
func TestGetPostsAfterAndBefore(t *testing.T) {
	th := Setup().InitBasic()
997
	defer th.TearDown()
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
	Client := th.Client

	post1 := th.CreatePost()
	post2 := th.CreatePost()
	post3 := th.CreatePost()
	post4 := th.CreatePost()
	post5 := th.CreatePost()

	posts, resp := Client.GetPostsBefore(th.BasicChannel.Id, post3.Id, 0, 100, "")
	CheckNoError(t, resp)

	found := make([]bool, 2)
	for _, p := range posts.Posts {
		if p.Id == post1.Id {
			found[0] = true
		} else if p.Id == post2.Id {
			found[1] = true
		}

		if p.Id == post4.Id || p.Id == post5.Id {
			t.Fatal("returned posts after")
		}
	}

	for _, f := range found {
		if !f {
			t.Fatal("missing post")
		}
	}

	posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post3.Id, 1, 1, "")
	CheckNoError(t, resp)

	if len(posts.Posts) != 1 {
		t.Fatal("too many posts returned")
	}

	posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, "junk", 1, 1, "")
	CheckNoError(t, resp)

	if len(posts.Posts) != 0 {
		t.Fatal("should have no posts")
	}

	posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post3.Id, 0, 100, "")
	CheckNoError(t, resp)

	found = make([]bool, 2)
	for _, p := range posts.Posts {
		if p.Id == post4.Id {
			found[0] = true
		} else if p.Id == post5.Id {
			found[1] = true
		}

		if p.Id == post1.Id || p.Id == post2.Id {
			t.Fatal("returned posts before")
		}
	}

	for _, f := range found {
		if !f {
			t.Fatal("missing post")
		}
	}

	posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post3.Id, 1, 1, "")
	CheckNoError(t, resp)

	if len(posts.Posts) != 1 {
		t.Fatal("too many posts returned")
	}

	posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, "junk", 1, 1, "")
	CheckNoError(t, resp)

	if len(posts.Posts) != 0 {
		t.Fatal("should have no posts")
	}
}

1079 1080
func TestGetPost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
1081
	defer th.TearDown()
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
	Client := th.Client

	post, resp := Client.GetPost(th.BasicPost.Id, "")
	CheckNoError(t, resp)

	if post.Id != th.BasicPost.Id {
		t.Fatal("post ids don't match")
	}

	post, resp = Client.GetPost(th.BasicPost.Id, resp.Etag)
	CheckEtag(t, post, resp)

	_, resp = Client.GetPost("", "")
	CheckNotFoundStatus(t, resp)

	_, resp = Client.GetPost("junk", "")
	CheckBadRequestStatus(t, resp)

	_, resp = Client.GetPost(model.NewId(), "")
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
	CheckNotFoundStatus(t, resp)

	Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)

	// Channel is public, should be able to read post
	post, resp = Client.GetPost(th.BasicPost.Id, "")
	CheckNoError(t, resp)

	privatePost := th.CreatePostWithClient(Client, th.BasicPrivateChannel)

	post, resp = Client.GetPost(privatePost.Id, "")
	CheckNoError(t, resp)

	Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)

	// Channel is private, should not be able to read post
	post, resp = Client.GetPost(privatePost.Id, "")
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.GetPost(model.NewId(), "")
	CheckUnauthorizedStatus(t, resp)

	post, resp = th.SystemAdminClient.GetPost(th.BasicPost.Id, "")
	CheckNoError(t, resp)
}

1128 1129
func TestDeletePost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
1130
	defer th.TearDown()
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
	Client := th.Client

	_, resp := Client.DeletePost("")
	CheckNotFoundStatus(t, resp)

	_, resp = Client.DeletePost("junk")
	CheckBadRequestStatus(t, resp)

	_, resp = Client.DeletePost(th.BasicPost.Id)
	CheckForbiddenStatus(t, resp)

	Client.Login(th.TeamAdminUser.Email, th.TeamAdminUser.Password)
	_, resp = Client.DeletePost(th.BasicPost.Id)
	CheckNoError(t, resp)

	post := th.CreatePost()
	user := th.CreateUser()

	Client.Logout()
	Client.Login(user.Email, user.Password)

	_, resp = Client.DeletePost(post.Id)
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.DeletePost(model.NewId())
	CheckUnauthorizedStatus(t, resp)

	status, resp := th.SystemAdminClient.DeletePost(post.Id)
	if status == false {
		t.Fatal("post should return status OK")
	}
	CheckNoError(t, resp)
}

1166 1167
func TestGetPostThread(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
1168
	defer th.TearDown()
1169 1170
	Client := th.Client

1171
	post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", RootId: th.BasicPost.Id}
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
	post, _ = Client.CreatePost(post)

	list, resp := Client.GetPostThread(th.BasicPost.Id, "")
	CheckNoError(t, resp)

	var list2 *model.PostList
	list2, resp = Client.GetPostThread(th.BasicPost.Id, resp.Etag)
	CheckEtag(t, list2, resp)

	if list.Order[0] != th.BasicPost.Id {
		t.Fatal("wrong order")
	}

	if _, ok := list.Posts[th.BasicPost.Id]; !ok {
		t.Fatal("should have had post")
	}

	if _, ok := list.Posts[post.Id]; !ok {
		t.Fatal("should have had post")
	}

	_, resp = Client.GetPostThread("junk", "")
	CheckBadRequestStatus(t, resp)

	_, resp = Client.GetPostThread(model.NewId(), "")
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	CheckNotFoundStatus(t, resp)

	Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)

	// Channel is public, should be able to read post
	_, resp = Client.GetPostThread(th.BasicPost.Id, "")
	CheckNoError(t, resp)

	privatePost := th.CreatePostWithClient(Client, th.BasicPrivateChannel)

	_, resp = Client.GetPostThread(privatePost.Id, "")
	CheckNoError(t, resp)

	Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)

	// Channel is private, should not be able to read post
	_, resp = Client.GetPostThread(privatePost.Id, "")
1214 1215 1216 1217 1218 1219 1220 1221 1222
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.GetPostThread(model.NewId(), "")
	CheckUnauthorizedStatus(t, resp)

	list, resp = th.SystemAdminClient.GetPostThread(th.BasicPost.Id, "")
	CheckNoError(t, resp)
}
1223 1224 1225

func TestSearchPosts(t *testing.T) {
	th := Setup().InitBasic()
1226
	defer th.TearDown()
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
	th.LoginBasic()
	Client := th.Client

	message := "search for post1"
	_ = th.CreateMessagePost(message)

	message = "search for post2"
	post2 := th.CreateMessagePost(message)

	message = "#hashtag search for post3"
	post3 := th.CreateMessagePost(message)

	message = "hashtag for post4"
	_ = th.CreateMessagePost(message)

	posts, resp := Client.SearchPosts(th.BasicTeam.Id, "search", false)
	CheckNoError(t, resp)
	if len(posts.Order) != 3 {
		t.Fatal("wrong search")
	}

	posts, resp = Client.SearchPosts(th.BasicTeam.Id, "post2", false)
	CheckNoError(t, resp)
	if len(posts.Order) != 1 && posts.Order[0] == post2.Id {
		t.Fatal("wrong search")
	}

	posts, resp = Client.SearchPosts(th.BasicTeam.Id, "#hashtag", false)
	CheckNoError(t, resp)
	if len(posts.Order) != 1 && posts.Order[0] == post3.Id {
		t.Fatal("wrong search")
	}

	if posts, resp = Client.SearchPosts(th.BasicTeam.Id, "*", false); len(posts.Order) != 0 {
		t.Fatal("searching for just * shouldn't return any results")
	}

	posts, resp = Client.SearchPosts(th.BasicTeam.Id, "post1 post2", true)
	CheckNoError(t, resp)
	if len(posts.Order) != 2 {
		t.Fatal("wrong search results")
	}

	_, resp = Client.SearchPosts("junk", "#sgtitlereview", false)
	CheckBadRequestStatus(t, resp)

	_, resp = Client.SearchPosts(model.NewId(), "#sgtitlereview", false)
	CheckForbiddenStatus(t, resp)

	_, resp = Client.SearchPosts(th.BasicTeam.Id, "", false)
	CheckBadRequestStatus(t, resp)

	Client.Logout()
	_, resp = Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)
	CheckUnauthorizedStatus(t, resp)

}

func TestSearchHashtagPosts(t *testing.T) {
	th := Setup().InitBasic()
1287
	defer th.TearDown()
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	th.LoginBasic()
	Client := th.Client

	message := "#sgtitlereview with space"
	_ = th.CreateMessagePost(message)

	message = "#sgtitlereview\n with return"
	_ = th.CreateMessagePost(message)

	message = "no hashtag"
	_ = th.CreateMessagePost(message)

	posts, resp := Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)
	CheckNoError(t, resp)
	if len(posts.Order) != 2 {
		t.Fatal("wrong search results")
	}

	Client.Logout()
	_, resp = Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)
	CheckUnauthorizedStatus(t, resp)
}

func TestSearchPostsInChannel(t *testing.T) {
	th := Setup().InitBasic()
1313
	defer th.TearDown()
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
	th.LoginBasic()
	Client := th.Client

	channel := th.CreatePublicChannel()

	message := "sgtitlereview with space"
	_ = th.CreateMessagePost(message)

	message = "sgtitlereview\n with return"
	_ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)

	message = "other message with no return"
	_ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)

	message = "other message with no return"
	_ = th.CreateMessagePostWithClient(Client, channel, message)

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:", false); len(posts.Order) != 0 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "in:", false); len(posts.Order) != 0 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:"+th.BasicChannel.Name, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "in:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "ChAnNeL:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview", false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview channel:"+th.BasicChannel.Name, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview in: "+th.BasicChannel2.Name, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview channel: "+th.BasicChannel2.Name, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel: "+th.BasicChannel2.Name+" channel: "+channel.Name, false); len(posts.Order) != 3 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

}

func TestSearchPostsFromUser(t *testing.T) {
	th := Setup().InitBasic()
1379
	defer th.TearDown()
1380 1381 1382 1383
	Client := th.Client

	th.LoginTeamAdmin()
	user := th.CreateUser()
1384
	th.LinkUserToTeam(user, th.BasicTeam)
Chris's avatar
Chris committed
1385 1386
	th.App.AddUserToChannel(user, th.BasicChannel)
	th.App.AddUserToChannel(user, th.BasicChannel2)
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

	message := "sgtitlereview with space"
	_ = th.CreateMessagePost(message)

	Client.Logout()
	th.LoginBasic2()

	message = "sgtitlereview\n with return"
	_ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.TeamAdminUser.Username, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" sgtitlereview", false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	message = "hullo"
	_ = th.CreateMessagePost(message)

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" in:"+th.BasicChannel.Name, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	Client.Login(user.Email, user.Password)

	// wait for the join/leave messages to be created for user3 since they're done asynchronously
	time.Sleep(100 * time.Millisecond)

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username, false); len(posts.Order) != 2 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username+" in:"+th.BasicChannel2.Name, false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}

	message = "coconut"
	_ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)

	if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username+" in:"+th.BasicChannel2.Name+" coconut", false); len(posts.Order) != 1 {
		t.Fatalf("wrong number of posts returned %v", len(posts.Order))
	}
}
1440 1441 1442

func TestGetFileInfosForPost(t *testing.T) {
	th := Setup().InitBasic().InitSystemAdmin()
1443
	defer th.TearDown()
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
	Client := th.Client

	fileIds := make([]string, 3, 3)
	if data, err := readTestFile("test.png"); err != nil {
		t.Fatal(err)
	} else {
		for i := 0; i < 3; i++ {
			fileResp, _ := Client.UploadFile(data, th.BasicChannel.Id, "test.png")
			fileIds[i] = fileResp.FileInfos[0].Id
		}
	}

1456
	post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", FileIds: fileIds}
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	post, _ = Client.CreatePost(post)

	infos, resp := Client.GetFileInfosForPost(post.Id, "")
	CheckNoError(t, resp)

	if len(infos) != 3 {
		t.Fatal("missing file infos")
	}

	found := false
	for _, info := range infos {
		if info.Id == fileIds[0] {
			found = true
		}
	}

	if !found {
		t.Fatal("missing file info")
	}

	infos, resp = Client.GetFileInfosForPost(post.Id, resp.Etag)
	CheckEtag(t, infos, resp)

	infos, resp = Client.GetFileInfosForPost(th.BasicPost.Id, "")
	CheckNoError(t, resp)

	if len(infos) != 0 {
		t.Fatal("should have no file infos")
	}

	_, resp = Client.GetFileInfosForPost("junk", "")
	CheckBadRequestStatus(t, resp)

	_, resp = Client.GetFileInfosForPost(model.NewId(), "")
	CheckForbiddenStatus(t, resp)

	Client.Logout()
	_, resp = Client.GetFileInfosForPost(model.NewId(), "")
	CheckUnauthorizedStatus(t, resp)

	_, resp = th.SystemAdminClient.GetFileInfosForPost(th.BasicPost.Id, "")
	CheckNoError(t, resp)
}