]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/update.ts
Update torrent metadata on video update
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
CommitLineData
41fb13c3 1import express from 'express'
c158a5fa 2import { Transaction } from 'sequelize/types'
9b293cd6 3import { updateTorrentMetadata } from '@server/helpers/webtorrent'
c158a5fa
C
4import { changeVideoChannelShare } from '@server/lib/activitypub/share'
5import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
c0e8b12e 6import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa
C
7import { FilteredModelAttributes } from '@server/types'
8import { MVideoFullLight } from '@server/types/models'
9import { VideoUpdate } from '../../../../shared'
c0e8b12e 10import { HttpStatusCode } from '../../../../shared/models'
c158a5fa
C
11import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
12import { resetSequelizeInstance } from '../../../helpers/database-utils'
13import { createReqFiles } from '../../../helpers/express-utils'
14import { logger, loggerTagsFactory } from '../../../helpers/logger'
15import { CONFIG } from '../../../initializers/config'
16import { MIMETYPES } from '../../../initializers/constants'
17import { sequelizeTypescript } from '../../../initializers/database'
18import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
19import { Notifier } from '../../../lib/notifier'
20import { Hooks } from '../../../lib/plugins/hooks'
21import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
22import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
23import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
24import { VideoModel } from '../../../models/video/video'
25
26const lTags = loggerTagsFactory('api', 'video')
27const auditLogger = auditLoggerFactory('videos')
28const updateRouter = express.Router()
29
30const reqVideoFileUpdate = createReqFiles(
31 [ 'thumbnailfile', 'previewfile' ],
32 MIMETYPES.IMAGE.MIMETYPE_EXT,
33 {
34 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
35 previewfile: CONFIG.STORAGE.TMP_DIR
36 }
37)
38
39updateRouter.put('/:id',
1c627fd8 40 openapiOperationDoc({ operationId: 'putVideo' }),
c158a5fa
C
41 authenticate,
42 reqVideoFileUpdate,
43 asyncMiddleware(videosUpdateValidator),
44 asyncRetryTransactionMiddleware(updateVideo)
45)
46
47// ---------------------------------------------------------------------------
48
49export {
50 updateRouter
51}
52
53// ---------------------------------------------------------------------------
54
b46cf4b9 55async function updateVideo (req: express.Request, res: express.Response) {
a2a81f5a
C
56 const videoFromReq = res.locals.videoAll
57 const videoFieldsSave = videoFromReq.toJSON()
58 const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
c158a5fa
C
59 const videoInfoToUpdate: VideoUpdate = req.body
60
a2a81f5a
C
61 const wasConfidentialVideo = videoFromReq.isConfidential()
62 const hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
c158a5fa
C
63
64 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
a2a81f5a 65 video: videoFromReq,
c158a5fa
C
66 files: req.files,
67 fallback: () => Promise.resolve(undefined),
68 automaticallyGenerated: false
69 })
70
71 try {
72 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
a2a81f5a
C
73 // Refresh video since thumbnails to prevent concurrent updates
74 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoFromReq.id, t)
75
c158a5fa 76 const sequelizeOptions = { transaction: t }
a2a81f5a 77 const oldVideoChannel = video.VideoChannel
c158a5fa
C
78
79 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
80 'name',
81 'category',
82 'licence',
83 'language',
84 'nsfw',
85 'waitTranscoding',
86 'support',
87 'description',
88 'commentsEnabled',
89 'downloadEnabled'
90 ]
91
92 for (const key of keysToUpdate) {
a2a81f5a 93 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
c158a5fa
C
94 }
95
96 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
a2a81f5a 97 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
c158a5fa
C
98 }
99
100 // Privacy update?
101 let isNewVideo = false
102 if (videoInfoToUpdate.privacy !== undefined) {
a2a81f5a 103 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
c158a5fa
C
104 }
105
5cf027bd 106 // Force updatedAt attribute change
a2a81f5a 107 if (!video.changed()) {
597f771f 108 await video.setAsRefreshed(t)
5cf027bd
C
109 }
110
a2a81f5a 111 const videoInstanceUpdated = await video.save(sequelizeOptions) as MVideoFullLight
c158a5fa
C
112
113 // Thumbnail & preview updates?
114 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
115 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
116
117 // Video tags update?
118 if (videoInfoToUpdate.tags !== undefined) {
119 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
120 }
121
122 // Video channel update?
123 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
124 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
125 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
126
127 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
128 }
129
130 // Schedule an update in the future?
131 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
132
133 await autoBlacklistVideoIfNeeded({
134 video: videoInstanceUpdated,
135 user: res.locals.oauth.token.User,
136 isRemote: false,
137 isNew: false,
138 transaction: t
139 })
140
141 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
142
143 auditLogger.update(
144 getAuditIdFromRes(res),
145 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
146 oldVideoAuditView
147 )
a2a81f5a 148 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
c158a5fa
C
149
150 return videoInstanceUpdated
151 })
152
9b293cd6
C
153 if (videoInfoToUpdate.name) await updateTorrentsMetadata(videoInstanceUpdated)
154 if (wasConfidentialVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
c158a5fa 155
7226e90f 156 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
c158a5fa
C
157 } catch (err) {
158 // Force fields we want to update
159 // If the transaction is retried, sequelize will think the object has not changed
160 // So it will skip the SQL request, even if the last one was ROLLBACKed!
a2a81f5a 161 resetSequelizeInstance(videoFromReq, videoFieldsSave)
c158a5fa
C
162
163 throw err
164 }
165
166 return res.type('json')
167 .status(HttpStatusCode.NO_CONTENT_204)
168 .end()
169}
170
171async function updateVideoPrivacy (options: {
172 videoInstance: MVideoFullLight
173 videoInfoToUpdate: VideoUpdate
174 hadPrivacyForFederation: boolean
175 transaction: Transaction
176}) {
177 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
178 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
179
180 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
181 videoInstance.setPrivacy(newPrivacy)
182
183 // Unfederate the video if the new privacy is not compatible with federation
184 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
185 await VideoModel.sendDelete(videoInstance, { transaction })
186 }
187
188 return isNewVideo
189}
190
191function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
192 if (videoInfoToUpdate.scheduleUpdate) {
193 return ScheduleVideoUpdateModel.upsert({
194 videoId: videoInstance.id,
195 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
196 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
197 }, { transaction })
198 } else if (videoInfoToUpdate.scheduleUpdate === null) {
199 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
200 }
201}
9b293cd6
C
202
203async function updateTorrentsMetadata (video: MVideoFullLight) {
204 for (const file of video.getAllFiles()) {
205 await updateTorrentMetadata(video, file)
206 }
207}