file.go 20.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
	"github.com/mattermost/mattermost-server/model"
31
	"github.com/mattermost/mattermost-server/plugin"
32
	"github.com/mattermost/mattermost-server/services/filesstore"
Christopher Speller's avatar
Christopher Speller committed
33
	"github.com/mattermost/mattermost-server/utils"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
)

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

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

62
func (a *App) FileBackend() (filesstore.FileBackend, *model.AppError) {
63
	license := a.License()
64
	return filesstore.NewFileBackend(&a.Config().FileSettings, license != nil && *license.Features.Compliance)
65 66 67 68 69 70 71 72 73 74
}

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

75 76
// Caller must close the first return value
func (a *App) FileReader(path string) (io.ReadCloser, *model.AppError) {
77 78 79 80 81 82 83
	backend, err := a.FileBackend()
	if err != nil {
		return nil, err
	}
	return backend.Reader(path)
}

84 85 86 87 88 89 90 91
func (a *App) FileExists(path string) (bool, *model.AppError) {
	backend, err := a.FileBackend()
	if err != nil {
		return false, err
	}
	return backend.FileExists(path)
}

92 93 94 95 96 97 98 99
func (a *App) MoveFile(oldPath, newPath string) *model.AppError {
	backend, err := a.FileBackend()
	if err != nil {
		return err
	}
	return backend.MoveFile(oldPath, newPath)
}

100
func (a *App) WriteFile(fr io.Reader, path string) (int64, *model.AppError) {
101 102
	backend, err := a.FileBackend()
	if err != nil {
103
		return 0, err
104
	}
105 106

	return backend.WriteFile(fr, path)
107 108 109 110 111 112 113 114 115 116 117
}

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 {
118 119 120
	// Find the path from the Filename of the form /{channelId}/{userId}/{uid}/{nameWithExtension}
	split := strings.SplitN(filename, "/", 5)
	if len(split) < 5 {
121
		mlog.Error("Unable to decipher filename when migrating post to use FileInfos", mlog.String("post_id", post.Id), mlog.String("filename", filename))
122 123 124 125 126 127 128 129 130
		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], "/") {
131 132 133 134 135 136 137
		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),
		)
138 139 140 141 142 143
	}

	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
144 145
	data, err := a.ReadFile(path)
	if err != nil {
146 147 148 149 150 151
		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),
		)
152
		return nil
153 154 155 156 157 158 159 160 161
	}

	info, err := model.GetInfoForBytes(name, data)
	if err != nil {
		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),
		)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	}

	// 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
181
func (a *App) FindTeamIdForFilename(post *model.Post, filename string) string {
182 183 184 185 186
	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.
187 188
	result := <-a.Srv.Store.Team().GetTeamsByUserId(post.UserId)
	if result.Err != nil {
189
		mlog.Error(fmt.Sprintf("Unable to get teams when migrating post to use FileInfo, err=%v", result.Err), mlog.String("post_id", post.Id))
190 191 192 193 194
		return ""
	}

	teams := result.Data.([]*model.Team)
	if len(teams) == 1 {
195 196
		// The user has only one team so the post must've been sent from it
		return teams[0].Id
197 198 199 200 201 202 203
	}

	for _, team := range teams {
		path := fmt.Sprintf("teams/%s/channels/%s/users/%s/%s/%s", team.Id, post.ChannelId, post.UserId, id, name)
		if _, err := a.ReadFile(path); err == nil {
			// Found the team that this file was posted from
			return team.Id
204 205 206 207 208 209 210 211 212
		}
	}

	return ""
}

var fileMigrationLock sync.Mutex

// Creates and stores FileInfos for a post created before the FileInfos table existed.
Chris's avatar
Chris committed
213
func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo {
214
	if len(post.Filenames) == 0 {
215
		mlog.Warn("Unable to migrate post to use FileInfos with an empty Filenames field", mlog.String("post_id", post.Id))
216 217 218
		return []*model.FileInfo{}
	}

Chris's avatar
Chris committed
219
	cchan := a.Srv.Store.Channel().Get(post.ChannelId, true)
220 221 222 223

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

224 225
	result := <-cchan
	if result.Err != nil {
226 227 228 229 230
		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),
		)
231 232
		return []*model.FileInfo{}
	}
233
	channel := result.Data.(*model.Channel)
234 235 236 237 238

	// 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
239
		teamId = a.FindTeamIdForFilename(post, filenames[0])
240 241 242 243 244 245 246
	} else {
		teamId = channel.TeamId
	}

	// Create FileInfo objects for this post
	infos := make([]*model.FileInfo, 0, len(filenames))
	if teamId == "" {
247 248 249 250
		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),
		)
