summaryrefslogtreecommitdiffstats
path: root/model/file_info.go
blob: d96723f32a3d1eb50c4bc08d86453212284cc1fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package model

import (
	"bytes"
	"encoding/json"
	"image/gif"
	"mime"
	"path/filepath"
)

type FileInfo struct {
	Filename        string `json:"filename"`
	Size            int    `json:"size"`
	Extension       string `json:"extension"`
	MimeType        string `json:"mime_type"`
	HasPreviewImage bool   `json:"has_preview_image"`
}

func GetInfoForBytes(filename string, data []byte) (*FileInfo, *AppError) {
	size := len(data)

	var mimeType string
	extension := filepath.Ext(filename)
	isImage := IsFileExtImage(extension)
	if isImage {
		mimeType = GetImageMimeType(extension)
	} else {
		mimeType = mime.TypeByExtension(extension)
	}

	hasPreviewImage := isImage
	if mimeType == "image/gif" {
		// just show the gif itself instead of a preview image for animated gifs
		if gifImage, err := gif.DecodeAll(bytes.NewReader(data)); err != nil {
			return nil, NewAppError("GetInfoForBytes", "Could not decode gif.", "filename="+filename)
		} else {
			hasPreviewImage = len(gifImage.Image) == 1
		}
	}

	return &FileInfo{
		Filename:        filename,
		Size:            size,
		Extension:       extension[1:],
		MimeType:        mimeType,
		HasPreviewImage: hasPreviewImage,
	}, nil
}

func (info *FileInfo) ToJson() string {
	b, err := json.Marshal(info)
	if err != nil {
		return ""
	} else {
		return string(b)
	}
}