]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/commitdiff
Add notification on new instance follower (server side)
authorChocobozzz <me@florianbigard.com>
Mon, 8 Apr 2019 15:26:01 +0000 (17:26 +0200)
committerChocobozzz <me@florianbigard.com>
Mon, 8 Apr 2019 15:30:48 +0000 (17:30 +0200)
19 files changed:
server/controllers/api/users/my-notifications.ts
server/initializers/migrations/0360-notification-instance-follower.ts [new file with mode: 0644]
server/lib/activitypub/actor.ts
server/lib/activitypub/process/process-follow.ts
server/lib/emailer.ts
server/lib/job-queue/handlers/activitypub-follow.ts
server/lib/notifier.ts
server/lib/user.ts
server/middlewares/validators/user-notifications.ts
server/models/account/user-notification-setting.ts
server/models/account/user-notification.ts
server/tests/api/check-params/user-notifications.ts
server/tests/api/index-1.ts
server/tests/api/notifications/index.ts [new file with mode: 0644]
server/tests/api/notifications/user-notifications.ts [moved from server/tests/api/users/user-notifications.ts with 97% similarity]
server/tests/api/users/index.ts
shared/models/users/user-notification-setting.model.ts
shared/models/users/user-notification.model.ts
shared/utils/users/user-notifications.ts

index 4edad2a7491a1bc7c38add5a8b31ba3c49761f17..f146284e4acc50b7f9c60155533214402b6e7076 100644 (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)
diff --git a/server/initializers/migrations/0360-notification-instance-follower.ts b/server/initializers/migrations/0360-notification-instance-follower.ts
new file mode 100644 (file)
index 0000000..05caf8e
--- /dev/null
@@ -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
+}
index 63e8106421f9fc49cd9ac2861e109bfa861a978c..c0ad07a525b1e29e235cfb3f0c90a70c979a9481 100644 (file)
@@ -342,6 +342,8 @@ function saveActorAndServerAndModelIfNotExist (
       actorCreated.VideoChannel.Account = ownerActor.Account
     }
 
+    actorCreated.Server = server
+
     return actorCreated
   }
 }
index 140bbe9f1322e26fe4cf5326e2e1594810051d75..276a57e6073e86ab170bd4d3bf6f9b3256e6cbbf 100644 (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)
 }
index eec97c27ee20066f64851bef0e278418fa367781..aa90833624b7d8eb4d1ce440517828470d5e2135 100644 (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()
 
index b4d381062564d5ba4b59178cedb26d8ad670f301..e7e5ff950bb74f30bd102d488b462a1fc8450763 100644 (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)
 }
index 9fe93ec0d1fb1cf3a285d71e234fdc4f75e216ab..91b71cc64dd992f3a8a939f07320c01e7f8db884 100644 (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
index 5588b0f7695a0b333b9cea391e5b0978b2b117fb..6fbe3ed03f0e8e0ca99be563564db5ab727f6b61 100644 (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 })
index 46486e081332a815edc0537ee6db4520d57fe09a..3ded8d8cf9c01e9039d40edc64efb6a9f9f8b9dd 100644 (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 })
index ba7f739b9c8f5cdbc3821b49d52df1d79a2b62f0..c2fbc6d23cc150b673bd9d02d524ef345718529f 100644 (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
     }
   }
 }
index 6cdbb827bca60f7b6c084280a06d794ecd02b7fe..ccf8277ab1ab45413f4c3b1d90b3278f347feeb1 100644 (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(),
index 36eaceac7b2a1206a1eb89d170a9a98a19e0570d..4b75f6920bdac59de312643589cd9f7454e3f0f1 100644 (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 () {
index 80d752f42169565f8c7a370e792b09c10b54eb27..75cdd9025441202193af0f82a41f2400446d0e6f 100644 (file)
@@ -1,2 +1,3 @@
 import './check-params'
+import './notifications'
 import './search'
diff --git a/server/tests/api/notifications/index.ts b/server/tests/api/notifications/index.ts
new file mode 100644 (file)
index 0000000..95ac8fc
--- /dev/null
@@ -0,0 +1 @@
+export * from './user-notifications'
similarity index 97%
rename from server/tests/api/users/user-notifications.ts
rename to server/tests/api/notifications/user-notifications.ts
index ac47978e2b992e3bad9c18a262602fa9d9b808ef..7bff527962aec864401e34f088804b1f5fa87c9d 100644 (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'
index 52ba6984eb7cdd96dfaa5adfaec066af9e785351..fcd022429421654ffacca7226ee8a227fbb9d507 100644 (file)
@@ -1,5 +1,4 @@
 import './users-verification'
-import './user-notifications'
 import './blocklist'
 import './user-subscriptions'
 import './users'
index 57b33e4b840af354b4bd09bd441435d6d8110ed4..e2a882b6916e324f9c28289dfc6c3b2ea3b33081 100644 (file)
@@ -15,4 +15,5 @@ export interface UserNotificationSetting {
   newUserRegistration: UserNotificationSettingValue
   newFollow: UserNotificationSettingValue
   commentMention: UserNotificationSettingValue
+  newInstanceFollower: UserNotificationSettingValue
 }
index 19892b61a51bfadfb9dd5227b8ef808a1dc6ea0e..fafc2b7d74e12cca8ae6618627166d51f877bc3b 100644 (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
index e3a79f523e95c71361a260e9d4f57c0ac651ab74..495ff80d9b61c450a6f02534a566a4f49ab0c012 100644 (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
 }