1 import express from 'express'
2 import { Transaction } from 'sequelize/types'
3 import { updateTorrentMetadata } from '@server/helpers/webtorrent'
4 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
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, 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 { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
17 import { Notifier } from '../../../lib/notifier'
18 import { Hooks } from '../../../lib/plugins/hooks'
19 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
20 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
21 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
22 import { VideoModel } from '../../../models/video/video'
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 wasConfidentialVideo = videoFromReq.isConfidential()
53 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
55 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
58 fallback: () => Promise.resolve(undefined),
59 automaticallyGenerated: false
63 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
64 // Refresh video since thumbnails to prevent concurrent updates
65 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoFromReq.id, t)
67 const sequelizeOptions = { transaction: t }
68 const oldVideoChannel = video.VideoChannel
70 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
83 for (const key of keysToUpdate) {
84 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
87 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
88 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
92 let isNewVideo = false
93 if (videoInfoToUpdate.privacy !== undefined) {
94 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
97 // Force updatedAt attribute change
98 if (!video.changed()) {
99 await video.setAsRefreshed(t)
102 const videoInstanceUpdated = await video.save(sequelizeOptions) as MVideoFullLight
104 // Thumbnail & preview updates?
105 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
106 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
108 // Video tags update?
109 if (videoInfoToUpdate.tags !== undefined) {
110 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
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
118 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
121 // Schedule an update in the future?
122 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
124 await autoBlacklistVideoIfNeeded({
125 video: videoInstanceUpdated,
126 user: res.locals.oauth.token.User,
133 getAuditIdFromRes(res),
134 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
137 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
139 return { videoInstanceUpdated, isNewVideo }
142 if (videoInfoToUpdate.name) await updateTorrentsMetadata(videoInstanceUpdated)
144 await sequelizeTypescript.transaction(t => federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t))
146 if (wasConfidentialVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
148 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
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!
153 resetSequelizeInstance(videoFromReq, videoFieldsSave)
158 return res.type('json')
159 .status(HttpStatusCode.NO_CONTENT_204)
163 async function updateVideoPrivacy (options: {
164 videoInstance: MVideoFullLight
165 videoInfoToUpdate: VideoUpdate
166 hadPrivacyForFederation: boolean
167 transaction: Transaction
169 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
170 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
172 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
173 videoInstance.setPrivacy(newPrivacy)
175 // Unfederate the video if the new privacy is not compatible with federation
176 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
177 await VideoModel.sendDelete(videoInstance, { transaction })
183 function 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
190 } else if (videoInfoToUpdate.scheduleUpdate === null) {
191 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
195 async function updateTorrentsMetadata (video: MVideoFullLight) {
196 for (const file of (video.VideoFiles || [])) {
197 await updateTorrentMetadata(video, file)
202 const hls = video.getHLSPlaylist()
205 for (const file of (hls.VideoFiles || [])) {
206 await updateTorrentMetadata(hls, file)