]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/upload.ts
allow public video privacy to be deleted in the web client
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
CommitLineData
c158a5fa
C
1import * as express from 'express'
2import { move } from 'fs-extra'
3import { extname } from 'path'
4import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
5import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
6import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
7import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
8import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
1c627fd8 9import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa
C
10import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
11import { uploadx } from '@uploadx/core'
12import { VideoCreate, VideoState } from '../../../../shared'
13import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
14import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
15import { retryTransactionWrapper } from '../../../helpers/database-utils'
16import { createReqFiles } from '../../../helpers/express-utils'
17import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
18import { logger, loggerTagsFactory } from '../../../helpers/logger'
19import { CONFIG } from '../../../initializers/config'
20import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
21import { sequelizeTypescript } from '../../../initializers/database'
22import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
23import { Notifier } from '../../../lib/notifier'
24import { Hooks } from '../../../lib/plugins/hooks'
25import { generateVideoMiniature } from '../../../lib/thumbnail'
26import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
27import {
28 asyncMiddleware,
29 asyncRetryTransactionMiddleware,
30 authenticate,
31 videosAddLegacyValidator,
32 videosAddResumableInitValidator,
33 videosAddResumableValidator
34} from '../../../middlewares'
35import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
36import { VideoModel } from '../../../models/video/video'
37import { VideoFileModel } from '../../../models/video/video-file'
38
39const lTags = loggerTagsFactory('api', 'video')
40const auditLogger = auditLoggerFactory('videos')
41const uploadRouter = express.Router()
42const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
43
44const reqVideoFileAdd = createReqFiles(
45 [ 'videofile', 'thumbnailfile', 'previewfile' ],
46 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
47 {
48 videofile: CONFIG.STORAGE.TMP_DIR,
49 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
50 previewfile: CONFIG.STORAGE.TMP_DIR
51 }
52)
53
54const reqVideoFileAddResumable = createReqFiles(
55 [ 'thumbnailfile', 'previewfile' ],
56 MIMETYPES.IMAGE.MIMETYPE_EXT,
57 {
58 thumbnailfile: getResumableUploadPath(),
59 previewfile: getResumableUploadPath()
60 }
61)
62
63uploadRouter.post('/upload',
1c627fd8 64 openapiOperationDoc({ operationId: 'uploadLegacy' }),
c158a5fa
C
65 authenticate,
66 reqVideoFileAdd,
67 asyncMiddleware(videosAddLegacyValidator),
68 asyncRetryTransactionMiddleware(addVideoLegacy)
69)
70
71uploadRouter.post('/upload-resumable',
1c627fd8 72 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
c158a5fa
C
73 authenticate,
74 reqVideoFileAddResumable,
75 asyncMiddleware(videosAddResumableInitValidator),
76 uploadxMiddleware
77)
78
79uploadRouter.delete('/upload-resumable',
80 authenticate,
81 uploadxMiddleware
82)
83
84uploadRouter.put('/upload-resumable',
1c627fd8 85 openapiOperationDoc({ operationId: 'uploadResumable' }),
c158a5fa
C
86 authenticate,
87 uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
88 asyncMiddleware(videosAddResumableValidator),
89 asyncMiddleware(addVideoResumable)
90)
91
92// ---------------------------------------------------------------------------
93
94export {
95 uploadRouter
96}
97
98// ---------------------------------------------------------------------------
99
100export async function addVideoLegacy (req: express.Request, res: express.Response) {
101 // Uploading the video could be long
102 // Set timeout to 10 minutes, as Express's default is 2 minutes
103 req.setTimeout(1000 * 60 * 10, () => {
76148b27
RK
104 logger.error('Video upload has timed out.')
105 return res.fail({
106 status: HttpStatusCode.REQUEST_TIMEOUT_408,
107 message: 'Video upload has timed out.'
108 })
c158a5fa
C
109 })
110
111 const videoPhysicalFile = req.files['videofile'][0]
112 const videoInfo: VideoCreate = req.body
113 const files = req.files
114
115 return addVideo({ res, videoPhysicalFile, videoInfo, files })
116}
117
118export async function addVideoResumable (_req: express.Request, res: express.Response) {
119 const videoPhysicalFile = res.locals.videoFileResumable
120 const videoInfo = videoPhysicalFile.metadata
121 const files = { previewfile: videoInfo.previewfile }
122
123 // Don't need the meta file anymore
124 await deleteResumableUploadMetaFile(videoPhysicalFile.path)
125
126 return addVideo({ res, videoPhysicalFile, videoInfo, files })
127}
128
129async function addVideo (options: {
130 res: express.Response
131 videoPhysicalFile: express.VideoUploadFile
132 videoInfo: VideoCreate
133 files: express.UploadFiles
134}) {
135 const { res, videoPhysicalFile, videoInfo, files } = options
136 const videoChannel = res.locals.videoChannel
137 const user = res.locals.oauth.token.User
138
139 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
140
141 videoData.state = CONFIG.TRANSCODING.ENABLED
142 ? VideoState.TO_TRANSCODE
143 : VideoState.PUBLISHED
144
145 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
146
147 const video = new VideoModel(videoData) as MVideoFullLight
148 video.VideoChannel = videoChannel
149 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
150
151 const videoFile = await buildNewFile(video, videoPhysicalFile)
152
153 // Move physical file
154 const destination = getVideoFilePath(video, videoFile)
155 await move(videoPhysicalFile.path, destination)
156 // This is important in case if there is another attempt in the retry process
157 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
158 videoPhysicalFile.path = destination
159
160 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
161 video,
162 files,
163 fallback: type => generateVideoMiniature({ video, videoFile, type })
164 })
165
166 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
167 const sequelizeOptions = { transaction: t }
168
169 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
170
171 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
172 await videoCreated.addAndSaveThumbnail(previewModel, t)
173
174 // Do not forget to add video channel information to the created video
175 videoCreated.VideoChannel = res.locals.videoChannel
176
177 videoFile.videoId = video.id
178 await videoFile.save(sequelizeOptions)
179
180 video.VideoFiles = [ videoFile ]
181
182 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
183
184 // Schedule an update in the future?
185 if (videoInfo.scheduleUpdate) {
186 await ScheduleVideoUpdateModel.create({
187 videoId: video.id,
188 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
189 privacy: videoInfo.scheduleUpdate.privacy || null
190 }, sequelizeOptions)
191 }
192
193 // Channel has a new content, set as updated
194 await videoCreated.VideoChannel.setAsUpdated(t)
195
196 await autoBlacklistVideoIfNeeded({
197 video,
198 user,
199 isRemote: false,
200 isNew: true,
201 transaction: t
202 })
203
204 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
205 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
206
207 return { videoCreated }
208 })
209
210 createTorrentFederate(video, videoFile)
211
212 if (video.state === VideoState.TO_TRANSCODE) {
213 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
214 }
215
216 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
217
218 return res.json({
219 video: {
220 id: videoCreated.id,
221 uuid: videoCreated.uuid
222 }
223 })
224}
225
226async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) {
227 const videoFile = new VideoFileModel({
228 extname: extname(videoPhysicalFile.filename),
229 size: videoPhysicalFile.size,
230 videoStreamingPlaylistId: null,
231 metadata: await getMetadataFromFile(videoPhysicalFile.path)
232 })
233
234 if (videoFile.isAudio()) {
235 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
236 } else {
237 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
238 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
239 }
240
241 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
242
243 return videoFile
244}
245
246async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
247 await createTorrentAndSetInfoHash(video, fileArg)
248
249 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
250 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
251 // File does not exist anymore, remove the generated torrent
252 if (!refreshedFile) return fileArg.removeTorrent()
253
254 refreshedFile.infoHash = fileArg.infoHash
255 refreshedFile.torrentFilename = fileArg.torrentFilename
256
257 return refreshedFile.save()
258}
259
260function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile): void {
261 // Create the torrent file in async way because it could be long
262 createTorrentAndSetInfoHashAsync(video, videoFile)
263 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
264 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
265 .then(refreshedVideo => {
266 if (!refreshedVideo) return
267
268 // Only federate and notify after the torrent creation
269 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
270
271 return retryTransactionWrapper(() => {
272 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
273 })
274 })
275 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
276}