]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/update.ts
Process video torrents in order
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
CommitLineData
41fb13c3 1import express from 'express'
c158a5fa
C
2import { Transaction } from 'sequelize/types'
3import { changeVideoChannelShare } from '@server/lib/activitypub/share'
f012319a 4import { JobQueue } from '@server/lib/job-queue'
c158a5fa 5import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
c0e8b12e 6import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa
C
7import { FilteredModelAttributes } from '@server/types'
8import { MVideoFullLight } from '@server/types/models'
f012319a 9import { HttpStatusCode, ManageVideoTorrentPayload, VideoUpdate } from '@shared/models'
c158a5fa
C
10import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
11import { resetSequelizeInstance } from '../../../helpers/database-utils'
12import { createReqFiles } from '../../../helpers/express-utils'
13import { logger, loggerTagsFactory } from '../../../helpers/logger'
c158a5fa
C
14import { MIMETYPES } from '../../../initializers/constants'
15import { sequelizeTypescript } from '../../../initializers/database'
16import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
17import { Notifier } from '../../../lib/notifier'
18import { Hooks } from '../../../lib/plugins/hooks'
19import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
20import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
21import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
22import { VideoModel } from '../../../models/video/video'
23
24const lTags = loggerTagsFactory('api', 'video')
25const auditLogger = auditLoggerFactory('videos')
26const updateRouter = express.Router()
27
d3d3deaa 28const reqVideoFileUpdate = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
c158a5fa
C
29
30updateRouter.put('/:id',
1c627fd8 31 openapiOperationDoc({ operationId: 'putVideo' }),
c158a5fa
C
32 authenticate,
33 reqVideoFileUpdate,
34 asyncMiddleware(videosUpdateValidator),
35 asyncRetryTransactionMiddleware(updateVideo)
36)
37
38// ---------------------------------------------------------------------------
39
40export {
41 updateRouter
42}
43
44// ---------------------------------------------------------------------------
45
b46cf4b9 46async function updateVideo (req: express.Request, res: express.Response) {
a2a81f5a
C
47 const videoFromReq = res.locals.videoAll
48 const videoFieldsSave = videoFromReq.toJSON()
49 const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
c158a5fa
C
50 const videoInfoToUpdate: VideoUpdate = req.body
51
a2a81f5a
C
52 const wasConfidentialVideo = videoFromReq.isConfidential()
53 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
c158a5fa
C
54
55 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
a2a81f5a 56 video: videoFromReq,
c158a5fa
C
57 files: req.files,
58 fallback: () => Promise.resolve(undefined),
59 automaticallyGenerated: false
60 })
61
62 try {
38d69d65 63 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
a2a81f5a
C
64 // Refresh video since thumbnails to prevent concurrent updates
65 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoFromReq.id, t)
66
c158a5fa 67 const sequelizeOptions = { transaction: t }
a2a81f5a 68 const oldVideoChannel = video.VideoChannel
c158a5fa
C
69
70 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
71 'name',
72 'category',
73 'licence',
74 'language',
75 'nsfw',
76 'waitTranscoding',
77 'support',
78 'description',
79 'commentsEnabled',
80 'downloadEnabled'
81 ]
82
83 for (const key of keysToUpdate) {
a2a81f5a 84 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
c158a5fa
C
85 }
86
87 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
a2a81f5a 88 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
c158a5fa
C
89 }
90
91 // Privacy update?
92 let isNewVideo = false
93 if (videoInfoToUpdate.privacy !== undefined) {
a2a81f5a 94 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
c158a5fa
C
95 }
96
5cf027bd 97 // Force updatedAt attribute change
a2a81f5a 98 if (!video.changed()) {
597f771f 99 await video.setAsRefreshed(t)
5cf027bd
C
100 }
101
a2a81f5a 102 const videoInstanceUpdated = await video.save(sequelizeOptions) as MVideoFullLight
c158a5fa
C
103
104 // Thumbnail & preview updates?
105 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
106 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
107
108 // Video tags update?
109 if (videoInfoToUpdate.tags !== undefined) {
110 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
111 }
112
113 // Video channel update?
114 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
115 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
116 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
117
118 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
119 }
120
121 // Schedule an update in the future?
122 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
123
124 await autoBlacklistVideoIfNeeded({
125 video: videoInstanceUpdated,
126 user: res.locals.oauth.token.User,
127 isRemote: false,
128 isNew: false,
129 transaction: t
130 })
131
c158a5fa
C
132 auditLogger.update(
133 getAuditIdFromRes(res),
134 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
135 oldVideoAuditView
136 )
a2a81f5a 137 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
c158a5fa 138
38d69d65 139 return { videoInstanceUpdated, isNewVideo }
c158a5fa
C
140 })
141
f012319a 142 const refreshedVideo = await updateTorrentsMetadataIfNeeded(videoInstanceUpdated, videoInfoToUpdate)
38d69d65 143
f012319a 144 await sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, isNewVideo, t))
38d69d65 145
f012319a 146 if (wasConfidentialVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
c158a5fa 147
f012319a 148 Hooks.runAction('action:api.video.updated', { video: refreshedVideo, body: req.body, req, res })
c158a5fa
C
149 } catch (err) {
150 // Force fields we want to update
151 // If the transaction is retried, sequelize will think the object has not changed
152 // So it will skip the SQL request, even if the last one was ROLLBACKed!
a2a81f5a 153 resetSequelizeInstance(videoFromReq, videoFieldsSave)
c158a5fa
C
154
155 throw err
156 }
157
158 return res.type('json')
159 .status(HttpStatusCode.NO_CONTENT_204)
160 .end()
161}
162
163async function updateVideoPrivacy (options: {
164 videoInstance: MVideoFullLight
165 videoInfoToUpdate: VideoUpdate
166 hadPrivacyForFederation: boolean
167 transaction: Transaction
168}) {
169 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
170 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
171
172 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
173 videoInstance.setPrivacy(newPrivacy)
174
175 // Unfederate the video if the new privacy is not compatible with federation
176 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
177 await VideoModel.sendDelete(videoInstance, { transaction })
178 }
179
180 return isNewVideo
181}
182
183function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
184 if (videoInfoToUpdate.scheduleUpdate) {
185 return ScheduleVideoUpdateModel.upsert({
186 videoId: videoInstance.id,
187 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
188 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
189 }, { transaction })
190 } else if (videoInfoToUpdate.scheduleUpdate === null) {
191 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
192 }
193}
9b293cd6 194
f012319a
C
195async function updateTorrentsMetadataIfNeeded (video: MVideoFullLight, videoInfoToUpdate: VideoUpdate) {
196 if (video.isLive || !videoInfoToUpdate.name) return video
197
6ba93fa6 198 for (const file of (video.VideoFiles || [])) {
f012319a 199 const payload: ManageVideoTorrentPayload = { action: 'update-metadata', videoId: video.id, videoFileId: file.id }
38d69d65 200
f012319a
C
201 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
202 await job.finished()
9b293cd6 203 }
6ba93fa6
C
204
205 const hls = video.getHLSPlaylist()
6ba93fa6 206
f012319a
C
207 for (const file of (hls?.VideoFiles || [])) {
208 const payload: ManageVideoTorrentPayload = { action: 'update-metadata', streamingPlaylistId: hls.id, videoFileId: file.id }
6ba93fa6 209
f012319a
C
210 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
211 await job.finished()
6ba93fa6 212 }
f012319a
C
213
214 // Refresh video since files have changed
215 return VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
9b293cd6 216}