]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/update.ts
15899307de27407f6f43e559da71747079e216c7
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
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'
23
24 const lTags = loggerTagsFactory('api', 'video')
25 const auditLogger = auditLoggerFactory('videos')
26 const updateRouter = express.Router()
27
28 const reqVideoFileUpdate = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
29
30 updateRouter.put('/:id',
31 openapiOperationDoc({ operationId: 'putVideo' }),
32 authenticate,
33 reqVideoFileUpdate,
34 asyncMiddleware(videosUpdateValidator),
35 asyncRetryTransactionMiddleware(updateVideo)
36 )
37
38 // ---------------------------------------------------------------------------
39
40 export {
41 updateRouter
42 }
43
44 // ---------------------------------------------------------------------------
45
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
51
52 const wasConfidentialVideo = videoFromReq.isConfidential()
53 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
54
55 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
56 video: videoFromReq,
57 files: req.files,
58 fallback: () => Promise.resolve(undefined),
59 automaticallyGenerated: false
60 })
61
62 try {
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)
66
67 const sequelizeOptions = { transaction: t }
68 const oldVideoChannel = video.VideoChannel
69
70 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
71 'name',
72 'category',
73 'licence',
74 'language',
75 'nsfw',
76 'waitTranscoding',
77 'support',
78 'description',
79 'commentsEnabled',
80 'downloadEnabled'
81 ]
82
83 for (const key of keysToUpdate) {
84 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
85 }
86
87 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
88 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
89 }
90
91 // Privacy update?
92 let isNewVideo = false
93 if (videoInfoToUpdate.privacy !== undefined) {
94 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
95 }
96
97 // Force updatedAt attribute change
98 if (!video.changed()) {
99 await video.setAsRefreshed(t)
100 }
101
102 const videoInstanceUpdated = await video.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 auditLogger.update(
133 getAuditIdFromRes(res),
134 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
135 oldVideoAuditView
136 )
137 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
138
139 return { videoInstanceUpdated, isNewVideo }
140 })
141
142 if (videoInstanceUpdated.isLive !== true && videoInfoToUpdate.name) {
143 await updateTorrentsMetadata(videoInstanceUpdated)
144 }
145
146 await sequelizeTypescript.transaction(t => federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t))
147
148 if (wasConfidentialVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
149
150 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
151 } catch (err) {
152 // Force fields we want to update
153 // If the transaction is retried, sequelize will think the object has not changed
154 // So it will skip the SQL request, even if the last one was ROLLBACKed!
155 resetSequelizeInstance(videoFromReq, videoFieldsSave)
156
157 throw err
158 }
159
160 return res.type('json')
161 .status(HttpStatusCode.NO_CONTENT_204)
162 .end()
163 }
164
165 async function updateVideoPrivacy (options: {
166 videoInstance: MVideoFullLight
167 videoInfoToUpdate: VideoUpdate
168 hadPrivacyForFederation: boolean
169 transaction: Transaction
170 }) {
171 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
172 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
173
174 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
175 videoInstance.setPrivacy(newPrivacy)
176
177 // Unfederate the video if the new privacy is not compatible with federation
178 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
179 await VideoModel.sendDelete(videoInstance, { transaction })
180 }
181
182 return isNewVideo
183 }
184
185 function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
186 if (videoInfoToUpdate.scheduleUpdate) {
187 return ScheduleVideoUpdateModel.upsert({
188 videoId: videoInstance.id,
189 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
190 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
191 }, { transaction })
192 } else if (videoInfoToUpdate.scheduleUpdate === null) {
193 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
194 }
195 }
196
197 async function updateTorrentsMetadata (video: MVideoFullLight) {
198 for (const file of (video.VideoFiles || [])) {
199 await updateTorrentMetadata(video, file)
200
201 await file.save()
202 }
203
204 const hls = video.getHLSPlaylist()
205 if (!hls) return
206
207 for (const file of (hls.VideoFiles || [])) {
208 await updateTorrentMetadata(hls, file)
209
210 await file.save()
211 }
212 }