Refactor a little bit controllers

This commit is contained in:
Chocobozzz 2021-05-12 14:51:17 +02:00
parent c00100b607
commit c158a5faab
No known key found for this signature in database
GPG Key ID: 583A612D890159BE
14 changed files with 625 additions and 504 deletions

View File

@ -88,6 +88,7 @@
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-extraneous-class": "off",
"@typescript-eslint/no-use-before-define": "off",
// bugged but useful
"@typescript-eslint/restrict-plus-operands": "off"
},

View File

@ -18,6 +18,7 @@ const configRouter = express.Router()
const auditLogger = auditLoggerFactory('config')
configRouter.get('/about', getAbout)
configRouter.get('/',
asyncMiddleware(getConfig)
)
@ -27,12 +28,14 @@ configRouter.get('/custom',
ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
getCustomConfig
)
configRouter.put('/custom',
authenticate,
ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
customConfigUpdateValidator,
asyncMiddleware(updateCustomConfig)
)
configRouter.delete('/custom',
authenticate,
ensureUserHasRight(UserRight.MANAGE_CONFIGURATION),
@ -67,13 +70,13 @@ function getAbout (req: express.Request, res: express.Response) {
}
}
return res.json(about).end()
return res.json(about)
}
function getCustomConfig (req: express.Request, res: express.Response) {
const data = customConfig()
return res.json(data).end()
return res.json(data)
}
async function deleteCustomConfig (req: express.Request, res: express.Response) {

View File

@ -31,6 +31,7 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat
import { UserModel } from '../../../models/user/user'
import { VideoModel } from '../../../models/video/video'
import { VideoImportModel } from '../../../models/video/video-import'
import { AttributesOnly } from '@shared/core-utils'
const auditLogger = auditLoggerFactory('users')
@ -191,17 +192,23 @@ async function updateMe (req: express.Request, res: express.Response) {
const user = res.locals.oauth.token.user
if (body.password !== undefined) user.password = body.password
if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
if (body.webTorrentEnabled !== undefined) user.webTorrentEnabled = body.webTorrentEnabled
if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
if (body.autoPlayNextVideo !== undefined) user.autoPlayNextVideo = body.autoPlayNextVideo
if (body.autoPlayNextVideoPlaylist !== undefined) user.autoPlayNextVideoPlaylist = body.autoPlayNextVideoPlaylist
if (body.videosHistoryEnabled !== undefined) user.videosHistoryEnabled = body.videosHistoryEnabled
if (body.videoLanguages !== undefined) user.videoLanguages = body.videoLanguages
if (body.theme !== undefined) user.theme = body.theme
if (body.noInstanceConfigWarningModal !== undefined) user.noInstanceConfigWarningModal = body.noInstanceConfigWarningModal
if (body.noWelcomeModal !== undefined) user.noWelcomeModal = body.noWelcomeModal
const keysToUpdate: (keyof UserUpdateMe & keyof AttributesOnly<UserModel>)[] = [
'password',
'nsfwPolicy',
'webTorrentEnabled',
'autoPlayVideo',
'autoPlayNextVideo',
'autoPlayNextVideoPlaylist',
'videosHistoryEnabled',
'videoLanguages',
'theme',
'noInstanceConfigWarningModal',
'noWelcomeModal'
]
for (const key of keysToUpdate) {
if (body[key] !== undefined) user.set(key, body[key])
}
if (body.email !== undefined) {
if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
@ -215,15 +222,15 @@ async function updateMe (req: express.Request, res: express.Response) {
await sequelizeTypescript.transaction(async t => {
await user.save({ transaction: t })
if (body.displayName !== undefined || body.description !== undefined) {
const userAccount = await AccountModel.load(user.Account.id, t)
if (body.displayName === undefined && body.description === undefined) return
if (body.displayName !== undefined) userAccount.name = body.displayName
if (body.description !== undefined) userAccount.description = body.description
await userAccount.save({ transaction: t })
const userAccount = await AccountModel.load(user.Account.id, t)
await sendUpdateActor(userAccount, t)
}
if (body.displayName !== undefined) userAccount.name = body.displayName
if (body.description !== undefined) userAccount.description = body.description
await userAccount.save({ transaction: t })
await sendUpdateActor(userAccount, t)
})
if (sendVerificationEmail === true) {

View File

@ -162,6 +162,7 @@ async function updateVideoChannelBanner (req: express.Request, res: express.Resp
return res.json({ banner: banner.toFormattedJSON() })
}
async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
const avatarPhysicalFile = req.files['avatarfile'][0]
const videoChannel = res.locals.videoChannel
@ -221,10 +222,6 @@ async function updateVideoChannel (req: express.Request, res: express.Response)
try {
await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = {
transaction: t
}
if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
@ -238,7 +235,7 @@ async function updateVideoChannel (req: express.Request, res: express.Response)
}
}
const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelBannerAccountDefault
const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
await sendUpdateActor(videoChannelInstanceUpdated, t)
auditLogger.update(

View File

@ -202,7 +202,7 @@ async function addVideoPlaylist (req: express.Request, res: express.Response) {
id: videoPlaylistCreated.id,
uuid: videoPlaylistCreated.uuid
}
}).end()
})
}
async function updateVideoPlaylist (req: express.Request, res: express.Response) {

View File

@ -83,32 +83,15 @@ async function addTorrentImport (req: express.Request, res: express.Response, to
let magnetUri: string
if (torrentfile) {
torrentName = torrentfile.originalname
const result = await processTorrentOrAbortRequest(req, res, torrentfile)
if (!result) return
// Rename the torrent to a secured name
const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
await move(torrentfile.path, newTorrentPath, { overwrite: true })
torrentfile.path = newTorrentPath
const buf = await readFile(torrentfile.path)
const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance
if (parsedTorrent.files.length !== 1) {
cleanUpReqFiles(req)
return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({
code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
error: 'Torrents with only 1 file are supported.'
})
}
videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name
videoName = result.name
torrentName = result.torrentName
} else {
magnetUri = body.magnetUri
const parsed = magnetUtil.decode(magnetUri)
videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
const result = processMagnetURI(body)
magnetUri = result.magnetUri
videoName = result.name
}
const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
@ -116,26 +99,26 @@ async function addTorrentImport (req: express.Request, res: express.Response, to
const thumbnailModel = await processThumbnail(req, video)
const previewModel = await processPreview(req, video)
const tags = body.tags || undefined
const videoImportAttributes = {
magnetUri,
torrentName,
state: VideoImportState.PENDING,
userId: user.id
}
const videoImport = await insertIntoDB({
video,
thumbnailModel,
previewModel,
videoChannel: res.locals.videoChannel,
tags,
videoImportAttributes,
user
tags: body.tags || undefined,
user,
videoImportAttributes: {
magnetUri,
torrentName,
state: VideoImportState.PENDING,
userId: user.id
}
})
// Create job to import the video
const payload = {
type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
type: torrentfile
? 'torrent-file' as 'torrent-file'
: 'magnet-uri' as 'magnet-uri',
videoImportId: videoImport.id,
magnetUri
}
@ -184,45 +167,22 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response)
previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
}
const tags = body.tags || youtubeDLInfo.tags
const videoImportAttributes = {
targetUrl,
state: VideoImportState.PENDING,
userId: user.id
}
const videoImport = await insertIntoDB({
video,
thumbnailModel,
previewModel,
videoChannel: res.locals.videoChannel,
tags,
videoImportAttributes,
user
tags: body.tags || youtubeDLInfo.tags,
user,
videoImportAttributes: {
targetUrl,
state: VideoImportState.PENDING,
userId: user.id
}
})
// Get video subtitles
try {
const subtitles = await youtubeDL.getYoutubeDLSubs()
logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
for (const subtitle of subtitles) {
const videoCaption = new VideoCaptionModel({
videoId: video.id,
language: subtitle.language,
filename: VideoCaptionModel.generateCaptionName(subtitle.language)
}) as MVideoCaption
// Move physical file
await moveAndProcessCaptionFile(subtitle, videoCaption)
await sequelizeTypescript.transaction(async t => {
await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
})
}
} catch (err) {
logger.warn('Cannot get video subtitles.', { err })
}
await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
// Create job to import the video
const payload = {
@ -358,3 +318,71 @@ async function insertIntoDB (parameters: {
return videoImport
}
async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
const torrentName = torrentfile.originalname
// Rename the torrent to a secured name
const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
await move(torrentfile.path, newTorrentPath, { overwrite: true })
torrentfile.path = newTorrentPath
const buf = await readFile(torrentfile.path)
const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance
if (parsedTorrent.files.length !== 1) {
cleanUpReqFiles(req)
res.status(HttpStatusCode.BAD_REQUEST_400)
.json({
code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
error: 'Torrents with only 1 file are supported.'
})
return undefined
}
return {
name: extractNameFromArray(parsedTorrent.name),
torrentName
}
}
function processMagnetURI (body: VideoImportCreate) {
const magnetUri = body.magnetUri
const parsed = magnetUtil.decode(magnetUri)
return {
name: extractNameFromArray(parsed.name),
magnetUri
}
}
function extractNameFromArray (name: string | string[]) {
return isArray(name) ? name[0] : name
}
async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) {
try {
const subtitles = await youtubeDL.getYoutubeDLSubs()
logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
for (const subtitle of subtitles) {
const videoCaption = new VideoCaptionModel({
videoId,
language: subtitle.language,
filename: VideoCaptionModel.generateCaptionName(subtitle.language)
}) as MVideoCaption
// Move physical file
await moveAndProcessCaptionFile(subtitle, videoCaption)
await sequelizeTypescript.transaction(async t => {
await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
})
}
} catch (err) {
logger.warn('Cannot get video subtitles.', { err })
}
}

View File

@ -1,43 +1,20 @@
import * as express from 'express'
import { move } from 'fs-extra'
import { extname } from 'path'
import toInt from 'validator/lib/toInt'
import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
import { changeVideoChannelShare } from '@server/lib/activitypub/share'
import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
import { LiveManager } from '@server/lib/live-manager'
import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
import { getServerActor } from '@server/models/application/application'
import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
import { uploadx } from '@uploadx/core'
import { VideoCreate, VideosCommonQuery, VideoState, VideoUpdate } from '../../../../shared'
import { VideosCommonQuery } from '../../../../shared'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils'
import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
import { logger, loggerTagsFactory } from '../../../helpers/logger'
import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
import { logger } from '../../../helpers/logger'
import { getFormattedObjects } from '../../../helpers/utils'
import { CONFIG } from '../../../initializers/config'
import {
DEFAULT_AUDIO_RESOLUTION,
MIMETYPES,
VIDEO_CATEGORIES,
VIDEO_LANGUAGES,
VIDEO_LICENCES,
VIDEO_PRIVACIES
} from '../../../initializers/constants'
import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
import { sequelizeTypescript } from '../../../initializers/database'
import { sendView } from '../../../lib/activitypub/send/send-view'
import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
import { JobQueue } from '../../../lib/job-queue'
import { Notifier } from '../../../lib/notifier'
import { Hooks } from '../../../lib/plugins/hooks'
import { Redis } from '../../../lib/redis'
import { generateVideoMiniature } from '../../../lib/thumbnail'
import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
@ -49,16 +26,11 @@ import {
setDefaultPagination,
setDefaultVideosSort,
videoFileMetadataGetValidator,
videosAddLegacyValidator,
videosAddResumableInitValidator,
videosAddResumableValidator,
videosCustomGetValidator,
videosGetValidator,
videosRemoveValidator,
videosSortValidator,
videosUpdateValidator
videosSortValidator
} from '../../../middlewares'
import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
import { VideoModel } from '../../../models/video/video'
import { VideoFileModel } from '../../../models/video/video-file'
import { blacklistRouter } from './blacklist'
@ -68,40 +40,12 @@ import { videoImportsRouter } from './import'
import { liveRouter } from './live'
import { ownershipVideoRouter } from './ownership'
import { rateVideoRouter } from './rate'
import { updateRouter } from './update'
import { uploadRouter } from './upload'
import { watchingRouter } from './watching'
const lTags = loggerTagsFactory('api', 'video')
const auditLogger = auditLoggerFactory('videos')
const videosRouter = express.Router()
const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
const reqVideoFileAdd = createReqFiles(
[ 'videofile', 'thumbnailfile', 'previewfile' ],
Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
{
videofile: CONFIG.STORAGE.TMP_DIR,
thumbnailfile: CONFIG.STORAGE.TMP_DIR,
previewfile: CONFIG.STORAGE.TMP_DIR
}
)
const reqVideoFileAddResumable = createReqFiles(
[ 'thumbnailfile', 'previewfile' ],
MIMETYPES.IMAGE.MIMETYPE_EXT,
{
thumbnailfile: getResumableUploadPath(),
previewfile: getResumableUploadPath()
}
)
const reqVideoFileUpdate = createReqFiles(
[ 'thumbnailfile', 'previewfile' ],
MIMETYPES.IMAGE.MIMETYPE_EXT,
{
thumbnailfile: CONFIG.STORAGE.TMP_DIR,
previewfile: CONFIG.STORAGE.TMP_DIR
}
)
videosRouter.use('/', blacklistRouter)
videosRouter.use('/', rateVideoRouter)
@ -111,6 +55,8 @@ videosRouter.use('/', videoImportsRouter)
videosRouter.use('/', ownershipVideoRouter)
videosRouter.use('/', watchingRouter)
videosRouter.use('/', liveRouter)
videosRouter.use('/', uploadRouter)
videosRouter.use('/', updateRouter)
videosRouter.get('/categories', listVideoCategories)
videosRouter.get('/licences', listVideoLicences)
@ -127,39 +73,6 @@ videosRouter.get('/',
asyncMiddleware(listVideos)
)
videosRouter.post('/upload',
authenticate,
reqVideoFileAdd,
asyncMiddleware(videosAddLegacyValidator),
asyncRetryTransactionMiddleware(addVideoLegacy)
)
videosRouter.post('/upload-resumable',
authenticate,
reqVideoFileAddResumable,
asyncMiddleware(videosAddResumableInitValidator),
uploadxMiddleware
)
videosRouter.delete('/upload-resumable',
authenticate,
uploadxMiddleware
)
videosRouter.put('/upload-resumable',
authenticate,
uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
asyncMiddleware(videosAddResumableValidator),
asyncMiddleware(addVideoResumable)
)
videosRouter.put('/:id',
authenticate,
reqVideoFileUpdate,
asyncMiddleware(videosUpdateValidator),
asyncRetryTransactionMiddleware(updateVideo)
)
videosRouter.get('/:id/description',
asyncMiddleware(videosGetValidator),
asyncMiddleware(getVideoDescription)
@ -209,279 +122,7 @@ function listVideoPrivacies (_req: express.Request, res: express.Response) {
res.json(VIDEO_PRIVACIES)
}
async function addVideoLegacy (req: express.Request, res: express.Response) {
// Uploading the video could be long
// Set timeout to 10 minutes, as Express's default is 2 minutes
req.setTimeout(1000 * 60 * 10, () => {
logger.error('Upload video has timed out.')
return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
})
const videoPhysicalFile = req.files['videofile'][0]
const videoInfo: VideoCreate = req.body
const files = req.files
return addVideo({ res, videoPhysicalFile, videoInfo, files })
}
async function addVideoResumable (_req: express.Request, res: express.Response) {
const videoPhysicalFile = res.locals.videoFileResumable
const videoInfo = videoPhysicalFile.metadata
const files = { previewfile: videoInfo.previewfile }
// Don't need the meta file anymore
await deleteResumableUploadMetaFile(videoPhysicalFile.path)
return addVideo({ res, videoPhysicalFile, videoInfo, files })
}
async function addVideo (options: {
res: express.Response
videoPhysicalFile: express.VideoUploadFile
videoInfo: VideoCreate
files: express.UploadFiles
}) {
const { res, videoPhysicalFile, videoInfo, files } = options
const videoChannel = res.locals.videoChannel
const user = res.locals.oauth.token.User
const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
videoData.state = CONFIG.TRANSCODING.ENABLED
? VideoState.TO_TRANSCODE
: VideoState.PUBLISHED
videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
const video = new VideoModel(videoData) as MVideoFullLight
video.VideoChannel = videoChannel
video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
const videoFile = new VideoFileModel({
extname: extname(videoPhysicalFile.filename),
size: videoPhysicalFile.size,
videoStreamingPlaylistId: null,
metadata: await getMetadataFromFile(videoPhysicalFile.path)
})
if (videoFile.isAudio()) {
videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
} else {
videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
}
videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
// Move physical file
const destination = getVideoFilePath(video, videoFile)
await move(videoPhysicalFile.path, destination)
// This is important in case if there is another attempt in the retry process
videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
videoPhysicalFile.path = destination
const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
video,
files,
fallback: type => generateVideoMiniature({ video, videoFile, type })
})
const { videoCreated } = await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = { transaction: t }
const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
await videoCreated.addAndSaveThumbnail(previewModel, t)
// Do not forget to add video channel information to the created video
videoCreated.VideoChannel = res.locals.videoChannel
videoFile.videoId = video.id
await videoFile.save(sequelizeOptions)
video.VideoFiles = [ videoFile ]
await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
// Schedule an update in the future?
if (videoInfo.scheduleUpdate) {
await ScheduleVideoUpdateModel.create({
videoId: video.id,
updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
privacy: videoInfo.scheduleUpdate.privacy || null
}, { transaction: t })
}
// Channel has a new content, set as updated
await videoCreated.VideoChannel.setAsUpdated(t)
await autoBlacklistVideoIfNeeded({
video,
user,
isRemote: false,
isNew: true,
transaction: t
})
auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
return { videoCreated }
})
// Create the torrent file in async way because it could be long
createTorrentAndSetInfoHashAsync(video, videoFile)
.catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
.then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
.then(refreshedVideo => {
if (!refreshedVideo) return
// Only federate and notify after the torrent creation
Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
return retryTransactionWrapper(() => {
return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
})
})
.catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
if (video.state === VideoState.TO_TRANSCODE) {
await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
}
Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
return res.json({
video: {
id: videoCreated.id,
uuid: videoCreated.uuid
}
})
}
async function updateVideo (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
const videoFieldsSave = videoInstance.toJSON()
const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
const videoInfoToUpdate: VideoUpdate = req.body
const wasConfidentialVideo = videoInstance.isConfidential()
const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
video: videoInstance,
files: req.files,
fallback: () => Promise.resolve(undefined),
automaticallyGenerated: false
})
try {
const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = { transaction: t }
const oldVideoChannel = videoInstance.VideoChannel
if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
}
let isNewVideo = false
if (videoInfoToUpdate.privacy !== undefined) {
isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
videoInstance.setPrivacy(newPrivacy)
// Unfederate the video if the new privacy is not compatible with federation
if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
await VideoModel.sendDelete(videoInstance, { transaction: t })
}
}
const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
// Video tags update?
if (videoInfoToUpdate.tags !== undefined) {
await setVideoTags({
video: videoInstanceUpdated,
tags: videoInfoToUpdate.tags,
transaction: t
})
}
// Video channel update?
if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
videoInstanceUpdated.VideoChannel = res.locals.videoChannel
if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
}
// Schedule an update in the future?
if (videoInfoToUpdate.scheduleUpdate) {
await ScheduleVideoUpdateModel.upsert({
videoId: videoInstanceUpdated.id,
updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
}, { transaction: t })
} else if (videoInfoToUpdate.scheduleUpdate === null) {
await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
}
await autoBlacklistVideoIfNeeded({
video: videoInstanceUpdated,
user: res.locals.oauth.token.User,
isRemote: false,
isNew: false,
transaction: t
})
await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
auditLogger.update(
getAuditIdFromRes(res),
new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
oldVideoAuditView
)
logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
return videoInstanceUpdated
})
if (wasConfidentialVideo) {
Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
}
Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
} catch (err) {
// Force fields we want to update
// If the transaction is retried, sequelize will think the object has not changed
// So it will skip the SQL request, even if the last one was ROLLBACKed!
resetSequelizeInstance(videoInstance, videoFieldsSave)
throw err
}
return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
async function getVideo (req: express.Request, res: express.Response) {
async function getVideo (_req: express.Request, res: express.Response) {
// We need more attributes
const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
@ -543,13 +184,10 @@ async function viewVideo (req: express.Request, res: express.Response) {
async function getVideoDescription (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
let description = ''
if (videoInstance.isOwned()) {
description = videoInstance.description
} else {
description = await fetchRemoteVideoDescription(videoInstance)
}
const description = videoInstance.isOwned()
? videoInstance.description
: await fetchRemoteVideoDescription(videoInstance)
return res.json({ description })
}
@ -591,7 +229,7 @@ async function listVideos (req: express.Request, res: express.Response) {
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
async function removeVideo (req: express.Request, res: express.Response) {
async function removeVideo (_req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
await sequelizeTypescript.transaction(async t => {
@ -607,17 +245,3 @@ async function removeVideo (req: express.Request, res: express.Response) {
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
await createTorrentAndSetInfoHash(video, fileArg)
// Refresh videoFile because the createTorrentAndSetInfoHash could be long
const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
// File does not exist anymore, remove the generated torrent
if (!refreshedFile) return fileArg.removeTorrent()
refreshedFile.infoHash = fileArg.infoHash
refreshedFile.torrentFilename = fileArg.torrentFilename
return refreshedFile.save()
}

View File

@ -99,7 +99,7 @@ async function listVideoOwnership (req: express.Request, res: express.Response)
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
async function acceptOwnership (req: express.Request, res: express.Response) {
function acceptOwnership (req: express.Request, res: express.Response) {
return sequelizeTypescript.transaction(async t => {
const videoChangeOwnership = res.locals.videoChangeOwnership
const channel = res.locals.videoChannel
@ -126,7 +126,7 @@ async function acceptOwnership (req: express.Request, res: express.Response) {
})
}
async function refuseOwnership (req: express.Request, res: express.Response) {
function refuseOwnership (req: express.Request, res: express.Response) {
return sequelizeTypescript.transaction(async t => {
const videoChangeOwnership = res.locals.videoChangeOwnership

View File

@ -0,0 +1,191 @@
import * as express from 'express'
import { Transaction } from 'sequelize/types'
import { changeVideoChannelShare } from '@server/lib/activitypub/share'
import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
import { FilteredModelAttributes } from '@server/types'
import { MVideoFullLight } from '@server/types/models'
import { VideoUpdate } from '../../../../shared'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
import { resetSequelizeInstance } from '../../../helpers/database-utils'
import { createReqFiles } from '../../../helpers/express-utils'
import { logger, loggerTagsFactory } from '../../../helpers/logger'
import { CONFIG } from '../../../initializers/config'
import { MIMETYPES } from '../../../initializers/constants'
import { sequelizeTypescript } from '../../../initializers/database'
import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
import { Notifier } from '../../../lib/notifier'
import { Hooks } from '../../../lib/plugins/hooks'
import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares'
import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
import { VideoModel } from '../../../models/video/video'
const lTags = loggerTagsFactory('api', 'video')
const auditLogger = auditLoggerFactory('videos')
const updateRouter = express.Router()
const reqVideoFileUpdate = createReqFiles(
[ 'thumbnailfile', 'previewfile' ],
MIMETYPES.IMAGE.MIMETYPE_EXT,
{
thumbnailfile: CONFIG.STORAGE.TMP_DIR,
previewfile: CONFIG.STORAGE.TMP_DIR
}
)
updateRouter.put('/:id',
authenticate,
reqVideoFileUpdate,
asyncMiddleware(videosUpdateValidator),
asyncRetryTransactionMiddleware(updateVideo)
)
// ---------------------------------------------------------------------------
export {
updateRouter
}
// ---------------------------------------------------------------------------
export async function updateVideo (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
const videoFieldsSave = videoInstance.toJSON()
const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
const videoInfoToUpdate: VideoUpdate = req.body
const wasConfidentialVideo = videoInstance.isConfidential()
const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
video: videoInstance,
files: req.files,
fallback: () => Promise.resolve(undefined),
automaticallyGenerated: false
})
try {
const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = { transaction: t }
const oldVideoChannel = videoInstance.VideoChannel
const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
'name',
'category',
'licence',
'language',
'nsfw',
'waitTranscoding',
'support',
'description',
'commentsEnabled',
'downloadEnabled'
]
for (const key of keysToUpdate) {
if (videoInfoToUpdate[key] !== undefined) videoInstance.set(key, videoInfoToUpdate[key])
}
if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
}
// Privacy update?
let isNewVideo = false
if (videoInfoToUpdate.privacy !== undefined) {
isNewVideo = await updateVideoPrivacy({ videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction: t })
}
const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
// Thumbnail & preview updates?
if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
// Video tags update?
if (videoInfoToUpdate.tags !== undefined) {
await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
}
// Video channel update?
if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
videoInstanceUpdated.VideoChannel = res.locals.videoChannel
if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
}
// Schedule an update in the future?
await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
await autoBlacklistVideoIfNeeded({
video: videoInstanceUpdated,
user: res.locals.oauth.token.User,
isRemote: false,
isNew: false,
transaction: t
})
await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
auditLogger.update(
getAuditIdFromRes(res),
new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
oldVideoAuditView
)
logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
return videoInstanceUpdated
})
if (wasConfidentialVideo) {
Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
}
Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
} catch (err) {
// Force fields we want to update
// If the transaction is retried, sequelize will think the object has not changed
// So it will skip the SQL request, even if the last one was ROLLBACKed!
resetSequelizeInstance(videoInstance, videoFieldsSave)
throw err
}
return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
async function updateVideoPrivacy (options: {
videoInstance: MVideoFullLight
videoInfoToUpdate: VideoUpdate
hadPrivacyForFederation: boolean
transaction: Transaction
}) {
const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
videoInstance.setPrivacy(newPrivacy)
// Unfederate the video if the new privacy is not compatible with federation
if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
await VideoModel.sendDelete(videoInstance, { transaction })
}
return isNewVideo
}
function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
if (videoInfoToUpdate.scheduleUpdate) {
return ScheduleVideoUpdateModel.upsert({
videoId: videoInstance.id,
updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
}, { transaction })
} else if (videoInfoToUpdate.scheduleUpdate === null) {
return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
}
}

View File

@ -0,0 +1,269 @@
import * as express from 'express'
import { move } from 'fs-extra'
import { extname } from 'path'
import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
import { uploadx } from '@uploadx/core'
import { VideoCreate, VideoState } from '../../../../shared'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
import { retryTransactionWrapper } from '../../../helpers/database-utils'
import { createReqFiles } from '../../../helpers/express-utils'
import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
import { logger, loggerTagsFactory } from '../../../helpers/logger'
import { CONFIG } from '../../../initializers/config'
import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
import { sequelizeTypescript } from '../../../initializers/database'
import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
import { Notifier } from '../../../lib/notifier'
import { Hooks } from '../../../lib/plugins/hooks'
import { generateVideoMiniature } from '../../../lib/thumbnail'
import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
videosAddLegacyValidator,
videosAddResumableInitValidator,
videosAddResumableValidator
} from '../../../middlewares'
import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
import { VideoModel } from '../../../models/video/video'
import { VideoFileModel } from '../../../models/video/video-file'
const lTags = loggerTagsFactory('api', 'video')
const auditLogger = auditLoggerFactory('videos')
const uploadRouter = express.Router()
const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
const reqVideoFileAdd = createReqFiles(
[ 'videofile', 'thumbnailfile', 'previewfile' ],
Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
{
videofile: CONFIG.STORAGE.TMP_DIR,
thumbnailfile: CONFIG.STORAGE.TMP_DIR,
previewfile: CONFIG.STORAGE.TMP_DIR
}
)
const reqVideoFileAddResumable = createReqFiles(
[ 'thumbnailfile', 'previewfile' ],
MIMETYPES.IMAGE.MIMETYPE_EXT,
{
thumbnailfile: getResumableUploadPath(),
previewfile: getResumableUploadPath()
}
)
uploadRouter.post('/upload',
authenticate,
reqVideoFileAdd,
asyncMiddleware(videosAddLegacyValidator),
asyncRetryTransactionMiddleware(addVideoLegacy)
)
uploadRouter.post('/upload-resumable',
authenticate,
reqVideoFileAddResumable,
asyncMiddleware(videosAddResumableInitValidator),
uploadxMiddleware
)
uploadRouter.delete('/upload-resumable',
authenticate,
uploadxMiddleware
)
uploadRouter.put('/upload-resumable',
authenticate,
uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
asyncMiddleware(videosAddResumableValidator),
asyncMiddleware(addVideoResumable)
)
// ---------------------------------------------------------------------------
export {
uploadRouter
}
// ---------------------------------------------------------------------------
export async function addVideoLegacy (req: express.Request, res: express.Response) {
// Uploading the video could be long
// Set timeout to 10 minutes, as Express's default is 2 minutes
req.setTimeout(1000 * 60 * 10, () => {
logger.error('Upload video has timed out.')
return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
})
const videoPhysicalFile = req.files['videofile'][0]
const videoInfo: VideoCreate = req.body
const files = req.files
return addVideo({ res, videoPhysicalFile, videoInfo, files })
}
export async function addVideoResumable (_req: express.Request, res: express.Response) {
const videoPhysicalFile = res.locals.videoFileResumable
const videoInfo = videoPhysicalFile.metadata
const files = { previewfile: videoInfo.previewfile }
// Don't need the meta file anymore
await deleteResumableUploadMetaFile(videoPhysicalFile.path)
return addVideo({ res, videoPhysicalFile, videoInfo, files })
}
async function addVideo (options: {
res: express.Response
videoPhysicalFile: express.VideoUploadFile
videoInfo: VideoCreate
files: express.UploadFiles
}) {
const { res, videoPhysicalFile, videoInfo, files } = options
const videoChannel = res.locals.videoChannel
const user = res.locals.oauth.token.User
const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
videoData.state = CONFIG.TRANSCODING.ENABLED
? VideoState.TO_TRANSCODE
: VideoState.PUBLISHED
videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
const video = new VideoModel(videoData) as MVideoFullLight
video.VideoChannel = videoChannel
video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
const videoFile = await buildNewFile(video, videoPhysicalFile)
// Move physical file
const destination = getVideoFilePath(video, videoFile)
await move(videoPhysicalFile.path, destination)
// This is important in case if there is another attempt in the retry process
videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
videoPhysicalFile.path = destination
const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
video,
files,
fallback: type => generateVideoMiniature({ video, videoFile, type })
})
const { videoCreated } = await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = { transaction: t }
const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
await videoCreated.addAndSaveThumbnail(previewModel, t)
// Do not forget to add video channel information to the created video
videoCreated.VideoChannel = res.locals.videoChannel
videoFile.videoId = video.id
await videoFile.save(sequelizeOptions)
video.VideoFiles = [ videoFile ]
await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
// Schedule an update in the future?
if (videoInfo.scheduleUpdate) {
await ScheduleVideoUpdateModel.create({
videoId: video.id,
updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
privacy: videoInfo.scheduleUpdate.privacy || null
}, sequelizeOptions)
}
// Channel has a new content, set as updated
await videoCreated.VideoChannel.setAsUpdated(t)
await autoBlacklistVideoIfNeeded({
video,
user,
isRemote: false,
isNew: true,
transaction: t
})
auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
return { videoCreated }
})
createTorrentFederate(video, videoFile)
if (video.state === VideoState.TO_TRANSCODE) {
await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
}
Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
return res.json({
video: {
id: videoCreated.id,
uuid: videoCreated.uuid
}
})
}
async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) {
const videoFile = new VideoFileModel({
extname: extname(videoPhysicalFile.filename),
size: videoPhysicalFile.size,
videoStreamingPlaylistId: null,
metadata: await getMetadataFromFile(videoPhysicalFile.path)
})
if (videoFile.isAudio()) {
videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
} else {
videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
}
videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
return videoFile
}
async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
await createTorrentAndSetInfoHash(video, fileArg)
// Refresh videoFile because the createTorrentAndSetInfoHash could be long
const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
// File does not exist anymore, remove the generated torrent
if (!refreshedFile) return fileArg.removeTorrent()
refreshedFile.infoHash = fileArg.infoHash
refreshedFile.torrentFilename = fileArg.torrentFilename
return refreshedFile.save()
}
function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile): void {
// Create the torrent file in async way because it could be long
createTorrentAndSetInfoHashAsync(video, videoFile)
.catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
.then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
.then(refreshedVideo => {
if (!refreshedVideo) return
// Only federate and notify after the torrent creation
Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
return retryTransactionWrapper(() => {
return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
})
})
.catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
}

