file.go 18.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
	"github.com/disintegration/imaging"
26 27
	"github.com/rwcarlsen/goexif/exif"
	_ "golang.org/x/image/bmp"
28

29
	"github.com/mattermost/mattermost-server/mlog"
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
	// Find the path from the Filename of the form /{channelId}/{userId}/{uid}/{nameWithExtension}
	split := strings.SplitN(filename, "/", 5)
	if len(split) < 5 {
101
		mlog.Error("Unable to decipher filename when migrating post to use FileInfos", mlog.String("post_id", post.Id), mlog.String("filename", filename))
102 103 104 105 106 107 108 109 110
		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], "/") {
111 112 113 114 115 116 117
		mlog.Warn(
			"Found an unusual filename when migrating post to use FileInfos",
			mlog.String("post_id", post.Id),
			mlog.String("channel_id", post.ChannelId),
			mlog.String("user_id", post.UserId),
			mlog.String("filename", filename),
		)
118 119 120 121 122 123 124
	}

	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
125
	if data, err := a.ReadFile(path); err != nil {
126 127 128 129 130 131
		mlog.Error(
			fmt.Sprintf("File not found when migrating post to use FileInfos, err=%v", err),
			mlog.String("post_id", post.Id),
			mlog.String("filename", filename),
			mlog.String("path", path),
		)
132 133 134 135 136
		return nil
	} else {
		var err *model.AppError
		info, err = model.GetInfoForBytes(name, data)
		if err != nil {
137 138 139 140 141
			mlog.Warn(
				fmt.Sprintf("Unable to fully decode file info when migrating post to use FileInfos, err=%v", err),
				mlog.String("post_id", post.Id),
				mlog.String("filename", filename),
			)
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		}
	}

	// 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
162
func (a *App) FindTeamIdForFilename(post *model.Post, filename string) string {
163 164 165 166 167
	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
168
	if result := <-a.Srv.Store.Team().GetTeamsByUserId(post.UserId); result.Err != nil {
169
		mlog.Error(fmt.Sprintf("Unable to get teams when migrating post to use FileInfo, err=%v", result.Err), mlog.String("post_id", post.Id))
170 171 172 173 174 175
	} 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)
176
			if _, err := a.ReadFile(path); err == nil {
177 178 179 180 181 182 183 184 185 186 187 188
				// 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
189
func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo {
190
	if len(post.Filenames) == 0 {
191
		mlog.Warn("Unable to migrate post to use FileInfos with an empty Filenames field", mlog.String("post_id", post.Id))
192 193 194
		return []*model.FileInfo{}
	}

Chris's avatar
Chris committed
195
	cchan := a.Srv.Store.Channel().Get(post.ChannelId, true)
196 197 198 199 200 201

	// 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 {
202 203 204 205 206
		mlog.Error(
			fmt.Sprintf("Unable to get channel when migrating post to use FileInfos, err=%v", result.Err),
			mlog.String("post_id", post.Id),
			mlog.String("channel_id", post.ChannelId),
		)
207 208 209 210 211 212 213 214 215
		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
216
		teamId = a.FindTeamIdForFilename(post, filenames[0])
217 218 219 220 221 222 223
	} else {
		teamId = channel.TeamId
	}

	// Create FileInfo objects for this post
	infos := make([]*model.FileInfo, 0, len(filenames))
	if teamId == "" {
224 225 226 227
		mlog.Error(
			fmt.Sprintf("Unable to find team id for files when migrating post to use FileInfos, filenames=%v", filenames),
			mlog.String("post_id", post.Id),
		)
228 229
	} else {
		for _, filename := range filenames {
230
			info := a.GetInfoForFilename(post, teamId, filename)
231 232 233 234 235 236 237 238 239 240 241 242
			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
243
	if result := <-a.Srv.Store.Post().Get(post.Id); result.Err != nil {
244
		mlog.Error(fmt.Sprintf("Unable to get post when migrating post to use FileInfos, err=%v", result.Err), mlog.String("post_id", post.Id))
245 246 247
		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
248
		if result := <-a.Srv.Store.FileInfo().GetForPost(post.Id, true, false); result.Err != nil {
249
			mlog.Error(fmt.Sprintf("Unable to get FileInfos for migrated post, err=%v", result.Err), mlog.String("post_id", post.Id))
250 251
			return []*model.FileInfo{}
		} else {
252
			mlog.Debug("Post already migrated to use FileInfos", mlog.String("post_id", post.Id))
253 254 255 256
			return result.Data.([]*model.FileInfo)
		}
	}

257
	mlog.Debug("Migrating post to use FileInfos", mlog.String("post_id", post.Id))
258 259 260 261

	savedInfos := make([]*model.FileInfo, 0, len(infos))
	fileIds := make([]string, 0, len(filenames))
	for _, info := range infos {
Chris's avatar
Chris committed
262
		if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
263 264 265 266 267 268
			mlog.Error(
				fmt.Sprintf("Unable to save file info when migrating post to use FileInfos, err=%v", result.Err),
				mlog.String("post_id", post.Id),
				mlog.String("file_info_id", info.Id),
				mlog.String("file_info_path", info.Path),
			)
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
			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
284
	if result := <-a.Srv.Store.Post().Update(newPost, post); result.Err != nil {
285
		mlog.Error(fmt.Sprintf("Unable to save migrated post when migrating to use FileInfos, new_file_ids=%v, old_filenames=%v, err=%v", newPost.FileIds, post.Filenames, result.Err), mlog.String("post_id", post.Id))
286 287 288 289 290 291
		return []*model.FileInfo{}
	} else {
		return savedInfos
	}
}

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

Chris's avatar
Chris committed
297 298
func (a *App) GeneratePublicLinkV3(siteURL string, info *model.FileInfo) string {
	hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
299
	return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash)
300 301 302 303 304 305 306 307 308
}

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

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

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
func (a *App) UploadMultipartFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string) (*model.FileUploadResponse, *model.AppError) {
	files := make([]io.ReadCloser, len(fileHeaders))
	filenames := make([]string, len(fileHeaders))

	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)
		}

		// Will be closed after UploadFiles returns
		defer file.Close()

		files[i] = file
		filenames[i] = fileHeader.Filename
	}

	return a.UploadFiles(teamId, channelId, userId, files, filenames, clientIds)
}

