1
0
Fork 0

Add notification on new instance follower (server side)

This commit is contained in:
Chocobozzz 2019-04-08 17:26:01 +02:00
parent 0dc6477758
commit 883993c81e
No known key found for this signature in database
GPG key ID: 583A612D890159BE
19 changed files with 212 additions and 21 deletions

View file

@ -75,7 +75,8 @@ async function updateNotificationSettings (req: express.Request, res: express.Re
myVideoImportFinished: body.myVideoImportFinished,
newFollow: body.newFollow,
newUserRegistration: body.newUserRegistration,
commentMention: body.commentMention
commentMention: body.commentMention,
newInstanceFollower: body.newInstanceFollower
}
await UserNotificationSettingModel.update(values, query)

View file

@ -0,0 +1,40 @@
import * as Sequelize from 'sequelize'
async function up (utils: {
transaction: Sequelize.Transaction,
queryInterface: Sequelize.QueryInterface,
sequelize: Sequelize.Sequelize,
db: any
}): Promise<void> {
{
const data = {
type: Sequelize.INTEGER,
defaultValue: null,
allowNull: true
}
await utils.queryInterface.addColumn('userNotificationSetting', 'newInstanceFollower', data)
}
{
const query = 'UPDATE "userNotificationSetting" SET "newInstanceFollower" = 1'
await utils.sequelize.query(query)
}
{
const data = {
type: Sequelize.INTEGER,
defaultValue: null,
allowNull: false
}
await utils.queryInterface.changeColumn('userNotificationSetting', 'newInstanceFollower', data)
}
}
function down (options) {
throw new Error('Not implemented.')
}
export {
up,
down
}

View file

@ -342,6 +342,8 @@ function saveActorAndServerAndModelIfNotExist (
actorCreated.VideoChannel.Account = ownerActor.Account
}
actorCreated.Server = server
return actorCreated
}
}

View file