View File

@ -78,17 +78,18 @@ function buildOEmbed (options: {
const maxWidth = parseInt(req.query.maxwidth, 10)
const embedUrl = webserverUrl + embedPath
let embedWidth = EMBED_SIZE.width
let embedHeight = EMBED_SIZE.height
const embedTitle = escapeHTML(title)
let thumbnailUrl = previewPath
? webserverUrl + previewPath
: undefined
if (maxHeight < embedHeight) embedHeight = maxHeight
let embedWidth = EMBED_SIZE.width
if (maxWidth < embedWidth) embedWidth = maxWidth
let embedHeight = EMBED_SIZE.height
if (maxHeight < embedHeight) embedHeight = maxHeight
// Our thumbnail is too big for the consumer
if (
(maxHeight !== undefined && maxHeight < previewSize.height) ||

View File

@ -14,7 +14,7 @@ function isSafePath (p: string) {
})
}
function isArray (value: any) {
function isArray (value: any): value is any[] {
return Array.isArray(value)
}

View File

@ -1,13 +1,13 @@
import * as express from 'express'
import * as multer from 'multer'
import { extname } from 'path'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
import { CONFIG } from '../initializers/config'
import { REMOTE_SCHEME } from '../initializers/constants'
import { isArray } from './custom-validators/misc'
import { logger } from './logger'
import { deleteFileAndCatch, generateRandomString } from './utils'
import { extname } from 'path'
import { isArray } from './custom-validators/misc'
import { CONFIG } from '../initializers/config'
import { getExtFromMimetype } from './video'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
function buildNSFWFilter (res?: express.Response, paramNSFW?: string) {
if (paramNSFW === 'true') return true
@ -30,21 +30,21 @@ function buildNSFWFilter (res?: express.Response, paramNSFW?: string) {
return null
}
function cleanUpReqFiles (req: { files: { [fieldname: string]: Express.Multer.File[] } | Express.Multer.File[] }) {
const files = req.files
function cleanUpReqFiles (
req: { files: { [fieldname: string]: Express.Multer.File[] } | Express.Multer.File[] }
) {
const filesObject = req.files
if (!filesObject) return
if (!files) return
if (isArray(files)) {
(files as Express.Multer.File[]).forEach(f => deleteFileAndCatch(f.path))
if (isArray(filesObject)) {
filesObject.forEach(f => deleteFileAndCatch(f.path))
return
}
for (const key of Object.keys(files)) {
const file = files[key]
for (const key of Object.keys(filesObject)) {
const files = filesObject[key]
if (isArray(file)) file.forEach(f => deleteFileAndCatch(f.path))
else deleteFileAndCatch(file.path)
files.forEach(f => deleteFileAndCatch(f.path))
}
}

View File

@ -21,7 +21,7 @@ import { AttributesOnly } from '@shared/core-utils'
import { Account, AccountSummary } from '../../../shared/models/actors'
import { isAccountDescriptionValid } from '../../helpers/custom-validators/accounts'
import { CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants'
import { sendDeleteActor } from '../../lib/activitypub/send'
import { sendDeleteActor } from '../../lib/activitypub/send/send-delete'
import {
MAccount,
MAccountActor,