PLT-1378 Initial version of emoji reactions (#4520)

* Refactored emoji.json to support multiple aliases and emoji categories

* Added custom category to emoji.jsx and stabilized all fields

* Removed conflicting aliases for :mattermost: and :ca:

* fixup after store changes

* Added emoji reactions

* Removed reactions for an emoji when that emoji is deleted

* Fixed incorrect test case

* Renamed ReactionList to ReactionListView

* Fixed 👍 and 👎 not showing up as possible reactions

* Removed text emoticons from emoji reaction autocomplete

* Changed emoji reactions to be sorted by the order that they were first created

* Set a maximum number of listeners for the ReactionStore

* Removed unused code from Textbox component

* Fixed reaction permissions

* Changed error code when trying to modify reactions for another user

* Fixed merge conflicts

* Properly applied theme colours to reactions

* Fixed ESLint and gofmt errors

* Fixed ReactionListContainer to properly update when its post prop changes

* Removed unnecessary escape characters from reaction regexes

* Shared reaction message pattern between CreatePost and CreateComment

* Removed an unnecessary select query when saving a reaction

* Changed reactions route to be under /reactions

* Fixed copyright dates on newly added files

* Removed debug code that prevented all unit tests from being ran

* Cleaned up unnecessary code for reactions

* Renamed ReactionStore.List to ReactionStore.GetForPost
Этот коммит содержится в:
Harrison Healey
2016-11-30 13:55:49 -05:00
коммит произвёл GitHub
родитель 2bf0342d13
Коммит 165ad0d4f7
47 изменённых файлов: 2154 добавлений и 98 удалений

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

@@ -103,6 +103,7 @@ func InitApi() {
InitEmoji()
InitStatus()
InitWebrtc()
InitReaction()
InitDeprecated()
// 404 on any api route before web.go has a chance to serve it

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

@@ -209,11 +209,14 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
var emoji *model.Emoji
if result := <-Srv.Store.Emoji().Get(id); result.Err != nil {
c.Err = result.Err
return
} else {
if c.Session.UserId != result.Data.(*model.Emoji).CreatorId && !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) {
emoji = result.Data.(*model.Emoji)
if c.Session.UserId != emoji.CreatorId && !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) {
c.Err = model.NewLocAppError("deleteEmoji", "api.emoji.delete.permissions.app_error", nil, "user_id="+c.Session.UserId)
c.Err.StatusCode = http.StatusUnauthorized
return
@@ -226,6 +229,7 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) {
}
go deleteEmojiImage(id)
go deleteReactionsForEmoji(emoji.Name)
ReturnStatusOK(w)
}
@@ -236,6 +240,13 @@ func deleteEmojiImage(id string) {
}
}
func deleteReactionsForEmoji(emojiName string) {
if result := <-Srv.Store.Reaction().DeleteAllWithEmojiName(emojiName); result.Err != nil {
l4g.Warn(utils.T("api.emoji.delete.delete_reactions.app_error"), emojiName)
l4g.Warn(result.Err)
}
}
func getEmojiImage(c *Context, w http.ResponseWriter, r *http.Request) {
if !*utils.Cfg.ServiceSettings.EnableCustomEmoji {
c.Err = model.NewLocAppError("getEmojiImage", "api.emoji.disabled.app_error", nil, "")

203
api/reaction.go Обычный файл
Просмотреть файл

@@ -0,0 +1,203 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api
import (
l4g "github.com/alecthomas/log4go"
"github.com/gorilla/mux"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
"net/http"
)
func InitReaction() {
l4g.Debug(utils.T("api.reaction.init.debug"))
BaseRoutes.NeedPost.Handle("/reactions/save", ApiUserRequired(saveReaction)).Methods("POST")
BaseRoutes.NeedPost.Handle("/reactions/delete", ApiUserRequired(deleteReaction)).Methods("POST")
BaseRoutes.NeedPost.Handle("/reactions", ApiUserRequired(listReactions)).Methods("GET")
}
func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) {
reaction := model.ReactionFromJson(r.Body)
if reaction == nil {
c.SetInvalidParam("saveReaction", "reaction")
return
}
if reaction.UserId != c.Session.UserId {
c.Err = model.NewLocAppError("saveReaction", "api.reaction.save_reaction.user_id.app_error", nil, "")
c.Err.StatusCode = http.StatusForbidden
return
}
params := mux.Vars(r)
channelId := params["channel_id"]
if len(channelId) != 26 {
c.SetInvalidParam("saveReaction", "channelId")
return
}
if !HasPermissionToChannelContext(c, channelId, model.PERMISSION_READ_CHANNEL) {
return
}
postId := params["post_id"]
if len(postId) != 26 || postId != reaction.PostId {
c.SetInvalidParam("saveReaction", "postId")
return
}
pchan := Srv.Store.Post().Get(reaction.PostId)
var postHadReactions bool
if result := <-pchan; result.Err != nil {
c.Err = result.Err
return
} else if post := result.Data.(*model.PostList).Posts[postId]; post.ChannelId != channelId {
c.Err = model.NewLocAppError("saveReaction", "api.reaction.save_reaction.mismatched_channel_id.app_error",
nil, "channelId="+channelId+", post.ChannelId="+post.ChannelId+", postId="+postId)
c.Err.StatusCode = http.StatusBadRequest
return
} else {
postHadReactions = post.HasReactions
}
if result := <-Srv.Store.Reaction().Save(reaction); result.Err != nil {
c.Err = result.Err
return
} else {
go sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, channelId, reaction, postHadReactions)
reaction := result.Data.(*model.Reaction)
w.Write([]byte(reaction.ToJson()))
}
}
func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) {
reaction := model.ReactionFromJson(r.Body)
if reaction == nil {
c.SetInvalidParam("deleteReaction", "reaction")
return
}
if reaction.UserId != c.Session.UserId {
c.Err = model.NewLocAppError("deleteReaction", "api.reaction.delete_reaction.user_id.app_error", nil, "")
c.Err.StatusCode = http.StatusForbidden
return
}
params := mux.Vars(r)
channelId := params["channel_id"]
if len(channelId) != 26 {
c.SetInvalidParam("deleteReaction", "channelId")
return
}
if !HasPermissionToChannelContext(c, channelId, model.PERMISSION_READ_CHANNEL) {
return
}
postId := params["post_id"]
if len(postId) != 26 || postId != reaction.PostId {
c.SetInvalidParam("deleteReaction", "postId")
return
}
pchan := Srv.Store.Post().Get(reaction.PostId)
var postHadReactions bool
if result := <-pchan; result.Err != nil {
c.Err = result.Err
return
} else if post := result.Data.(*model.PostList).Posts[postId]; post.ChannelId != channelId {
c.Err = model.NewLocAppError("deleteReaction", "api.reaction.delete_reaction.mismatched_channel_id.app_error",
nil, "channelId="+channelId+", post.ChannelId="+post.ChannelId+", postId="+postId)
c.Err.StatusCode = http.StatusBadRequest
return
} else {
postHadReactions = post.HasReactions
}
if result := <-Srv.Store.Reaction().Delete(reaction); result.Err != nil {
c.Err = result.Err
return
} else {
go sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, channelId, reaction, postHadReactions)
ReturnStatusOK(w)
}
}
func sendReactionEvent(event string, channelId string, reaction *model.Reaction, postHadReactions bool) {
// send out that a reaction has been added/removed
go func() {
message := model.NewWebSocketEvent(event, "", channelId, "", nil)
message.Add("reaction", reaction.ToJson())
Publish(message)
}()
// send out that a post was updated if post.HasReactions has changed
go func() {
var post *model.Post
if result := <-Srv.Store.Post().Get(reaction.PostId); result.Err != nil {
l4g.Warn(utils.T("api.reaction.send_reaction_event.post.app_error"))
return
} else {
post = result.Data.(*model.PostList).Posts[reaction.PostId]
}
if post.HasReactions != postHadReactions {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", channelId, "", nil)
message.Add("post", post.ToJson())
Publish(message)
}
}()
}
func listReactions(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
channelId := params["channel_id"]
if len(channelId) != 26 {
c.SetInvalidParam("deletePost", "channelId")
return
}
postId := params["post_id"]
if len(postId) != 26 {
c.SetInvalidParam("listReactions", "postId")
return
}
pchan := Srv.Store.Post().Get(postId)
if !HasPermissionToChannelContext(c, channelId, model.PERMISSION_READ_CHANNEL) {
return
}
if result := <-pchan; result.Err != nil {
c.Err = result.Err
return
} else if post := result.Data.(*model.PostList).Posts[postId]; post.ChannelId != channelId {
c.Err = model.NewLocAppError("listReactions", "api.reaction.list_reactions.mismatched_channel_id.app_error",
nil, "channelId="+channelId+", post.ChannelId="+post.ChannelId+", postId="+postId)
c.Err.StatusCode = http.StatusBadRequest
return
}
if result := <-Srv.Store.Reaction().GetForPost(postId); result.Err != nil {
c.Err = result.Err
return
} else {
reactions := result.Data.([]*model.Reaction)
w.Write([]byte(model.ReactionsToJson(reactions)))
}
}

