file.go 8.83 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 17 18 19 20 21 22 23 24
// See License.txt for license information.

package api4

import (
	"net/http"
	"net/url"
	"strconv"

	l4g "github.com/alecthomas/log4go"
	"github.com/mattermost/platform/app"
	"github.com/mattermost/platform/model"
	"github.com/mattermost/platform/utils"
)

const (
	FILE_TEAM_ID = "noteam"
)

func InitFile() {
	l4g.Debug(utils.T("api.file.init.debug"))

	BaseRoutes.Files.Handle("", ApiSessionRequired(uploadFile)).Methods("POST")
25 26
	BaseRoutes.File.Handle("", ApiSessionRequiredTrustRequester(getFile)).Methods("GET")
	BaseRoutes.File.Handle("/thumbnail", ApiSessionRequiredTrustRequester(getFileThumbnail)).Methods("GET")
27
	BaseRoutes.File.Handle("/link", ApiSessionRequired(getFileLink)).Methods("GET")
28
	BaseRoutes.File.Handle("/preview", ApiSessionRequiredTrustRequester(getFilePreview)).Methods("GET")
29
	BaseRoutes.File.Handle("/info", ApiSessionRequired(getFileInfo)).Methods("GET")
30

31 32
	BaseRoutes.PublicFile.Handle("", ApiHandler(getPublicFile)).Methods("GET")

33 34 35
}

func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) {
36 37 38 39 40
	if !*utils.Cfg.FileSettings.EnableFileAttachments {
		c.Err = model.NewAppError("uploadFile", "api.file.attachments.disabled.app_error", nil, "", http.StatusNotImplemented)
		return
	}

41
	if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize {
42
		c.Err = model.NewAppError("uploadFile", "api.file.upload_file.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge)
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
		return
	}

	if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	m := r.MultipartForm

	props := m.Value
	if len(props["channel_id"]) == 0 {
		c.SetInvalidParam("channel_id")
		return
	}
	channelId := props["channel_id"][0]
	if len(channelId) == 0 {
		c.SetInvalidParam("channel_id")
		return
	}

	if !app.SessionHasPermissionToChannel(c.Session, channelId, model.PERMISSION_UPLOAD_FILE) {
		c.SetPermissionError(model.PERMISSION_UPLOAD_FILE)
		return
	}

	resStruct, err := app.UploadFiles(FILE_TEAM_ID, channelId, c.Session.UserId, m.File["files"], m.Value["client_ids"])
	if err != nil {
		c.Err = err
		return
	}

	w.WriteHeader(http.StatusCreated)
	w.Write([]byte(resStruct.ToJson()))
}

func getFile(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

85 86 87 88 89
	toDownload, failConv := strconv.ParseBool(r.URL.Query().Get("download"))
	if failConv != nil {
		toDownload = false
	}

90 91 92 93 94 95 96 97 98 99 100
	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
		c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
		return
	}

101 102
	data, err := app.ReadFile(info.Path)
	if err != nil {
103 104
		c.Err = err
		c.Err.StatusCode = http.StatusNotFound
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
		return
	}

	contentTypeToCheck := []string{"image/jpeg", "image/png", "image/bmp", "image/gif",
		"video/avi", "video/mpeg", "audio/mpeg3", "audio/wav"}

	contentType := http.DetectContentType(data)
	foundContentType := false
	for _, contentTypeFromList := range contentTypeToCheck {
		if contentType == contentTypeFromList && toDownload == false {
			foundContentType = true
			break
		}
	}
	if !foundContentType {
		toDownload = true
	}

	err = writeFileResponse(info.Name, info.MimeType, data, toDownload, w, r)
	if err != nil {
125 126 127 128 129
		c.Err = err
		return
	}
}

130 131 132 133 134 135
func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

