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