file.go 16.1 KB
Newer Older
1
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
2 3 4 5 6 7 8 9 10
// See License.txt for license information.

package app

import (
	"bytes"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
11 12 13
	"image"
	"image/color"
	"image/draw"
14
	_ "image/gif"
15
	"image/jpeg"
16
	"io"
17
	"mime/multipart"
18
	"net/http"
19 20 21 22
	"net/url"
	"path/filepath"
	"strings"
	"sync"
23
	"time"
24 25

	l4g "github.com/alecthomas/log4go"
26
	"github.com/disintegration/imaging"
27 28
	"github.com/rwcarlsen/goexif/exif"
	_ "golang.org/x/image/bmp"
29

Christopher Speller's avatar
Christopher Speller committed
30 31
	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/utils"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
)

const (
	/*
	  EXIF Image Orientations
	  1        2       3      4         5            6           7          8

	  888888  888888      88  88      8888888888  88                  88  8888888888
	  88          88      88  88      88  88      88  88          88  88      88  88
	  8888      8888    8888  8888    88          8888888888  8888888888          88
	  88          88      88  88
	  88          88  888888  888888
	*/
	Upright            = 1
	UprightMirrored    = 2
	UpsideDown         = 3
	UpsideDownMirrored = 4
	RotatedCWMirrored  = 5
	RotatedCCW         = 6
	RotatedCCWMirrored = 7
	RotatedCW          = 8

54 55
	MaxImageSize                 = 6048 * 4032 // 24 megapixels, roughly 36MB as a raw image
	IMAGE_THUMBNAIL_PIXEL_WIDTH  = 120
56
	IMAGE_THUMBNAIL_PIXEL_HEIGHT = 100
57
	IMAGE_PREVIEW_PIXEL_WIDTH    = 1024
58 59
)