136 137 138 139 140
	toDownload, failConv := strconv.ParseBool(r.URL.Query().Get("download"))
	if failConv != nil {
		toDownload = false
	}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
		c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
		return
	}

	if info.ThumbnailPath == "" {
		c.Err = model.NewLocAppError("getFileThumbnail", "api.file.get_file_thumbnail.no_thumbnail.app_error", nil, "file_id="+info.Id)
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	if data, err := app.ReadFile(info.ThumbnailPath); err != nil {
		c.Err = err
		c.Err.StatusCode = http.StatusNotFound
161
	} else if err := writeFileResponse(info.Name, info.MimeType, data, toDownload, w, r); err != nil {
162 163 164 165 166
		c.Err = err
		return
	}
}

167 168 169 170 171 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
func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

	if !utils.Cfg.FileSettings.EnablePublicLink {
		c.Err = model.NewLocAppError("getPublicLink", "api.file.get_public_link.disabled.app_error", nil, "")
		c.Err.StatusCode = http.StatusNotImplemented
		return
	}

	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
		c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
		return
	}

	if len(info.PostId) == 0 {
		c.Err = model.NewLocAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id)
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	resp := make(map[string]string)
197
	resp["link"] = app.GeneratePublicLink(c.GetSiteURLHeader(), info)
198 199 200 201

	w.Write([]byte(model.MapToJson(resp)))
}

202 203 204 205 206 207
func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

208 209 210 211 212
	toDownload, failConv := strconv.ParseBool(r.URL.Query().Get("download"))
	if failConv != nil {
		toDownload = false
	}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
		c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
		return
	}

	if info.PreviewPath == "" {
		c.Err = model.NewLocAppError("getFilePreview", "api.file.get_file_preview.no_preview.app_error", nil, "file_id="+info.Id)
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	if data, err := app.ReadFile(info.PreviewPath); err != nil {
		c.Err = err
		c.Err.StatusCode = http.StatusNotFound
233
	} else if err := writeFileResponse(info.Name, info.MimeType, data, toDownload, w, r); err != nil {
234 235 236 237 238
		c.Err = err
		return
	}
}

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
		c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
		return
	}

	w.Header().Set("Cache-Control", "max-age=2592000, public")
	w.Write([]byte(info.ToJson()))
}

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) {
	c.RequireFileId()
	if c.Err != nil {
		return
	}

	if !utils.Cfg.FileSettings.EnablePublicLink {
		c.Err = model.NewLocAppError("getPublicFile", "api.file.get_public_link.disabled.app_error", nil, "")
		c.Err.StatusCode = http.StatusNotImplemented
		return
	}

	info, err := app.GetFileInfo(c.Params.FileId)
	if err != nil {
		c.Err = err
		return
	}

	hash := r.URL.Query().Get("h")

	if len(hash) == 0 {
		c.Err = model.NewLocAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "")
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	if hash != app.GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) {
		c.Err = model.NewLocAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "")
		c.Err.StatusCode = http.StatusBadRequest
		return
	}

	if data, err := app.ReadFile(info.Path); err != nil {
		c.Err = err
		c.Err.StatusCode = http.StatusNotFound
295
	} else if err := writeFileResponse(info.Name, info.MimeType, data, true, w, r); err != nil {
296 297 298 299 300
		c.Err = err
		return
	}
}

301
func writeFileResponse(filename string, contentType string, bytes []byte, toDownload bool, w http.ResponseWriter, r *http.Request) *model.AppError {
302 303 304 305 306 307 308 309 310
	w.Header().Set("Cache-Control", "max-age=2592000, public")
	w.Header().Set("Content-Length", strconv.Itoa(len(bytes)))

	if contentType != "" {
		w.Header().Set("Content-Type", contentType)
	} else {
		w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer
	}

311 312 313 314 315
	if toDownload {
		w.Header().Set("Content-Disposition", "attachment;filename=\""+filename+"\"; filename*=UTF-8''"+url.QueryEscape(filename))
	} else {
		w.Header().Set("Content-Disposition", "inline;filename=\""+filename+"\"; filename*=UTF-8''"+url.QueryEscape(filename))
	}
316 317 318 319 320 321 322 323 324

	// prevent file links from being embedded in iframes
	w.Header().Set("X-Frame-Options", "DENY")
	w.Header().Set("Content-Security-Policy", "Frame-ancestors 'none'")

	w.Write(bytes)

	return nil
}