// Uploads some files to the given team and channel as the given user. files and filenames should have
// the same length. clientIds should either not be provided or have the same length as files and filenames.
// The provided files should be closed by the caller so that they are not leaked.
func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string) (*model.FileUploadResponse, *model.AppError) {
Chris's avatar
Chris committed
334
	if len(*a.Config().FileSettings.DriverName) == 0 {
335 336 337
		return nil, model.NewAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented)
	}

338 339 340 341
	if len(filenames) != len(files) || (len(clientIds) > 0 && len(clientIds) != len(files)) {
		return nil, model.NewAppError("UploadFiles", "api.file.upload_file.incorrect_number_of_files.app_error", nil, "", http.StatusBadRequest)
	}

342 343 344 345 346 347 348 349 350
	resStruct := &model.FileUploadResponse{
		FileInfos: []*model.FileInfo{},
		ClientIds: []string{},
	}

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

351
	for i, file := range files {
352 353 354 355
		buf := bytes.NewBuffer(nil)
		io.Copy(buf, file)
		data := buf.Bytes()

356
		info, err := a.DoUploadFile(time.Now(), teamId, channelId, userId, filenames[i], data)
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
		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])
		}
	}

374
	a.HandleImages(previewPathList, thumbnailPathList, imageDataList)
375 376 377 378

	return resStruct, nil
}

379
func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
380
	filename := filepath.Base(rawFilename)
381 382 383
	teamId := filepath.Base(rawTeamId)
	channelId := filepath.Base(rawChannelId)
	userId := filepath.Base(rawUserId)
384 385 386 387 388 389 390

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

391 392 393 394 395 396 397 398
	if orientation, err := getImageOrientation(bytes.NewReader(data)); err == nil &&
		(orientation == RotatedCWMirrored ||
			orientation == RotatedCCW ||
			orientation == RotatedCCWMirrored ||
			orientation == RotatedCW) {
		info.Width, info.Height = info.Height, info.Width
	}

399 400 401
	info.Id = model.NewId()
	info.CreatorId = userId

402
	pathPrefix := now.Format("20060102") + "/teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + info.Id + "/"
403 404 405 406 407
	info.Path = pathPrefix + filename

	if info.IsImage() {
		// Check dimensions before loading the whole thing into memory later on
		if info.Width*info.Height > MaxImageSize {
408
			err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]interface{}{"Filename": filename}, "", http.StatusBadRequest)
409 410 411 412 413 414 415 416
			return nil, err
		}

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

417
	if err := a.WriteFile(data, info.Path); err != nil {
418 419 420
		return nil, err
	}

