emoji.go 7.53 KB
Newer Older
1
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// See License.txt for license information.

package app

import (
	"bytes"
	"image"
	"image/draw"
	"image/gif"
	_ "image/jpeg"
	"image/png"
	"io"
	"mime/multipart"
	"net/http"

17 18
	l4g "github.com/alecthomas/log4go"

19 20
	"image/color/palette"

21
	"github.com/disintegration/imaging"
Christopher Speller's avatar
Christopher Speller committed
22 23
	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/utils"
24 25 26 27 28 29 30 31
)

const (
	MaxEmojiFileSize = 1000 * 1024 // 1 MB
	MaxEmojiWidth    = 128
	MaxEmojiHeight   = 128
)

Chris's avatar
Chris committed
32
func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) {
33 34 35 36 37 38 39 40 41 42 43 44 45 46
	// wipe the emoji id so that existing emojis can't get overwritten
	emoji.Id = ""

	// do our best to validate the emoji before committing anything to the DB so that we don't have to clean up
	// orphaned files left over when validation fails later on
	emoji.PreSave()
	if err := emoji.IsValid(); err != nil {
		return nil, err
	}

	if emoji.CreatorId != sessionUserId {
		return nil, model.NewAppError("createEmoji", "api.emoji.create.other_user.app_error", nil, "", http.StatusForbidden)
	}

Chris's avatar
Chris committed
47
	if result := <-a.Srv.Store.Emoji().GetByName(emoji.Name); result.Err == nil && result.Data != nil {
48 49 50 51
		return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest)
	}

	if imageData := multiPartImageData.File["image"]; len(imageData) == 0 {
52
		err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": "createEmoji"}, "", http.StatusBadRequest)
53
		return nil, err
54
	} else if err := a.UploadEmojiImage(emoji.Id, imageData[0]); err != nil {
55 56 57
		return nil, err
	}

Chris's avatar
Chris committed
58
	if result := <-a.Srv.Store.Emoji().Save(emoji); result.Err != nil {
59 60
		return nil, result.Err
	} else {
61 62 63
		message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil)
		message.Add("emoji", emoji.ToJson())

64
		a.Publish(message)
65 66 67 68
		return result.Data.(*model.Emoji), nil
	}
}

Chris's avatar
Chris committed
69 70
func (a *App) GetEmojiList(page, perPage int) ([]*model.Emoji, *model.AppError) {
	if result := <-a.Srv.Store.Emoji().GetList(page*perPage, perPage); result.Err != nil {
71 72 73 74 75 76
		return nil, result.Err
	} else {
		return result.Data.([]*model.Emoji), nil
	}
}

77
func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
	file, err := imageData.Open()
	if err != nil {
		return model.NewAppError("uploadEmojiImage", "api.emoji.upload.open.app_error", nil, "", http.StatusBadRequest)
	}
	defer file.Close()

	buf := bytes.NewBuffer(nil)
	io.Copy(buf, file)

	// make sure the file is an image and is within the required dimensions
	if config, _, err := image.DecodeConfig(bytes.NewReader(buf.Bytes())); err != nil {
		return model.NewAppError("uploadEmojiImage", "api.emoji.upload.image.app_error", nil, "", http.StatusBadRequest)
	} else if config.Width > MaxEmojiWidth || config.Height > MaxEmojiHeight {
		data := buf.Bytes()
		newbuf := bytes.NewBuffer(nil)
		if info, err := model.GetInfoForBytes(imageData.Filename, data); err != nil {
			return err
		} else if info.MimeType == "image/gif" {
			if gif_data, err := gif.DecodeAll(bytes.NewReader(data)); err != nil {
				return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_decode_error", nil, "", http.StatusBadRequest)
			} else {
				resized_gif := resizeEmojiGif(gif_data)
				if err := gif.EncodeAll(newbuf, resized_gif); err != nil {
					return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_encode_error", nil, "", http.StatusBadRequest)
				}
103
				if err := a.WriteFile(newbuf.Bytes(), getEmojiImagePath(id)); err != nil {
104 105 106 107 108 109 110 111 112 113 114
					return err
				}
			}
		} else {
			if img, _, err := image.Decode(bytes.NewReader(data)); err != nil {
				return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.decode_error", nil, "", http.StatusBadRequest)
			} else {
				resized_image := resizeEmoji(img, config.Width, config.Height)
				if err := png.Encode(newbuf, resized_image); err != nil {
					return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.encode_error", nil, "", http.StatusBadRequest)
				}
115
				if err := a.WriteFile(newbuf.Bytes(), getEmojiImagePath(id)); err != nil {
116 117 118 119 120 121
					return err
				}
			}
		}
	}