251 252
	} else {
		for _, filename := range filenames {
253
			info := a.GetInfoForFilename(post, teamId, filename)
254 255 256 257 258 259 260 261 262 263 264 265
			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()

266 267
	result = <-a.Srv.Store.Post().Get(post.Id)
	if result.Err != nil {
268
		mlog.Error(fmt.Sprintf("Unable to get post when migrating post to use FileInfos, err=%v", result.Err), mlog.String("post_id", post.Id))
269
		return []*model.FileInfo{}
270 271 272
	}

	if newPost := result.Data.(*model.PostList).Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) {
273
		// Another thread has already created FileInfos for this post, so just return those
274 275
		result := <-a.Srv.Store.FileInfo().GetForPost(post.Id, true, false)
		if result.Err != nil {
276
			mlog.Error(fmt.Sprintf("Unable to get FileInfos for migrated post, err=%v", result.Err), mlog.String("post_id", post.Id))
277 278
			return []*model.FileInfo{}
		}
279 280 281

		mlog.Debug("Post already migrated to use FileInfos", mlog.String("post_id", post.Id))
		return result.Data.([]*model.FileInfo)
282 283
	}

284
	mlog.Debug("Migrating post to use FileInfos", mlog.String("post_id", post.Id))
285 286 287 288

	savedInfos := make([]*model.FileInfo, 0, len(infos))
	fileIds := make([]string, 0, len(filenames))
	for _, info := range infos {
Chris's avatar
Chris committed
289
		if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
290 291 292 293 294 295
			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),
			)
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
			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
311
	if result := <-a.Srv.Store.Post().Update(newPost, post); result.Err != nil {
312
		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))
313 314
		return []*model.FileInfo{}
	}
315
	return savedInfos
316 317
}

318 319
func (a *App) GeneratePublicLink(siteURL string, info *model.FileInfo) string {
	hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
320 321 322
	return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash)
}

323 324 325 326 327 328 329
func GeneratePublicLinkHash(fileId, salt string) string {
	hash := sha256.New()
	hash.Write([]byte(salt))
	hash.Write([]byte(fileId))

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

331
func (a *App) UploadMultipartFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
	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
	}

348
	return a.UploadFiles(teamId, channelId, userId, files, filenames, clientIds, now)
349 350 351 352 353
}

// 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.
354
func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
Chris's avatar
Chris committed
355
	if len(*a.Config().FileSettings.DriverName) == 0 {
356 357 358
		return nil, model.NewAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented)
	}

359 360 361 362
	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)
	}

363 364 365 366 367 368 369 370 371
	resStruct := &model.FileUploadResponse{
		FileInfos: []*model.FileInfo{},
		ClientIds: []string{},
	}

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

372
	for i, file := range files {
373 374 375 376
		buf := bytes.NewBuffer(nil)
		io.Copy(buf, file)
		data := buf.Bytes()

377
		info, data, err := a.DoUploadFileExpectModification(now, teamId, channelId, userId, filenames[i], data)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
		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])
		}
	}

395
	a.HandleImages(previewPathList, thumbnailPathList, imageDataList)
396 397 398 399

	return resStruct, nil
}

400
func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
401 402 403 404 405
	info, _, err := a.DoUploadFileExpectModification(now, rawTeamId, rawChannelId, rawUserId, rawFilename, data)
	return info, err
}

func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) {
406
	filename := filepath.Base(rawFilename)
407 408 409
	teamId := filepath.Base(rawTeamId)
	channelId := filepath.Base(rawChannelId)
	userId := filepath.Base(rawUserId)
410 411 412 413

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

417 418 419 420 421 422 423 424
	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
	}

425 426
	info.Id = model.NewId()
	info.CreatorId = userId
427
	info.CreateAt = now.UnixNano() / int64(time.Millisecond)
428

429
	pathPrefix := now.Format("20060102") + "/teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + info.Id + "/"
430 431 432 433 434
	info.Path = pathPrefix + filename

	if info.IsImage() {
		// Check dimensions before loading the whole thing into memory later on
		if info.Width*info.Height > MaxImageSize {
435
			err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]interface{}{"Filename": filename}, "", http.StatusBadRequest)
436
			return nil, data, err
437 438 439 440 441 442 443
		}

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

444
	if a.PluginsReady() {
445
		var rejectionError *model.AppError
446 447 448
		pluginContext := &plugin.Context{}
		a.Plugins.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
			var newBytes bytes.Buffer
449 450 451 452 453 454 455 456 457
			replacementInfo, rejectionReason := hooks.FileWillBeUploaded(pluginContext, info, bytes.NewReader(data), &newBytes)
			if rejectionReason != "" {
				rejectionError = model.NewAppError("DoUploadFile", "File rejected by plugin. "+rejectionReason, nil, "", http.StatusBadRequest)
				return false
			}
			if replacementInfo != nil {
				info = replacementInfo
			}
			if newBytes.Len() != 0 {
458 459 460
				data = newBytes.Bytes()
				info.Size = int64(len(data))
			}
461 462

			return true
463
		}, plugin.FileWillBeUploadedId)
464 465
		if rejectionError != nil {
			return nil, data, rejectionError
466 467 468
		}
	}

469
	if _, err := a.WriteFile(bytes.NewReader(data), info.Path); err != nil {
470
		return nil, data, err
471 472
	}

