ActivityPub-federated video streaming platform using P2P directly in your web browser
Add notifications to video ownership changes
Chocobozzze594e80c443f
diff --git a/client/src/app/shared/shared-main/users/user-notification.model.ts b/client/src/app/shared/shared-main/users/user-notification.model.tsindex 0089f53a3a..9ab2bf26d8 100644--- a/client/src/app/shared/shared-main/users/user-notification.model.ts+++ b/client/src/app/shared/shared-main/users/user-notification.model.ts@@ -157,6 +157,12 @@ export class UserNotification {case UserNotificationType.REFUSED_TO_COLLABORATE_TO_CHANNEL:this.url = this.buildChannelUrl(payload.videoChannelCollaborator.channel)break++ case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST:+ case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED:+ case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED:+ this.url = '/my-library/ownership'+ break}} catch (err) {this.payload.type = nulldiff --git a/client/src/app/shared/shared-notifications/user-notification-content.component.html b/client/src/app/shared/shared-notifications/user-notification-content.component.htmlindex 47ac71e294..23462c1e2d 100644--- a/client/src/app/shared/shared-notifications/user-notification-content.component.html+++ b/client/src/app/shared/shared-notifications/user-notification-content.component.html@@ -270,6 +270,30 @@</div>}+ @case (26) { <!-- UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST -->+ <my-global-icon iconName="user-add"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.videoOwnership.initiatorAccount.displayName }}</strong> requested to transfer ownership of video <strong>{{ n.payload.videoOwnership.video.name }}</strong> to you+ </div>+ }++ @case (27) { <!-- UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED -->+ <my-global-icon iconName="tick"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.videoOwnership.nextOwnerAccount.displayName }}</strong> accepted the ownership change request for video <strong>{{ n.payload.videoOwnership.video.name }}</strong>+ </div>+ }++ @case (28) { <!-- UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED -->+ <my-global-icon iconName="cross"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.videoOwnership.nextOwnerAccount.displayName }}</strong> rejected the ownership change request for video <strong>{{ n.payload.videoOwnership.video.name }}</strong>+ </div>+ }+@default {<my-global-icon iconName="alert"></my-global-icon>diff --git a/packages/models/src/users/user-notification.model.ts b/packages/models/src/users/user-notification.model.tsindex 5b21598430..1b4663fb34 100644--- a/packages/models/src/users/user-notification.model.ts+++ b/packages/models/src/users/user-notification.model.ts@@ -46,7 +46,11 @@ export const UserNotificationType = {INVITED_TO_COLLABORATE_TO_CHANNEL: 23,ACCEPTED_TO_COLLABORATE_TO_CHANNEL: 24,- REFUSED_TO_COLLABORATE_TO_CHANNEL: 25+ REFUSED_TO_COLLABORATE_TO_CHANNEL: 25,++ VIDEO_OWNERSHIP_CHANGED_REQUEST: 26,+ VIDEO_OWNERSHIP_CHANGED_ACCEPTED: 27,+ VIDEO_OWNERSHIP_CHANGED_REJECTED: 28} as constexport type UserNotificationType_Type = typeof UserNotificationType[keyof typeof UserNotificationType]@@ -170,6 +174,13 @@ export interface UserNotification {account: ActorInfo}+ videoOwnership?: {+ id: number+ initiatorAccount: ActorInfo+ nextOwnerAccount: ActorInfo+ video: VideoInfo+ }+createdAt: stringupdatedAt: string}diff --git a/packages/server-commands/src/users/notifications-command.ts b/packages/server-commands/src/users/notifications-command.tsindex 692a365f0e..16c12632e8 100644--- a/packages/server-commands/src/users/notifications-command.ts+++ b/packages/server-commands/src/users/notifications-command.ts@@ -2,10 +2,11 @@ import { HttpStatusCode, ResultList, UserNotification, UserNotificationSetting,import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'export class NotificationsCommand extends AbstractCommand {-- updateMySettings (options: OverrideCommandOptions & {- settings: UserNotificationSetting- }) {+ updateMySettings (+ options: OverrideCommandOptions & {+ settings: UserNotificationSetting+ }+ ) {const path = '/api/v1/users/me/notification-settings'return this.putBodyRequest({@@ -18,13 +19,15 @@ export class NotificationsCommand extends AbstractCommand {})}- list (options: OverrideCommandOptions & {- start?: number- count?: number- unread?: boolean- sort?: string- typeOneOf?: UserNotificationType_Type[]- }) {+ list (+ options: OverrideCommandOptions & {+ start?: number+ count?: number+ unread?: boolean+ sort?: string+ typeOneOf?: UserNotificationType_Type[]+ }+ ) {const { start, count, unread, typeOneOf, sort = '-createdAt' } = optionsconst path = '/api/v1/users/me/notifications'@@ -44,9 +47,11 @@ export class NotificationsCommand extends AbstractCommand {})}- markAsRead (options: OverrideCommandOptions & {- ids: number[]- }) {+ markAsRead (+ options: OverrideCommandOptions & {+ ids: number[]+ }+ ) {const { ids } = optionsconst path = '/api/v1/users/me/notifications/read'@@ -72,9 +77,15 @@ export class NotificationsCommand extends AbstractCommand {})}- async getLatest (options: OverrideCommandOptions = {}) {+ async getLatest (options: OverrideCommandOptions & { type?: UserNotificationType_Type } = {}) {+ const { type } = options+const { total, data } = await this.list({...options,++ typeOneOf: type+ ? [ type ]+ : undefined,start: 0,count: 1,sort: '-createdAt'diff --git a/packages/tests/src/api/notifications/user-notifications.ts b/packages/tests/src/api/notifications/user-notifications.tsindex 4ec6bdac9d..dd876b0c56 100644--- a/packages/tests/src/api/notifications/user-notifications.ts+++ b/packages/tests/src/api/notifications/user-notifications.ts@@ -14,7 +14,11 @@ import {checkNewVideoFromSubscription,checkVideoStudioEditionIsFinished} from '@tests/shared/notifications/check-video-notifications.js'-import { prepareNotificationsTest, waitUntilNotification } from '@tests/shared/notifications/notifications-common.js'+import {+ getAllNotificationsSettings,+ prepareNotificationsTest,+ waitUntilNotification+} from '@tests/shared/notifications/notifications-common.js'import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'import { uploadRandomVideoOnServers } from '@tests/shared/videos.js'import { expect } from 'chai'@@ -550,6 +554,103 @@ describe('Test user notifications', function () {})})+ describe('Video ownership change notifications', function () {+ const nextOwner = 'ownership_request_target'+ let nextOwnerToken: string++ const videoName = 'ownership change'+ let videoId: string++ before(async function () {+ nextOwnerToken = await servers[0].users.generateUserAndToken(nextOwner)++ await servers[0].notifications.updateMySettings({ token: nextOwnerToken, settings: getAllNotificationsSettings() })+ const { uuid } = await servers[0].videos.quickUpload({ name: videoName, privacy: VideoPrivacy.PRIVATE })++ videoId = uuid+ })++ it('Should notify the next owner when ownership change is requested', async function () {+ const requestDate = new Date()+ await servers[0].changeOwnership.create({ videoId, username: nextOwner })++ await waitUntilNotification({+ server: servers[0],+ token: nextOwnerToken,+ notificationType: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST,+ fromDate: requestDate+ })++ const notification = await servers[0].notifications.getLatest({+ token: nextOwnerToken,+ type: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ })+ expect(notification.type).to.equal(UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST)+ expect(notification.videoOwnership.id).to.exist+ expect(notification.videoOwnership.video.name).to.equal(videoName)+ expect(notification.videoOwnership.initiatorAccount.name).to.equal('root')+ expect(notification.videoOwnership.nextOwnerAccount.name).to.equal(nextOwner)+ })++ it('Should notify the video owner when ownership change is accepted', async function () {+ const { data } = await servers[0].changeOwnership.list({ token: nextOwnerToken })++ const acceptedAt = new Date()+ await servers[0].changeOwnership.accept({+ token: nextOwnerToken,+ ownershipId: data[0].id,+ channelId: await servers[0].channels.getDefaultId({ token: nextOwnerToken })+ })++ await waitUntilNotification({+ server: servers[0],+ token: servers[0].accessToken,+ notificationType: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED,+ fromDate: acceptedAt+ })++ const notification = await servers[0].notifications.getLatest({ type: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED })+ expect(notification.type).to.equal(UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED)+ expect(notification.videoOwnership.id).to.exist+ expect(notification.videoOwnership.video.name).to.equal(videoName)+ expect(notification.videoOwnership.initiatorAccount.name).to.equal('root')+ expect(notification.videoOwnership.nextOwnerAccount.name).to.equal(nextOwner)+ })++ it('Should notify rejected channel collaborators when ownership change is rejected', async function () {+ const collaboratorToken = await servers[0].channelCollaborators.createEditor('ownership_reject_collaborator', `${nextOwner}_channel`)++ const nextNextOwner = 'ownership_reject_target'+ const nextNextOwnerToken = await servers[0].users.generateUserAndToken(nextNextOwner)++ await servers[0].changeOwnership.create({ videoId, username: nextNextOwner })+ const { data } = await servers[0].changeOwnership.list({ token: nextNextOwnerToken })++ const rejectedAt = new Date()+ await servers[0].changeOwnership.refuse({+ token: nextNextOwnerToken,+ ownershipId: data[0].id+ })++ await waitUntilNotification({+ server: servers[0],+ token: collaboratorToken,+ notificationType: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED,+ fromDate: rejectedAt+ })++ const notification = await servers[0].notifications.getLatest({+ token: collaboratorToken,+ type: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED+ })+ expect(notification.type).to.equal(UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED)+ expect(notification.videoOwnership.id).to.exist+ expect(notification.videoOwnership.video.name).to.equal(videoName)+ expect(notification.videoOwnership.initiatorAccount.name).to.equal('root') // root made the request on behalf of the nextOwner user+ expect(notification.videoOwnership.nextOwnerAccount.name).to.equal(nextNextOwner)+ })+ })+describe('New actor follow', function () {let baseParams: CheckerBaseParamsconst myChannelName = 'super channel name'diff --git a/server/core/controllers/api/videos/ownership.ts b/server/core/controllers/api/videos/ownership.tsindex a5780cca75..e41b58af75 100644--- a/server/core/controllers/api/videos/ownership.ts+++ b/server/core/controllers/api/videos/ownership.ts@@ -1,4 +1,9 @@-import { HttpStatusCode, VideoChangeOwnershipStatus, VideoChangeOwnershipStatusType, VideoChannelActivityAction } from '@peertube/peertube-models'+import {+ HttpStatusCode,+ VideoChangeOwnershipStatus,+ VideoChangeOwnershipStatusType,+ VideoChannelActivityAction+} from '@peertube/peertube-models'import { canVideoBeFederated } from '@server/lib/activitypub/videos/federate.js'import { VideoChannelActivityModel } from '@server/models/video/video-channel-activity.js'import { MVideoFull } from '@server/types/models/index.js'@@ -8,6 +13,7 @@ import { getFormattedObjects } from '../../../helpers/utils.js'import { sequelizeTypescript } from '../../../initializers/database.js'import { sendUpdateVideo } from '../../../lib/activitypub/send/index.js'import { changeVideoChannelShare } from '../../../lib/activitypub/share.js'+import { Notifier } from '../../../lib/notifier/notifier.js'import {asyncMiddleware,asyncRetryTransactionMiddleware,@@ -85,8 +91,8 @@ async function giveVideoOwnership (req: express.Request, res: express.Response)const initiatorAccountId = res.locals.oauth.token.User.Account.idconst nextOwner = res.locals.videoChangeOwnershipNextOwner- await sequelizeTypescript.transaction(async t => {- await VideoChangeOwnershipModel.findOrCreate({+ const ownershipChange = await sequelizeTypescript.transaction(async t => {+ const [ ownershipChange ] = await VideoChangeOwnershipModel.findOrCreate({where: {initiatorAccountId,nextOwnerAccountId: nextOwner.id,@@ -110,8 +116,14 @@ async function giveVideoOwnership (req: express.Request, res: express.Response)targetAccount: nextOwner,transaction: t})++ return ownershipChange})+ const ownershipChangeFull = await VideoChangeOwnershipModel.load(ownershipChange.id)++ Notifier.Instance.notifyOfRequestedVideoOwnershipChange(ownershipChangeFull)+logger.info('Ownership change for video %s created.', video.name)return res.sendStatus(HttpStatusCode.NO_CONTENT_204)@@ -179,6 +191,8 @@ function acceptOwnership (req: express.Request, res: express.Response) {})}+ Notifier.Instance.notifyOfAcceptedVideoOwnershipChange(videoChangeOwnership)+return res.sendStatus(HttpStatusCode.NO_CONTENT_204)})}@@ -201,6 +215,8 @@ function refuseOwnership (req: express.Request, res: express.Response) {transaction: t})+ Notifier.Instance.notifyOfRejectedVideoOwnershipChange(videoChangeOwnership)+return res.sendStatus(HttpStatusCode.NO_CONTENT_204)})}diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex 422f32bd21..4f8be94ad8 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -60,7 +60,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'// ----------------------------------------------------------------------------export const LAST_MIGRATION_VERSION = 1010+export const LAST_MIGRATION_VERSION = 1015// ---------------------------------------------------------------------------diff --git a/server/core/initializers/migrations/1015-video-ownership-notifications.ts b/server/core/initializers/migrations/1015-video-ownership-notifications.tsnew file mode 100644index 0000000000..269ba5abc4--- /dev/null+++ b/server/core/initializers/migrations/1015-video-ownership-notifications.ts@@ -0,0 +1,26 @@+import * as Sequelize from 'sequelize'++async function up (utils: {+ transaction: Sequelize.Transaction+ queryInterface: Sequelize.QueryInterface+ sequelize: Sequelize.Sequelize+}): Promise<void> {+ const { transaction } = utils++ {+ await utils.sequelize.query(+ `ALTER TABLE "userNotification" ` ++ `ADD COLUMN "videoOwnershipId" INTEGER REFERENCES "videoChangeOwnership" ("id") ON DELETE SET NULL ON UPDATE CASCADE`,+ { transaction }+ )+ }+}++function down () {+ throw new Error('Not implemented.')+}++export {+ up,+ down+}diff --git a/server/core/lib/notifier/notifier.ts b/server/core/lib/notifier/notifier.tsindex 9a9d50fbf3..eb868c2504 100644--- a/server/core/lib/notifier/notifier.ts+++ b/server/core/lib/notifier/notifier.ts@@ -15,6 +15,7 @@ import {MPlugin,MVideoAccountLight,MVideoCaptionVideo,+ MVideoChangeOwnershipFull,MVideoFull,MVideoWithSchedule} from '../../types/models/index.js'@@ -52,6 +53,9 @@ import {UnblacklistForOwner,VideoTranscriptionGeneratedForOwner} from './shared/index.js'+import { RequestVideoOwnershipChange } from './shared/video-ownership/request-video-ownership-change.js'+import { VideoOwnershipChangeAccepted } from './shared/video-ownership/video-ownership-change-accepted.js'+import { VideoOwnershipChangeRejected } from './shared/video-ownership/video-ownership-change-rejected.js'const lTags = loggerTagsFactory('notifier')@@ -90,7 +94,11 @@ class Notifier {channelCollaboratorInvitation: [ InvitedToCollaborateToChannel ],channelCollaborationAccepted: [ AcceptedToCollaborateToChannel ],- channelCollaborationRefused: [ RefusedToCollaborateToChannel ]+ channelCollaborationRefused: [ RefusedToCollaborateToChannel ],++ videoOwnershipRequest: [ RequestVideoOwnershipChange ],+ videoOwnershipAccepted: [ VideoOwnershipChangeAccepted ],+ videoOwnershipRejected: [ VideoOwnershipChangeRejected ]}private static instance: Notifier@@ -342,6 +350,37 @@ class Notifier {.catch(err => logger.error(`Cannot notify ${channelOwner} of refused invitation to collaborate to channel ${channelName}`, { err }))}+ // ---------------------------------------------------------------------------+ // Video ownership change notifications+ // ---------------------------------------------------------------------------++ notifyOfRequestedVideoOwnershipChange (videoOwnership: MVideoChangeOwnershipFull) {+ const models = this.notificationModels.videoOwnershipRequest++ logger.debug('Notify on requested video ownership change', { id: videoOwnership.id, video: videoOwnership.Video.url, ...lTags() })++ this.sendNotifications(models, videoOwnership)+ .catch(err => logger.error('Cannot notify requested video ownership change %d.', videoOwnership.id, { err }))+ }++ notifyOfAcceptedVideoOwnershipChange (videoOwnership: MVideoChangeOwnershipFull) {+ const models = this.notificationModels.videoOwnershipAccepted++ logger.debug('Notify on accepted video ownership change', { id: videoOwnership.id, video: videoOwnership.Video.url, ...lTags() })++ this.sendNotifications(models, videoOwnership)+ .catch(err => logger.error('Cannot notify accepted video ownership change %d.', videoOwnership.id, { err }))+ }++ notifyOfRejectedVideoOwnershipChange (videoOwnership: MVideoChangeOwnershipFull) {+ const models = this.notificationModels.videoOwnershipRejected++ logger.debug('Notify on rejected video ownership change', { id: videoOwnership.id, video: videoOwnership.Video.url, ...lTags() })++ this.sendNotifications(models, videoOwnership)+ .catch(err => logger.error('Cannot notify rejected video ownership change %d.', videoOwnership.id, { err }))+ }+// ---------------------------------------------------------------------------private async notify<T> (object: AbstractNotification<T>) {diff --git a/server/core/lib/notifier/shared/index.ts b/server/core/lib/notifier/shared/index.tsindex 5ae060db72..bc0d1594a0 100644--- a/server/core/lib/notifier/shared/index.ts+++ b/server/core/lib/notifier/shared/index.ts@@ -5,4 +5,5 @@ export * from './comment/index.js'export * from './common/index.js'export * from './follow/index.js'export * from './instance/index.js'+export * from './video-ownership/index.js'export * from './video-publication/index.js'diff --git a/server/core/lib/notifier/shared/video-ownership/abstract-video-ownership-response.ts b/server/core/lib/notifier/shared/video-ownership/abstract-video-ownership-response.tsnew file mode 100644index 0000000000..d9b0a837eb--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/abstract-video-ownership-response.ts@@ -0,0 +1,36 @@+import { UserNotificationSettingValue, UserNotificationType_Type } from '@peertube/peertube-models'+import { UserModel } from '@server/models/user/user.js'+import { MUserWithNotificationSetting } from '@server/types/models/index.js'+import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildVideoOwnershipNotification } from './video-ownership-utils.js'++export abstract class AbstractVideoOwnershipResponse extends AbstractNotification<MVideoChangeOwnershipFull> {+ protected users: MUserWithNotificationSetting[] = []++ async prepare () {+ this.users = await UserModel.listOwnerAndAcceptedCollaboratorsOfChannel(this.payload.Video.channelId)+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ return this.users.filter(user => user.id !== this.payload.NextOwner.userId)+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildVideoOwnershipNotification({+ user,+ payload: this.payload,+ notificationType: this.getNotificationType()+ })+ }++ protected abstract getNotificationType (): UserNotificationType_Type+}diff --git a/server/core/lib/notifier/shared/video-ownership/index.ts b/server/core/lib/notifier/shared/video-ownership/index.tsnew file mode 100644index 0000000000..1a03fc1e1a--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/index.ts@@ -0,0 +1,3 @@+export * from './request-video-ownership-change.js'+export * from './video-ownership-change-accepted.js'+export * from './video-ownership-change-rejected.js'diff --git a/server/core/lib/notifier/shared/video-ownership/request-video-ownership-change.ts b/server/core/lib/notifier/shared/video-ownership/request-video-ownership-change.tsnew file mode 100644index 0000000000..f737a25504--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/request-video-ownership-change.ts@@ -0,0 +1,63 @@+import { UserNotificationSettingValue, UserNotificationType } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { WEBSERVER } from '@server/initializers/constants.js'+import { UserModel } from '@server/models/user/user.js'+import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'+import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildVideoOwnershipNotification } from './video-ownership-utils.js'++export class RequestVideoOwnershipChange extends AbstractNotification<MVideoChangeOwnershipFull> {+ private user: MUserDefault++ async prepare () {+ this.user = await UserModel.loadByAccountId(this.payload.nextOwnerAccountId)+ }++ log () {+ logger.info('Notifying %s of ownership request for video %s.', this.user.username, this.payload.Video.url)+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ if (!this.user) return []++ return [ this.user ]+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildVideoOwnershipNotification({+ user,+ payload: this.payload,+ notificationType: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ })+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A video ownership change request is waiting for you', language),+ text: t('{initiator} wants to transfer ownership of {videoName} to you.', language, {+ initiator: this.payload.Initiator.getDisplayName(),+ videoName: this.payload.Video.name+ }),+ locals: {+ action: {+ text: t('Review the request', language),+ url: WEBSERVER.URL + '/my-account/notifications'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/video-ownership/video-ownership-change-accepted.ts b/server/core/lib/notifier/shared/video-ownership/video-ownership-change-accepted.tsnew file mode 100644index 0000000000..390541858b--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/video-ownership-change-accepted.ts@@ -0,0 +1,36 @@+import { UserNotificationType } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { WEBSERVER } from '@server/initializers/constants.js'+import { MUserWithNotificationSetting } from '@server/types/models/index.js'+import { AbstractVideoOwnershipResponse } from './abstract-video-ownership-response.js'++export class VideoOwnershipChangeAccepted extends AbstractVideoOwnershipResponse {+ log () {+ logger.info('Notifying source channel members that ownership change of %s was accepted.', this.payload.Video.url)+ }++ protected getNotificationType () {+ return UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A video ownership change request has been accepted', language),+ text: t('{nextOwner} accepted the ownership change request for {videoName}.', language, {+ nextOwner: this.payload.NextOwner.getDisplayName(),+ videoName: this.payload.Video.name+ }),+ locals: {+ action: {+ text: t('Review ownership changes', language),+ url: WEBSERVER.URL + '/my-library/ownership'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/video-ownership/video-ownership-change-rejected.ts b/server/core/lib/notifier/shared/video-ownership/video-ownership-change-rejected.tsnew file mode 100644index 0000000000..b4db8eef6e--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/video-ownership-change-rejected.ts@@ -0,0 +1,36 @@+import { UserNotificationType } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { WEBSERVER } from '@server/initializers/constants.js'+import { MUserWithNotificationSetting } from '@server/types/models/index.js'+import { AbstractVideoOwnershipResponse } from './abstract-video-ownership-response.js'++export class VideoOwnershipChangeRejected extends AbstractVideoOwnershipResponse {+ log () {+ logger.info('Notifying source channel members that ownership change of %s was rejected.', this.payload.Video.url)+ }++ protected getNotificationType () {+ return UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A video ownership change request has been rejected', language),+ text: t('{nextOwner} rejected the ownership change request for {videoName}.', language, {+ nextOwner: this.payload.NextOwner.getDisplayName(),+ videoName: this.payload.Video.name+ }),+ locals: {+ action: {+ text: t('Review ownership changes', language),+ url: WEBSERVER.URL + '/my-library/ownership'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/video-ownership/video-ownership-utils.ts b/server/core/lib/notifier/shared/video-ownership/video-ownership-utils.tsnew file mode 100644index 0000000000..b7cab3bf15--- /dev/null+++ b/server/core/lib/notifier/shared/video-ownership/video-ownership-utils.ts@@ -0,0 +1,22 @@+import { UserNotificationType_Type } from '@peertube/peertube-models'+import { UserNotificationModel } from '@server/models/user/user-notification.js'+import { MUserId, UserNotificationModelForApi } from '@server/types/models/user/index.js'+import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership.js'++export function buildVideoOwnershipNotification (options: {+ user: MUserId+ payload: MVideoChangeOwnershipFull+ notificationType: UserNotificationType_Type+}): UserNotificationModelForApi {+ const { user, payload, notificationType } = options++ const notification = UserNotificationModel.build<UserNotificationModelForApi>({+ type: notificationType,+ userId: user.id,+ videoOwnershipId: payload.id+ })++ notification.VideoOwnership = payload++ return notification+}diff --git a/server/core/models/shared/model-builder.ts b/server/core/models/shared/model-builder.tsindex e5a60ff99c..87bb47f9c9 100644--- a/server/core/models/shared/model-builder.ts+++ b/server/core/models/shared/model-builder.ts@@ -43,7 +43,8 @@ export class ModelBuilder<T extends SequelizeModel> {VideoChannelCollaborators: 'VideoChannelCollaboratorModel',Tags: 'TagModel',Initiator: 'AccountModel',- NextOwner: 'AccountModel'+ NextOwner: 'AccountModel',+ VideoOwnership: 'VideoChangeOwnershipModel'}constructor (private readonly sequelize: Sequelize) {diff --git a/server/core/models/user/sql/user-notification/user-notification-list-query-builder.ts b/server/core/models/user/sql/user-notification/user-notification-list-query-builder.tsindex 6c78578a7b..2ad5d38084 100644--- a/server/core/models/user/sql/user-notification/user-notification-list-query-builder.ts+++ b/server/core/models/user/sql/user-notification/user-notification-list-query-builder.ts@@ -146,7 +146,15 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {`"ChannelCollab"."state" AS "ChannelCollab.state"`,...this.getAccountOrChannelAttributes('ChannelCollab->Account', 'ChannelCollab.Account'),...this.getAccountOrChannelAttributes('ChannelCollab->Channel->Account', 'ChannelCollab.Channel.Account'),- ...this.getAccountOrChannelAttributes('ChannelCollab->Channel', 'ChannelCollab.Channel')+ ...this.getAccountOrChannelAttributes('ChannelCollab->Channel', 'ChannelCollab.Channel'),++ `"VideoOwnership"."id" AS "VideoOwnership.id"`,+ ...this.getAccountOrChannelAttributes('VideoOwnership->Initiator', 'VideoOwnership.Initiator'),+ ...this.getAccountOrChannelAttributes('VideoOwnership->NextOwner', 'VideoOwnership.NextOwner'),+ `"VideoOwnership->Video"."id" AS "VideoOwnership.Video.id"`,+ `"VideoOwnership->Video"."uuid" AS "VideoOwnership.Video.uuid"`,+ `"VideoOwnership->Video"."name" AS "VideoOwnership.Video.name"`,+ `"VideoOwnership->Video"."state" AS "VideoOwnership.Video.state"`]}@@ -221,7 +229,14 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {${this.getAccountJoin('ChannelCollab', 'accountId')}${this.getChannelJoin('ChannelCollab', 'channelId', 'Channel')}${this.getAccountJoin('ChannelCollab->Channel', 'accountId')}- ) ON "UserNotificationModel"."channelCollaboratorId" = "ChannelCollab"."id"`+ ) ON "UserNotificationModel"."channelCollaboratorId" = "ChannelCollab"."id"++ LEFT JOIN (+ "videoChangeOwnership" AS "VideoOwnership"+ ${this.getAccountJoin('VideoOwnership', 'initiatorAccountId', 'Initiator')}+ ${this.getAccountJoin('VideoOwnership', 'nextOwnerAccountId', 'NextOwner')}+ INNER JOIN "video" AS "VideoOwnership->Video" ON "VideoOwnership"."videoId" = "VideoOwnership->Video"."id"+ ) ON "UserNotificationModel"."videoOwnershipId" = "VideoOwnership"."id"`}// ---------------------------------------------------------------------------@@ -241,9 +256,9 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {]}- private getAccountJoin (tableName: string, columnJoin: string) {- return `INNER JOIN "account" AS "${tableName}->Account" ON "${tableName}"."${columnJoin}" = "${tableName}->Account"."id" ` +- this.getActorJoin(`${tableName}->Account`, 'accountId')+ private getAccountJoin (tableName: string, columnJoin: string, aliasTableName = 'Account') {+ return `INNER JOIN "account" AS "${tableName}->${aliasTableName}" ON "${tableName}"."${columnJoin}" = "${tableName}->${aliasTableName}"."id" ` ++ this.getActorJoin(`${tableName}->${aliasTableName}`, 'accountId')}private getChannelJoin (tableName: string, columnJoin: string, aliasTableName = 'VideoChannel') {diff --git a/server/core/models/user/user-notification.ts b/server/core/models/user/user-notification.tsindex a4167cc04f..5b78652018 100644--- a/server/core/models/user/user-notification.ts+++ b/server/core/models/user/user-notification.ts@@ -17,6 +17,7 @@ import { VideoBlacklistModel } from '../video/video-blacklist.js'import { VideoCaptionModel } from '../video/video-caption.js'import { VideoChannelCollaboratorModel } from '../video/video-channel-collaborator.js'import { VideoCommentModel } from '../video/video-comment.js'+import { VideoChangeOwnershipModel } from '../video/video-change-ownership.js'import { VideoImportModel } from '../video/video-import.js'import { VideoModel } from '../video/video.js'import { UserNotificationListQueryBuilder } from './sql/user-notification/user-notification-list-query-builder.js'@@ -124,6 +125,14 @@ import { UserModel } from './user.js'[Op.ne]: null}}+ },+ {+ fields: [ 'videoOwnershipId' ],+ where: {+ videoOwnershipId: {+ [Op.ne]: null+ }+ }}] as (ModelIndexesOptions & { where?: WhereOptions })[]})@@ -306,6 +315,18 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>})declare VideoChannelCollaborator: Awaited<VideoChannelCollaboratorModel>+ @ForeignKey(() => VideoChangeOwnershipModel)+ @Column+ declare videoOwnershipId: number++ @BelongsTo(() => VideoChangeOwnershipModel, {+ foreignKey: {+ allowNull: true+ },+ onDelete: 'cascade'+ })+ declare VideoOwnership: Awaited<VideoChangeOwnershipModel>+static listForApi (options: {userId: numberstart: number@@ -537,6 +558,15 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>}: undefined+ const videoOwnership = this.VideoOwnership+ ? {+ id: this.VideoOwnership.id,+ initiatorAccount: this.formatActor(this.VideoOwnership.Initiator),+ nextOwnerAccount: this.formatActor(this.VideoOwnership.NextOwner),+ video: this.formatVideo(this.VideoOwnership.Video)+ }+ : undefined+return {id: this.id,type: this.type,@@ -554,6 +584,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>registration,videoCaption,videoChannelCollaborator,+ videoOwnership,createdAt: this.createdAt.toISOString(),updatedAt: this.updatedAt.toISOString()}diff --git a/server/core/models/user/user.ts b/server/core/models/user/user.tsindex f825c27e0d..1331a924bc 100644--- a/server/core/models/user/user.ts+++ b/server/core/models/user/user.ts@@ -7,6 +7,7 @@ import {UserAdminFlag,UserRightType,UserRole,+ VideoChannelCollaboratorState,VideoPlaylistType,type NSFWPolicyType,type UserAdminFlagType,@@ -74,6 +75,7 @@ import { ActorFollowModel } from '../actor/actor-follow.js'import { ActorModel } from '../actor/actor.js'import { OAuthTokenModel } from '../oauth/oauth-token.js'import { buildSQLAttributes, getAdminUsersSort, parseAggregateResult, SequelizeModel, throwIfNotValid } from '../shared/index.js'+import { VideoChannelCollaboratorModel } from '../video/video-channel-collaborator.js'import { VideoChannelModel } from '../video/video-channel.js'import { VideoImportModel } from '../video/video-import.js'import { VideoLiveModel } from '../video/video-live.js'@@ -621,6 +623,48 @@ export class UserModel extends SequelizeModel<UserModel> {return UserModel.unscoped().findAll(query)}+ static listOwnerAndAcceptedCollaboratorsOfChannel (channelId: number): Promise<MUserWithNotificationSetting[]> {+ const query = {+ include: [+ {+ model: UserNotificationSettingModel.unscoped(),+ required: true+ },+ {+ model: AccountModel.unscoped(),+ required: true,+ include: [+ {+ model: VideoChannelModel.unscoped(),+ required: false,+ attributes: [ 'id' ],+ where: {+ id: channelId+ }+ },+ {+ model: VideoChannelCollaboratorModel.unscoped(),+ required: false,+ attributes: [ 'id' ],+ where: {+ channelId,+ state: VideoChannelCollaboratorState.ACCEPTED+ }+ }+ ]+ }+ ],+ where: {+ [Op.or]: [+ { '$Account.VideoChannels.id$': { [Op.ne]: null } },+ { '$Account.VideoChannelCollaborators.id$': { [Op.ne]: null } }+ ]+ }+ }++ return UserModel.unscoped().findAll(query)+ }+static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {const query = {where: {diff --git a/server/core/types/models/user/user-notification.ts b/server/core/types/models/user/user-notification.tsindex cdf19af260..d7848345a9 100644--- a/server/core/types/models/user/user-notification.ts+++ b/server/core/types/models/user/user-notification.ts@@ -9,6 +9,7 @@ import { UserNotificationModel } from '@server/models/user/user-notification.js'import { UserRegistrationModel } from '@server/models/user/user-registration.js'import { VideoCaptionModel } from '@server/models/video/video-caption.js'import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'+import { VideoChangeOwnershipModel } from '@server/models/video/video-change-ownership.js'import { AbuseModel } from '../../../models/abuse/abuse.js'import { AccountModel } from '../../../models/account/account.js'import { ActorFollowModel } from '../../../models/actor/actor-follow.js'@@ -118,6 +119,12 @@ export namespace UserNotificationIncludes {& Pick<VideoChannelCollaboratorModel, 'id' | 'state'>& PickWith<VideoChannelCollaboratorModel, 'Account', AccountIncludeActor>& PickWith<VideoChannelCollaboratorModel, 'Channel', VideoChannelIncludeActorOwnerActor>++ export type VideoOwnershipInclude =+ & Pick<VideoChangeOwnershipModel, 'id'>+ & PickWith<VideoChangeOwnershipModel, 'Initiator', AccountIncludeActor>+ & PickWith<VideoChangeOwnershipModel, 'NextOwner', AccountIncludeActor>+ & PickWith<VideoChangeOwnershipModel, 'Video', VideoInclude>}// ############################################################################@@ -137,6 +144,7 @@ export type MUserNotification = Omit<| 'UserRegistration'| 'VideoCaption'| 'VideoChannelCollaborator'+ | 'VideoOwnership'>// ############################################################################@@ -155,3 +163,4 @@ export type UserNotificationModelForApi =& Use<'UserRegistration', UserNotificationIncludes.UserRegistrationInclude>& Use<'VideoCaption', UserNotificationIncludes.VideoCaptionInclude>& Use<'VideoChannelCollaborator', UserNotificationIncludes.VideoChannelCollaboratorInclude>+ & Use<'VideoOwnership', UserNotificationIncludes.VideoOwnershipInclude>diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex 74f1b120e5..c26a3e1069 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -12453,6 +12453,12 @@ components:- 20- 21- 22+ - 23+ - 24+ - 25+ - 26+ - 27+ - 28description: >Notification type. One of the following values:@@ -12500,6 +12506,18 @@ components:- `22` MY_VIDEO_TRANSCRIPTION_GENERATED+ - `23` INVITED_TO_COLLABORATE_TO_CHANNEL++ - `24` ACCEPTED_TO_COLLABORATE_TO_CHANNEL++ - `25` REFUSED_TO_COLLABORATE_TO_CHANNEL++ - `26` VIDEO_OWNERSHIP_CHANGED_REQUEST++ - `27` VIDEO_OWNERSHIP_CHANGED_ACCEPTED++ - `28` VIDEO_OWNERSHIP_CHANGED_REJECTED+NewFeatureInfoType:type: integerenum: