1 import express from 'express'
2 import { Transaction } from 'sequelize/types'
3 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
4 import { addVideoJobsAfterUpdate, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
5 import { setVideoPrivacy } from '@server/lib/video-privacy'
6 import { openapiOperationDoc } from '@server/middlewares/doc'
7 import { FilteredModelAttributes } from '@server/types'
8 import { MVideoFullLight } from '@server/types/models'
9 import { HttpStatusCode, VideoUpdate } 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 { MIMETYPES } from '../../../initializers/constants'
15 import { sequelizeTypescript } from '../../../initializers/database'
16 import { Hooks } from '../../../lib/plugins/hooks'
17 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
18 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
19 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
20 import { VideoModel } from '../../../models/video/video'
21 import { VideoPathManager } from '@server/lib/video-path-manager'
22 import { forceNumber } from '@shared/core-utils'
24 const lTags = loggerTagsFactory('api', 'video')
25 const auditLogger = auditLoggerFactory('videos')
26 const updateRouter = express.Router()
28 const reqVideoFileUpdate = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
30 updateRouter.put('/:id',
31 openapiOperationDoc({ operationId: 'putVideo' }),
34 asyncMiddleware(videosUpdateValidator),
35 asyncRetryTransactionMiddleware(updateVideo)
38 // ---------------------------------------------------------------------------
44 // ---------------------------------------------------------------------------
46 async function updateVideo (req: express.Request, res: express.Response) {
47 const videoFromReq = res.locals.videoAll
48 const videoFieldsSave = videoFromReq.toJSON()
49 const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
50 const videoInfoToUpdate: VideoUpdate = req.body
52 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
53 const oldPrivacy = videoFromReq.privacy
55 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
58 fallback: () => Promise.resolve(undefined),
59 automaticallyGenerated: false
62 const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
65 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
66 // Refresh video since thumbnails to prevent concurrent updates
67 const video = await VideoModel.loadFull(videoFromReq.id, t)
69 const oldVideoChannel = video.VideoChannel
71 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
84 for (const key of keysToUpdate) {
85 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
88 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
89 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
93 let isNewVideo = false
94 if (videoInfoToUpdate.privacy !== undefined) {
95 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
98 // Force updatedAt attribute change
99 if (!video.changed()) {
100 await video.setAsRefreshed(t)
103 const videoInstanceUpdated = await video.save({ transaction: t }) as MVideoFullLight
105 // Thumbnail & preview updates?
106 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
107 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
109 // Video tags update?
110 if (videoInfoToUpdate.tags !== undefined) {
111 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
114 // Video channel update?
115 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
116 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
117 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
119 if (hadPrivacyForFederation === true) {
120 await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
124 // Schedule an update in the future?
125 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
127 await autoBlacklistVideoIfNeeded({
128 video: videoInstanceUpdated,
129 user: res.locals.oauth.token.User,
136 getAuditIdFromRes(res),
137 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
140 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
142 return { videoInstanceUpdated, isNewVideo }
145 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
147 await addVideoJobsAfterUpdate({
148 video: videoInstanceUpdated,
149 nameChanged: !!videoInfoToUpdate.name,
154 // Force fields we want to update
155 // If the transaction is retried, sequelize will think the object has not changed
156 // So it will skip the SQL request, even if the last one was ROLLBACKed!
157 resetSequelizeInstance(videoFromReq, videoFieldsSave)
161 videoFileLockReleaser()
164 return res.type('json')
165 .status(HttpStatusCode.NO_CONTENT_204)
169 async function updateVideoPrivacy (options: {
170 videoInstance: MVideoFullLight
171 videoInfoToUpdate: VideoUpdate
172 hadPrivacyForFederation: boolean
173 transaction: Transaction
175 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
176 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
178 const newPrivacy = forceNumber(videoInfoToUpdate.privacy)
179 setVideoPrivacy(videoInstance, newPrivacy)
181 // Unfederate the video if the new privacy is not compatible with federation
182 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
183 await VideoModel.sendDelete(videoInstance, { transaction })
189 function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
190 if (videoInfoToUpdate.scheduleUpdate) {
191 return ScheduleVideoUpdateModel.upsert({
192 videoId: videoInstance.id,
193 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
194 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
196 } else if (videoInfoToUpdate.scheduleUpdate === null) {
197 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)