]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/update.ts
Merge branch 'release/3.3.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
1 import * as 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 videoInstance = res.locals.videoAll
56 const videoFieldsSave = videoInstance.toJSON()
57 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
58 const videoInfoToUpdate: VideoUpdate = req.body
59
60 const wasConfidentialVideo = videoInstance.isConfidential()
61 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
62
63 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
64 video: videoInstance,
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 const sequelizeOptions = { transaction: t }
73 const oldVideoChannel = videoInstance.VideoChannel
74
75 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
76 'name',
77 'category',
78 'licence',
79 'language',
80 'nsfw',
81 'waitTranscoding',
82 'support',
83 'description',
84 'commentsEnabled',
85 'downloadEnabled'
86 ]
87
88 for (const key of keysToUpdate) {
89 if (videoInfoToUpdate[key] !== undefined) videoInstance.set(key, videoInfoToUpdate[key])
90 }
91
92 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
93 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
94 }
95
96 // Privacy update?
97 let isNewVideo = false
98 if (videoInfoToUpdate.privacy !== undefined) {
99 isNewVideo = await updateVideoPrivacy({ videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
100 }
101
102 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
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
118 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
119 }
120
121 // Schedule an update in the future?
122 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
123
124 await autoBlacklistVideoIfNeeded({
125 video: videoInstanceUpdated,
126 user: res.locals.oauth.token.User,
127 isRemote: false,
128 isNew: false,
129 transaction: t
130 })
131
132 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
133
134 auditLogger.update(
135 getAuditIdFromRes(res),
136 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
137 oldVideoAuditView
138 )
139 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
140
141 return videoInstanceUpdated
142 })
143
144 if (wasConfidentialVideo) {
145 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
146 }
147
148 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
149 } catch (err) {
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(videoInstance, videoFieldsSave)
154
155 throw err
156 }
157
158 return res.type('json')
159 .status(HttpStatusCode.NO_CONTENT_204)
160 .end()
161 }
162
163 async function updateVideoPrivacy (options: {
164 videoInstance: MVideoFullLight
165 videoInfoToUpdate: VideoUpdate
166 hadPrivacyForFederation: boolean
167 transaction: Transaction
168 }) {
169 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
170 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
171
172 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
173 videoInstance.setPrivacy(newPrivacy)
174
175 // Unfederate the video if the new privacy is not compatible with federation
176 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
177 await VideoModel.sendDelete(videoInstance, { transaction })
178 }
179
180 return isNewVideo
181 }
182
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
189 }, { transaction })
190 } else if (videoInfoToUpdate.scheduleUpdate === null) {
191 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
192 }
193 }