60
func (a *App) FileBackend() (utils.FileBackend, *model.AppError) {
61 62
	license := a.License()
	return utils.NewFileBackend(&a.Config().FileSettings, license != nil && *license.Features.Compliance)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

func (a *App) ReadFile(path string) ([]byte, *model.AppError) {
	backend, err := a.FileBackend()
	if err != nil {
		return nil, err
	}
	return backend.ReadFile(path)
}

func (a *App) MoveFile(oldPath, newPath string) *model.AppError {
	backend, err := a.FileBackend()
	if err != nil {
		return err
	}
	return backend.MoveFile(oldPath, newPath)
}

func (a *App) WriteFile(f []byte, path string) *model.AppError {
	backend, err := a.FileBackend()
	if err != nil {
		return err
	}
	return backend.WriteFile(f, path)
}

func (a *App) RemoveFile(path string) *model.AppError {
	backend, err := a.FileBackend()
	if err != nil {
		return err
	}
	return backend.RemoveFile(path)
}

func (a *App) GetInfoForFilename(post *model.Post, teamId string, filename string) *model.FileInfo {
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
	// Find the path from the Filename of the form /{channelId}/{userId}/{uid}/{nameWithExtension}
	split := strings.SplitN(filename, "/", 5)
	if len(split) < 5 {
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.unexpected_filename.error"), post.Id, filename)
		return nil
	}

	channelId := split[1]
	userId := split[2]
	oldId := split[3]
	name, _ := url.QueryUnescape(split[4])

	if split[0] != "" || split[1] != post.ChannelId || split[2] != post.UserId || strings.Contains(split[4], "/") {
		l4g.Warn(utils.T("api.file.migrate_filenames_to_file_infos.mismatched_filename.warn"), post.Id, post.ChannelId, post.UserId, filename)
	}

	pathPrefix := fmt.Sprintf("teams/%s/channels/%s/users/%s/%s/", teamId, channelId, userId, oldId)
	path := pathPrefix + name

	// Open the file and populate the fields of the FileInfo
	var info *model.FileInfo
119
	if data, err := a.ReadFile(path); err != nil {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.file_not_found.error"), post.Id, filename, path, err)
		return nil
	} else {
		var err *model.AppError
		info, err = model.GetInfoForBytes(name, data)
		if err != nil {
			l4g.Warn(utils.T("api.file.migrate_filenames_to_file_infos.info.app_error"), post.Id, filename, err)
		}
	}

	// Generate a new ID because with the old system, you could very rarely get multiple posts referencing the same file
	info.Id = model.NewId()
	info.CreatorId = post.UserId
	info.PostId = post.Id
	info.CreateAt = post.CreateAt
	info.UpdateAt = post.UpdateAt
	info.Path = path

	if info.IsImage() {
		nameWithoutExtension := name[:strings.LastIndex(name, ".")]
		info.PreviewPath = pathPrefix + nameWithoutExtension + "_preview.jpg"
		info.ThumbnailPath = pathPrefix + nameWithoutExtension + "_thumb.jpg"
	}

	return info
}

Chris's avatar
Chris committed
147
func (a *App) FindTeamIdForFilename(post *model.Post, filename string) string {
148 149 150 151 152
	split := strings.SplitN(filename, "/", 5)
	id := split[3]
	name, _ := url.QueryUnescape(split[4])

	// This post is in a direct channel so we need to figure out what team the files are stored under.
Chris's avatar
Chris committed
153
	if result := <-a.Srv.Store.Team().GetTeamsByUserId(post.UserId); result.Err != nil {
154 155 156 157 158 159 160
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.teams.app_error"), post.Id, result.Err)
	} else if teams := result.Data.([]*model.Team); len(teams) == 1 {
		// The user has only one team so the post must've been sent from it
		return teams[0].Id
	} else {
		for _, team := range teams {
			path := fmt.Sprintf("teams/%s/channels/%s/users/%s/%s/%s", team.Id, post.ChannelId, post.UserId, id, name)
161
			if _, err := a.ReadFile(path); err == nil {
162 163 164 165 166 167 168 169 170 171 172 173
				// Found the team that this file was posted from
				return team.Id
			}
		}
	}

	return ""
}

var fileMigrationLock sync.Mutex

// Creates and stores FileInfos for a post created before the FileInfos table existed.
Chris's avatar
Chris committed
174
func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo {
175 176 177 178 179
	if len(post.Filenames) == 0 {
		l4g.Warn(utils.T("api.file.migrate_filenames_to_file_infos.no_filenames.warn"), post.Id)
		return []*model.FileInfo{}
	}

Chris's avatar
Chris committed
180
	cchan := a.Srv.Store.Channel().Get(post.ChannelId, true)
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

	// There's a weird bug that rarely happens where a post ends up with duplicate Filenames so remove those
	filenames := utils.RemoveDuplicatesFromStringArray(post.Filenames)

	var channel *model.Channel
	if result := <-cchan; result.Err != nil {
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.channel.app_error"), post.Id, post.ChannelId, result.Err)
		return []*model.FileInfo{}
	} else {
		channel = result.Data.(*model.Channel)
	}

	// Find the team that was used to make this post since its part of the file path that isn't saved in the Filename
	var teamId string
	if channel.TeamId == "" {
		// This post was made in a cross-team DM channel so we need to find where its files were saved
Chris's avatar
Chris committed
197
		teamId = a.FindTeamIdForFilename(post, filenames[0])
198 199 200 201 202 203 204 205 206 207
	} else {
		teamId = channel.TeamId
	}

	// Create FileInfo objects for this post
	infos := make([]*model.FileInfo, 0, len(filenames))
	if teamId == "" {
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.team_id.error"), post.Id, filenames)
	} else {
		for _, filename := range filenames {
208
			info := a.GetInfoForFilename(post, teamId, filename)
209 210 211 212 213 214 215 216 217 218 219 220
			if info == nil {
				continue
			}

			infos = append(infos, info)
		}
	}

	// Lock to prevent only one migration thread from trying to update the post at once, preventing duplicate FileInfos from being created
	fileMigrationLock.Lock()
	defer fileMigrationLock.Unlock()

Chris's avatar
Chris committed
221
	if result := <-a.Srv.Store.Post().Get(post.Id); result.Err != nil {
222 223 224 225
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.get_post_again.app_error"), post.Id, result.Err)
		return []*model.FileInfo{}
	} else if newPost := result.Data.(*model.PostList).Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) {
		// Another thread has already created FileInfos for this post, so just return those
Chris's avatar
Chris committed
226
		if result := <-a.Srv.Store.FileInfo().GetForPost(post.Id, true, false); result.Err != nil {
227 228 229 230 231 232 233 234 235 236 237 238 239
			l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.get_post_file_infos_again.app_error"), post.Id, result.Err)
			return []*model.FileInfo{}
		} else {
			l4g.Debug(utils.T("api.file.migrate_filenames_to_file_infos.not_migrating_post.debug"), post.Id)
			return result.Data.([]*model.FileInfo)
		}
	}

	l4g.Debug(utils.T("api.file.migrate_filenames_to_file_infos.migrating_post.debug"), post.Id)

	savedInfos := make([]*model.FileInfo, 0, len(infos))
	fileIds := make([]string, 0, len(filenames))
	for _, info := range infos {
Chris's avatar
Chris committed
240
		if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
			l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.save_file_info.app_error"), post.Id, info.Id, info.Path, result.Err)
			continue
		}

		savedInfos = append(savedInfos, info)
		fileIds = append(fileIds, info.Id)
	}

	// Copy and save the updated post
	newPost := &model.Post{}
	*newPost = *post

	newPost.Filenames = []string{}
	newPost.FileIds = fileIds

	// Update Posts to clear Filenames and set FileIds
