]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/jobs/handlers/video-file-optimizer.ts
Use async/await in lib and initializers
[github/Chocobozzz/PeerTube.git] / server / lib / jobs / handlers / video-file-optimizer.ts
1 import * as Bluebird from 'bluebird'
2
3 import { database as db } from '../../../initializers/database'
4 import { logger, computeResolutionsToTranscode } from '../../../helpers'
5 import { VideoInstance } from '../../../models'
6 import { addVideoToFriends } from '../../friends'
7 import { JobScheduler } from '../job-scheduler'
8
9 async function process (data: { videoUUID: string }, jobId: number) {
10 const video = await db.Video.loadByUUIDAndPopulateAuthorAndPodAndTags(data.videoUUID)
11 // No video, maybe deleted?
12 if (!video) {
13 logger.info('Do not process job %d, video does not exist.', jobId, { videoUUID: video.uuid })
14 return undefined
15 }
16
17 await video.optimizeOriginalVideofile()
18
19 return video
20 }
21
22 function onError (err: Error, jobId: number) {
23 logger.error('Error when optimized video file in job %d.', jobId, err)
24 return Promise.resolve()
25 }
26
27 async function onSuccess (jobId: number, video: VideoInstance) {
28 if (video === undefined) return undefined
29
30 logger.info('Job %d is a success.', jobId)
31
32 const remoteVideo = await video.toAddRemoteJSON()
33
34 // Now we'll add the video's meta data to our friends
35 await addVideoToFriends(remoteVideo, null)
36
37 const originalFileHeight = await video.getOriginalFileHeight()
38 // Create transcoding jobs if there are enabled resolutions
39
40 const resolutionsEnabled = computeResolutionsToTranscode(originalFileHeight)
41 logger.info(
42 'Resolutions computed for video %s and origin file height of %d.', video.uuid, originalFileHeight,
43 { resolutions: resolutionsEnabled }
44 )
45
46 if (resolutionsEnabled.length !== 0) {
47 try {
48 await db.sequelize.transaction(async t => {
49 const tasks: Bluebird<any>[] = []
50
51 for (const resolution of resolutionsEnabled) {
52 const dataInput = {
53 videoUUID: video.uuid,
54 resolution
55 }
56
57 const p = JobScheduler.Instance.createJob(t, 'videoFileTranscoder', dataInput)
58 tasks.push(p)
59 }
60
61 await Promise.all(tasks)
62 })
63
64 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })
65 } catch (err) {
66 logger.warn('Cannot transcode the video.', err)
67 }
68 } else {
69 logger.info('No transcoding jobs created for video %s (no resolutions enabled).')
70 return undefined
71 }
72 }
73
74 // ---------------------------------------------------------------------------
75
76 export {
77 process,
78 onError,
79 onSuccess
80 }