Files
mostlymatter/api4/job.go
Claudio Costa 92837fa1ee [MM-22051] Remove To/From JSON (#18070)
* Posts

* Add missing translation

* Fix internal store marshaling

* [MM-22051] Remove To/From JSON (Channels) (#18116)

* Channels

* Channel members

* ChannelSearch

* Channel categories, list, sidebar, stats, view

* Fix conversions

* [MM-22051] Remove To/From JSON (Users) (#18121)

* User related structs

* Fix return

* Team related structures (#18127)

* [MM-22051] Remove To/From JSON (Status, Bot, Reaction, Thread, FileInfo) (#18130)

* Status

* Bot

* Reaction

* Thread

* FileInfo

* Some fixes

* Translations update from Weblate (#18143)

* Translated using Weblate (German)

Currently translated at 100.0% (2309 of 2309 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/de/

* Translated using Weblate (Turkish)

Currently translated at 100.0% (2309 of 2309 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/tr/

* Translated using Weblate (Hungarian)

Currently translated at 100.0% (2309 of 2309 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/hu/

* Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/

Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/

Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/

Update translation files

Updated by "Cleanup translation files" hook in Weblate.

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/

* Translated using Weblate (German)

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/de/

* Translated using Weblate (Turkish)

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/tr/

* Translated using Weblate (Hungarian)

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/hu/

* Translated using Weblate (English (Australia))

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/en_AU/

* Translated using Weblate (Bulgarian)

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/bg/

* Translated using Weblate (Japanese)

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/ja/

* Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (2301 of 2301 strings)

Translation: mattermost-languages-shipped/mattermost-server
Translate-URL: https://translate.mattermost.com/projects/mattermost/mattermost-server_master/zh_Hans/

Co-authored-by: JtheBAB <srast@bioc.uzh.ch>
Co-authored-by: Kaya Zeren <kayazeren@gmail.com>
Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu>
Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au>
Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com>
Co-authored-by: kaakaa <stooner.hoe@gmail.com>
Co-authored-by: aeomin <lin@aeomin.net>

Co-authored-by: Weblate (bot) <hosted@weblate.org>
Co-authored-by: JtheBAB <srast@bioc.uzh.ch>
Co-authored-by: Kaya Zeren <kayazeren@gmail.com>
Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu>
Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au>
Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com>
Co-authored-by: kaakaa <stooner.hoe@gmail.com>
Co-authored-by: aeomin <lin@aeomin.net>

* [MM-22051] Remove To/From JSON methods from model (#18138)

* Scheme

* Role

* Session

* Config

* Status

* Fix logic

* Emoji

* GuestsInvite

* Group

* Command

* ClusterInfo

* License

* Job

* System

* Plugin

* Command2

* IncomingWebhook

* OutgoingWebhook

* Fix tests

* Update traslation

* Some fixes

* Add missing return

* Simplify

* Make Config.ToJSONFiltered() return []byte

* Make Busy.ToJSON() return []byte

* Include error in log

* Split logic

* [MM-22051] Remove To/From JSON (final) (#18150)

* SwitchRequest

* PluginEventData

* Permalink

* PushNotification

* SuggestCommand

* PluginsResponse

* WebSocketMessage

* RemoteCluster

* SharedChannel

* PluginStatuses

* InitialLoad

* ClusterDiscovery

* ClusterStats

* MfaSecret

* GroupSyncable

* SAML

* WebSocketRequest

* TypingRequest

* SecurityBulletin

* OAuthApp

* IntegrationAction

* DataRetention

* Preference

* FileInfoList

* Compliance

* Preferences

* FileInfoSearchResults

* TermsOfService

* InstallMarketplacePluginRequest

* GitLabUser

* UploadSessions

* Remove unused helpers

* Fix tests

* [MM-23280] Fix linting for ToJSON/FromJSON (#18153)

* SwitchRequest

* PluginEventData

* Permalink

* PushNotification

* SuggestCommand

* PluginsResponse

* WebSocketMessage

* RemoteCluster

* SharedChannel

* PluginStatuses

* InitialLoad

* ClusterDiscovery

* ClusterStats

* MfaSecret

* GroupSyncable

* SAML

* WebSocketRequest

* TypingRequest

* SecurityBulletin

* OAuthApp

* IntegrationAction

* DataRetention

* Preference

* FileInfoList

* Compliance

* Preferences

* FileInfoSearchResults

* TermsOfService

* InstallMarketplacePluginRequest

* GitLabUser

* UploadSessions

* Remove unused helpers

* Fix tests

* Fix linting for ToJSON/FromJSON

* Fix conversions

Co-authored-by: Weblate (bot) <hosted@weblate.org>
Co-authored-by: JtheBAB <srast@bioc.uzh.ch>
Co-authored-by: Kaya Zeren <kayazeren@gmail.com>
Co-authored-by: Tóth Csaba // Online ERP Hungary Kft <csaba.toth@online-erp.hu>
Co-authored-by: Matthew Williams <Matthew.Williams@outlook.com.au>
Co-authored-by: Nikolai Zahariev <nikolaiz@yahoo.com>
Co-authored-by: kaakaa <stooner.hoe@gmail.com>
Co-authored-by: aeomin <lin@aeomin.net>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
2021-09-01 14:43:12 +02:00

245 строки
7.0 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package api4
import (
"encoding/json"
"net/http"
"path/filepath"
"strconv"
"time"
"github.com/mattermost/mattermost-server/v6/audit"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
func (api *API) InitJob() {
api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(getJobs)).Methods("GET")
api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(createJob)).Methods("POST")
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.APISessionRequired(getJob)).Methods("GET")
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/download", api.APISessionRequiredTrustRequester(downloadJob)).Methods("GET")
api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.APISessionRequired(cancelJob)).Methods("POST")
api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.APISessionRequired(getJobsByType)).Methods("GET")
}
func getJob(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobId()
if c.Err != nil {
return
}
job, err := c.App.GetJob(c.Params.JobId)
if err != nil {
c.Err = err
return
}
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), job.Type)
if permissionRequired == nil {
c.Err = model.NewAppError("getJob", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
if err := json.NewEncoder(w).Encode(job); err != nil {
mlog.Warn("Error while writing response", mlog.Err(err))
}
}
func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) {
config := c.App.Config()
const FilePath = "export"
const FileMime = "application/zip"
c.RequireJobId()
if c.Err != nil {
return
}
if !*config.MessageExportSettings.DownloadExportResults {
c.Err = model.NewAppError("downloadExportResultsNotEnabled", "app.job.download_export_results_not_enabled", nil, "", http.StatusNotImplemented)
return
}
job, err := c.App.GetJob(c.Params.JobId)
if err != nil {
c.Err = err
return
}
// Currently, this endpoint only supports downloading the compliance report.
// If you need to download another job type, you will need to alter this section of the code to accommodate it.
if job.Type == model.JobTypeMessageExport && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDownloadComplianceExportResult) {
c.SetPermissionError(model.PermissionDownloadComplianceExportResult)
return
} else if job.Type != model.JobTypeMessageExport {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
isDownloadable, _ := strconv.ParseBool(job.Data["is_downloadable"])
if !isDownloadable {
c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job", nil, "", http.StatusBadRequest)
return
}
fileName := job.Id + ".zip"
filePath := filepath.Join(FilePath, fileName)
fileReader, err := c.App.FileReader(filePath)
if err != nil {
c.Err = err
c.Err.StatusCode = http.StatusNotFound
return
}
defer fileReader.Close()
// We are able to pass 0 for content size due to the fact that Golang's serveContent (https://golang.org/src/net/http/fs.go)
// already sets that for us
writeFileResponse(fileName, FileMime, 0, time.Unix(0, job.LastActivityAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r)
}
func createJob(c *Context, w http.ResponseWriter, r *http.Request) {
var job model.Job
if jsonErr := json.NewDecoder(r.Body).Decode(&job); jsonErr != nil {
c.SetInvalidParam("job")
return
}
auditRec := c.MakeAuditRecord("createJob", audit.Fail)
defer c.LogAuditRec(auditRec)
auditRec.AddMeta("job", job)
hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), &job)
if permissionRequired == nil {
c.Err = model.NewAppError("unableToCreateJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
rjob, err := c.App.CreateJob(&job)
if err != nil {
c.Err = err
return
}
auditRec.Success()
auditRec.AddMeta("job", rjob) // overwrite meta
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(rjob); err != nil {
mlog.Warn("Error while writing response", mlog.Err(err))
}
}
func getJobs(c *Context, w http.ResponseWriter, r *http.Request) {
if c.Err != nil {
return
}
var validJobTypes []string
for _, jobType := range model.AllJobTypes {
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), jobType)
if permissionRequired == nil {
mlog.Warn("The job types of a job you are trying to retrieve does not contain permissions", mlog.String("jobType", jobType))
continue
}
if hasPermission {
validJobTypes = append(validJobTypes, jobType)
}
}
if len(validJobTypes) == 0 {
c.SetPermissionError()
return
}
jobs, err := c.App.GetJobsByTypesPage(validJobTypes, c.Params.Page, c.Params.PerPage)
if err != nil {
c.Err = err
return
}
js, jsonErr := json.Marshal(jobs)
if jsonErr != nil {
c.Err = model.NewAppError("getJobs", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
return
}
w.Write(js)
}
func getJobsByType(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobType()
if c.Err != nil {
return
}
hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), c.Params.JobType)
if permissionRequired == nil {
c.Err = model.NewAppError("getJobsByType", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
jobs, err := c.App.GetJobsByTypePage(c.Params.JobType, c.Params.Page, c.Params.PerPage)
if err != nil {
c.Err = err
return
}
js, jsonErr := json.Marshal(jobs)
if jsonErr != nil {
c.Err = model.NewAppError("getJobsByType", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
return
}
w.Write(js)
}
func cancelJob(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireJobId()
if c.Err != nil {
return
}
auditRec := c.MakeAuditRecord("cancelJob", audit.Fail)
defer c.LogAuditRec(auditRec)
auditRec.AddMeta("job_id", c.Params.JobId)
job, err := c.App.GetJob(c.Params.JobId)
if err != nil {
c.Err = err
return
}
// if permission to create, permission to cancel, same permission
hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), job)
if permissionRequired == nil {
c.Err = model.NewAppError("unableToCancelJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest)
return
}
if !hasPermission {
c.SetPermissionError(permissionRequired)
return
}
if err := c.App.CancelJob(c.Params.JobId); err != nil {
c.Err = err
return
}
auditRec.Success()
ReturnStatusOK(w)
}