]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/update.ts
Support studio transcoding in peertube runner
[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'
3545e72c
C
4import { addVideoJobsAfterUpdate, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
5import { setVideoPrivacy } from '@server/lib/video-privacy'
c0e8b12e 6import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa
C
7import { FilteredModelAttributes } from '@server/types'
8import { MVideoFullLight } from '@server/types/models'
3545e72c 9import { HttpStatusCode, 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'
c158a5fa
C
16import { Hooks } from '../../../lib/plugins/hooks'
17import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
18import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
19import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
20import { VideoModel } from '../../../models/video/video'
3545e72c 21import { VideoPathManager } from '@server/lib/video-path-manager'
4638cd71 22import { forceNumber } from '@shared/core-utils'
c158a5fa
C
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 47 const videoFromReq = res.locals.videoAll
a2a81f5a 48 const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
c158a5fa
C
49 const videoInfoToUpdate: VideoUpdate = req.body
50
a2a81f5a 51 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
3545e72c 52 const oldPrivacy = videoFromReq.privacy
c158a5fa
C
53
54 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
a2a81f5a 55 video: videoFromReq,
c158a5fa
C
56 files: req.files,
57 fallback: () => Promise.resolve(undefined),
58 automaticallyGenerated: false
59 })
60
3545e72c
C
61 const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
62
c158a5fa 63 try {
38d69d65 64 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
a2a81f5a 65 // Refresh video since thumbnails to prevent concurrent updates
4fae2b1f 66 const video = await VideoModel.loadFull(videoFromReq.id, t)
a2a81f5a 67
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
3545e72c 102 const videoInstanceUpdated = await video.save({ transaction: t }) 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
3545e72c
C
118 if (hadPrivacyForFederation === true) {
119 await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
120 }
c158a5fa
C
121 }
122
123 // Schedule an update in the future?
124 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
125
126 await autoBlacklistVideoIfNeeded({
127 video: videoInstanceUpdated,
128 user: res.locals.oauth.token.User,
129 isRemote: false,
130 isNew: false,
131 transaction: t
132 })
133
c158a5fa
C
134 auditLogger.update(
135 getAuditIdFromRes(res),
136 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
137 oldVideoAuditView
138 )
a2a81f5a 139 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
c158a5fa 140
38d69d65 141 return { videoInstanceUpdated, isNewVideo }
c158a5fa
C
142 })
143
bd911b54 144 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
38d69d65 145
3545e72c
C
146 await addVideoJobsAfterUpdate({
147 video: videoInstanceUpdated,
148 nameChanged: !!videoInfoToUpdate.name,
149 oldPrivacy,
150 isNewVideo
151 })
c158a5fa 152 } catch (err) {
c158a5fa 153 // If the transaction is retried, sequelize will think the object has not changed
45657746
C
154 // So we need to restore the previous fields
155 resetSequelizeInstance(videoFromReq)
c158a5fa
C
156
157 throw err
3545e72c
C
158 } finally {
159 videoFileLockReleaser()
c158a5fa
C
160 }
161
162 return res.type('json')
163 .status(HttpStatusCode.NO_CONTENT_204)
164 .end()
165}
166
167async function updateVideoPrivacy (options: {
168 videoInstance: MVideoFullLight
169 videoInfoToUpdate: VideoUpdate
170 hadPrivacyForFederation: boolean
171 transaction: Transaction
172}) {
173 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
174 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
175
4638cd71 176 const newPrivacy = forceNumber(videoInfoToUpdate.privacy)
3545e72c 177 setVideoPrivacy(videoInstance, newPrivacy)
c158a5fa
C
178
179 // Unfederate the video if the new privacy is not compatible with federation
180 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
181 await VideoModel.sendDelete(videoInstance, { transaction })
182 }
183
184 return isNewVideo
185}
186
187function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
188 if (videoInfoToUpdate.scheduleUpdate) {
189 return ScheduleVideoUpdateModel.upsert({
190 videoId: videoInstance.id,
191 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
192 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
193 }, { transaction })
194 } else if (videoInfoToUpdate.scheduleUpdate === null) {
195 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
196 }
197}