]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/update.ts
Add ability to get user from file token
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / update.ts
1 import express from 'express'
2 import { Transaction } from 'sequelize/types'
3 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
4 import { addVideoJobsAfterUpdate, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
5 import { setVideoPrivacy } from '@server/lib/video-privacy'
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 { Hooks } from '../../../lib/plugins/hooks'
17 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
18 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
19 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
20 import { VideoModel } from '../../../models/video/video'
21 import { VideoPathManager } from '@server/lib/video-path-manager'
22 import { forceNumber } from '@shared/core-utils'
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 hadPrivacyForFederation = videoFromReq.hasPrivacyForFederation()
53 const oldPrivacy = videoFromReq.privacy
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 const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
63
64 try {
65 const { videoInstanceUpdated, isNewVideo } = await sequelizeTypescript.transaction(async t => {
66 // Refresh video since thumbnails to prevent concurrent updates
67 const video = await VideoModel.loadFull(videoFromReq.id, t)
68
69 const oldVideoChannel = video.VideoChannel
70
71 const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
72 'name',
73 'category',
74 'licence',
75 'language',
76 'nsfw',
77 'waitTranscoding',
78 'support',
79 'description',
80 'commentsEnabled',
81 'downloadEnabled'
82 ]
83
84 for (const key of keysToUpdate) {
85 if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
86 }
87
88 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
89 video.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
90 }
91
92 // Privacy update?
93 let isNewVideo = false
94 if (videoInfoToUpdate.privacy !== undefined) {
95 isNewVideo = await updateVideoPrivacy({ videoInstance: video, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
96 }
97
98 // Force updatedAt attribute change
99 if (!video.changed()) {
100 await video.setAsRefreshed(t)
101 }
102
103 const videoInstanceUpdated = await video.save({ transaction: t }) as MVideoFullLight
104
105 // Thumbnail & preview updates?
106 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
107 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
108
109 // Video tags update?
110 if (videoInfoToUpdate.tags !== undefined) {
111 await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
112 }
113
114 // Video channel update?
115 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
116 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
117 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
118
119 if (hadPrivacyForFederation === true) {
120 await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
121 }
122 }
123
124 // Schedule an update in the future?
125 await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
126
127 await autoBlacklistVideoIfNeeded({
128 video: videoInstanceUpdated,
129 user: res.locals.oauth.token.User,
130 isRemote: false,
131 isNew: false,
132 transaction: t
133 })
134
135 auditLogger.update(
136 getAuditIdFromRes(res),
137 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
138 oldVideoAuditView
139 )
140 logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
141
142 return { videoInstanceUpdated, isNewVideo }
143 })
144
145 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
146
147 await addVideoJobsAfterUpdate({
148 video: videoInstanceUpdated,
149 nameChanged: !!videoInfoToUpdate.name,
150 oldPrivacy,
151 isNewVideo
152 })
153 } catch (err) {
154 // Force fields we want to update
155 // If the transaction is retried, sequelize will think the object has not changed
156 // So it will skip the SQL request, even if the last one was ROLLBACKed!
157 resetSequelizeInstance(videoFromReq, videoFieldsSave)
158
159 throw err
160 } finally {
161 videoFileLockReleaser()
162 }
163
164 return res.type('json')
165 .status(HttpStatusCode.NO_CONTENT_204)
166 .end()
167 }
168
169 async function updateVideoPrivacy (options: {
170 videoInstance: MVideoFullLight
171 videoInfoToUpdate: VideoUpdate
172 hadPrivacyForFederation: boolean
173 transaction: Transaction
174 }) {
175 const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
176 const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
177
178 const newPrivacy = forceNumber(videoInfoToUpdate.privacy)
179 setVideoPrivacy(videoInstance, newPrivacy)
180
181 // Unfederate the video if the new privacy is not compatible with federation
182 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
183 await VideoModel.sendDelete(videoInstance, { transaction })
184 }
185
186 return isNewVideo
187 }
188
189 function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
190 if (videoInfoToUpdate.scheduleUpdate) {
191 return ScheduleVideoUpdateModel.upsert({
192 videoId: videoInstance.id,
193 updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
194 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
195 }, { transaction })
196 } else if (videoInfoToUpdate.scheduleUpdate === null) {
197 return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
198 }
199 }