122
	return a.WriteFile(buf.Bytes(), getEmojiImagePath(id))
123 124
}

Chris's avatar
Chris committed
125 126
func (a *App) DeleteEmoji(emoji *model.Emoji) *model.AppError {
	if err := (<-a.Srv.Store.Emoji().Delete(emoji.Id, model.GetMillis())).Err; err != nil {
127 128 129
		return err
	}

130
	a.deleteEmojiImage(emoji.Id)
Chris's avatar
Chris committed
131
	a.deleteReactionsForEmoji(emoji.Name)
132 133 134
	return nil
}

Chris's avatar
Chris committed
135
func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) {
Chris's avatar
Chris committed
136
	if !*a.Config().ServiceSettings.EnableCustomEmoji {
137 138 139
		return nil, model.NewAppError("deleteEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
	}

Chris's avatar
Chris committed
140
	if len(*a.Config().FileSettings.DriverName) == 0 {
141 142 143
		return nil, model.NewAppError("deleteImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
	}

Chris's avatar
Chris committed
144
	if result := <-a.Srv.Store.Emoji().Get(emojiId, false); result.Err != nil {
145 146 147 148 149 150
		return nil, result.Err
	} else {
		return result.Data.(*model.Emoji), nil
	}
}

Chris's avatar
Chris committed
151 152
func (a *App) GetEmojiImage(emojiId string) (imageByte []byte, imageType string, err *model.AppError) {
	if result := <-a.Srv.Store.Emoji().Get(emojiId, true); result.Err != nil {
153 154 155 156
		return nil, "", result.Err
	} else {
		var img []byte

157
		if data, err := a.ReadFile(getEmojiImagePath(emojiId)); err != nil {
158 159 160 161 162 163 164 165 166 167 168 169 170 171
			return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.read.app_error", nil, err.Error(), http.StatusNotFound)
		} else {
			img = data
		}

		_, imageType, err := image.DecodeConfig(bytes.NewReader(img))
		if err != nil {
			return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.decode.app_error", nil, err.Error(), http.StatusInternalServerError)
		}

		return img, imageType, nil
	}
}

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
func resizeEmojiGif(gifImg *gif.GIF) *gif.GIF {
	// Create a new RGBA image to hold the incremental frames.
	firstFrame := gifImg.Image[0].Bounds()
	b := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy())
	img := image.NewRGBA(b)

	resizedImage := image.Image(nil)
	// Resize each frame.
	for index, frame := range gifImg.Image {
		bounds := frame.Bounds()
		draw.Draw(img, bounds, frame, bounds.Min, draw.Over)
		resizedImage = resizeEmoji(img, firstFrame.Dx(), firstFrame.Dy())
		gifImg.Image[index] = imageToPaletted(resizedImage)
	}
	// Set new gif width and height
	gifImg.Config.Width = resizedImage.Bounds().Dx()
	gifImg.Config.Height = resizedImage.Bounds().Dy()
	return gifImg
}

func getEmojiImagePath(id string) string {
	return "emoji/" + id + "/image"
}

func resizeEmoji(img image.Image, width int, height int) image.Image {
	emojiWidth := float64(width)
	emojiHeight := float64(height)

	var emoji image.Image
	if emojiHeight <= MaxEmojiHeight && emojiWidth <= MaxEmojiWidth {
		emoji = img
	} else {
		emoji = imaging.Fit(img, MaxEmojiWidth, MaxEmojiHeight, imaging.Lanczos)
	}
	return emoji
}

func imageToPaletted(img image.Image) *image.Paletted {
	b := img.Bounds()
	pm := image.NewPaletted(b, palette.Plan9)
	draw.FloydSteinberg.Draw(pm, b, img, image.ZP)
	return pm
}
215

216 217
func (a *App) deleteEmojiImage(id string) {
	if err := a.MoveFile(getEmojiImagePath(id), "emoji/"+id+"/image_deleted"); err != nil {
218 219 220 221
		l4g.Error("Failed to rename image when deleting emoji %v", id)
	}
}

Chris's avatar
Chris committed
222 223
func (a *App) deleteReactionsForEmoji(emojiName string) {
	if result := <-a.Srv.Store.Reaction().DeleteAllWithEmojiName(emojiName); result.Err != nil {
224 225 226 227
		l4g.Warn(utils.T("api.emoji.delete.delete_reactions.app_error"), emojiName)
		l4g.Warn(result.Err)
	}
}