314
api/reaction_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,314 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api
import (
"testing"
"github.com/mattermost/platform/model"
)
func TestSaveReaction(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
user := th.BasicUser
user2 := th.BasicUser2
channel := th.BasicChannel
post := th.BasicPost
// saving a reaction
reaction := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: "smile",
}
if returned, err := Client.SaveReaction(channel.Id, reaction); err != nil {
t.Fatal(err)
} else {
reaction = returned
}
if reactions := Client.MustGeneric(Client.ListReactions(channel.Id, post.Id)).([]*model.Reaction); len(reactions) != 1 || *reactions[0] != *reaction {
t.Fatal("didn't save reaction correctly")
}
// saving a duplicate reaction
if _, err := Client.SaveReaction(channel.Id, reaction); err != nil {
t.Fatal(err)
}
// saving a second reaction on a post
reaction2 := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: "sad",
}
if returned, err := Client.SaveReaction(channel.Id, reaction2); err != nil {
t.Fatal(err)
} else {
reaction2 = returned
}
if reactions := Client.MustGeneric(Client.ListReactions(channel.Id, post.Id)).([]*model.Reaction); len(reactions) != 2 ||
(*reactions[0] != *reaction && *reactions[1] != *reaction) || (*reactions[0] != *reaction2 && *reactions[1] != *reaction2) {
t.Fatal("didn't save multiple reactions correctly")
}
// saving a reaction without a user id
reaction3 := &model.Reaction{
PostId: post.Id,
EmojiName: "smile",
}
if _, err := Client.SaveReaction(channel.Id, reaction3); err == nil {
t.Fatal("should've failed to save reaction without user id")
}
// saving a reaction without a post id
reaction4 := &model.Reaction{
UserId: user.Id,
EmojiName: "smile",
}
if _, err := Client.SaveReaction(channel.Id, reaction4); err == nil {
t.Fatal("should've failed to save reaction without post id")
}
// saving a reaction without a emoji name
reaction5 := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
}
if _, err := Client.SaveReaction(channel.Id, reaction5); err == nil {
t.Fatal("should've failed to save reaction without emoji name")
}
// saving a reaction for another user
reaction6 := &model.Reaction{
UserId: user2.Id,
PostId: post.Id,
EmojiName: "smile",
}
if _, err := Client.SaveReaction(channel.Id, reaction6); err == nil {
t.Fatal("should've failed to save reaction for another user")
}
// saving a reaction to a channel we're not a member of
th.LoginBasic2()
channel2 := th.CreateChannel(th.BasicClient, th.BasicTeam)
post2 := th.CreatePost(th.BasicClient, channel2)
th.LoginBasic()
reaction7 := &model.Reaction{
UserId: user.Id,
PostId: post2.Id,
EmojiName: "smile",
}
if _, err := Client.SaveReaction(channel2.Id, reaction7); err == nil {
t.Fatal("should've failed to save reaction to a channel we're not a member of")
}
// saving a reaction to a direct channel
directChannel := Client.Must(Client.CreateDirectChannel(user2.Id)).Data.(*model.Channel)
directPost := th.CreatePost(th.BasicClient, directChannel)
reaction8 := &model.Reaction{
UserId: user.Id,
PostId: directPost.Id,
EmojiName: "smile",
}
if returned, err := Client.SaveReaction(directChannel.Id, reaction8); err != nil {
t.Fatal(err)
} else {
reaction8 = returned
}
if reactions := Client.MustGeneric(Client.ListReactions(directChannel.Id, directPost.Id)).([]*model.Reaction); len(reactions) != 1 || *reactions[0] != *reaction8 {
t.Fatal("didn't save reaction correctly")
}
// saving a reaction for a post in the wrong channel
reaction9 := &model.Reaction{
UserId: user.Id,
PostId: directPost.Id,
EmojiName: "sad",
}
if _, err := Client.SaveReaction(channel.Id, reaction9); err == nil {
t.Fatal("should've failed to save reaction to a post that isn't in the given channel")
}
}
func TestDeleteReaction(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
user := th.BasicUser
user2 := th.BasicUser2
channel := th.BasicChannel
post := th.BasicPost
reaction1 := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: "smile",
}
// deleting a reaction that does exist
Client.MustGeneric(Client.SaveReaction(channel.Id, reaction1))
if err := Client.DeleteReaction(channel.Id, reaction1); err != nil {
t.Fatal(err)
}
if reactions := Client.MustGeneric(Client.ListReactions(channel.Id, post.Id)).([]*model.Reaction); len(reactions) != 0 {
t.Fatal("should've deleted reaction")
}
// deleting one reaction when a post has multiple
reaction2 := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: "sad",
}
reaction1 = Client.MustGeneric(Client.SaveReaction(channel.Id, reaction1)).(*model.Reaction)
reaction2 = Client.MustGeneric(Client.SaveReaction(channel.Id, reaction2)).(*model.Reaction)
if err := Client.DeleteReaction(channel.Id, reaction2); err != nil {
t.Fatal(err)
}
if reactions := Client.MustGeneric(Client.ListReactions(channel.Id, post.Id)).([]*model.Reaction); len(reactions) != 1 || *reactions[0] != *reaction1 {
t.Fatal("should've deleted only one reaction")
}
// deleting a reaction made by another user
reaction3 := &model.Reaction{
UserId: user2.Id,
PostId: post.Id,
EmojiName: "smile",
}
th.LoginBasic2()
Client.Must(Client.JoinChannel(channel.Id))
reaction3 = Client.MustGeneric(Client.SaveReaction(channel.Id, reaction3)).(*model.Reaction)
th.LoginBasic()
if err := Client.DeleteReaction(channel.Id, reaction3); err == nil {
t.Fatal("should've failed to delete another user's reaction")
}
// deleting a reaction for a post we can't see
channel2 := th.CreateChannel(th.BasicClient, th.BasicTeam)
post2 := th.CreatePost(th.BasicClient, channel2)
reaction4 := &model.Reaction{
UserId: user.Id,
PostId: post2.Id,
EmojiName: "smile",
}
reaction4 = Client.MustGeneric(Client.SaveReaction(channel2.Id, reaction4)).(*model.Reaction)
Client.Must(Client.LeaveChannel(channel2.Id))
if err := Client.DeleteReaction(channel2.Id, reaction4); err == nil {
t.Fatal("should've failed to delete a reaction from a channel we're not in")
}
// deleting a reaction for a post with the wrong channel
channel3 := th.CreateChannel(th.BasicClient, th.BasicTeam)
reaction5 := &model.Reaction{
UserId: user.Id,
PostId: post.Id,
EmojiName: "happy",
}
if _, err := Client.SaveReaction(channel3.Id, reaction5); err == nil {
t.Fatal("should've failed to save reaction to a post that isn't in the given channel")
}
}
func TestListReactions(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
user := th.BasicUser
user2 := th.BasicUser2
channel := th.BasicChannel
post := th.BasicPost
userReactions := []*model.Reaction{
{
UserId: user.Id,
PostId: post.Id,
EmojiName: "smile",
},
{
UserId: user.Id,
PostId: post.Id,
EmojiName: "happy",
},
{
UserId: user.Id,
PostId: post.Id,
EmojiName: "sad",
},
}
for i, reaction := range userReactions {
userReactions[i] = Client.MustGeneric(Client.SaveReaction(channel.Id, reaction)).(*model.Reaction)
}
th.LoginBasic2()
Client.Must(Client.JoinChannel(channel.Id))
userReactions2 := []*model.Reaction{
{
UserId: user2.Id,
PostId: post.Id,
EmojiName: "smile",
},
{
UserId: user2.Id,
PostId: post.Id,
EmojiName: "sad",
},
}
for i, reaction := range userReactions2 {
userReactions2[i] = Client.MustGeneric(Client.SaveReaction(channel.Id, reaction)).(*model.Reaction)
}
if reactions, err := Client.ListReactions(channel.Id, post.Id); err != nil {
t.Fatal(err)
} else if len(reactions) != 5 {
t.Fatal("should've returned 5 reactions")
} else {
checkForReaction := func(expected *model.Reaction) {
found := false
for _, reaction := range reactions {
if *reaction == *expected {
found = true
break
}
}
if !found {
t.Fatalf("didn't return expected reaction %v", *expected)
}
}
for _, reaction := range userReactions {
checkForReaction(reaction)
}
for _, reaction := range userReactions2 {
checkForReaction(reaction)
}
}
}

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

@@ -805,6 +805,10 @@
"id": "api.emoji.create.too_large.app_error",
"translation": "Unable to create emoji. Image must be less than 1 MB in size."
},
{
"id": "api.emoji.delete.delete_reactions.app_error",
"translation": "Unable to delete reactions when deleting emoji with emoji name %v"
},
{
"id": "api.emoji.delete.permissions.app_error",
"translation": "Inappropriate permissions to delete emoji."
@@ -1503,6 +1507,22 @@
"id": "api.preference.save_preferences.set_details.app_error",
"translation": "session.user_id={{.SessionUserId}}, preference.user_id={{.PreferenceUserId}}"
},
{
"id": "api.reaction.delete_reaction.mismatched_channel_id.app_error",
"translation": "Failed to save reaction when channel id in URL doesn't match post id in URL"
},
{
"id": "api.reaction.list_reactions.mismatched_channel_id.app_error",
"translation": "Failed to get reactions when channel id in URL doesn't match post id in URL"
},
{
"id": "api.reaction.save_reaction.mismatched_channel_id.app_error",
"translation": "Failed to save reaction when channel id in URL doesn't match post id in URL"
},
{
"id": "api.reaction.send_reaction_event.post.app_error",
"translation": "Failed to get post when sending websocket event for reaction"
},
{
"id": "api.saml.save_certificate.app_error",
"translation": "Certificate did not save properly."
@@ -3707,6 +3727,22 @@
"id": "model.preference.is_valid.value.app_error",
"translation": "Value is too long"
},
{
"id": "model.reaction.is_valid.create_at.app_error",
"translation": "Create at must be a valid time"
},
{
"id": "model.reaction.is_valid.emoji_name.app_error",
"translation": "Invalid emoji name"
},
{
"id": "model.reaction.is_valid.post_id.app_error",
"translation": "Invalid post id"
},
{
"id": "model.reaction.is_valid.user_id.app_error",
"translation": "Invalid user id"
},
{
"id": "model.team.is_valid.characters.app_error",
"translation": "Name must be 2 or more lowercase alphanumeric characters"
@@ -4575,6 +4611,46 @@
"id": "store.sql_preference.update.app_error",
"translation": "We couldn't update the preference"
},
{
"id": "store.sql_reaction.delete.begin.app_error",
"translation": "Unable to open transaction while deleting reaction"
},
{
"id": "store.sql_reaction.delete.commit.app_error",
"translation": "Unable to commit transaction while deleting reaction"
},
{
"id": "store.sql_reaction.delete.save.app_error",
"translation": "Unable to delete reaction"
},
{
"id": "store.sql_reaction.delete_all_with_emoj_name.delete_reactions.app_error",
"translation": "Unable to delete reactions with the given emoji name"
},
{
"id": "store.sql_reaction.delete_all_with_emoj_name.get_reactions.app_error",
"translation": "Unable to get reactions with the given emoji name"
},
{
"id": "store.sql_reaction.delete_all_with_emoji_name.update_post.warn",
"translation": "Unable to update Post.HasReactions while removing reactions post_id=%v, error=%v"
},
{
"id": "store.sql_reaction.get_for_post.app_error",
"translation": "Unable to get reactions for post"
},
{
"id": "store.sql_reaction.save.begin.app_error",
"translation": "Unable to open transaction while saving reaction"
},
{
"id": "store.sql_reaction.save.commit.app_error",
"translation": "Unable to commit transaction while saving reaction"
},
{
"id": "store.sql_reaction.save.save.app_error",
"translation": "Unable to save reaction"
},
{
"id": "store.sql_session.analytics_session_count.app_error",
"translation": "We couldn't count the sessions"

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

@@ -2102,6 +2102,7 @@ func (c *Client) DeleteEmoji(id string) (bool, *AppError) {
if r, err := c.DoApiPost(c.GetEmojiRoute()+"/delete", MapToJson(data)); err != nil {
return false, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return c.CheckStatusOK(r), nil
}
@@ -2132,6 +2133,7 @@ func (c *Client) UploadCertificateFile(data []byte, contentType string) *AppErro
return AppErrorFromJson(rp.Body)
} else {
defer closeBody(rp)
c.fillInExtraProperties(rp)
return nil
}
}
@@ -2143,6 +2145,7 @@ func (c *Client) RemoveCertificateFile(filename string) *AppError {
return err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return nil
}
}
@@ -2154,6 +2157,7 @@ func (c *Client) SamlCertificateStatus(filename string) (map[string]interface{},
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return StringInterfaceFromJson(r.Body), nil
}
}
@@ -2182,3 +2186,36 @@ func (c *Client) GetFileInfosForPost(channelId string, postId string, etag strin
return FileInfosFromJson(r.Body), nil
}
}
// Saves an emoji reaction for a post in the given channel. Returns the saved reaction if successful, otherwise returns an AppError.
func (c *Client) SaveReaction(channelId string, reaction *Reaction) (*Reaction, *AppError) {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/save", reaction.PostId), reaction.ToJson()); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return ReactionFromJson(r.Body), nil
}
}
// Removes an emoji reaction for a post in the given channel. Returns nil if successful, otherwise returns an AppError.
func (c *Client) DeleteReaction(channelId string, reaction *Reaction) *AppError {
if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/delete", reaction.PostId), reaction.ToJson()); err != nil {
return err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return nil
}
}
// Lists all emoji reactions made for the given post in the given channel. Returns a list of Reactions if successful, otherwise returns an AppError.
func (c *Client) ListReactions(channelId string, postId string) ([]*Reaction, *AppError) {
if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions", postId), "", ""); err != nil {
return nil, err
} else {
defer closeBody(r)
c.fillInExtraProperties(r)
return ReactionsFromJson(r.Body), nil
}
}

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

