ActivityPub-federated video streaming platform using P2P directly in your web browser
Add ability to transfer channel ownership
Chocobozzz3faff0d7a6d0
diff --git a/.github/actions/reusable-prepare-peertube-build/action.yml b/.github/actions/reusable-prepare-peertube-build/action.ymlindex 9cea065b92..e235d07f12 100644--- a/.github/actions/reusable-prepare-peertube-build/action.yml+++ b/.github/actions/reusable-prepare-peertube-build/action.yml@@ -11,7 +11,7 @@ runs:using: "composite"steps:- - uses: pnpm/action-setup@v4+ - uses: pnpm/action-setup@v5name: Install pnpmwith:run_install: falsediff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 5fa02c62bb..3d13a1d858 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -129,7 +129,7 @@ jobs:echo "parse-log.js script does not exist, skipping."- name: Upload logs and database- uses: actions/upload-artifact@v4+ uses: actions/upload-artifact@v7if: failure()with:name: test-storages-${{ matrix.test_suite }}diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-activity.component.html b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-activity.component.htmlindex de7765d7d4..98fc53d2b7 100644--- a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-activity.component.html+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-activity.component.html@@ -179,19 +179,31 @@@case (12) { <!-- VideoChannelActivityAction.SEND_OWNERSHIP_REQUEST) --><ng-container i18n>- <strong>{{ account }}</strong> sent an ownership request to {{ a.targetAccount.displayName }} for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ @if (a.video) {+ <strong>{{ account }}</strong> sent an ownership change request to {{ a.targetAccount.displayName }} for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ } @else if (a.channel) {+ <strong>{{ account }}</strong> sent an ownership change request to {{ a.targetAccount.displayName }} for this channel+ }</ng-container>}@case (13) { <!-- VideoChannelActivityAction.ACCEPT_OWNERSHIP_REQUEST) --><ng-container i18n>- <strong>{{ account }}</strong> accepted an ownership request for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ @if (a.video) {+ <strong>{{ account }}</strong> accepted an ownership change request for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ } @else if (a.channel) {+ <strong>{{ account }}</strong> accepted an ownership change request for this channel+ }</ng-container>}@case (14) { <!-- VideoChannelActivityAction.REFUSE_OWNERSHIP_REQUEST) --><ng-container i18n>- <strong>{{ account }}</strong> refused an ownership request for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ @if (a.video) {+ <strong>{{ account }}</strong> refused an ownership change request for video <a [routerLink]="[ '/w', a.video.shortUUID ]">{{ a.video.name }}</a>+ } @else if (a.channel) {+ <strong>{{ account }}</strong> refused an ownership change request for this channel+ }</ng-container>}diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.html b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.htmlindex 332277f68b..b8f445a23c 100644--- a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.html+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.html@@ -130,4 +130,46 @@</div></div></div>++ @if (canBeDeletedOrTransferred()) {+ <div class="pt-two-cols danger-zone mt-5">+ <div class="title-col">+ <h3 i18n>DANGER ZONE</h3>+ </div>++ <div class="content-col">+ <div class="form-group">+ <label i18n for="deleteVideo">Change ownership of your channel</label>+ <div class="form-group-description" >+ <div i18n>A modal window will open for you to specify the local account to which you want to transfer your channel</div>+ <div i18n>The collaborators of this channel will remain after the transfer</div>+ </div>++ <button type="button" class="peertube-button danger-button" (click)="showChangeOwnershipModal()" [disabled]="!!pendingOwnershipRequest" i18n>Transfer ownership</button>++ @if (pendingOwnershipRequest) {+ <my-alert class="d-block mt-3 d-flex" type="success">+ <div class="d-flex align-items-center gap-2 flex-wrap">+ <div i18n>Ownership change request sent to <strong>{{pendingOwnershipRequest.nextOwnerAccount.name}}</strong>, awaiting its approval.</div>++ <my-button (click)="cancelOwnershipRequest()" theme="secondary">Cancel request</my-button>+ </div>+ </my-alert>+ }+ </div>++ <my-send-change-ownership+ #sendChangeOwnershipModal+ [channelName]="videoChannelEdit.channel.name" (requestSent)="onChangeOwnershipRequest($event)"+ ></my-send-change-ownership>++ <div class="form-group">+ <label i18n for="delete-channel-button">Delete your channel</label>+ <div class="form-group-description" i18n>Warning: this is a definitive action!</div>++ <button type="button" id="delete-channel-button" class="peertube-button danger-button" (click)="deleteChannel()" i18n>Delete</button>+ </div>+ </div>+ </div>+ }</form>diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scss b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scssindex 5a7181301d..c1ecca9039 100644--- a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scss+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scss@@ -23,3 +23,11 @@ my-select-player-theme {@include responsive-width(340px);}++.danger-zone {+ h3 {+ color: pvar(--red);+ font-weight: $font-bold;+ font-size: 1rem;+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.ts b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.tsindex 0bd2ec9a8f..a44b4cb27b 100644--- a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.ts+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.ts@@ -1,6 +1,8 @@import { CommonModule } from '@angular/common'-import { Component, inject, OnDestroy, OnInit } from '@angular/core'+import { Component, inject, OnDestroy, OnInit, viewChild } from '@angular/core'import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'+import { Router } from '@angular/router'+import { AuthService, ConfirmService, Notifier } from '@app/core'import {BuildFormArgumentTyped,FormReactiveErrorsTyped,@@ -14,14 +16,19 @@ import {} from '@app/shared/form-validators/video-channel-validators'import { ActorAvatarEditComponent } from '@app/shared/shared-actor-image-edit/actor-avatar-edit.component'import { ActorBannerEditComponent } from '@app/shared/shared-actor-image-edit/actor-banner-edit.component'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'+import { SendChangeOwnershipComponent } from '@app/shared/shared-change-ownership/send-change-ownership.component'import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'import { MarkdownTextareaComponent } from '@app/shared/shared-forms/markdown-textarea.component'import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-checkbox.component'import { SelectPlayerThemeComponent } from '@app/shared/shared-forms/select/select-player-theme.component'import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'+import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'import { HelpComponent } from '@app/shared/shared-main/buttons/help.component'+import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'+import { AlertComponent } from '@app/shared/shared-main/common/alert.component'import { MarkdownHintComponent } from '@app/shared/shared-main/text/markdown-hint.component'-import { PlayerChannelSettings } from '@peertube/peertube-models'+import { ChangeOwnership, ChangeOwnershipState, PlayerChannelSettings } from '@peertube/peertube-models'import { Subscription } from 'rxjs'import { EditMode, VideoChannelEditControllerService } from '../video-channel-edit-controller.service'import { VideoChannelEdit } from '../video-channel-edit.model'@@ -50,12 +57,23 @@ type Form = {PeertubeCheckboxComponent,MarkdownHintComponent,SelectPlayerThemeComponent,- GlobalIconComponent+ GlobalIconComponent,+ AlertComponent,+ ButtonComponent,+ SendChangeOwnershipComponent]})export class VideoChannelEditGeneralComponent implements OnInit, OnDestroy {private formReactiveService = inject(FormReactiveService)private editController = inject(VideoChannelEditControllerService)+ private authService = inject(AuthService)+ private confirmService = inject(ConfirmService)+ private notifier = inject(Notifier)+ private changeOwnershipService = inject(ChangeOwnershipService)+ private channelService = inject(VideoChannelService)+ private router = inject(Router)++ readonly sendChangeOwnershipModal = viewChild<SendChangeOwnershipComponent>('sendChangeOwnershipModal')form: FormGroup<Form>formErrors: FormReactiveErrorsTyped<Form> = {}@@ -63,6 +81,8 @@ export class VideoChannelEditGeneralComponent implements OnInit, OnDestroy {mode: EditModevideoChannelEdit: VideoChannelEdit+ pendingOwnershipRequest: ChangeOwnership+private formSub: Subscriptionprivate storeSub: Subscription@@ -74,11 +94,14 @@ export class VideoChannelEditGeneralComponent implements OnInit, OnDestroy {this.mode = this.editController.getMode()this.videoChannelEdit = this.editController.getStore()+ this.loadOwnershipRequestIfNeeded()+this.buildForm()this.storeSub = this.editController.getStoreChangesObs().subscribe(() => {this.videoChannelEdit = this.editController.getStore()+ this.loadOwnershipRequestIfNeeded()this.buildForm()})@@ -190,4 +213,76 @@ export class VideoChannelEditGeneralComponent implements OnInit, OnDestroy {})})}++ // ---------------------------------------------------------------------------++ canBeDeletedOrTransferred () {+ if (this.mode === 'create') return false++ // Check is owner+ return this.videoChannelEdit.apiInfo.ownerAccount.id === this.authService.getUser().account.id+ }++ showChangeOwnershipModal () {+ this.sendChangeOwnershipModal().show()+ }++ onChangeOwnershipRequest (ownershipChange: ChangeOwnership) {+ this.pendingOwnershipRequest = ownershipChange+ }++ async cancelOwnershipRequest () {+ const message =+ $localize`Are you sure you want to cancel the ownership change request to "${this.pendingOwnershipRequest.nextOwnerAccount.name}"?`+ const res = await this.confirmService.confirm(message, $localize`Cancel request`)+ if (res === false) return++ this.changeOwnershipService.cancelChannel(this.pendingOwnershipRequest.id)+ .subscribe({+ next: () => {+ this.notifier.success($localize`Ownership change request cancelled`)+ this.pendingOwnershipRequest = null+ },++ error: err => this.notifier.handleError(err)+ })+ }++ loadOwnershipRequestIfNeeded () {+ if (this.mode !== 'update') return++ this.changeOwnershipService.listFromChannel(this.videoChannelEdit.channel.name, ChangeOwnershipState.PENDING)+ .subscribe(({ data }) => {+ if (data.length === 0) {+ this.pendingOwnershipRequest = undefined+ } else {+ this.pendingOwnershipRequest = data[0]+ }+ })+ }++ // ---------------------------------------------------------------------------++ deleteChannel () {+ const channel = {+ name: this.videoChannelEdit.channel.name,+ nameWithHost: this.videoChannelEdit.channel.name,+ displayName: this.videoChannelEdit.channel.displayName,++ ...this.videoChannelEdit.apiInfo+ }++ this.channelService.removeWithConfirmation(channel)+ .subscribe({+ next: ({ removed }) => {+ if (!removed) return++ this.router.navigateByUrl('/my-library/video-channels')++ this.notifier.success($localize`Video channel ${channel.displayName} deleted.`)+ },++ error: err => this.notifier.handleError(err)+ })+ }}diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.model.ts b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.model.tsindex a02998a7dc..3824463f27 100644--- a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.model.ts+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.model.ts@@ -39,6 +39,7 @@ export class VideoChannelEdit {ownerAccount: AccountSummaryavatars: VideoChannel['avatars']followersCount: VideoChannel['followersCount']+ videosCount: numberbannerUrl: stringsupport: string}@@ -69,6 +70,7 @@ export class VideoChannelEdit {id: undefined,ownerAccount: user.account,avatars: [],+ videosCount: 0,followersCount: 0,bannerUrl: undefined,support: undefined@@ -101,6 +103,7 @@ export class VideoChannelEdit {this.apiInfo = {id: channel.id,avatars: channel.avatars,+ videosCount: channel.videosCount,followersCount: channel.followersCount,bannerUrl: channel.bannerUrl,support: channel.support,diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.html b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.htmlindex e959c4785e..d8f07758c4 100644--- a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.html+++ b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.html@@ -53,7 +53,7 @@{videoChannel.followersCount, plural, =0 {No subscribers} =1 {1 subscriber} other {{{ videoChannel.followersCount }} subscribers}}</a>- <div class="videos-info">+ <div class="videos-info" [class.opacity-0]="videoChannel.totalViews === undefined"><span i18n>{videoChannel.videosCount, plural, =0 {No videos} =1 {1 video} other {{{ videoChannel.videosCount }} videos}}</span><span class="mx-1">·</span><span i18n>{videoChannel.totalViews, plural, =0 {No views} =1 {1 view} other {{{ videoChannel.totalViews | myNumberFormatter }} views}}</span>diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.tsindex f504085061..17cdab76e9 100644--- a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts+++ b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts@@ -18,10 +18,10 @@ import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collimport { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'import { maxBy, minBy } from '@peertube/peertube-core-utils'+import { SelectOptionsItem } from '@pt-types'import { ChartData, ChartOptions, TooltipItem, TooltipModel } from 'chart.js'import { ChartModule } from 'primeng/chart'import { Subject, first, switchMap, tap } from 'rxjs'-import { SelectOptionsItem } from '@pt-types'import { ActorAvatarComponent } from '../../shared/shared-actor-image/actor-avatar.component'import { SearchInputComponent } from '../../shared/shared-forms/search-input.component'import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'@@ -119,7 +119,6 @@ export class MyVideoChannelsComponent implements OnInit {}onSearch (search: string) {- console.log(search)this.search = searchthis.resetDataAndReload()@@ -135,24 +134,12 @@ export class MyVideoChannelsComponent implements OnInit {this.loadMoreVideoChannels()}- async deleteVideoChannel (videoChannel: VideoChannel) {- const res = await this.confirmService.confirmWithExpectedInput(- $localize`Do you really want to delete ${videoChannel.displayName}?` +- `<br />` +- formatICU(- // eslint-disable-next-line max-len- $localize`It will delete {count, plural, =1 {1 video} other {{count} videos}} uploaded in this channel, and you will not be able to create another channel or account with the same name (${videoChannel.name})!`,- { count: videoChannel.videosCount }- ),- $localize`Please type the name of the video channel (${videoChannel.name}) to confirm`,- videoChannel.name,- $localize`Delete`- )- if (res === false) return-- this.videoChannelService.remove(videoChannel)+ deleteVideoChannel (videoChannel: VideoChannel) {+ this.videoChannelService.removeWithConfirmation(videoChannel).subscribe({- next: () => {+ next: removed => {+ if (!removed) return+this.videoChannels = this.videoChannels.filter(c => c.id !== videoChannel.id)this.notifier.success($localize`Video channel ${videoChannel.displayName} deleted.`)@@ -201,6 +188,8 @@ export class MyVideoChannelsComponent implements OnInit {const channel = this.videoChannels.find(c => c.id === channelWithStats.id)channel.viewsPerDay = channelWithStats.viewsPerDay+ channel.videosCount = channelWithStats.videosCount+ channel.totalViews = channelWithStats.totalViews}this.videoChannelsChartData = this.videoChannels.map(v => ({diff --git a/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.html b/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.htmlnew file mode 100644index 0000000000..8d5c7fa939--- /dev/null+++ b/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.html@@ -0,0 +1,46 @@+<my-table+ #table+ key="MyChannelOwnershipChangesComponent"+ [defaultColumns]="columns"+ i18n-paginatorText+ paginatorText="entries per page"+ [dataLoader]="dataLoader"+ columnConfig="false"+ [bulkActions]="bulkActions"+>+ <ng-template #totalTitle let-totalRecords>+ <ng-container i18n>{ totalRecords, plural, =0 {No channel ownership change} =1 {1 channel ownership change} other {{{ totalRecords | myNumberFormatter }} channel ownership changes}}</ng-container>+ </ng-template>++ <ng-template #tableCells let-entry>+ <td>+ <my-actor-cell [actor]="entry.videoChannel" actorType="channel" [displayAvatar]="true" [displayUsername]="true" target="_blank"></my-actor-cell>+ </td>++ <td>+ @if (isReceiver(entry)) {+ <span class="pt-badge badge-primary">TO YOU</span>+ } @else {+ <my-actor-cell [actor]="entry.nextOwnerAccount" actorType="account" [displayAvatar]="true" [displayUsername]="true" target="_blank"></my-actor-cell>+ }++ </td>++ <td>{{ entry.createdAt | ptDate: 'short' }}</td>++ <td>+ <span class="pt-badge" [ngClass]="getStateClass(entry.state.id)">{{ entry.state.label }}</span>+ </td>+ </ng-template>++ <ng-template #actionCell let-entry>+ <my-action-dropdown+ placement="bottom-right top-right left auto" container="body"+ i18n-label label="Actions" [actions]="actions" [entry]="entry"+ ></my-action-dropdown>+ </ng-template>++ <ng-template #noResults>+ <ng-container i18n>No ownership change request found.</ng-container>+ </ng-template>+</my-table>diff --git a/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.ts b/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.tsnew file mode 100644index 0000000000..19cb1d3501--- /dev/null+++ b/client/src/app/+my-library/my-ownership-changes/my-channel-ownership-changes/my-channel-ownership-changes.component.ts@@ -0,0 +1,122 @@+import { CommonModule, NgClass } from '@angular/common'+import { Component, inject, viewChild } from '@angular/core'+import { AuthService, Notifier } from '@app/core'+import { Account } from '@app/shared/shared-main/account/account.model'+import { buildDropdownSimpleAndBulkActions } from '@app/shared/shared-main/buttons/action-dropdown-helpers'+import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'+import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'+import { ActorCellComponent } from '@app/shared/shared-tables/actor-cell.component'+import { DataLoaderOptionsBase, TableColumnInfo, TableComponent } from '@app/shared/shared-tables/table.component'+import { ChangeOwnership, ChangeOwnershipState, ChangeOwnershipStateType } from '@peertube/peertube-models'+import { map } from 'rxjs'+import { NumberFormatterPipe } from '../../../shared/shared-main/common/number-formatter.pipe'++@Component({+ selector: 'my-channel-ownership-changes',+ templateUrl: './my-channel-ownership-changes.component.html',+ imports: [+ CommonModule,+ NgClass,+ PTDatePipe,+ NumberFormatterPipe,+ TableComponent,+ ActionDropdownComponent,+ ActorCellComponent+ ]+})+export class MyChannelOwnershipChangesComponent {+ private notifier = inject(Notifier)+ private changeOwnershipService = inject(ChangeOwnershipService)+ private authService = inject(AuthService)++ readonly table = viewChild<TableComponent<ChangeOwnership>>('table')++ actions: DropdownAction<ChangeOwnership>[][] = []+ bulkActions: DropdownAction<ChangeOwnership[]>[][] = []++ columns: TableColumnInfo<string>[] = [+ { id: 'channel', label: $localize`Channel`, sortable: false },+ { id: 'targetAccount', label: $localize`Target account`, sortable: false },+ { id: 'createdAt', label: $localize`Created`, sortable: true },+ { id: 'status', label: $localize`Status`, sortable: false }+ ]++ dataLoader: typeof this._dataLoader++ constructor () {+ this.dataLoader = this._dataLoader.bind(this)++ const { simpleActions, bulkActions } = buildDropdownSimpleAndBulkActions<ChangeOwnership>([+ [+ {+ label: $localize`Accept`,+ handler: changeOwnership => this.accept(changeOwnership),+ isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),+ enableBulk: true+ },+ {+ label: $localize`Reject`,+ handler: changeOwnership => this.reject(changeOwnership),+ isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),+ enableBulk: true+ }+ ]+ ])++ this.actions = simpleActions+ this.bulkActions = bulkActions+ }++ private canAcceptOrReject (changeOwnership: ChangeOwnership) {+ return this.isReceiver(changeOwnership) && changeOwnership.state.id === ChangeOwnershipState.PENDING+ }++ isReceiver (changeOwnership: ChangeOwnership) {+ return changeOwnership.nextOwnerAccount.id === this.authService.getUser().account.id+ }++ getStateClass (status: ChangeOwnershipStateType) {+ switch (status) {+ case ChangeOwnershipState.ACCEPTED:+ return 'badge-green'++ case ChangeOwnershipState.REJECTED:+ return 'badge-red'++ default:+ return 'badge-yellow'+ }+ }++ accept (entries: ChangeOwnership[]) {+ this.changeOwnershipService.acceptChannel(entries.map(entry => entry.id))+ .subscribe({+ next: () => this.table().loadData(),+ error: err => this.notifier.handleError(err)+ })+ }++ reject (entries: ChangeOwnership[]) {+ this.changeOwnershipService.rejectChannel(entries.map(entry => entry.id))+ .subscribe({+ next: () => this.table().loadData(),+ error: err => this.notifier.handleError(err)+ })+ }++ private _dataLoader (options: DataLoaderOptionsBase) {+ return this.changeOwnershipService.listOfChannels(options.pagination, options.sort)+ .pipe(+ map(resultList => ({+ data: resultList.data.map(change => ({+ ...change,++ initiatorAccount: new Account(change.initiatorAccount),+ nextOwnerAccount: new Account(change.nextOwnerAccount)+ })),+ total: resultList.total+ }))+ )+ }+}diff --git a/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.html b/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.htmlindex 27b73f8ec5..ab4c547be8 100644--- a/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.html+++ b/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.html@@ -1,48 +1,2 @@-<my-table- #table- key="MyOwnershipChangesComponent"- [defaultColumns]="columns"- i18n-paginatorText- paginatorText="entries per page"- [dataLoader]="dataLoader"- columnConfig="false"- [bulkActions]="bulkActions"->- <ng-template #totalTitle let-totalRecords>- <ng-container i18n>{ totalRecords, plural, =0 {No video ownership change} =1 {1 video ownership change} other {{{ totalRecords | myNumberFormatter }} video ownership changes}}</ng-container>- </ng-template>-- <ng-template #tableCells let-entry>- <td>- <my-video-cell [video]="entry.video" size="small"></my-video-cell>- </td>-- <td>- @if (isReceiver(entry)) {- <span class="pt-badge badge-primary">TO YOU</span>- } @else {- <my-actor-cell [actor]="entry.nextOwnerAccount" actorType="account" [displayAvatar]="true" [displayUsername]="true" target="_blank"></my-actor-cell>- }-- </td>-- <td>{{ entry.createdAt | ptDate: 'short' }}</td>-- <td>- <span class="pt-badge" [ngClass]="getStateClass(entry.state.id)">{{ entry.state.label }}</span>- </td>- </ng-template>-- <ng-template #actionCell let-entry>- <my-action-dropdown- placement="bottom-right top-right left auto" container="body"- i18n-label label="Actions" [actions]="actions" [entry]="entry"- ></my-action-dropdown>- </ng-template>-- <ng-template #noResults>- <ng-container i18n>No ownership change request found.</ng-container>- </ng-template>-</my-table>--<my-accept-change-ownership #myAcceptChangeOwnershipComponent (accepted)="accepted()"></my-accept-change-ownership>+<my-video-ownership-changes></my-video-ownership-changes>+<my-channel-ownership-changes></my-channel-ownership-changes>diff --git a/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.ts b/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.tsindex 01922cd130..43ab150702 100644--- a/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.ts+++ b/client/src/app/+my-library/my-ownership-changes/my-ownership-changes.component.ts@@ -1,128 +1,10 @@-import { CommonModule, NgClass } from '@angular/common'-import { Component, inject, viewChild } from '@angular/core'-import { AuthService, Notifier } from '@app/core'-import { Account } from '@app/shared/shared-main/account/account.model'-import { buildDropdownSimpleAndBulkActions } from '@app/shared/shared-main/buttons/action-dropdown-helpers'-import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'-import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'-import { ChangeOwnershipService } from '@app/shared/shared-main/video/change-ownership.service'-import { ActorCellComponent } from '@app/shared/shared-tables/actor-cell.component'-import { DataLoaderOptionsBase, TableColumnInfo, TableComponent } from '@app/shared/shared-tables/table.component'-import { ChangeOwnership, ChangeOwnershipState, ChangeOwnershipStateType } from '@peertube/peertube-models'-import { map } from 'rxjs'-import { ActorAvatarComponent } from '../../shared/shared-actor-image/actor-avatar.component'-import { NumberFormatterPipe } from '../../shared/shared-main/common/number-formatter.pipe'-import { VideoCellComponent } from '../../shared/shared-tables/video-cell.component'-import { MyAcceptChangeOwnershipComponent } from './my-accept-change-ownership/my-accept-change-ownership.component'+import { Component } from '@angular/core'+import { MyChannelOwnershipChangesComponent } from './my-channel-ownership-changes/my-channel-ownership-changes.component'+import { MyVideoOwnershipChangesComponent } from './my-video-ownership-changes/my-video-ownership-changes.component'@Component({templateUrl: './my-ownership-changes.component.html',- imports: [- CommonModule,- ActorAvatarComponent,- NgClass,- MyAcceptChangeOwnershipComponent,- PTDatePipe,- VideoCellComponent,- NumberFormatterPipe,- TableComponent,- ActionDropdownComponent,- ActorCellComponent- ]+ imports: [ MyVideoOwnershipChangesComponent, MyChannelOwnershipChangesComponent ]})export class MyOwnershipChangesComponent {- private notifier = inject(Notifier)- private changeOwnershipService = inject(ChangeOwnershipService)- private authService = inject(AuthService)-- readonly myAcceptChangeOwnershipComponent = viewChild<MyAcceptChangeOwnershipComponent>('myAcceptChangeOwnershipComponent')- readonly table = viewChild<TableComponent<ChangeOwnership>>('table')-- actions: DropdownAction<ChangeOwnership>[][] = []- bulkActions: DropdownAction<ChangeOwnership[]>[][] = []-- columns: TableColumnInfo<string>[] = [- { id: 'video', label: $localize`Video`, sortable: false },- { id: 'targetAccount', label: $localize`Target account`, sortable: false },- { id: 'createdAt', label: $localize`Created`, sortable: true },- { id: 'status', label: $localize`Status`, sortable: false }- ]-- dataLoader: typeof this._dataLoader-- constructor () {- this.dataLoader = this._dataLoader.bind(this)-- const { simpleActions, bulkActions } = buildDropdownSimpleAndBulkActions<ChangeOwnership>([- [- {- label: $localize`Accept`,- handler: changeOwnership => this.openAcceptModal(changeOwnership),- isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),- enableBulk: true- },- {- label: $localize`Reject`,- handler: changeOwnership => this.reject(changeOwnership),- isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),- enableBulk: true- }- ]- ])-- this.actions = simpleActions- this.bulkActions = bulkActions- }-- private canAcceptOrReject (changeOwnership: ChangeOwnership) {- return this.isReceiver(changeOwnership) && changeOwnership.state.id === ChangeOwnershipState.PENDING- }-- isReceiver (changeOwnership: ChangeOwnership) {- return changeOwnership.nextOwnerAccount.id === this.authService.getUser().account.id- }-- getStateClass (status: ChangeOwnershipStateType) {- switch (status) {- case ChangeOwnershipState.ACCEPTED:- return 'badge-green'-- case ChangeOwnershipState.REJECTED:- return 'badge-red'-- default:- return 'badge-yellow'- }- }-- openAcceptModal (entries: ChangeOwnership[]) {- this.myAcceptChangeOwnershipComponent().show(entries)- }-- accepted () {- this.table().loadData()- }-- reject (entries: ChangeOwnership[]) {- this.changeOwnershipService.rejectVideo(entries.map(entry => entry.id))- .subscribe({- next: () => this.table().loadData(),- error: err => this.notifier.handleError(err)- })- }-- private _dataLoader (options: DataLoaderOptionsBase) {- return this.changeOwnershipService.listOfVideos(options.pagination, options.sort)- .pipe(- map(resultList => ({- data: resultList.data.map(change => ({- ...change,-- initiatorAccount: new Account(change.initiatorAccount),- nextOwnerAccount: new Account(change.nextOwnerAccount)- })),- total: resultList.total- }))- )- }}diff --git a/client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.html b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.htmlsimilarity index 100%rename from client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.htmlrename to client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.htmldiff --git a/client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.scss b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.scsssimilarity index 100%rename from client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.scssrename to client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.scssdiff --git a/client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.ts b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.tssimilarity index 88%rename from client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.tsrename to client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.tsindex bbdaf4fdbb..af0a1e680d 100644--- a/client/src/app/+my-library/my-ownership-changes/my-accept-change-ownership/my-accept-change-ownership.component.ts+++ b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/accept-change-video-ownership.component.ts@@ -5,7 +5,7 @@ import { formatICU, listUserChannelsForSelect } from '@app/helpers'import { OWNERSHIP_CHANGE_CHANNEL_VALIDATOR } from '@app/shared/form-validators/video-ownership-change-validators'import { FormReactive } from '@app/shared/shared-forms/form-reactive'import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'-import { ChangeOwnershipService } from '@app/shared/shared-main/video/change-ownership.service'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'import { NgbModal } from '@ng-bootstrap/ng-bootstrap'import { ChangeOwnership } from '@peertube/peertube-models'import { SelectChannelItem } from '@pt-types'@@ -13,12 +13,12 @@ import { SelectChannelComponent } from '../../../shared/shared-forms/select/seleimport { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'@Component({- selector: 'my-accept-change-ownership',- templateUrl: './my-accept-change-ownership.component.html',- styleUrls: [ './my-accept-change-ownership.component.scss' ],+ selector: 'my-accept-change-video-ownership',+ templateUrl: './accept-change-video-ownership.component.html',+ styleUrls: [ './accept-change-video-ownership.component.scss' ],imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, SelectChannelComponent ]})-export class MyAcceptChangeOwnershipComponent extends FormReactive implements OnInit {+export class AcceptChangeVideoOwnershipComponent extends FormReactive implements OnInit {protected formReactiveService = inject(FormReactiveService)private changeOwnershipService = inject(ChangeOwnershipService)private notifier = inject(Notifier)diff --git a/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.html b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.htmlnew file mode 100644index 0000000000..b9c29ad3e6--- /dev/null+++ b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.html@@ -0,0 +1,48 @@+<my-table+ #table+ key="MyOwnershipChangesComponent"+ [defaultColumns]="columns"+ i18n-paginatorText+ paginatorText="entries per page"+ [dataLoader]="dataLoader"+ columnConfig="false"+ [bulkActions]="bulkActions"+>+ <ng-template #totalTitle let-totalRecords>+ <ng-container i18n>{ totalRecords, plural, =0 {No video ownership change} =1 {1 video ownership change} other {{{ totalRecords | myNumberFormatter }} video ownership changes}}</ng-container>+ </ng-template>++ <ng-template #tableCells let-entry>+ <td>+ <my-video-cell [video]="entry.video" size="small"></my-video-cell>+ </td>++ <td>+ @if (isReceiver(entry)) {+ <span class="pt-badge badge-primary">TO YOU</span>+ } @else {+ <my-actor-cell [actor]="entry.nextOwnerAccount" actorType="account" [displayAvatar]="true" [displayUsername]="true" target="_blank"></my-actor-cell>+ }++ </td>++ <td>{{ entry.createdAt | ptDate: 'short' }}</td>++ <td>+ <span class="pt-badge" [ngClass]="getStateClass(entry.state.id)">{{ entry.state.label }}</span>+ </td>+ </ng-template>++ <ng-template #actionCell let-entry>+ <my-action-dropdown+ placement="bottom-right top-right left auto" container="body"+ i18n-label label="Actions" [actions]="actions" [entry]="entry"+ ></my-action-dropdown>+ </ng-template>++ <ng-template #noResults>+ <ng-container i18n>No ownership change request found.</ng-container>+ </ng-template>+</my-table>++<my-accept-change-video-ownership #acceptChangeVideoOwnershipComponent (accepted)="accepted()"></my-accept-change-video-ownership>diff --git a/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.ts b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.tsnew file mode 100644index 0000000000..9d2768046e--- /dev/null+++ b/client/src/app/+my-library/my-ownership-changes/my-video-ownership-changes/my-video-ownership-changes.component.ts@@ -0,0 +1,127 @@+import { CommonModule, NgClass } from '@angular/common'+import { Component, inject, viewChild } from '@angular/core'+import { AuthService, Notifier } from '@app/core'+import { Account } from '@app/shared/shared-main/account/account.model'+import { buildDropdownSimpleAndBulkActions } from '@app/shared/shared-main/buttons/action-dropdown-helpers'+import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'+import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'+import { ActorCellComponent } from '@app/shared/shared-tables/actor-cell.component'+import { DataLoaderOptionsBase, TableColumnInfo, TableComponent } from '@app/shared/shared-tables/table.component'+import { ChangeOwnership, ChangeOwnershipState, ChangeOwnershipStateType } from '@peertube/peertube-models'+import { map } from 'rxjs'+import { NumberFormatterPipe } from '../../../shared/shared-main/common/number-formatter.pipe'+import { VideoCellComponent } from '../../../shared/shared-tables/video-cell.component'+import { AcceptChangeVideoOwnershipComponent } from './accept-change-video-ownership.component'++@Component({+ selector: 'my-video-ownership-changes',+ templateUrl: './my-video-ownership-changes.component.html',+ imports: [+ CommonModule,+ NgClass,+ AcceptChangeVideoOwnershipComponent,+ PTDatePipe,+ VideoCellComponent,+ NumberFormatterPipe,+ TableComponent,+ ActionDropdownComponent,+ ActorCellComponent+ ]+})+export class MyVideoOwnershipChangesComponent {+ private notifier = inject(Notifier)+ private changeOwnershipService = inject(ChangeOwnershipService)+ private authService = inject(AuthService)++ readonly acceptChangeVideoOwnershipComponent = viewChild<AcceptChangeVideoOwnershipComponent>('acceptChangeVideoOwnershipComponent')+ readonly table = viewChild<TableComponent<ChangeOwnership>>('table')++ actions: DropdownAction<ChangeOwnership>[][] = []+ bulkActions: DropdownAction<ChangeOwnership[]>[][] = []++ columns: TableColumnInfo<string>[] = [+ { id: 'video', label: $localize`Video`, sortable: false },+ { id: 'targetAccount', label: $localize`Target account`, sortable: false },+ { id: 'createdAt', label: $localize`Created`, sortable: true },+ { id: 'status', label: $localize`Status`, sortable: false }+ ]++ dataLoader: typeof this._dataLoader++ constructor () {+ this.dataLoader = this._dataLoader.bind(this)++ const { simpleActions, bulkActions } = buildDropdownSimpleAndBulkActions<ChangeOwnership>([+ [+ {+ label: $localize`Accept`,+ handler: changeOwnership => this.openAcceptModal(changeOwnership),+ isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),+ enableBulk: true+ },+ {+ label: $localize`Reject`,+ handler: changeOwnership => this.reject(changeOwnership),+ isDisplayed: changeOwnership => this.canAcceptOrReject(changeOwnership),+ enableBulk: true+ }+ ]+ ])++ this.actions = simpleActions+ this.bulkActions = bulkActions+ }++ private canAcceptOrReject (changeOwnership: ChangeOwnership) {+ return this.isReceiver(changeOwnership) && changeOwnership.state.id === ChangeOwnershipState.PENDING+ }++ isReceiver (changeOwnership: ChangeOwnership) {+ return changeOwnership.nextOwnerAccount.id === this.authService.getUser().account.id+ }++ getStateClass (status: ChangeOwnershipStateType) {+ switch (status) {+ case ChangeOwnershipState.ACCEPTED:+ return 'badge-green'++ case ChangeOwnershipState.REJECTED:+ return 'badge-red'++ default:+ return 'badge-yellow'+ }+ }++ openAcceptModal (entries: ChangeOwnership[]) {+ this.acceptChangeVideoOwnershipComponent().show(entries)+ }++ accepted () {+ this.table().loadData()+ }++ reject (entries: ChangeOwnership[]) {+ this.changeOwnershipService.rejectVideo(entries.map(entry => entry.id))+ .subscribe({+ next: () => this.table().loadData(),+ error: err => this.notifier.handleError(err)+ })+ }++ private _dataLoader (options: DataLoaderOptionsBase) {+ return this.changeOwnershipService.listOfVideos(options.pagination, options.sort)+ .pipe(+ map(resultList => ({+ data: resultList.data.map(change => ({+ ...change,++ initiatorAccount: new Account(change.initiatorAccount),+ nextOwnerAccount: new Account(change.nextOwnerAccount)+ })),+ total: resultList.total+ }))+ )+ }+}diff --git a/client/src/app/+my-library/my-videos/my-videos.component.ts b/client/src/app/+my-library/my-videos/my-videos.component.tsindex 5ad1b32cc2..6aae254dd9 100644--- a/client/src/app/+my-library/my-videos/my-videos.component.ts+++ b/client/src/app/+my-library/my-videos/my-videos.component.ts@@ -29,7 +29,6 @@ import {import { PrivacyBadgeComponent } from '../../shared/shared-video/privacy-badge.component'import { VideoNSFWBadgeComponent } from '../../shared/shared-video/video-nsfw-badge.component'import { VideoStateBadgeComponent } from '../../shared/shared-video/video-state-badge.component'-import { VideoChangeOwnershipComponent } from './modals/video-change-ownership.component'type ColumnName =| 'duration'@@ -80,7 +79,6 @@ export class MyVideosComponent implements OnInit, OnDestroy {private headerService = inject(HeaderService)private badgeService = inject(PeerTubeBadgeService)- readonly videoChangeOwnershipModal = viewChild<VideoChangeOwnershipComponent>('videoChangeOwnershipModal')readonly table = viewChild<TableComponent<Video, DataLoaderParameter, ColumnName, QueryParams>>('table')videosContainedInPlaylists: VideosExistInPlaylists = {}diff --git a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.htmlindex 7632137bbe..e4f4b2a934 100644--- a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html@@ -212,19 +212,19 @@</div></my-alert>}- </div>+ </div>- <my-video-change-ownership- #videoChangeOwnershipModal- [videoId]="videoEdit.getVideoAttributes().id" (requestSent)="onChangeOwnershipRequest($event)"- ></my-video-change-ownership>+ <my-send-change-ownership+ #sendChangeOwnershipModal+ [videoId]="videoEdit.getVideoAttributes().id" (requestSent)="onChangeOwnershipRequest($event)"+ ></my-send-change-ownership>- <div class="form-group">- <label i18n for="deleteVideo">Delete your video</label>- <div class="form-group-description" i18n>Warning: this is a definitive action!</div>+ <div class="form-group">+ <label i18n for="delte-video-button">Delete your video</label>+ <div class="form-group-description" i18n>Warning: this is a definitive action!</div>- <button type="button" class="peertube-button danger-button" (click)="deleteVideo()" i18n>Delete</button>- </div>+ <button type="button" id="delete-video-button" class="peertube-button danger-button" (click)="deleteVideo()" i18n>Delete</button></div>- }-+ </div>+ }+</form>diff --git a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.tsindex 2086115a04..9671a99e7a 100644--- a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts+++ b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts@@ -2,7 +2,6 @@ import { CommonModule } from '@angular/common'import { ChangeDetectorRef, Component, inject, NgZone, OnDestroy, OnInit, viewChild } from '@angular/core'import { AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'import { Router, RouterLink } from '@angular/router'-import { VideoChangeOwnershipComponent } from '@app/+my-library/my-videos/modals/video-change-ownership.component'import { AuthService, ConfirmService, HooksService, Notifier, PluginService, ServerService } from '@app/core'import { BuildFormArgument, BuildFormValidator } from '@app/shared/form-validators/form-validator.model'import {@@ -18,6 +17,8 @@ import {VIDEO_SUPPORT_VALIDATOR,VIDEO_TAGS_ARRAY_VALIDATOR} from '@app/shared/form-validators/video-validators'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'+import { SendChangeOwnershipComponent } from '@app/shared/shared-change-ownership/send-change-ownership.component'import { DynamicFormFieldComponent } from '@app/shared/shared-forms/dynamic-form-field.component'import { FormReactiveErrors, FormReactiveMessages, FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'import { FormValidatorService } from '@app/shared/shared-forms/form-validator.service'@@ -31,7 +32,6 @@ import { ButtonComponent } from '@app/shared/shared-main/buttons/button.componenimport { AlertComponent } from '@app/shared/shared-main/common/alert.component'import { PeerTubeTemplateDirective } from '@app/shared/shared-main/common/peertube-template.directive'import { InstanceService } from '@app/shared/shared-main/instance/instance.service'-import { ChangeOwnershipService } from '@app/shared/shared-main/video/change-ownership.service'import { VideoService } from '@app/shared/shared-main/video/video.service'import {ChangeOwnership,@@ -106,9 +106,9 @@ type Form = {GlobalIconComponent,MarkdownHintComponent,RouterLink,- VideoChangeOwnershipComponent,AlertComponent,- ButtonComponent+ ButtonComponent,+ SendChangeOwnershipComponent]})export class VideoMainInfoComponent implements OnInit, OnDestroy {@@ -129,7 +129,7 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {private router = inject(Router)private changeOwnershipService = inject(ChangeOwnershipService)- readonly videoChangeOwnershipModal = viewChild<VideoChangeOwnershipComponent>('videoChangeOwnershipModal')+ readonly sendChangeOwnershipModal = viewChild<SendChangeOwnershipComponent>('sendChangeOwnershipModal')form: FormGroup<Form>formErrors: FormReactiveErrors = {}@@ -509,7 +509,7 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {// ---------------------------------------------------------------------------showChangeOwnershipModal () {- this.videoChangeOwnershipModal().show()+ this.sendChangeOwnershipModal().show()}onChangeOwnershipRequest (ownershipChange: ChangeOwnership) {diff --git a/client/src/app/shared/shared-main/video/change-ownership.service.ts b/client/src/app/shared/shared-change-ownership/change-ownership.service.tssimilarity index 54%rename from client/src/app/shared/shared-main/video/change-ownership.service.tsrename to client/src/app/shared/shared-change-ownership/change-ownership.service.tsindex a5ce1dc964..17b8fde12c 100644--- a/client/src/app/shared/shared-main/video/change-ownership.service.ts+++ b/client/src/app/shared/shared-change-ownership/change-ownership.service.ts@@ -3,15 +3,15 @@ import { inject, Injectable } from '@angular/core'import { RestExtractor, RestPagination, RestService } from '@app/core'import {ChangeOwnership,- ChangeOwnershipAccept,ChangeOwnershipCreate,ChangeOwnershipStateType,+ ChangeVideoOwnershipAccept,ResultList} from '@peertube/peertube-models'import { SortMeta } from 'primeng/api'import { from, Observable } from 'rxjs'import { catchError, concatMap, toArray } from 'rxjs/operators'-import { environment } from '../../../../environments/environment'+import { environment } from '../../../environments/environment'@Injectable()export class ChangeOwnershipService {@@ -20,6 +20,7 @@ export class ChangeOwnershipService {private restExtractor = inject(RestExtractor)private static BASE_VIDEO_CHANGE_OWNERSHIP_URL = environment.apiUrl + '/api/v1/videos/'+ private static BASE_CHANNEL_CHANGE_OWNERSHIP_URL = environment.apiUrl + '/api/v1/video-channels/'sendVideoChangeRequest (id: number, username: string) {const url = ChangeOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + id + '/give-ownership'@@ -51,7 +52,7 @@ export class ChangeOwnershipService {.pipe(catchError(res => this.restExtractor.handleError(res)))}- acceptVideo (ids: number[], input: ChangeOwnershipAccept) {+ acceptVideo (ids: number[], input: ChangeVideoOwnershipAccept) {return from(ids).pipe(concatMap(id => {@@ -85,4 +86,65 @@ export class ChangeOwnershipService {}// ---------------------------------------------------------------------------++ sendChannelChangeRequest (channelName: string, username: string) {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + channelName + '/give-ownership'+ const body: ChangeOwnershipCreate = { username }++ return this.authHttp.post(url, body)+ .pipe(catchError(res => this.restExtractor.handleError(res)))+ }++ listOfChannels (pagination: RestPagination, sort: SortMeta): Observable<ResultList<ChangeOwnership>> {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + 'ownership'++ let params = new HttpParams()+ params = this.restService.addRestGetParams(params, pagination, sort)++ return this.authHttp.get<ResultList<ChangeOwnership>>(url, { params })+ .pipe(catchError(res => this.restExtractor.handleError(res)))+ }++ listFromChannel (channelName: string, state: ChangeOwnershipStateType): Observable<ResultList<ChangeOwnership>> {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + channelName + '/ownership'++ let params = new HttpParams()+ params = params.set('state', state)++ return this.authHttp.get<ResultList<ChangeOwnership>>(url, { params })+ .pipe(catchError(res => this.restExtractor.handleError(res)))+ }++ acceptChannel (ids: number[]) {+ return from(ids)+ .pipe(+ concatMap(id => {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + 'ownership/' + id + '/accept'++ return this.authHttp.post(url, {})+ }),+ toArray(),+ catchError(err => this.restExtractor.handleError(err))+ )+ }++ rejectChannel (ids: number[]) {+ return from(ids)+ .pipe(+ concatMap(id => {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + 'ownership/' + id + '/refuse'++ return this.authHttp.post(url, {})+ }),+ toArray(),+ catchError(err => this.restExtractor.handleError(err))+ )+ }++ cancelChannel (id: number) {+ const url = ChangeOwnershipService.BASE_CHANNEL_CHANGE_OWNERSHIP_URL + 'ownership/' + id++ return this.authHttp.delete(url)+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }}diff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.html b/client/src/app/shared/shared-change-ownership/send-change-ownership.component.htmlsimilarity index 91%rename from client/src/app/+my-library/my-videos/modals/video-change-ownership.component.htmlrename to client/src/app/shared/shared-change-ownership/send-change-ownership.component.htmlindex 45acb5e2f8..716f45c6ff 100644--- a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.html+++ b/client/src/app/shared/shared-change-ownership/send-change-ownership.component.html@@ -8,6 +8,8 @@</div><div class="modal-body" [formGroup]="form">+ <p i18n>Once the request is sent, the new owner will have to approve the transfer for it to be effective</p>+<div class="form-group"><label i18n for="next-ownership-username">Select the next owner</label>diff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.scss b/client/src/app/shared/shared-change-ownership/send-change-ownership.component.scsssimilarity index 100%rename from client/src/app/+my-library/my-videos/modals/video-change-ownership.component.scssrename to client/src/app/shared/shared-change-ownership/send-change-ownership.component.scssdiff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts b/client/src/app/shared/shared-change-ownership/send-change-ownership.component.tssimilarity index 64%rename from client/src/app/+my-library/my-videos/modals/video-change-ownership.component.tsrename to client/src/app/shared/shared-change-ownership/send-change-ownership.component.tsindex 64760eacb1..1c0aa6f976 100644--- a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts+++ b/client/src/app/shared/shared-change-ownership/send-change-ownership.component.ts@@ -2,29 +2,31 @@ import { Component, ElementRef, OnInit, inject, input, output, viewChild } fromimport { FormsModule, ReactiveFormsModule } from '@angular/forms'import { Notifier } from '@app/core'import { OWNERSHIP_CHANGE_USERNAME_VALIDATOR } from '@app/shared/form-validators/video-ownership-change-validators'+import { ChangeOwnershipService } from '@app/shared/shared-change-ownership/change-ownership.service'import { FormReactive } from '@app/shared/shared-forms/form-reactive'import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'import { UserAutoCompleteComponent } from '@app/shared/shared-forms/user-auto-complete.component'-import { ChangeOwnershipService } from '@app/shared/shared-main/video/change-ownership.service'import { NgbModal } from '@ng-bootstrap/ng-bootstrap'import { ChangeOwnership, ChangeOwnershipState } from '@peertube/peertube-models'import { AutoCompleteModule } from 'primeng/autocomplete'import { switchMap } from 'rxjs'-import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'+import { GlobalIconComponent } from '../shared-icons/global-icon.component'@Component({- selector: 'my-video-change-ownership',- templateUrl: './video-change-ownership.component.html',- styleUrls: [ './video-change-ownership.component.scss' ],+ selector: 'my-send-change-ownership',+ templateUrl: './send-change-ownership.component.html',+ styleUrls: [ './send-change-ownership.component.scss' ],imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, AutoCompleteModule, UserAutoCompleteComponent ]})-export class VideoChangeOwnershipComponent extends FormReactive implements OnInit {+export class SendChangeOwnershipComponent extends FormReactive implements OnInit {protected formReactiveService = inject(FormReactiveService)private changeOwnershipService = inject(ChangeOwnershipService)private notifier = inject(Notifier)private modalService = inject(NgbModal)- videoId = input.required<number>()+ videoId = input<number>()+ channelName = input<string>()+requestSent = output<ChangeOwnership>()readonly modal = viewChild<ElementRef>('modal')@@ -46,6 +48,14 @@ export class VideoChangeOwnershipComponent extends FormReactive implements OnIni}changeOwnership () {+ if (this.channelName()) {+ return this.changeChannelOwnership()+ }++ return this.changeVideoOwnership()+ }++ private changeVideoOwnership () {const username = this.form.value['username']this.changeOwnershipService@@ -59,4 +69,19 @@ export class VideoChangeOwnershipComponent extends FormReactive implements OnInierror: err => this.notifier.handleError(err)})}++ private changeChannelOwnership () {+ const username = this.form.value['username']++ this.changeOwnershipService+ .sendChannelChangeRequest(this.channelName(), username)+ .pipe(switchMap(() => this.changeOwnershipService.listFromChannel(this.channelName(), ChangeOwnershipState.PENDING)))+ .subscribe({+ next: ({ data }) => {+ this.requestSent.emit(data[0])+ },++ error: err => this.notifier.handleError(err)+ })+ }}diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss b/client/src/app/shared/shared-main/buttons/action-dropdown.component.scssindex 83df387ee8..3f31d9195f 100644--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss@@ -27,14 +27,24 @@ button {color: inherit;}+.primary-button {+ --co-fg: #{pvar(--on-primary-300)};+ --co-active-fg: #{pvar(--on-primary)};+}++.secondary-button {+ --co-fg: #{pvar(--fg-300)};+ --co-active-fg: #{pvar(--fg)};+}+.dropdown-toggle {- color: pvar(--fg-300);+ color: var(--co-fg);&:hover,&:active,&:focus,&:focus-visible {- color: pvar(--fg);+ color: var(--co-active-fg);}&::after {diff --git a/client/src/app/shared/shared-main/channel/video-channel.service.ts b/client/src/app/shared/shared-main/channel/video-channel.service.tsindex c54b15feb8..e39b9c1391 100644--- a/client/src/app/shared/shared-main/channel/video-channel.service.ts+++ b/client/src/app/shared/shared-main/channel/video-channel.service.ts@@ -1,6 +1,7 @@import { HttpClient, HttpParams } from '@angular/common/http'-import { Injectable, inject } from '@angular/core'-import { ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'+import { inject, Injectable } from '@angular/core'+import { ComponentPaginationLight, ConfirmService, RestExtractor, RestService, ServerService } from '@app/core'+import { formatICU } from '@app/helpers'import {ActorImage,ResultList,@@ -11,8 +12,8 @@ import {VideoChannelUpdate,VideosImportInChannelCreate} from '@peertube/peertube-models'-import { Observable, ReplaySubject } from 'rxjs'-import { catchError, map, tap } from 'rxjs/operators'+import { from, Observable, of, ReplaySubject } from 'rxjs'+import { catchError, map, switchMap, tap } from 'rxjs/operators'import { environment } from '../../../../environments/environment'import { Account } from '../account/account.model'import { AccountService } from '../account/account.service'@@ -24,6 +25,7 @@ export class VideoChannelService {private restService = inject(RestService)private restExtractor = inject(RestExtractor)private serverService = inject(ServerService)+ private confirmService = inject(ConfirmService)static BASE_VIDEO_CHANNEL_URL = environment.apiUrl + '/api/v1/video-channels/'@@ -89,9 +91,35 @@ export class VideoChannelService {.pipe(catchError(err => this.restExtractor.handleError(err)))}- remove (channel: VideoChannel) {- return this.authHttp.delete(VideoChannelService.BASE_VIDEO_CHANNEL_URL + channel.nameWithHost)- .pipe(catchError(err => this.restExtractor.handleError(err)))+ removeWithConfirmation (videoChannel: Pick<VideoChannel, 'name' | 'displayName' | 'videosCount' | 'nameWithHost'>) {+ const msg = $localize`Do you really want to delete ${videoChannel.displayName}?` ++ `<br />` ++ formatICU(+ // eslint-disable-next-line max-len+ $localize`It will delete {count, plural, =1 {1 video} other {{count} videos}} uploaded in this channel, and you will not be able to create another channel or account with the same name (${videoChannel.name})!`,+ { count: videoChannel.videosCount }+ )++ const confirmation = this.confirmService.confirmWithExpectedInput(+ msg,+ $localize`Please type the name of the video channel (${videoChannel.name}) to confirm`,+ videoChannel.name,+ $localize`Delete video channel`,+ $localize`Delete`+ )++ return from(confirmation)+ .pipe(+ switchMap(confirmed => {+ if (!confirmed) return of({ removed: false })++ return this.authHttp.delete(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost)+ .pipe(+ map(() => ({ removed: true })),+ catchError(err => this.restExtractor.handleError(err))+ )+ })+ )}// ---------------------------------------------------------------------------diff --git a/client/src/app/shared/shared-main/main-providers.ts b/client/src/app/shared/shared-main/main-providers.tsindex 4cac4c5f69..0132fb4331 100644--- a/client/src/app/shared/shared-main/main-providers.ts+++ b/client/src/app/shared/shared-main/main-providers.ts@@ -16,7 +16,7 @@ import { RedundancyService } from './video/redundancy.service'import { VideoChapterService } from './video/video-chapter.service'import { VideoFileTokenService } from './video/video-file-token.service'import { VideoImportService } from './video/video-import.service'-import { ChangeOwnershipService } from './video/change-ownership.service'+import { ChangeOwnershipService } from '../shared-change-ownership/change-ownership.service'import { VideoPasswordService } from './video/video-password.service'import { VideoResolver } from './video/video.resolver'import { VideoService } from './video/video.service'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 9ab2bf26d8..5fb9f1650c 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@@ -161,6 +161,9 @@ export class UserNotification {case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST:case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_ACCEPTED:case UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REJECTED:+ case UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST:+ case UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_ACCEPTED:+ case UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REJECTED:this.url = '/my-library/ownership'break}diff --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 23462c1e2d..e0a6bc4f41 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@@ -242,8 +242,8 @@</div>} @else if (isChannelCollabInvitation(n)) {<div class="action-button">- <my-button small="true" icon="tick" (click)="acceptChannelCollab()" i18n theme="primary">Accept</my-button>- <my-button small="true" icon="cross" (click)="rejectChannelCollab()" i18n theme="secondary">Decline</my-button>+ <my-button small="true" icon="tick" (click)="acceptChannelCollab($event)" i18n theme="primary">Accept</my-button>+ <my-button small="true" icon="cross" (click)="rejectChannelCollab($event)" i18n theme="secondary">Decline</my-button></div>} @else if (isChannelCollabAccepted(n)) {<div class="action-button">@@ -274,7 +274,7 @@<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+ <strong>{{ n.payload.changeOwnership.initiatorAccount.displayName }}</strong> requested to transfer ownership of video <strong>{{ n.payload.changeOwnership.video.name }}</strong> to you</div>}@@ -282,7 +282,7 @@<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>+ <strong>{{ n.payload.changeOwnership.nextOwnerAccount.displayName }}</strong> accepted the ownership change request for video <strong>{{ n.payload.changeOwnership.video.name }}</strong></div>}@@ -290,7 +290,50 @@<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>+ <strong>{{ n.payload.changeOwnership.nextOwnerAccount.displayName }}</strong> rejected the ownership change request for video <strong>{{ n.payload.changeOwnership.video.name }}</strong>+ </div>+ }++ @case (29) { <!-- UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST -->+ <my-global-icon iconName="user-add"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.changeOwnership.initiatorAccount.displayName }}</strong> requested to transfer ownership of channel <strong>{{ n.payload.changeOwnership.videoChannel.displayName }}</strong> to you+ </div>++ @if (isOwnershipChangeRejected(n)) {+ <div class="action-button">+ <my-global-icon iconName="cross"></my-global-icon>++ <div i18n>Request declined</div>+ </div>+ } @else if (isOwnershipChangeRequest(n)) {+ <div class="action-button">+ <my-button small="true" icon="tick" (click)="acceptChannelOwnershipChange($event)" i18n theme="primary">Accept</my-button>+ <my-button small="true" icon="cross" (click)="rejectChannelOwnershipChange($event)" i18n theme="secondary">Decline</my-button>+ </div>+ } @else if (isOwnershipChangeAccepted(n)) {+ <div class="action-button">+ <my-global-icon iconName="tick"></my-global-icon>++ <div i18n>Request accepted</div>+ </div>+ }+ }++ @case (30) { <!-- UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_ACCEPTED -->+ <my-global-icon iconName="tick"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.changeOwnership.nextOwnerAccount.displayName }}</strong> accepted the ownership change request for channel <strong>{{ n.payload.changeOwnership.videoChannel.displayName }}</strong>+ </div>+ }++ @case (31) { <!-- UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REJECTED -->+ <my-global-icon iconName="cross"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.changeOwnership.nextOwnerAccount.displayName }}</strong> rejected the ownership change request for channel <strong>{{ n.payload.changeOwnership.videoChannel.displayName }}</strong></div>}diff --git a/client/src/app/shared/shared-notifications/user-notification-content.component.ts b/client/src/app/shared/shared-notifications/user-notification-content.component.tsindex af4093a99e..be0cd00985 100644--- a/client/src/app/shared/shared-notifications/user-notification-content.component.ts+++ b/client/src/app/shared/shared-notifications/user-notification-content.component.ts@@ -2,15 +2,16 @@ import { CommonModule } from '@angular/common'import { Component, inject, input, output } from '@angular/core'import { Router } from '@angular/router'import { AuthService, Notifier } from '@app/core'-import { AbuseState, VideoChannelCollaboratorState, VideoState } from '@peertube/peertube-models'+import { AbuseState, ChangeOwnershipState, VideoChannelCollaboratorState, VideoState } from '@peertube/peertube-models'import { AccountOnChannelAvatarComponent } from '../shared-actor-image/account-on-channel-avatar.component'import { ActorAvatarComponent } from '../shared-actor-image/actor-avatar.component'+import { ChangeOwnershipService } from '../shared-change-ownership/change-ownership.service'import { GlobalIconComponent } from '../shared-icons/global-icon.component'import { ButtonComponent } from '../shared-main/buttons/button.component'+import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'import { VideoChannelService } from '../shared-main/channel/video-channel.service'import { FromNowPipe } from '../shared-main/date/from-now.pipe'import { UserNotification } from '../shared-main/users/user-notification.model'-import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'@Component({selector: 'my-user-notification-content',@@ -30,6 +31,7 @@ export class UserNotificationContentComponent {readonly router = inject(Router)readonly notifier = inject(Notifier)readonly channelService = inject(VideoChannelService)+ readonly changeOwnershipService = inject(ChangeOwnershipService)readonly authService = inject(AuthService)readonly notification = input.required<UserNotification>()@@ -70,9 +72,11 @@ export class UserNotificationContentComponent {return notification.payload.videoChannelCollaborator.state.id === VideoChannelCollaboratorState.REJECTED}- acceptChannelCollab () {+ acceptChannelCollab (event: Event) {const collab = this.n.payload.videoChannelCollaborator+ event.preventDefault()+ event.stopPropagation()this.buttonClicked.emit()this.channelService.acceptCollaboratorInvitation(collab.channel.name, collab.id)@@ -89,9 +93,11 @@ export class UserNotificationContentComponent {})}- rejectChannelCollab () {+ rejectChannelCollab (event: Event) {const collab = this.n.payload.videoChannelCollaborator+ event.preventDefault()+ event.stopPropagation()this.buttonClicked.emit()this.channelService.rejectCollaboratorInvitation(collab.channel.name, collab.id)@@ -103,4 +109,63 @@ export class UserNotificationContentComponent {error: err => this.notifier.handleError(err)})}++ // ---------------------------------------------------------------------------++ isOwnershipChangeRejected (notification: UserNotification) {+ if (!notification.payload.changeOwnership) return false++ return notification.payload.changeOwnership.state.id === ChangeOwnershipState.REJECTED+ }++ isOwnershipChangeAccepted (notification: UserNotification) {+ if (!notification.payload.changeOwnership) return false++ return notification.payload.changeOwnership.state.id === ChangeOwnershipState.ACCEPTED+ }++ isOwnershipChangeRequest (notification: UserNotification) {+ if (!notification.payload.changeOwnership) return false++ return notification.payload.changeOwnership.state.id === ChangeOwnershipState.PENDING+ }++ acceptChannelOwnershipChange (event: Event) {+ const changeOwnership = this.n.payload.changeOwnership++ event.preventDefault()+ event.stopPropagation()+ this.buttonClicked.emit()++ this.changeOwnershipService.acceptChannel([ changeOwnership.id ])+ .subscribe({+ next: () => {+ this.authService.refreshUserInformation()++ this.n.payload.changeOwnership.state.id = ChangeOwnershipState.ACCEPTED+ this.n.url = this.n.buildChannelUrl(changeOwnership.videoChannel)+ this.router.navigate(this.n.url)+ this.notifier.success($localize`You are now the owner of the channel ${changeOwnership.videoChannel.name}`)+ },++ error: err => this.notifier.handleError(err)+ })+ }++ rejectChannelOwnershipChange (event: Event) {+ const changeOwnership = this.n.payload.changeOwnership++ event.preventDefault()+ event.stopPropagation()+ this.buttonClicked.emit()++ this.changeOwnershipService.rejectChannel([ changeOwnership.id ])+ .subscribe({+ next: () => {+ this.n.payload.changeOwnership.state.id = ChangeOwnershipState.REJECTED+ },++ error: err => this.notifier.handleError(err)+ })+ }}diff --git a/client/src/main.ts b/client/src/main.tsindex 2a8325e35a..ef51946bda 100644--- a/client/src/main.ts+++ b/client/src/main.ts@@ -3,6 +3,7 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'import {ApplicationRef,enableProdMode,+ enableProfiling,importProvidersFrom,inject,provideAppInitializer,@@ -61,12 +62,14 @@ export function loadConfigFactory (if (environment.production) {enableProdMode()+} else {+ enableProfiling()}logger.registerServerSending(environment.apiUrl)-const bootstrap = () =>- bootstrapApplication(AppComponent, {+const bootstrap = () => {+ return bootstrapApplication(AppComponent, {providers: [provideZoneChangeDetection({ eventCoalescing: true }),@@ -119,33 +122,32 @@ const bootstrap = () =>}})]- })- .then(bootstrapModule => {- if (!environment.production) {- const applicationRef = bootstrapModule.injector.get(ApplicationRef)- const componentRef = applicationRef.components[0]-- // allows to run `ng.profiler.timeChangeDetection();`- enableDebugTools(componentRef)- }-- return bootstrapModule- })- .catch(err => {- try {- logger.error(err)- } catch (err2) {- console.error('Cannot log error', { err, err2 })+ }).then(bootstrapModule => {+ if (!environment.production) {+ const applicationRef = bootstrapModule.injector.get(ApplicationRef)+ const componentRef = applicationRef.components[0]++ // allows to run `ng.profiler.timeChangeDetection();`+ enableDebugTools(componentRef)+ }++ return bootstrapModule+ }).catch(err => {+ try {+ logger.error(err)+ } catch (err2) {+ console.error('Cannot log error', { err, err2 })+ }++ // Ensure we display an "incompatible message" on Angular bootstrap error+ setTimeout(() => {+ if (document.querySelector('my-app').innerHTML === '') {+ throw err}+ }, 1000)- // Ensure we display an "incompatible message" on Angular bootstrap error- setTimeout(() => {- if (document.querySelector('my-app').innerHTML === '') {- throw err- }- }, 1000)-- return null as any- })+ return null as any+ })+}bootstrap()diff --git a/packages/models/src/users/user-notification.model.ts b/packages/models/src/users/user-notification.model.tsindex 2084dc5494..02b9c0cc0d 100644--- a/packages/models/src/users/user-notification.model.ts+++ b/packages/models/src/users/user-notification.model.ts@@ -1,8 +1,8 @@import { FollowState } from '../actors/index.js'+import { ConstantLabel } from '../common/constant-label.model.js'import { AbuseStateType } from '../moderation/index.js'import { PluginType_Type } from '../plugins/index.js'-import { VideoChannelCollaboratorStateType } from '../videos/index.js'-import { ConstantLabel } from '../common/constant-label.model.js'+import { ChangeOwnershipStateType, VideoChannelCollaboratorStateType } from '../videos/index.js'import { VideoStateType } from '../videos/video-state.enum.js'import { UserNotificationData } from './user-notification-data.model.js'@@ -50,7 +50,11 @@ export const UserNotificationType = {VIDEO_OWNERSHIP_CHANGED_REQUEST: 26,VIDEO_OWNERSHIP_CHANGED_ACCEPTED: 27,- VIDEO_OWNERSHIP_CHANGED_REJECTED: 28+ VIDEO_OWNERSHIP_CHANGED_REJECTED: 28,++ CHANNEL_OWNERSHIP_CHANGED_REQUEST: 29,+ CHANNEL_OWNERSHIP_CHANGED_ACCEPTED: 30,+ CHANNEL_OWNERSHIP_CHANGED_REJECTED: 31} as constexport type UserNotificationType_Type = typeof UserNotificationType[keyof typeof UserNotificationType]@@ -176,9 +180,14 @@ export interface UserNotification {changeOwnership?: {id: number++ state: ConstantLabel<ChangeOwnershipStateType>+initiatorAccount: ActorInfonextOwnerAccount: ActorInfo+video: VideoInfo+ videoChannel: ActorInfo}createdAt: stringdiff --git a/packages/models/src/videos/change-ownership/change-ownership-accept.model.ts b/packages/models/src/videos/change-ownership/change-ownership-accept.model.tsdeleted file mode 100644index 3b78596fdc..0000000000--- a/packages/models/src/videos/change-ownership/change-ownership-accept.model.ts+++ /dev/null@@ -1,3 +0,0 @@-export interface ChangeOwnershipAccept {- channelId: number-}diff --git a/packages/models/src/videos/change-ownership/change-ownership.model.ts b/packages/models/src/videos/change-ownership/change-ownership.model.tsindex d90939690e..a4b7870d9d 100644--- a/packages/models/src/videos/change-ownership/change-ownership.model.ts+++ b/packages/models/src/videos/change-ownership/change-ownership.model.ts@@ -1,7 +1,7 @@import { Account } from '../../actors/index.js'import { ConstantLabel } from '../../common/constant-label.model.js'-import { VideoChannel } from '../channel/video-channel.model.js'-import { Video } from '../video.model.js'+import { VideoChannelSummary } from '../channel/video-channel.model.js'+import { VideoSummary } from '../video.model.js'export interface ChangeOwnership {id: number@@ -15,8 +15,8 @@ export interface ChangeOwnership {initiatorAccount: AccountnextOwnerAccount: Account- video: Video- videoChannel: VideoChannel+ video: VideoSummary+ videoChannel: VideoChannelSummarycreatedAt: Date}diff --git a/packages/models/src/videos/change-ownership/change-video-ownership-accept.model.ts b/packages/models/src/videos/change-ownership/change-video-ownership-accept.model.tsnew file mode 100644index 0000000000..7e4baf6a84--- /dev/null+++ b/packages/models/src/videos/change-ownership/change-video-ownership-accept.model.ts@@ -0,0 +1,3 @@+export interface ChangeVideoOwnershipAccept {+ channelId: number+}diff --git a/packages/models/src/videos/change-ownership/index.ts b/packages/models/src/videos/change-ownership/index.tsindex 7f76369e4b..111d54566e 100644--- a/packages/models/src/videos/change-ownership/index.ts+++ b/packages/models/src/videos/change-ownership/index.ts@@ -1,3 +1,3 @@-export * from './change-ownership-accept.model.js'+export * from './change-video-ownership-accept.model.js'export * from './change-ownership-create.model.js'export * from './change-ownership.model.js'diff --git a/packages/models/src/videos/video.model.ts b/packages/models/src/videos/video.model.tsindex bdf8924337..f7d4bbfae5 100644--- a/packages/models/src/videos/video.model.ts+++ b/packages/models/src/videos/video.model.ts@@ -138,3 +138,19 @@ export interface VideoDetails extends Video {embedPrivacyPolicy: ConstantLabel<VideoEmbedPrivacyPolicyType>}++export type VideoSummary =+ & Pick<+ Video,+ | 'id'+ | 'uuid'+ | 'shortUUID'+ | 'name'+ | 'nsfw'+ | 'publishedAt'+ | 'isLive'+ | 'thumbnails'+ >+ & {+ channel: VideoChannelSummary+ }diff --git a/packages/server-commands/src/videos/change-ownership-command.ts b/packages/server-commands/src/videos/change-ownership-command.tsindex 3c9da65848..adc52614d3 100644--- a/packages/server-commands/src/videos/change-ownership-command.ts+++ b/packages/server-commands/src/videos/change-ownership-command.ts@@ -2,7 +2,11 @@ import { ChangeOwnership, ChangeOwnershipStateType, HttpStatusCode, ResultList }import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'export class ChangeOwnershipCommand extends AbstractCommand {- create (+ // ---------------------------------------------------------------------------+ // Video ownership change+ // ---------------------------------------------------------------------------++ createVideo (options: OverrideCommandOptions & {videoId: number | stringusername: string@@ -21,14 +25,18 @@ export class ChangeOwnershipCommand extends AbstractCommand {})}- list (options: OverrideCommandOptions = {}) {+ listVideos (options: OverrideCommandOptions & {+ sort?: string+ start?: number+ count?: number+ } = {}) {const path = '/api/v1/videos/ownership'return this.getRequestBody<ResultList<ChangeOwnership>>({...options,path,- query: { sort: '-createdAt' },+ query: { sort: options.sort ?? '-createdAt', start: options.start, count: options.count },implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200})@@ -53,7 +61,7 @@ export class ChangeOwnershipCommand extends AbstractCommand {})}- accept (+ acceptVideo (options: OverrideCommandOptions & {ownershipId: numberchannelId: number@@ -72,7 +80,7 @@ export class ChangeOwnershipCommand extends AbstractCommand {})}- refuse (+ refuseVideo (options: OverrideCommandOptions & {ownershipId: number}@@ -89,7 +97,7 @@ export class ChangeOwnershipCommand extends AbstractCommand {})}- delete (+ deleteVideo (options: OverrideCommandOptions & {ownershipId: number}@@ -105,4 +113,114 @@ export class ChangeOwnershipCommand extends AbstractCommand {defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204})}++ // ---------------------------------------------------------------------------+ // Channel ownership change+ // ---------------------------------------------------------------------------++ createChannel (+ options: OverrideCommandOptions & {+ channelName: string+ username: string+ }+ ) {+ const { channelName, username } = options+ const path = '/api/v1/video-channels/' + channelName + '/give-ownership'++ return this.postBodyRequest({+ ...options,++ path,+ fields: { username },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ listChannels (options: OverrideCommandOptions & {+ sort?: string+ start?: number+ count?: number+ } = {}) {+ const path = '/api/v1/video-channels/ownership'++ return this.getRequestBody<ResultList<ChangeOwnership>>({+ ...options,++ path,+ query: { sort: options.sort ?? '-createdAt', start: options.start, count: options.count },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }++ listOfChannel (+ options: OverrideCommandOptions & {+ channelName: string+ state?: ChangeOwnershipStateType+ }+ ) {+ const { channelName, state } = options+ const path = '/api/v1/video-channels/' + channelName + '/ownership'++ return this.getRequestBody<ResultList<ChangeOwnership>>({+ ...options,++ path,+ query: { state, sort: '-createdAt' },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }++ acceptChannel (+ options: OverrideCommandOptions & {+ ownershipId: number+ }+ ) {+ const { ownershipId } = options+ const path = '/api/v1/video-channels/ownership/' + ownershipId + '/accept'++ return this.postBodyRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ refuseChannel (+ options: OverrideCommandOptions & {+ ownershipId: number+ }+ ) {+ const { ownershipId } = options+ const path = '/api/v1/video-channels/ownership/' + ownershipId + '/refuse'++ return this.postBodyRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ deleteChannel (+ options: OverrideCommandOptions & {+ ownershipId: number+ }+ ) {+ const { ownershipId } = options+ const path = '/api/v1/video-channels/ownership/' + ownershipId++ return this.deleteRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }}diff --git a/packages/server-commands/src/videos/playlists-command.ts b/packages/server-commands/src/videos/playlists-command.tsindex 85688a9edf..aed24d3ee9 100644--- a/packages/server-commands/src/videos/playlists-command.ts+++ b/packages/server-commands/src/videos/playlists-command.ts@@ -195,11 +195,16 @@ export class PlaylistsCommand extends AbstractCommand {options: OverrideCommandOptions & {displayName: stringprivacy?: VideoPlaylistPrivacyType+ channelId?: number}) {- const { displayName, privacy = VideoPlaylistPrivacy.PUBLIC } = options+ const { displayName, channelId, privacy = VideoPlaylistPrivacy.PUBLIC } = options- const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })+ let videoChannelId = channelId+ if (!videoChannelId && privacy === VideoPlaylistPrivacy.PUBLIC) {+ const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })+ videoChannelId = videoChannels[0].id+ }return this.create({...options,@@ -207,9 +212,7 @@ export class PlaylistsCommand extends AbstractCommand {attributes: {displayName,privacy,- videoChannelId: privacy === VideoPlaylistPrivacy.PUBLIC- ? videoChannels[0].id- : undefined+ videoChannelId}})}diff --git a/packages/tests/src/api/activitypub/refresher.ts b/packages/tests/src/api/activitypub/refresher.tsindex d5b66efd61..fd1a91f67a 100644--- a/packages/tests/src/api/activitypub/refresher.ts+++ b/packages/tests/src/api/activitypub/refresher.ts@@ -65,14 +65,15 @@ describe('Test AP refresher', function () {await doubleFollow(servers[0], servers[1])sqlCommandServer2 = new SQLCommand(servers[1])++ // Wait refresh min interval+ await wait(10000)})describe('Videos refresher', function () {it('Should remove a deleted remote video', async function () {this.timeout(60000)- await wait(10000)-// Change UUID so the remote server returns a 404await sqlCommandServer2.setVideoField(videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f')@@ -111,8 +112,6 @@ describe('Test AP refresher', function () {const command = servers[0].accounts- await wait(10000)-// Change actor name so the remote server returns a 404const to = servers[1].url + '/accounts/user2'await sqlCommandServer2.setActorField(to, 'preferredUsername', 'toto')@@ -131,8 +130,6 @@ describe('Test AP refresher', function () {it('Should remove a deleted playlist', async function () {this.timeout(60000)- await wait(10000)-// Change UUID so the remote server returns a 404await sqlCommandServer2.setPlaylistField(playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e')diff --git a/packages/tests/src/api/check-params/channel-change-ownership.ts b/packages/tests/src/api/check-params/channel-change-ownership.tsnew file mode 100644index 0000000000..bff452a827--- /dev/null+++ b/packages/tests/src/api/check-params/channel-change-ownership.ts@@ -0,0 +1,348 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { ChangeOwnershipState, HttpStatusCode } from '@peertube/peertube-models'+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@peertube/peertube-server-commands'+import { checkBadCountPagination, checkBadSort, checkBadStartPagination } from '@tests/shared/checks.js'+import { expect } from 'chai'++describe('Test channel change ownership API validator', function () {+ let server: PeerTubeServer+ let userToken: string+ let anotherUserToken: string+ let rootEditorToken: string+ let userEditorToken: string+ let ownershipChangeId: number++ // ---------------------------------------------------------------++ before(async function () {+ this.timeout(120000)++ server = await createSingleServer(1)++ await setAccessTokensToServers([ server ])++ await server.channels.create({ attributes: { name: 'root_channel_1' } })+ await server.channels.create({ attributes: { name: 'root_channel_2' } })++ userToken = await server.users.generateUserAndToken('user')+ anotherUserToken = await server.users.generateUserAndToken('another_user')+ rootEditorToken = await server.channelCollaborators.createEditor('root_editor', 'root_channel_1')+ userEditorToken = await server.channelCollaborators.createEditor('user_editor', 'user_channel')+ })++ describe('Create channel ownership change request', function () {+ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'user_channel',+ username: 'another_user',+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a channel of another user', async function () {+ for (const token of [ userToken, userEditorToken ]) {+ await server.changeOwnership.createChannel({+ channelName: 'root_channel',+ username: 'another_user',+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail with a non existing target', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'user_channel',+ username: 'unexisting',+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail with a non existing channel', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'non_existing_channel',+ username: 'another_user',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with the token of a collaborator', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'root_channel_1',+ username: 'user',+ token: rootEditorToken,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail if the target is already the owner of the video', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'root_channel_1',+ username: 'root',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.createChannel({ channelName: 'root_channel_1', username: 'user' })+ })++ it('Should fail to create a request for a channel with a pending ownership change request', async function () {+ await server.changeOwnership.createChannel({+ channelName: 'root_channel_1',+ username: 'user',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('List ownership change requests', function () {+ it('Should fail with bad pagination/sort params', async function () {+ await checkBadStartPagination(server.url, '/api/v1/video-channels/ownership', server.accessToken)+ await checkBadCountPagination(server.url, '/api/v1/video-channels/ownership', server.accessToken)+ await checkBadSort(server.url, '/api/v1/video-channels/ownership', server.accessToken)+ })++ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.listChannels({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+ })++ it('Should succeed with valid params', async function () {+ const { data } = await server.changeOwnership.listChannels({ token: userToken })+ ownershipChangeId = data[0].id+ })+ })++ describe('List ownership changes of a specific channel', function () {+ it('Should fail with bad pagination/sort params', async function () {+ await checkBadStartPagination(server.url, '/api/v1/video-channels/root_channel_1/ownership', server.accessToken)+ await checkBadCountPagination(server.url, '/api/v1/video-channels/root_channel_1/ownership', server.accessToken)+ await checkBadSort(server.url, '/api/v1/video-channels/root_channel_1/ownership', server.accessToken)+ })++ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.listOfChannel({+ channelName: 'root_channel_1',+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing channel', async function () {+ await server.changeOwnership.listOfChannel({+ channelName: 'non_existing_channel',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a channel of another user', async function () {+ for (const token of [ userToken, userEditorToken ]) {+ await server.changeOwnership.listOfChannel({+ channelName: 'root_channel_1',+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail with an invalid state parameter', async function () {+ await server.changeOwnership.listOfChannel({+ channelName: 'root_channel_1',+ state: 'INVALID_STATE' as any,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should succeed with valid params', async function () {+ for (const token of [ server.accessToken, rootEditorToken ]) {+ const { data, total } = await server.changeOwnership.listOfChannel({+ token,+ channelName: 'root_channel_1'+ })+ expect(total).to.be.a('number')+ expect(data).to.be.an('array')+ }+ })++ it('Should succeed with a state filter', async function () {+ const { data } = await server.changeOwnership.listOfChannel({+ channelName: 'root_channel_1',+ state: ChangeOwnershipState.PENDING+ })+ expect(data).to.be.an('array')+ })+ })++ describe('Reject ownership change request', function () {+ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.refuseChannel({+ ownershipId: ownershipChangeId,+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing ownership id', async function () {+ await server.changeOwnership.refuseChannel({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })+ })++ it('Should fail with a ownership of another user', async function () {+ for (const token of [ userEditorToken, anotherUserToken, rootEditorToken ]) {+ await server.changeOwnership.refuseChannel({+ ownershipId: ownershipChangeId,+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail to refuse using the video endpoint', async function () {+ await server.changeOwnership.refuseVideo({+ ownershipId: ownershipChangeId,+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.refuseChannel({ ownershipId: ownershipChangeId, token: userToken })+ })++ it('Should fail to reject a non pending request', async function () {+ await server.changeOwnership.refuseChannel({+ ownershipId: ownershipChangeId,+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('Accept ownership change request', function () {+ before(async function () {+ await server.changeOwnership.createChannel({+ channelName: 'root_channel_2',+ username: 'user'+ })++ const { data } = await server.changeOwnership.listChannels({ token: userToken, sort: '-createdAt' })+ ownershipChangeId = data[0].id+ })++ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.acceptChannel({+ ownershipId: ownershipChangeId,+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing ownership id', async function () {+ await server.changeOwnership.acceptChannel({+ ownershipId: 42,+ token: userToken,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a ownership of another user', async function () {+ for (const token of [ userEditorToken, anotherUserToken ]) {+ await server.changeOwnership.acceptChannel({+ ownershipId: ownershipChangeId,+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail with a non existing target', async function () {+ await server.changeOwnership.acceptChannel({+ ownershipId: 42,+ token: userToken,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.acceptChannel({+ ownershipId: ownershipChangeId,+ token: userToken+ })+ })++ it('Should fail to accept a non pending request', async function () {+ await server.changeOwnership.acceptChannel({+ ownershipId: ownershipChangeId,+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('Delete ownership change request', function () {+ let deleteOwnershipChangeId: number++ before(async function () {+ await server.changeOwnership.createChannel({ channelName: 'root_channel_2', username: 'another_user' })++ const { data } = await server.changeOwnership.listOfChannel({ channelName: 'root_channel_2' })+ deleteOwnershipChangeId = data[0].id+ })++ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.deleteChannel({+ ownershipId: deleteOwnershipChangeId,+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing ownership id', async function () {+ await server.changeOwnership.deleteChannel({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })+ })++ it('Should fail by another user', async function () {+ await server.changeOwnership.deleteChannel({+ ownershipId: deleteOwnershipChangeId,+ token: anotherUserToken,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail by an editor', async function () {+ await server.changeOwnership.deleteChannel({+ ownershipId: deleteOwnershipChangeId,+ token: rootEditorToken,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.deleteChannel({ ownershipId: deleteOwnershipChangeId })+ })++ it('Should fail to delete a non existing request', async function () {+ await server.changeOwnership.deleteChannel({+ ownershipId: deleteOwnershipChangeId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a non pending request', async function () {+ await server.changeOwnership.createChannel({ channelName: 'root_channel_2', username: 'another_user', token: userToken })++ const { data } = await server.changeOwnership.listOfChannel({ channelName: 'root_channel_2' })+ const newOwnershipChangeId = data[0].id++ await server.changeOwnership.acceptChannel({ ownershipId: newOwnershipChangeId, token: anotherUserToken })++ await server.changeOwnership.deleteChannel({ ownershipId: newOwnershipChangeId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ })+ })++ after(async function () {+ await cleanupTests([ server ])+ })+})diff --git a/packages/tests/src/api/check-params/video-change-ownership.ts b/packages/tests/src/api/check-params/video-change-ownership.tsindex db43147809..24f47b9feb 100644--- a/packages/tests/src/api/check-params/video-change-ownership.ts+++ b/packages/tests/src/api/check-params/video-change-ownership.ts@@ -37,7 +37,7 @@ describe('Test video change ownership API validator', function () {describe('Create video ownership change request', function () {it('Should fail if not authenticated', async function () {- await server.changeOwnership.create({+ await server.changeOwnership.createVideo({videoId: userVideo.id,username: 'another_user',token: null,@@ -47,7 +47,7 @@ describe('Test video change ownership API validator', function () {it('Should fail with a video of another user', async function () {for (const token of [ userToken, userEditorToken ]) {- await server.changeOwnership.create({+ await server.changeOwnership.createVideo({videoId: rootVideo.id,username: 'another_user',token,@@ -57,7 +57,7 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing target', async function () {- await server.changeOwnership.create({+ await server.changeOwnership.createVideo({videoId: userVideo.id,username: 'unexisting',token: userToken,@@ -66,20 +66,29 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing video', async function () {- await server.changeOwnership.create({+ await server.changeOwnership.createVideo({videoId: 42,username: 'another_user',expectedStatus: HttpStatusCode.NOT_FOUND_404})})+ it('Should fail if the target is already the owner of the video', async function () {+ await server.changeOwnership.createVideo({+ videoId: userVideo.id,+ username: 'user',+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+it('Should succeed with valid params', async function () {- await server.changeOwnership.create({ videoId: rootVideo2.id, username: 'user', token: rootEditorToken })- await server.changeOwnership.create({ videoId: rootVideo.id, username: 'user' })+ await server.changeOwnership.createVideo({ videoId: rootVideo2.id, username: 'user', token: rootEditorToken })+ await server.changeOwnership.createVideo({ videoId: rootVideo.id, username: 'user' })})it('Should fail to create a request for a video with a pending ownership change request', async function () {- await server.changeOwnership.create({+ await server.changeOwnership.createVideo({videoId: rootVideo2.id,username: 'user',token: rootEditorToken,@@ -90,11 +99,11 @@ describe('Test video change ownership API validator', function () {describe('List ownership change requests', function () {it('Should fail if not authenticated', async function () {- await server.changeOwnership.list({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+ await server.changeOwnership.listVideos({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})it('Should succeed with valid params', async function () {- const { data } = await server.changeOwnership.list({ token: userToken })+ const { data } = await server.changeOwnership.listVideos({ token: userToken })ownershipChangeId = data.find(d => d.video.id === rootVideo2.id).id})})@@ -134,11 +143,11 @@ describe('Test video change ownership API validator', function () {})it('Should succeed with valid params', async function () {- const { data, total } = await server.changeOwnership.listOfVideo({- videoId: rootVideo.id- })- expect(total).to.be.a('number')- expect(data).to.be.an('array')+ for (const token of [ rootEditorToken, server.accessToken ]) {+ const { data, total } = await server.changeOwnership.listOfVideo({ token, videoId: rootVideo.id })+ expect(total).to.be.a('number')+ expect(data).to.be.an('array')+ }})it('Should succeed with a state filter', async function () {@@ -152,7 +161,7 @@ describe('Test video change ownership API validator', function () {describe('Reject ownership change request', function () {it('Should fail if not authenticated', async function () {- await server.changeOwnership.refuse({+ await server.changeOwnership.refuseVideo({ownershipId: ownershipChangeId,token: null,expectedStatus: HttpStatusCode.UNAUTHORIZED_401@@ -160,12 +169,12 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing ownership id', async function () {- await server.changeOwnership.refuse({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })+ await server.changeOwnership.refuseVideo({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })})it('Should fail with a ownership of another user', async function () {for (const token of [ userEditorToken, anotherUserToken, rootEditorToken ]) {- await server.changeOwnership.refuse({+ await server.changeOwnership.refuseVideo({ownershipId: ownershipChangeId,token,expectedStatus: HttpStatusCode.FORBIDDEN_403@@ -174,11 +183,11 @@ describe('Test video change ownership API validator', function () {})it('Should succeed with valid params', async function () {- await server.changeOwnership.refuse({ ownershipId: ownershipChangeId, token: userToken })+ await server.changeOwnership.refuseVideo({ ownershipId: ownershipChangeId, token: userToken })})it('Should fail to reject a non pending request', async function () {- await server.changeOwnership.refuse({+ await server.changeOwnership.refuseVideo({ownershipId: ownershipChangeId,token: userToken,expectedStatus: HttpStatusCode.BAD_REQUEST_400@@ -190,9 +199,9 @@ describe('Test video change ownership API validator', function () {let targetChannelId: numberbefore(async function () {- await server.changeOwnership.create({ videoId: rootVideo2.id, username: 'user' })+ await server.changeOwnership.createVideo({ videoId: rootVideo2.id, username: 'user' })- const { data } = await server.changeOwnership.list({ token: userToken })+ const { data } = await server.changeOwnership.listVideos({ token: userToken })ownershipChangeId = data[0].idconst me = await server.users.getMyInfo({ token: userToken })@@ -200,7 +209,7 @@ describe('Test video change ownership API validator', function () {})it('Should fail if not authenticated', async function () {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: ownershipChangeId,token: null,channelId: targetChannelId,@@ -209,7 +218,7 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing ownership id', async function () {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: 42,token: userToken,channelId: targetChannelId,@@ -219,7 +228,7 @@ describe('Test video change ownership API validator', function () {it('Should fail with a ownership of another user', async function () {for (const token of [ userEditorToken, anotherUserToken ]) {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: ownershipChangeId,token,channelId: targetChannelId,@@ -229,7 +238,7 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing target', async function () {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: 42,token: userToken,channelId: targetChannelId,@@ -241,7 +250,7 @@ describe('Test video change ownership API validator', function () {const me = await server.users.getMyInfo({ token: anotherUserToken })const anotherUserChannelId = me.videoChannels[0].id- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: ownershipChangeId,token: userToken,channelId: anotherUserChannelId,@@ -250,7 +259,7 @@ describe('Test video change ownership API validator', function () {})it('Should succeed with valid params', async function () {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: ownershipChangeId,token: userToken,channelId: targetChannelId@@ -258,7 +267,7 @@ describe('Test video change ownership API validator', function () {})it('Should fail to accept a non pending request', async function () {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: ownershipChangeId,token: userToken,channelId: targetChannelId,@@ -275,14 +284,14 @@ describe('Test video change ownership API validator', function () {const { uuid } = await server.videos.quickUpload({ name: 'video', token: userToken })videoId = uuid- await server.changeOwnership.create({ videoId, username: 'another_user', token: userToken })+ await server.changeOwnership.createVideo({ videoId, username: 'another_user', token: userToken })const { data } = await server.changeOwnership.listOfVideo({ videoId })deleteOwnershipChangeId = data[0].id})it('Should fail if not authenticated', async function () {- await server.changeOwnership.delete({+ await server.changeOwnership.deleteVideo({ownershipId: deleteOwnershipChangeId,token: null,expectedStatus: HttpStatusCode.UNAUTHORIZED_401@@ -290,11 +299,11 @@ describe('Test video change ownership API validator', function () {})it('Should fail with a non existing ownership id', async function () {- await server.changeOwnership.delete({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })+ await server.changeOwnership.deleteVideo({ ownershipId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 })})it('Should fail with a video from another user', async function () {- await server.changeOwnership.delete({+ await server.changeOwnership.deleteVideo({ownershipId: deleteOwnershipChangeId,token: anotherUserToken,expectedStatus: HttpStatusCode.FORBIDDEN_403@@ -302,32 +311,32 @@ describe('Test video change ownership API validator', function () {})it('Should succeed with valid params', async function () {- await server.changeOwnership.delete({+ await server.changeOwnership.deleteVideo({token: userEditorToken,ownershipId: deleteOwnershipChangeId})})it('Should fail to delete a non existing request', async function () {- await server.changeOwnership.delete({+ await server.changeOwnership.deleteVideo({ownershipId: deleteOwnershipChangeId,expectedStatus: HttpStatusCode.NOT_FOUND_404})})it('Should fail with a non pending request', async function () {- await server.changeOwnership.create({ videoId, username: 'another_user', token: userToken })+ await server.changeOwnership.createVideo({ videoId, username: 'another_user', token: userToken })const { data } = await server.changeOwnership.listOfVideo({ videoId })const newOwnershipChangeId = data[0].id- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: newOwnershipChangeId,token: anotherUserToken,channelId: await server.channels.getDefaultId({ token: anotherUserToken })})- await server.changeOwnership.delete({+ await server.changeOwnership.deleteVideo({ownershipId: newOwnershipChangeId,expectedStatus: HttpStatusCode.BAD_REQUEST_400})diff --git a/packages/tests/src/api/check-params/videos.ts b/packages/tests/src/api/check-params/videos.tsindex 615451eda4..b7366eff64 100644--- a/packages/tests/src/api/check-params/videos.ts+++ b/packages/tests/src/api/check-params/videos.ts@@ -926,7 +926,7 @@ describe('Test videos API validator', function () {it('Should fail with the channel of another user if the video has pending ownership change', async function () {const video = await server.videos.quickUpload({ name: 'video to transfer', channelId: channelIdEditor, token: editorToken })- await server.changeOwnership.create({ videoId: video.id, username: 'root', token: editorToken })+ await server.changeOwnership.createVideo({ videoId: video.id, username: 'root', token: editorToken })// Can update video metadataawait server.videos.update({ id: video.id, attributes: { name: 'video to transfer 2' }, token: editorToken })@@ -941,8 +941,8 @@ describe('Test videos API validator', function () {token: editorToken})- const { data } = await server.changeOwnership.list()- await server.changeOwnership.refuse({ ownershipId: data[0].id })+ const { data } = await server.changeOwnership.listVideos()+ await server.changeOwnership.refuseVideo({ ownershipId: data[0].id })// Can update video channel to a channel of another user now there's no pending ownership changeawait server.videos.update({ id: video.id, attributes: { channelId }, token: editorToken })diff --git a/packages/tests/src/api/moderation/blocklist-notification.ts b/packages/tests/src/api/moderation/blocklist-notification.tsindex c5abc89644..5da45ffa23 100644--- a/packages/tests/src/api/moderation/blocklist-notification.ts+++ b/packages/tests/src/api/moderation/blocklist-notification.ts@@ -1,6 +1,5 @@/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'import { UserNotificationType, UserNotificationType_Type } from '@peertube/peertube-models'import {cleanupTests,@@ -10,9 +9,11 @@ import {setAccessTokensToServers,waitJobs} from '@peertube/peertube-server-commands'+import { expect } from 'chai'async function checkNotifications (server: PeerTubeServer, token: string, expected: UserNotificationType_Type[]) {const { data } = await server.notifications.list({ token, start: 0, count: 10, unread: true })+expect(data).to.have.lengthOf(expected.length)for (const type of expected) {@@ -26,13 +27,31 @@ describe('Test blocklist notifications', function () {let userToken1: stringlet userToken2: string++ let userToBlockToken: stringlet remoteUserToken: string+ let collaboratorId: number+ let videoOwnershipId: number+ let channelOwnershipId: number++ const allUser1Notifications = [+ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO,+ UserNotificationType.NEW_FOLLOW,+ UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL,+ UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST,+ UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ ]+async function resetState () {- try {+ if (videoOwnershipId) {await servers[1].subscriptions.remove({ token: remoteUserToken, uri: 'user1_channel@' + servers[0].host })await servers[1].subscriptions.remove({ token: remoteUserToken, uri: 'user2_channel@' + servers[0].host })- } catch {}++ await servers[0].channelCollaborators.remove({ channel: 'user_to_block_channel', token: userToBlockToken, id: collaboratorId })+ await servers[0].changeOwnership.deleteVideo({ token: userToBlockToken, ownershipId: videoOwnershipId })+ await servers[0].changeOwnership.deleteChannel({ token: userToBlockToken, ownershipId: channelOwnershipId })+ }await waitJobs(servers)@@ -59,6 +78,31 @@ describe('Test blocklist notifications', function () {await servers[1].subscriptions.add({ token: remoteUserToken, targetUri: 'user2_channel@' + servers[0].host })}+ {+ const { id } = await servers[0].channelCollaborators.invite({+ channel: 'user_to_block_channel',+ token: userToBlockToken,+ target: 'user1'+ })+ collaboratorId = id+ }++ {+ const { uuid } = await servers[0].videos.quickUpload({ name: 'video', token: userToBlockToken })+ await servers[0].changeOwnership.createVideo({ token: userToBlockToken, username: 'user1', videoId: uuid })+ await servers[0].changeOwnership.createChannel({ token: userToBlockToken, username: 'user1', channelName: 'user_to_block_channel' })++ {+ const { data } = await servers[0].changeOwnership.listVideos({ token: userToBlockToken })+ videoOwnershipId = data[0].id+ }++ {+ const { data } = await servers[0].changeOwnership.listChannels({ token: userToBlockToken })+ channelOwnershipId = data[0].id+ }+ }+await waitJobs(servers)}@@ -68,6 +112,8 @@ describe('Test blocklist notifications', function () {servers = await createMultipleServers(2)await setAccessTokensToServers(servers)+ userToBlockToken = await servers[0].users.generateUserAndToken('user_to_block')+{const user = { username: 'user1', password: 'password' }await servers[0].users.create({@@ -106,16 +152,28 @@ describe('Test blocklist notifications', function () {})it('Should have appropriate notifications', async function () {- const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken1, notifs)+ await checkNotifications(servers[0], userToken1, allUser1Notifications)})- it('Should block an account', async function () {+ it('Should block a remote account', async function () {await servers[0].blocklist.addToMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host })await waitJobs(servers)})- it('Should not have notifications from this account', async function () {+ it('Should not have notifications from this remote account', async function () {+ await checkNotifications(servers[0], userToken1, [+ UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL,+ UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST,+ UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ ])+ })++ it('Should block a local account', async function () {+ await servers[0].blocklist.addToMyBlocklist({ token: userToken1, account: 'user_to_block' })+ await waitJobs(servers)+ })++ it('Should not have notifications from this local account', async function () {await checkNotifications(servers[0], userToken1, [])})@@ -123,37 +181,43 @@ describe('Test blocklist notifications', function () {const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]await checkNotifications(servers[0], userToken2, notifs)+ })+ after(async function () {await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host })+ await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, account: 'user_to_block' })})})describe('User blocks another server', function () {before(async function () {- this.timeout(30000)-await resetState()})it('Should have appropriate notifications', async function () {- const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken1, notifs)+ await checkNotifications(servers[0], userToken1, allUser1Notifications)})- it('Should block an account', async function () {+ it('Should block a server', async function () {await servers[0].blocklist.addToMyBlocklist({ token: userToken1, server: servers[1].host })await waitJobs(servers)})- it('Should not have notifications from this account', async function () {- await checkNotifications(servers[0], userToken1, [])+ it('Should not have notifications from this server', async function () {+ await checkNotifications(servers[0], userToken1, [+ UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL,+ UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST,+ UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ ])})it('Should have notifications of this account on user 2', async function () {- const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]+ const notifications = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken2, notifs)+ await checkNotifications(servers[0], userToken2, notifications)+ })+ after(async function () {await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, server: servers[1].host })})})@@ -167,25 +231,41 @@ describe('Test blocklist notifications', function () {it('Should have appropriate notifications', async function () {{- const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken1, notifs)+ await checkNotifications(servers[0], userToken1, allUser1Notifications)}{- const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken2, notifs)+ const notifications = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]+ await checkNotifications(servers[0], userToken2, notifications)}})- it('Should block an account', async function () {+ it('Should block a remote account', async function () {await servers[0].blocklist.addToServerBlocklist({ account: 'user3@' + servers[1].host })await waitJobs(servers)})- it('Should not have notifications from this account', async function () {- await checkNotifications(servers[0], userToken1, [])+ it('Should not have notifications from this remote account', async function () {+ await checkNotifications(servers[0], userToken1, [+ UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL,+ UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST,+ UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ ])+await checkNotifications(servers[0], userToken2, [])+ })++ it('Should block a local account', async function () {+ await servers[0].blocklist.addToServerBlocklist({ account: 'user_to_block' })+ await waitJobs(servers)+ })++ it('Should not have notifications from this local account', async function () {+ await checkNotifications(servers[0], userToken1, [])+ })+ after(async function () {+ await servers[0].blocklist.removeFromServerBlocklist({ account: 'user_to_block' })await servers[0].blocklist.removeFromServerBlocklist({ account: 'user3@' + servers[1].host })})})@@ -199,13 +279,12 @@ describe('Test blocklist notifications', function () {it('Should have appropriate notifications', async function () {{- const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken1, notifs)+ await checkNotifications(servers[0], userToken1, allUser1Notifications)}{- const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]- await checkNotifications(servers[0], userToken2, notifs)+ const notifications = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ]+ await checkNotifications(servers[0], userToken2, notifications)}})@@ -215,7 +294,11 @@ describe('Test blocklist notifications', function () {})it('Should not have notifications from this account', async function () {- await checkNotifications(servers[0], userToken1, [])+ await checkNotifications(servers[0], userToken1, [+ UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL,+ UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST,+ UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST+ ])await checkNotifications(servers[0], userToken2, [])})})diff --git a/packages/tests/src/api/notifications/user-notifications.ts b/packages/tests/src/api/notifications/user-notifications.tsindex f429afd2da..e30a298916 100644--- a/packages/tests/src/api/notifications/user-notifications.ts+++ b/packages/tests/src/api/notifications/user-notifications.ts@@ -572,7 +572,7 @@ describe('Test user notifications', function () {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 servers[0].changeOwnership.createVideo({ videoId, username: nextOwner })await waitUntilNotification({server: servers[0],@@ -593,10 +593,10 @@ describe('Test user notifications', function () {})it('Should notify the video owner when ownership change is accepted', async function () {- const { data } = await servers[0].changeOwnership.list({ token: nextOwnerToken })+ const { data } = await servers[0].changeOwnership.listVideos({ token: nextOwnerToken })const acceptedAt = new Date()- await servers[0].changeOwnership.accept({+ await servers[0].changeOwnership.acceptVideo({token: nextOwnerToken,ownershipId: data[0].id,channelId: await servers[0].channels.getDefaultId({ token: nextOwnerToken })@@ -623,11 +623,11 @@ describe('Test user notifications', function () {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 })+ await servers[0].changeOwnership.createVideo({ videoId, username: nextNextOwner })+ const { data } = await servers[0].changeOwnership.listVideos({ token: nextNextOwnerToken })const rejectedAt = new Date()- await servers[0].changeOwnership.refuse({+ await servers[0].changeOwnership.refuseVideo({token: nextNextOwnerToken,ownershipId: data[0].id})diff --git a/packages/tests/src/api/videos/channel-activities.ts b/packages/tests/src/api/videos/channel-activities.tsindex 7a8b81f037..70bba9c95a 100644--- a/packages/tests/src/api/videos/channel-activities.ts+++ b/packages/tests/src/api/videos/channel-activities.ts@@ -705,7 +705,7 @@ describe('Test channel activities', function () {it('Should send an ownership request', async function () {const a = await getActivityAfterAction(() => {- return server.changeOwnership.create({ videoId: video.id, username: 'user_ownership_change' })+ return server.changeOwnership.createVideo({ videoId: video.id, username: 'user_ownership_change' })})expect(a.action.id).to.equal(VideoChannelActivityAction.SEND_OWNERSHIP_REQUEST)@@ -721,10 +721,10 @@ describe('Test channel activities', function () {})it('Should refuse an ownership request', async function () {- const { data } = await server.changeOwnership.list({ token: userToken })+ const { data } = await server.changeOwnership.listVideos({ token: userToken })const a = await getActivityAfterAction(async () => {- await server.changeOwnership.refuse({ ownershipId: data[0].id, token: userToken })+ await server.changeOwnership.refuseVideo({ ownershipId: data[0].id, token: userToken })})expect(a.action.id).to.equal(VideoChannelActivityAction.REFUSE_OWNERSHIP_REQUEST)@@ -735,11 +735,11 @@ describe('Test channel activities', function () {})it('Should accept an ownership request', async function () {- await server.changeOwnership.create({ videoId: video.id, username: 'user_ownership_change' })- const { data } = await server.changeOwnership.list({ token: userToken })+ await server.changeOwnership.createVideo({ videoId: video.id, username: 'user_ownership_change' })+ const { data } = await server.changeOwnership.listVideos({ token: userToken })const a = await getActivityAfterAction(async () => {- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({ownershipId: data[0].id,channelId: await server.channels.getIdOf({ channelName: 'user_ownership_change_channel' }),token: userToken@@ -756,12 +756,12 @@ describe('Test channel activities', function () {it('Should delete an ownership request', async function () {video = await server.videos.quickUpload({ name: 'video 2 for ownership change', channelId })- await server.changeOwnership.create({ videoId: video.id, username: 'user_ownership_change' })+ await server.changeOwnership.createVideo({ videoId: video.id, username: 'user_ownership_change' })const { data } = await server.changeOwnership.listOfVideo({ videoId: video.id })const changeOwnershipId = data[0].idconst a = await getActivityAfterAction(async () => {- await server.changeOwnership.delete({ ownershipId: changeOwnershipId })+ await server.changeOwnership.deleteVideo({ ownershipId: changeOwnershipId })})expect(a.action.id).to.equal(VideoChannelActivityAction.DELETE_OWNERSHIP_REQUEST)diff --git a/packages/tests/src/api/videos/channel-change-ownership.ts b/packages/tests/src/api/videos/channel-change-ownership.tsnew file mode 100644index 0000000000..86a32d2a29--- /dev/null+++ b/packages/tests/src/api/videos/channel-change-ownership.ts@@ -0,0 +1,354 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { ChangeOwnershipState, HttpStatusCode, VideoPlaylistPrivacy, VideoPrivacy } from '@peertube/peertube-models'+import {+ ChangeOwnershipCommand,+ cleanupTests,+ createMultipleServers,+ doubleFollow,+ PeerTubeServer,+ setAccessTokensToServers,+ setDefaultVideoChannel,+ waitJobs+} from '@peertube/peertube-server-commands'+import { expect } from 'chai'++describe('Test channel change ownership', function () {+ let servers: PeerTubeServer[] = []++ const firstUser = 'first'+ const secondUser = 'second'++ let firstUserToken = ''+ let secondUserToken = ''+ let unrelatedUserToken = ''++ let firstUserEditorToken = ''+ let secondUserEditorToken = ''++ let lastRequestId: number++ let videoId: string+ let playlistId: string+ let privatePlaylistId1: string+ let privatePlaylistId2: string++ let command: ChangeOwnershipCommand++ before(async function () {+ this.timeout(240000)++ servers = await createMultipleServers(2)+ await setAccessTokensToServers(servers)+ await setDefaultVideoChannel(servers)++ firstUserToken = await servers[0].users.generateUserAndToken(firstUser)+ secondUserToken = await servers[0].users.generateUserAndToken(secondUser)+ unrelatedUserToken = await servers[0].users.generateUserAndToken('unrelated')++ const { id } = await servers[0].channels.create({ token: firstUserToken, attributes: { name: 'first_user_channel' } })++ {+ const { uuid } = await servers[0].videos.quickUpload({ name: 'video 1', channelId: id })+ videoId = uuid+ }++ {+ const { uuid } = await servers[0].playlists.quickCreate({+ token: firstUserToken,+ displayName: 'playlist',+ privacy: VideoPrivacy.PUBLIC,+ channelId: id+ })+ await servers[0].playlists.addElement({ playlistId: uuid, attributes: { videoId } })++ playlistId = uuid+ }++ {+ const { uuid } = await servers[0].playlists.quickCreate({+ token: firstUserToken,+ displayName: 'private playlist 1',+ privacy: VideoPrivacy.PRIVATE,+ channelId: id+ })+ await servers[0].playlists.addElement({ playlistId: uuid, attributes: { videoId } })++ privatePlaylistId1 = uuid+ }++ {+ const { uuid } = await servers[0].playlists.quickCreate({+ token: firstUserToken,+ displayName: 'private playlist 2',+ privacy: VideoPrivacy.PRIVATE+ })+ await servers[0].playlists.addElement({ playlistId: uuid, attributes: { videoId } })++ privatePlaylistId2 = uuid+ }++ firstUserEditorToken = await servers[0].channelCollaborators.createEditor('first_user_editor', 'first_user_channel')+ secondUserEditorToken = await servers[0].channelCollaborators.createEditor('second_user_editor', secondUser + '_channel')++ command = servers[0].changeOwnership++ await doubleFollow(servers[0], servers[1])+ })++ it('Should not have channel change ownership', async function () {+ for (const token of [ firstUserToken, secondUserToken, unrelatedUserToken ]) {+ const body = await command.listChannels({ token })++ expect(body.total).to.equal(0)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(0)+ }+ })++ it('Should send a request to change ownership of a channel', async function () {+ await command.createChannel({ token: firstUserToken, channelName: 'first_user_channel', username: secondUser })+ })++ it('Should correctly list ownership change', async function () {+ {+ const body = await command.listChannels({ token: unrelatedUserToken })++ expect(body.total).to.equal(0)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(0)+ }++ for (const token of [ firstUserToken, secondUserToken ]) {+ const body = await command.listChannels({ token })++ expect(body.total).to.equal(1)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(1)++ const entry = body.data[0]++ expect(entry.createdAt).to.exist+ expect(entry.id).to.exist+ expect(entry.initiatorAccount.name).to.equal(firstUser)+ expect(entry.nextOwnerAccount.name).to.equal(secondUser)+ expect(entry.state.id).to.equal(ChangeOwnershipState.PENDING)+ expect(entry.videoChannel.name).to.equal('first_user_channel')+ expect(entry.videoChannel.avatars).to.be.an('array')++ lastRequestId = body.data[0].id+ }+ })++ it('Should not be possible to refuse the change of ownership from first user', async function () {+ await command.refuseChannel({ token: firstUserToken, ownershipId: lastRequestId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ })++ it('Should be possible to refuse the change of ownership from second user', async function () {+ await command.refuseChannel({ token: secondUserToken, ownershipId: lastRequestId })+ })++ it('Should send a new request to change ownership of a channel', async function () {+ await command.createChannel({ token: firstUserToken, channelName: 'first_user_channel', username: secondUser })+ })++ it('Should return two requests to change ownership for the second user', async function () {+ {+ const body = await command.listChannels({ token: unrelatedUserToken })++ expect(body.total).to.equal(0)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(0)+ }++ for (const token of [ firstUserToken, secondUserToken ]) {+ const body = await command.listChannels({ token })++ expect(body.total).to.equal(2)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(2)++ lastRequestId = body.data[0].id+ }+ })++ it('Should correctly sort/paginate ownership change list', async function () {+ const body = await command.listChannels({ token: secondUserToken, start: 1, count: 1, sort: 'createdAt' })++ expect(body.total).to.equal(2)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(1)++ const entry = body.data[0]+ expect(entry.state.id).to.equal(ChangeOwnershipState.PENDING)+ })++ it('Should not list change ownership requests for collaborators', async function () {+ const body = await command.listChannels({ token: firstUserEditorToken })++ expect(body.total).to.equal(0)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(0)+ })++ it('Should not list change ownership requests for collaborators of a channel of next owner', async function () {+ const body = await command.listChannels({ token: secondUserEditorToken })++ expect(body.total).to.equal(0)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(0)+ })++ it('Should not be possible to accept the change of ownership from first user', async function () {+ await command.acceptChannel({+ token: firstUserToken,+ ownershipId: lastRequestId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should be possible to accept the change of ownership from second user', async function () {+ await command.acceptChannel({ token: secondUserToken, ownershipId: lastRequestId })++ await waitJobs(servers)+ })++ it('Should have the owner of the channel updated', async function () {+ for (const server of servers) {+ const video = await server.videos.get({ id: videoId })++ expect(video.name).to.equal('video 1')+ expect(video.channel.name).to.equal('first_user_channel')+ expect(video.account.name).to.equal(secondUser)++ const channel = await server.channels.get({ channelName: 'first_user_channel@' + servers[0].host })++ expect(channel.name).to.equal('first_user_channel')+ expect(channel.ownerAccount.name).to.equal(secondUser)++ const playlist = await server.playlists.get({ playlistId })++ expect(playlist.displayName).to.equal('playlist')+ expect(playlist.privacy.id).to.equal(VideoPlaylistPrivacy.PUBLIC)+ expect(playlist.videoChannel.name).to.equal('first_user_channel')+ expect(playlist.ownerAccount.name).to.equal(secondUser)+ }++ {+ const playlist = await servers[0].playlists.get({ playlistId: privatePlaylistId1, token: servers[0].accessToken })++ expect(playlist.displayName).to.equal('private playlist 1')+ expect(playlist.privacy.id).to.equal(VideoPlaylistPrivacy.PRIVATE)+ expect(playlist.videoChannel.name).to.equal('first_user_channel')+ expect(playlist.ownerAccount.name).to.equal(secondUser)+ }++ {+ const playlist = await servers[0].playlists.get({ playlistId: privatePlaylistId2, token: servers[0].accessToken })++ expect(playlist.displayName).to.equal('private playlist 2')+ expect(playlist.privacy.id).to.equal(VideoPlaylistPrivacy.PRIVATE)+ expect(playlist.videoChannel).to.not.exist+ expect(playlist.ownerAccount.name).to.equal(firstUser)+ }+ })++ it('Should have kept collaborators on this channel', async function () {+ const collaborators = await servers[0].channelCollaborators.list({ channel: 'first_user_channel' })++ expect(collaborators.total).to.equal(1)+ expect(collaborators.data).to.be.an('array')+ expect(collaborators.data.length).to.equal(1)++ expect(collaborators.data[0].account.name).to.equal('first_user_editor')+ })++ it('Should transfer ownership of the channel to a collaborator', async function () {+ await command.createChannel({ token: secondUserToken, channelName: 'first_user_channel', username: 'first_user_editor' })++ const body = await command.listChannels({ token: firstUserEditorToken })+ const ownershipChangeId = body.data[0].id++ await command.acceptChannel({ token: firstUserEditorToken, ownershipId: ownershipChangeId })++ await waitJobs(servers)++ const collaborators = await servers[0].channelCollaborators.list({ channel: 'first_user_channel' })+ expect(collaborators.total).to.equal(0)++ const channel = await servers[0].channels.get({ channelName: 'first_user_channel' })++ expect(channel.name).to.equal('first_user_channel')+ expect(channel.ownerAccount.name).to.equal('first_user_editor')+ })++ it('Should delete an ownership change request', async function () {+ await command.createChannel({ token: firstUserEditorToken, channelName: 'first_user_channel', username: firstUser })++ const { data } = await command.listOfChannel({ token: firstUserEditorToken, channelName: 'first_user_channel' })+ const ownershipChangeId = data[0].id++ await command.deleteChannel({ ownershipId: ownershipChangeId, token: firstUserEditorToken })++ const bodyAfterDelete = await command.listOfChannel({+ token: firstUserEditorToken,+ channelName: 'first_user_channel',+ state: ChangeOwnershipState.PENDING+ })+ expect(bodyAfterDelete.total).to.equal(0)+ })++ it('Should list ownership changes for a specific channel', async function () {+ const body = await command.listOfChannel({ channelName: 'first_user_channel' })++ expect(body.total).to.equal(3)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(3)++ expect(body.data[0].videoChannel.name).to.equal('first_user_channel')++ expect(body.data.map(i => i.status)).to.have.members([ 'ACCEPTED', 'ACCEPTED', 'REFUSED' ])+ expect(body.data.map(i => i.state.label)).to.have.members([ 'Accepted', 'Accepted', 'Rejected' ])+ expect(body.data.map(i => i.state.id)).to.have.members([+ ChangeOwnershipState.ACCEPTED,+ ChangeOwnershipState.ACCEPTED,+ ChangeOwnershipState.REJECTED+ ])+ })++ it('Should list ownership changes with state filter', async function () {+ const body = await command.listOfChannel({+ channelName: 'first_user_channel',+ state: ChangeOwnershipState.ACCEPTED+ })++ expect(body.total).to.equal(2)++ for (const entry of body.data) {+ expect(entry.status).to.equal('ACCEPTED')+ expect(entry.state.id).to.equal(ChangeOwnershipState.ACCEPTED)+ expect(entry.state.label).to.equal('Accepted')+ }+ })++ it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () {+ const outOfQuotaToken = await servers[0].users.generateUserAndToken('out_of_quota_user')+ const outOfQuotaId = (await servers[0].users.getMyInfo({ token: outOfQuotaToken })).id+ await servers[0].users.update({ userId: outOfQuotaId, videoQuota: 0 })++ await command.createChannel({ token: firstUserEditorToken, channelName: 'first_user_channel', username: 'out_of_quota_user' })++ const body = await servers[0].changeOwnership.listChannels({ token: outOfQuotaToken })+ lastRequestId = body.data[0].id++ await servers[0].changeOwnership.acceptChannel({+ token: outOfQuotaToken,+ ownershipId: lastRequestId,+ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413+ })+ })++ after(async function () {+ await cleanupTests(servers)+ })+})diff --git a/packages/tests/src/api/videos/video-change-ownership.ts b/packages/tests/src/api/videos/video-change-ownership.tsindex d96c15c239..5c1e87e623 100644--- a/packages/tests/src/api/videos/video-change-ownership.ts+++ b/packages/tests/src/api/videos/video-change-ownership.ts@@ -96,7 +96,7 @@ describe('Test video change ownership - nominal', function () {it('Should not have video change ownership', async function () {for (const token of [ firstUserToken, secondUserToken, unrelatedUserToken ]) {- const body = await command.list({ token })+ const body = await command.listVideos({ token })expect(body.total).to.equal(0)expect(body.data).to.be.an('array')@@ -105,12 +105,12 @@ describe('Test video change ownership - nominal', function () {})it('Should send a request to change ownership of a video', async function () {- await command.create({ token: firstUserToken, videoId: servers[0].store.videoCreated.id, username: secondUser })+ await command.createVideo({ token: firstUserToken, videoId: servers[0].store.videoCreated.id, username: secondUser })})it('Should correctly list ownership change', async function () {{- const body = await command.list({ token: unrelatedUserToken })+ const body = await command.listVideos({ token: unrelatedUserToken })expect(body.total).to.equal(0)expect(body.data).to.be.an('array')@@ -118,31 +118,47 @@ describe('Test video change ownership - nominal', function () {}for (const token of [ firstUserToken, secondUserToken ]) {- const body = await command.list({ token })+ const body = await command.listVideos({ token })expect(body.total).to.equal(1)expect(body.data).to.be.an('array')expect(body.data.length).to.equal(1)+ const entry = body.data[0]++ expect(entry.createdAt).to.exist+ expect(entry.id).to.exist+ expect(entry.initiatorAccount.name).to.equal(firstUser)+ expect(entry.nextOwnerAccount.name).to.equal(secondUser)++ expect(entry.state.id).to.equal(ChangeOwnershipState.PENDING)+ expect(entry.video.name).to.equal('my super name')+ expect(entry.video.uuid).to.exist+ expect(entry.video.shortUUID).to.exist+ expect(entry.video.nsfw).to.be.true+ expect(entry.video.isLive).to.be.false+ expect(entry.video.publishedAt).to.exist+ expect(entry.video.thumbnails).to.have.length.above(2)+lastRequestId = body.data[0].id}})it('Should not be possible to refuse the change of ownership from first user', async function () {- await command.refuse({ token: firstUserToken, ownershipId: lastRequestId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await command.refuseVideo({ token: firstUserToken, ownershipId: lastRequestId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should be possible to refuse the change of ownership from second user', async function () {- await command.refuse({ token: secondUserToken, ownershipId: lastRequestId })+ await command.refuseVideo({ token: secondUserToken, ownershipId: lastRequestId })})it('Should send a new request to change ownership of a video', async function () {- await command.create({ token: firstUserToken, videoId: servers[0].store.videoCreated.id, username: secondUser })+ await command.createVideo({ token: firstUserToken, videoId: servers[0].store.videoCreated.id, username: secondUser })})it('Should return two requests to change ownership for the second user', async function () {{- const body = await command.list({ token: unrelatedUserToken })+ const body = await command.listVideos({ token: unrelatedUserToken })expect(body.total).to.equal(0)expect(body.data).to.be.an('array')@@ -150,7 +166,7 @@ describe('Test video change ownership - nominal', function () {}for (const token of [ firstUserToken, secondUserToken ]) {- const body = await command.list({ token })+ const body = await command.listVideos({ token })expect(body.total).to.equal(2)expect(body.data).to.be.an('array')@@ -160,16 +176,27 @@ describe('Test video change ownership - nominal', function () {}})+ it('Should correctly sort/paginate ownership change list', async function () {+ const body = await command.listVideos({ token: secondUserToken, start: 1, count: 1, sort: 'createdAt' })++ expect(body.total).to.equal(2)+ expect(body.data).to.be.an('array')+ expect(body.data.length).to.equal(1)++ const entry = body.data[0]+ expect(entry.state.id).to.equal(ChangeOwnershipState.PENDING)+ })+it('Should list change ownership requests for collaborators', async function () {- const body = await command.list({ token: firstUserEditorToken })+ const body = await command.listVideos({ token: firstUserEditorToken })expect(body.total).to.equal(2)expect(body.data).to.be.an('array')expect(body.data.length).to.equal(2)})- it('Should list change ownership requests for collaborators of a channel of next owner', async function () {- const body = await command.list({ token: secondUserEditorToken })+ it('Should not list change ownership requests for collaborators of a channel of next owner', async function () {+ const body = await command.listVideos({ token: secondUserEditorToken })expect(body.total).to.equal(0)expect(body.data).to.be.an('array')@@ -177,7 +204,7 @@ describe('Test video change ownership - nominal', function () {})it('Should not be possible to accept the change of ownership from first user', async function () {- await command.accept({+ await command.acceptVideo({token: firstUserToken,ownershipId: lastRequestId,channelId: secondUserChannelId,@@ -186,7 +213,7 @@ describe('Test video change ownership - nominal', function () {})it('Should be possible to accept the change of ownership from second user', async function () {- await command.accept({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId })+ await command.acceptVideo({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId })await waitJobs(servers)})@@ -202,9 +229,9 @@ describe('Test video change ownership - nominal', function () {})it('Should send a request to change ownership of a live', async function () {- await command.create({ token: firstUserToken, videoId: liveId, username: secondUser })+ await command.createVideo({ token: firstUserToken, videoId: liveId, username: secondUser })- const body = await command.list({ token: secondUserToken })+ const body = await command.listVideos({ token: secondUserToken })expect(body.total).to.equal(3)expect(body.data.length).to.equal(3)@@ -216,18 +243,18 @@ describe('Test video change ownership - nominal', function () {const { data } = await command.listOfVideo({ videoId: liveId })const ownershipChangeId = data[0].id- await command.delete({ ownershipId: ownershipChangeId, token: firstUserToken })+ await command.deleteVideo({ ownershipId: ownershipChangeId, token: firstUserToken })const bodyAfterDelete = await command.listOfVideo({ videoId: liveId, state: ChangeOwnershipState.PENDING })expect(bodyAfterDelete.total).to.equal(0)})it('Should accept a live ownership change', async function () {- await command.create({ token: firstUserToken, videoId: liveId, username: secondUser })- const body = await command.list({ token: secondUserToken })+ await command.createVideo({ token: firstUserToken, videoId: liveId, username: secondUser })+ const body = await command.listVideos({ token: secondUserToken })lastRequestId = body.data[0].id- await command.accept({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId })+ await command.acceptVideo({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId })await waitJobs(servers)@@ -308,17 +335,17 @@ describe('Test video change ownership - quota too small', function () {})it('Should send a request to change ownership of a video', async function () {- await server.changeOwnership.create({ token: firstUserToken, videoId: server.store.videoCreated.id, username: secondUser })+ await server.changeOwnership.createVideo({ token: firstUserToken, videoId: server.store.videoCreated.id, username: secondUser })})it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () {- const body = await server.changeOwnership.list({ token: secondUserToken })+ const body = await server.changeOwnership.listVideos({ token: secondUserToken })lastRequestId = body.data[0].idconst { videoChannels } = await server.users.getMyInfo({ token: secondUserToken })const channelId = videoChannels[0].id- await server.changeOwnership.accept({+ await server.changeOwnership.acceptVideo({token: secondUserToken,ownershipId: lastRequestId,channelId,diff --git a/server/core/controllers/api/video-channels/index.ts b/server/core/controllers/api/video-channels/index.tsindex 6573c5cedb..d67bbb8e0b 100644--- a/server/core/controllers/api/video-channels/index.ts+++ b/server/core/controllers/api/video-channels/index.ts@@ -8,6 +8,7 @@ import {VideosImportInChannelCreate} from '@peertube/peertube-models'import { pickCommonVideoQuery } from '@server/helpers/query.js'+import { scheduleActorRefreshIfNeeded } from '@server/lib/activitypub/actors/refresh.js'import { Hooks } from '@server/lib/plugins/hooks.js'import { reorderPlaylistOrElementsPosition, sendPlaylistPositionUpdateOfChannel } from '@server/lib/video-playlist.js'import { ActorFollowModel } from '@server/models/actor/actor-follow.js'@@ -58,9 +59,9 @@ import { guessAdditionalAttributesFromQuery } from '../../../models/video/formatimport { VideoChannelModel } from '../../../models/video/video-channel.js'import { VideoPlaylistModel } from '../../../models/video/video-playlist.js'import { VideoModel } from '../../../models/video/video.js'+import { ownershipChannelRouter } from './ownership.js'import { channelCollaborators } from './video-channel-collaborators.js'import { videoChannelLogosRouter } from './video-channel-logos.js'-import { scheduleActorRefreshIfNeeded } from '@server/lib/activitypub/actors/refresh.js'const auditLogger = auditLoggerFactory('channels')@@ -69,6 +70,7 @@ const videoChannelRouter = express.Router()videoChannelRouter.use(apiRateLimiter)videoChannelRouter.use(channelCollaborators)videoChannelRouter.use(videoChannelLogosRouter)+videoChannelRouter.use(ownershipChannelRouter)videoChannelRouter.get('/',diff --git a/server/core/controllers/api/video-channels/ownership.ts b/server/core/controllers/api/video-channels/ownership.tsnew file mode 100644index 0000000000..bda5bc9182--- /dev/null+++ b/server/core/controllers/api/video-channels/ownership.ts@@ -0,0 +1,234 @@+import { ChangeOwnershipState, ChangeOwnershipStateType, HttpStatusCode, VideoChannelActivityAction } from '@peertube/peertube-models'+import { getAuthUser } from '@server/helpers/express-utils.js'+import { VideoChannelActivityModel } from '@server/models/video/video-channel-activity.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'+import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'+import express from 'express'+import { logger } from '../../../helpers/logger.js'+import { getFormattedObjects } from '../../../helpers/utils.js'+import { sequelizeTypescript } from '../../../initializers/database.js'+import { sendUpdateActor } from '../../../lib/activitypub/send/index.js'+import { Notifier } from '../../../lib/notifier/notifier.js'+import {+ acceptChannelChangeOwnershipValidator,+ acceptOrRejectChangeOwnershipValidatorFactory,+ asyncMiddleware,+ asyncRetryTransactionMiddleware,+ authenticate,+ changeChannelOwnershipValidator,+ changeOwnershipSortValidator,+ deleteChangeChannelOwnershipValidator,+ listChannelOwnershipChangesValidator,+ paginationValidator,+ setDefaultPagination+} from '../../../middlewares/index.js'+import { ChangeOwnershipModel } from '../../../models/video/change-ownership.js'+import { VideoChannelModel } from '../../../models/video/video-channel.js'++const ownershipChannelRouter = express.Router()++ownershipChannelRouter.post(+ '/:handle/give-ownership',+ authenticate,+ asyncMiddleware(changeChannelOwnershipValidator),+ asyncRetryTransactionMiddleware(createChangeOwnershipRequest)+)++ownershipChannelRouter.get(+ '/:handle/ownership',+ authenticate,+ paginationValidator,+ setDefaultPagination,+ changeOwnershipSortValidator,+ asyncMiddleware(listChannelOwnershipChangesValidator),+ asyncRetryTransactionMiddleware(listChannelOwnershipChanges)+)++ownershipChannelRouter.get(+ '/ownership',+ authenticate,+ paginationValidator,+ setDefaultPagination,+ changeOwnershipSortValidator,+ asyncRetryTransactionMiddleware(listAccountChannelOwnershipChanges)+)++ownershipChannelRouter.post(+ '/ownership/:id/accept',+ authenticate,+ asyncMiddleware(acceptOrRejectChangeOwnershipValidatorFactory('channel')),+ asyncMiddleware(acceptChannelChangeOwnershipValidator),+ asyncRetryTransactionMiddleware(acceptOwnershipChange)+)++ownershipChannelRouter.post(+ '/ownership/:id/refuse',+ authenticate,+ asyncMiddleware(acceptOrRejectChangeOwnershipValidatorFactory('channel')),+ asyncRetryTransactionMiddleware(refuseOwnershipChange)+)++ownershipChannelRouter.delete(+ '/ownership/:id',+ authenticate,+ asyncMiddleware(deleteChangeChannelOwnershipValidator),+ asyncRetryTransactionMiddleware(deleteOwnershipChange)+)++// ---------------------------------------------------------------------------++export {+ ownershipChannelRouter+}++// ---------------------------------------------------------------------------++async function createChangeOwnershipRequest (req: express.Request, res: express.Response) {+ const channel = res.locals.videoChannel+ const initiatorAccountId = res.locals.oauth.token.User.Account.id+ const nextOwner = res.locals.changeOwnershipNextOwner++ const ownershipChange = await sequelizeTypescript.transaction(async t => {+ const ownershipChange = await ChangeOwnershipModel.create({+ initiatorAccountId,+ nextOwnerAccountId: nextOwner.id,+ videoChannelId: channel.id,+ state: ChangeOwnershipState.PENDING+ }, { transaction: t })++ await VideoChannelActivityModel.addChannelOwnershipChangeActivity({+ action: VideoChannelActivityAction.SEND_OWNERSHIP_REQUEST,+ user: res.locals.oauth.token.User,+ channel: channel,+ targetAccount: nextOwner,+ transaction: t+ })++ return ownershipChange+ })++ const ownershipChangeFull = await ChangeOwnershipModel.load(ownershipChange.id)++ Notifier.Instance.notifyOfRequestedChannelOwnershipChange(ownershipChangeFull)++ logger.info('Ownership change for channel %s created.', channel.Actor.preferredUsername)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}++async function listChannelOwnershipChanges (req: express.Request, res: express.Response) {+ const videoChannelId = res.locals.videoChannel.id+ const state = req.query.state as ChangeOwnershipStateType++ const resultList = await ChangeOwnershipModel.listForChannelApi({+ videoChannelId,+ state,+ start: req.query.start,+ count: req.query.count,+ sort: req.query.sort || 'createdAt'+ })++ return res.json(getFormattedObjects(resultList.data, resultList.total))+}++async function listAccountChannelOwnershipChanges (req: express.Request, res: express.Response) {+ const currentAccountId = getAuthUser(res).Account.id++ const resultList = await ChangeOwnershipModel.listForChannelApi({+ accountId: currentAccountId,+ start: req.query.start,+ count: req.query.count,+ sort: req.query.sort || 'createdAt'+ })++ return res.json(getFormattedObjects(resultList.data, resultList.total))+}++function acceptOwnershipChange (req: express.Request, res: express.Response) {+ return sequelizeTypescript.transaction(async t => {+ const changeOwnership = res.locals.changeOwnership+ const channel = await VideoChannelModel.load(changeOwnership.VideoChannel.id, t)+ const previousOwnerId = channel.accountId++ channel.accountId = changeOwnership.NextOwner.id+ await channel.save({ transaction: t })++ // Update owner of channel playlists+ await VideoPlaylistModel.updateOwnerOfChannelPlaylists({+ currentOwnerId: previousOwnerId,+ nextOwnerId: changeOwnership.NextOwner.id,+ videoChannelId: channel.id,+ transaction: t+ })++ // Remove collaborator if the next owner is a collaborator of the channel+ const collaborator = await VideoChannelCollaboratorModel.loadByCollaboratorAccountName({+ accountName: changeOwnership.NextOwner.Actor.preferredUsername,+ channelId: channel.id,+ transaction: t+ })+ if (collaborator) await collaborator.destroy({ transaction: t })++ const channelFull = await VideoChannelModel.loadAndPopulateAccount(channel.id, t)+ await sendUpdateActor(channelFull, t)++ changeOwnership.state = ChangeOwnershipState.ACCEPTED+ await changeOwnership.save({ transaction: t })++ await VideoChannelActivityModel.addChannelOwnershipChangeActivity({+ action: VideoChannelActivityAction.ACCEPT_OWNERSHIP_REQUEST,+ user: res.locals.oauth.token.User,+ channel: channelFull,+ targetAccount: changeOwnership.NextOwner,+ transaction: t+ })++ Notifier.Instance.notifyOfAcceptedChannelOwnershipChange(changeOwnership)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+ })+}++function refuseOwnershipChange (req: express.Request, res: express.Response) {+ return sequelizeTypescript.transaction(async t => {+ const changeOwnership = res.locals.changeOwnership++ changeOwnership.state = ChangeOwnershipState.REJECTED+ await changeOwnership.save({ transaction: t })++ const channel = await VideoChannelModel.loadAndPopulateAccount(changeOwnership.videoChannelId, t)++ await VideoChannelActivityModel.addChannelOwnershipChangeActivity({+ action: VideoChannelActivityAction.REFUSE_OWNERSHIP_REQUEST,+ user: res.locals.oauth.token.User,+ channel,+ targetAccount: changeOwnership.NextOwner,+ transaction: t+ })++ Notifier.Instance.notifyOfRejectedChannelOwnershipChange(changeOwnership)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+ })+}++function deleteOwnershipChange (req: express.Request, res: express.Response) {+ return sequelizeTypescript.transaction(async t => {+ const changeOwnership = res.locals.changeOwnership+ const channel = await VideoChannelModel.loadAndPopulateAccount(changeOwnership.videoChannelId, t)++ await changeOwnership.destroy({ transaction: t })++ await VideoChannelActivityModel.addChannelOwnershipChangeActivity({+ action: VideoChannelActivityAction.DELETE_OWNERSHIP_REQUEST,+ user: res.locals.oauth.token.User,+ channel,+ targetAccount: changeOwnership.NextOwner,+ transaction: t+ })++ logger.info('Channel ownership change request %d deleted.', changeOwnership.id)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+ })+}diff --git a/server/core/controllers/api/videos/ownership.ts b/server/core/controllers/api/videos/ownership.tsindex d03a8fb9ad..4827fd4e83 100644--- a/server/core/controllers/api/videos/ownership.ts+++ b/server/core/controllers/api/videos/ownership.ts@@ -10,16 +10,17 @@ import { sendUpdateVideo } from '../../../lib/activitypub/send/index.js'import { changeVideoChannelShare } from '../../../lib/activitypub/share.js'import { Notifier } from '../../../lib/notifier/notifier.js'import {+ acceptOrRejectChangeOwnershipValidatorFactory,+ acceptVideoChangeOwnershipValidator,asyncMiddleware,asyncRetryTransactionMiddleware,authenticate,- paginationValidator,- setDefaultPagination,- acceptVideoChangeOwnershipValidator,+ changeOwnershipSortValidator,changeVideoOwnershipValidator,- deleteChangeOwnershipValidator,+ deleteChangeVideoOwnershipValidator,listVideoOwnershipChangesValidator,- acceptOrRejectChangeOwnershipValidator+ paginationValidator,+ setDefaultPagination} from '../../../middlewares/index.js'import { ChangeOwnershipModel } from '../../../models/video/change-ownership.js'import { VideoChannelModel } from '../../../models/video/video-channel.js'@@ -37,9 +38,10 @@ ownershipVideoRouter.post(ownershipVideoRouter.get('/:videoId/ownership',authenticate,- asyncMiddleware(listVideoOwnershipChangesValidator),paginationValidator,setDefaultPagination,+ changeOwnershipSortValidator,+ asyncMiddleware(listVideoOwnershipChangesValidator),asyncRetryTransactionMiddleware(listVideoOwnershipChanges))@@ -54,7 +56,7 @@ ownershipVideoRouter.get(ownershipVideoRouter.post('/ownership/:id/accept',authenticate,- asyncMiddleware(acceptOrRejectChangeOwnershipValidator),+ asyncMiddleware(acceptOrRejectChangeOwnershipValidatorFactory('video')),asyncMiddleware(acceptVideoChangeOwnershipValidator),asyncRetryTransactionMiddleware(acceptOwnershipChange))@@ -62,14 +64,14 @@ ownershipVideoRouter.post(ownershipVideoRouter.post('/ownership/:id/refuse',authenticate,- asyncMiddleware(acceptOrRejectChangeOwnershipValidator),+ asyncMiddleware(acceptOrRejectChangeOwnershipValidatorFactory('video')),asyncRetryTransactionMiddleware(refuseOwnershipChange))ownershipVideoRouter.delete('/ownership/:id',authenticate,- asyncMiddleware(deleteChangeOwnershipValidator),+ asyncMiddleware(deleteChangeVideoOwnershipValidator),asyncRetryTransactionMiddleware(deleteOwnershipChange))@@ -87,23 +89,14 @@ async function createChangeOwnershipRequest (req: express.Request, res: express.const nextOwner = res.locals.changeOwnershipNextOwnerconst ownershipChange = await sequelizeTypescript.transaction(async t => {- const [ ownershipChange ] = await ChangeOwnershipModel.findOrCreate({- where: {- initiatorAccountId,- nextOwnerAccountId: nextOwner.id,- videoId: video.id,- state: ChangeOwnershipState.PENDING- },- defaults: {- initiatorAccountId,- nextOwnerAccountId: nextOwner.id,- videoId: video.id,- state: ChangeOwnershipState.PENDING- },- transaction: t- })-- await VideoChannelActivityModel.addOwnershipChangeActivity({+ const ownershipChange = await ChangeOwnershipModel.create({+ initiatorAccountId,+ nextOwnerAccountId: nextOwner.id,+ videoId: video.id,+ state: ChangeOwnershipState.PENDING+ }, { transaction: t })++ await VideoChannelActivityModel.addVideoOwnershipChangeActivity({action: VideoChannelActivityAction.SEND_OWNERSHIP_REQUEST,user: res.locals.oauth.token.User,channel: video.VideoChannel,@@ -176,7 +169,7 @@ function acceptOwnershipChange (req: express.Request, res: express.Response) {await changeOwnership.save({ transaction: t })for (const channel of [ oldVideoChannel, targetVideoUpdated.VideoChannel ]) {- await VideoChannelActivityModel.addOwnershipChangeActivity({+ await VideoChannelActivityModel.addVideoOwnershipChangeActivity({action: VideoChannelActivityAction.ACCEPT_OWNERSHIP_REQUEST,user: res.locals.oauth.token.User,channel,@@ -201,7 +194,7 @@ function refuseOwnershipChange (req: express.Request, res: express.Response) {const channel = await VideoChannelModel.loadAndPopulateAccount(changeOwnership.Video.channelId, t)- await VideoChannelActivityModel.addOwnershipChangeActivity({+ await VideoChannelActivityModel.addVideoOwnershipChangeActivity({action: VideoChannelActivityAction.REFUSE_OWNERSHIP_REQUEST,user: res.locals.oauth.token.User,channel,@@ -223,7 +216,7 @@ function deleteOwnershipChange (req: express.Request, res: express.Response) {await changeOwnership.destroy({ transaction: t })- await VideoChannelActivityModel.addOwnershipChangeActivity({+ await VideoChannelActivityModel.addVideoOwnershipChangeActivity({action: VideoChannelActivityAction.DELETE_OWNERSHIP_REQUEST,user: res.locals.oauth.token.User,channel,@@ -232,7 +225,7 @@ function deleteOwnershipChange (req: express.Request, res: express.Response) {transaction: t})- logger.info('Ownership change request %d deleted.', changeOwnership.id)+ logger.info('Video ownership change request %d deleted.', changeOwnership.id)return res.sendStatus(HttpStatusCode.NO_CONTENT_204)})diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex 5d0f14b7d0..4056443eb1 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -112,6 +112,7 @@ export const SORTABLE_COLUMNS = {VIDEO_COMMENTS: [ 'createdAt' ],VIDEO_PASSWORDS: [ 'createdAt' ],+ CHANGE_OWNERSHIP: [ 'createdAt' ],VIDEO_RATES: [ 'createdAt' ],BLACKLISTS: [ 'id', 'name', 'duration', 'views', 'likes', 'dislikes', 'uuid', 'createdAt' ],diff --git a/server/core/lib/activitypub/actors/updater.ts b/server/core/lib/activitypub/actors/updater.tsindex 97524c5446..c9cdc7f401 100644--- a/server/core/lib/activitypub/actors/updater.ts+++ b/server/core/lib/activitypub/actors/updater.ts@@ -3,6 +3,7 @@ import { resetSequelizeInstance, runInReadCommittedTransaction } from '@server/himport { logger } from '@server/helpers/logger.js'import { AccountModel } from '@server/models/account/account.js'import { VideoChannelModel } from '@server/models/video/video-channel.js'+import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'import { MAccount, MActor, MActorFull, MChannel } from '@server/types/models/index.js'import { upsertAPPlayerSettings } from '../player-settings.js'import { getOrCreateAPOwner } from './get.js'@@ -38,6 +39,19 @@ export class APActorUpdater {const owner = await getOrCreateAPOwner(this.actorObject, this.actorObject.id)+ if (owner.accountId !== channel.accountId) {+ logger.info(`Updating owner of channel ${channel.name} to ${owner.preferredUsername}`)++ await runInReadCommittedTransaction(async t => {+ await VideoPlaylistModel.updateOwnerOfChannelPlaylists({+ currentOwnerId: channel.accountId,+ nextOwnerId: owner.Account.id,+ videoChannelId: channel.id,+ transaction: t+ })+ })+ }+channel.accountId = owner.Account.idchannel.support = this.actorObject.supportdiff --git a/server/core/lib/activitypub/playlists/refresh.ts b/server/core/lib/activitypub/playlists/refresh.tsindex 625cc9ef24..0ca9515ecd 100644--- a/server/core/lib/activitypub/playlists/refresh.ts+++ b/server/core/lib/activitypub/playlists/refresh.ts@@ -17,10 +17,14 @@ function schedulePlaylistRefreshIfNeeded (playlist: MVideoPlaylist) {}async function refreshVideoPlaylistIfNeeded (videoPlaylist: MVideoPlaylistOwnerDefault): Promise<MVideoPlaylistOwnerDefault> {- if (!videoPlaylist.isOutdated()) return videoPlaylist-const lTags = loggerTagsFactory('ap', 'video-playlist', 'refresh', videoPlaylist.uuid, videoPlaylist.url)+ if (!videoPlaylist.isOutdated()) {+ logger.debug('Playlist ' + videoPlaylist.url + ' is not outdated, no need to refresh it.', lTags())++ return videoPlaylist+ }+logger.info('Refreshing playlist %s.', videoPlaylist.url, lTags())try {diff --git a/server/core/lib/notifier/notifier.ts b/server/core/lib/notifier/notifier.tsindex 372169b417..6144fb60eb 100644--- a/server/core/lib/notifier/notifier.ts+++ b/server/core/lib/notifier/notifier.ts@@ -22,6 +22,9 @@ import {import { JobQueue } from '../job-queue/index.js'import { PeerTubeSocket } from '../peertube-socket.js'import { Hooks } from '../plugins/hooks.js'+import { RequestVideoChangeOwnership } from './shared/change-ownership/request-video-change-ownership.js'+import { VideoChangeOwnershipAccepted } from './shared/change-ownership/video-change-ownership-accepted.js'+import { VideoChangeOwnershipRejected } from './shared/change-ownership/video-change-ownership-rejected.js'import { AcceptedToCollaborateToChannel } from './shared/channel/accepted-to-collaborate-to-channel.js'import { InvitedToCollaborateToChannel } from './shared/channel/invited-to-collaborate-to-channel.js'import { RefusedToCollaborateToChannel } from './shared/channel/refused-to-collaborate-to-channel.js'@@ -29,6 +32,8 @@ import {AbstractNotification,AbuseStateChangeForReporter,AutoFollowForInstance,+ ChannelChangeOwnershipAccepted,+ ChannelChangeOwnershipRejected,CommentMention,DirectRegistrationForModerators,FollowForInstance,@@ -49,13 +54,11 @@ import {OwnedPublicationAfterScheduleUpdate,OwnedPublicationAfterTranscoding,RegistrationRequestForModerators,+ RequestChannelChangeOwnership,StudioEditionFinishedForOwner,UnblacklistForOwner,VideoTranscriptionGeneratedForOwner} from './shared/index.js'-import { RequestVideoChangeOwnership } from './shared/video-change-ownership/request-video-change-ownership.js'-import { VideoChangeOwnershipAccepted } from './shared/video-change-ownership/video-change-ownership-accepted.js'-import { VideoChangeOwnershipRejected } from './shared/video-change-ownership/video-change-ownership-rejected.js'const lTags = loggerTagsFactory('notifier')@@ -98,7 +101,11 @@ class Notifier {changeVideoOwnershipRequest: [ RequestVideoChangeOwnership ],changeVideoOwnershipAccepted: [ VideoChangeOwnershipAccepted ],- changeVideoOwnershipRejected: [ VideoChangeOwnershipRejected ]+ changeVideoOwnershipRejected: [ VideoChangeOwnershipRejected ],++ changeChannelOwnershipRequest: [ RequestChannelChangeOwnership ],+ changeChannelOwnershipAccepted: [ ChannelChangeOwnershipAccepted ],+ changeChannelOwnershipRejected: [ ChannelChangeOwnershipRejected ]}private static instance: Notifier@@ -381,6 +388,43 @@ class Notifier {.catch(err => logger.error('Cannot notify rejected video ownership change %d.', changeOwnership.id, { err }))}+ // ---------------------------------------------------------------------------+ // Channel ownership change notifications+ // ---------------------------------------------------------------------------++ notifyOfRequestedChannelOwnershipChange (changeOwnership: MChangeOwnershipFull) {+ const models = this.notificationModels.changeChannelOwnershipRequest++ const channelName = changeOwnership.VideoChannel.Actor.preferredUsername++ logger.debug(`Notify on requested channel ${channelName} ownership change`, { id: changeOwnership.id, channelName, ...lTags() })++ this.sendNotifications(models, changeOwnership)+ .catch(err => logger.error('Cannot notify requested channel ownership change %d.', changeOwnership.id, { err }))+ }++ notifyOfAcceptedChannelOwnershipChange (changeOwnership: MChangeOwnershipFull) {+ const models = this.notificationModels.changeChannelOwnershipAccepted++ const channelName = changeOwnership.VideoChannel.Actor.preferredUsername++ logger.debug(`Notify on accepted channel ${channelName} ownership change`, { id: changeOwnership.id, channelName, ...lTags() })++ this.sendNotifications(models, changeOwnership)+ .catch(err => logger.error('Cannot notify accepted channel ownership change %d.', changeOwnership.id, { err }))+ }++ notifyOfRejectedChannelOwnershipChange (changeOwnership: MChangeOwnershipFull) {+ const models = this.notificationModels.changeChannelOwnershipRejected++ const channelName = changeOwnership.VideoChannel.Actor.preferredUsername++ logger.debug(`Notify on rejected channel ${channelName} ownership change`, { id: changeOwnership.id, channelName, ...lTags() })++ this.sendNotifications(models, changeOwnership)+ .catch(err => logger.error('Cannot notify rejected channel ownership change %d.', changeOwnership.id, { err }))+ }+// ---------------------------------------------------------------------------private async notify<T> (object: AbstractNotification<T>) {diff --git a/server/core/lib/notifier/shared/change-ownership/abstract-channel-change-ownership-response.ts b/server/core/lib/notifier/shared/change-ownership/abstract-channel-change-ownership-response.tsnew file mode 100644index 0000000000..115d4bb10a--- /dev/null+++ b/server/core/lib/notifier/shared/change-ownership/abstract-channel-change-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 { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildChangeOwnershipNotification } from './change-ownership-utils.js'++export abstract class AbstractChannelChangeOwnershipResponse extends AbstractNotification<MChangeOwnershipFull> {+ protected users: MUserWithNotificationSetting[] = []++ async prepare () {+ this.users = await UserModel.listOwnerAndAcceptedCollaboratorsOfChannel(this.payload.videoChannelId)+ }++ 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 buildChangeOwnershipNotification({+ user,+ payload: this.payload,+ notificationType: this.getNotificationType()+ })+ }++ protected abstract getNotificationType (): UserNotificationType_Type+}diff --git a/server/core/lib/notifier/shared/video-change-ownership/abstract-video-change-ownership-response.ts b/server/core/lib/notifier/shared/change-ownership/abstract-video-change-ownership-response.tssimilarity index 89%rename from server/core/lib/notifier/shared/video-change-ownership/abstract-video-change-ownership-response.tsrename to server/core/lib/notifier/shared/change-ownership/abstract-video-change-ownership-response.tsindex 92247290c9..6705f0fded 100644--- a/server/core/lib/notifier/shared/video-change-ownership/abstract-video-change-ownership-response.ts+++ b/server/core/lib/notifier/shared/change-ownership/abstract-video-change-ownership-response.ts@@ -3,7 +3,7 @@ import { UserModel } from '@server/models/user/user.js'import { MUserWithNotificationSetting } from '@server/types/models/index.js'import { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'import { AbstractNotification } from '../common/abstract-notification.js'-import { buildVideoChangeOwnershipNotification } from './video-change-ownership-utils.js'+import { buildChangeOwnershipNotification } from './change-ownership-utils.js'export abstract class AbstractVideoChangeOwnershipResponse extends AbstractNotification<MChangeOwnershipFull> {protected users: MUserWithNotificationSetting[] = []@@ -25,7 +25,7 @@ export abstract class AbstractVideoChangeOwnershipResponse extends AbstractNotif}createNotification (user: MUserWithNotificationSetting) {- return buildVideoChangeOwnershipNotification({+ return buildChangeOwnershipNotification({user,payload: this.payload,notificationType: this.getNotificationType()diff --git a/server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-utils.ts b/server/core/lib/notifier/shared/change-ownership/change-ownership-utils.tssimilarity index 91%rename from server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-utils.tsrename to server/core/lib/notifier/shared/change-ownership/change-ownership-utils.tsindex ee26d90136..8b4cebaf7f 100644--- a/server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-utils.ts+++ b/server/core/lib/notifier/shared/change-ownership/change-ownership-utils.ts@@ -3,7 +3,7 @@ import { UserNotificationModel } from '@server/models/user/user-notification.js'import { MUserId, UserNotificationModelForApi } from '@server/types/models/user/index.js'import { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'-export function buildVideoChangeOwnershipNotification (options: {+export function buildChangeOwnershipNotification (options: {user: MUserIdpayload: MChangeOwnershipFullnotificationType: UserNotificationType_Typediff --git a/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-accepted.ts b/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-accepted.tsnew file mode 100644index 0000000000..d0b22095d5--- /dev/null+++ b/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-accepted.ts@@ -0,0 +1,39 @@+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 { AbstractChannelChangeOwnershipResponse } from './abstract-channel-change-ownership-response.js'++export class ChannelChangeOwnershipAccepted extends AbstractChannelChangeOwnershipResponse {+ log () {+ logger.info(+ 'Notifying source channel members that ownership change of channel %s was accepted.',+ this.payload.VideoChannel.Actor.preferredUsername+ )+ }++ protected getNotificationType () {+ return UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_ACCEPTED+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A channel ownership change request has been accepted', language),+ text: t('{nextOwner} accepted the ownership change request for channel {channelName}.', language, {+ nextOwner: this.payload.NextOwner.getDisplayName(),+ channelName: this.payload.VideoChannel.name+ }),+ locals: {+ action: {+ text: t('View your notifications', language),+ url: WEBSERVER.URL + '/my-account/notifications'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-rejected.ts b/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-rejected.tsnew file mode 100644index 0000000000..dde22b619e--- /dev/null+++ b/server/core/lib/notifier/shared/change-ownership/channel-change-ownership-rejected.ts@@ -0,0 +1,39 @@+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 { AbstractChannelChangeOwnershipResponse } from './abstract-channel-change-ownership-response.js'++export class ChannelChangeOwnershipRejected extends AbstractChannelChangeOwnershipResponse {+ log () {+ logger.info(+ 'Notifying source channel members that ownership change of channel %s was rejected.',+ this.payload.VideoChannel.Actor.preferredUsername+ )+ }++ protected getNotificationType () {+ return UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REJECTED+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A channel ownership change request has been rejected', language),+ text: t('{nextOwner} rejected the ownership change request for channel {channelName}.', language, {+ nextOwner: this.payload.NextOwner.getDisplayName(),+ channelName: this.payload.VideoChannel.name+ }),+ locals: {+ action: {+ text: t('View your notifications', language),+ url: WEBSERVER.URL + '/my-account/notifications'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/change-ownership/index.ts b/server/core/lib/notifier/shared/change-ownership/index.tsnew file mode 100644index 0000000000..932e65966a--- /dev/null+++ b/server/core/lib/notifier/shared/change-ownership/index.ts@@ -0,0 +1,6 @@+export * from './request-video-change-ownership.js'+export * from './video-change-ownership-accepted.js'+export * from './video-change-ownership-rejected.js'+export * from './request-channel-change-ownership.js'+export * from './channel-change-ownership-accepted.js'+export * from './channel-change-ownership-rejected.js'diff --git a/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.ts b/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.tsnew file mode 100644index 0000000000..a08ff3beda--- /dev/null+++ b/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.ts@@ -0,0 +1,70 @@+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 { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { UserModel } from '@server/models/user/user.js'+import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'+import { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildChangeOwnershipNotification } from './change-ownership-utils.js'++export class RequestChannelChangeOwnership extends AbstractNotification<MChangeOwnershipFull> {+ private user: MUserDefault+ private channelAccountMuted: boolean++ async prepare () {+ this.user = await UserModel.loadByAccountId(this.payload.nextOwnerAccountId)++ const hash = await AccountBlocklistModel.isAccountMutedByAccounts([ this.user.Account.id ], this.payload.initiatorAccountId)+ this.channelAccountMuted = hash[this.user.Account.id] === true+ }++ log () {+ logger.info('Notifying %s of ownership request for channel %s.', this.user.username, this.payload.VideoChannel.Actor.preferredUsername)+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ if (this.channelAccountMuted) return UserNotificationSettingValue.NONE++ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ if (!this.user) return []++ return [ this.user ]+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildChangeOwnershipNotification({+ user,+ payload: this.payload,+ notificationType: UserNotificationType.CHANNEL_OWNERSHIP_CHANGED_REQUEST+ })+ }++ createEmail (user: MUserWithNotificationSetting) {+ const language = user.getLanguage()+ const to = { email: user.email, language }++ return {+ to,+ subject: t('A channel ownership change request is waiting for you', language),+ text: t('{initiator} wants to transfer ownership of channel {channelName} to you.', language, {+ initiator: this.payload.Initiator.getDisplayName(),+ channelName: this.payload.VideoChannel.name+ }),+ locals: {+ action: {+ text: t('Review the request', language),+ url: WEBSERVER.URL + '/my-account/notifications'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/video-change-ownership/request-video-change-ownership.ts b/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.tssimilarity index 77%rename from server/core/lib/notifier/shared/video-change-ownership/request-video-change-ownership.tsrename to server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.tsindex 80e98ffaf6..3f65f23070 100644--- a/server/core/lib/notifier/shared/video-change-ownership/request-video-change-ownership.ts+++ b/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.ts@@ -6,13 +6,18 @@ import { UserModel } from '@server/models/user/user.js'import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'import { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'import { AbstractNotification } from '../common/abstract-notification.js'-import { buildVideoChangeOwnershipNotification } from './video-change-ownership-utils.js'+import { buildChangeOwnershipNotification } from './change-ownership-utils.js'+import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'export class RequestVideoChangeOwnership extends AbstractNotification<MChangeOwnershipFull> {private user: MUserDefault+ private channelAccountMuted: booleanasync prepare () {this.user = await UserModel.loadByAccountId(this.payload.nextOwnerAccountId)++ const hash = await AccountBlocklistModel.isAccountMutedByAccounts([ this.user.Account.id ], this.payload.initiatorAccountId)+ this.channelAccountMuted = hash[this.user.Account.id] === true}log () {@@ -24,6 +29,8 @@ export class RequestVideoChangeOwnership extends AbstractNotification<MChangeOwn}getSetting (_user: MUserWithNotificationSetting) {+ if (this.channelAccountMuted) return UserNotificationSettingValue.NONE+return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL}@@ -34,7 +41,7 @@ export class RequestVideoChangeOwnership extends AbstractNotification<MChangeOwn}createNotification (user: MUserWithNotificationSetting) {- return buildVideoChangeOwnershipNotification({+ return buildChangeOwnershipNotification({user,payload: this.payload,notificationType: UserNotificationType.VIDEO_OWNERSHIP_CHANGED_REQUEST@@ -55,7 +62,7 @@ export class RequestVideoChangeOwnership extends AbstractNotification<MChangeOwnlocals: {action: {text: t('Review the request', language),- url: WEBSERVER.URL + '/my-account/notifications'+ url: WEBSERVER.URL + '/my-library/ownership'}}}diff --git a/server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-accepted.ts b/server/core/lib/notifier/shared/change-ownership/video-change-ownership-accepted.tssimilarity index 100%rename from server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-accepted.tsrename to server/core/lib/notifier/shared/change-ownership/video-change-ownership-accepted.tsdiff --git a/server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-rejected.ts b/server/core/lib/notifier/shared/change-ownership/video-change-ownership-rejected.tssimilarity index 100%rename from server/core/lib/notifier/shared/video-change-ownership/video-change-ownership-rejected.tsrename to server/core/lib/notifier/shared/change-ownership/video-change-ownership-rejected.tsdiff --git a/server/core/lib/notifier/shared/index.ts b/server/core/lib/notifier/shared/index.tsindex 745bcfc375..c47ee73af6 100644--- a/server/core/lib/notifier/shared/index.ts+++ b/server/core/lib/notifier/shared/index.ts@@ -5,5 +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-change-ownership/index.js'+export * from './change-ownership/index.js'export * from './video-publication/index.js'diff --git a/server/core/lib/notifier/shared/video-change-ownership/index.ts b/server/core/lib/notifier/shared/video-change-ownership/index.tsdeleted file mode 100644index 9bdfd6f1d9..0000000000--- a/server/core/lib/notifier/shared/video-change-ownership/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export * from './request-video-change-ownership.js'-export * from './video-change-ownership-accepted.js'-export * from './video-change-ownership-rejected.js'diff --git a/server/core/middlewares/user-right.ts b/server/core/middlewares/user-right.tsindex 7554368c67..dc554d4d37 100644--- a/server/core/middlewares/user-right.ts+++ b/server/core/middlewares/user-right.ts@@ -6,7 +6,7 @@ export function ensureUserHasRight (userRight: UserRightType) {return function (req: express.Request, res: express.Response, next: express.NextFunction) {const user = res.locals.oauth.token.userif (user.hasRight(userRight) === false) {- const message = `User ${user.username} does not have right (No. ${userRight}) to access to ${req.path}.`+ const message = `User ${user.username} does not have right (No. ${userRight}) to access to ${req.originalUrl}.`logger.info(message)return res.fail({diff --git a/server/core/middlewares/validators/shared/videos.ts b/server/core/middlewares/validators/shared/videos.tsindex 304a24f0c8..5ca439584a 100644--- a/server/core/middlewares/validators/shared/videos.ts+++ b/server/core/middlewares/validators/shared/videos.ts@@ -357,16 +357,16 @@ export async function checkCanManageVideo (options: {export async function checkUserQuota (options: {channelUser: MUserId- videoFileSize: number+ uploadSize: numberreq: Requestres: Response}) {- const { channelUser, videoFileSize, req, res } = options+ const { channelUser, uploadSize, req, res } = options- if (await isUserQuotaValid({ channelUserId: channelUser.id, uploadSize: videoFileSize }) === false) {+ if (await isUserQuotaValid({ channelUserId: channelUser.id, uploadSize }) === false) {res.fail({status: HttpStatusCode.PAYLOAD_TOO_LARGE_413,- message: req.t('The user video quota is exceeded with this video'),+ message: req.t('The user video quota is exceeded'),type: ServerErrorCode.QUOTA_REACHED})return falsediff --git a/server/core/middlewares/validators/sort.ts b/server/core/middlewares/validators/sort.tsindex 1416d05bd5..1a7277f819 100644--- a/server/core/middlewares/validators/sort.ts+++ b/server/core/middlewares/validators/sort.ts@@ -29,6 +29,7 @@ export const availablePluginsSortValidator = checkSortFactory(SORTABLE_COLUMNS.Aexport const videoRedundanciesSortValidator = checkSortFactory(SORTABLE_COLUMNS.VIDEO_REDUNDANCIES)export const videoChannelSyncsSortValidator = checkSortFactory(SORTABLE_COLUMNS.VIDEO_CHANNEL_SYNCS)export const videoPasswordsSortValidator = checkSortFactory(SORTABLE_COLUMNS.VIDEO_PASSWORDS)+export const changeOwnershipSortValidator = checkSortFactory(SORTABLE_COLUMNS.CHANGE_OWNERSHIP)export const watchedWordsListsSortValidator = checkSortFactory(SORTABLE_COLUMNS.WATCHED_WORDS_LISTS)diff --git a/server/core/middlewares/validators/videos/change-ownership.ts b/server/core/middlewares/validators/videos/change-ownership.tsindex b6d198ddb4..1fc79681b8 100644--- a/server/core/middlewares/validators/videos/change-ownership.ts+++ b/server/core/middlewares/validators/videos/change-ownership.ts@@ -1,23 +1,88 @@-import { ChangeOwnershipAccept, ChangeOwnershipState, HttpStatusCode, UserRight, VideoState } from '@peertube/peertube-models'+import {+ ChangeOwnershipState,+ ChangeOwnershipStateType,+ ChangeVideoOwnershipAccept,+ HttpStatusCode,+ UserRight,+ VideoState+} from '@peertube/peertube-models'import { exists, isIdValid } from '@server/helpers/custom-validators/misc.js'+import { getAuthUser } from '@server/helpers/express-utils.js'import { CONFIG } from '@server/initializers/config.js'import { CHANGE_OWNERSHIP_STATES } from '@server/initializers/constants.js'import { AccountModel } from '@server/models/account/account.js'import { ChangeOwnershipModel } from '@server/models/video/change-ownership.js'+import { VideoChannelModel } from '@server/models/video/video-channel.js'import { VideoModel } from '@server/models/video/video.js'import express from 'express'import { param, query } from 'express-validator'import {areValidationErrors,checkCanManageAccount,+ checkCanManageChannel,checkCanManageVideo,checkUserQuota,doesChangeOwnershipExist,+ doesChannelHandleExist,doesChannelIdExist,doesVideoExist,isValidVideoIdParam} from '../shared/index.js'+// ---------------------------------------------------------------------------+// Common validators for video and channel ownership change+// ---------------------------------------------------------------------------++export const acceptOrRejectChangeOwnershipValidatorFactory = (type: 'video' | 'channel') => {+ return [+ param('id')+ .custom(isIdValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ if (!await doesChangeOwnershipExist(req.params.id, req, res)) return++ // Check if the user who did the request is able to change the ownership of the video+ const user = res.locals.oauth.token.User+ const videoChangeOwnership = res.locals.changeOwnership++ if (type === 'video' && !videoChangeOwnership.Video) {+ res.fail({ message: req.t('The ownership change request is not linked to a video') })+ return+ }++ if (type === 'channel' && !videoChangeOwnership.VideoChannel) {+ res.fail({ message: req.t('The ownership change request is not linked to a channel') })+ return+ }++ if (!checkCanManageAccount({ user, account: videoChangeOwnership.NextOwner, req, res: null, specialRight: UserRight.MANAGE_USERS })) {+ res.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('Cannot terminate an ownership change of another user')+ })+ return+ }++ const changeOwnership = res.locals.changeOwnership++ if (changeOwnership.state !== ChangeOwnershipState.PENDING) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('Ownership change request already accepted or refused')+ })+ return+ }++ return next()+ }+ ]+}++// ---------------------------------------------------------------------------+// Ownership change for videos+// ---------------------------------------------------------------------------+export const changeVideoOwnershipValidator = [isValidVideoIdParam('videoId'),@@ -38,10 +103,13 @@ export const changeVideoOwnershipValidator = [})) return- const nextOwner = await AccountModel.loadLocalByName(req.body.username)- if (!nextOwner) {+ if (!await checkNextOwner({ username: req.body.username, req, res })) return++ const nextOwner = res.locals.changeOwnershipNextOwner+ if (nextOwner.id === res.locals.videoWithRights.VideoChannel.accountId) {res.fail({- message: req.t('{username} does not exist on {instanceName}', { username: req.body.username, instanceName: CONFIG.INSTANCE.NAME })+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('The new owner is already the owner of this video')})return}@@ -55,48 +123,13 @@ export const changeVideoOwnershipValidator = [return}- res.locals.changeOwnershipNextOwner = nextOwner- return next()- }-]--export const acceptOrRejectChangeOwnershipValidator = [- param('id')- .custom(isIdValid),-- async (req: express.Request, res: express.Response, next: express.NextFunction) => {- if (areValidationErrors(req, res)) return- if (!await doesChangeOwnershipExist(req.params.id, req, res)) return-- // Check if the user who did the request is able to change the ownership of the video- const user = res.locals.oauth.token.User- const videoChangeOwnership = res.locals.changeOwnership-- if (!checkCanManageAccount({ user, account: videoChangeOwnership.NextOwner, req, res: null, specialRight: UserRight.MANAGE_USERS })) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: req.t('Cannot terminate an ownership change of another user')- })- return- }-- const changeOwnership = res.locals.changeOwnership-- if (changeOwnership.state !== ChangeOwnershipState.PENDING) {- res.fail({- status: HttpStatusCode.BAD_REQUEST_400,- message: req.t('Ownership change request already accepted or refused')- })- return- }-return next()}]export const acceptVideoChangeOwnershipValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {- const body = req.body as ChangeOwnershipAccept+ const body = req.body as ChangeVideoOwnershipAcceptif (!await doesChannelIdExist({ id: body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: true })) returnconst videoChangeOwnership = res.locals.changeOwnership@@ -115,7 +148,7 @@ export const acceptVideoChangeOwnershipValidator = [} else {const channelUser = res.locals.oauth.token.User- if (!await checkUserQuota({ channelUser, videoFileSize: video.getMaxQualityBytes(), req, res })) return+ if (!await checkUserQuota({ channelUser, uploadSize: video.getMaxQualityBytes(), req, res })) return}return next()@@ -127,7 +160,7 @@ export const listVideoOwnershipChangesValidator = [query('state').optional()- .custom(value => exists(value) && CHANGE_OWNERSHIP_STATES[value] !== undefined),+ .custom(isOwnershipChangeStateValid),async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return@@ -150,7 +183,7 @@ export const listVideoOwnershipChangesValidator = [}]-export const deleteChangeOwnershipValidator = [+export const deleteChangeVideoOwnershipValidator = [param('id').custom(isIdValid),@@ -163,11 +196,16 @@ export const deleteChangeOwnershipValidator = [if (videoChangeOwnership.state !== ChangeOwnershipState.PENDING) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: req.t('Ownership already accepted or refused')+ message: req.t('Ownership request already accepted or refused')})return}+ if (!videoChangeOwnership.Video) {+ res.fail({ message: req.t('The ownership change request is not linked to a video') })+ return+ }+const video = await VideoModel.loadWithRights(videoChangeOwnership.Video.id)if (@@ -185,3 +223,145 @@ export const deleteChangeOwnershipValidator = [return next()}]++// ---------------------------------------------------------------------------+// Ownership change for channels+// ---------------------------------------------------------------------------++export const changeChannelOwnershipValidator = [+ param('handle').exists(),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ if (+ !await doesChannelHandleExist({ handle: req.params.handle, checkCanManage: true, checkIsLocal: true, checkIsOwner: true, req, res })+ ) return++ if (!await checkNextOwner({ username: req.body.username, req, res })) return++ const nextOwner = res.locals.changeOwnershipNextOwner+ if (nextOwner.id === res.locals.videoChannel.accountId) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('The new owner is already the owner of this channel')+ })+ return+ }++ const existing = await ChangeOwnershipModel.loadPendingByChannel(res.locals.videoChannel.id)+ if (existing) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('There is already a pending ownership change request for this channel')+ })+ return+ }++ return next()+ }+]++export const listChannelOwnershipChangesValidator = [+ param('handle').exists(),++ query('state')+ .optional()+ .custom(isOwnershipChangeStateValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ if (+ !await doesChannelHandleExist({ handle: req.params.handle, checkCanManage: true, checkIsLocal: true, checkIsOwner: false, req, res })+ ) return++ return next()+ }+]++export const acceptChannelChangeOwnershipValidator = [+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ const videoChangeOwnership = res.locals.changeOwnership++ const count = await VideoChannelModel.countByAccount(videoChangeOwnership.Initiator.id)++ if (count <= 1) {+ res.fail({+ status: HttpStatusCode.CONFLICT_409,+ message: req.t('Cannot accept to transfer the last channel of this user')+ })+ return+ }++ const channelQuota = await VideoChannelModel.getChannelQuota(videoChangeOwnership.VideoChannel.id)+ if (!await checkUserQuota({ channelUser: getAuthUser(res), uploadSize: channelQuota, req, res })) return++ return next()+ }+]++export const deleteChangeChannelOwnershipValidator = [+ param('id').custom(isIdValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ if (!await doesChangeOwnershipExist(req.params.id, req, res)) return++ const videoChangeOwnership = res.locals.changeOwnership++ if (videoChangeOwnership.state !== ChangeOwnershipState.PENDING) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('Ownership request already accepted or refused')+ })+ return+ }++ if (!videoChangeOwnership.VideoChannel) {+ res.fail({ message: req.t('The ownership change request is not linked to a channel') })+ return+ }++ const channel = await VideoChannelModel.loadAndPopulateAccount(videoChangeOwnership.VideoChannel.id)++ if (+ !await checkCanManageChannel({+ channel,+ user: getAuthUser(res),+ req,+ res,+ checkCanManage: true,+ checkIsOwner: true+ })+ ) return false++ return next()+ }+]++// ---------------------------------------------------------------------------+// Common helpers+// ---------------------------------------------------------------------------++async function checkNextOwner (options: {+ username: string+ req: express.Request+ res: express.Response+}) {+ const { username, req, res } = options++ const nextOwner = await AccountModel.loadLocalByName(username)+ if (!nextOwner) {+ res.fail({+ message: req.t('{username} does not exist on {instanceName}', { username: username, instanceName: CONFIG.INSTANCE.NAME })+ })+ return false+ }++ res.locals.changeOwnershipNextOwner = nextOwner++ return true+}++function isOwnershipChangeStateValid (value: any): value is ChangeOwnershipStateType {+ return exists(value) && CHANGE_OWNERSHIP_STATES[value] !== undefined+}diff --git a/server/core/middlewares/validators/videos/shared/video-validators.ts b/server/core/middlewares/validators/videos/shared/video-validators.tsindex 65dec12620..05f857c258 100644--- a/server/core/middlewares/validators/videos/shared/video-validators.ts+++ b/server/core/middlewares/validators/videos/shared/video-validators.ts@@ -38,7 +38,7 @@ export async function commonVideoFileChecks (options: {return false}- if (await checkUserQuota({ channelUser, videoFileSize, req, res }) === false) return false+ if (await checkUserQuota({ channelUser, uploadSize: videoFileSize, req, res }) === false) return falsereturn true}diff --git a/server/core/middlewares/validators/videos/video-channel-collaborators.ts b/server/core/middlewares/validators/videos/video-channel-collaborators.tsindex 896624c066..17c8beadac 100644--- a/server/core/middlewares/validators/videos/video-channel-collaborators.ts+++ b/server/core/middlewares/validators/videos/video-channel-collaborators.ts@@ -126,7 +126,7 @@ export const channelDeleteCollaboratorsValidator = [user,account: res.locals.channelCollaborator.Account,req,- res,+ res: null, // Don't return a failed responsespecialRight: UserRight.MANAGE_ANY_VIDEO_CHANNEL})diff --git a/server/core/middlewares/validators/videos/video-channels.ts b/server/core/middlewares/validators/videos/video-channels.tsindex fd76b2869b..0d959cb617 100644--- a/server/core/middlewares/validators/videos/video-channels.ts+++ b/server/core/middlewares/validators/videos/video-channels.ts@@ -161,7 +161,7 @@ export const videoChannelImportVideosValidator = [}const channelUser = { id: res.locals.videoChannel.Account.userId }- if (!await checkUserQuota({ channelUser, videoFileSize: 1, req, res })) return+ if (!await checkUserQuota({ channelUser, uploadSize: 1, req, res })) returnreturn next()}diff --git a/server/core/middlewares/validators/videos/video-studio.ts b/server/core/middlewares/validators/videos/video-studio.tsindex 9a60a1d86e..f500083d14 100644--- a/server/core/middlewares/validators/videos/video-studio.ts+++ b/server/core/middlewares/validators/videos/video-studio.ts@@ -90,7 +90,7 @@ const videoStudioAddEditionValidator = [// Try to make an approximation of bytes added by the intro/outroconst additionalBytes = await approximateIntroOutroAdditionalSize(video, body.tasks, i => getTaskFileFromReq(files, i).path)const channelUser = { id: res.locals.videoFull.VideoChannel.Account.userId }- if (await checkUserQuota({ channelUser, videoFileSize: additionalBytes, req, res }) === false) return cleanUpReqFiles(req)+ if (await checkUserQuota({ channelUser, uploadSize: additionalBytes, req, res }) === false) return cleanUpReqFiles(req)return next()}diff --git a/server/core/middlewares/validators/videos/videos.ts b/server/core/middlewares/validators/videos/videos.tsindex be64c24c8c..46d8135d3c 100644--- a/server/core/middlewares/validators/videos/videos.ts+++ b/server/core/middlewares/validators/videos/videos.ts@@ -271,7 +271,7 @@ export const videosUpdateValidator = getCommonVideoEditAttributes().concat([// Check quota of the target channelconst channelUser = { id: targetChannel.Account.userId }- if (!await checkUserQuota({ channelUser, videoFileSize: video.getMaxQualityBytes(), req, res })) {+ if (!await checkUserQuota({ channelUser, uploadSize: video.getMaxQualityBytes(), req, res })) {return false}}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 62133a512c..9ef542b8a4 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@@ -54,51 +54,34 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {`"UserNotificationModel"."createdAt"`,`"UserNotificationModel"."updatedAt"`,- `"Video"."id" AS "Video.id"`,- `"Video"."uuid" AS "Video.uuid"`,- `"Video"."name" AS "Video.name"`,- `"Video"."state" AS "Video.state"`,+ ...this.getVideoAttributes('Video', 'Video'),...this.getAccountOrChannelAttributes('Video->VideoChannel', 'Video.VideoChannel'),`"VideoComment"."id" AS "VideoComment.id"`,`"VideoComment"."originCommentId" AS "VideoComment.originCommentId"`,`"VideoComment"."heldForReview" AS "VideoComment.heldForReview"`,- `"VideoComment->Video"."id" AS "VideoComment.Video.id"`,- `"VideoComment->Video"."uuid" AS "VideoComment.Video.uuid"`,- `"VideoComment->Video"."name" AS "VideoComment.Video.name"`,- `"VideoComment->Video"."state" AS "VideoComment.Video.state"`,+ ...this.getVideoAttributes('VideoComment->Video', 'VideoComment.Video'),...this.getAccountOrChannelAttributes('VideoComment->Account', 'VideoComment.Account'),`"Abuse"."id" AS "Abuse.id"`,`"Abuse"."state" AS "Abuse.state"`,`"Abuse->VideoAbuse"."id" AS "Abuse.VideoAbuse.id"`,- `"Abuse->VideoAbuse->Video"."id" AS "Abuse.VideoAbuse.Video.id"`,- `"Abuse->VideoAbuse->Video"."uuid" AS "Abuse.VideoAbuse.Video.uuid"`,- `"Abuse->VideoAbuse->Video"."name" AS "Abuse.VideoAbuse.Video.name"`,- `"Abuse->VideoAbuse->Video"."state" AS "Abuse.VideoAbuse.Video.state"`,+ ...this.getVideoAttributes('Abuse->VideoAbuse->Video', 'Abuse.VideoAbuse.Video'),+`"Abuse->VideoCommentAbuse"."id" AS "Abuse.VideoCommentAbuse.id"`,`"Abuse->VideoCommentAbuse->VideoComment"."id" AS "Abuse.VideoCommentAbuse.VideoComment.id"`,`"Abuse->VideoCommentAbuse->VideoComment"."originCommentId" AS "Abuse.VideoCommentAbuse.VideoComment.originCommentId"`,- `"Abuse->VideoCommentAbuse->VideoComment->Video"."id" AS "Abuse.VideoCommentAbuse.VideoComment.Video.id"`,- `"Abuse->VideoCommentAbuse->VideoComment->Video"."name" AS "Abuse.VideoCommentAbuse.VideoComment.Video.name"`,- `"Abuse->VideoCommentAbuse->VideoComment->Video"."uuid" AS "Abuse.VideoCommentAbuse.VideoComment.Video.uuid"`,- `"Abuse->VideoCommentAbuse->VideoComment->Video"."state" AS "Abuse.VideoCommentAbuse.VideoComment.Video.state"`,+ ...this.getVideoAttributes('Abuse->VideoCommentAbuse->VideoComment->Video', 'Abuse.VideoCommentAbuse.VideoComment.Video'),...this.getAccountOrChannelAttributes('Abuse->FlaggedAccount', 'Abuse.FlaggedAccount'),`"VideoBlacklist"."id" AS "VideoBlacklist.id"`,- `"VideoBlacklist->Video"."id" AS "VideoBlacklist.Video.id"`,- `"VideoBlacklist->Video"."uuid" AS "VideoBlacklist.Video.uuid"`,- `"VideoBlacklist->Video"."name" AS "VideoBlacklist.Video.name"`,- `"VideoBlacklist->Video"."state" AS "VideoBlacklist.Video.state"`,+ ...this.getVideoAttributes('VideoBlacklist->Video', 'VideoBlacklist.Video'),`"VideoImport"."id" AS "VideoImport.id"`,`"VideoImport"."magnetUri" AS "VideoImport.magnetUri"`,`"VideoImport"."targetUrl" AS "VideoImport.targetUrl"`,`"VideoImport"."torrentName" AS "VideoImport.torrentName"`,- `"VideoImport->Video"."id" AS "VideoImport.Video.id"`,- `"VideoImport->Video"."uuid" AS "VideoImport.Video.uuid"`,- `"VideoImport->Video"."name" AS "VideoImport.Video.name"`,- `"VideoImport->Video"."state" AS "VideoImport.Video.state"`,+ ...this.getVideoAttributes('VideoImport->Video', 'VideoImport.Video'),`"Plugin"."id" AS "Plugin.id"`,`"Plugin"."name" AS "Plugin.name"`,@@ -137,10 +120,7 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {`"VideoCaption"."id" AS "VideoCaption.id"`,`"VideoCaption"."language" AS "VideoCaption.language"`,- `"VideoCaption->Video"."id" AS "VideoCaption.Video.id"`,- `"VideoCaption->Video"."uuid" AS "VideoCaption.Video.uuid"`,- `"VideoCaption->Video"."name" AS "VideoCaption.Video.name"`,- `"VideoCaption->Video"."state" AS "VideoCaption.Video.state"`,+ ...this.getVideoAttributes('VideoCaption->Video', 'VideoCaption.Video'),`"ChannelCollab"."id" AS "ChannelCollab.id"`,`"ChannelCollab"."state" AS "ChannelCollab.state"`,@@ -149,13 +129,11 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {...this.getAccountOrChannelAttributes('ChannelCollab->Channel', 'ChannelCollab.Channel'),`"ChangeOwnership"."id" AS "ChangeOwnership.id"`,+ `"ChangeOwnership"."state" AS "ChangeOwnership.state"`,...this.getAccountOrChannelAttributes('ChangeOwnership->Initiator', 'ChangeOwnership.Initiator'),...this.getAccountOrChannelAttributes('ChangeOwnership->NextOwner', 'ChangeOwnership.NextOwner'),- `"ChangeOwnership->Video"."id" AS "ChangeOwnership.Video.id"`,- `"ChangeOwnership->Video"."uuid" AS "ChangeOwnership.Video.uuid"`,- `"ChangeOwnership->Video"."name" AS "ChangeOwnership.Video.name"`,- `"ChangeOwnership->Video"."state" AS "ChangeOwnership.Video.state"`,- ...this.getAccountOrChannelAttributes('ChangeOwnership->Channel', 'ChangeOwnership.Channel')+ ...this.getVideoAttributes('ChangeOwnership->Video', 'ChangeOwnership.Video'),+ ...this.getAccountOrChannelAttributes('ChangeOwnership->VideoChannel', 'ChangeOwnership.VideoChannel')]}@@ -237,7 +215,7 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {${this.getAccountJoin({ tableName: 'ChangeOwnership', columnJoin: 'initiatorAccountId', aliasTableName: 'Initiator' })}${this.getAccountJoin({ tableName: 'ChangeOwnership', columnJoin: 'nextOwnerAccountId', aliasTableName: 'NextOwner' })}LEFT JOIN "video" AS "ChangeOwnership->Video" ON "ChangeOwnership"."videoId" = "ChangeOwnership->Video"."id"- ${this.getChannelJoin({ tableName: 'ChangeOwnership', columnJoin: 'videoChannelId', aliasTableName: 'Channel', joinType: 'LEFT' })}+ ${this.getChannelJoin({ tableName: 'ChangeOwnership', columnJoin: 'videoChannelId', joinType: 'LEFT' })}) ON "UserNotificationModel"."changeOwnershipId" = "ChangeOwnership"."id"`}@@ -258,6 +236,15 @@ export class UserNotificationListQueryBuilder extends AbstractListQuery {]}+ private getVideoAttributes (tableName: string, alias: string) {+ return [+ `"${tableName}"."id" AS "${alias}.id"`,+ `"${tableName}"."uuid" AS "${alias}.uuid"`,+ `"${tableName}"."name" AS "${alias}.name"`,+ `"${tableName}"."state" AS "${alias}.state"`+ ]+ }+private getAccountJoin (options: {tableName: stringcolumnJoin: stringdiff --git a/server/core/models/user/user-notification.ts b/server/core/models/user/user-notification.tsindex 0248a7ed5b..28be620efd 100644--- a/server/core/models/user/user-notification.ts+++ b/server/core/models/user/user-notification.ts@@ -444,12 +444,11 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>`INNER JOIN actor ON "actor"."accountId" = "account"."id" `),- // Remove notifications from muted accounts that invited us to collaborate to a channel+ // Remove notifications from muted accounts that sent ownership changer requestsbuildAccountWhereQuery(`SELECT "userNotification"."id" FROM "userNotification" ` +- `INNER JOIN "videoChannelCollaborator" ON "videoChannelCollaborator".id = "userNotification"."channelCollaboratorId" ` +- `INNER JOIN "videoChannel" ON "videoChannel".id = "videoChannelCollaborator"."channelId" ` +- `INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ` ++ `INNER JOIN "changeOwnership" ON "changeOwnership".id = "userNotification"."changeOwnershipId" ` ++ `INNER JOIN "account" ON "changeOwnership"."initiatorAccountId" = "account"."id" ` +`INNER JOIN actor ON "actor"."accountId" = "account"."id" `)]@@ -570,6 +569,10 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>const changeOwnership = this.ChangeOwnership? {id: this.ChangeOwnership.id,+ state: {+ id: this.ChangeOwnership.state,+ label: ChangeOwnershipModel.getStateLabel(this.ChangeOwnership.state)+ },initiatorAccount: this.formatActor(this.ChangeOwnership.Initiator),nextOwnerAccount: this.formatActor(this.ChangeOwnership.NextOwner),diff --git a/server/core/models/video/change-ownership.ts b/server/core/models/video/change-ownership.tsindex 907f13d06e..26de768067 100644--- a/server/core/models/video/change-ownership.ts+++ b/server/core/models/video/change-ownership.ts@@ -121,6 +121,31 @@ export class ChangeOwnershipModel extends SequelizeModel<ChangeOwnershipModel> {// ---------------------------------------------------------------------------+ static listForChannelApi (options: ListChangeOwnershipOptions) {+ const queryOptions = { ...options, type: 'video-channel' as const }++ return Promise.all([+ new ChangeOwnershipListQueryBuilder(ChangeOwnershipModel.sequelize, queryOptions).list<MChangeOwnershipFull>(),+ new ChangeOwnershipListQueryBuilder(ChangeOwnershipModel.sequelize, queryOptions).count()+ ]).then(([ rows, total ]) => ({ total, data: rows }))+ }++ static loadPendingByChannel (videoChannelId: number): Promise<MChangeOwnership> {+ return new ChangeOwnershipListQueryBuilder(ChangeOwnershipModel.sequelize, {+ type: 'video-channel',+ videoChannelId,+ state: ChangeOwnershipState.PENDING+ }).get<MChangeOwnershipFull>()+ }++ // ---------------------------------------------------------------------------++ static getStateLabel (state: ChangeOwnershipStateType) {+ return CHANGE_OWNERSHIP_STATES[state]+ }++ // ---------------------------------------------------------------------------+toFormattedJSON (this: MChangeOwnershipFull): ChangeOwnership {let status: ChangeOwnership['status']@@ -133,7 +158,7 @@ export class ChangeOwnershipModel extends SequelizeModel<ChangeOwnershipModel> {state: {id: this.state,- label: CHANGE_OWNERSHIP_STATES[this.state]+ label: ChangeOwnershipModel.getStateLabel(this.state)},status,@@ -141,8 +166,8 @@ export class ChangeOwnershipModel extends SequelizeModel<ChangeOwnershipModel> {initiatorAccount: this.Initiator.toFormattedJSON(),nextOwnerAccount: this.NextOwner.toFormattedJSON(),- video: this.Video?.toFormattedJSON(),- videoChannel: this.VideoChannel?.toFormattedJSON(),+ video: this.Video?.toFormattedSummaryJSON(),+ videoChannel: this.VideoChannel?.toFormattedSummaryJSON(),createdAt: this.createdAt}diff --git a/server/core/models/video/sql/change-ownership/change-ownership-list-query-builder.ts b/server/core/models/video/sql/change-ownership/change-ownership-list-query-builder.tsindex fda2352ac7..a2b6887715 100644--- a/server/core/models/video/sql/change-ownership/change-ownership-list-query-builder.ts+++ b/server/core/models/video/sql/change-ownership/change-ownership-list-query-builder.ts@@ -14,6 +14,7 @@ export interface ListChangeOwnershipOptions extends AbstractListQueryOptions {state?: ChangeOwnershipStateTypevideoId?: number+ videoChannelId?: number}export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {@@ -21,13 +22,16 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {private builtInitiatorJoin = falseprivate builtNextOwnerJoin = false- private builtVideoJoin = falseprivate builtInitiatorAvatarJoin = falseprivate builtNextOwnerAvatarJoin = false- private builtChannelAvatarJoin = false- private builtChannelAccountAvatarJoin = false++ private builtVideoJoin = false+ private builtVideoChannelAvatarJoin = falseprivate builtThumbnailJoin = false++ private builtChannelJoin = falseprivate builtChannelCollaboratorsJoin = false+ private builtChannelAvatarJoin = falseconstructor (protected readonly sequelize: Sequelize,@@ -48,19 +52,26 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {}if (this.options.accountId) {+ this.buildVideoJoin()+ this.buildChannelJoin()+this.buildChannelCollaboratorsJoin()where.push(- `"ChangeOwnershipModel"."nextOwnerAccountId" = :nextOwnerAccountId ` ++ `(` ++ `"ChangeOwnershipModel"."nextOwnerAccountId" = :nextOwnerAccountId ` +`OR (` +- `"Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId OR ` +- `"Video->VideoChannel->Account"."id" = :videoAccountId` ++ ` "Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId OR ` ++ ` "Video->VideoChannel"."accountId" = :videoAccountId` ++ `)` ++ `OR "VideoChannel"."accountId" = :videoChannelAccountId` +`)`)this.replacements.collaborationAccountId = this.options.accountIdthis.replacements.videoAccountId = this.options.accountIdthis.replacements.nextOwnerAccountId = this.options.accountId+ this.replacements.videoChannelAccountId = this.options.accountId}if (this.options.state) {@@ -73,6 +84,11 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.replacements.videoId = this.options.videoId}+ if (this.options.videoChannelId) {+ where.push(`"ChangeOwnershipModel"."videoChannelId" = :videoChannelId`)+ this.replacements.videoChannelId = this.options.videoChannelId+ }+if (this.options.id) {where.push(`"ChangeOwnershipModel"."id" = :id`)this.replacements.id = this.options.id@@ -106,24 +122,37 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {private buildVideoJoin () {if (this.builtVideoJoin) return- this.subQueryJoin += ' INNER JOIN "video" "Video" ON "Video"."id" = "ChangeOwnershipModel"."videoId" ' ++ this.subQueryJoin += ' LEFT JOIN "video" "Video" ON "Video"."id" = "ChangeOwnershipModel"."videoId" ' +getChannelJoin({base: 'Video->',on: '"Video"."channelId"',- includeAccount: true,+ includeAccount: false,includeActors: true,includeAvatars: false,- required: true+ required: false})this.builtVideoJoin = true}+ private buildChannelJoin () {+ if (this.builtChannelJoin) return++ this.subQueryJoin += getChannelJoin({+ base: '',+ on: '"ChangeOwnershipModel"."videoChannelId"',+ includeAccount: false,+ includeActors: true,+ includeAvatars: false,+ required: false+ })++ this.builtChannelJoin = true+ }+private buildChannelCollaboratorsJoin () {if (this.builtChannelCollaboratorsJoin) return- this.buildVideoJoin()-this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "Video->VideoChannel->VideoChannelCollaborators" ' +'ON "Video->VideoChannel->VideoChannelCollaborators"."channelId" = "Video->VideoChannel"."id" ' +'AND "Video->VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' +@@ -154,20 +183,12 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.builtNextOwnerAvatarJoin = true}- private buildChannelAvatarsJoin () {- if (this.builtChannelAvatarJoin) return+ private buildVideoChannelAvatarsJoin () {+ if (this.builtVideoChannelAvatarJoin) returnthis.join += getAvatarsJoin({ base: 'Video->VideoChannel->Actor->', on: '"Video.VideoChannel.Actor.id"' })- this.builtChannelAvatarJoin = true- }-- private buildChannelAccountAvatarsJoin () {- if (this.builtChannelAccountAvatarJoin) return-- this.join += getAvatarsJoin({ base: 'Video->VideoChannel->Account->Actor->', on: '"Video.VideoChannel.Account.Actor.id"' })-- this.builtChannelAccountAvatarJoin = true+ this.builtVideoChannelAvatarJoin = true}private buildThumbnailJoin () {@@ -178,13 +199,21 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.builtThumbnailJoin = true}+ private buildChannelAvatarsJoin () {+ if (this.builtChannelAvatarJoin) return++ this.join += getAvatarsJoin({ base: 'VideoChannel->Actor->', on: '"VideoChannel.Actor.id"' })++ this.builtChannelAvatarJoin = true+ }+// ---------------------------------------------------------------------------protected buildQueryJoin () {this.buildInitiatorAvatarsJoin()this.buildNextOwnerAvatarsJoin()+ this.buildVideoChannelAvatarsJoin()this.buildChannelAvatarsJoin()- this.buildChannelAccountAvatarsJoin()this.buildThumbnailJoin()}@@ -195,8 +224,8 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.tableAttributes.getInitiatorAvatarAttributes(),this.tableAttributes.getNextOwnerAvatarAttributes(),this.tableAttributes.getVideoChannelAvatarAttributes(),- this.tableAttributes.getVideoChannelAccountAvatarAttributes(),- this.tableAttributes.getThumbnailAttributes()+ this.tableAttributes.getThumbnailAttributes(),+ this.tableAttributes.getChannelAvatarAttributes()]}@@ -204,6 +233,7 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.buildInitiatorJoin()this.buildNextOwnerJoin()this.buildVideoJoin()+ this.buildChannelJoin()}protected buildSubQueryAttributes () {@@ -221,14 +251,13 @@ export class ChangeOwnershipListQueryBuilder extends AbstractListQuery {this.tableAttributes.getNextOwnerServerAttributes(),this.tableAttributes.getVideoAttributes(),-this.tableAttributes.getVideoChannelAttributes(),this.tableAttributes.getVideoChannelActorAttributes(),this.tableAttributes.getVideoChannelServerAttributes(),- this.tableAttributes.getVideoChannelAccountAttributes(),- this.tableAttributes.getVideoChannelAccountActorAttributes(),- this.tableAttributes.getVideoChannelAccountServerAttributes()+ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes()]}}diff --git a/server/core/models/video/sql/change-ownership/change-ownership-table-attributes.ts b/server/core/models/video/sql/change-ownership/change-ownership-table-attributes.tsindex 26c1677369..94dc7767a1 100644--- a/server/core/models/video/sql/change-ownership/change-ownership-table-attributes.ts+++ b/server/core/models/video/sql/change-ownership/change-ownership-table-attributes.ts@@ -3,9 +3,9 @@ import { AccountModel } from '@server/models/account/account.js'import { ActorImageModel } from '@server/models/actor/actor-image.js'import { ActorModel } from '@server/models/actor/actor.js'import { ServerModel } from '@server/models/server/server.js'+import { ChangeOwnershipModel } from '../../change-ownership.js'import { ThumbnailModel } from '../../thumbnail.js'import { VideoChannelModel } from '../../video-channel.js'-import { ChangeOwnershipModel } from '../../change-ownership.js'import { VideoModel } from '../../video.js'export class VideoChangeOwnershipTableAttributes {@@ -58,11 +58,13 @@ export class VideoChangeOwnershipTableAttributes {return ActorImageModel.getSQLAttributes('NextOwner->Actor->Avatars', 'NextOwner.Actor.Avatars.').join(', ')}+ // ---------------------------------------------------------------------------+ // Video joins// ---------------------------------------------------------------------------@Memoize()getVideoAttributes () {- return VideoModel.getSQLAttributes('Video', 'Video.').join(', ')+ return VideoModel.getSQLSummaryAttributes('Video', 'Video.').join(', ')}// ---------------------------------------------------------------------------@@ -90,35 +92,31 @@ export class VideoChangeOwnershipTableAttributes {// ---------------------------------------------------------------------------@Memoize()- getVideoChannelAccountAttributes () {- return AccountModel.getSQLSummaryAttributes('Video->VideoChannel->Account', 'Video.VideoChannel.Account.').join(', ')+ getThumbnailAttributes () {+ return ThumbnailModel.getSQLAttributes('Video->Thumbnails', 'Video.Thumbnails.').join(', ')}+ // ---------------------------------------------------------------------------+ // Channel joins+ // ---------------------------------------------------------------------------+@Memoize()- getVideoChannelAccountActorAttributes () {- return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Account->Actor', 'Video.VideoChannel.Account.Actor.').join(', ')+ getChannelAttributes () {+ return VideoChannelModel.getSQLSummaryAttributes('VideoChannel', 'VideoChannel.').join(', ')}@Memoize()- getVideoChannelAccountServerAttributes () {- return ServerModel.getSQLSummaryAttributes(- 'Video->VideoChannel->Account->Actor->Server',- 'Video.VideoChannel.Account.Actor.Server.'- ).join(', ')+ getChannelActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('VideoChannel->Actor', 'VideoChannel.Actor.').join(', ')}@Memoize()- getVideoChannelAccountAvatarAttributes () {- return ActorImageModel.getSQLAttributes(- 'Video->VideoChannel->Account->Actor->Avatars',- 'Video.VideoChannel.Account.Actor.Avatars.'- ).join(', ')+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('VideoChannel->Actor->Server', 'VideoChannel.Actor.Server.').join(', ')}- // ----------------------------------------------------------------------------@Memoize()- getThumbnailAttributes () {- return ThumbnailModel.getSQLAttributes('Video->Thumbnails', 'Video.Thumbnails.').join(', ')+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('VideoChannel->Actor->Avatars', 'VideoChannel.Actor.Avatars.').join(', ')}}diff --git a/server/core/models/video/video-channel-activity.ts b/server/core/models/video/video-channel-activity.tsindex 214b8c481b..a34f8f4038 100644--- a/server/core/models/video/video-channel-activity.ts+++ b/server/core/models/video/video-channel-activity.ts@@ -305,11 +305,11 @@ export class VideoChannelActivityModel extends SequelizeModel<VideoChannelActivi}, { transaction })}- static async addOwnershipChangeActivity (options: {+ static async addVideoOwnershipChangeActivity (options: {action: VideoChannelActivityActionTypeuser: MUserAccountIdchannel: MChannelId- video: MVideo+ video: Pick<MVideo, 'id' | 'name' | 'uuid' | 'url' | 'isLive'>targetAccount: MAccountNames & MAccountUrltransaction: Transaction}) {@@ -339,6 +339,37 @@ export class VideoChannelActivityModel extends SequelizeModel<VideoChannelActivi}, { transaction })}+ static async addChannelOwnershipChangeActivity (options: {+ action: VideoChannelActivityActionType+ user: MUserAccountId+ channel: MChannelActivityFormattable['VideoChannel']+ targetAccount: MAccountNames & MAccountUrl+ transaction: Transaction+ }) {+ const { action, user, channel, targetAccount, transaction } = options++ return this.create({+ action,+ targetType: VideoChannelActivityTarget.CHANNEL,+ data: {+ channel: {+ id: channel.id,+ name: channel.Actor.preferredUsername,+ displayName: channel.name,+ url: channel.Actor.url+ },+ targetAccount: {+ username: targetAccount.Actor.preferredUsername,+ displayName: targetAccount.name,+ url: targetAccount.Actor.url+ }+ },+ details: null,+ accountId: user.Account.id,+ videoChannelId: channel.id+ }, { transaction })+ }+static async addVideoImportActivity (options: {action: VideoChannelActivityActionTypeuser: MUserAccountIddiff --git a/server/core/models/video/video-channel-collaborator.ts b/server/core/models/video/video-channel-collaborator.tsindex 6deced8dbc..8f94b67371 100644--- a/server/core/models/video/video-channel-collaborator.ts+++ b/server/core/models/video/video-channel-collaborator.ts@@ -5,12 +5,12 @@ import {} from '@peertube/peertube-models'import { CHANNEL_COLLABORATOR_STATE } from '@server/initializers/constants.js'import { MChannelCollaboratorAccount, MChannelId, MUserId } from '@server/types/models/index.js'+import { Op, Transaction } from 'sequelize'import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Scopes, Table, UpdatedAt } from 'sequelize-typescript'import { AccountModel } from '../account/account.js'import { ActorModel } from '../actor/actor.js'import { SequelizeModel, buildSQLAttributes, doesExist, getSort } from '../shared/index.js'import { VideoChannelModel } from './video-channel.js'-import { Op } from 'sequelize'enum ScopeNames {WITH_ACCOUNT = 'WITH_ACCOUNT'@@ -147,8 +147,9 @@ export class VideoChannelCollaboratorModel extends SequelizeModel<VideoChannelCostatic loadByCollaboratorAccountName (options: {channelId: numberaccountName: string+ transaction?: Transaction}): Promise<MChannelCollaboratorAccount | null> {- const { channelId, accountName } = options+ const { channelId, accountName, transaction } = optionsreturn VideoChannelCollaboratorModel.findOne({where: {@@ -168,7 +169,8 @@ export class VideoChannelCollaboratorModel extends SequelizeModel<VideoChannelCo}]}- ]+ ],+ transaction})}diff --git a/server/core/models/video/video-channel.ts b/server/core/models/video/video-channel.tsindex 745caee0e2..df4dbdc2f7 100644--- a/server/core/models/video/video-channel.ts+++ b/server/core/models/video/video-channel.ts@@ -325,6 +325,35 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {}}+ static async getChannelQuota (channelId: number) {+ const webVideoFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' ++ 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' ++ 'AND "video"."isLive" IS FALSE AND "video"."channelId" = $channelId'++ const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' ++ 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' ++ 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' ++ 'AND "video"."isLive" IS FALSE AND "video"."channelId" = $channelId'++ const sql = 'SELECT COALESCE(SUM("size"), 0) AS "total" ' ++ 'FROM (' ++ `SELECT MAX("t1"."size") AS "size" FROM (${webVideoFiles} UNION ${hlsFiles}) t1 ` ++ 'GROUP BY "t1"."videoId"' ++ ') t2'++ const queryOptions = {+ bind: { channelId },+ type: QueryTypes.SELECT as QueryTypes.SELECT+ }++ const [ { total } ] = await VideoChannelModel.sequelize.query<{ total: string }>(sql, queryOptions)+ if (!total) return 0++ return parseInt(total, 10)+ }++ // ---------------------------------------------------------------------------+static listLocalsForSitemap (sort: string): Promise<MChannelHost[]> {const query = {attributes: [],@@ -394,6 +423,12 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {return VideoChannelModel.findAll(query)}+ // ---------------------------------------------------------------------------++ static load (id: number, transaction?: Transaction): Promise<MChannel> {+ return VideoChannelModel.unscoped().findByPk(id, { transaction })+ }+static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {return VideoChannelModel.unscoped().scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])@@ -489,6 +524,8 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {.findOne(query)}+ // ---------------------------------------------------------------------------+toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {const actor = this.Actor.toFormattedSummaryJSON()diff --git a/server/core/models/video/video-playlist.ts b/server/core/models/video/video-playlist.tsindex 2a923d700b..92d54511b8 100644--- a/server/core/models/video/video-playlist.ts+++ b/server/core/models/video/video-playlist.ts@@ -69,9 +69,9 @@ import {import { getNextPositionOf, increasePositionOf, reassignPositionOf } from '../shared/position.js'import { ListVideoPlaylistsOptions, VideoPlaylistListQueryBuilder } from './sql/playlist/video-playlist-list-query-builder.js'import { ThumbnailModel } from './thumbnail.js'+import { VideoChannelCollaboratorModel } from './video-channel-collaborator.js'import { VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel.js'import { VideoPlaylistElementModel } from './video-playlist-element.js'-import { VideoChannelCollaboratorModel } from './video-channel-collaborator.js'enum ScopeNames {WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',@@ -551,6 +551,29 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {}, query)}+ // ---------------------------------------------------------------------------++ static updateOwnerOfChannelPlaylists (options: {+ currentOwnerId: number+ videoChannelId: number+ nextOwnerId: number+ transaction: Transaction+ }) {+ const { currentOwnerId, nextOwnerId, videoChannelId, transaction } = options++ const query = {+ where: {+ ownerAccountId: currentOwnerId,+ videoChannelId+ },+ transaction+ }++ return VideoPlaylistModel.update({ ownerAccountId: nextOwnerId }, query)+ }++ // ---------------------------------------------------------------------------+async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {thumbnail.videoPlaylistId = this.iddiff --git a/server/core/models/video/video.ts b/server/core/models/video/video.tsindex 129073ea88..ebe9eb340b 100644--- a/server/core/models/video/video.ts+++ b/server/core/models/video/video.ts@@ -16,12 +16,14 @@ import {VideoRateType,VideoState,VideoStreamingPlaylistType,+ VideoSummary,type VideoCommentPolicyType,type VideoEmbedPrivacyPolicyType,type VideoPrivacyType,type VideoStateType} from '@peertube/peertube-models'import { uuidToShort } from '@peertube/peertube-node-utils'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'import { getPrivaciesForFederation } from '@server/helpers/video.js'import { isPrivacyForFederation } from '@server/lib/activitypub/videos/federate.js'import { InternalEventEmitter } from '@server/lib/internal-event-emitter.js'@@ -106,6 +108,7 @@ import {MVideoImmutable,MVideoOwned,MVideoSeo,+ MVideoSummary,MVideoThumbnails,MVideoWithAllFiles,MVideoWithBlacklist,@@ -136,9 +139,9 @@ import {setAsUpdated,throwIfNotValid} from '../shared/index.js'+import { VideoStatModel } from '../stat/video-stat.js'import { UserVideoHistoryModel } from '../user/user-video-history.js'import { UserModel } from '../user/user.js'-import { VideoStatModel } from '../stat/video-stat.js'import { videoModelToActivityPubObject } from './formatter/video-activity-pub-format.js'import {VideoFormattingJSONOptions,@@ -174,6 +177,19 @@ import { VideoTagModel } from './video-tag.js'const lTags = loggerTagsFactory('video')+const videoSummaryAttributes = [+ 'id',+ 'name',+ 'uuid',+ 'nsfw',+ 'url',+ 'channelId',+ 'remote',+ 'state',+ 'isLive',+ 'publishedAt'+] as const satisfies (keyof AttributesOnly<VideoModel>)[]+export enum ScopeNames {FOR_API = 'FOR_API',WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',@@ -927,6 +943,15 @@ export class VideoModel extends SequelizeModel<VideoModel> {// ---------------------------------------------------------------------------+ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix,+ includeAttributes: videoSummaryAttributes+ })+ }+static getSQLAttributes (tableName: string, aliasPrefix = '') {return buildSQLAttributes({model: this,@@ -2011,6 +2036,20 @@ export class VideoModel extends SequelizeModel<VideoModel> {return WEBSERVER.URL + buildVideoEmbedPath({ shortUUID: uuidToShort(this.uuid) })}+ toFormattedSummaryJSON (this: MVideoSummary): VideoSummary {+ return {+ id: this.id,+ uuid: this.uuid,+ name: this.name,+ nsfw: this.nsfw,+ isLive: this.isLive,+ shortUUID: uuidToShort(this.uuid),+ publishedAt: this.publishedAt,+ thumbnails: this.Thumbnails.map(t => t.toFormattedJSON()),+ channel: this.VideoChannel.toFormattedSummaryJSON()+ }+ }+toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {return videoModelToFormattedJSON(this, options)}diff --git a/server/core/types/models/user/user-notification.ts b/server/core/types/models/user/user-notification.tsindex a201d27b66..297be4eaf4 100644--- a/server/core/types/models/user/user-notification.ts+++ b/server/core/types/models/user/user-notification.ts@@ -121,7 +121,7 @@ export namespace UserNotificationIncludes {& PickWith<VideoChannelCollaboratorModel, 'Channel', VideoChannelIncludeActorOwnerActor>export type ChangeOwnershipInclude =- & Pick<ChangeOwnershipModel, 'id'>+ & Pick<ChangeOwnershipModel, 'id' | 'state'>& PickWith<ChangeOwnershipModel, 'Initiator', AccountIncludeActor>& PickWith<ChangeOwnershipModel, 'NextOwner', AccountIncludeActor>& PickWith<ChangeOwnershipModel, 'Video', VideoInclude>diff --git a/server/core/types/models/video/change-ownership.ts b/server/core/types/models/video/change-ownership.tsindex 1bd49714ba..444c365029 100644--- a/server/core/types/models/video/change-ownership.ts+++ b/server/core/types/models/video/change-ownership.ts@@ -1,8 +1,8 @@import { PickWith } from '@peertube/peertube-typescript-utils'import { ChangeOwnershipModel } from '@server/models/video/change-ownership.js'import { MAccountFormattable } from '../account/account.js'-import { MChannelFormattable } from './video-channel.js'-import { MVideoFormattable } from './video.js'+import { MChannelSummary } from './video-channel.js'+import { MVideoSummary } from './video.js'type Use<K extends keyof ChangeOwnershipModel, M> = PickWith<ChangeOwnershipModel, K, M>@@ -14,5 +14,5 @@ export type MChangeOwnershipFull =& MChangeOwnership& Use<'Initiator', MAccountFormattable>& Use<'NextOwner', MAccountFormattable>- & Use<'Video', MVideoFormattable>- & Use<'VideoChannel', MChannelFormattable>+ & Use<'Video', MVideoSummary>+ & Use<'VideoChannel', MChannelSummary>diff --git a/server/core/types/models/video/video.ts b/server/core/types/models/video/video.tsindex 871a2ad979..34be96dbc2 100644--- a/server/core/types/models/video/video.ts+++ b/server/core/types/models/video/video.ts@@ -16,7 +16,8 @@ import {MChannelAccountSummaryFormattable,MChannelActor,MChannelFormattable,- MChannelHostOnly+ MChannelHostOnly,+ MChannelSummary} from './video-channel.js'import { MVideoFile } from './video-file.js'import { MVideoLiveWithSchedules } from './video-live.js'@@ -179,6 +180,14 @@ export type MVideoWithChannelActor =& MVideo& Use<'VideoChannel', MChannelActor>+export type MVideoSummary =+ & Pick<+ MVideo,+ 'id' | 'uuid' | 'name' | 'nsfw' | 'url' | 'channelId' | 'publishedAt' | 'isLive' | 'remote' | 'state' | 'toFormattedSummaryJSON'+ >+ & Use<'VideoChannel', MChannelSummary>+ & Use<'Thumbnails', MThumbnail[]>+export type MVideoWithHost =& MVideo& Use<'VideoChannel', MChannelHostOnly>diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex 8308a8909e..1ab02c8249 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -350,7 +350,7 @@ x-tagGroups:- Video Rates- Video Playlists- Video Stats- - Video Ownership Change+ - Ownership Change- Video Mirroring- Video Files- Video Transcoding@@ -2969,9 +2969,20 @@ paths:summary: List video ownership changesdescription: List ownership change requests received by the authenticated user and requests sent by a channel managed by the authenticated usertags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []+ parameters:+ - $ref: '#/components/parameters/start'+ - $ref: '#/components/parameters/count'+ - name: sort+ in: query+ required: false+ schema:+ type: string+ enum:+ - -createdAt+ - createdAtresponses:'200':description: successful operation@@ -2987,21 +2998,39 @@ paths:type: arrayitems:$ref: '#/components/schemas/ChangeOwnership'+ '401':+ description: authentication required'/api/v1/videos/ownership/{id}/accept':post:summary: Accept ownership change requesttags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []parameters:- $ref: '#/components/parameters/idOrUUID'+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ channelId:+ type: integer+ description: Target channel id owned by the authenticated user+ required:+ - channelIdresponses:'204':description: successful operation+ '400':+ description: ownership change request already accepted/refused or invalid target channel id'403':description: cannot terminate an ownership change of another user+ '413':+ description: quota exceeded for the target account/channel'404':description: video ownership change not found@@ -3009,7 +3038,7 @@ paths:post:summary: Refuse ownership change requesttags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []parameters:@@ -3017,6 +3046,8 @@ paths:responses:'204':description: successful operation+ '400':+ description: ownership change request already accepted/refused'403':description: cannot terminate an ownership change of another user'404':@@ -3027,7 +3058,7 @@ paths:summary: Delete ownership change requestdescription: Delete an ownership change request. Only users who can manage the video can delete the request.tags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []parameters:@@ -3035,21 +3066,31 @@ paths:responses:'204':description: successful operation+ '400':+ description: ownership request already accepted or refused'403':description: only users who can manage the video can delete an ownership change request'404':description: video ownership change not found- '/api/v1/videos/{id}/ownership':+ '/api/v1/videos/{videoId}/ownership':get:summary: List ownership change requests for a videodescription: List all ownership change requests for a specific video. The authenticated user must be able to manage the video.tags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []parameters:- - $ref: '#/components/parameters/idOrUUID'+ - name: videoId+ in: path+ required: true+ description: The video id, uuid or short uuid+ schema:+ oneOf:+ - $ref: '#/components/schemas/id'+ - $ref: '#/components/schemas/UUIDv4'+ - $ref: '#/components/schemas/shortUUID'- name: statein: queryrequired: false@@ -3058,7 +3099,14 @@ paths:$ref: '#/components/schemas/ChangeOwnershipState'- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'- - $ref: '#/components/parameters/sort'+ - name: sort+ in: query+ required: false+ schema:+ type: string+ enum:+ - -createdAt+ - createdAtresponses:'200':description: successful operation@@ -3079,15 +3127,23 @@ paths:'404':description: video not found- '/api/v1/videos/{id}/give-ownership':+ '/api/v1/videos/{videoId}/give-ownership':post:summary: Request ownership changetags:- - Video Ownership Change+ - Ownership Changesecurity:- OAuth2: []parameters:- - $ref: '#/components/parameters/idOrUUID'+ - name: videoId+ in: path+ required: true+ description: The video id, uuid or short uuid+ schema:+ oneOf:+ - $ref: '#/components/schemas/id'+ - $ref: '#/components/schemas/UUIDv4'+ - $ref: '#/components/schemas/shortUUID'requestBody:required: truecontent:@@ -3103,10 +3159,189 @@ paths:'204':description: successful operation'400':- description: changing video ownership to a remote account is not supported yet+ description: changing video ownership to a remote account is not supported yet or there is already a pending ownership request+ '403':+ description: cannot change ownership of this video'404':description: video not found+ /api/v1/video-channels/ownership:+ get:+ summary: List channel ownership changes+ description: List ownership change requests received by the authenticated user and requests sent by channels managed by the authenticated user+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/start'+ - $ref: '#/components/parameters/count'+ - name: sort+ in: query+ required: false+ schema:+ type: string+ enum:+ - -createdAt+ - createdAt+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ type: object+ properties:+ total:+ type: integer+ example: 1+ data:+ type: array+ items:+ $ref: '#/components/schemas/ChangeOwnership'+ '401':+ description: authentication required++ '/api/v1/video-channels/ownership/{id}/accept':+ post:+ summary: Accept channel ownership change request+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/idOrUUID'+ responses:+ '204':+ description: successful operation+ '400':+ description: ownership change request already accepted/refused or request type mismatch+ '403':+ description: cannot terminate an ownership change of another user+ '404':+ description: channel ownership change not found+ '409':+ description: cannot accept transferring the last channel of the initiator account+ '413':+ description: quota exceeded for the target account++ '/api/v1/video-channels/ownership/{id}/refuse':+ post:+ summary: Refuse channel ownership change request+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/idOrUUID'+ responses:+ '204':+ description: successful operation+ '400':+ description: ownership change request already accepted/refused or request type mismatch+ '403':+ description: cannot terminate an ownership change of another user+ '404':+ description: channel ownership change not found++ '/api/v1/video-channels/ownership/{id}':+ delete:+ summary: Delete channel ownership change request+ description: Delete a channel ownership change request. Only channel owners can delete the request.+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/idOrUUID'+ responses:+ '204':+ description: successful operation+ '400':+ description: ownership request already accepted/refused or request type mismatch+ '403':+ description: only channel owners can delete a channel ownership change request+ '404':+ description: channel ownership change not found++ '/api/v1/video-channels/{channelHandle}/ownership':+ get:+ summary: List ownership change requests for a channel+ description: List all ownership change requests for a specific channel. The authenticated user must be able to manage the channel.+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ - name: state+ in: query+ required: false+ description: Filter by ownership change state+ schema:+ $ref: '#/components/schemas/ChangeOwnershipState'+ - $ref: '#/components/parameters/start'+ - $ref: '#/components/parameters/count'+ - name: sort+ in: query+ required: false+ schema:+ type: string+ enum:+ - -createdAt+ - createdAt+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ type: object+ properties:+ total:+ type: integer+ example: 1+ data:+ type: array+ items:+ $ref: '#/components/schemas/ChangeOwnership'+ '400':+ description: invalid parameters+ '403':+ description: cannot manage the channel+ '404':+ description: channel not found++ '/api/v1/video-channels/{channelHandle}/give-ownership':+ post:+ summary: Request channel ownership change+ tags:+ - Ownership Change+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ username:+ type: string+ required:+ - username+ responses:+ '204':+ description: successful operation+ '400':+ description: changing channel ownership to this target is invalid or there is already a pending ownership request+ '403':+ description: cannot change ownership of this channel+ '404':+ description: channel not found+'/api/v1/videos/{id}/token':post:summary: Request video token@@ -9389,6 +9624,35 @@ components:type: arrayitems:$ref: '#/components/schemas/ActorImage'++ VideoSummary:+ properties:+ id:+ description: object id for the video+ allOf:+ - $ref: '#/components/schemas/id'+ uuid:+ description: universal identifier for the video, that can be used across instances+ allOf:+ - $ref: '#/components/schemas/UUIDv4'+ shortUUID:+ allOf:+ - $ref: '#/components/schemas/shortUUID'+ name:+ type: string+ isLive:+ type: boolean+ nsfw:+ type: boolean+ publishedAt:+ type: string+ format: date-time+ thumbnails:+ description: "**PeerTube >= 8.1** Array of thumbnails for the video"+ type: array+ channel:+ $ref: '#/components/schemas/VideoChannelSummary'+VideoChannelSummary:properties:id:@@ -10064,7 +10328,9 @@ components:nextOwnerAccount:$ref: '#/components/schemas/Account'video:- $ref: '#/components/schemas/Video'+ $ref: '#/components/schemas/VideoSummary'+ videoChannel:+ $ref: '#/components/schemas/VideoChannelSummary'createdAt:type: stringformat: date-time@@ -12462,6 +12728,9 @@ components:- 26- 27- 28+ - 29+ - 30+ - 31description: >Notification type. One of the following values:@@ -12521,6 +12790,12 @@ components:- `28` VIDEO_OWNERSHIP_CHANGED_REJECTED+ - `29` CHANNEL_OWNERSHIP_CHANGED_REQUEST++ - `30` CHANNEL_OWNERSHIP_CHANGED_ACCEPTED++ - `31` CHANNEL_OWNERSHIP_CHANGED_REJECTED+NewFeatureInfoType:type: integerenum: