PeerTube/server/controllers/api/jobs.ts

83 lines
2.1 KiB
TypeScript
Raw Normal View History

2017-11-30 10:51:13 +01:00
import * as express from 'express'
import { ResultList } from '../../../shared'
2020-12-14 12:00:35 +01:00
import { Job, JobState, JobType } from '../../../shared/models'
2017-12-12 17:53:50 +01:00
import { UserRight } from '../../../shared/models/users'
2020-12-14 12:00:35 +01:00
import { isArray } from '../../helpers/custom-validators/misc'
import { JobQueue } from '../../lib/job-queue'
import {
asyncMiddleware,
authenticate,
ensureUserHasRight,
jobsSortValidator,
setDefaultPagination,
setDefaultSort
} from '../../middlewares'
2017-12-12 17:53:50 +01:00
import { paginationValidator } from '../../middlewares/validators'
2020-12-14 12:00:35 +01:00
import { listJobsValidator } from '../../middlewares/validators/jobs'
2017-11-30 10:51:13 +01:00
const jobsRouter = express.Router()
2020-12-14 12:00:35 +01:00
jobsRouter.get('/:state?',
2020-12-13 19:27:25 +01:00
authenticate,
ensureUserHasRight(UserRight.MANAGE_JOBS),
paginationValidator,
jobsSortValidator,
setDefaultSort,
setDefaultPagination,
listJobsValidator,
asyncMiddleware(listJobs)
)
2017-11-30 10:51:13 +01:00
// ---------------------------------------------------------------------------
export {
jobsRouter
}
// ---------------------------------------------------------------------------
2019-10-21 14:50:55 +02:00
async function listJobs (req: express.Request, res: express.Response) {
2020-12-14 12:00:35 +01:00
const state = req.params.state as JobState
2018-07-10 17:02:20 +02:00
const asc = req.query.sort === 'createdAt'
2019-12-04 14:49:59 +01:00
const jobType = req.query.jobType
2019-12-04 14:49:59 +01:00
const jobs = await JobQueue.Instance.listForApi({
state,
start: req.query.start,
count: req.query.count,
asc,
jobType
})
2020-11-09 16:13:03 +01:00
const total = await JobQueue.Instance.count(state, jobType)
2020-01-31 16:56:52 +01:00
const result: ResultList<Job> = {
total,
2020-12-14 12:00:35 +01:00
data: state
? jobs.map(j => formatJob(j, state))
: await Promise.all(jobs.map(j => formatJobWithUnknownState(j)))
}
2020-12-14 12:00:35 +01:00
return res.json(result)
}
2017-11-30 10:51:13 +01:00
2020-12-14 12:00:35 +01:00
async function formatJobWithUnknownState (job: any) {
return formatJob(job, await job.getState())
}
2018-07-10 17:02:20 +02:00
function formatJob (job: any, state: JobState): Job {
2020-12-14 12:00:35 +01:00
const error = isArray(job.stacktrace) && job.stacktrace.length !== 0
? job.stacktrace[0]
: null
2018-07-10 17:02:20 +02:00
return {
id: job.id,
2018-07-10 17:02:20 +02:00
state: state,
type: job.queue.name as JobType,
data: job.data,
2018-07-10 17:02:20 +02:00
error,
createdAt: new Date(job.timestamp),
finishedOn: new Date(job.finishedOn),
processedOn: new Date(job.processedOn)
}
2017-11-30 10:51:13 +01:00
}