@@ -38,6 +38,7 @@ type Post struct {
Filenames StringArray `json:"filenames,omitempty"` // Deprecated, do not use this field any more
FileIds StringArray `json:"file_ids,omitempty"`
PendingPostId string `json:"pending_post_id" db:"-"`
HasReactions bool `json:"has_reactions,omitempty"`
}
func (o *Post) ToJson() string {

78
model/reaction.go Обычный файл
Просмотреть файл

@@ -0,0 +1,78 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"encoding/json"
"io"
)
type Reaction struct {
UserId string `json:"user_id"`
PostId string `json:"post_id"`
EmojiName string `json:"emoji_name"`
CreateAt int64 `json:"create_at"`
}
func (o *Reaction) ToJson() string {
if b, err := json.Marshal(o); err != nil {
return ""
} else {
return string(b)
}
}
func ReactionFromJson(data io.Reader) *Reaction {
var o Reaction
if err := json.NewDecoder(data).Decode(&o); err != nil {
return nil
} else {
return &o
}
}
func ReactionsToJson(o []*Reaction) string {
if b, err := json.Marshal(o); err != nil {
return ""
} else {
return string(b)
}
}
func ReactionsFromJson(data io.Reader) []*Reaction {
var o []*Reaction
if err := json.NewDecoder(data).Decode(&o); err != nil {
return nil
} else {
return o
}
}
func (o *Reaction) IsValid() *AppError {
if len(o.UserId) != 26 {
return NewLocAppError("Reaction.IsValid", "model.reaction.is_valid.user_id.app_error", nil, "user_id="+o.UserId)
}
if len(o.PostId) != 26 {
return NewLocAppError("Reaction.IsValid", "model.reaction.is_valid.post_id.app_error", nil, "post_id="+o.PostId)
}
if len(o.EmojiName) == 0 || len(o.EmojiName) > 64 {
return NewLocAppError("Reaction.IsValid", "model.reaction.is_valid.emoji_name.app_error", nil, "emoji_name="+o.EmojiName)
}
if o.CreateAt == 0 {
return NewLocAppError("Reaction.IsValid", "model.reaction.is_valid.create_at.app_error", nil, "")
}
return nil
}
func (o *Reaction) PreSave() {
if o.CreateAt == 0 {
o.CreateAt = GetMillis()
}
}

64
model/reaction_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,64 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"strings"
"testing"
)
func TestReactionIsValid(t *testing.T) {
reaction := Reaction{
UserId: NewId(),
PostId: NewId(),
EmojiName: "emoji",
CreateAt: GetMillis(),
}
if err := reaction.IsValid(); err != nil {
t.Fatal(err)
}
reaction.UserId = ""
if err := reaction.IsValid(); err == nil {
t.Fatal("user id should be invalid")
}
reaction.UserId = "1234garbage"
if err := reaction.IsValid(); err == nil {
t.Fatal("user id should be invalid")
}
reaction.UserId = NewId()
reaction.PostId = ""
if err := reaction.IsValid(); err == nil {
t.Fatal("post id should be invalid")
}
reaction.PostId = "1234garbage"
if err := reaction.IsValid(); err == nil {
t.Fatal("post id should be invalid")
}
reaction.PostId = NewId()
reaction.EmojiName = ""
if err := reaction.IsValid(); err == nil {
t.Fatal("emoji name should be invalid")
}
reaction.EmojiName = strings.Repeat("a", 65)
if err := reaction.IsValid(); err == nil {
t.Fatal("emoji name should be invalid")
}
reaction.EmojiName = strings.Repeat("a", 64)
if err := reaction.IsValid(); err != nil {
t.Fatal(err)
}
reaction.CreateAt = 0
if err := reaction.IsValid(); err == nil {
t.Fatal("create at should be invalid")
}
}

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

@@ -27,6 +27,8 @@ const (
WEBSOCKET_EVENT_HELLO = "hello"
WEBSOCKET_EVENT_WEBRTC = "webrtc"
WEBSOCKET_AUTHENTICATION_CHALLENGE = "authentication_challenge"
WEBSOCKET_EVENT_REACTION_ADDED = "reaction_added"
WEBSOCKET_EVENT_REACTION_REMOVED = "reaction_removed"
)
type WebSocketMessage interface {

230
store/sql_reaction_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,230 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package store
import (
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
l4g "github.com/alecthomas/log4go"
"github.com/go-gorp/gorp"
)
type SqlReactionStore struct {
*SqlStore
}
func NewSqlReactionStore(sqlStore *SqlStore) ReactionStore {
s := &SqlReactionStore{sqlStore}
for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.Reaction{}, "Reactions").SetKeys(false, "UserId", "PostId", "EmojiName")
table.ColMap("UserId").SetMaxSize(26)
table.ColMap("PostId").SetMaxSize(26)
table.ColMap("EmojiName").SetMaxSize(64)
}
return s
}
func (s SqlReactionStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_reactions_post_id", "Reactions", "PostId")
}
func (s SqlReactionStore) Save(reaction *model.Reaction) StoreChannel {
storeChannel := make(StoreChannel)
go func() {
result := StoreResult{}
reaction.PreSave()
if result.Err = reaction.IsValid(); result.Err != nil {
storeChannel <- result
close(storeChannel)
return
}
if transaction, err := s.GetMaster().Begin(); err != nil {
result.Err = model.NewLocAppError("SqlReactionStore.Save", "store.sql_reaction.save.begin.app_error", nil, err.Error())
} else {
err := saveReactionAndUpdatePost(transaction, reaction)
if err != nil {
transaction.Rollback()
// We don't consider duplicated save calls as an error
if !IsUniqueConstraintError(err.Error(), []string{"reactions_pkey", "PRIMARY"}) {
result.Err = model.NewLocAppError("SqlPreferenceStore.Save", "store.sql_reaction.save.save.app_error", nil, err.Error())
}
} else {
if err := transaction.Commit(); err != nil {
// don't need to rollback here since the transaction is already closed
result.Err = model.NewLocAppError("SqlPreferenceStore.Save", "store.sql_preference.save.commit.app_error", nil, err.Error())
}
}
if result.Err == nil {
result.Data = reaction
}
}
storeChannel <- result
close(storeChannel)
}()
return storeChannel
}
func (s SqlReactionStore) Delete(reaction *model.Reaction) StoreChannel {
storeChannel := make(StoreChannel)
go func() {
result := StoreResult{}
if transaction, err := s.GetMaster().Begin(); err != nil {
result.Err = model.NewLocAppError("SqlReactionStore.Delete", "store.sql_reaction.delete.begin.app_error", nil, err.Error())
} else {
err := deleteReactionAndUpdatePost(transaction, reaction)
if err != nil {
transaction.Rollback()
result.Err = model.NewLocAppError("SqlPreferenceStore.Delete", "store.sql_reaction.delete.app_error", nil, err.Error())
} else if err := transaction.Commit(); err != nil {
// don't need to rollback here since the transaction is already closed
result.Err = model.NewLocAppError("SqlPreferenceStore.Delete", "store.sql_preference.delete.commit.app_error", nil, err.Error())
} else {
result.Data = reaction
}
}
storeChannel <- result
close(storeChannel)
}()
return storeChannel
}
func saveReactionAndUpdatePost(transaction *gorp.Transaction, reaction *model.Reaction) error {
if err := transaction.Insert(reaction); err != nil {
return err
}
return updatePostForReactions(transaction, reaction.PostId)
}
func deleteReactionAndUpdatePost(transaction *gorp.Transaction, reaction *model.Reaction) error {
if _, err := transaction.Exec(
`DELETE FROM
Reactions
WHERE
PostId = :PostId AND
UserId = :UserId AND
EmojiName = :EmojiName`,
map[string]interface{}{"PostId": reaction.PostId, "UserId": reaction.UserId, "EmojiName": reaction.EmojiName}); err != nil {
return err
}
return updatePostForReactions(transaction, reaction.PostId)
}
const (
// Set HasReactions = true if and only if the post has reactions, update UpdateAt only if HasReactions changes
UPDATE_POST_HAS_REACTIONS_QUERY = `UPDATE
Posts
SET
UpdateAt = (CASE
WHEN HasReactions != (SELECT count(0) > 0 FROM Reactions WHERE PostId = :PostId) THEN :UpdateAt
ELSE UpdateAt
END),
HasReactions = (SELECT count(0) > 0 FROM Reactions WHERE PostId = :PostId)
WHERE
Id = :PostId`
)
func updatePostForReactions(transaction *gorp.Transaction, postId string) error {
_, err := transaction.Exec(UPDATE_POST_HAS_REACTIONS_QUERY, map[string]interface{}{"PostId": postId, "UpdateAt": model.GetMillis()})
return err
}
func (s SqlReactionStore) GetForPost(postId string) StoreChannel {
storeChannel := make(StoreChannel)
go func() {
result := StoreResult{}
var reactions []*model.Reaction
if _, err := s.GetReplica().Select(&reactions,
`SELECT
*
FROM
Reactions
WHERE
PostId = :PostId
ORDER BY
CreateAt`, map[string]interface{}{"PostId": postId}); err != nil {
result.Err = model.NewLocAppError("SqlReactionStore.GetForPost", "store.sql_reaction.get_for_post.app_error", nil, "")
} else {
result.Data = reactions
}
storeChannel <- result
close(storeChannel)
}()
return storeChannel
}
func (s SqlReactionStore) DeleteAllWithEmojiName(emojiName string) StoreChannel {
storeChannel := make(StoreChannel)
go func() {
result := StoreResult{}
// doesn't use a transaction since it's better for this to half-finish than to not commit anything
var reactions []*model.Reaction
if _, err := s.GetReplica().Select(&reactions,
`SELECT
*
FROM
Reactions
WHERE
EmojiName = :EmojiName`, map[string]interface{}{"EmojiName": emojiName}); err != nil {
result.Err = model.NewLocAppError("SqlReactionStore.DeleteAllWithEmojiName",
"store.sql_reaction.delete_all_with_emoji_name.get_reactions.app_error", nil,
"emoji_name="+emojiName+", error="+err.Error())
storeChannel <- result
close(storeChannel)
return
}
if _, err := s.GetMaster().Exec(
`DELETE FROM
Reactions
WHERE
EmojiName = :EmojiName`, map[string]interface{}{"EmojiName": emojiName}); err != nil {
result.Err = model.NewLocAppError("SqlReactionStore.DeleteAllWithEmojiName",
"store.sql_reaction.delete_all_with_emoji_name.delete_reactions.app_error", nil,
"emoji_name="+emojiName+", error="+err.Error())
storeChannel <- result
close(storeChannel)
return
}
for _, reaction := range reactions {
if _, err := s.GetMaster().Exec(UPDATE_POST_HAS_REACTIONS_QUERY,
map[string]interface{}{"PostId": reaction.PostId, "UpdateAt": model.GetMillis()}); err != nil {
l4g.Warn(utils.T("store.sql_reaction.delete_all_with_emoji_name.update_post.warn"), reaction.PostId, err.Error())
}
}
storeChannel <- result
close(storeChannel)
}()
return storeChannel
}