Chris's avatar
Chris committed
257
	if result := <-a.Srv.Store.Post().Update(newPost, post); result.Err != nil {
258 259 260 261 262 263 264
		l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.save_post.app_error"), post.Id, newPost.FileIds, post.Filenames, result.Err)
		return []*model.FileInfo{}
	} else {
		return savedInfos
	}
}

Chris's avatar
Chris committed
265 266
func (a *App) GeneratePublicLink(siteURL string, info *model.FileInfo) string {
	hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
267 268 269
	return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash)
}

Chris's avatar
Chris committed
270 271
func (a *App) GeneratePublicLinkV3(siteURL string, info *model.FileInfo) string {
	hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
272
	return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash)
273 274 275 276 277 278 279 280 281
}

func GeneratePublicLinkHash(fileId, salt string) string {
	hash := sha256.New()
	hash.Write([]byte(salt))
	hash.Write([]byte(fileId))

	return base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
}
282

Chris's avatar
Chris committed
283
func (a *App) UploadFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string) (*model.FileUploadResponse, *model.AppError) {
Chris's avatar
Chris committed
284
	if len(*a.Config().FileSettings.DriverName) == 0 {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
		return nil, model.NewAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented)
	}

	resStruct := &model.FileUploadResponse{
		FileInfos: []*model.FileInfo{},
		ClientIds: []string{},
	}

	previewPathList := []string{}
	thumbnailPathList := []string{}
	imageDataList := [][]byte{}

	for i, fileHeader := range fileHeaders {
		file, fileErr := fileHeader.Open()
		if fileErr != nil {
			return nil, model.NewAppError("UploadFiles", "api.file.upload_file.bad_parse.app_error", nil, fileErr.Error(), http.StatusBadRequest)
		}
302
		defer file.Close()
303 304 305 306 307

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

Chris's avatar
Chris committed
308
		info, err := a.DoUploadFile(time.Now(), teamId, channelId, userId, fileHeader.Filename, data)
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
		if err != nil {
			return nil, err
		}

		if info.PreviewPath != "" || info.ThumbnailPath != "" {
			previewPathList = append(previewPathList, info.PreviewPath)
			thumbnailPathList = append(thumbnailPathList, info.ThumbnailPath)
			imageDataList = append(imageDataList, data)
		}

		resStruct.FileInfos = append(resStruct.FileInfos, info)

		if len(clientIds) > 0 {
			resStruct.ClientIds = append(resStruct.ClientIds, clientIds[i])
		}
	}

326
	a.HandleImages(previewPathList, thumbnailPathList, imageDataList)
327 328 329 330

	return resStruct, nil
}

331
func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
332
	filename := filepath.Base(rawFilename)
333 334 335
	teamId := filepath.Base(rawTeamId)
	channelId := filepath.Base(rawChannelId)
	userId := filepath.Base(rawUserId)
336 337 338 339 340 341 342 343 344 345

	info, err := model.GetInfoForBytes(filename, data)
	if err != nil {
		err.StatusCode = http.StatusBadRequest
		return nil, err
	}

	info.Id = model.NewId()
	info.CreatorId = userId

346
	pathPrefix := now.Format("20060102") + "/teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + info.Id + "/"
347 348 349 350 351
	info.Path = pathPrefix + filename

	if info.IsImage() {
		// Check dimensions before loading the whole thing into memory later on
		if info.Width*info.Height > MaxImageSize {
352
			err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]interface{}{"Filename": filename}, "", http.StatusBadRequest)
353 354 355 356 357 358 359 360
			return nil, err
		}

		nameWithoutExtension := filename[:strings.LastIndex(filename, ".")]
		info.PreviewPath = pathPrefix + nameWithoutExtension + "_preview.jpg"
		info.ThumbnailPath = pathPrefix + nameWithoutExtension + "_thumb.jpg"
	}

361
	if err := a.WriteFile(data, info.Path); err != nil {
362 363 364
		return nil, err
	}

Chris's avatar
Chris committed
365
	if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
366 367 368 369 370 371
		return nil, result.Err
	}

	return info, nil
}

372
func (a *App) HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) {
373 374 375 376 377 378 379 380
	wg := new(sync.WaitGroup)

	for i := range fileData {
		img, width, height := prepareImage(fileData[i])
		if img != nil {
			wg.Add(2)
			go func(img *image.Image, path string, width int, height int) {
				defer wg.Done()
381
				a.generateThumbnailImage(*img, path, width, height)
382
			}(img, thumbnailPathList[i], width, height)
383 384 385

			go func(img *image.Image, path string, width int) {
				defer wg.Done()
386
				a.generatePreviewImage(*img, path, width)
387 388
			}(img, previewPathList[i], width)
		}
389
	}
390
	wg.Wait()
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
}

