From b4055e1c23eeefb0c8a85a77f312b2827d98f483 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 18 Jul 2019 14:28:37 +0200 Subject: Add server hooks --- server/lib/activitypub/video-comments.ts | 2 +- server/lib/activitypub/videos.ts | 132 ++++++++++++++++--------------- server/lib/moderation.ts | 64 +++++++++++++++ server/lib/plugins/hooks.ts | 26 ++++++ server/lib/plugins/plugin-manager.ts | 22 +++--- server/lib/video-blacklist.ts | 25 ++++-- 6 files changed, 186 insertions(+), 85 deletions(-) create mode 100644 server/lib/moderation.ts create mode 100644 server/lib/plugins/hooks.ts (limited to 'server/lib') diff --git a/server/lib/activitypub/video-comments.ts b/server/lib/activitypub/video-comments.ts index c3fc6b462..2f26ddefd 100644 --- a/server/lib/activitypub/video-comments.ts +++ b/server/lib/activitypub/video-comments.ts @@ -134,7 +134,7 @@ async function resolveThread (url: string, comments: VideoCommentModel[] = []): }) if (sanitizeAndCheckVideoCommentObject(body) === false) { - throw new Error('Remote video comment JSON is not valid :' + JSON.stringify(body)) + throw new Error('Remote video comment JSON is not valid:' + JSON.stringify(body)) } const actorUrl = body.attributedTo diff --git a/server/lib/activitypub/videos.ts b/server/lib/activitypub/videos.ts index 4f26cb6be..dade6b55f 100644 --- a/server/lib/activitypub/videos.ts +++ b/server/lib/activitypub/videos.ts @@ -54,6 +54,8 @@ import { ThumbnailModel } from '../../models/video/thumbnail' import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type' import { join } from 'path' import { FilteredModelAttributes } from '../../typings/sequelize' +import { Hooks } from '../plugins/hooks' +import { autoBlacklistVideoIfNeeded } from '../video-blacklist' async function federateVideoIfNeeded (video: VideoModel, isNewVideo: boolean, transaction?: sequelize.Transaction) { // If the video is not private and is published, we federate it @@ -236,72 +238,74 @@ async function updateVideoFromAP (options: { channel: VideoChannelModel, overrideTo?: string[] }) { + const { video, videoObject, account, channel, overrideTo } = options + logger.debug('Updating remote video "%s".', options.videoObject.uuid) let videoFieldsSave: any - const wasPrivateVideo = options.video.privacy === VideoPrivacy.PRIVATE - const wasUnlistedVideo = options.video.privacy === VideoPrivacy.UNLISTED + const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE + const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED try { let thumbnailModel: ThumbnailModel try { - thumbnailModel = await createVideoMiniatureFromUrl(options.videoObject.icon.url, options.video, ThumbnailType.MINIATURE) + thumbnailModel = await createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE) } catch (err) { - logger.warn('Cannot generate thumbnail of %s.', options.videoObject.id, { err }) + logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }) } await sequelizeTypescript.transaction(async t => { const sequelizeOptions = { transaction: t } - videoFieldsSave = options.video.toJSON() + videoFieldsSave = video.toJSON() // Check actor has the right to update the video - const videoChannel = options.video.VideoChannel - if (videoChannel.Account.id !== options.account.id) { - throw new Error('Account ' + options.account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url) + const videoChannel = video.VideoChannel + if (videoChannel.Account.id !== account.id) { + throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url) } - const to = options.overrideTo ? options.overrideTo : options.videoObject.to - const videoData = await videoActivityObjectToDBAttributes(options.channel, options.videoObject, to) - options.video.set('name', videoData.name) - options.video.set('uuid', videoData.uuid) - options.video.set('url', videoData.url) - options.video.set('category', videoData.category) - options.video.set('licence', videoData.licence) - options.video.set('language', videoData.language) - options.video.set('description', videoData.description) - options.video.set('support', videoData.support) - options.video.set('nsfw', videoData.nsfw) - options.video.set('commentsEnabled', videoData.commentsEnabled) - options.video.set('downloadEnabled', videoData.downloadEnabled) - options.video.set('waitTranscoding', videoData.waitTranscoding) - options.video.set('state', videoData.state) - options.video.set('duration', videoData.duration) - options.video.set('createdAt', videoData.createdAt) - options.video.set('publishedAt', videoData.publishedAt) - options.video.set('originallyPublishedAt', videoData.originallyPublishedAt) - options.video.set('privacy', videoData.privacy) - options.video.set('channelId', videoData.channelId) - options.video.set('views', videoData.views) - - await options.video.save(sequelizeOptions) - - if (thumbnailModel) if (thumbnailModel) await options.video.addAndSaveThumbnail(thumbnailModel, t) + const to = overrideTo ? overrideTo : videoObject.to + const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to) + video.name = videoData.name + video.uuid = videoData.uuid + video.url = videoData.url + video.category = videoData.category + video.licence = videoData.licence + video.language = videoData.language + video.description = videoData.description + video.support = videoData.support + video.nsfw = videoData.nsfw + video.commentsEnabled = videoData.commentsEnabled + video.downloadEnabled = videoData.downloadEnabled + video.waitTranscoding = videoData.waitTranscoding + video.state = videoData.state + video.duration = videoData.duration + video.createdAt = videoData.createdAt + video.publishedAt = videoData.publishedAt + video.originallyPublishedAt = videoData.originallyPublishedAt + video.privacy = videoData.privacy + video.channelId = videoData.channelId + video.views = videoData.views + + await video.save(sequelizeOptions) + + if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) // FIXME: use icon URL instead - const previewUrl = buildRemoteBaseUrl(options.video, join(STATIC_PATHS.PREVIEWS, options.video.getPreview().filename)) - const previewModel = createPlaceholderThumbnail(previewUrl, options.video, ThumbnailType.PREVIEW, PREVIEWS_SIZE) - await options.video.addAndSaveThumbnail(previewModel, t) + const previewUrl = buildRemoteBaseUrl(video, join(STATIC_PATHS.PREVIEWS, video.getPreview().filename)) + const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE) + await video.addAndSaveThumbnail(previewModel, t) { - const videoFileAttributes = videoFileActivityUrlToDBAttributes(options.video, options.videoObject) + const videoFileAttributes = videoFileActivityUrlToDBAttributes(video, videoObject) const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a)) // Remove video files that do not exist anymore - const destroyTasks = options.video.VideoFiles - .filter(f => !newVideoFiles.find(newFile => newFile.hasSameUniqueKeysThan(f))) - .map(f => f.destroy(sequelizeOptions)) + const destroyTasks = video.VideoFiles + .filter(f => !newVideoFiles.find(newFile => newFile.hasSameUniqueKeysThan(f))) + .map(f => f.destroy(sequelizeOptions)) await Promise.all(destroyTasks) // Update or add other one @@ -310,21 +314,17 @@ async function updateVideoFromAP (options: { .then(([ file ]) => file) }) - options.video.VideoFiles = await Promise.all(upsertTasks) + video.VideoFiles = await Promise.all(upsertTasks) } { - const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes( - options.video, - options.videoObject, - options.video.VideoFiles - ) + const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(video, videoObject, video.VideoFiles) const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a)) // Remove video files that do not exist anymore - const destroyTasks = options.video.VideoStreamingPlaylists - .filter(f => !newStreamingPlaylists.find(newPlaylist => newPlaylist.hasSameUniqueKeysThan(f))) - .map(f => f.destroy(sequelizeOptions)) + const destroyTasks = video.VideoStreamingPlaylists + .filter(f => !newStreamingPlaylists.find(newPlaylist => newPlaylist.hasSameUniqueKeysThan(f))) + .map(f => f.destroy(sequelizeOptions)) await Promise.all(destroyTasks) // Update or add other one @@ -333,36 +333,36 @@ async function updateVideoFromAP (options: { .then(([ streamingPlaylist ]) => streamingPlaylist) }) - options.video.VideoStreamingPlaylists = await Promise.all(upsertTasks) + video.VideoStreamingPlaylists = await Promise.all(upsertTasks) } { // Update Tags - const tags = options.videoObject.tag.map(tag => tag.name) + const tags = videoObject.tag.map(tag => tag.name) const tagInstances = await TagModel.findOrCreateTags(tags, t) - await options.video.$set('Tags', tagInstances, sequelizeOptions) + await video.$set('Tags', tagInstances, sequelizeOptions) } { // Update captions - await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(options.video.id, t) + await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(video.id, t) - const videoCaptionsPromises = options.videoObject.subtitleLanguage.map(c => { - return VideoCaptionModel.insertOrReplaceLanguage(options.video.id, c.identifier, t) + const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => { + return VideoCaptionModel.insertOrReplaceLanguage(video.id, c.identifier, t) }) - options.video.VideoCaptions = await Promise.all(videoCaptionsPromises) + video.VideoCaptions = await Promise.all(videoCaptionsPromises) } }) - // Notify our users? - if (wasPrivateVideo || wasUnlistedVideo) { - Notifier.Instance.notifyOnNewVideo(options.video) - } + const autoBlacklisted = await autoBlacklistVideoIfNeeded(video, undefined, undefined) + + if (autoBlacklisted) Notifier.Instance.notifyOnVideoAutoBlacklist(video) + else if (!wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideo(video) // Notify our users? - logger.info('Remote video with uuid %s updated', options.videoObject.uuid) + logger.info('Remote video with uuid %s updated', videoObject.uuid) } catch (err) { - if (options.video !== undefined && videoFieldsSave !== undefined) { - resetSequelizeInstance(options.video, videoFieldsSave) + if (video !== undefined && videoFieldsSave !== undefined) { + resetSequelizeInstance(video, videoFieldsSave) } // This is just a debug because we will retry the insert @@ -379,7 +379,9 @@ async function refreshVideoIfNeeded (options: { if (!options.video.isOutdated()) return options.video // We need more attributes if the argument video was fetched with not enough joints - const video = options.fetchedType === 'all' ? options.video : await VideoModel.loadByUrlAndPopulateAccount(options.video.url) + const video = options.fetchedType === 'all' + ? options.video + : await VideoModel.loadByUrlAndPopulateAccount(options.video.url) try { const { response, videoObject } = await fetchRemoteVideo(video.url) diff --git a/server/lib/moderation.ts b/server/lib/moderation.ts new file mode 100644 index 000000000..b609f4585 --- /dev/null +++ b/server/lib/moderation.ts @@ -0,0 +1,64 @@ +import { VideoModel } from '../models/video/video' +import { VideoCommentModel } from '../models/video/video-comment' +import { VideoCommentCreate } from '../../shared/models/videos/video-comment.model' +import { VideoCreate } from '../../shared/models/videos' +import { UserModel } from '../models/account/user' +import { VideoTorrentObject } from '../../shared/models/activitypub/objects' +import { ActivityCreate } from '../../shared/models/activitypub' +import { ActorModel } from '../models/activitypub/actor' +import { VideoCommentObject } from '../../shared/models/activitypub/objects/video-comment-object' + +export type AcceptResult = { + accepted: boolean + errorMessage?: string +} + +// Can be filtered by plugins +function isLocalVideoAccepted (object: { + videoBody: VideoCreate, + videoFile: Express.Multer.File & { duration?: number }, + user: UserModel +}): AcceptResult { + return { accepted: true } +} + +function isLocalVideoThreadAccepted (_object: { + commentBody: VideoCommentCreate, + video: VideoModel, + user: UserModel +}): AcceptResult { + return { accepted: true } +} + +function isLocalVideoCommentReplyAccepted (_object: { + commentBody: VideoCommentCreate, + parentComment: VideoCommentModel, + video: VideoModel, + user: UserModel +}): AcceptResult { + return { accepted: true } +} + +function isRemoteVideoAccepted (_object: { + activity: ActivityCreate, + videoAP: VideoTorrentObject, + byActor: ActorModel +}): AcceptResult { + return { accepted: true } +} + +function isRemoteVideoCommentAccepted (_object: { + activity: ActivityCreate, + commentAP: VideoCommentObject, + byActor: ActorModel +}): AcceptResult { + return { accepted: true } +} + +export { + isLocalVideoAccepted, + isLocalVideoThreadAccepted, + isRemoteVideoAccepted, + isRemoteVideoCommentAccepted, + isLocalVideoCommentReplyAccepted +} diff --git a/server/lib/plugins/hooks.ts b/server/lib/plugins/hooks.ts new file mode 100644 index 000000000..7bb907e6a --- /dev/null +++ b/server/lib/plugins/hooks.ts @@ -0,0 +1,26 @@ +import { ServerActionHookName, ServerFilterHookName } from '../../../shared/models/plugins/server-hook.model' +import { PluginManager } from './plugin-manager' +import { logger } from '../../helpers/logger' +import * as Bluebird from 'bluebird' + +// Helpers to run hooks +const Hooks = { + wrapObject: (obj: T, hookName: U) => { + return PluginManager.Instance.runHook(hookName, obj) as Promise + }, + + wrapPromise: async (fun: Promise | Bluebird, hookName: U) => { + const result = await fun + + return PluginManager.Instance.runHook(hookName, result) + }, + + runAction: (hookName: U, params?: T) => { + PluginManager.Instance.runHook(hookName, params) + .catch(err => logger.error('Fatal hook error.', { err })) + } +} + +export { + Hooks +} diff --git a/server/lib/plugins/plugin-manager.ts b/server/lib/plugins/plugin-manager.ts index 570b56193..85ee3decb 100644 --- a/server/lib/plugins/plugin-manager.ts +++ b/server/lib/plugins/plugin-manager.ts @@ -14,6 +14,10 @@ import { RegisterSettingOptions } from '../../../shared/models/plugins/register- import { RegisterHookOptions } from '../../../shared/models/plugins/register-hook.model' import { PluginSettingsManager } from '../../../shared/models/plugins/plugin-settings-manager.model' import { PluginStorageManager } from '../../../shared/models/plugins/plugin-storage-manager.model' +import { ServerHookName, ServerHook } from '../../../shared/models/plugins/server-hook.model' +import { isCatchable, isPromise } from '../../../shared/core-utils/miscs/miscs' +import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks' +import { HookType } from '../../../shared/models/plugins/hook-type.enum' export interface RegisteredPlugin { npmName: string @@ -42,7 +46,7 @@ export interface HookInformationValue { priority: number } -export class PluginManager { +export class PluginManager implements ServerHook { private static instance: PluginManager @@ -95,25 +99,17 @@ export class PluginManager { // ###################### Hooks ###################### - async runHook (hookName: string, param?: any) { + async runHook (hookName: ServerHookName, param?: any) { let result = param if (!this.hooks[hookName]) return result - const wait = hookName.startsWith('static:') + const hookType = getHookType(hookName) for (const hook of this.hooks[hookName]) { - try { - const p = hook.handler(param) - - if (wait) { - result = await p - } else if (p.catch) { - p.catch(err => logger.warn('Hook %s of plugin %s thrown an error.', hookName, hook.pluginName, { err })) - } - } catch (err) { + result = await internalRunHook(hook.handler, hookType, param, err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) - } + }) } return result diff --git a/server/lib/video-blacklist.ts b/server/lib/video-blacklist.ts index 985b89e31..32b1a28fa 100644 --- a/server/lib/video-blacklist.ts +++ b/server/lib/video-blacklist.ts @@ -1,4 +1,4 @@ -import * as sequelize from 'sequelize' +import { Transaction } from 'sequelize' import { CONFIG } from '../initializers/config' import { UserRight, VideoBlacklistType } from '../../shared/models' import { VideoBlacklistModel } from '../models/video/video-blacklist' @@ -6,26 +6,39 @@ import { UserModel } from '../models/account/user' import { VideoModel } from '../models/video/video' import { logger } from '../helpers/logger' import { UserAdminFlag } from '../../shared/models/users/user-flag.model' +import { Hooks } from './plugins/hooks' -async function autoBlacklistVideoIfNeeded (video: VideoModel, user: UserModel, transaction: sequelize.Transaction) { - if (!CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED) return false +async function autoBlacklistVideoIfNeeded (video: VideoModel, user?: UserModel, transaction?: Transaction) { + const doAutoBlacklist = await Hooks.wrapPromise( + autoBlacklistNeeded({ video, user }), + 'filter:video.auto-blacklist.result' + ) - if (user.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) || user.hasAdminFlag(UserAdminFlag.BY_PASS_VIDEO_AUTO_BLACKLIST)) return false + if (!doAutoBlacklist) return false - const sequelizeOptions = { transaction } const videoBlacklistToCreate = { videoId: video.id, unfederated: true, reason: 'Auto-blacklisted. Moderator review required.', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED } - await VideoBlacklistModel.create(videoBlacklistToCreate, sequelizeOptions) + await VideoBlacklistModel.create(videoBlacklistToCreate, { transaction }) logger.info('Video %s auto-blacklisted.', video.uuid) return true } +async function autoBlacklistNeeded (parameters: { video: VideoModel, user?: UserModel }) { + const { user } = parameters + + if (!CONFIG.AUTO_BLACKLIST.VIDEOS.OF_USERS.ENABLED || !user) return false + + if (user.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST) || user.hasAdminFlag(UserAdminFlag.BY_PASS_VIDEO_AUTO_BLACKLIST)) return false + + return true +} + // --------------------------------------------------------------------------- export { -- cgit v1.2.3