270
store/sql_reaction_store_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,270 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package store
import (
"github.com/mattermost/platform/model"
"testing"
)
func TestReactionSave(t *testing.T) {
Setup()
post := Must(store.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
firstUpdateAt := post.UpdateAt
reaction1 := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
if result := <-store.Reaction().Save(reaction1); result.Err != nil {
t.Fatal(result.Err)
} else if saved := result.Data.(*model.Reaction); saved.UserId != reaction1.UserId ||
saved.PostId != reaction1.PostId || saved.EmojiName != reaction1.EmojiName {
t.Fatal("should've saved reaction and returned it")
}
var secondUpdateAt int64
if postList := Must(store.Post().Get(reaction1.PostId)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = true on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("should've marked post as updated when HasReactions changed")
} else {
secondUpdateAt = postList.Posts[post.Id].UpdateAt
}
if result := <-store.Reaction().Save(reaction1); result.Err != nil {
t.Log(result.Err)
t.Fatal("should've allowed saving a duplicate reaction")
}
// different user
reaction2 := &model.Reaction{
UserId: model.NewId(),
PostId: reaction1.PostId,
EmojiName: reaction1.EmojiName,
}
if result := <-store.Reaction().Save(reaction2); result.Err != nil {
t.Fatal(result.Err)
}
if postList := Must(store.Post().Get(reaction2.PostId)).(*model.PostList); postList.Posts[post.Id].UpdateAt != secondUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions hasn't changed")
}
// different post
reaction3 := &model.Reaction{
UserId: reaction1.UserId,
PostId: model.NewId(),
EmojiName: reaction1.EmojiName,
}
if result := <-store.Reaction().Save(reaction3); result.Err != nil {
t.Fatal(result.Err)
}
// different emoji
reaction4 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
EmojiName: model.NewId(),
}
if result := <-store.Reaction().Save(reaction4); result.Err != nil {
t.Fatal(result.Err)
}
// invalid reaction
reaction5 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
}
if result := <-store.Reaction().Save(reaction5); result.Err == nil {
t.Fatal("should've failed for invalid reaction")
}
}
func TestReactionDelete(t *testing.T) {
Setup()
post := Must(store.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
reaction := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
Must(store.Reaction().Save(reaction))
firstUpdateAt := Must(store.Post().Get(reaction.PostId)).(*model.PostList).Posts[post.Id].UpdateAt
if result := <-store.Reaction().Delete(reaction); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-store.Reaction().GetForPost(post.Id); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.Reaction)) != 0 {
t.Fatal("should've deleted reaction")
}
if postList := Must(store.Post().Get(post.Id)).(*model.PostList); postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = false on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions has changed after deleting reactions")
}
}
func TestReactionGetForPost(t *testing.T) {
Setup()
postId := model.NewId()
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: postId,
EmojiName: "smile",
},
{
UserId: model.NewId(),
PostId: postId,
EmojiName: "smile",
},
{
UserId: userId,
PostId: postId,
EmojiName: "sad",
},
{
UserId: userId,
PostId: model.NewId(),
EmojiName: "angry",
},
}
for _, reaction := range reactions {
Must(store.Reaction().Save(reaction))
}
if result := <-store.Reaction().GetForPost(postId); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions")
} else {
for _, reaction := range reactions {
found := false
for _, returnedReaction := range returned {
if returnedReaction.UserId == reaction.UserId && returnedReaction.PostId == reaction.PostId &&
returnedReaction.EmojiName == reaction.EmojiName {
found = true
break
}
}
if !found && reaction.PostId == postId {
t.Fatalf("should've returned reaction for post %v", reaction)
} else if found && reaction.PostId != postId {
t.Fatal("shouldn't have returned reaction for another post")
}
}
}
}
func TestReactionDeleteAllWithEmojiName(t *testing.T) {
Setup()
emojiToDelete := model.NewId()
post := Must(store.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post2 := Must(store.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post3 := Must(store.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: userId,
PostId: post.Id,
EmojiName: "sad",
},
{
UserId: userId,
PostId: post2.Id,
EmojiName: "angry",
},
{
UserId: userId,
PostId: post3.Id,
EmojiName: emojiToDelete,
},
}
for _, reaction := range reactions {
Must(store.Reaction().Save(reaction))
}
if result := <-store.Reaction().DeleteAllWithEmojiName(emojiToDelete); result.Err != nil {
t.Fatal(result.Err)
}
// check that the reactions were deleted
if returned := Must(store.Reaction().GetForPost(post.Id)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
} else {
for _, reaction := range returned {
if reaction.EmojiName == "smile" {
t.Fatal("should've removed reaction with emoji name")
}
}
}
if returned := Must(store.Reaction().GetForPost(post2.Id)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
}
if returned := Must(store.Reaction().GetForPost(post3.Id)).([]*model.Reaction); len(returned) != 0 {
t.Fatal("should've only removed reactions with emoji name")
}
// check that the posts are updated
if postList := Must(store.Post().Get(post.Id)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := Must(store.Post().Get(post2.Id)).(*model.PostList); !postList.Posts[post2.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := Must(store.Post().Get(post3.Id)).(*model.PostList); postList.Posts[post3.Id].HasReactions {
t.Fatal("post shouldn't have reactions any more")
}
}

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

@@ -84,6 +84,7 @@ type SqlStore struct {
emoji EmojiStore
status StatusStore
fileInfo FileInfoStore
reaction ReactionStore
SchemaVersion string
rrCounter int64
}
@@ -134,6 +135,7 @@ func NewSqlStore() Store {
sqlStore.emoji = NewSqlEmojiStore(sqlStore)
sqlStore.status = NewSqlStatusStore(sqlStore)
sqlStore.fileInfo = NewSqlFileInfoStore(sqlStore)
sqlStore.reaction = NewSqlReactionStore(sqlStore)
err := sqlStore.master.CreateTablesIfNotExists()
if err != nil {
@@ -161,6 +163,7 @@ func NewSqlStore() Store {
sqlStore.emoji.(*SqlEmojiStore).CreateIndexesIfNotExists()
sqlStore.status.(*SqlStatusStore).CreateIndexesIfNotExists()
sqlStore.fileInfo.(*SqlFileInfoStore).CreateIndexesIfNotExists()
sqlStore.reaction.(*SqlReactionStore).CreateIndexesIfNotExists()
sqlStore.preference.(*SqlPreferenceStore).DeleteUnusedFeatures()
@@ -676,6 +679,10 @@ func (ss *SqlStore) FileInfo() FileInfoStore {
return ss.fileInfo
}
func (ss *SqlStore) Reaction() ReactionStore {
return ss.reaction
}
func (ss *SqlStore) DropAllTables() {
ss.master.TruncateTables()
}

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

@@ -15,6 +15,7 @@ import (
)
const (
VERSION_3_6_0 = "3.6.0"
VERSION_3_5_0 = "3.5.0"
VERSION_3_4_0 = "3.4.0"
VERSION_3_3_0 = "3.3.0"
@@ -37,6 +38,7 @@ func UpgradeDatabase(sqlStore *SqlStore) {
UpgradeDatabaseToVersion33(sqlStore)
UpgradeDatabaseToVersion34(sqlStore)
UpgradeDatabaseToVersion35(sqlStore)
UpgradeDatabaseToVersion36(sqlStore)
// If the SchemaVersion is empty this this is the first time it has ran
// so lets set it to the current version.
@@ -210,3 +212,17 @@ func UpgradeDatabaseToVersion35(sqlStore *SqlStore) {
saveSchemaVersion(sqlStore, VERSION_3_5_0)
}
}
func UpgradeDatabaseToVersion36(sqlStore *SqlStore) {
//if shouldPerformUpgrade(sqlStore, VERSION_3_5_0, VERSION_3_6_0) {
sqlStore.CreateColumnIfNotExists("Posts", "HasReactions", "tinyint", "boolean", "0")
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO FIXME UNCOMMENT WHEN WE DO RELEASE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//sqlStore.Session().RemoveAllSessions()
//saveSchemaVersion(sqlStore, VERSION_3_6_0)
//}
}

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

@@ -46,6 +46,7 @@ type Store interface {
Emoji() EmojiStore
Status() StatusStore
FileInfo() FileInfoStore
Reaction() ReactionStore
MarkSystemRanUnitTests()
Close()
DropAllTables()
@@ -310,3 +311,10 @@ type FileInfoStore interface {
AttachToPost(fileId string, postId string) StoreChannel
DeleteForPost(postId string) StoreChannel
}
type ReactionStore interface {
Save(reaction *model.Reaction) StoreChannel
Delete(reaction *model.Reaction) StoreChannel
GetForPost(postId string) StoreChannel
DeleteAllWithEmojiName(emojiName string) StoreChannel
}

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

@@ -1,7 +1,7 @@
# Emoticon Testing
Verify that all emoticons render.
:mm: :mattermost:
:mattermost:
### Emoticon - Punctuation

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

@@ -1,3 +1,3 @@
### Emoticons - Places
:house: :house_with_garden: :school: :office: :post_office: :hospital: :bank: :convenience_store: :love_hotel: :hotel: :wedding: :church: :department_store: :european_post_office: :city_sunrise: :city_sunset: :japanese_castle: :european_castle: :tent: :factory: :tokyo_tower: :japan: :mount_fuji: :sunrise_over_mountains: :sunrise: :stars: :statue_of_liberty: :bridge_at_night: :carousel_horse: :rainbow: :ferris_wheel: :fountain: :roller_coaster: :ship: :speedboat: :boat: :sailboat: :rowboat: :anchor: :rocket: :airplane: :helicopter: :steam_locomotive: :tram: :mountain_railway: :bike: :aerial_tramway: :suspension_railway: :mountain_cableway: :tractor: :blue_car: :oncoming_automobile: :car: :red_car: :taxi: :oncoming_taxi: :articulated_lorry: :bus: :oncoming_bus: :rotating_light: :police_car: :oncoming_police_car: :fire_engine: :ambulance: :minibus: :truck: :train: :station: :train2: :bullettrain_front: :bullettrain_side: :light_rail: :monorail: :railway_car: :trolleybus: :ticket: :fuelpump: :vertical_traffic_light: :traffic_light: :warning: :construction: :beginner: :atm: :slot_machine: :busstop: :barber: :hotsprings: :checkered_flag: :crossed_flags: :izakaya_lantern: :moyai: :circus_tent: :performing_arts: :round_pushpin: :triangular_flag_on_post: :jp: :kr: :cn: :us: :fr: :es: :it: :ru: :gb: :uk: :de: :ca: :eh: :pk: :za:
:house: :house_with_garden: :school: :office: :post_office: :hospital: :bank: :convenience_store: :love_hotel: :hotel: :wedding: :church: :department_store: :european_post_office: :city_sunrise: :city_sunset: :japanese_castle: :european_castle: :tent: :factory: :tokyo_tower: :japan: :mount_fuji: :sunrise_over_mountains: :sunrise: :stars: :statue_of_liberty: :bridge_at_night: :carousel_horse: :rainbow: :ferris_wheel: :fountain: :roller_coaster: :ship: :speedboat: :boat: :sailboat: :rowboat: :anchor: :rocket: :airplane: :helicopter: :steam_locomotive: :tram: :mountain_railway: :bike: :aerial_tramway: :suspension_railway: :mountain_cableway: :tractor: :blue_car: :oncoming_automobile: :car: :red_car: :taxi: :oncoming_taxi: :articulated_lorry: :bus: :oncoming_bus: :rotating_light: :police_car: :oncoming_police_car: :fire_engine: :ambulance: :minibus: :truck: :train: :station: :train2: :bullettrain_front: :bullettrain_side: :light_rail: :monorail: :railway_car: :trolleybus: :ticket: :fuelpump: :vertical_traffic_light: :traffic_light: :warning: :construction: :beginner: :atm: :slot_machine: :busstop: :barber: :hotsprings: :checkered_flag: :crossed_flags: :izakaya_lantern: :moyai: :circus_tent: :performing_arts: :round_pushpin: :triangular_flag_on_post: :jp: :kr: :cn: :us: :fr: :es: :it: :ru: :gb: :uk: :de: :ca: :pk: :za:

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

@@ -252,3 +252,23 @@ export function loadProfilesForPosts(posts) {
AsyncClient.getProfilesByIds(list);
}
export function addReaction(channelId, postId, emojiName) {
const reaction = {
post_id: postId,
user_id: UserStore.getCurrentId(),
emoji_name: emojiName
};
AsyncClient.saveReaction(channelId, reaction);
}
export function removeReaction(channelId, postId, emojiName) {
const reaction = {
post_id: postId,
user_id: UserStore.getCurrentId(),
emoji_name: emojiName
};
AsyncClient.deleteReaction(channelId, reaction);
}

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

@@ -11,6 +11,7 @@ import BrowserStore from 'stores/browser_store.jsx';
import ErrorStore from 'stores/error_store.jsx';
import NotificationStore from 'stores/notification_store.jsx'; //eslint-disable-line no-unused-vars
import AppDispatcher from 'dispatcher/app_dispatcher.jsx';
import Client from 'client/web_client.jsx';
import WebSocketClient from 'client/web_websocket_client.jsx';
import * as WebrtcActions from './webrtc_actions.jsx';
@@ -23,7 +24,7 @@ import {loadProfilesAndTeamMembersForDMSidebar} from 'actions/user_actions.jsx';
import {loadChannelsForCurrentUser} from 'actions/channel_actions.jsx';
import * as StatusActions from 'actions/status_actions.jsx';
import {Constants, SocketEvents, UserStatuses} from 'utils/constants.jsx';
import {ActionTypes, Constants, SocketEvents, UserStatuses} from 'utils/constants.jsx';
import {browserHistory} from 'react-router/es6';
@@ -165,6 +166,14 @@ function handleEvent(msg) {
handleWebrtc(msg);
break;
case SocketEvents.REACTION_ADDED:
handleReactionAddedEvent(msg);
break;
case SocketEvents.REACTION_REMOVED:
handleReactionRemovedEvent(msg);
break;
default:
}
}
@@ -320,3 +329,23 @@ function handleWebrtc(msg) {
const data = msg.data;
return WebrtcActions.handle(data);
}
function handleReactionAddedEvent(msg) {
const reaction = JSON.parse(msg.data.reaction);
AppDispatcher.handleServerAction({
type: ActionTypes.ADDED_REACTION,
postId: reaction.post_id,
reaction
});
}
function handleReactionRemovedEvent(msg) {
const reaction = JSON.parse(msg.data.reaction);
AppDispatcher.handleServerAction({
type: ActionTypes.REMOVED_REACTION,
postId: reaction.post_id,
reaction
});
}

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

@@ -2005,11 +2005,11 @@ export default class Client {
removeCertificateFile(filename, success, error) {
request.
post(`${this.getAdminRoute()}/remove_certificate`).
set(this.defaultHeaders).
accept('application/json').
send({filename}).
end(this.handleResponse.bind(this, 'removeCertificateFile', success, error));
post(`${this.getAdminRoute()}/remove_certificate`).
set(this.defaultHeaders).
accept('application/json').
send({filename}).
end(this.handleResponse.bind(this, 'removeCertificateFile', success, error));
}
samlCertificateStatus(success, error) {
@@ -2030,6 +2030,33 @@ export default class Client {
});
}
saveReaction(channelId, reaction, success, error) {
request.
post(`${this.getChannelNeededRoute(channelId)}/posts/${reaction.post_id}/reactions/save`).
set(this.defaultHeaders).
accept('application/json').
send(reaction).
end(this.handleResponse.bind(this, 'saveReaction', success, error));
}
deleteReaction(channelId, reaction, success, error) {
request.
post(`${this.getChannelNeededRoute(channelId)}/posts/${reaction.post_id}/reactions/delete`).
set(this.defaultHeaders).
accept('application/json').
send(reaction).
end(this.handleResponse.bind(this, 'deleteReaction', success, error));
}
listReactions(channelId, postId, success, error) {
request.
get(`${this.getChannelNeededRoute(channelId)}/posts/${postId}/reactions`).
set(this.defaultHeaders).
type('application/json').
accept('application/json').
end(this.handleResponse.bind(this, 'listReactions', success, error));
}
webrtcToken(success, error) {
request.post(`${this.getWebrtcRoute()}/token`).
set(this.defaultHeaders).

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

@@ -5,6 +5,7 @@ import $ from 'jquery';
import ReactDOM from 'react-dom';
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Client from 'client/web_client.jsx';
import EmojiStore from 'stores/emoji_store.jsx';
import UserStore from 'stores/user_store.jsx';
import PostDeletedModal from './post_deleted_modal.jsx';
import PostStore from 'stores/post_store.jsx';
@@ -17,6 +18,7 @@ import FilePreview from './file_preview.jsx';
import * as Utils from 'utils/utils.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as GlobalActions from 'actions/global_actions.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import Constants from 'utils/constants.jsx';
@@ -25,6 +27,8 @@ import {FormattedMessage} from 'react-intl';
const ActionTypes = Constants.ActionTypes;
const KeyCodes = Constants.KeyCodes;
import {REACTION_PATTERN} from './create_post.jsx';
import React from 'react';
export default class CreateComment extends React.Component {
@@ -34,6 +38,8 @@ export default class CreateComment extends React.Component {
this.lastTime = 0;
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSubmitPost = this.handleSubmitPost.bind(this);
this.handleSubmitReaction = this.handleSubmitReaction.bind(this);
this.commentMsgKeyPress = this.commentMsgKeyPress.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
@@ -100,15 +106,9 @@ export default class CreateComment extends React.Component {
return;
}
const post = {};
post.file_ids = [];
post.message = this.state.message;
const message = this.state.message;
if (post.message.trim().length === 0 && this.state.fileInfos.length === 0) {
return;
}
if (post.message.length > Constants.CHARACTER_LIMIT) {
if (message.length > Constants.CHARACTER_LIMIT) {
this.setState({
postError: (
<FormattedMessage
@@ -121,15 +121,43 @@ export default class CreateComment extends React.Component {
return;
}
MessageHistoryStore.storeMessageInHistory(this.state.message);
MessageHistoryStore.storeMessageInHistory(message);
if (message.trim().length === 0 && this.state.previews.length === 0) {
return;
}
const isReaction = REACTION_PATTERN.exec(message);
if (isReaction && EmojiStore.has(isReaction[2])) {
this.handleSubmitReaction(isReaction);
} else {
this.handleSubmitPost(message);
}
this.setState({
message: '',
submitting: false,
postError: null,
fileInfos: [],
serverError: null
});
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
}
handleSubmitPost(message) {
const userId = UserStore.getCurrentId();
const time = Utils.getTimestamp();
const post = {};
post.file_ids = [];
post.message = message;
post.channel_id = this.props.channelId;
post.root_id = this.props.rootId;
post.parent_id = this.props.rootId;
post.file_ids = this.state.fileInfos.map((info) => info.id);
const time = Utils.getTimestamp();
post.pending_post_id = `${userId}:${time}`;
post.user_id = userId;
post.create_at = time;
@@ -160,18 +188,21 @@ export default class CreateComment extends React.Component {
});
}
);
}
this.setState({
message: '',
submitting: false,
postError: null,
fileInfos: [],
serverError: null
});
handleSubmitReaction(isReaction) {
const action = isReaction[1];
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
const emojiName = isReaction[2];
const postId = this.props.latestPostId;
if (action === '+') {
PostActions.addReaction(this.props.channelId, postId, emojiName);
} else if (action === '-') {
PostActions.removeReaction(this.props.channelId, postId, emojiName);
}
PostStore.storeCommentDraft(this.props.rootId, null);
}
commentMsgKeyPress(e) {
@@ -455,5 +486,6 @@ export default class CreateComment extends React.Component {
CreateComment.propTypes = {
channelId: React.PropTypes.string.isRequired,
rootId: React.PropTypes.string.isRequired
rootId: React.PropTypes.string.isRequired,
latestPostId: React.PropTypes.string.isRequired
};

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

@@ -9,14 +9,16 @@ import FilePreview from './file_preview.jsx';
import PostDeletedModal from './post_deleted_modal.jsx';
import TutorialTip from './tutorial/tutorial_tip.jsx';
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import AppDispatcher from 'dispatcher/app_dispatcher.jsx';
import * as GlobalActions from 'actions/global_actions.jsx';
import Client from 'client/web_client.jsx';
import * as Utils from 'utils/utils.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as ChannelActions from 'actions/channel_actions.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import ChannelStore from 'stores/channel_store.jsx';
import EmojiStore from 'stores/emoji_store.jsx';
import PostStore from 'stores/post_store.jsx';
import MessageHistoryStore from 'stores/message_history_store.jsx';
import UserStore from 'stores/user_store.jsx';
@@ -34,6 +36,8 @@ const KeyCodes = Constants.KeyCodes;
import React from 'react';
export const REACTION_PATTERN = /^(\+|-):([^:\s]+):\s*$/;
export default class CreatePost extends React.Component {
constructor(props) {
super(props);
@@ -101,6 +105,7 @@ export default class CreatePost extends React.Component {
this.setState({submitting: true, serverError: null});
const isReaction = REACTION_PATTERN.exec(post.message);
if (post.message.indexOf('/') === 0) {
PostStore.storeDraft(this.state.channelId, null);
this.setState({message: '', postError: null, fileInfos: []});
@@ -123,14 +128,18 @@ export default class CreatePost extends React.Component {
const state = {};
state.serverError = err.message;
state.submitting = false;
this.setState(state);
this.setState({state});
}
}
);
} else if (isReaction && EmojiStore.has(isReaction[2])) {
this.sendReaction(isReaction);
} else {
this.sendMessage(post);
}
this.setState({message: '', submitting: false, postError: null, fileInfos: [], serverError: null});
const fasterThanHumanWillClick = 150;
const forceFocus = (Date.now() - this.state.lastBlurAt < fasterThanHumanWillClick);
this.focusTextbox(forceFocus);
@@ -148,7 +157,6 @@ export default class CreatePost extends React.Component {
post.parent_id = this.state.parentId;
GlobalActions.emitUserPostedEvent(post);
this.setState({message: '', submitting: false, postError: null, fileInfos: [], serverError: null});
Client.createPost(post,
(data) => {
@@ -177,6 +185,21 @@ export default class CreatePost extends React.Component {
);
}
sendReaction(isReaction) {
const action = isReaction[1];
const emojiName = isReaction[2];
const postId = PostStore.getLatestPost(this.state.channelId).id;
if (action === '+') {
PostActions.addReaction(this.state.channelId, postId, emojiName);
} else if (action === '-') {
PostActions.removeReaction(this.state.channelId, postId, emojiName);
}
PostStore.storeCurrentDraft(null);
}
focusTextbox(keepFocus = false) {
if (keepFocus || !Utils.isMobile()) {
this.refs.textbox.focus();

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

@@ -85,7 +85,7 @@ export default class AddEmoji extends React.Component {
});
return;
} else if (EmojiStore.getSystemEmojis().has(emoji.name)) {
} else if (EmojiStore.hasSystemEmoji(emoji.name)) {
this.setState({
saving: false,
error: (

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

@@ -255,6 +255,7 @@ export default class Post extends React.Component {
/>
<PostBody
post={post}
currentUser={this.props.currentUser}
sameRoot={this.props.sameRoot}
parentPost={parentPost}
handleCommentClick={this.handleCommentClick}

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

@@ -10,6 +10,7 @@ import FileAttachmentListContainer from 'components/file_attachment_list_contain
import PostBodyAdditionalContent from './post_body_additional_content.jsx';
import PostMessageContainer from './post_message_container.jsx';
import PendingPostOptions from './pending_post_options.jsx';
import ReactionListContainer from './reaction_list_container.jsx';
import {FormattedMessage} from 'react-intl';
@@ -202,6 +203,10 @@ export default class PostBody extends React.Component {
<div className={'post__body ' + mentionHighlightClass}>
{messageWithAdditionalContent}
{fileAttachmentHolder}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
);
@@ -210,6 +215,7 @@ export default class PostBody extends React.Component {
PostBody.propTypes = {
post: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object.isRequired,
parentPost: React.PropTypes.object,
retryPost: React.PropTypes.func,
handleCommentClick: React.PropTypes.func.isRequired,

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

@@ -0,0 +1,136 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import EmojiStore from 'stores/emoji_store.jsx';
import * as PostActions from 'actions/post_actions.jsx';
import * as Utils from 'utils/utils.jsx';
import {FormattedHTMLMessage, FormattedMessage} from 'react-intl';
import {OverlayTrigger, Tooltip} from 'react-bootstrap';
export default class Reaction extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired,
emojiName: React.PropTypes.string.isRequired,
reactions: React.PropTypes.arrayOf(React.PropTypes.object)
}
constructor(props) {
super(props);
this.addReaction = this.addReaction.bind(this);
this.removeReaction = this.removeReaction.bind(this);
}
addReaction(e) {
e.preventDefault();
PostActions.addReaction(this.props.post.channel_id, this.props.post.id, this.props.emojiName);
}
removeReaction(e) {
e.preventDefault();
PostActions.removeReaction(this.props.post.channel_id, this.props.post.id, this.props.emojiName);
}
render() {
if (!EmojiStore.has(this.props.emojiName)) {
return null;
}
let currentUserReacted = false;
const users = [];
for (const reaction of this.props.reactions) {
if (reaction.user_id === this.props.currentUserId) {
currentUserReacted = true;
} else {
users.push(Utils.displayUsername(reaction.user_id));
}
}
// sort users in alphabetical order with "you" being first if the current user reacted
users.sort();
if (currentUserReacted) {
users.unshift(Utils.localizeMessage('reaction.you', 'You'));
}
let tooltip;
if (users.length > 1) {
tooltip = (
<FormattedHTMLMessage
id='reaction.multipleReacted'
defaultMessage='<b>{users} and {lastUser}</b> reacted with <b>:{emojiName}:</b>'
values={{
users: users.slice(0, -1).join(', '),
lastUser: users[users.length - 1],
emojiName: this.props.emojiName
}}
/>
);
} else {
tooltip = (
<FormattedHTMLMessage
id='reaction.oneReacted'
defaultMessage='<b>{user}</b> reacted with <b>:{emojiName}:</b>'
values={{
user: users[0],
emojiName: this.props.emojiName
}}
/>
);
}
let handleClick;
let clickTooltip;
let className = 'post-reaction';
if (currentUserReacted) {
handleClick = this.removeReaction;
clickTooltip = (
<FormattedMessage
id='reaction.clickToRemove'
defaultMessage='(click to remove)'
/>
);
className += ' post-reaction--current-user';
} else {
handleClick = this.addReaction;
clickTooltip = (
<FormattedMessage
id='reaction.clickToAdd'
defaultMessage='(click to add)'
/>
);
}
return (
<OverlayTrigger
delayShow={1000}
placement='top'
shouldUpdatePosition={true}
overlay={
<Tooltip>
{tooltip}
<br/>
{clickTooltip}
</Tooltip>
}
>
<div
className={className}
onClick={handleClick}
>
<img
className='post-reaction__emoji'
src={EmojiStore.getEmojiImageUrl(EmojiStore.get(this.props.emojiName))}
/>
<span className='post-reaction__count'>
{this.props.reactions.length}
</span>
</div>
</OverlayTrigger>
);
}
}

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

@@ -0,0 +1,82 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import * as AsyncClient from 'utils/async_client.jsx';
import ReactionStore from 'stores/reaction_store.jsx';
import ReactionListView from './reaction_list_view.jsx';
export default class ReactionListContainer extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired
}
constructor(props) {
super(props);
this.handleReactionsChanged = this.handleReactionsChanged.bind(this);
this.state = {
reactions: ReactionStore.getReactions(this.props.post.id)
};
}
componentDidMount() {
ReactionStore.addChangeListener(this.props.post.id, this.handleReactionsChanged);
if (this.props.post.has_reactions) {
AsyncClient.listReactions(this.props.post.channel_id, this.props.post.id);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.post.id !== this.props.post.id) {
ReactionStore.removeChangeListener(this.props.post.id, this.handleReactionsChanged);
ReactionStore.addChangeListener(nextProps.post.id, this.handleReactionsChanged);
this.setState({
reactions: ReactionStore.getReactions(nextProps.post.id)
});
}
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.post.has_reactions !== this.props.post.has_reactions) {
return true;
}
if (nextState.reactions !== this.state.reactions) {
// this will only work so long as the entries in the ReactionStore are never mutated
return true;
}
return false;
}
componentWillUnmount() {
ReactionStore.removeChangeListener(this.props.post.id, this.handleReactionsChanged);
}
handleReactionsChanged() {
this.setState({
reactions: ReactionStore.getReactions(this.props.post.id)
});
}
render() {
if (!this.props.post.has_reactions) {
return null;
}
return (
<ReactionListView
post={this.props.post}
currentUserId={this.props.currentUserId}
reactions={this.state.reactions}
/>
);
}
}

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

@@ -0,0 +1,48 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import Reaction from './reaction.jsx';
export default class ReactionListView extends React.Component {
static propTypes = {
post: React.PropTypes.object.isRequired,
currentUserId: React.PropTypes.string.isRequired,
reactions: React.PropTypes.arrayOf(React.PropTypes.object)
}
render() {
const reactionsByName = new Map();
const emojiNames = [];
for (const reaction of this.props.reactions) {
const emojiName = reaction.emoji_name;
if (reactionsByName.has(emojiName)) {
reactionsByName.get(emojiName).push(reaction);
} else {
emojiNames.push(emojiName);
reactionsByName.set(emojiName, [reaction]);
}
}
const children = emojiNames.map((emojiName) => {
return (
<Reaction
key={emojiName}
post={this.props.post}
currentUserId={this.props.currentUserId}
emojiName={emojiName}
reactions={reactionsByName.get(emojiName)}
/>
);
});
return (
<div className='post-reaction-list'>
{children}
</div>
);
}
}

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

@@ -6,6 +6,7 @@ import FileAttachmentListContainer from './file_attachment_list_container.jsx';
import PendingPostOptions from 'components/post_view/components/pending_post_options.jsx';
import PostMessageContainer from 'components/post_view/components/post_message_container.jsx';
import ProfilePicture from 'components/profile_picture.jsx';
import ReactionListContainer from 'components/post_view/components/reaction_list_container.jsx';
import RhsDropdown from 'components/rhs_dropdown.jsx';
import TeamStore from 'stores/team_store.jsx';
@@ -404,6 +405,10 @@ export default class RhsComment extends React.Component {
{message}
</div>
{fileAttachment}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
</div>

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

@@ -6,6 +6,7 @@ import PostBodyAdditionalContent from 'components/post_view/components/post_body
import PostMessageContainer from 'components/post_view/components/post_message_container.jsx';
import FileAttachmentListContainer from './file_attachment_list_container.jsx';
import ProfilePicture from 'components/profile_picture.jsx';
import ReactionListContainer from 'components/post_view/components/reaction_list_container.jsx';
import RhsDropdown from 'components/rhs_dropdown.jsx';
import ChannelStore from 'stores/channel_store.jsx';
@@ -389,6 +390,10 @@ export default class RhsRootPost extends React.Component {
message={messageWrapper}
/>
{fileAttachment}
<ReactionListContainer
post={post}
currentUserId={this.props.currentUser.id}
/>
</div>
</div>
</div>

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

@@ -339,6 +339,7 @@ export default class RhsThread extends React.Component {
<CreateComment
channelId={selected.channel_id}
rootId={selected.id}
latestPostId={postsArray.length > 0 ? postsArray[postsArray.length - 1].id : selected.id}
/>
</div>
</div>

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

@@ -46,20 +46,23 @@ export default class EmoticonProvider {
handlePretextChanged(suggestionId, pretext) {
let hasSuggestions = false;
// look for partial matches among the named emojis
const captured = (/(?:^|\s)(:([^:\s]*))$/g).exec(pretext);
// look for the potential emoticons at the start of the text, after whitespace, and at the start of emoji reaction commands
const captured = (/(^|\s|^\+|^-)(:([^:\s]*))$/g).exec(pretext);
if (captured) {
const text = captured[1];
const partialName = captured[2];
const prefix = captured[1];
const text = captured[2];
const partialName = captured[3];
const matched = [];
// check for text emoticons
for (const emoticon of Object.keys(Emoticons.emoticonPatterns)) {
if (Emoticons.emoticonPatterns[emoticon].test(text)) {
SuggestionStore.addSuggestion(suggestionId, text, EmojiStore.get(emoticon), EmoticonSuggestion, text);
// check for text emoticons if this isn't for an emoji reaction
if (prefix !== '-' && prefix !== '+') {
for (const emoticon of Object.keys(Emoticons.emoticonPatterns)) {
if (Emoticons.emoticonPatterns[emoticon].test(text)) {
SuggestionStore.addSuggestion(suggestionId, text, EmojiStore.get(emoticon), EmoticonSuggestion, text);
hasSuggestions = true;
hasSuggestions = true;
}
}
}
@@ -76,11 +79,14 @@ export default class EmoticonProvider {
// sort the emoticons so that emoticons starting with the entered text come first
matched.sort((a, b) => {
const aPrefix = a.name.startsWith(partialName);
const bPrefix = b.name.startsWith(partialName);
const aName = a.name || a.aliases[0];
const bName = b.name || b.aliases[0];
const aPrefix = aName.startsWith(partialName);
const bPrefix = bName.startsWith(partialName);
if (aPrefix === bPrefix) {
return a.name.localeCompare(b.name);
return aName.localeCompare(bName);
} else if (aPrefix) {
return -1;
}
@@ -88,7 +94,7 @@ export default class EmoticonProvider {
return 1;
});
const terms = matched.map((emoticon) => ':' + emoticon.name + ':');
const terms = matched.map((emoticon) => ':' + (emoticon.name || emoticon.aliases[0]) + ':');
SuggestionStore.clearSuggestions(suggestionId);
if (terms.length > 0) {

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

@@ -26,7 +26,6 @@ export default class Textbox extends React.Component {
this.focus = this.focus.bind(this);
this.recalculateSize = this.recalculateSize.bind(this);
this.getStateFromStores = this.getStateFromStores.bind(this);
this.onRecievedError = this.onRecievedError.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
@@ -48,16 +47,6 @@ export default class Textbox extends React.Component {
}
}
getStateFromStores() {
const error = ErrorStore.getLastError();
if (error) {
return {message: error.message};
}
return {message: null};
}
componentDidMount() {
ErrorStore.addChangeListener(this.onRecievedError);
}

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

@@ -1620,6 +1620,11 @@
"post_info.reply": "Reply",
"posts_view.loadMore": "Load more messages",
"posts_view.newMsg": "New Messages",
"reaction.clickToAdd": "(click to add)",
"reaction.clickToRemove": "(click to remove)",
"reaction.multipleReacted": "<b>{users} and {lastUser}</b> reacted with <b>:{emojiName}:</b>",
"reaction.oneReacted": "<b>{user}</b> reacted with <b>:{emojiName}:</b>",
"reaction.you": "You",
"removed_channel.channelName": "the channel",
"removed_channel.from": "Removed from ",
"removed_channel.okay": "Okay",

Двоичные данные
webapp/images/emoji/basecamp.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 898 B

Двоичные данные
webapp/images/emoji/basecampy.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 2.9 KiB

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

До

Ширина:  |  Высота:  |  Размер: 6.4 KiB

После

Ширина:  |  Высота:  |  Размер: 6.4 KiB

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

@@ -1206,3 +1206,31 @@
margin-left: 50px !important;
min-width: 320px;
}
.post-reaction-list {
height: 24px;
}
.post-reaction {
border: 1px solid $primary-color;
border-radius: 3px;
cursor: pointer;
display: inline-block;
padding: 1px 2px;
@include user-select(none);
.post-reaction__emoji {
height: 14px;
margin-top: 3px;
width: 14px;
vertical-align: top;
}
& + & {
margin-left: 5px;
}
&--current-user {
// background-colour set by theme code
}
}

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

@@ -5,12 +5,64 @@ import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Constants from 'utils/constants.jsx';
import EventEmitter from 'events';
import EmojiJson from 'utils/emoji.json';
import * as Emoji from 'utils/emoji.jsx';
const ActionTypes = Constants.ActionTypes;
const CHANGE_EVENT = 'changed';
// Wrap the contents of the store so that we don't need to construct an ES6 map where most of the content
// (the system emojis) will never change. It provides the get/has functions of a map and an iterator so
// that it can be used in for..of loops
class EmojiMap {
constructor(customEmojis) {
this.customEmojis = customEmojis;
// Store customEmojis to an array so we can iterate it more easily
this.customEmojisArray = [...customEmojis];
}
has(name) {
return Emoji.EmojiIndicesByAlias.has(name) || this.customEmojis.has(name);
}
get(name) {
if (Emoji.EmojiIndicesByAlias.has(name)) {
return Emoji.Emojis[Emoji.EmojiIndicesByAlias.get(name)];
}
return this.customEmojis.get(name);
}
[Symbol.iterator]() {
const customEmojisArray = this.customEmojisArray;
return {
systemIndex: 0,
customIndex: 0,
next() {
if (this.systemIndex < Emoji.Emojis.length) {
const emoji = Emoji.Emojis[this.systemIndex];
this.systemIndex += 1;
return {value: [emoji.aliases[0], emoji]};
}
if (this.customIndex < customEmojisArray.length) {
const emoji = customEmojisArray[this.customIndex][1];
this.customIndex += 1;
return {value: [emoji.name, emoji]};
}
return {done: true};
}
};
}
}
class EmojiStore extends EventEmitter {
constructor() {
super();
@@ -19,18 +71,10 @@ class EmojiStore extends EventEmitter {
this.setMaxListeners(600);
this.emojis = new Map(EmojiJson);
this.systemEmojis = new Map(EmojiJson);
this.unicodeEmojis = new Map();
for (const [, emoji] of this.systemEmojis) {
if (emoji.unicode) {
this.unicodeEmojis.set(emoji.unicode, emoji);
}
}
this.receivedCustomEmojis = false;
this.customEmojis = new Map();
this.map = new EmojiMap(this.customEmojis);
}
addChangeListener(callback) {
@@ -50,20 +94,19 @@ class EmojiStore extends EventEmitter {
}
setCustomEmojis(customEmojis) {
customEmojis.sort((a, b) => a.name[0].localeCompare(b.name[0]));
this.customEmojis = new Map();
for (const emoji of customEmojis) {
this.addCustomEmoji(emoji);
}
this.sortCustomEmojis();
this.updateEmojiMap();
this.map = new EmojiMap(this.customEmojis);
}
addCustomEmoji(emoji) {
this.customEmojis.set(emoji.name, emoji);
// this doesn't update this.emojis, but it's only called by setCustomEmojis which does that afterwards
}
removeCustomEmoji(id) {
@@ -73,21 +116,10 @@ class EmojiStore extends EventEmitter {
break;
}
}
this.updateEmojiMap();
}
sortCustomEmojis() {
this.customEmojis = new Map([...this.customEmojis.entries()].sort((a, b) => a[0].localeCompare(b[0])));
}
updateEmojiMap() {
// add custom emojis to the map first so that they can't override system ones
this.emojis = new Map([...this.customEmojis, ...this.systemEmojis]);
}
getSystemEmojis() {
return this.systemEmojis;
hasSystemEmoji(name) {
return Emoji.EmojiIndicesByAlias.has(name);
}
getCustomEmojiMap() {
@@ -95,24 +127,23 @@ class EmojiStore extends EventEmitter {
}
getEmojis() {
return this.emojis;
return this.map;
}
has(name) {
return this.emojis.has(name);
return this.map.has(name);
}
get(name) {
// prioritize system emojis so that custom ones can't override them
return this.emojis.get(name);
return this.map.get(name);
}
hasUnicode(codepoint) {
return this.unicodeEmojis.has(codepoint);
return Emoji.EmojiIndicesByUnicode.has(codepoint);
}
getUnicode(codepoint) {
return this.unicodeEmojis.get(codepoint);
return Emoji.Emojis[Emoji.EmojiIndicesByUnicode.get(codepoint)];
}
getEmojiImageUrl(emoji) {
@@ -121,7 +152,7 @@ class EmojiStore extends EventEmitter {
return `/api/v3/emoji/${emoji.id}`;
}
const filename = emoji.unicode || emoji.filename || emoji.name;
const filename = emoji.filename || emoji.aliases[0];
return Constants.EMOJI_PATH + '/' + filename + '.png';
}

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

@@ -118,7 +118,15 @@ class PostStoreClass extends EventEmitter {
getEarliestPost(id) {
if (this.postsInfo.hasOwnProperty(id)) {
return this.postsInfo[id].postList.posts[this.postsInfo[id].postList.order[this.postsInfo[id].postList.order.length - 1]];
const postList = this.postsInfo[id].postList;
for (let i = postList.order.length - 1; i >= 0; i--) {
const postId = postList.order[i];
if (postList.posts[postId].state !== Constants.POST_DELETED) {
return postList.posts[postId];
}
}
}
return null;
@@ -126,7 +134,13 @@ class PostStoreClass extends EventEmitter {
getLatestPost(id) {
if (this.postsInfo.hasOwnProperty(id)) {
return this.postsInfo[id].postList.posts[this.postsInfo[id].postList.order[0]];
const postList = this.postsInfo[id].postList;
for (const postId of postList.order) {
if (postList.posts[postId].state !== Constants.POST_DELETED) {
return postList.posts[postId];
}
}
}
return null;
@@ -318,7 +332,8 @@ class PostStoreClass extends EventEmitter {
// make sure to copy the post so that component state changes work properly
postList.posts[post.id] = Object.assign({}, post, {
state: Constants.POST_DELETED,
file_ids: []
file_ids: [],
has_reactions: false
});
}
}

92
webapp/stores/reaction_store.jsx Обычный файл
Просмотреть файл

@@ -0,0 +1,92 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import AppDispatcher from '../dispatcher/app_dispatcher.jsx';
import Constants from 'utils/constants.jsx';
import EventEmitter from 'events';
const ActionTypes = Constants.ActionTypes;
const CHANGE_EVENT = 'changed';
class ReactionStore extends EventEmitter {
constructor() {
super();
this.dispatchToken = AppDispatcher.register(this.handleEventPayload.bind(this));
this.reactions = new Map();
this.setMaxListeners(600);
}
addChangeListener(postId, callback) {
this.on(CHANGE_EVENT + postId, callback);
}
removeChangeListener(postId, callback) {
this.removeListener(CHANGE_EVENT + postId, callback);
}
emitChange(postId) {
this.emit(CHANGE_EVENT + postId, postId);
}
setReactions(postId, reactions) {
this.reactions.set(postId, reactions);
}
addReaction(postId, reaction) {
const reactions = [];
for (const existing of this.getReactions(postId)) {
// make sure not to add duplicates
if (existing.user_id !== reaction.user_id || existing.post_id !== reaction.post_id ||
existing.emoji_name !== reaction.emoji_name) {
reactions.push(existing);
}
}
reactions.push(reaction);
this.setReactions(postId, reactions);
}
removeReaction(postId, reaction) {
const reactions = [];
for (const existing of this.getReactions(postId)) {
if (existing.user_id !== reaction.user_id || existing.post_id !== reaction.post_id ||
existing.emoji_name !== reaction.emoji_name) {
reactions.push(existing);
}
}
this.setReactions(postId, reactions);
}
getReactions(postId) {
return this.reactions.get(postId) || [];
}
handleEventPayload(payload) {
const action = payload.action;
switch (action.type) {
case ActionTypes.RECEIVED_REACTIONS:
this.setReactions(action.postId, action.reactions);
this.emitChange(action.postId);
break;
case ActionTypes.ADDED_REACTION:
this.addReaction(action.postId, action.reaction);
this.emitChange(action.postId);
break;
case ActionTypes.REMOVED_REACTION:
this.removeReaction(action.postId, action.reaction);
this.emitChange(action.postId);
break;
}
}
}
export default new ReactionStore();

81
webapp/tests/client_reaction.test.jsx Обычный файл
Просмотреть файл

@@ -0,0 +1,81 @@
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import TestHelper from './test_helper.jsx';
describe('Client.Reaction', function() {
this.timeout(100000);
it('saveListReaction', function(done) {
TestHelper.initBasic(() => {
const channelId = TestHelper.basicChannel().id;
const postId = TestHelper.basicPost().id;
const reaction = {
post_id: postId,
user_id: TestHelper.basicUser().id,
emoji_name: 'upside_down_face'
};
TestHelper.basicClient().saveReaction(
channelId,
reaction,
function() {
TestHelper.basicClient().listReactions(
channelId,
postId,
function(reactions) {
if (reactions.length === 1 &&
reactions[0].post_id === reaction.post_id &&
reactions[0].user_id === reaction.user_id &&
reactions[0].emoji_name === reaction.emoji_name) {
done();
} else {
done(new Error('test reaction wasn\'t returned'));
}
},
function(err) {
done(new Error(err.message));
}
);
},
function(err) {
done(new Error(err.message));
}
);
});
});
it('deleteReaction', function(done) {
TestHelper.initBasic(() => {
const channelId = TestHelper.basicChannel().id;
const postId = TestHelper.basicPost().id;
const reaction = {
post_id: postId,
user_id: TestHelper.basicUser().id,
emoji_name: 'upside_down_face'
};
TestHelper.basicClient().saveReaction(
channelId,
reaction,
function() {
TestHelper.basicClient().deleteReaction(
channelId,
reaction,
function() {
done();
},
function(err) {
done(new Error(err.message));
}
);
},
function(err) {
done(new Error(err.message));
}
);
});
});
});

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

@@ -1527,3 +1527,53 @@ export function deleteEmoji(id) {
}
);
}
export function saveReaction(channelId, reaction) {
Client.saveReaction(
channelId,
reaction,
null, // the added reaction will be sent over the websocket
(err) => {
dispatchError(err, 'saveReaction');
}
);
}
export function deleteReaction(channelId, reaction) {
Client.deleteReaction(
channelId,
reaction,
null, // the removed reaction will be sent over the websocket
(err) => {
dispatchError(err, 'deleteReaction');
}
);
}
export function listReactions(channelId, postId) {
const callName = 'deleteEmoji' + postId;
if (isCallInProgress(callName)) {
return;
}
callTracker[callName] = utils.getTimestamp();
Client.listReactions(
channelId,
postId,
(data) => {
callTracker[callName] = 0;
AppDispatcher.handleServerAction({
type: ActionTypes.RECEIVED_REACTIONS,
postId,
reactions: data
});
},
(err) => {
callTracker[callName] = 0;
dispatchError(err, 'listReactions');
}
);
}

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

@@ -122,6 +122,10 @@ export const ActionTypes = keyMirror({
UPDATED_CUSTOM_EMOJI: null,
REMOVED_CUSTOM_EMOJI: null,
RECEIVED_REACTIONS: null,
ADDED_REACTION: null,
REMOVED_REACTION: null,
RECEIVED_MSG: null,
RECEIVED_MY_TEAM: null,
@@ -206,7 +210,9 @@ export const SocketEvents = {
EPHEMERAL_MESSAGE: 'ephemeral_message',
STATUS_CHANGED: 'status_change',
HELLO: 'hello',
WEBRTC: 'webrtc'
WEBRTC: 'webrtc',
REACTION_ADDED: 'reaction_added',
REACTION_REMOVED: 'reaction_removed'
};
export const TutorialSteps = {

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

18
webapp/utils/emoji.jsx Обычный файл

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

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

@@ -539,6 +539,7 @@ export function applyTheme(theme) {
if (theme.mentionColor) {
changeCss('.sidebar--left .nav-pills__unread-indicator', 'color:' + theme.mentionColor);
changeCss('.sidebar--left .badge', 'color:' + theme.mentionColor + '!important;');
changeCss('.app__body .post-reaction--current-user', 'background-color:' + changeOpacity(theme.mentionColor, 0.4));
}
if (theme.centerChannelBg) {
@@ -628,6 +629,8 @@ export function applyTheme(theme) {
changeCss('.app__body .post.post--comment.current--user .post__body', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2));
changeCss('.app__body .channel-header__info .status .offline--icon', 'fill:' + theme.centerChannelColor);
changeCss('.app__body .navbar .status .offline--icon', 'fill:' + theme.centerChannelColor);
changeCss('.app__body .post-reaction:not(.post-reaction--current-user)', 'background-color:' + changeOpacity(theme.centerChannelColor, 0.2));
changeCss('.app__body .post-reaction', 'border-color:' + theme.centerChannelColor);
}
if (theme.newMessageSeparator) {