func prepareImage(fileData []byte) (*image.Image, int, int) {
	// Decode image bytes into Image object
	img, imgType, err := image.Decode(bytes.NewReader(fileData))
	if err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.decode.error"), err)
		return nil, 0, 0
	}

	width := img.Bounds().Dx()
	height := img.Bounds().Dy()

	// Fill in the background of a potentially-transparent png file as white
	if imgType == "png" {
		dst := image.NewRGBA(img.Bounds())
		draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
		draw.Draw(dst, dst.Bounds(), img, img.Bounds().Min, draw.Over)
		img = dst
	}

	// Flip the image to be upright
413 414
	orientation, _ := getImageOrientation(bytes.NewReader(fileData))
	img = makeImageUpright(img, orientation)
415

416 417 418 419
	return &img, width, height
}

func makeImageUpright(img image.Image, orientation int) image.Image {
420 421
	switch orientation {
	case UprightMirrored:
422
		return imaging.FlipH(img)
423
	case UpsideDown:
424
		return imaging.Rotate180(img)
425
	case UpsideDownMirrored:
426
		return imaging.FlipV(img)
427
	case RotatedCWMirrored:
428
		return imaging.Transpose(img)
429
	case RotatedCCW:
430
		return imaging.Rotate270(img)
431
	case RotatedCCWMirrored:
432
		return imaging.Transverse(img)
433
	case RotatedCW:
434 435 436
		return imaging.Rotate90(img)
	default:
		return img
437 438 439
	}
}

440 441
func getImageOrientation(input io.Reader) (int, error) {
	if exifData, err := exif.Decode(input); err != nil {
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
		return Upright, err
	} else {
		if tag, err := exifData.Get("Orientation"); err != nil {
			return Upright, err
		} else {
			orientation, err := tag.Int(0)
			if err != nil {
				return Upright, err
			} else {
				return orientation, nil
			}
		}
	}
}

457
func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) {
458 459 460 461 462
	thumbWidth := float64(IMAGE_THUMBNAIL_PIXEL_WIDTH)
	thumbHeight := float64(IMAGE_THUMBNAIL_PIXEL_HEIGHT)
	imgWidth := float64(width)
	imgHeight := float64(height)

463
	var thumbnail image.Image
464
	if imgHeight < IMAGE_THUMBNAIL_PIXEL_HEIGHT && imgWidth < thumbWidth {
465
		thumbnail = img
466 467
	} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
		thumbnail = imaging.Resize(img, 0, IMAGE_THUMBNAIL_PIXEL_HEIGHT, imaging.Lanczos)
468
	} else {
469
		thumbnail = imaging.Resize(img, IMAGE_THUMBNAIL_PIXEL_WIDTH, 0, imaging.Lanczos)
470 471 472 473 474 475 476 477
	}

	buf := new(bytes.Buffer)
	if err := jpeg.Encode(buf, thumbnail, &jpeg.Options{Quality: 90}); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.encode_jpeg.error"), thumbnailPath, err)
		return
	}

478
	if err := a.WriteFile(buf.Bytes(), thumbnailPath); err != nil {
479 480 481 482 483
		l4g.Error(utils.T("api.file.handle_images_forget.upload_thumb.error"), thumbnailPath, err)
		return
	}
}

484
func (a *App) generatePreviewImage(img image.Image, previewPath string, width int) {
485
	var preview image.Image
486 487 488

	if width > IMAGE_PREVIEW_PIXEL_WIDTH {
		preview = imaging.Resize(img, IMAGE_PREVIEW_PIXEL_WIDTH, 0, imaging.Lanczos)
489 490 491 492 493 494 495 496 497 498 499
	} else {
		preview = img
	}

	buf := new(bytes.Buffer)

	if err := jpeg.Encode(buf, preview, &jpeg.Options{Quality: 90}); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.encode_preview.error"), previewPath, err)
		return
	}

500
	if err := a.WriteFile(buf.Bytes(), previewPath); err != nil {
501 502 503 504
		l4g.Error(utils.T("api.file.handle_images_forget.upload_preview.error"), previewPath, err)
		return
	}
}
505

Chris's avatar
Chris committed
506 507
func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) {
	if result := <-a.Srv.Store.FileInfo().Get(fileId); result.Err != nil {
508 509 510 511 512
		return nil, result.Err
	} else {
		return result.Data.(*model.FileInfo), nil
	}
}