]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/update.ts
Fix CLI build
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
CommitLineData
c158a5fa
C
1import * as express from 'express'
2import { Transaction } from 'sequelize/types'
3import { changeVideoChannelShare } from '@server/lib/activitypub/share'
4import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
5import { FilteredModelAttributes } from '@server/types'
6import { MVideoFullLight } from '@server/types/models'
7import { VideoUpdate } from '../../../../shared'
8import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
9import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
10import { resetSequelizeInstance } from '../../../helpers/database-utils'
11import { createReqFiles } from '../../../helpers/express-utils'
12import { logger, loggerTagsFactory } from '../../../helpers/logger'
13import { CONFIG } from '../../../initializers/config'
14import { MIMETYPES } from '../../../initializers/constants'
15import { sequelizeTypescript } from '../../../initializers/database'
16import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
17import { Notifier } from '../../../lib/notifier'
18import { Hooks } from '../../../lib/plugins/hooks'
19import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
20import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
21import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
22import { VideoModel } from '../../../models/video/video'
e030bfb5 23import { docMiddleware } from '@server/middlewares/doc'
c158a5fa
C
24
25const lTags = loggerTagsFactory('api', 'video')
26const auditLogger = auditLoggerFactory('videos')
27const updateRouter = express.Router()
28
29const 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
38updateRouter.put('/:id',
e030bfb5 39 docMiddleware('https://docs.joinpeertube.org/api-rest-reference.html#operation/putVideo'),
c158a5fa
C
40 authenticate,
41 reqVideoFileUpdate,
42 asyncMiddleware(videosUpdateValidator),
43 asyncRetryTransactionMiddleware(updateVideo)
44)
45
46// ---------------------------------------------------------------------------
47
48export {
49 updateRouter
50}
51
52// ---------------------------------------------------------------------------
53
54export 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
163async 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
183function 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}