Chris's avatar
Chris committed
421
	if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
422 423 424 425 426 427
		return nil, result.Err
	}

	return info, nil
}

428
func (a *App) HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) {
429 430 431 432 433 434 435 436
	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()
437
				a.generateThumbnailImage(*img, path, width, height)
438
			}(img, thumbnailPathList[i], width, height)
439 440 441

			go func(img *image.Image, path string, width int) {
				defer wg.Done()
442
				a.generatePreviewImage(*img, path, width)
443 444
			}(img, previewPathList[i], width)
		}
445
	}
446
	wg.Wait()
447 448 449 450 451 452
}

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 {
453
		mlog.Error(fmt.Sprintf("Unable to decode image err=%v", err))
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
		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
469 470
	orientation, _ := getImageOrientation(bytes.NewReader(fileData))
	img = makeImageUpright(img, orientation)
471

472 473 474 475
	return &img, width, height
}

func makeImageUpright(img image.Image, orientation int) image.Image {
476 477
	switch orientation {
	case UprightMirrored:
478
		return imaging.FlipH(img)
479
	case UpsideDown:
480
		return imaging.Rotate180(img)
481
	case UpsideDownMirrored:
482
		return imaging.FlipV(img)
483
	case RotatedCWMirrored:
484
		return imaging.Transpose(img)
485
	case RotatedCCW:
486
		return imaging.Rotate270(img)
487
	case RotatedCCWMirrored:
488
		return imaging.Transverse(img)
489
	case RotatedCW:
490 491 492
		return imaging.Rotate90(img)
	default:
		return img
493 494 495
	}
}

496 497
func getImageOrientation(input io.Reader) (int, error) {
	if exifData, err := exif.Decode(input); err != nil {
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
		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
			}
		}
	}
}

513
func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) {
514 515 516 517 518
	thumbWidth := float64(IMAGE_THUMBNAIL_PIXEL_WIDTH)
	thumbHeight := float64(IMAGE_THUMBNAIL_PIXEL_HEIGHT)
	imgWidth := float64(width)
	imgHeight := float64(height)

519
	var thumbnail image.Image
520
	if imgHeight < IMAGE_THUMBNAIL_PIXEL_HEIGHT && imgWidth < thumbWidth {
521
		thumbnail = img
522 523
	} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
		thumbnail = imaging.Resize(img, 0, IMAGE_THUMBNAIL_PIXEL_HEIGHT, imaging.Lanczos)
524
	} else {
525
		thumbnail = imaging.Resize(img, IMAGE_THUMBNAIL_PIXEL_WIDTH, 0, imaging.Lanczos)
526 527 528 529
	}

	buf := new(bytes.Buffer)
	if err := jpeg.Encode(buf, thumbnail, &jpeg.Options{Quality: 90}); err != nil {
530
		mlog.Error(fmt.Sprintf("Unable to encode image as jpeg path=%v err=%v", thumbnailPath, err))
531 532 533
		return
	}

534
	if err := a.WriteFile(buf.Bytes(), thumbnailPath); err != nil {
535
		mlog.Error(fmt.Sprintf("Unable to upload thumbnail path=%v err=%v", thumbnailPath, err))
536 537 538 539
		return
	}
}

540
func (a *App) generatePreviewImage(img image.Image, previewPath string, width int) {
541
	var preview image.Image
542 543 544

	if width > IMAGE_PREVIEW_PIXEL_WIDTH {
		preview = imaging.Resize(img, IMAGE_PREVIEW_PIXEL_WIDTH, 0, imaging.Lanczos)
545 546 547 548 549 550 551
	} else {
		preview = img
	}

	buf := new(bytes.Buffer)

	if err := jpeg.Encode(buf, preview, &jpeg.Options{Quality: 90}); err != nil {
552
		mlog.Error(fmt.Sprintf("Unable to encode image as preview jpg err=%v", err), mlog.String("path", previewPath))
553 554 555
		return
	}

556
	if err := a.WriteFile(buf.Bytes(), previewPath); err != nil {
557
		mlog.Error(fmt.Sprintf("Unable to upload preview err=%v", err), mlog.String("path", previewPath))
558 559 560
		return
	}
}
561

Chris's avatar
Chris committed
562 563
func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) {
	if result := <-a.Srv.Store.FileInfo().Get(fileId); result.Err != nil {
564 565 566 567 568
		return nil, result.Err
	} else {
		return result.Data.(*model.FileInfo), nil
	}
}