Chris's avatar
Chris committed
473
	if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil {
474
		return nil, data, result.Err
475 476
	}

477
	return info, data, nil
478 479
}

480
func (a *App) HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) {
481 482 483 484 485 486 487 488
	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()
489
				a.generateThumbnailImage(*img, path, width, height)
490
			}(img, thumbnailPathList[i], width, height)
491 492 493

			go func(img *image.Image, path string, width int) {
				defer wg.Done()
494
				a.generatePreviewImage(*img, path, width)
495 496
			}(img, previewPathList[i], width)
		}
497
	}
498
	wg.Wait()
499 500 501 502 503 504
}

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 {
505
		mlog.Error(fmt.Sprintf("Unable to decode image err=%v", err))
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
		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
521 522
	orientation, _ := getImageOrientation(bytes.NewReader(fileData))
	img = makeImageUpright(img, orientation)
523

524 525 526 527
	return &img, width, height
}

func makeImageUpright(img image.Image, orientation int) image.Image {
528 529
	switch orientation {
	case UprightMirrored:
530
		return imaging.FlipH(img)
531
	case UpsideDown:
532
		return imaging.Rotate180(img)
533
	case UpsideDownMirrored:
534
		return imaging.FlipV(img)
535
	case RotatedCWMirrored:
536
		return imaging.Transpose(img)
537
	case RotatedCCW:
538
		return imaging.Rotate270(img)
539
	case RotatedCCWMirrored:
540
		return imaging.Transverse(img)
541
	case RotatedCW:
542 543 544
		return imaging.Rotate90(img)
	default:
		return img
545 546 547
	}
}

548
func getImageOrientation(input io.Reader) (int, error) {
549 550
	exifData, err := exif.Decode(input)
	if err != nil {
551 552
		return Upright, err
	}
553 554 555 556 557 558 559 560 561 562 563 564

	tag, err := exifData.Get("Orientation")
	if err != nil {
		return Upright, err
	}

	orientation, err := tag.Int(0)
	if err != nil {
		return Upright, err
	}

	return orientation, nil
565 566
}

567
func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) {
568 569 570 571 572
	thumbWidth := float64(IMAGE_THUMBNAIL_PIXEL_WIDTH)
	thumbHeight := float64(IMAGE_THUMBNAIL_PIXEL_HEIGHT)
	imgWidth := float64(width)
	imgHeight := float64(height)

573
	var thumbnail image.Image
574
	if imgHeight < IMAGE_THUMBNAIL_PIXEL_HEIGHT && imgWidth < thumbWidth {
575
		thumbnail = img
576 577
	} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
		thumbnail = imaging.Resize(img, 0, IMAGE_THUMBNAIL_PIXEL_HEIGHT, imaging.Lanczos)
578
	} else {
579
		thumbnail = imaging.Resize(img, IMAGE_THUMBNAIL_PIXEL_WIDTH, 0, imaging.Lanczos)
580 581 582 583
	}

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

588
	if _, err := a.WriteFile(buf, thumbnailPath); err != nil {
589
		mlog.Error(fmt.Sprintf("Unable to upload thumbnail path=%v err=%v", thumbnailPath, err))
590 591 592 593
		return
	}
}

594
func (a *App) generatePreviewImage(img image.Image, previewPath string, width int) {
595
	var preview image.Image
596 597 598

	if width > IMAGE_PREVIEW_PIXEL_WIDTH {
		preview = imaging.Resize(img, IMAGE_PREVIEW_PIXEL_WIDTH, 0, imaging.Lanczos)
599 600 601 602 603 604 605
	} else {
		preview = img
	}

	buf := new(bytes.Buffer)

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

610
	if _, err := a.WriteFile(buf, previewPath); err != nil {
611
		mlog.Error(fmt.Sprintf("Unable to upload preview err=%v", err), mlog.String("path", previewPath))
612 613 614
		return
	}
}
615

Chris's avatar
Chris committed
616
func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) {
617 618
	result := <-a.Srv.Store.FileInfo().Get(fileId)
	if result.Err != nil {
619 620
		return nil, result.Err
	}
621
	return result.Data.(*model.FileInfo), nil
622
}
623 624

func (a *App) CopyFileInfos(userId string, fileIds []string) ([]string, *model.AppError) {
625
	var newFileIds []string
626 627 628 629

	now := model.GetMillis()

	for _, fileId := range fileIds {
630
		result := <-a.Srv.Store.FileInfo().Get(fileId)
631

632
		if result.Err != nil {
633 634 635
			return nil, result.Err
		}

636
		fileInfo := result.Data.(*model.FileInfo)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
		fileInfo.Id = model.NewId()
		fileInfo.CreatorId = userId
		fileInfo.CreateAt = now
		fileInfo.UpdateAt = now
		fileInfo.PostId = ""

		if result := <-a.Srv.Store.FileInfo().Save(fileInfo); result.Err != nil {
			return newFileIds, result.Err
		}

		newFileIds = append(newFileIds, fileInfo.Id)
	}

	return newFileIds, nil
}