1 import express from 'express'
2 import { Transaction } from 'sequelize/types'
3 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
4 import { CreateJobArgument, JobQueue } from '@server/lib/job-queue'
5 import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
6 import { openapiOperationDoc } from '@server/middlewares/doc'
7 import { FilteredModelAttributes } from '@server/types'
8 import { MVideoFullLight } from '@server/types/models'
9 import { HttpStatusCode, ManageVideoTorrentPayload, 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'
22 const lTags = loggerTagsFactory('api', 'video')
23 const auditLogger = auditLoggerFactory('videos')
24 const updateRouter = express.Router()
26 const reqVideoFileUpdate = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
28 updateRouter.put('/:id',
29 openapiOperationDoc({ operationId: 'putVideo' }),
32 asyncMiddleware(videosUpdateValidator),
33 asyncRetryTransactionMiddleware(updateVideo)
36 // ---------------------------------------------------------------------------
42 // ---------------------------------------------------------------------------
44 async function updateVideo (req: express.Request, res: express.Response) {
45 const videoFromReq = res.locals.videoAll
46 const videoFieldsSave = videoFromReq.toJSON()
47 const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
48 const videoInfoToUpdate: VideoUpdate = req.body
50 const wasConfidentialVideo = videoFromReq.isConfidential()
51 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
53 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
56 fallback: () => Promise.resolve(undefined),
57 automaticallyGenerated: false
61 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
62 // Refresh video since thumbnails to prevent concurrent updates
63 const video = await VideoModel.loadFull(videoFromReq.id, t)
65 const sequelizeOptions = { transaction: t }
66 const oldVideoChannel = video.VideoChannel
68 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
81 for (const key of keysToUpdate) {
82 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
85 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
86 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
90 let isNewVideo = false
91 if (videoInfoToUpdate.privacy !== undefined) {
92 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
95 // Force updatedAt attribute change
96 if (!video.changed()) {
97 await video.setAsRefreshed(t)
100 const videoInstanceUpdated = await video.save(sequelizeOptions) as MVideoFullLight
102 // Thumbnail & preview updates?
103 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
104 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
106 // Video tags update?
107 if (videoInfoToUpdate.tags !== undefined) {
108 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
111 // Video channel update?
112 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
113 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
114 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
116 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
119 // Schedule an update in the future?
120 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
122 await autoBlacklistVideoIfNeeded({
123 video: videoInstanceUpdated,
124 user: res.locals.oauth.token.User,
131 getAuditIdFromRes(res),
132 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
135 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
137 return { videoInstanceUpdated, isNewVideo }
140 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
142 await addVideoJobsAfterUpdate({ video: videoInstanceUpdated, videoInfoToUpdate, wasConfidentialVideo, isNewVideo })
144 // Force fields we want to update
145 // If the transaction is retried, sequelize will think the object has not changed
146 // So it will skip the SQL request, even if the last one was ROLLBACKed!
147 resetSequelizeInstance(videoFromReq, videoFieldsSave)
152 return res.type('json')
153 .status(HttpStatusCode.NO_CONTENT_204)
157 async function updateVideoPrivacy (options: {
158 videoInstance: MVideoFullLight
159 videoInfoToUpdate: VideoUpdate
160 hadPrivacyForFederation: boolean
161 transaction: Transaction
163 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
164 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
166 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
167 videoInstance.setPrivacy(newPrivacy)
169 // Unfederate the video if the new privacy is not compatible with federation
170 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
171 await VideoModel.sendDelete(videoInstance, { transaction })
177 function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
178 if (videoInfoToUpdate.scheduleUpdate) {
179 return ScheduleVideoUpdateModel.upsert({
180 videoId: videoInstance.id,
181 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
182 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
184 } else if (videoInfoToUpdate.scheduleUpdate === null) {
185 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
189 async function addVideoJobsAfterUpdate (options: {
190 video: MVideoFullLight
191 videoInfoToUpdate: VideoUpdate
192 wasConfidentialVideo: boolean
195 const { video, videoInfoToUpdate, wasConfidentialVideo, isNewVideo } = options
196 const jobs: CreateJobArgument[] = []
198 if (!video.isLive && videoInfoToUpdate.name) {
200 for (const file of (video.VideoFiles || [])) {
201 const payload: ManageVideoTorrentPayload = { action: 'update-metadata', videoId: video.id, videoFileId: file.id }
203 jobs.push({ type: 'manage-video-torrent', payload })
206 const hls = video.getHLSPlaylist()
208 for (const file of (hls?.VideoFiles || [])) {
209 const payload: ManageVideoTorrentPayload = { action: 'update-metadata', streamingPlaylistId: hls.id, videoFileId: file.id }
211 jobs.push({ type: 'manage-video-torrent', payload })
216 type: 'federate-video',
218 videoUUID: video.uuid,
223 if (wasConfidentialVideo) {
228 videoUUID: video.uuid
233 return JobQueue.Instance.createSequentialJobFlow(...jobs)