github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/api4/export.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package api4 5 6 import ( 7 "encoding/json" 8 "net/http" 9 "path/filepath" 10 "time" 11 12 "github.com/masterhung0112/hk_server/v5/audit" 13 "github.com/masterhung0112/hk_server/v5/model" 14 ) 15 16 func (api *API) InitExport() { 17 api.BaseRoutes.Exports.Handle("", api.ApiSessionRequired(listExports)).Methods("GET") 18 api.BaseRoutes.Export.Handle("", api.ApiSessionRequired(deleteExport)).Methods("DELETE") 19 api.BaseRoutes.Export.Handle("", api.ApiSessionRequired(downloadExport)).Methods("GET") 20 } 21 22 func listExports(c *Context, w http.ResponseWriter, r *http.Request) { 23 if !c.IsSystemAdmin() { 24 c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) 25 return 26 } 27 28 exports, appErr := c.App.ListExports() 29 if appErr != nil { 30 c.Err = appErr 31 return 32 } 33 34 data, err := json.Marshal(exports) 35 if err != nil { 36 c.Err = model.NewAppError("listImports", "app.export.marshal.app_error", nil, err.Error(), http.StatusInternalServerError) 37 return 38 } 39 40 w.Write(data) 41 } 42 43 func deleteExport(c *Context, w http.ResponseWriter, r *http.Request) { 44 auditRec := c.MakeAuditRecord("deleteExport", audit.Fail) 45 defer c.LogAuditRec(auditRec) 46 auditRec.AddMeta("export_name", c.Params.ExportName) 47 48 if !c.IsSystemAdmin() { 49 c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) 50 return 51 } 52 53 if err := c.App.DeleteExport(c.Params.ExportName); err != nil { 54 c.Err = err 55 return 56 } 57 58 auditRec.Success() 59 ReturnStatusOK(w) 60 } 61 62 func downloadExport(c *Context, w http.ResponseWriter, r *http.Request) { 63 if !c.IsSystemAdmin() { 64 c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) 65 return 66 } 67 68 filePath := filepath.Join(*c.App.Config().ExportSettings.Directory, c.Params.ExportName) 69 if ok, err := c.App.FileExists(filePath); err != nil { 70 c.Err = err 71 return 72 } else if !ok { 73 c.Err = model.NewAppError("downloadExport", "api.export.export_not_found.app_error", nil, "", http.StatusNotFound) 74 return 75 } 76 77 file, err := c.App.FileReader(filePath) 78 if err != nil { 79 c.Err = err 80 return 81 } 82 defer file.Close() 83 84 w.Header().Set("Content-Type", "application/zip") 85 http.ServeContent(w, r, c.Params.ExportName, time.Time{}, file) 86 }