@ -24,14 +24,16 @@ export {
// ---------------------------------------------------------------------------
async function processFollow (actor: ActorModel, targetActorURL: string) {
const { actorFollow, created } = await sequelizeTypescript.transaction(async t => {
const { actorFollow, created, isFollowingInstance } = await sequelizeTypescript.transaction(async t => {
const targetActor = await ActorModel.loadByUrlAndPopulateAccountAndChannel(targetActorURL, t)
if (!targetActor) throw new Error('Unknown actor')
if (targetActor.isOwned() === false) throw new Error('This is not a local actor.')
const serverActor = await getServerActor()
if (targetActor.id === serverActor.id && CONFIG.FOLLOWERS.INSTANCE.ENABLED === false) {
const isFollowingInstance = targetActor.id === serverActor.id
if (isFollowingInstance && CONFIG.FOLLOWERS.INSTANCE.ENABLED === false) {
logger.info('Rejecting %s because instance followers are disabled.', targetActor.url)
return sendReject(actor, targetActor)
@ -50,9 +52,6 @@ async function processFollow (actor: ActorModel, targetActorURL: string) {
transaction: t
})
actorFollow.ActorFollower = actor
actorFollow.ActorFollowing = targetActor
if (actorFollow.state !== 'accepted' && CONFIG.FOLLOWERS.INSTANCE.MANUAL_APPROVAL === false) {
actorFollow.state = 'accepted'
await actorFollow.save({ transaction: t })
@ -64,10 +63,16 @@ async function processFollow (actor: ActorModel, targetActorURL: string) {
// Target sends to actor he accepted the follow request
if (actorFollow.state === 'accepted') await sendAccept(actorFollow)
return { actorFollow, created }
return { actorFollow, created, isFollowingInstance }
})
if (created) Notifier.Instance.notifyOfNewFollow(actorFollow)
// Rejected
if (!actorFollow) return
if (created) {
if (isFollowingInstance) Notifier.Instance.notifyOfNewInstanceFollow(actorFollow)
else Notifier.Instance.notifyOfNewUserFollow(actorFollow)
}
logger.info('Actor %s is followed by actor %s.', targetActorURL, actor.url)
}

View file

@ -129,6 +129,24 @@ class Emailer {
return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
}
addNewInstanceFollowerNotification (to: string[], actorFollow: ActorFollowModel) {
const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
const text = `Hi dear admin,\n\n` +
`Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
`\n\n` +
`Cheers,\n` +
`PeerTube.`
const emailPayload: EmailPayload = {
to,
subject: 'New instance follower',
text
}
return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
}
myVideoPublishedNotification (to: string[], video: VideoModel) {
const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()

View file

@ -73,5 +73,5 @@ async function follow (fromActor: ActorModel, targetActor: ActorModel) {
return actorFollow
})
if (actorFollow.state === 'accepted') Notifier.Instance.notifyOfNewFollow(actorFollow)
if (actorFollow.state === 'accepted') Notifier.Instance.notifyOfNewUserFollow(actorFollow)
}

View file

@ -92,18 +92,25 @@ class Notifier {
.catch(err => logger.error('Cannot notify moderators of new user registration (%s).', user.username, { err }))
}
notifyOfNewFollow (actorFollow: ActorFollowModel): void {
notifyOfNewUserFollow (actorFollow: ActorFollowModel): void {
this.notifyUserOfNewActorFollow(actorFollow)
.catch(err => {
logger.error(
'Cannot notify owner of channel %s of a new follow by %s.',
actorFollow.ActorFollowing.VideoChannel.getDisplayName(),
actorFollow.ActorFollower.Account.getDisplayName(),
err
{ err }
)
})
}
notifyOfNewInstanceFollow (actorFollow: ActorFollowModel): void {
this.notifyAdminsOfNewInstanceFollow(actorFollow)
.catch(err => {
logger.error('Cannot notify administrators of new follower %s.', actorFollow.ActorFollower.url, { err })
})
}
private async notifySubscribersOfNewVideo (video: VideoModel) {
// List all followers that are users
const users = await UserModel.listUserSubscribersOf(video.VideoChannel.actorId)
@ -261,6 +268,33 @@ class Notifier {
return this.notify({ users: [ user ], settingGetter, notificationCreator, emailSender })
}
private async notifyAdminsOfNewInstanceFollow (actorFollow: ActorFollowModel) {
const admins = await UserModel.listWithRight(UserRight.MANAGE_SERVER_FOLLOW)
logger.info('Notifying %d administrators of new instance follower: %s.', admins.length, actorFollow.ActorFollower.url)
function settingGetter (user: UserModel) {
return user.NotificationSetting.newInstanceFollower
}
async function notificationCreator (user: UserModel) {
const notification = await UserNotificationModel.create({
type: UserNotificationType.NEW_INSTANCE_FOLLOWER,
userId: user.id,
actorFollowId: actorFollow.id
})
notification.ActorFollow = actorFollow
return notification
}
function emailSender (emails: string[]) {
return Emailer.Instance.addNewInstanceFollowerNotification(emails, actorFollow)
}
return this.notify({ users: admins, settingGetter, notificationCreator, emailSender })
}
private async notifyModeratorsOfNewVideoAbuse (videoAbuse: VideoAbuseModel) {
const moderators = await UserModel.listWithRight(UserRight.MANAGE_VIDEO_ABUSES)
if (moderators.length === 0) return

View file

@ -110,7 +110,8 @@ function createDefaultUserNotificationSettings (user: UserModel, t: Sequelize.Tr
blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newUserRegistration: UserNotificationSettingValue.WEB,
commentMention: UserNotificationSettingValue.WEB,
newFollow: UserNotificationSettingValue.WEB
newFollow: UserNotificationSettingValue.WEB,
newInstanceFollower: UserNotificationSettingValue.WEB
}
return UserNotificationSettingModel.create(values, { transaction: t })

View file

@ -28,8 +28,22 @@ const updateNotificationSettingsValidator = [
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new comment on my video notification setting'),
body('videoAbuseAsModerator')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new video abuse as moderator notification setting'),
body('videoAutoBlacklistAsModerator')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid video auto blacklist notification setting'),
body('blacklistOnMyVideo')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new blacklist on my video notification setting'),
body('myVideoImportFinished')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid video import finished video notification setting'),
body('myVideoPublished')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid video published notification setting'),
body('commentMention')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid comment mention notification setting'),
body('newFollow')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new follow notification setting'),
body('newUserRegistration')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new user registration notification setting'),
body('newInstanceFollower')
.custom(isUserNotificationSettingValid).withMessage('Should have a valid new instance follower notification setting'),
(req: express.Request, res: express.Response, next: express.NextFunction) => {
logger.debug('Checking updateNotificationSettingsValidator parameters', { parameters: req.body })

View file

@ -101,6 +101,15 @@ export class UserNotificationSettingModel extends Model<UserNotificationSettingM
@Column
newUserRegistration: UserNotificationSettingValue
@AllowNull(false)
@Default(null)
@Is(
'UserNotificationSettingNewInstanceFollower',
value => throwIfNotValid(value, isUserNotificationSettingValid, 'newInstanceFollower')
)
@Column
newInstanceFollower: UserNotificationSettingValue
@AllowNull(false)
@Default(null)
@Is(
@ -154,7 +163,8 @@ export class UserNotificationSettingModel extends Model<UserNotificationSettingM
myVideoImportFinished: this.myVideoImportFinished,
newUserRegistration: this.newUserRegistration,
commentMention: this.commentMention,
newFollow: this.newFollow
newFollow: this.newFollow,
newInstanceFollower: this.newInstanceFollower
}
}
}

View file

@ -418,6 +418,7 @@ export class UserNotificationModel extends Model<UserNotificationModel> {
const actorFollow = this.ActorFollow ? {
id: this.ActorFollow.id,
state: this.ActorFollow.state,
follower: {
id: this.ActorFollow.ActorFollower.Account.id,
displayName: this.ActorFollow.ActorFollower.Account.getDisplayName(),

View file

@ -174,7 +174,8 @@ describe('Test user notifications API validators', function () {
myVideoPublished: UserNotificationSettingValue.WEB,
commentMention: UserNotificationSettingValue.WEB,
newFollow: UserNotificationSettingValue.WEB,
newUserRegistration: UserNotificationSettingValue.WEB
newUserRegistration: UserNotificationSettingValue.WEB,
newInstanceFollower: UserNotificationSettingValue.WEB
}
it('Should fail with missing fields', async function () {

View file

@ -1,2 +1,3 @@
import './check-params'
import './notifications'
import './search'

View file

@ -0,0 +1 @@
export * from './user-notifications'

View file

@ -19,7 +19,7 @@ import {
userLogin,
wait,
getCustomConfig,
updateCustomConfig, getVideoThreadComments, getVideoCommentThreads
updateCustomConfig, getVideoThreadComments, getVideoCommentThreads, follow
} from '../../../../shared/utils'
import { killallServers, ServerInfo, uploadVideo } from '../../../../shared/utils/index'
import { setAccessTokensToServers } from '../../../../shared/utils/users/login'
@ -41,7 +41,7 @@ import {
getUserNotifications,
markAsReadNotifications,
updateMyNotificationSettings,
markAsReadAllNotifications
markAsReadAllNotifications, checkNewInstanceFollower
} from '../../../../shared/utils/users/user-notifications'
import {
User,
@ -103,7 +103,8 @@ describe('Test users notifications', function () {
myVideoPublished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
commentMention: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newFollow: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL
newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newInstanceFollower: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL
}
before(async function () {
@ -118,7 +119,7 @@ describe('Test users notifications', function () {
hostname: 'localhost'
}
}
servers = await flushAndRunMultipleServers(2, overrideConfig)
servers = await flushAndRunMultipleServers(3, overrideConfig)
// Get the access tokens
await setAccessTokensToServers(servers)
@ -861,6 +862,32 @@ describe('Test users notifications', function () {
})
})
describe('New instance follower', function () {
let baseParams: CheckerBaseParams
before(async () => {
baseParams = {
server: servers[0],
emails,
socketNotifications: adminNotifications,
token: servers[0].accessToken
}
})
it('Should send a notification only to admin when there is a new instance follower', async function () {
this.timeout(10000)
await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken)
await waitJobs(servers)
await checkNewInstanceFollower(baseParams, 'localhost:9003', 'presence')
const userOverride = { socketNotifications: userNotifications, token: userAccessToken, check: { web: true, mail: false } }
await checkNewInstanceFollower(immutableAssign(baseParams, userOverride), 'localhost:9003', 'absence')
})
})
describe('New actor follow', function () {
let baseParams: CheckerBaseParams
let myChannelName = 'super channel name'

View file

@ -1,5 +1,4 @@
import './users-verification'
import './user-notifications'
import './blocklist'
import './user-subscriptions'
import './users'

View file

@ -15,4 +15,5 @@ export interface UserNotificationSetting {
newUserRegistration: UserNotificationSettingValue
newFollow: UserNotificationSettingValue
commentMention: UserNotificationSettingValue
newInstanceFollower: UserNotificationSettingValue
}

View file

@ -1,3 +1,5 @@
import { FollowState } from '../actors'
export enum UserNotificationType {
NEW_VIDEO_FROM_SUBSCRIPTION = 1,
NEW_COMMENT_ON_MY_VIDEO = 2,
@ -15,7 +17,9 @@ export enum UserNotificationType {
NEW_FOLLOW = 10,
COMMENT_MENTION = 11,
VIDEO_AUTO_BLACKLIST_FOR_MODERATORS = 12
VIDEO_AUTO_BLACKLIST_FOR_MODERATORS = 12,
NEW_INSTANCE_FOLLOWER = 13
}
export interface VideoInfo {
@ -73,6 +77,7 @@ export interface UserNotification {
actorFollow?: {
id: number
follower: ActorInfo
state: FollowState
following: {
type: 'account' | 'channel'
name: string

View file

@ -298,6 +298,35 @@ async function checkNewActorFollow (
await checkNotification(base, notificationChecker, emailFinder, type)
}
async function checkNewInstanceFollower (base: CheckerBaseParams, followerHost: string, type: CheckerType) {
const notificationType = UserNotificationType.NEW_INSTANCE_FOLLOWER
function notificationChecker (notification: UserNotification, type: CheckerType) {
if (type === 'presence') {
expect(notification).to.not.be.undefined
expect(notification.type).to.equal(notificationType)
checkActor(notification.actorFollow.follower)
expect(notification.actorFollow.follower.name).to.equal('peertube')
expect(notification.actorFollow.follower.host).to.equal(followerHost)
expect(notification.actorFollow.following.name).to.equal('peertube')
} else {
expect(notification).to.satisfy(n => {
return n.type !== notificationType || n.actorFollow.follower.host !== followerHost
})
}
}
function emailFinder (email: object) {
const text: string = email[ 'text' ]
return text.includes('instance has a new follower') && text.includes(followerHost)
}
await checkNotification(base, notificationChecker, emailFinder, type)
}
async function checkCommentMention (
base: CheckerBaseParams,
uuid: string,
@ -462,5 +491,6 @@ export {
checkVideoAutoBlacklistForModerators,
getUserNotifications,
markAsReadNotifications,
getLastNotification
getLastNotification,
checkNewInstanceFollower
}